CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygmt

A Python interface for the Generic Mapping Tools

Pending
Overview
Eval results
Files

config-utilities.mddocs/

Configuration and Utilities

System configuration, session management, and utility functions for customizing GMT behavior, managing resources, and accessing system information.

Capabilities

GMT Configuration

Configure GMT default settings and behavior.

def config(**kwargs) -> None:
    """
    Modify individual GMT default settings.
    
    Parameters (via kwargs):
    - MAP_FRAME_TYPE: Frame type ("plain", "fancy")
    - MAP_FRAME_WIDTH: Frame width (e.g., "5p")
    - MAP_FRAME_PEN: Frame pen attributes (e.g., "1p,black")
    - MAP_GRID_PEN_PRIMARY: Primary grid pen (e.g., "0.5p,gray")
    - MAP_GRID_PEN_SECONDARY: Secondary grid pen (e.g., "0.25p,lightgray")
    - MAP_TICK_LENGTH_PRIMARY: Primary tick length (e.g., "8p")
    - MAP_TICK_LENGTH_SECONDARY: Secondary tick length (e.g., "4p")
    - MAP_ANNOT_FONT_PRIMARY: Primary annotation font (e.g., "12p,Helvetica")
    - MAP_ANNOT_FONT_SECONDARY: Secondary annotation font (e.g., "10p,Helvetica")
    - MAP_LABEL_FONT: Axis label font (e.g., "14p,Helvetica-Bold")
    - MAP_TITLE_FONT: Title font (e.g., "16p,Helvetica-Bold")
    - COLOR_BACKGROUND: Background color (e.g., "white")
    - COLOR_FOREGROUND: Foreground color (e.g., "black")
    - COLOR_MODEL: Color model ("RGB", "HSV", "CMYK")
    - PS_MEDIA: Paper size ("A4", "Letter", "Custom")
    - PS_PAGE_ORIENTATION: Page orientation ("portrait", "landscape")
    - FORMAT_GEO_OUT: Geographic output format (e.g., "ddd:mm:ss")
    - FORMAT_DATE_OUT: Date output format (e.g., "yyyy-mm-dd")
    - FORMAT_TIME_OUT: Time output format (e.g., "hh:mm:ss")
    - PROJ_LENGTH_UNIT: Default length unit ("cm", "inch", "point")
    - GMT_VERBOSE: Verbosity level ("quiet", "normal", "verbose", "debug")
    - GMT_INTERPOLANT: Default interpolation ("linear", "akima", "cubic", "none")
    
    Notes:
    - Settings persist for the current GMT session
    - Use GMT parameter names exactly as documented
    - String values should be quoted appropriately
    """

System Information

Access information about PyGMT, GMT, and system configuration.

def show_versions() -> None:
    """
    Show versions of PyGMT and dependencies.
    
    Displays:
    - PyGMT version and commit hash
    - GMT version and library path
    - Python version and platform
    - NumPy, pandas, xarray versions
    - Ghostscript version
    - GDAL/OGR version
    - System information
    """

def info(data: PathLike | TableLike, **kwargs) -> str:
    """
    Get information about data tables.
    
    Parameters:
    - data: Input data file or table
    - verbose: Show detailed statistics (bool)
    - per_column: Report statistics per column (bool)
    - spacing_guess: Guess grid spacing from data (bool)
    - force_scan: Force reading entire dataset (bool)
    
    Returns:
    str: Data information string including:
         - Number of records and columns
         - Data extent and ranges  
         - Missing values count
         - Data type information
    """

def which(fname: str, **kwargs) -> str:
    """
    Find full path to specified files.
    
    Parameters:
    - fname: File name to locate
    - show_all: Show all matching files (bool)
    - download: Download file if not found locally (bool)
    
    Returns:
    str: Full path to file, or empty string if not found
    
    Searches:
    - Current directory
    - GMT data directories
    - GMT cache directories
    - System PATH (for executables)
    """

Display Configuration

Configure how figures are displayed in different environments.

def set_display(method: Literal["external", "notebook", "none"] | None = None) -> None:
    """
    Set Figure display method for show().
    
    Parameters:
    - method: Display method
      - "external": Launch external image viewer
      - "notebook": Display inline in Jupyter notebooks
      - "none": No display (useful for batch processing)
      - None: Use default based on environment
    
    Notes:
    - Setting persists for current Python session  
    - Jupyter notebooks default to "notebook"
    - Other environments default to "external"
    - Use "none" for headless servers or batch jobs
    """

