A Python interface for the Generic Mapping Tools
—
Grid and table data processing functions that wrap GMT's powerful analysis capabilities. These functions provide gridding, filtering, sampling, mathematical operations, and coordinate transformations for geospatial data.
Convert irregular (x, y, z) data into regular grids using various interpolation methods.
def surface(data: PathLike | TableLike | None = None, **kwargs):
"""
Grid table data using adjustable tension continuous curvature splines.
Parameters:
- data: Input data file or table with x, y, z columns
- region: Output grid extent [west, east, south, north]
- spacing: Grid spacing (dx, dy)
- tension: Tension parameter (0-1, default 0)
- convergence: Convergence criteria
- max_iterations: Maximum iterations
- mask: Apply land/ocean mask
- clipgrid: Clip output to input data bounds
Returns:
xarray.DataArray: Output grid
"""
def nearneighbor(data: PathLike | TableLike | None = None, **kwargs):
"""
Grid table data using a "Nearest neighbor" algorithm.
Parameters:
- data: Input data file or table
- region: Output grid extent
- spacing: Grid spacing
- search_radius: Search radius for neighbors
- sectors: Number of sectors for searching
- min_sectors: Minimum sectors that must have data
- empty: Value to assign to empty nodes
Returns:
xarray.DataArray: Output grid
"""
def triangulate(data: PathLike | TableLike | None = None, **kwargs):
"""
Do optimal (Delaunay) triangulation and gridding of Cartesian table data.
Parameters:
- data: Input data file or table
- region: Output grid extent
- spacing: Grid spacing for optional gridding
- derivatives: Output derivative grids
- unity: Normalize output by triangle areas
- edges: Output triangle edges
Returns:
xarray.DataArray or None: Output grid (if gridding requested)
"""
def xyz2grd(data: PathLike | TableLike | None = None, **kwargs):
"""
Convert data table to a grid.
Parameters:
- data: Input xyz data file or table
- region: Grid extent
- spacing: Grid spacing
- registration: Grid registration (gridline/pixel)
- duplicate: How to handle duplicate coordinates (mean/median/mode/lower/upper)
- statistics: Report statistics about input data
Returns:
xarray.DataArray: Output grid
"""
def sph2grd(data: PathLike | TableLike | None = None, **kwargs):
"""
Compute grid from spherical harmonic coefficients.
Parameters:
- data: Spherical harmonic coefficients file or table
- region: Output grid extent
- spacing: Grid spacing
- normalize: Normalization method
- format: Input coefficient format
Returns:
xarray.DataArray: Output grid
"""
def sphdistance(data: PathLike | TableLike | None = None, **kwargs):
"""
Create Voronoi distance, node, or natural nearest-neighbor grid.
Parameters:
- data: Input point data
- region: Output grid extent
- spacing: Grid spacing
- quantity: Output quantity (distance/node_id/natural_weights)
- unit: Distance unit
Returns:
xarray.DataArray: Output grid
"""
def sphinterpolate(data: PathLike | TableLike | None = None, **kwargs):
"""
Spherical gridding in tension of data on a sphere.
Parameters:
- data: Input data on sphere
- region: Output grid extent
- spacing: Grid spacing
- tension: Tension parameter
- iterations: Number of iterations
Returns:
xarray.DataArray: Output grid
"""Modify, filter, and analyze existing grids.
def grdfilter(grid: PathLike | xr.DataArray, **kwargs):
"""
Filter a grid in the space/time domain.
Parameters:
- grid: Input grid file or xarray DataArray
- filter: Filter type and parameters (boxcar/cosine/gaussian/median/mode)
- distance: Filter full width
- nans: How to handle NaN values
- toggle: Toggle between high-pass and low-pass filtering
Returns:
xarray.DataArray: Filtered grid
"""
def grdgradient(grid: PathLike | xr.DataArray, **kwargs):
"""
Compute directional gradients from a grid.
Parameters:
- grid: Input grid file or xarray DataArray
- azimuth: Azimuth for directional derivative (degrees)
- slope_file: Output slope magnitude grid
- aspect_file: Output aspect (direction) grid
- normalize: Normalize gradients
- sigma: Smoothing sigma for gradient calculation
Returns:
xarray.DataArray: Gradient grid
"""
def grdsample(grid: PathLike | xr.DataArray, **kwargs):
"""
Resample a grid onto a new lattice.
Parameters:
- grid: Input grid file or xarray DataArray
- region: Output grid extent
- spacing: Output grid spacing
- registration: Output grid registration
- translate: Translate grid by offset
- interpolation: Interpolation method (bilinear/bicubic/nearest)
Returns:
xarray.DataArray: Resampled grid
"""
def grdcut(grid: PathLike | xr.DataArray, **kwargs):
"""
Extract subsets from a grid.
Parameters:
- grid: Input grid file or xarray DataArray
- region: Subset extent [west, east, south, north]
- extend: Extend region if needed
- nans: Replace nodes outside region with NaN
Returns:
xarray.DataArray: Subset grid
"""
def grdclip(grid: PathLike | xr.DataArray, **kwargs):
"""
Clip the range of grid values.
Parameters:
- grid: Input grid file or xarray DataArray
- above: Clip values above this level
- below: Clip values below this level
- between: Clip values between two levels
- new_high: New value for clipped high values
- new_low: New value for clipped low values
Returns:
xarray.DataArray: Clipped grid
"""
def grdfill(grid: PathLike | xr.DataArray, **kwargs):
"""
Interpolate across holes in a grid.
Parameters:
- grid: Input grid with holes (NaN values)
- algorithm: Interpolation algorithm (constant/nearest/akima/spline)
- radius: Search radius for hole filling
- mode: Fill mode (all/edge/interior)
Returns:
xarray.DataArray: Filled grid
"""
def grdhisteq(grid: PathLike | xr.DataArray, **kwargs):
"""
Perform histogram equalization for a grid.
Parameters:
- grid: Input grid file or xarray DataArray
- divisions: Number of divisions for histogram equalization
- output_type: Output data type
- quadratic: Use quadratic intensity transformation
Returns:
xarray.DataArray: Histogram-equalized grid
"""
def grdlandmask(**kwargs):
"""
Create a "wet/dry" mask grid from shoreline data.
Parameters:
- region: Grid extent
- spacing: Grid spacing
- registration: Grid registration
- resolution: Shoreline resolution (full/high/intermediate/low/crude)
- area_thresh: Minimum feature area
- mask_type: Mask values (0/1 or 1/0 for land/water)
Returns:
xarray.DataArray: Land/water mask grid
"""
def grdproject(grid: PathLike | xr.DataArray, **kwargs):
"""
Forward and inverse map transformation of grids.
Parameters:
- grid: Input grid file or xarray DataArray
- projection: Target projection
- region: Output region (if different from input)
- spacing: Output spacing
- interpolation: Resampling method
- inverse: Perform inverse projection
- center: Center coordinates for projection
Returns:
xarray.DataArray: Projected grid
"""
def grdvolume(grid: PathLike | xr.DataArray, **kwargs):
"""
Calculate grid volume and area constrained by a contour.
Parameters:
- grid: Input grid file or xarray DataArray
- contour: Contour value for volume calculation
- unit: Area unit (squared map unit)
- find_volume: Calculate volume above/below contour
Returns:
dict: Volume and area statistics
"""Extract information from grids and convert between formats.
def grdinfo(grid: PathLike | xr.DataArray, **kwargs):
"""
Extract information from grids.
Parameters:
- grid: Input grid file or xarray DataArray
- verbose: Verbose output with full statistics
- force_scan: Force reading entire grid for statistics
- per_column: Report statistics per column
- nearest_multiple: Round spacing to nearest multiple
Returns:
str: Grid information string
"""
def grd2xyz(grid: PathLike | xr.DataArray, **kwargs):
"""
Convert grid to data table.
Parameters:
- grid: Input grid file or xarray DataArray
- region: Subset region for conversion
- output_type: Output format (xyz/table)
- reverse: List z-values in reverse order
- weights: Output (x,y,z,w) where w is weight
Returns:
pandas.DataFrame: Output data table
"""
def grd2cpt(**kwargs):
"""
Make a color palette table from grid(s).
Parameters:
- grid: Input grid file(s) or xarray DataArray(s)
- cmap: Master color palette to use as base
- reverse: Reverse the color progression
- symmetric: Make color palette symmetric about zero
- series: Set specific z-value range
- levels: Number of levels in output CPT
Returns:
str: Color palette table data
"""Process and analyze tabular (x, y, z) data.
def blockmean(data: PathLike | TableLike | None = None, **kwargs):
"""
Block average (x,y,z) data tables by mean estimation.
Parameters:
- data: Input data file or table
- region: Processing region
- spacing: Block size (dx, dy)
- registration: Block registration (gridline/pixel)
- summary: Summary mode for multiple values per block
- weights: Use weighted mean
- extend: Extend blocks to region boundary
Returns:
pandas.DataFrame: Block-averaged data
"""
def blockmedian(data: PathLike | TableLike | None = None, **kwargs):
"""
Block average (x,y,z) data tables by median estimation.
Parameters:
- data: Input data file or table
- region: Processing region
- spacing: Block size
- registration: Block registration
- quantile: Use L1 (median) or other quantile
- summary: Summary mode for blocks
Returns:
pandas.DataFrame: Block-processed data
"""
def blockmode(data: PathLike | TableLike | None = None, **kwargs):
"""
Block average (x,y,z) data tables by mode estimation.
Parameters:
- data: Input data file or table
- region: Processing region
- spacing: Block size
- registration: Block registration
- width: Half-width for mode search
- summary: Summary mode for blocks
Returns:
pandas.DataFrame: Block-processed data
"""
def binstats(data: PathLike | TableLike | None = None, **kwargs):
"""
Bin spatial data and calculate statistics per bin.
Parameters:
- data: Input data file or table
- region: Processing region
- spacing: Bin size
- statistic: Statistic to calculate (count/mean/median/mode/std/etc.)
- center: Center bins on coordinates
- empty: Value for empty bins
Returns:
pandas.DataFrame: Binned statistics
"""
def dimfilter(grid: PathLike | xr.DataArray, **kwargs):
"""
Directional median filter for grids.
Parameters:
- grid: Input grid file or xarray DataArray
- filter: Filter specification (type and parameters)
- distance: Filter distance/width
- geometry: Filter geometry (rectangular/circular)
- nans: How to handle NaN values
Returns:
xarray.DataArray: Filtered grid
"""
def filter1d(data: PathLike | TableLike | None = None, **kwargs):
"""
Apply a time domain filter to 1-D time series.
Parameters:
- data: Input time series data
- filter: Filter type and parameters
- output_format: Output format specification
- time_col: Time column specification
- robust: Use robust filtering
Returns:
pandas.DataFrame: Filtered time series
"""Transform coordinates and project data between coordinate systems.
def project(data: PathLike | TableLike | None = None, **kwargs):
"""
Project/transform coordinates.
Parameters:
- data: Input coordinate data
- center: Projection center coordinates
- projection: Projection type
- length_scale: Length scale for projection
- width_scale: Width scale for projection
- inverse: Perform inverse transformation
- ellipsoid: Reference ellipsoid
- unit: Distance units
Returns:
pandas.DataFrame: Transformed coordinates
"""
def grdtrack(data: PathLike | TableLike | None = None, grid: PathLike | xr.DataArray | None = None,
**kwargs):
"""
Sample grids at specified (x,y) locations.
Parameters:
- data: Input coordinate file or table (x, y columns)
- grid: Grid file(s) or xarray DataArray(s) to sample
- newcolname: Name for new columns with sampled values
- no_skip: Do not skip points outside grid domain
- radius: Search radius for nearest point
- bicubic: Use bicubic interpolation
Returns:
pandas.DataFrame: Input coordinates with sampled grid values
"""
def select(data: PathLike | TableLike | None = None, **kwargs):
"""
Select data subset based on multiple criteria.
Parameters:
- data: Input data file or table
- region: Geographic region selection
- condition: Conditional expression for selection
- reverse: Reverse the selection (select NOT matching)
- polygon: Select points inside/outside polygon
- distance: Distance-based selection criteria
- connect: Connect selection criteria with AND/OR
Returns:
pandas.DataFrame: Selected data subset
"""Create and modify color palettes for visualization.
def makecpt(**kwargs):
"""
Make GMT color palette tables.
Parameters:
- cmap: Master color palette table to use
- series: Define z-value range for new CPT ([min, max, inc])
- reverse: Reverse color progression
- truncate: Truncate incoming CPT range
- background: Select background/foreground colors
- output: Output filename for CPT file
- overrule_bg: Overrule background colors from master CPT
- continuous: Force continuous CPT
- no_bg: Don't write background/foreground/NaN colors
- transparency: Set transparency level (0-100)
- categorical: Use categorical color table
- cyclic: Produce wrapped/cyclic color table
- color_model: Force output CPT color model (RGB/HSV/CMYK)
- log: Use logarithmic interpolation
Returns:
str: Color palette table data
"""Analyze intersections between track data files.
def x2sys_init(tag: str, **kwargs):
"""
Initialize a new x2sys track database.
Parameters:
- tag: Database tag name
- suffix: File suffix for track files
- format: Track file format specification
- region: Default region for database
- projection: Default projection
- units: Distance and speed units
- gap: Maximum gap between data points
Returns:
None: Creates database files
"""
def x2sys_cross(tracks: PathLike | list | None = None, **kwargs):
"""
Calculate crossovers between track data files.
Parameters:
- tracks: Track file(s) or list of files
- tag: x2sys database tag
- region: Geographic region for crossover search
- interpolation: Interpolation method at crossovers
- coe: Crossover error calculation method
- track_output: Output individual track crossovers
- speed: Speed column for time-based interpolation
Returns:
pandas.DataFrame: Crossover analysis results
"""import pygmt
import numpy as np
# Create sample irregular data
np.random.seed(42)
x = np.random.uniform(-5, 5, 100)
y = np.random.uniform(-5, 5, 100)
z = x**2 + y**2
# Grid the data using surface method
grid = pygmt.surface(
data=np.column_stack([x, y, z]),
region=[-5, 5, -5, 5],
spacing=0.1,
tension=0.25
)
print(f"Grid shape: {grid.shape}")
print(f"Grid extent: {grid.gmt.registration}")import pygmt
# Load a sample grid
grid = pygmt.datasets.load_earth_relief(resolution="05m", region=[120, 160, 20, 50])
# Apply a smoothing filter
filtered = pygmt.grdfilter(
grid=grid,
filter="g50k", # Gaussian filter with 50 km width
distance="50k"
)
# Calculate gradients
gradients = pygmt.grdgradient(
grid=filtered,
azimuth=45, # Northeast direction
normalize="e" # Normalize by illumination
)
# Clip extreme values
clipped = pygmt.grdclip(
grid=gradients,
above=0.8,
below=-0.8,
new_high=0.8,
new_low=-0.8
)import pygmt
import pandas as pd
# Load sample data
data = pd.DataFrame({
'longitude': [120.5, 120.6, 120.7, 120.5, 120.6],
'latitude': [25.1, 25.2, 25.1, 25.3, 25.4],
'elevation': [100, 150, 120, 200, 180]
})
# Block average the data
block_avg = pygmt.blockmean(
data=data,
region=[120, 121, 25, 26],
spacing="0.1d", # 0.1 degree blocks
registration="g" # Gridline registration
)
print(block_avg.head())import pygmt
import numpy as np
# Create a sample track
track_lon = np.linspace(130, 140, 50)
track_lat = np.linspace(30, 35, 50)
track = np.column_stack([track_lon, track_lat])
# Load elevation grid
grid = pygmt.datasets.load_earth_relief(resolution="01m", region=[129, 141, 29, 36])
# Sample grid along track
sampled = pygmt.grdtrack(
data=track,
grid=grid,
newcolname="elevation"
)
print(f"Track points: {len(sampled)}")
print(f"Columns: {sampled.columns.tolist()}")Install with Tessl CLI
npx tessl i tessl/pypi-pygmt