Session Management

Functions for managing GMT modern mode sessions (typically handled automatically).

def begin() -> None:
    """
    Initiate a new GMT modern mode session.
    
    Notes:
    - Called automatically when importing PyGMT
    - Creates global GMT session for all operations
    - Sets GMT compatibility mode to version 6
    - Handles platform-specific session naming
    """

def end() -> None:
    """
    Terminate the GMT modern mode session.
    
    Notes:
    - Called automatically at Python exit
    - Cleans up temporary files and session directory
    - Should only be called explicitly in special cases
    """

Helper Utilities

Utility functions for data validation, type checking, and file management.

def unique_name() -> str:
    """
    Generate unique names for temporary files and figures.
    
    Returns:
    str: Unique identifier string
    """

class GMTTempFile:
    """
    Context manager for creating temporary files with GMT-compatible names.
    
    Usage:
    with GMTTempFile() as tmpfile:
        # Use tmpfile.name for file operations
        data.to_csv(tmpfile.name)
        result = pygmt.info(tmpfile.name)
    # File automatically cleaned up
    """
    
    def __init__(self, suffix: str = ".txt") -> None:
        """
        Initialize temporary file.
        
        Parameters:
        - suffix: File extension (e.g., ".txt", ".grd", ".cpt")
        """
    
    def __enter__(self) -> "GMTTempFile":
        """Enter context manager and create temporary file."""
    
    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        """Exit context manager and clean up temporary file."""

def tempfile_from_geojson(geojson_dict: dict) -> GMTTempFile:
    """
    Create temporary file from GeoJSON data.
    
    Parameters:
    - geojson_dict: GeoJSON data as dictionary
    
    Returns:
    GMTTempFile: Temporary file containing GeoJSON data
    """

def tempfile_from_image(image: np.ndarray) -> GMTTempFile:
    """
    Create temporary file from image array.
    
    Parameters:
    - image: Image data as numpy array
    
    Returns:
    GMTTempFile: Temporary file containing image data
    """

def launch_external_viewer(fname: str) -> None:
    """
    Launch external image viewer for file.
    
    Parameters:
    - fname: Image file path
    
    Notes:
    - Uses system default image viewer
    - Platform-specific implementation
    - Non-blocking call (viewer runs independently)
    """

Data Validation

Functions for validating and checking data inputs.

def data_kind(data: any) -> str:
    """
    Determine data type/kind for GMT processing.
    
    Parameters:
    - data: Input data (file path, array, DataFrame, etc.)
    
    Returns:
    str: Data kind ("file", "matrix", "vectors", "grid", etc.)
    """

def is_nonstr_iter(obj: any) -> bool:
    """
    Check if object is non-string iterable.
    
    Parameters:
    - obj: Object to check
    
    Returns:
    bool: True if iterable but not string
    """

def args_in_kwargs(args: list, kwargs: dict) -> list:
    """
    Check if arguments are present in kwargs.
    
    Parameters:
    - args: List of argument names to check
    - kwargs: Keyword arguments dictionary
    
    Returns:
    list: Arguments found in kwargs
    """

def build_arg_list(kwargs: dict) -> list:
    """
    Build GMT argument list from kwargs.
    
    Parameters:
    - kwargs: Keyword arguments with GMT parameters
    
    Returns:
    list: GMT command-line arguments
    """

String and Encoding Utilities

Functions for handling text encoding and character conversion.

def non_ascii_to_octal(text: str) -> str:
    """
    Convert non-ASCII characters to octal representation.
    
    Parameters:
    - text: Input text with potential non-ASCII characters
    
    Returns:
    str: Text with non-ASCII characters converted to octal codes
    
    Notes:
    - Required for GMT text processing with special characters
    - Handles Unicode characters in plot labels and annotations
    """

def sequence_join(sequence: list, separator: str = " ") -> str:
    """
    Join sequences with specified separator.
    
    Parameters:
    - sequence: List or array to join
    - separator: String separator between elements
    
    Returns:
    str: Joined string
    """

XArray Integration

PyGMT extends xarray with GMT-specific functionality for grids and backend support.

class GMTDataArrayAccessor:
    """
    GMT accessor for xarray.DataArray providing .gmt attribute.
    
    Automatically registered as xarray.DataArray.gmt accessor.
    Provides GMT-specific metadata for grids and images.
    
    Properties:
    - registration: Grid registration type (GridRegistration.GRIDLINE or GridRegistration.PIXEL)
    - gtype: Grid coordinate system (GridType.CARTESIAN or GridType.GEOGRAPHIC)
    
    Usage:
    data_array.gmt.registration  # Access grid registration
    data_array.gmt.gtype        # Access grid coordinate type
    """

class GMTBackendEntrypoint:
    """
    XArray backend for reading GMT netCDF files.
    
    Automatically registered as xarray backend for GMT files.
    Enables direct loading of GMT grids with proper metadata.
    
    Usage:
    xr.open_dataarray("file.grd", engine="gmt")
    """

def load_dataarray(filename_or_obj: str, **kwargs) -> xr.DataArray:
    """
    Load GMT grid file as xarray.DataArray with GMT metadata.
    
    Parameters:
    - filename_or_obj: Path to GMT grid file
    - **kwargs: Additional arguments passed to xarray.open_dataarray
    
    Returns:
    xr.DataArray: Grid data with GMT-specific metadata via .gmt accessor
    
    Notes:
    - Deprecated: Will be removed in PyGMT v0.20.0
    - Use xr.open_dataarray() with engine="gmt" instead
    - Loads data into memory and closes file automatically
    """

Usage Examples

Basic Configuration

import pygmt

# Configure map appearance
pygmt.config(
    MAP_FRAME_TYPE="fancy",
    MAP_FRAME_WIDTH="8p",
    MAP_GRID_PEN_PRIMARY="0.5p,gray",
    MAP_ANNOT_FONT_PRIMARY="12p,Helvetica",
    COLOR_BACKGROUND="lightblue"
)

# Create a map with custom settings
fig = pygmt.Figure()
fig.basemap(region=[0, 10, 0, 10], projection="X10c", frame="a2f1")
fig.show()

# Reset to defaults (by restarting session or setting explicitly)
pygmt.config(
    MAP_FRAME_TYPE="plain",
    COLOR_BACKGROUND="white"
)

System Information

import pygmt

# Display comprehensive version information
pygmt.show_versions()

# Get information about a data file
data_info = pygmt.info("@earth_relief_01d_g")
print("Earth relief data info:")
print(data_info)

# Locate GMT data files
relief_path = pygmt.which("@earth_relief_01d_g")
print(f"Earth relief grid location: {relief_path}")

# Check if a file exists in GMT data directories
hotspots_path = pygmt.which("@hotspots.txt")
if hotspots_path:
    print(f"Hotspots data found at: {hotspots_path}")
else:
    print("Hotspots data not found")

Display Configuration

import pygmt

# Configure for different environments
# For Jupyter notebooks (usually automatic)
pygmt.set_display(method="notebook")

# For headless servers or batch processing
pygmt.set_display(method="none")

# For desktop environments
pygmt.set_display(method="external")

# Create and display figure (behavior depends on display method)
fig = pygmt.Figure()
fig.basemap(region="global", projection="W15c", frame=True)
fig.coast(shorelines=True)
fig.show()  # Display method determined by set_display()

Temporary File Management

import pygmt
import pandas as pd

# Create temporary file for data processing
data = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 4, 6, 8, 10],
    'z': [1, 4, 9, 16, 25]
})

# Use context manager for automatic cleanup
with pygmt.helpers.GMTTempFile(suffix=".txt") as tmpfile:
    # Save data to temporary file
    data.to_csv(tmpfile.name, sep='\t', index=False)
    
    # Use temporary file with GMT functions
    info_str = pygmt.info(tmpfile.name)
    print("Temporary data info:", info_str)
    
    # Process with GMT
    grid = pygmt.surface(
        data=tmpfile.name,
        region=[0, 6, 0, 12],
        spacing=0.5
    )
# Temporary file automatically deleted here

print(f"Generated grid shape: {grid.shape}")

Advanced Configuration

import pygmt

# Set up custom plotting defaults
pygmt.config(
    # Font settings
    MAP_ANNOT_FONT_PRIMARY="10p,Times-Roman",
    MAP_LABEL_FONT="12p,Times-Bold", 
    MAP_TITLE_FONT="16p,Times-Bold",
    
    # Grid and frame settings
    MAP_FRAME_PEN="1.5p,black",
    MAP_GRID_PEN_PRIMARY="0.5p,gray50",
    MAP_GRID_PEN_SECONDARY="0.25p,gray75",
    MAP_TICK_LENGTH_PRIMARY="6p",
    
    # Format settings
    FORMAT_GEO_OUT="ddd:mm:ss",
    FORMAT_DATE_OUT="yyyy-mm-dd",
    
    # Paper and color settings
    PS_MEDIA="A4",
    COLOR_MODEL="RGB",
    GMT_VERBOSE="normal"
)

# Create publication-quality figure
fig = pygmt.Figure()
fig.basemap(
    region=[-10, 10, -5, 5],
    projection="M15c",
    frame=["xa2f1+lLongitude", "ya1f0.5+lLatitude", "WSen+tCustom Map Title"]
)
fig.coast(shorelines="1p,black", land="lightgray", water="lightblue")

# Add grid
fig.basemap(frame=["xa2f1", "ya1f0.5", "g"])

fig.show()

Data Processing Pipeline with Utilities

import pygmt
import numpy as np

# Generate sample data
np.random.seed(42)
x = np.random.uniform(-5, 5, 50)  
y = np.random.uniform(-5, 5, 50)
z = np.exp(-(x**2 + y**2)/10) + 0.1 * np.random.randn(50)

# Create data table
import pandas as pd
data = pd.DataFrame({'x': x, 'y': y, 'z': z})

# Get data information
print("Data summary:")
with pygmt.helpers.GMTTempFile() as tmpfile:
    data.to_csv(tmpfile.name, sep='\t', index=False)
    info_str = pygmt.info(tmpfile.name, verbose=True)
    print(info_str)

# Process data with custom configuration
pygmt.config(GMT_VERBOSE="verbose")  # Enable verbose output

# Grid the data
grid = pygmt.surface(
    data=data,
    region=[-6, 6, -6, 6],
    spacing=0.2,
    tension=0.25
)

# Get grid information
grid_info = pygmt.grdinfo(grid)
print("\nGrid information:")
print(grid_info)

# Create visualization
fig = pygmt.Figure()
fig.grdimage(grid=grid, cmap="hot", projection="X12c")
fig.colorbar(frame='a0.2+l"Z values"')
fig.plot(x=x, y=y, style="c0.1c", fill="white", pen="0.5p,black")
fig.show()

Error Handling and Debugging

import pygmt

# Enable verbose output for debugging
pygmt.config(GMT_VERBOSE="debug")

try:
    # This might fail - let's see detailed error info
    fig = pygmt.Figure()
    fig.basemap(region=[0, 10, 0, 10], projection="InvalidProjection")
    
except pygmt.exceptions.GMTCLibError as e:
    print(f"GMT Library Error: {e}")
    # Check system information for debugging
    pygmt.show_versions()
    
except pygmt.exceptions.GMTInvalidInput as e:
    print(f"Invalid Input Error: {e}")
    
finally:
    # Reset verbosity
    pygmt.config(GMT_VERBOSE="normal")

Configuration Reference

Common GMT Parameters

Map Frame and Annotation:

  • MAP_FRAME_TYPE: "plain" or "fancy"
  • MAP_FRAME_WIDTH: Frame width (e.g., "5p")
  • MAP_ANNOT_FONT_PRIMARY: Primary annotation font
  • MAP_TICK_LENGTH_PRIMARY: Primary tick length

Grid and Lines:

  • MAP_GRID_PEN_PRIMARY: Primary grid pen
  • MAP_DEFAULT_PEN: Default pen for lines
  • MAP_VECTOR_SHAPE: Vector head shape

Colors:

  • COLOR_BACKGROUND: Background color
  • COLOR_FOREGROUND: Foreground color
  • COLOR_NAN: Color for NaN values
  • COLOR_MODEL: "RGB", "HSV", or "CMYK"

Paper and Output:

  • PS_MEDIA: Paper size ("A4", "Letter", etc.)
  • PS_PAGE_ORIENTATION: "portrait" or "landscape"
  • GMT_VERBOSE: "quiet", "normal", "verbose", "debug"

Format:

  • FORMAT_GEO_OUT: Geographic coordinate format
  • FORMAT_DATE_OUT: Date format
  • FORMAT_TIME_OUT: Time format
  • FORMAT_FLOAT_OUT: Floating point format

All parameters use GMT's standard names and values. Refer to GMT documentation for complete parameter reference.

Install with Tessl CLI

npx tessl i tessl/pypi-pygmt

docs

config-utilities.md

data-processing.md

datasets.md

figure-plotting.md

index.md

tile.json