Skip to content

Geometry

Grid, projection and tiling operators, plus swath / sensor-geometry corrections and image registration. Coregistration operators for multi-source matchups live in the geom.coregister subnamespace (below).

  • Projection / resampling: Reproject, ReprojectLike, Resample, ResampleLike, Resize
  • Shape: CropTo, CropToBounds, PadTo
  • Tiling: Tile, SlidingWindow, Stitch, Mosaic
  • Vector ↔ raster: Rasterize, RasterizeLike, Vectorize
  • Swath / sensor geometry: Georeference (GLT), SegmentStitch, BowtieCorrection, AntimeridianSplit, GeostationaryParallaxCorrect
  • Sampling at points: interp_at (function, under jit / grad), InterpAt (operator): H(x), a grid read at GeoPoints
  • Registration: PhaseAlign (phase cross-correlation), OpticalFlowILK, OpticalFlowTVL1
  • Diagnostic calculus: Gradient1D / 2D / 3D, Divergence1D / 2D / 3D, Curl2D / 3D, Laplacian1D / 2D / 3D (operators); gradient_1d, divergence_2d, curl_3d, … and their adaptive_* twins (arrays); difference, adaptive_difference, difference_offsets, difference_coeffs, nonuniform_coeffs (stencils)

Projection operator choices

  • Reproject changes CRS and optionally resolution, or warps onto a target grid. engine="gdal" (the default) runs georeader on NumPy; engine="interp" (the [interp] extra) warps onto target through a functax plan, on NumPy and on JAX under jit, with nearest, bilinear, cubic or cubic_spline.
  • ReprojectLike matches another GeoArray's CRS, transform, and shape.
  • ResampleLike is the same grid-matching surface for resolution/alignment work where the CRS is already compatible.
  • CropToBounds delegates to georeader.read.read_from_bounds(..., boundless=False): the pixel window is rounded outward, so every pixel the bounds touch (even partially) is kept, and the result is clipped to the carrier.

Diagnostic calculus

The calculus family has three levels, and each level is built from the one below. The operators read the geometry from the carrier: they map pixel derivatives to the CRS's axes through the transform, and on a geographic CRS they use the CRS ellipsoid's radii, so horizontal results are per CRS unit (per metre on a geographic CRS). The array primitives take the steps (dz, dy, dx) or the level positions (z=, coords=) instead, so the same maths runs on bare NumPy or JAX arrays inside a jitted cost. Both rest on difference and adaptive_difference, whose stencils come from difference_offsets and difference_coeffs, or from nonuniform_coeffs on an unevenly spaced axis.

Each name carries its dimension:

  • the 2-D operators (Gradient2D, Divergence2D, Curl2D, Laplacian2D) work over y x;
  • the 3-D ones (Gradient3D, Divergence3D, Curl3D, Laplacian3D) add the level dim, spaced by its VerticalAxis (depths, heights or pressures, unevenly spaced or not); Gradient3D and Curl3D return a component dim holding (z, y, x);
  • the 1-D ones (Gradient1D, Divergence1D, Laplacian1D) work along one dim named by along: "x" or "y" (on an axis-aligned grid), "level", or "time" (per second, from the TimeAxis).

A curl needs two dimensions, so there is no Curl1D.

The calculus operators expect collocated fields, all on one grid of cell centres. Ocean and atmosphere models often write staggered (Arakawa C-grid) output, with u on x-faces and v on y-faces. Collocate such output in the model library before calling an operator here, for example with finitevolX's Interpolation2D, or use finitevolX's own C-grid operators when you need model-grade differences. xrtoolz follows the same rule (its decision D14).

Pick nan_policy="adaptive" when the field has a mask that matters, such as a coastline: each derivative then uses the widest stencil that fits on valid data, so the cells next to land keep a value and only the masked cells are NaN. The default, "propagate", uses the plain stencil, and a masked cell costs a halo of about accuracy cells.

import numpy as np
from geoarray import GeoArray

import geoops as gz

rows, cols = np.mgrid[0:7, 0:9] + 0.5
x, y = 10.0 * cols, -10.0 * rows                      # (7, 9) metres
transform = (10.0, 0.0, 0.0, 0.0, -10.0, 0.0)
u = GeoArray(-y, transform, "EPSG:32613", dims=("y", "x"))  # (7, 9) float64
v = GeoArray(x, transform, "EPSG:32613", dims=("y", "x"))   # (7, 9) float64
land = np.zeros((7, 9), dtype=bool)                   # (7, 9) bool, True drops
land[:, 4] = True

zeta = gz.Curl2D(nan_policy="adaptive")(u, v, land)     # (7, 9), 2.0 off the wall
div = gz.Divergence2D()(u, v)                           # (7, 9), 0.0 everywhere
same = gz.geom.adaptive_curl_2d(-y, x, -10.0, 10.0, mask=land)  # (7, 9) ndarray

depth = np.array([0.0, 5.0, 15.0, 30.0])              # (4,) uneven levels, m
dtdz = gz.geom.gradient_1d(depth**2, coords=depth)    # (4,) per metre
lap = gz.geom.laplacian_3d(np.zeros((4, 7, 9)), z=depth)  # (4, 7, 9) float64

Sampling at points

interp_at reads a grid at the positions of a geoarray.GeoPoints: the observation operator H(x) of data assimilation. Bilinear weights blend the four pixels around each point (InterpAt declares it spatial, reach 1); "nearest" reads one. A point off the grid or on nodata is NaN and invalid, and a padded point gives 0, so a masked cost and its gradient do not depend on the padding. It runs on NumPy and under jax.jit / jax.grad; InterpAt is the same function as an operator, with the points as its second input. It moved here from geoarray (GA-B6), which keeps geoarray.to_pixel for the coordinate maths. InterpAt.plan(grid, points) returns that plan, H, built once per grid and points: plan.adjoint(r) and plan.operator().transpose() send point residuals back onto the grid as Hᵀ r. The stencil is a functax plan (functax.interp.Linear or Nearest on the grid's AffineGrid, with extent="cells" and boundary="edge"), so H has a tested adjoint, and both need the [interp] extra; a NumPy grid is read on JAX in 64-bit mode and comes back as NumPy.

geoops.geom

Geometry, projection, tiling, mosaicking, rasterization, and vectorization.

Cross-modality coregistration operators (raster↔raster grid alignment, swath↔grid, raster↔points, point-cloud↔raster, vector-with-aggregation) live in the coregister subnamespace (and at the top level) — see docs/catalog/design/query-matchup.md §5 for the design.

AntimeridianSplit

Bases: Operator

Split a geographic swath at a longitude wrap.

Longitudes are read from gt.attrs["lons"] / gt.attrs["lon"] / gt.attrs["longitude"] when present -- one value per column (a 1-D tuple) or one per pixel (nested (H, W) tuples such as lons.tolist(); attrs cannot hold a 2-D array) -- otherwise they are derived from the affine grid for geographic CRSs. If no jump larger than tolerance_deg is found, the output is a single-item list containing the input unchanged.

Each part carries its normalised longitudes (in [-180, 180)) under attrs["lons"], in the form they were read: per column when the input gave one value per column (or the grid-derived longitudes are constant along rows), else per pixel as nested tuples.

Geo-dependent: requires a georeferenced GeoArray input (attrs / geographic grid); plain arrays raise TypeError.

Parameters:

Name Type Description Default
crs str

Geographic CRS used to interpret longitudes.

'EPSG:4326'
tolerance_deg float

Absolute longitude jump threshold in degrees.

90.0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class AntimeridianSplit(Operator):
    """Split a geographic swath at a longitude wrap.

    Longitudes are read from ``gt.attrs["lons"]`` / ``gt.attrs["lon"]`` /
    ``gt.attrs["longitude"]`` when present -- one value per column (a 1-D
    tuple) or one per pixel (nested ``(H, W)`` tuples such as
    ``lons.tolist()``; attrs cannot hold a 2-D array) -- otherwise they are
    derived from the affine grid for geographic CRSs. If no jump larger
    than ``tolerance_deg`` is found, the output is a single-item list
    containing the input unchanged.

    Each part carries its normalised longitudes (in ``[-180, 180)``) under
    ``attrs["lons"]``, in the form they were read: per column when the
    input gave one value per column (or the grid-derived longitudes are
    constant along rows), else per pixel as nested tuples.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (attrs /
    geographic grid); plain arrays raise ``TypeError``.

    Args:
        crs: Geographic CRS used to interpret longitudes.
        tolerance_deg: Absolute longitude jump threshold in degrees.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # one carrier per side of the longitude wrap
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "split"}, kind="fan-out")

    def __init__(self, *, crs: str = "EPSG:4326", tolerance_deg: float = 90.0) -> None:
        self.crs = crs
        self._parsed_crs = CRS.from_user_input(crs)
        self.tolerance_deg = tolerance_deg

    def _apply(self, gt: GeoArray) -> list[GeoArray]:
        require_geoarray(gt, "AntimeridianSplit")
        lons = _longitude_grid(gt, self._parsed_crs)
        if lons is None:
            raise ValueError(
                "AntimeridianSplit requires geographic longitudes in attrs['lons'] "
                "or an affine geographic grid."
            )
        diffs = np.abs(np.diff(lons, axis=1))
        if diffs.size == 0 or np.nanmax(diffs) <= self.tolerance_deg:
            return [gt]
        # Reject swaths with more than one longitude discontinuity (e.g. polar
        # passes that wrap twice). The single-split heuristic below cannot
        # represent multi-jump cases correctly.
        per_col_max = np.nanmax(diffs, axis=0)
        n_jumps = int(np.sum(per_col_max > self.tolerance_deg))
        if n_jumps > 1:
            raise ValueError(
                f"AntimeridianSplit found {n_jumps} longitude jumps above "
                f"tolerance_deg={self.tolerance_deg}; only single-discontinuity "
                "swaths are supported."
            )
        # The diff at column i is the jump between i and i + 1.
        split_col = int(np.nanargmax(per_col_max)) + 1
        per_column = _per_column(gt, lons)
        left = _with_sliced_longitudes(
            gt[..., :, :split_col], lons[:, :split_col], per_column
        )
        right = _with_sliced_longitudes(
            gt[..., :, split_col:], lons[:, split_col:], per_column
        )
        left_mean = float(np.nanmean(_normalise_longitudes(lons[:, :split_col])))
        right_mean = float(np.nanmean(_normalise_longitudes(lons[:, split_col:])))
        return [left, right] if left_mean < right_mean else [right, left]

BowtieCorrection

Bases: Operator

Remove whiskbroom bowtie overlap by resampling each scan along track.

A whiskbroom scanner (MODIS, VIIRS) images N detector rows per mirror scan. The along-track footprint of a detector grows with scan angle θ, while the satellite advances by the same distance every scan, so consecutive scans overlap along track towards the swath edges: the same ground appears in the last rows of scan j and the first rows of scan j + 1 (the "bowtie" effect). This operator removes that duplication, per column, from the scan geometry alone.

Geometry (spherical Earth, radius R; altitude h; see radiomax.geometry.scan_pixel_growth)::

β(θ) = arcsin(((R + h)/R)·sin θ) − θ          Earth central angle
s(θ) = (R + h)·cos θ − √(R² − (R + h)²·sin² θ)  slant range
g(θ) = s / (h·cos β)                          along-track growth

g is the along-track size of a detector, measured in orbit angle (the coordinate in which every scan advances by the same amount), relative to nadir; g(0) = 1 and the flat-Earth limit is 1 / cos θ. The column scan angles θ_c follow the constant mirror rate (see radiomax.geometry.scan_angles), including VIIRS along-scan aggregation when aggregation_zones is given.

De-overlap. In units of one nadir detector, scans are contiguous at nadir (scan j spans rows j·N … j·N + N − 1) and detector k of scan j lies at y = j·N + (N − 1)/2 + (k − (N − 1)/2)·g. Output row r = j·N + m is the ground at y = r — a uniform along-track grid, identical to the input grid at nadir — sampled from the scan whose centre is nearest (scan j) at fractional detector k₀ = (N − 1)/2 + (m − (N − 1)/2)/g (nearest or linear in k). Each scan is therefore shrunk about its centre by 1/g so the rows it shares with a neighbour are taken once, from the nearer scan. If that sample is nodata, the overlapping neighbour scan j ± 1 is used instead when its footprint covers y = r; otherwise the output is fill.

Output grid. Same shape, transform and CRS as the input; only along-track values change. Columns are never moved (cross-track pixel growth is left for a swath-to-grid resampler: grid the corrected swath with :class:~geoops.geom.coregister.SwathToGrid) and the along-track extent is conserved.

Assumptions / limitations. Spherical Earth, circular orbit at a constant altitude, no terrain; scans exactly contiguous at nadir; detectors equally spaced along track (first order in the detector angle, error ~ (N·IFOV)² ≈ 10⁻⁴ of a row); the along-track shift of a scan line caused by satellite motion and Earth rotation during a scan is common to all scans of a column and does not change the overlap, so it is ignored. Input rows must be whole scans (H % N == 0) with row 0 the first detector of a scan.

VIIRS. On-board aggregation makes the columns non-uniform in angle; pass aggregation_zones (the viirs preset does). On-board bowtie deletion (1 row per scan edge in the 2-sample zone, 2 in the unaggregated zone, M-band; doubled for I-bands) delivers the duplicated rows as fill: they are nodata here, so the neighbouring scan's copy of that ground is used and no gap remains.

Nodata: a pixel is invalid when any band is non-finite or equals the carrier's fill; invalid samples never contribute to an output pixel, and output pixels without a valid source hold the output's fill (carried_fill: the input's fill for "nearest"; NaN for "linear" on integer input, which is promoted to float). (T, C, H, W) stacks are corrected frame by frame.

Pixel-space resampling (driven entirely by the scan-geometry constructor arguments): both GeoArray and plain np.ndarray inputs are supported and returned in kind.

Parameters:

Name Type Description Default
detectors_per_scan int

Detector rows per scan N.

required
max_scan_angle_deg float

Scan-edge angle θ_max in degrees (outer edge of the outermost native sample); 0 is the identity.

required
altitude_km float

Orbit altitude h (km).

required
earth_radius_km float

Earth radius R (km); defaults to the mean radius 6371.0088 km.

_EARTH_MEAN_RADIUS_KM
aggregation_zones Sequence[Sequence[int]] | None

Optional along-scan aggregation table, (native_samples, factor) per zone from nadir outward for one half-scan (VIIRS); None means one column per native sample.

None
method str

"nearest" (dtype-preserving, safe for masks / QA) or "linear" interpolation between detectors.

'nearest'

Examples:

>>> import geoops as gz
>>> debowtie = gz.geom.BowtieCorrection.modis()  # 1 km bands
>>> viirs = gz.geom.BowtieCorrection.viirs(band="M", method="linear")
>>> custom = gz.geom.BowtieCorrection(
...     detectors_per_scan=10, max_scan_angle_deg=55.0, altitude_km=705.0
... )
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class BowtieCorrection(Operator):
    """Remove whiskbroom bowtie overlap by resampling each scan along track.

    A whiskbroom scanner (MODIS, VIIRS) images ``N`` detector rows per
    mirror scan. The along-track footprint of a detector grows with scan
    angle θ, while the satellite advances by the same distance every scan,
    so consecutive scans overlap along track towards the swath edges: the
    same ground appears in the last rows of scan ``j`` and the first rows of
    scan ``j + 1`` (the "bowtie" effect). This operator removes that
    duplication, per column, from the scan geometry alone.

    **Geometry** (spherical Earth, radius ``R``; altitude ``h``; see
    `radiomax.geometry.scan_pixel_growth`)::

        β(θ) = arcsin(((R + h)/R)·sin θ) − θ          Earth central angle
        s(θ) = (R + h)·cos θ − √(R² − (R + h)²·sin² θ)  slant range
        g(θ) = s / (h·cos β)                          along-track growth

    ``g`` is the along-track size of a detector, measured in orbit angle
    (the coordinate in which every scan advances by the same amount),
    relative to nadir; ``g(0) = 1`` and the flat-Earth limit is
    ``1 / cos θ``. The column scan angles ``θ_c`` follow the constant
    mirror rate (see `radiomax.geometry.scan_angles`),
    including VIIRS along-scan aggregation when ``aggregation_zones`` is
    given.

    **De-overlap.** In units of one nadir detector, scans are contiguous
    at nadir (scan ``j`` spans rows ``j·N … j·N + N − 1``) and detector
    ``k`` of scan ``j`` lies at ``y = j·N + (N − 1)/2 + (k − (N − 1)/2)·g``.
    Output row ``r = j·N + m`` is the ground at ``y = r`` — a uniform
    along-track grid, identical to the input grid at nadir — sampled from
    the scan whose centre is nearest (scan ``j``) at fractional detector
    ``k₀ = (N − 1)/2 + (m − (N − 1)/2)/g`` (nearest or linear in ``k``).
    Each scan is therefore shrunk about its centre by ``1/g`` so the rows
    it shares with a neighbour are taken once, from the nearer scan. If
    that sample is nodata, the overlapping neighbour scan ``j ± 1`` is
    used instead when its footprint covers ``y = r``; otherwise the output
    is fill.

    **Output grid.** Same shape, transform and CRS as the input; only
    along-track values change. Columns are never moved (cross-track pixel
    growth is left for a swath-to-grid resampler: grid the corrected swath
    with :class:`~geoops.geom.coregister.SwathToGrid`) and the along-track
    extent is conserved.

    **Assumptions / limitations.** Spherical Earth, circular orbit at a
    constant altitude, no terrain; scans exactly contiguous at nadir;
    detectors equally spaced along track (first order in the detector
    angle, error ~ (N·IFOV)² ≈ 10⁻⁴ of a row); the along-track shift of a
    scan line caused by satellite motion and Earth rotation during a scan
    is common to all scans of a column and does not change the overlap, so
    it is ignored. Input rows must be whole scans (``H % N == 0``) with
    row 0 the first detector of a scan.

    **VIIRS.** On-board aggregation makes the columns non-uniform in angle;
    pass ``aggregation_zones`` (the ``viirs`` preset does). On-board
    *bowtie deletion* (1 row per scan edge in the 2-sample zone, 2 in the
    unaggregated zone, M-band; doubled for I-bands) delivers the duplicated
    rows as fill: they are nodata here, so the neighbouring scan's copy of
    that ground is used and no gap remains.

    Nodata: a pixel is invalid when any band is non-finite or equals the
    carrier's fill; invalid samples never contribute to an output pixel,
    and output pixels without a valid source hold the output's fill
    (``carried_fill``: the input's fill for ``"nearest"``; ``NaN`` for
    ``"linear"`` on integer input, which is promoted to float).
    ``(T, C, H, W)`` stacks are corrected frame by frame.

    Pixel-space resampling (driven entirely by the scan-geometry
    constructor arguments): both ``GeoArray`` and plain ``np.ndarray``
    inputs are supported and returned in kind.

    Args:
        detectors_per_scan: Detector rows per scan ``N``.
        max_scan_angle_deg: Scan-edge angle ``θ_max`` in degrees (outer edge
            of the outermost native sample); ``0`` is the identity.
        altitude_km: Orbit altitude ``h`` (km).
        earth_radius_km: Earth radius ``R`` (km); defaults to the mean
            radius 6371.0088 km.
        aggregation_zones: Optional along-scan aggregation table,
            ``(native_samples, factor)`` per zone from nadir outward for one
            half-scan (VIIRS); ``None`` means one column per native sample.
        method: ``"nearest"`` (dtype-preserving, safe for masks / QA) or
            ``"linear"`` interpolation between detectors.

    Examples:
        >>> import geoops as gz
        >>> debowtie = gz.geom.BowtieCorrection.modis()  # 1 km bands
        >>> viirs = gz.geom.BowtieCorrection.viirs(band="M", method="linear")
        >>> custom = gz.geom.BowtieCorrection(
        ...     detectors_per_scan=10, max_scan_angle_deg=55.0, altitude_km=705.0
        ... )
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each scan resampled along track
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        detectors_per_scan: int,
        max_scan_angle_deg: float,
        altitude_km: float,
        earth_radius_km: float = _EARTH_MEAN_RADIUS_KM,
        aggregation_zones: Sequence[Sequence[int]] | None = None,
        method: str = "nearest",
    ) -> None:
        if detectors_per_scan < 1:
            raise ValueError("detectors_per_scan must be >= 1.")
        if altitude_km <= 0 or earth_radius_km <= 0:
            raise ValueError("altitude_km and earth_radius_km must be > 0.")
        horizon = np.rad2deg(
            np.arcsin(earth_radius_km / (earth_radius_km + altitude_km))
        )
        if not 0.0 <= max_scan_angle_deg < horizon:
            raise ValueError(
                f"max_scan_angle_deg must be in [0, {horizon:.2f}) — the horizon "
                f"seen from {altitude_km} km."
            )
        if method not in {"nearest", "linear"}:
            raise ValueError("method must be 'nearest' or 'linear'.")
        self.detectors_per_scan = int(detectors_per_scan)
        self.max_scan_angle_deg = max_scan_angle_deg
        self.altitude_km = altitude_km
        self.earth_radius_km = earth_radius_km
        self.aggregation_zones = (
            None
            if aggregation_zones is None
            else tuple(
                (int(native), int(factor)) for native, factor in aggregation_zones
            )
        )
        self.method = method

    @classmethod
    def modis(
        cls, resolution_m: int = 1000, *, method: str = "nearest"
    ) -> BowtieCorrection:
        """MODIS (Terra / Aqua) preset.

        10 / 20 / 40 detectors per scan at 1 km / 500 m / 250 m, ±55°,
        705 km (Barnes et al. 1998; Wolfe et al. 2002).

        Args:
            resolution_m: Band resolution: ``1000``, ``500`` or ``250``.
            method: ``"nearest"`` or ``"linear"``.

        Returns:
            The configured operator.

        Examples:
            >>> BowtieCorrection.modis().detectors_per_scan
            10
            >>> BowtieCorrection.modis(250).detectors_per_scan
            40
        """
        if resolution_m not in _MODIS_DETECTORS:
            raise ValueError(f"resolution_m must be one of {sorted(_MODIS_DETECTORS)}.")
        return cls(
            detectors_per_scan=_MODIS_DETECTORS[resolution_m],
            max_scan_angle_deg=_MODIS_MAX_SCAN_ANGLE_DEG,
            altitude_km=_MODIS_ALTITUDE_KM,
            method=method,
        )

    @classmethod
    def viirs(cls, band: str = "M", *, method: str = "nearest") -> BowtieCorrection:
        """VIIRS (S-NPP / JPSS) preset for aggregated SDR swaths.

        16 M-band (3200 columns) or 32 I-band (6400 columns) detectors per
        scan, ±56.28°, 824 km, with the three on-board aggregation zones
        (NOAA NESDIS 142, VIIRS SDR User's Guide). Bowtie-deleted rows are
        expected as fill and are refilled from the overlapping scan.

        Args:
            band: ``"M"`` (750 m) or ``"I"`` (375 m).
            method: ``"nearest"`` or ``"linear"``.

        Returns:
            The configured operator.

        Examples:
            >>> BowtieCorrection.viirs().detectors_per_scan
            16
            >>> BowtieCorrection.viirs("I").aggregation_zones[0]
            (3552, 3)
        """
        if band not in _VIIRS_DETECTORS:
            raise ValueError(f"band must be one of {sorted(_VIIRS_DETECTORS)}.")
        scale = 2 if band == "I" else 1
        return cls(
            detectors_per_scan=_VIIRS_DETECTORS[band],
            max_scan_angle_deg=_VIIRS_MAX_SCAN_ANGLE_DEG,
            altitude_km=_VIIRS_ALTITUDE_KM,
            aggregation_zones=tuple(
                (native * scale, factor) for native, factor in _VIIRS_M_ZONES
            ),
            method=method,
        )

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        require_ndim(gt, (2, 3), "BowtieCorrection")
        n = self.detectors_per_scan
        height, width = gt.shape[-2:]
        if height % n:
            raise ValueError(
                f"BowtieCorrection needs whole scans: {height} rows is not a "
                f"multiple of detectors_per_scan={n}."
            )
        theta = scan_angles(width, self.max_scan_angle_deg, self.aggregation_zones)
        _, growth, _ = scan_pixel_growth(
            theta, 1e3 * self.altitude_km, radius=1e3 * self.earth_radius_km
        )
        k0, k1, step = bowtie_detector_positions(growth, n)

        values = np.asarray(gt)
        if self.method == "linear":
            values = as_float(values)
        valid = valid_pixels(gt)
        rows = np.arange(height)
        scan = rows // n
        m = rows % n
        n_scans = height // n
        # Primary source: the scan whose nadir rows contain the output row.
        out, ok = self._sample_scan(values, valid, scan, k0[m], n)
        # Fallback: the overlapping neighbour scan, where the primary is nodata.
        neighbour = scan + step[m]
        in_granule = (neighbour >= 0) & (neighbour < n_scans)
        alt, alt_ok = self._sample_scan(
            values, valid, np.clip(neighbour, 0, n_scans - 1), k1[m], n
        )
        use_alt = ~ok & alt_ok & in_granule[:, None]
        out = np.where(use_alt, alt, out)
        filled = ok | use_alt
        fill = carried_fill(gt, out.dtype)
        return wrap_filled(gt, out, fill_value=fill, valid=filled)

    def _sample_scan(
        self,
        values: np.ndarray,
        valid: np.ndarray,
        scan: np.ndarray,
        k: np.ndarray,
        n: int,
    ) -> tuple[np.ndarray, np.ndarray]:
        """Sample ``values`` at fractional detector ``k`` of scan ``scan``.

        Returns the ``(..., H, W)`` samples and the ``(H, W)`` mask of
        samples inside the scan footprint (``−½ ≤ k ≤ N − ½``) whose
        contributing input pixels are all valid.
        """
        cols = np.arange(k.shape[-1])[None, :]
        base = (scan * n)[:, None]
        inside = (k >= -0.5) & (k <= n - 0.5)
        kc = np.clip(k, 0.0, n - 1.0)
        if self.method == "nearest":
            row = base + np.rint(kc).astype(int)
            return values[..., row, cols], inside & valid[row, cols]
        # Linear in k: v = v[k₀] + w·(v[k₀ + 1] − v[k₀]), w = k − k₀ (exact when
        # the two detectors agree, so a cross-track ramp maps to itself).
        lo = np.minimum(np.floor(kc).astype(int), max(n - 2, 0))
        hi = np.minimum(lo + 1, n - 1)
        weight = (kc - lo).astype(values.dtype)
        row_lo, row_hi = base + lo, base + hi
        valid_lo, valid_hi = valid[row_lo, cols], valid[row_hi, cols]
        # Zero-weight neighbours may be nodata without spoiling the sample.
        ok = inside & (valid_lo | (weight == 1)) & (valid_hi | (weight == 0))
        v_lo = np.where(valid_lo, values[..., row_lo, cols], 0)
        v_hi = np.where(valid_hi, values[..., row_hi, cols], 0)
        return v_lo + weight * (v_hi - v_lo), ok

modis(resolution_m=1000, *, method='nearest') classmethod

MODIS (Terra / Aqua) preset.

10 / 20 / 40 detectors per scan at 1 km / 500 m / 250 m, ±55°, 705 km (Barnes et al. 1998; Wolfe et al. 2002).

Parameters:

Name Type Description Default
resolution_m int

Band resolution: 1000, 500 or 250.

1000
method str

"nearest" or "linear".

'nearest'

Returns:

Type Description
BowtieCorrection

The configured operator.

Examples:

>>> BowtieCorrection.modis().detectors_per_scan
10
>>> BowtieCorrection.modis(250).detectors_per_scan
40
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
@classmethod
def modis(
    cls, resolution_m: int = 1000, *, method: str = "nearest"
) -> BowtieCorrection:
    """MODIS (Terra / Aqua) preset.

    10 / 20 / 40 detectors per scan at 1 km / 500 m / 250 m, ±55°,
    705 km (Barnes et al. 1998; Wolfe et al. 2002).

    Args:
        resolution_m: Band resolution: ``1000``, ``500`` or ``250``.
        method: ``"nearest"`` or ``"linear"``.

    Returns:
        The configured operator.

    Examples:
        >>> BowtieCorrection.modis().detectors_per_scan
        10
        >>> BowtieCorrection.modis(250).detectors_per_scan
        40
    """
    if resolution_m not in _MODIS_DETECTORS:
        raise ValueError(f"resolution_m must be one of {sorted(_MODIS_DETECTORS)}.")
    return cls(
        detectors_per_scan=_MODIS_DETECTORS[resolution_m],
        max_scan_angle_deg=_MODIS_MAX_SCAN_ANGLE_DEG,
        altitude_km=_MODIS_ALTITUDE_KM,
        method=method,
    )

viirs(band='M', *, method='nearest') classmethod

VIIRS (S-NPP / JPSS) preset for aggregated SDR swaths.

16 M-band (3200 columns) or 32 I-band (6400 columns) detectors per scan, ±56.28°, 824 km, with the three on-board aggregation zones (NOAA NESDIS 142, VIIRS SDR User's Guide). Bowtie-deleted rows are expected as fill and are refilled from the overlapping scan.

Parameters:

Name Type Description Default
band str

"M" (750 m) or "I" (375 m).

'M'
method str

"nearest" or "linear".

'nearest'

Returns:

Type Description
BowtieCorrection

The configured operator.

Examples:

>>> BowtieCorrection.viirs().detectors_per_scan
16
>>> BowtieCorrection.viirs("I").aggregation_zones[0]
(3552, 3)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
@classmethod
def viirs(cls, band: str = "M", *, method: str = "nearest") -> BowtieCorrection:
    """VIIRS (S-NPP / JPSS) preset for aggregated SDR swaths.

    16 M-band (3200 columns) or 32 I-band (6400 columns) detectors per
    scan, ±56.28°, 824 km, with the three on-board aggregation zones
    (NOAA NESDIS 142, VIIRS SDR User's Guide). Bowtie-deleted rows are
    expected as fill and are refilled from the overlapping scan.

    Args:
        band: ``"M"`` (750 m) or ``"I"`` (375 m).
        method: ``"nearest"`` or ``"linear"``.

    Returns:
        The configured operator.

    Examples:
        >>> BowtieCorrection.viirs().detectors_per_scan
        16
        >>> BowtieCorrection.viirs("I").aggregation_zones[0]
        (3552, 3)
    """
    if band not in _VIIRS_DETECTORS:
        raise ValueError(f"band must be one of {sorted(_VIIRS_DETECTORS)}.")
    scale = 2 if band == "I" else 1
    return cls(
        detectors_per_scan=_VIIRS_DETECTORS[band],
        max_scan_angle_deg=_VIIRS_MAX_SCAN_ANGLE_DEG,
        altitude_km=_VIIRS_ALTITUDE_KM,
        aggregation_zones=tuple(
            (native * scale, factor) for native, factor in _VIIRS_M_ZONES
        ),
        method=method,
    )

CropTo

Bases: Operator

Crop a GeoArray to a target spatial shape.

Anchors either at the centre (default) or upper-left corner of the input. The affine transform is updated by slicing the GeoArray, so the geographic extent of the surviving pixels is preserved.

Pixel-space cropping: plain np.ndarray inputs are supported (sliced and returned as plain arrays); the transform bookkeeping only happens for GeoArray input.

Parameters:

Name Type Description Default
shape tuple[int, int]

Target spatial shape (H, W). Must be <= the input shape; oversize crops raise ValueError.

required
anchor str

"center" (default) or "upper_left".

'center'

Examples:

>>> import geoops as gz
>>> # Centre-crop a 1024×1024 scene to a 512×512 chip.
>>> chip = gz.geom.CropTo(shape=(512, 512))(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class CropTo(Operator):
    """Crop a `GeoArray` to a target spatial shape.

    Anchors either at the centre (default) or upper-left corner of the
    input. The affine transform is updated by slicing the `GeoArray`, so
    the geographic extent of the surviving pixels is preserved.

    Pixel-space cropping: plain ``np.ndarray`` inputs are supported
    (sliced and returned as plain arrays); the transform bookkeeping
    only happens for ``GeoArray`` input.

    Args:
        shape: Target spatial shape ``(H, W)``. Must be ``<=`` the
            input shape; oversize crops raise ``ValueError``.
        anchor: ``"center"`` (default) or ``"upper_left"``.

    Examples:
        >>> import geoops as gz
        >>> # Centre-crop a 1024×1024 scene to a 512×512 chip.
        >>> chip = gz.geom.CropTo(shape=(512, 512))(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self, *, shape: tuple[int, int], anchor: str = "center") -> None:
        self.shape = shape
        self.anchor = anchor

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "CropTo")
        height, width = gt.shape[-2:]
        if self.shape[0] > height or self.shape[1] > width:
            raise ValueError(f"Cannot crop shape {(height, width)} to {self.shape}.")
        if self.anchor == "center":
            row_off, col_off = center_offsets((height, width), self.shape)
        elif self.anchor == "upper_left":
            row_off, col_off = 0, 0
        else:
            raise ValueError("anchor must be 'center' or 'upper_left'.")
        rows = slice(row_off, row_off + self.shape[0])
        cols = slice(col_off, col_off + self.shape[1])
        if not isinstance(gt, GeoArray):
            return np.asarray(gt)[..., rows, cols]
        return gt[..., rows, cols]

    def get_config(self) -> dict[str, Any]:
        return {"shape": list(self.shape), "anchor": self.anchor}

CropToBounds

Bases: Operator

Crop a GeoArray to a geographic bounding box.

Thin wrapper over :func:georeader.read.read_from_bounds with boundless=False: bounds are reprojected into the carrier's CRS if crs differs from it, the pixel window is rounded outward (every pixel the bounds touch, even partially, is kept — matching georeader's readers), and the intersection with the carrier is read. Non-intersecting bounds raise :class:rasterio.windows.WindowError.

Geo-dependent: requires a georeferenced GeoArray input (transform + CRS); plain arrays raise TypeError.

Parameters:

Name Type Description Default
bounds tuple[float, float, float, float]

(minx, miny, maxx, maxy) in CRS units of crs.

required
crs str | None

CRS of bounds. None (default) means "same as the carrier".

None

Examples:

>>> import geoops as gz
>>> # Crop a global mosaic to a small AOI in geographic coords.
>>> aoi = gz.geom.CropToBounds(
...     bounds=(-10.0, 35.0, -8.0, 36.5), crs="EPSG:4326"
... )
>>> patch = aoi(global_scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class CropToBounds(Operator):
    """Crop a `GeoArray` to a geographic bounding box.

    Thin wrapper over :func:`georeader.read.read_from_bounds` with
    ``boundless=False``: ``bounds`` are reprojected into the carrier's
    CRS if ``crs`` differs from it, the pixel window is rounded
    *outward* (every pixel the bounds touch, even partially, is kept —
    matching georeader's readers), and the intersection with the carrier
    is read. Non-intersecting bounds raise
    :class:`rasterio.windows.WindowError`.

    Geo-dependent: requires a georeferenced ``GeoArray`` input
    (transform + CRS); plain arrays raise ``TypeError``.

    Args:
        bounds: ``(minx, miny, maxx, maxy)`` in CRS units of ``crs``.
        crs: CRS of ``bounds``. ``None`` (default) means "same as the
            carrier".

    Examples:
        >>> import geoops as gz
        >>> # Crop a global mosaic to a small AOI in geographic coords.
        >>> aoi = gz.geom.CropToBounds(
        ...     bounds=(-10.0, 35.0, -8.0, 36.5), crs="EPSG:4326"
        ... )
        >>> patch = aoi(global_scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(
        self,
        *,
        bounds: tuple[float, float, float, float],
        crs: str | None = None,
    ) -> None:
        self.bounds = bounds
        self.crs = crs

    def _apply(self, gt: GeoArray) -> GeoArray:
        rasterio = optional_root(
            "rasterio.windows", "raster", feature="geoops.geom.CropToBounds"
        )
        read = optional_name(
            "georeader", "read", "sensors", feature="geoops.geom.CropToBounds"
        )
        require_geoarray(gt, "CropToBounds")
        cropped = read.read_from_bounds(
            to_engine(gt), tuple(self.bounds), crs_bounds=self.crs, boundless=False
        )
        if cropped is None:
            # georeader signals an empty intersection with ``None``.
            raise rasterio.windows.WindowError(
                f"CropToBounds: bounds {tuple(self.bounds)!r} (crs={self.crs!r}) "
                f"do not intersect the carrier's bounds {gt.bounds!r}."
            )
        return adopt_attrs(gt, cropped)

    def get_config(self) -> dict[str, Any]:
        return {"bounds": list(self.bounds), "crs": self.crs}

Curl2D

Bases: Operator

Curl (relative vorticity) of a gridded 2-D vector field in map axes.

.. math::

\zeta = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y}

Inputs, geometry, masks and outputs as :class:Divergence2D. On a geographic CRS, with the CRS ellipsoid's radii,

.. math::

\zeta = \frac{1}{N \cos\varphi} \frac{\partial v}{\partial \lambda}
      - \frac{1}{M N \cos\varphi}
        \frac{\partial (N \cos\varphi\, u)}{\partial \varphi}.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> zeta = gz.Curl2D()(u, v)                               # (y, x)
>>> zeta = gz.Curl2D(nan_policy="adaptive")(u, v, land)    # up to the coast
>>> zeta = gz.geom.curl_2d(u, v, dy, dx)                   # arrays only, jittable
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Curl2D(Operator):
    r"""Curl (relative vorticity) of a gridded 2-D vector field in map axes.

    .. math::

        \zeta = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y}

    Inputs, geometry, masks and outputs as :class:`Divergence2D`. On a
    geographic CRS, with the CRS ellipsoid's radii,

    .. math::

        \zeta = \frac{1}{N \cos\varphi} \frac{\partial v}{\partial \lambda}
              - \frac{1}{M N \cos\varphi}
                \frac{\partial (N \cos\varphi\, u)}{\partial \varphi}.

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> zeta = gz.Curl2D()(u, v)                               # (y, x)
        >>> zeta = gz.Curl2D(nan_policy="adaptive")(u, v, land)    # up to the coast
        >>> zeta = gz.geom.curl_2d(u, v, dy, dx)                   # arrays only, jittable
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, u: Any, v: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Curl2D", (u, v), mask)
        return prepared.finish(_horizontal_curl(self, prepared, *prepared.fields))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Curl3D

Bases: Operator

Curl (vorticity vector) of a gridded 3-D vector field on vertical levels.

.. math::

\omega_z = \partial_x v - \partial_y u, \quad
\omega_y = \partial_z u - \partial_x w, \quad
\omega_x = \partial_y w - \partial_z v

:math:\omega_z is :class:Curl2D's relative vorticity; the horizontal derivatives of w are :class:Gradient2D's (thin-shell on a geographic CRS), and ∂/∂z runs along the level dim with its VerticalAxis spacing. z is the level coordinate as stored and w its component: on a positive="down" axis (depth, pressure) (x, y, z) is left-handed, so :math:\omega_y and :math:\omega_x have the opposite sign of the curl in upward height. The result gains a component dim before y x holding (ω_z, ω_y, ω_x), in axis order as :class:Gradient3D.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> omega = gz.Curl3D()(u, v, w)               # (level, component, y, x)
>>> omega = gz.geom.curl_3d(u, v, w, dz, dy, dx, z=height)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Curl3D(Operator):
    r"""Curl (vorticity vector) of a gridded 3-D vector field on vertical levels.

    .. math::

        \omega_z = \partial_x v - \partial_y u, \quad
        \omega_y = \partial_z u - \partial_x w, \quad
        \omega_x = \partial_y w - \partial_z v

    :math:`\omega_z` is :class:`Curl2D`'s relative vorticity; the horizontal
    derivatives of ``w`` are :class:`Gradient2D`'s (thin-shell on a
    geographic CRS), and ``∂/∂z`` runs along the ``level`` dim with its
    ``VerticalAxis`` spacing. ``z`` is the level coordinate as stored and
    ``w`` its component: on a ``positive="down"`` axis (depth, pressure)
    ``(x, y, z)`` is left-handed, so :math:`\omega_y` and :math:`\omega_x`
    have the opposite sign of the curl in upward height. The result gains a
    ``component`` dim before ``y x`` holding ``(ω_z, ω_y, ω_x)``, in axis
    order as :class:`Gradient3D`.

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> omega = gz.Curl3D()(u, v, w)               # (level, component, y, x)
        >>> omega = gz.geom.curl_3d(u, v, w, dz, dy, dx, z=height)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"level", "space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, u: Any, v: Any, w: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Curl3D", (u, v, w), mask)
        fu, fv, fw = prepared.fields
        omega_z = _horizontal_curl(self, prepared, fu, fv)
        dw_y, dw_x = _map_gradient(self, prepared, fw)
        du_z = _vertical(self, prepared, fu, 1, "Curl3D")
        dv_z = _vertical(self, prepared, fv, 1, "Curl3D")
        return prepared.finish_components((omega_z, du_z - dw_x, dw_y - dv_z))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Divergence1D

Bases: Operator

Divergence of a flux along one dim, :math:\partial u / \partial s.

In one dimension the divergence of a flux is its derivative, so this is :class:Gradient1D read as a conservation term: ∂F/∂z of a vertical flux on "level", ∂q/∂x along a channel. along, spacing, masks and outputs as :class:Gradient1D.

Parameters:

Name Type Description Default
along str

"x", "y", "level" or "time".

'x'
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic bool

The dim wraps.

False

Examples:

>>> import geoops as gz
>>> heating = gz.Divergence1D(along="level")(heat_flux)  # (level, y, x)
>>> ddiv = gz.geom.divergence_1d(flux, coords=depth, axis=-3)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Divergence1D(Operator):
    r"""Divergence of a flux along one dim, :math:`\partial u / \partial s`.

    In one dimension the divergence of a flux is its derivative, so this is
    :class:`Gradient1D` read as a conservation term: ``∂F/∂z`` of a vertical
    flux on ``"level"``, ``∂q/∂x`` along a channel. ``along``, spacing, masks
    and outputs as :class:`Gradient1D`.

    Args:
        along: ``"x"``, ``"y"``, ``"level"`` or ``"time"``.
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic: The dim wraps.

    Examples:
        >>> import geoops as gz
        >>> heating = gz.Divergence1D(along="level")(heat_flux)  # (level, y, x)
        >>> ddiv = gz.geom.divergence_1d(flux, coords=depth, axis=-3)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        along: str = "x",
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy, along=along)
        self.along = along
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic = periodic

    def _apply(self, u: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Divergence1D", (u,), mask)
        (field,) = prepared.fields
        return prepared.finish(_along(self, prepared, field, 1, "Divergence1D"))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Divergence2D

Bases: Operator

Divergence of a gridded 2-D vector field in map axes, NaN- and mask-aware.

.. math::

\nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
                        + \frac{\partial v}{\partial y}

u and v are two positional carriers on one grid, the components along the CRS's x and y (eastward and northward on a geographic CRS). The geometry, nan_policy and mask follow :class:Gradient2D: pixel derivatives map to map axes through the transform's Jacobian, so north-up, flipped and rotated grids are exact for a linear field. On a geographic CRS the divergence uses the CRS ellipsoid's radii :math:M(\varphi) and :math:N(\varphi), as Gradient2D does,

.. math::

\nabla \cdot \mathbf{u} = \frac{1}{N \cos\varphi}
    \frac{\partial u}{\partial \lambda}
  + \frac{1}{M N \cos\varphi}
    \frac{\partial (N \cos\varphi\, v)}{\partial \varphi},

which is the spherical form on a sphere (:math:M = N = R). A cell is dropped where either component is nodata (non-finite, or its carrier's fill) or mask is True. The result is on the input grid, per CRS unit (per metre on a geographic CRS), with fill_value=NaN. A plain array is differentiated in pixel units, rows then columns; a DataArray is refused (lift it with xrops.lift, or call :func:geoops.geom.divergence_2d with coordinate spacings).

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> div = gz.Divergence2D()(u, v)                              # (y, x)
>>> div = gz.Divergence2D(nan_policy="adaptive")(u, v, land)   # keeps the coast
>>> div = gz.geom.adaptive_divergence_2d(u, v, dy, dx, mask=land)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Divergence2D(Operator):
    r"""Divergence of a gridded 2-D vector field in map axes, NaN- and mask-aware.

    .. math::

        \nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
                                + \frac{\partial v}{\partial y}

    ``u`` and ``v`` are two positional carriers on one grid, the components
    along the CRS's ``x`` and ``y`` (eastward and northward on a geographic
    CRS). The geometry, ``nan_policy`` and mask follow :class:`Gradient2D`:
    pixel derivatives map to map axes through the transform's Jacobian, so
    north-up, flipped and rotated grids are exact for a linear field. On a
    geographic CRS the divergence uses the CRS ellipsoid's radii
    :math:`M(\varphi)` and :math:`N(\varphi)`, as ``Gradient2D`` does,

    .. math::

        \nabla \cdot \mathbf{u} = \frac{1}{N \cos\varphi}
            \frac{\partial u}{\partial \lambda}
          + \frac{1}{M N \cos\varphi}
            \frac{\partial (N \cos\varphi\, v)}{\partial \varphi},

    which is the spherical form on a sphere (:math:`M = N = R`). A cell is
    dropped where either component is nodata (non-finite, or its carrier's
    fill) or ``mask`` is ``True``. The result is on the input grid, per CRS
    unit (per metre on a geographic CRS), with ``fill_value=NaN``. A plain
    array is differentiated in pixel units, rows then columns; a
    ``DataArray`` is refused (lift it with ``xrops.lift``, or call
    :func:`geoops.geom.divergence_2d` with coordinate spacings).

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> div = gz.Divergence2D()(u, v)                              # (y, x)
        >>> div = gz.Divergence2D(nan_policy="adaptive")(u, v, land)   # keeps the coast
        >>> div = gz.geom.adaptive_divergence_2d(u, v, dy, dx, mask=land)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, u: Any, v: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Divergence2D", (u, v), mask)
        return prepared.finish(_horizontal_divergence(self, prepared, *prepared.fields))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Divergence3D

Bases: Operator

Divergence of a gridded 3-D vector field on vertical levels.

.. math::

\nabla \cdot \mathbf{u} = \nabla_h \cdot \mathbf{u}_h
                        + \frac{\partial w}{\partial z}

The horizontal part as :class:Divergence2D (the ellipsoid's flux form on a geographic CRS, thin-shell), plus ∂w/∂z along the level dim with its VerticalAxis spacing. w is the component along increasing level values, so on pressure levels this is the pressure-coordinate divergence with :math:\omega in w; on depth levels w points down. u, v and w are three positional carriers with one grid and one level axis.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> div = gz.Divergence3D()(u, v, omega)       # (level, y, x)
>>> div = gz.geom.divergence_3d(u, v, w, dz, dy, dx, z=depth)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Divergence3D(Operator):
    r"""Divergence of a gridded 3-D vector field on vertical levels.

    .. math::

        \nabla \cdot \mathbf{u} = \nabla_h \cdot \mathbf{u}_h
                                + \frac{\partial w}{\partial z}

    The horizontal part as :class:`Divergence2D` (the ellipsoid's flux form on
    a geographic CRS, thin-shell), plus ``∂w/∂z`` along the ``level`` dim with
    its ``VerticalAxis`` spacing. ``w`` is the component along increasing
    level values, so on pressure levels this is the pressure-coordinate
    divergence with :math:`\omega` in ``w``; on depth levels ``w`` points
    down. ``u``, ``v`` and ``w`` are three positional carriers with one grid
    and one ``level`` axis.

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> div = gz.Divergence3D()(u, v, omega)       # (level, y, x)
        >>> div = gz.geom.divergence_3d(u, v, w, dz, dy, dx, z=depth)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"level", "space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, u: Any, v: Any, w: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Divergence3D", (u, v, w), mask)
        fu, fv, fw = prepared.fields
        horizontal = _horizontal_divergence(self, prepared, fu, fv)
        return prepared.finish(
            horizontal + _vertical(self, prepared, fw, 1, "Divergence3D")
        )

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Georeference

Bases: Operator

Georeference swath data using a GLT (geolocation lookup table) GeoArray.

Thin wrapper around :func:georeader.griddata.georreference (note the upstream spelling), called through the engine boundary. The GLT (Geolocation Lookup Table) maps output-grid pixels to source-sensor pixels for fast, exact orthorectification with no resampling artifacts.

The input is sensor-space swath data, so plain np.ndarray input is accepted alongside GeoArray; the output is always a georeferenced GeoArray whose geometry comes from the GLT.

Parameters:

Name Type Description Default
glt GeoArray

GLT GeoArray of shape (2, H_out, W_out). glt[0] holds source columns; glt[1] holds source rows.

required
valid_glt ndarray | None

Optional boolean mask of valid GLT pixels.

None
Note

Carries a concrete GeoArray and (optionally) a numpy array reference, so flagged forbid_in_yaml = True.

Examples:

>>> import geoops as gz
>>> # Orthorectify a hyperspectral scene predicted in sensor space.
>>> ortho = gz.geom.Georeference(glt=glt)(prediction_swath)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Georeference(Operator):
    """Georeference swath data using a GLT (geolocation lookup table) `GeoArray`.

    Thin wrapper around :func:`georeader.griddata.georreference` (note
    the upstream spelling), called through the engine boundary. The GLT (Geolocation Lookup Table) maps
    output-grid pixels to source-sensor pixels for fast, exact
    orthorectification with no resampling artifacts.

    The input is sensor-space swath data, so plain ``np.ndarray`` input
    is accepted alongside ``GeoArray``; the output is always a
    georeferenced ``GeoArray`` whose geometry comes from the GLT.

    Args:
        glt: GLT `GeoArray` of shape ``(2, H_out, W_out)``. ``glt[0]``
            holds source columns; ``glt[1]`` holds source rows.
        valid_glt: Optional boolean mask of valid GLT pixels.

    Note:
        Carries a concrete `GeoArray` and (optionally) a numpy array
        reference, so flagged ``forbid_in_yaml = True``.

    Examples:
        >>> import geoops as gz
        >>> # Orthorectify a hyperspectral scene predicted in sensor space.
        >>> ortho = gz.geom.Georeference(glt=glt)(prediction_swath)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a lookup table moves each sensor pixel onto the map grid
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, glt: GeoArray, valid_glt: np.ndarray | None = None) -> None:
        self.glt = glt
        self.valid_glt = valid_glt

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray:
        griddata = optional_name(
            "georeader",
            "griddata",
            "sensors",
            feature="geoops.geom.Georeference",
        )
        reject_geotensor(gt, "Georeference")
        reject_georeader(self.glt, "Georeference (glt)")
        reject_geotensor(self.valid_glt, "Georeference (valid_glt)")
        fill = gt.fill_value if isinstance(gt, GeoArray) else None
        return from_engine(
            griddata.georreference(
                to_engine(self.glt),
                np.asarray(gt),
                valid_glt=self.valid_glt,
                fill_value_default=fill,
            )
        )

    def get_config(self) -> dict[str, Any]:
        return {"glt": repr(self.glt), "valid_glt": None}

GeostationaryParallaxCorrect

Bases: Operator

Shift pixels from apparent geostationary view position to nadir.

For each output ground pixel, the operator finds where an elevated target would appear to a geostationary satellite, on the ellipsoid (radiomax.geometry.apparent_position), and samples the input there, treating each input value as located at its pixel centre. target_height_m=0 is an exact identity. Pixels without an apparent position (the target is above the limb or behind it) are filled with gt.fill_value (0 when it is None).

Geo-dependent: requires a georeferenced GeoArray input on an EPSG:4326 grid; plain arrays raise TypeError.

Parameters:

Name Type Description Default
satellite_lon_deg float

Sub-satellite longitude.

required
satellite_height_m float

Satellite height above the equator.

35786023.0
target_height_m float | ndarray | GeoArray

Scalar height, same-grid array, or same-grid GeoArray.

0.0
earth_radius_m float | None

Radius of a spherical Earth; None (the default) is the WGS84 ellipsoid, which the grid's latitudes refer to.

None
method str

"nearest" or "bilinear".

'bilinear'
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class GeostationaryParallaxCorrect(Operator):
    """Shift pixels from apparent geostationary view position to nadir.

    For each output ground pixel, the operator finds where an elevated target
    would appear to a geostationary satellite, on the ellipsoid
    (`radiomax.geometry.apparent_position`), and samples the input there,
    treating each input value as located at its pixel centre.
    ``target_height_m=0`` is an exact identity. Pixels without an apparent
    position (the target is above the limb or behind it) are filled with
    ``gt.fill_value`` (``0`` when it is ``None``).

    Geo-dependent: requires a georeferenced ``GeoArray`` input on an
    EPSG:4326 grid; plain arrays raise ``TypeError``.

    Args:
        satellite_lon_deg: Sub-satellite longitude.
        satellite_height_m: Satellite height above the equator.
        target_height_m: Scalar height, same-grid array, or same-grid GeoArray.
        earth_radius_m: Radius of a spherical Earth; ``None`` (the default)
            is the WGS84 ellipsoid, which the grid's latitudes refer to.
        method: ``"nearest"`` or ``"bilinear"``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # pixels moved by a height-dependent shift, resampled
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        satellite_lon_deg: float,
        satellite_height_m: float = 35_786_023.0,
        target_height_m: float | np.ndarray | GeoArray = 0.0,
        earth_radius_m: float | None = None,
        method: str = "bilinear",
    ) -> None:
        self.satellite_lon_deg = satellite_lon_deg
        self.satellite_height_m = satellite_height_m
        self.target_height_m = target_height_m
        self.earth_radius_m = earth_radius_m
        self.method = method

    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "GeostationaryParallaxCorrect")
        if self.method not in {"nearest", "bilinear"}:
            raise ValueError("method must be 'nearest' or 'bilinear'.")
        reject_geotensor(
            self.target_height_m, "GeostationaryParallaxCorrect (target_height_m)"
        )
        heights = _height_array(self.target_height_m, gt.shape[-2:])
        if np.all(heights == 0):
            return gt
        lons_lats = _lonlat_centres(gt)
        if lons_lats is None:
            raise ValueError("GeostationaryParallaxCorrect requires EPSG:4326 grids.")
        lons, lats = lons_lats
        earth = WGS84 if self.earth_radius_m is None else sphere(self.earth_radius_m)
        satellite = geodetic_to_ecef(
            self.satellite_lon_deg, 0.0, self.satellite_height_m, earth=earth
        )
        apparent_lon, apparent_lat, visible = apparent_position(
            lons, lats, heights, *satellite, earth=earth
        )
        inv = ~affine_of(gt)
        # a hidden pixel has no position; its own is as good, being filled below
        src_cols, src_rows = inv * (
            np.where(visible, apparent_lon, lons),
            np.where(visible, apparent_lat, lats),
        )
        # ``~transform`` yields continuous pixel coordinates in which pixel
        # ``(r, c)`` is centred at ``(r + 0.5, c + 0.5)``; the samplers index
        # ``arr[r]`` at coordinate ``r``, so shift to centre-indexed space.
        sampled = _sample_array(
            np.asarray(gt),
            np.asarray(src_rows) - 0.5,
            np.asarray(src_cols) - 0.5,
            method=self.method,
            fill=gt.fill_value,
        )
        if not np.all(visible):
            sampled = _apply_invalid_fill(sampled, visible, gt.fill_value)
        return wrap_like(gt, sampled)

    def get_config(self) -> dict[str, Any]:
        target: float | str
        if np.isscalar(self.target_height_m):
            target = float(self.target_height_m)
        else:
            target = f"<{type(self.target_height_m).__name__}>"
        return {
            "satellite_lon_deg": self.satellite_lon_deg,
            "satellite_height_m": self.satellite_height_m,
            "target_height_m": target,
            "earth_radius_m": self.earth_radius_m,
            "method": self.method,
        }

Gradient1D

Bases: Operator

Derivative of a gridded field along one dim, NaN- and mask-aware.

along names the dim, and its spacing comes from the carrier:

  • "x" or "y": the transform's column or row step, on a grid whose rows and columns follow the CRS's axes (a rotated or sheared grid raises, naming :class:Reproject; NaN under jax.jit). On a geographic CRS the derivative is per metre of arc on the CRS ellipsoid, eastward along a parallel or northward along a meridian, as :class:Gradient2D's components are;
  • "level": the VerticalAxis values on the level dim, unevenly spaced or not (depth or height in metres, pressure in its units);
  • "time": the TimeAxis stamps, per second.

Masks, nodata and outputs as :class:Gradient2D, on the input's dims; a plain array is differentiated in pixel units along "x" (its last axis) or "y".

Parameters:

Name Type Description Default
along str

"x", "y", "level" or "time".

'x'
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic bool

The dim wraps (along="x" on a global longitude grid).

False

Examples:

>>> import geoops as gz
>>> dtdz = gz.Gradient1D(along="level")(temperature)   # (level, y, x), per metre
>>> dfdt = gz.Gradient1D(along="time")(ssh_series)     # per second
>>> dfdx = gz.geom.gradient_1d(f, dx)                  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Gradient1D(Operator):
    r"""Derivative of a gridded field along one dim, NaN- and mask-aware.

    ``along`` names the dim, and its spacing comes from the carrier:

    - ``"x"`` or ``"y"``: the transform's column or row step, on a grid whose
      rows and columns follow the CRS's axes (a rotated or sheared grid
      raises, naming :class:`Reproject`; ``NaN`` under ``jax.jit``). On a
      geographic CRS the derivative is per metre of arc on the CRS ellipsoid,
      eastward along a parallel or northward along a meridian, as
      :class:`Gradient2D`'s components are;
    - ``"level"``: the ``VerticalAxis`` values on the ``level`` dim, unevenly
      spaced or not (depth or height in metres, pressure in its units);
    - ``"time"``: the ``TimeAxis`` stamps, per second.

    Masks, nodata and outputs as :class:`Gradient2D`, on the input's dims; a
    plain array is differentiated in pixel units along ``"x"`` (its last
    axis) or ``"y"``.

    Args:
        along: ``"x"``, ``"y"``, ``"level"`` or ``"time"``.
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic: The dim wraps (``along="x"`` on a global longitude grid).

    Examples:
        >>> import geoops as gz
        >>> dtdz = gz.Gradient1D(along="level")(temperature)   # (level, y, x), per metre
        >>> dfdt = gz.Gradient1D(along="time")(ssh_series)     # per second
        >>> dfdx = gz.geom.gradient_1d(f, dx)                  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        along: str = "x",
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy, along=along)
        self.along = along
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic = periodic

    def _apply(self, f: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Gradient1D", (f,), mask)
        (field,) = prepared.fields
        return prepared.finish(_along(self, prepared, field, 1, "Gradient1D"))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Gradient2D

Bases: Operator

Diagnostic gradient of a gridded field in map axes, NaN- and mask-aware (OP-O7).

Masks. nan_policy decides what a masked cell costs:

  • "propagate" (default): the plain stencil; a masked cell (non-finite, the carrier's fill, or True in mask) makes every derivative whose stencil reads it NaN, a halo of about accuracy cells;
  • "adaptive": per point, the widest stencil lying wholly on valid data (central, then forward, then backward, at decreasing accuracy), so valid cells next to land keep a one-order-lower estimate and only masked cells are NaN.

The arithmetic is the public L1 primitives, so the same maths is available without a carrier: :func:geoops.geom.gradient_2d / :func:geoops.geom.adaptive_gradient_2d over :func:geoops.geom.difference / :func:geoops.geom.adaptive_difference, whose stencils come from :func:geoops.geom.difference_offsets and :func:geoops.geom.difference_coeffs.

Geometry, derived from the carrier. The row and column derivatives map to the CRS's x and y through the transform's Jacobian (:math:x = a\,j + b\,i + c,\; y = d\,j + e\,i + f),

.. math::

\begin{pmatrix} \partial_x f \\ \partial_y f \end{pmatrix}
= \frac{1}{ae - bd}
  \begin{pmatrix} e & -d \\ -b & a \end{pmatrix}
  \begin{pmatrix} \partial_j f \\ \partial_i f \end{pmatrix},

exact for a linear field on north-up, flipped and rotated grids. On a geographic CRS its angular unit (degrees, grads) becomes metres on the CRS's ellipsoid at each pixel's latitude :math:\varphi: :math:\partial_{\mathrm{north}} f = \partial_\varphi f / (M(\varphi)\,\pi/180), :math:\partial_{\mathrm{east}} f = \partial_\lambda f / (N(\varphi)\cos\varphi\,\pi/180), with :math:M, :math:N the meridional and prime-vertical radii.

The result gains a component dim just before y x holding (∂f/∂y, ∂f/∂x), per CRS unit (per metre on a geographic CRS), and declares fill_value=NaN. A plain array is differentiated in pixel units, rows then columns. A diagnostic: model-grade calculus on staggered grids stays in finitevolX. A geometry operator, so a DataArray is refused: lift it with xrops.lift, or call the L1 primitives with coordinate spacings.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils (the centred one is one order higher); 1 is numpy.gradient's scheme.

1
nan_policy str

"propagate" or "adaptive" (above).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> grad = gz.Gradient2D()(ssh_map)                 # (component, y, x)
>>> grad = gz.Gradient2D(nan_policy="adaptive")(ssh_map, land)  # keeps the coast
>>> step = jax.jit(gz.Gradient2D())                 # one trace across transforms
>>> d_y, d_x = gz.geom.adaptive_gradient_2d(ssh, dy, dx, mask=land)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Gradient2D(Operator):
    r"""Diagnostic gradient of a gridded field in map axes, NaN- and mask-aware (OP-O7).

    **Masks.** ``nan_policy`` decides what a masked cell costs:

    - ``"propagate"`` (default): the plain stencil; a masked cell (non-finite,
      the carrier's fill, or ``True`` in ``mask``) makes every derivative
      whose stencil reads it ``NaN``, a halo of about ``accuracy`` cells;
    - ``"adaptive"``: per point, the widest stencil lying wholly on valid
      data (central, then forward, then backward, at decreasing accuracy),
      so valid cells next to land keep a one-order-lower estimate and only
      masked cells are ``NaN``.

    The arithmetic is the public L1 primitives, so the same maths is
    available without a carrier: :func:`geoops.geom.gradient_2d` /
    :func:`geoops.geom.adaptive_gradient_2d` over :func:`geoops.geom.difference`
    / :func:`geoops.geom.adaptive_difference`, whose stencils come from
    :func:`geoops.geom.difference_offsets` and :func:`geoops.geom.difference_coeffs`.

    **Geometry**, derived from the carrier. The row and column derivatives
    map to the CRS's ``x`` and ``y`` through the transform's Jacobian
    (:math:`x = a\,j + b\,i + c,\; y = d\,j + e\,i + f`),

    .. math::

        \begin{pmatrix} \partial_x f \\ \partial_y f \end{pmatrix}
        = \frac{1}{ae - bd}
          \begin{pmatrix} e & -d \\ -b & a \end{pmatrix}
          \begin{pmatrix} \partial_j f \\ \partial_i f \end{pmatrix},

    exact for a linear field on north-up, flipped and rotated grids. On a
    geographic CRS its angular unit (degrees, grads) becomes metres on the CRS's ellipsoid at each
    pixel's latitude :math:`\varphi`:
    :math:`\partial_{\mathrm{north}} f = \partial_\varphi f / (M(\varphi)\,\pi/180)`,
    :math:`\partial_{\mathrm{east}} f = \partial_\lambda f / (N(\varphi)\cos\varphi\,\pi/180)`,
    with :math:`M`, :math:`N` the meridional and prime-vertical radii.

    The result gains a ``component`` dim just before ``y x`` holding
    ``(∂f/∂y, ∂f/∂x)``, per CRS unit (per metre on a geographic CRS), and
    declares ``fill_value=NaN``. A plain array is differentiated in pixel
    units, rows then columns. A diagnostic: model-grade calculus on
    staggered grids stays in finitevolX. A geometry operator, so a
    ``DataArray`` is refused: lift it with ``xrops.lift``, or call the L1
    primitives with coordinate spacings.

    Args:
        accuracy: Accuracy order of the one-sided stencils (the centred one
            is one order higher); ``1`` is ``numpy.gradient``'s scheme.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (above).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> grad = gz.Gradient2D()(ssh_map)                 # (component, y, x)
        >>> grad = gz.Gradient2D(nan_policy="adaptive")(ssh_map, land)  # keeps the coast
        >>> step = jax.jit(gz.Gradient2D())                 # one trace across transforms
        >>> d_y, d_x = gz.geom.adaptive_gradient_2d(ssh, dy, dx, mask=land)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        if nan_policy not in ("propagate", "adaptive"):
            raise ValueError(
                f"nan_policy must be 'propagate' or 'adaptive'; got {nan_policy!r}"
            )
        if accuracy < 1:
            raise ValueError(f"accuracy must be at least 1; got {accuracy}")
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, gt: Any, mask: Any = None) -> Any:
        reject_geotensor(gt, "Gradient2D")
        if type(gt).__module__.startswith("xarray."):
            raise TypeError(
                "Gradient2D is a geometry operator and takes a GeoArray: lift it "
                "over a DataArray cube with xrops.lift(Gradient2D(), dim=...), or "
                "call geoops.geom.gradient_2d / adaptive_gradient with coordinate "
                "spacings."
            )
        if mask is not None and isinstance(gt, GeoArray) and isinstance(mask, GeoArray):
            # geoarray's own grid check: exact, and deferred to run time under jit
            try:
                get_adapter(gt).check_compatible(gt, mask)
            except GridMismatchError as exc:
                raise GridMismatchError(
                    f"Gradient2D: the mask is not on the field's pixel grid ({exc})"
                ) from exc
        if not isinstance(gt, GeoArray):
            # a plain array (NumPy or JAX): pixel units, on its own backend
            field = as_float(gt if hasattr(gt, "dtype") else np.asarray(gt))
            xp = array_namespace(field)
            grad = self._pixel_gradient(field, xp, _mask_data(mask, xp))
            return xp.moveaxis(grad, 0, -3)
        if gt.batch_dims:
            raise ValueError(
                f"Gradient2D: the carrier is batched over {gt.batch_dims} (one "
                "transform per item); map it per item with "
                f"geoarray.map_over(x, Gradient2D(...), {gt.batch_dims[0]!r})."
            )
        xp = gt.xp
        data = as_float(gt.data)
        # geoops' pixel nodata rule (any invalid band), on the carrier's backend
        invalid = invalid_pixel_mask(gt, mask=_aligned_mask(mask, gt, xp))
        mask_data = invalid
        field = xp.where(invalid, xp.nan, data)
        d_row, d_col = self._pixel_gradient(field, xp, mask_data)
        d_y, d_x = _map_axes(gt, d_row, d_col)
        # an invalid input pixel has no derivative, whatever its neighbours hold
        grad = xp.where(invalid[..., None, :, :], xp.nan, xp.stack([d_y, d_x], axis=-3))
        dims = (*gt.dims[:-2], "component", *gt.dims[-2:])
        return rewrap_dims(gt, grad, dims, fill_value=np.nan)

    def _pixel_gradient(self, field: Any, xp: Any, mask: Any) -> Any:
        """``(∂f/∂i, ∂f/∂j)`` per pixel step, through the L1 primitives."""
        if self.nan_policy == "adaptive":
            return adaptive_gradient_2d(
                field, mask=mask, accuracy=self.accuracy, periodic_x=self.periodic_x
            )
        if mask is not None:
            field = xp.where(mask, xp.nan, field)
        out = gradient_2d(field, accuracy=self.accuracy, periodic_x=self.periodic_x)
        if mask is not None:
            out = xp.where(mask, xp.nan, out)
        return out

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

Gradient3D

Bases: Operator

Gradient of a gridded field on vertical levels, NaN- and mask-aware.

(∂f/∂z, ∂f/∂y, ∂f/∂x): the horizontal components as :class:Gradient2D (map axes, the ellipsoid on a geographic CRS), and the vertical one along the carrier's level dim with the spacing of its VerticalAxis, unevenly spaced levels included. z is the level coordinate as stored (depth, height or pressure), so ∂f/∂z is per unit of it. On a geographic CRS this is the thin-shell form: the horizontal metric does not change with height.

The result gains a component dim before y x holding (∂f/∂z, ∂f/∂y, ∂f/∂x), with fill_value=NaN. A plain array is differentiated in pixel units over its last three axes.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> grad = gz.Gradient3D()(temperature)          # (level, component, y, x)
>>> grad = gz.Gradient3D(nan_policy="adaptive")(temperature, seabed)
>>> d_z, d_y, d_x = gz.geom.gradient_3d(t, dz, dy, dx, z=depth)  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Gradient3D(Operator):
    r"""Gradient of a gridded field on vertical levels, NaN- and mask-aware.

    ``(∂f/∂z, ∂f/∂y, ∂f/∂x)``: the horizontal components as
    :class:`Gradient2D` (map axes, the ellipsoid on a geographic CRS), and
    the vertical one along the carrier's ``level`` dim with the spacing of its
    ``VerticalAxis``, unevenly spaced levels included. ``z`` is the level
    coordinate as stored (depth, height or pressure), so ``∂f/∂z`` is per
    unit of it. On a geographic CRS this is the thin-shell form: the
    horizontal metric does not change with height.

    The result gains a ``component`` dim before ``y x`` holding
    ``(∂f/∂z, ∂f/∂y, ∂f/∂x)``, with ``fill_value=NaN``. A plain array is
    differentiated in pixel units over its last three axes.

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> grad = gz.Gradient3D()(temperature)          # (level, component, y, x)
        >>> grad = gz.Gradient3D(nan_policy="adaptive")(temperature, seabed)
        >>> d_z, d_y, d_x = gz.geom.gradient_3d(t, dz, dy, dx, z=depth)  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"level", "space"}, reach=1)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 1)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, f: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Gradient3D", (f,), mask)
        (field,) = prepared.fields
        d_z = _vertical(self, prepared, field, 1, "Gradient3D")
        d_y, d_x = _map_gradient(self, prepared, field)
        return prepared.finish_components((d_z, d_y, d_x))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 1)

InterpAt

Bases: Operator

H(x): a grid read at the positions of points, as an operator.

geoops.geom.interp_at in a pipeline: InterpAt()(grid, points) returns a geoarray.GeoPoints with the grid's values at the points (bilinear or nearest), valid=False and NaN off the grid or on nodata, and 0 on padded points so a masked cost stays finite. The points are the second positional input, so a pipekit_ops.Graph wires them from their own Input. Unlike the function, the operator never moves a NumPy grid to JAX for JAX points: pipekit refuses mixed backends, so call grid.to_jax() first.

The declared coupling (spatial, reach 1) is bilinear's; "nearest" reads one pixel, so for it the declaration is an upper bound.

plan(grid, points) returns the functax plan H the operator reads with: H(y) on the grid flattened to (..., N) gives the values at the points, and H.adjoint(r) (or H.operator().transpose()) sends point residuals back onto the grid, Hᵀ r. The operator builds a plan once per (grid, points) on concrete inputs and reuses it.

Parameters:

Name Type Description Default
method Literal['bilinear', 'nearest']

"bilinear" (blends the four pixels around each point) or "nearest".

'bilinear'
along str

The dim a per-point frame index selects; frame is the optional third input.

'time'
Example

import numpy as np from geoarray import GeoArray, GeoPoints import geoops as gz t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0) g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x") p = GeoPoints(np.zeros(1), xy=np.array([[1.0, 3.0]]), dims="obs", crs=None) gz.InterpAt()(g, p).data.tolist() [2.5]

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class InterpAt(Operator):
    """H(x): a grid read at the positions of points, as an operator.

    `geoops.geom.interp_at` in a pipeline: ``InterpAt()(grid, points)``
    returns a `geoarray.GeoPoints` with the grid's values at the points
    (bilinear or nearest), ``valid=False`` and NaN off the grid or on
    nodata, and 0 on padded points so a masked cost stays finite. The
    points are the second positional input, so a `pipekit_ops.Graph` wires
    them from their own `Input`. Unlike the function, the operator never
    moves a NumPy grid to JAX for JAX points: pipekit refuses mixed
    backends, so call ``grid.to_jax()`` first.

    The declared coupling (spatial, reach 1) is bilinear's; ``"nearest"``
    reads one pixel, so for it the declaration is an upper bound.

    ``plan(grid, points)`` returns the functax plan H the operator reads
    with: ``H(y)`` on the grid flattened to ``(..., N)`` gives the values at
    the points, and ``H.adjoint(r)`` (or ``H.operator().transpose()``) sends
    point residuals back onto the grid, Hᵀ r. The operator builds a plan
    once per (grid, points) on concrete inputs and reuses it.

    Args:
        method: ``"bilinear"`` (blends the four pixels around each point)
            or ``"nearest"``.
        along: The dim a per-point ``frame`` index selects; ``frame`` is
            the optional third input.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray, GeoPoints
        >>> import geoops as gz
        >>> t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0)
        >>> g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x")
        >>> p = GeoPoints(np.zeros(1), xy=np.array([[1.0, 3.0]]), dims="obs", crs=None)
        >>> gz.InterpAt()(g, p).data.tolist()
        [2.5]
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    # each value blends the 2 x 2 pixels around its point
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=1, kind="conversion"
    )
    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        method: Literal["bilinear", "nearest"] = "bilinear",
        along: str = "time",
    ) -> None:
        if method not in ("bilinear", "nearest"):
            raise ValueError(
                f"InterpAt.method is 'bilinear' or 'nearest', got {method!r}"
            )
        self.method = method
        self.along = along
        # runtime only: the plans of the last few (grid, points), not config
        self._plans: OrderedDict[tuple[Any, ...], Any] = OrderedDict()

    _MAX_PLANS: ClassVar[int] = 16

    def plan(self, grid: GeoArray, points: GeoPoints) -> Any:
        """H, the functax plan this operator reads ``grid`` at ``points`` with.

        f̂ = H y for y the grid flattened row-major to ``(..., N)``, N = H·W,
        with NaN at points off the grid; ``plan.adjoint(r)`` is Hᵀ r, and
        ``plan.operator()`` is H as an (M, N) lineax operator (its
        ``transpose()`` is (N, M)). Padded or non-finite points read
        nothing. The nodata rule is the operator's, not the plan's: calling
        the operator also masks points that read nodata.

        Built once per (grid, points) and cached (the 16 most recent) when
        both are concrete and it is built outside a trace; under ``jit`` it
        is built in the trace and not kept. A plan
        on a NumPy grid is built in JAX's 64-bit mode and holds float64
        weights, so apply it with ``jax_enable_x64`` on.

        Args:
            grid: The carrier ``(..., y, x)``; only its grid matters.
            points: Where to read, in ``grid``'s CRS.

        Returns:
            A ``functax.interp.Plan`` with M = ``points.size`` rows.

        Raises:
            ImportError: functax's plans are missing (the ``[interp]`` extra).

        Example:
            >>> import numpy as np
            >>> from geoarray import GeoArray, GeoPoints
            >>> import geoops as gz
            >>> t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0)
            >>> g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x")
            >>> p = GeoPoints(np.zeros(1), xy=np.array([[1.0, 3.0]]), dims="obs", crs=None)
            >>> H = gz.InterpAt().plan(g, p)  # (1, 16)
            >>> np.asarray(H(g.data.reshape(-1))).tolist()  # doctest: +SKIP
            [2.5]
        """
        self._check_inputs(grid, points)
        check_args(grid, points, self.method)
        interp = functax_module("interp", feature="geoops.geom.InterpAt.plan")
        import jax  # functax_module has checked that the [interp] extra is in

        # the key reads the positions and validity on the host: concrete only
        inputs = (grid.transform, points.xy, points.valid)
        concrete = not any(is_traced(leaf) for leaf in inputs)
        key = self._plan_key(grid, points) if concrete else None
        if key is not None and key in self._plans:
            self._plans.move_to_end(key)
            return self._plans[key]
        host = grid.backend == "numpy" and backend_of(points.xy) != "jax"
        with x64("geoops.geom.InterpAt.plan") if host else nullcontext():
            plan = plan_at(interp, grid, points, self.method)
        # inside a trace even concrete inputs give a plan of tracers, which
        # must not outlive it: keep only plans whose leaves are all concrete
        leaves = jax.tree_util.tree_leaves(plan)
        if key is not None and not any(is_traced(leaf) for leaf in leaves):
            self._plans[key] = plan
            while len(self._plans) > self._MAX_PLANS:
                self._plans.popitem(last=False)
        return plan

    def _plan_key(self, grid: GeoArray, points: GeoPoints) -> tuple[Any, ...]:
        """What a plan depends on: the grid and the positions and validity."""
        xy = np.asarray(points.xy)
        valid = None if points.valid is None else np.asarray(points.valid).tobytes()
        return (grid.grid, xy.shape, xy.dtype.str, xy.tobytes(), valid)

    @staticmethod
    def _check_inputs(grid: Any, points: Any) -> None:
        require_geoarray(grid, "InterpAt")
        reject_geotensor(points, "InterpAt")
        if not isinstance(points, GeoPoints):
            raise TypeError(
                f"InterpAt reads a grid at a geoarray.GeoPoints, "
                f"got {type(points).__name__}"
            )

    def _apply(self, grid: GeoArray, points: GeoPoints, frame: Any = None) -> GeoPoints:
        plan = self.plan(grid, points)
        return interp_with_plan(
            grid, points, self.method, frame=frame, along=self.along, plan=plan
        )

plan(grid, points)

H, the functax plan this operator reads grid at points with.

f̂ = H y for y the grid flattened row-major to (..., N), N = H·W, with NaN at points off the grid; plan.adjoint(r) is Hᵀ r, and plan.operator() is H as an (M, N) lineax operator (its transpose() is (N, M)). Padded or non-finite points read nothing. The nodata rule is the operator's, not the plan's: calling the operator also masks points that read nodata.

Built once per (grid, points) and cached (the 16 most recent) when both are concrete and it is built outside a trace; under jit it is built in the trace and not kept. A plan on a NumPy grid is built in JAX's 64-bit mode and holds float64 weights, so apply it with jax_enable_x64 on.

Parameters:

Name Type Description Default
grid GeoArray

The carrier (..., y, x); only its grid matters.

required
points GeoPoints

Where to read, in grid's CRS.

required

Returns:

Type Description
Any

A functax.interp.Plan with M = points.size rows.

Raises:

Type Description
ImportError

functax's plans are missing (the [interp] extra).

Example

import numpy as np from geoarray import GeoArray, GeoPoints import geoops as gz t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0) g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x") p = GeoPoints(np.zeros(1), xy=np.array([[1.0, 3.0]]), dims="obs", crs=None) H = gz.InterpAt().plan(g, p) # (1, 16) np.asarray(H(g.data.reshape(-1))).tolist() # doctest: +SKIP [2.5]

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def plan(self, grid: GeoArray, points: GeoPoints) -> Any:
    """H, the functax plan this operator reads ``grid`` at ``points`` with.

    f̂ = H y for y the grid flattened row-major to ``(..., N)``, N = H·W,
    with NaN at points off the grid; ``plan.adjoint(r)`` is Hᵀ r, and
    ``plan.operator()`` is H as an (M, N) lineax operator (its
    ``transpose()`` is (N, M)). Padded or non-finite points read
    nothing. The nodata rule is the operator's, not the plan's: calling
    the operator also masks points that read nodata.

    Built once per (grid, points) and cached (the 16 most recent) when
    both are concrete and it is built outside a trace; under ``jit`` it
    is built in the trace and not kept. A plan
    on a NumPy grid is built in JAX's 64-bit mode and holds float64
    weights, so apply it with ``jax_enable_x64`` on.

    Args:
        grid: The carrier ``(..., y, x)``; only its grid matters.
        points: Where to read, in ``grid``'s CRS.

    Returns:
        A ``functax.interp.Plan`` with M = ``points.size`` rows.

    Raises:
        ImportError: functax's plans are missing (the ``[interp]`` extra).

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray, GeoPoints
        >>> import geoops as gz
        >>> t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0)
        >>> g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x")
        >>> p = GeoPoints(np.zeros(1), xy=np.array([[1.0, 3.0]]), dims="obs", crs=None)
        >>> H = gz.InterpAt().plan(g, p)  # (1, 16)
        >>> np.asarray(H(g.data.reshape(-1))).tolist()  # doctest: +SKIP
        [2.5]
    """
    self._check_inputs(grid, points)
    check_args(grid, points, self.method)
    interp = functax_module("interp", feature="geoops.geom.InterpAt.plan")
    import jax  # functax_module has checked that the [interp] extra is in

    # the key reads the positions and validity on the host: concrete only
    inputs = (grid.transform, points.xy, points.valid)
    concrete = not any(is_traced(leaf) for leaf in inputs)
    key = self._plan_key(grid, points) if concrete else None
    if key is not None and key in self._plans:
        self._plans.move_to_end(key)
        return self._plans[key]
    host = grid.backend == "numpy" and backend_of(points.xy) != "jax"
    with x64("geoops.geom.InterpAt.plan") if host else nullcontext():
        plan = plan_at(interp, grid, points, self.method)
    # inside a trace even concrete inputs give a plan of tracers, which
    # must not outlive it: keep only plans whose leaves are all concrete
    leaves = jax.tree_util.tree_leaves(plan)
    if key is not None and not any(is_traced(leaf) for leaf in leaves):
        self._plans[key] = plan
        while len(self._plans) > self._MAX_PLANS:
            self._plans.popitem(last=False)
    return plan

Laplacian1D

Bases: Operator

Second derivative of a gridded field along one dim, NaN- and mask-aware.

:math:\partial^2 f / \partial s^2 with second-derivative stencils; along, spacing, masks and outputs as :class:Gradient1D. On a geographic CRS it is per square metre of arc: along a parallel :math:f_{\lambda\lambda} / (N \cos\varphi)^2, along a meridian :math:f_{\varphi\varphi} / M^2 - M' f_\varphi / M^3 (the meridian's radius of curvature changes with latitude).

Parameters:

Name Type Description Default
along str

"x", "y", "level" or "time".

'x'
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic bool

The dim wraps.

False

Examples:

>>> import geoops as gz
>>> curvature = gz.Laplacian1D(along="level")(temperature)  # per m²
>>> d2f = gz.geom.laplacian_1d(f, coords=depth, axis=-3)    # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Laplacian1D(Operator):
    r"""Second derivative of a gridded field along one dim, NaN- and mask-aware.

    :math:`\partial^2 f / \partial s^2` with second-derivative stencils;
    ``along``, spacing, masks and outputs as :class:`Gradient1D`. On a
    geographic CRS it is per square metre of arc: along a parallel
    :math:`f_{\lambda\lambda} / (N \cos\varphi)^2`, along a meridian
    :math:`f_{\varphi\varphi} / M^2 - M' f_\varphi / M^3` (the meridian's
    radius of curvature changes with latitude).

    Args:
        along: ``"x"``, ``"y"``, ``"level"`` or ``"time"``.
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic: The dim wraps.

    Examples:
        >>> import geoops as gz
        >>> curvature = gz.Laplacian1D(along="level")(temperature)  # per m²
        >>> d2f = gz.geom.laplacian_1d(f, coords=depth, axis=-3)    # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=2)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 2)

    def __init__(
        self,
        *,
        along: str = "x",
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy, along=along)
        self.along = along
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic = periodic

    def _apply(self, f: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Laplacian1D", (f,), mask)
        (field,) = prepared.fields
        return prepared.finish(_along(self, prepared, field, 2, "Laplacian1D"))

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 2)

Laplacian2D

Bases: Operator

Laplacian of a gridded field in 2-D map axes, NaN- and mask-aware.

.. math::

\nabla^2 f = \frac{\partial^2 f}{\partial x^2}
           + \frac{\partial^2 f}{\partial y^2}

Second-derivative stencils (derivative=2) along the pixel axes. The Laplacian is rotation-invariant, so on a grid with perpendicular axes (north-up, flipped or rotated) it is :math:f_{jj} / |\mathbf{a}_j|^2 + f_{ii} / |\mathbf{a}_i|^2, with :math:\mathbf{a}_j = (a, d) and :math:\mathbf{a}_i = (b, e) the column and row steps; a quadratic stays exact up to the edges. On a geographic CRS (rows and columns along latitude and longitude), with the CRS ellipsoid's radii :math:M(\varphi) and :math:N(\varphi),

.. math::

\nabla^2 f = \frac{1}{N^2 \cos^2\varphi}
             \frac{\partial^2 f}{\partial \lambda^2}
           + \frac{1}{M^2} \frac{\partial^2 f}{\partial \varphi^2}
           + \frac{1}{M N \cos\varphi}
             \frac{d}{d\varphi}\!\left(\frac{N \cos\varphi}{M}\right)
             \frac{\partial f}{\partial \varphi},

which on a sphere has the last term :math:-\tan\varphi / R^2\, \partial f / \partial \varphi. A sheared grid (or a rotated geographic one) raises, naming :class:Reproject; under jax.jit, where the transform is traced, such a grid gives NaN instead. Units per CRS unit squared (per square metre on a geographic CRS); masks, nodata and carriers as :class:Gradient2D.

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> lap = gz.Laplacian2D()(ssh_map)                          # (y, x)
>>> lap = gz.Laplacian2D(nan_policy="adaptive")(ssh_map, land)
>>> lap = gz.geom.laplacian_2d(ssh, dy, dx)                  # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Laplacian2D(Operator):
    r"""Laplacian of a gridded field in 2-D map axes, NaN- and mask-aware.

    .. math::

        \nabla^2 f = \frac{\partial^2 f}{\partial x^2}
                   + \frac{\partial^2 f}{\partial y^2}

    Second-derivative stencils (``derivative=2``) along the pixel axes. The
    Laplacian is rotation-invariant, so on a grid with perpendicular axes
    (north-up, flipped or rotated) it is
    :math:`f_{jj} / |\mathbf{a}_j|^2 + f_{ii} / |\mathbf{a}_i|^2`, with
    :math:`\mathbf{a}_j = (a, d)` and :math:`\mathbf{a}_i = (b, e)` the
    column and row steps; a quadratic stays exact up to the edges. On a
    geographic CRS (rows and columns along latitude and longitude), with the
    CRS ellipsoid's radii :math:`M(\varphi)` and :math:`N(\varphi)`,

    .. math::

        \nabla^2 f = \frac{1}{N^2 \cos^2\varphi}
                     \frac{\partial^2 f}{\partial \lambda^2}
                   + \frac{1}{M^2} \frac{\partial^2 f}{\partial \varphi^2}
                   + \frac{1}{M N \cos\varphi}
                     \frac{d}{d\varphi}\!\left(\frac{N \cos\varphi}{M}\right)
                     \frac{\partial f}{\partial \varphi},

    which on a sphere has the last term :math:`-\tan\varphi / R^2\,
    \partial f / \partial \varphi`. A sheared grid (or a rotated geographic
    one) raises, naming :class:`Reproject`; under ``jax.jit``, where the
    transform is traced, such a grid gives ``NaN`` instead. Units per CRS
    unit squared (per square metre on a geographic CRS); masks, nodata and
    carriers as :class:`Gradient2D`.

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> lap = gz.Laplacian2D()(ssh_map)                          # (y, x)
        >>> lap = gz.Laplacian2D(nan_policy="adaptive")(ssh_map, land)
        >>> lap = gz.geom.laplacian_2d(ssh, dy, dx)                  # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=2)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 2)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, f: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Laplacian2D", (f,), mask)
        (field,) = prepared.fields
        return prepared.finish(
            _horizontal_laplacian(self, prepared, field, "Laplacian2D")
        )

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 2)

Laplacian3D

Bases: Operator

Laplacian of a gridded field on vertical levels, NaN- and mask-aware.

.. math::

\nabla^2 f = \nabla_h^2 f + \frac{\partial^2 f}{\partial z^2}

The horizontal part as :class:Laplacian2D (its grid conditions and the ellipsoid's metric, thin-shell), plus the second derivative along the level dim with its VerticalAxis spacing, unevenly spaced levels included. Units: the horizontal part per CRS unit squared (per square metre on a geographic CRS), the vertical one per level unit squared, so mix them only where those agree (heights or depths in metres).

Parameters:

Name Type Description Default
accuracy int

Accuracy order of the one-sided stencils.

1
nan_policy str

"propagate" or "adaptive" (see :class:Gradient2D).

'propagate'
periodic_x bool

The columns wrap, for a global longitude grid.

False

Examples:

>>> import geoops as gz
>>> lap = gz.Laplacian3D()(temperature)                  # (level, y, x)
>>> lap = gz.geom.laplacian_3d(t, dz, dy, dx, z=depth)    # arrays only
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Laplacian3D(Operator):
    r"""Laplacian of a gridded field on vertical levels, NaN- and mask-aware.

    .. math::

        \nabla^2 f = \nabla_h^2 f + \frac{\partial^2 f}{\partial z^2}

    The horizontal part as :class:`Laplacian2D` (its grid conditions and the
    ellipsoid's metric, thin-shell), plus the second derivative along the
    ``level`` dim with its ``VerticalAxis`` spacing, unevenly spaced levels
    included. Units: the horizontal part per CRS unit squared (per square
    metre on a geographic CRS), the vertical one per level unit squared, so
    mix them only where those agree (heights or depths in metres).

    Args:
        accuracy: Accuracy order of the one-sided stencils.
        nan_policy: ``"propagate"`` or ``"adaptive"`` (see :class:`Gradient2D`).
        periodic_x: The columns wrap, for a global longitude grid.

    Examples:
        >>> import geoops as gz
        >>> lap = gz.Laplacian3D()(temperature)                  # (level, y, x)
        >>> lap = gz.geom.laplacian_3d(t, dz, dy, dx, z=depth)    # arrays only
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(couples={"level", "space"}, reach=2)

    def spatial_reach(self) -> int | None:
        """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
        return _calculus_reach(self, 2)

    def __init__(
        self,
        *,
        accuracy: int = 1,
        nan_policy: str = "propagate",
        periodic_x: bool = False,
    ) -> None:
        _check_calculus(accuracy, nan_policy)
        self.accuracy = accuracy
        self.nan_policy = nan_policy
        self.periodic_x = periodic_x

    def _apply(self, f: Any, mask: Any = None) -> Any:
        prepared = _calculus_inputs("Laplacian3D", (f,), mask)
        (field,) = prepared.fields
        horizontal = _horizontal_laplacian(self, prepared, field, "Laplacian3D")
        return prepared.finish(
            horizontal + _vertical(self, prepared, field, 2, "Laplacian3D")
        )

spatial_reach()

The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
def spatial_reach(self) -> int | None:
    """The spatial reach in pixels: the widest stencil the mask-aware policy may use; None when x is periodic."""
    return _calculus_reach(self, 2)

Mosaic

Bases: Operator

Mosaic multiple GeoArrays onto a single grid.

For method="first" this is a thin wrapper around :func:georeader.mosaic.spatial_mosaic: rasters are processed in order and the first valid pixel wins. For all other methods the frame is the union of the input bounds on the first raster's pixel grid (its CRS / dtype), every input is reprojected onto that frame (its fill sentinel becoming NaN) and the per-pixel reduction is applied:

.. math::

\hat{x}_{ij} \;=\; \mathrm{agg}\!\left(
    \{ x^{(k)}_{ij} \;|\; x^{(k)}_{ij} \neq \text{fill} \}
\right)

with agg chosen from mean, median, max, min. Pixels no input covers get the first raster's fill_value; when that is None they get NaN (float dtypes) or 0 (integer dtypes), and "first" also takes this stacked path because spatial_mosaic cannot pad fill-less inputs.

Geo-dependent: every input must be a georeferenced GeoArray (transform + CRS drive the mosaic frame); plain arrays raise TypeError.

Parameters:

Name Type Description Default
method str

"first" (default), "mean" / "average", "median", "max", "min".

'first'
resampling str

Resampling mode used for reprojection onto the mosaic frame.

'bilinear'

Examples:

>>> import geoops as gz
>>> # Median-composite a stack of overlapping S2 scenes.
>>> composite = gz.geom.Mosaic(method="median")(s2_scene_list)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Mosaic(Operator):
    r"""Mosaic multiple `GeoArray`s onto a single grid.

    For ``method="first"`` this is a thin wrapper around
    :func:`georeader.mosaic.spatial_mosaic`: rasters are processed in
    order and the first valid pixel wins. For all other methods the
    *frame* is the union of the input bounds on the first raster's pixel
    grid (its CRS / dtype), every input is reprojected onto that frame
    (its fill sentinel becoming NaN) and the per-pixel reduction is
    applied:

    .. math::

        \hat{x}_{ij} \;=\; \mathrm{agg}\!\left(
            \{ x^{(k)}_{ij} \;|\; x^{(k)}_{ij} \neq \text{fill} \}
        \right)

    with ``agg`` chosen from ``mean``, ``median``, ``max``, ``min``.
    Pixels no input covers get the first raster's ``fill_value``;
    when that is ``None`` they get NaN (float dtypes) or ``0`` (integer
    dtypes), and ``"first"`` also takes this stacked path because
    ``spatial_mosaic`` cannot pad fill-less inputs.

    Geo-dependent: every input must be a georeferenced ``GeoArray``
    (transform + CRS drive the mosaic frame); plain arrays raise
    ``TypeError``.

    Args:
        method: ``"first"`` (default), ``"mean"`` / ``"average"``,
            ``"median"``, ``"max"``, ``"min"``.
        resampling: Resampling mode used for reprojection onto the
            mosaic frame.

    Examples:
        >>> import geoops as gz
        >>> # Median-composite a stack of overlapping S2 scenes.
        >>> composite = gz.geom.Mosaic(method="median")(s2_scene_list)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # several rasters resampled onto one grid; the first valid value wins
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space", "time"},
        effects={"space": "regrid", "time": "reduce"},
        reach=None,
    )

    _REDUCERS: ClassVar[dict[str, Any]] = {
        "first": _nan_first,
        "mean": np.nanmean,
        "average": np.nanmean,
        "median": np.nanmedian,
        "max": np.nanmax,
        "min": np.nanmin,
    }

    def __init__(self, *, method: str = "first", resampling: str = "bilinear") -> None:
        self.method = method
        self.resampling = resampling

    def _apply(self, gts: list[GeoArray]) -> GeoArray:
        mosaic = optional_name(
            "georeader",
            "mosaic",
            "sensors",
            feature="geoops.geom.Mosaic",
        )
        read = optional_name(
            "georeader", "read", "sensors", feature="geoops.geom.Mosaic"
        )
        _require_carrier_list(gts, "Mosaic", "rasters")
        for gt in gts:
            require_geoarray(gt, "Mosaic")
        if self.method == "first" and all(gt.fill_value is not None for gt in gts):
            return adopt_attrs(
                gts[0],
                mosaic.spatial_mosaic(
                    [to_engine(gt) for gt in gts],
                    resampling=resolve_resampling(self.resampling),
                ),
            )
        # ``spatial_mosaic`` cannot pad inputs that carry no fill value, so
        # ``"first"`` over such inputs goes through the stacked path below.
        if self.method not in self._REDUCERS:
            raise ValueError(
                "method must be 'first', 'mean', 'median', 'max', or 'min'."
            )
        first = gts[0]
        transform, window = _mosaic_frame(gts)
        arrays = [
            np.asarray(
                read.read_reproject(
                    to_engine(_nan_masked(gt)),
                    dst_crs=first.crs,
                    dst_transform=transform,
                    window_out=window,
                    resampling=resolve_resampling(self.resampling),
                    dst_nodata=np.nan,
                )
            )
            for gt in gts
        ]
        stack = np.stack(arrays, axis=0)
        # Pixels no input covers are all-NaN slices; numpy warns about
        # them, but they are expected here and refilled below.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            values = self._REDUCERS[self.method](stack, axis=0)
        fill = first.fill_value
        if fill is None:
            fill = np.nan if np.issubdtype(first.dtype, np.floating) else 0
        values = np.where(np.isnan(values), fill, values)
        return wrap_like(
            first,
            values.astype(first.dtype, copy=False),
            transform=transform,
            fill_value=fill,
        )

OpticalFlowILK

Bases: OpticalFlowTVL1

Dense per-pixel displacement via iterative Lucas-Kanade optical flow.

Same contract as :class:OpticalFlowTVL1 (both carriers supported), delegating to :func:skimage.registration.optical_flow_ilk.

Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class OpticalFlowILK(OpticalFlowTVL1):
    """Dense per-pixel displacement via iterative Lucas-Kanade optical flow.

    Same contract as :class:`OpticalFlowTVL1` (both carriers supported),
    delegating to :func:`skimage.registration.optical_flow_ilk`.
    """

    def _apply(
        self, gt: GeoArray | np.ndarray, reference: GeoArray | np.ndarray
    ) -> GeoArray | np.ndarray:
        optical_flow_ilk = optional_name(
            "skimage.registration",
            "optical_flow_ilk",
            "morph",
            feature="geoops.geom.OpticalFlowILK",
        )
        name = type(self).__name__
        require_grid_match(gt, reference, name, names=("moving", "reference"))
        flow = np.asarray(
            optical_flow_ilk(
                _registration_band(
                    np.asarray(reference), self.band, f"{name} reference"
                ),
                _registration_band(np.asarray(gt), self.band, name),
            )
        )
        return _wrap_flow(gt, reference, flow)

OpticalFlowTVL1

Bases: Operator

Dense per-pixel displacement via TV-L1 optical flow.

Wraps :func:skimage.registration.optical_flow_tvl1 on the selected registration band. The output is a (2, H, W) displacement field ([dy, dx] per pixel) on the input's carrier: pixel-space math, so both GeoArray and plain np.ndarray inputs are supported and returned in kind. Pixels that are nodata in either scene are NaN (fill_value=NaN). Inputs are (H, W) or (C, H, W); a 4-D (T, C, H, W) stack raises ValueError (compute the flow of each frame separately).

Called as op(moving, reference): reference is the fixed scene the input is registered against, on the input's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
band int

Band index (along the band axis) used for registration on 3-D inputs.

0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class OpticalFlowTVL1(Operator):
    """Dense per-pixel displacement via TV-L1 optical flow.

    Wraps :func:`skimage.registration.optical_flow_tvl1` on the selected
    registration band. The output is a ``(2, H, W)`` displacement field
    (``[dy, dx]`` per pixel) on the input's carrier: pixel-space math,
    so both ``GeoArray`` and plain ``np.ndarray`` inputs are supported
    and returned in kind. Pixels that are nodata in either scene are
    ``NaN`` (``fill_value=NaN``). Inputs are ``(H, W)`` or
    ``(C, H, W)``; a 4-D ``(T, C, H, W)`` stack raises ``ValueError``
    (compute the flow of each frame separately).

    Called as ``op(moving, reference)``: ``reference`` is the fixed scene
    the input is registered against, on the input's pixel grid
    (``ValueError`` otherwise).

    Args:
        band: Band index (along the band axis) used for registration on
            3-D inputs.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a flow field between two frames, from a global variational fit
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(self, *, band: int = 0) -> None:
        self.band = band

    def _apply(
        self, gt: GeoArray | np.ndarray, reference: GeoArray | np.ndarray
    ) -> GeoArray | np.ndarray:
        optical_flow_tvl1 = optional_name(
            "skimage.registration",
            "optical_flow_tvl1",
            "morph",
            feature="geoops.geom.OpticalFlowTVL1",
        )
        name = type(self).__name__
        require_grid_match(gt, reference, name, names=("moving", "reference"))
        flow = np.asarray(
            optical_flow_tvl1(
                _registration_band(
                    np.asarray(reference), self.band, f"{name} reference"
                ),
                _registration_band(np.asarray(gt), self.band, name),
            )
        )
        return _wrap_flow(gt, reference, flow)

PadTo

Bases: Operator

Pad a GeoArray up to a target spatial shape.

Pads the spatial axes ("y", "x") symmetrically so the output has at least shape pixels along each spatial axis. If the input already exceeds the target on an axis, that axis is left alone (no truncation — pair with :class:CropTo for that).

The affine transform is re-based (geoarray.pad for a constant pad with the carrier's own fill) so the geographic position of the existing data does not move; new rows appear to the top/bottom and new columns to the left/right. The output keeps the input's fill_value.

Pixel-space padding: plain np.ndarray inputs are supported and padded with :func:numpy.pad (returned as plain arrays); the transform bookkeeping only happens for GeoArray input.

Parameters:

Name Type Description Default
shape tuple[int, int]

Target minimum spatial shape (H, W).

required
mode str

Numpy pad mode. "constant" (default), "edge", "reflect", "symmetric", ...

'constant'
fill_value float | None

Constant value when mode == "constant". None falls back to the carrier's fill_value, or 0 when the carrier has none (and for plain-array input).

None

Examples:

>>> import geoops as gz
>>> # Pad to a multiple of 256 before tiling.
>>> snug = gz.geom.PadTo(shape=(2048, 2048), fill_value=0)(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class PadTo(Operator):
    """Pad a `GeoArray` up to a target spatial shape.

    Pads the spatial axes (``"y"``, ``"x"``) symmetrically so the output
    has *at least* ``shape`` pixels along each spatial axis. If the
    input already exceeds the target on an axis, that axis is left
    alone (no truncation — pair with :class:`CropTo` for that).

    The affine transform is re-based (``geoarray.pad`` for a constant
    pad with the carrier's own fill) so the *geographic* position of the
    existing data does not move; new rows appear to the top/bottom and
    new columns to the left/right. The output keeps the input's
    ``fill_value``.

    Pixel-space padding: plain ``np.ndarray`` inputs are supported and
    padded with :func:`numpy.pad` (returned as plain arrays); the
    transform bookkeeping only happens for ``GeoArray`` input.

    Args:
        shape: Target minimum spatial shape ``(H, W)``.
        mode: Numpy pad mode. ``"constant"`` (default), ``"edge"``,
            ``"reflect"``, ``"symmetric"``, ...
        fill_value: Constant value when ``mode == "constant"``. ``None``
            falls back to the carrier's ``fill_value``, or ``0``
            when the carrier has none (and for plain-array input).

    Examples:
        >>> import geoops as gz
        >>> # Pad to a multiple of 256 before tiling.
        >>> snug = gz.geom.PadTo(shape=(2048, 2048), fill_value=0)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(
        self,
        *,
        shape: tuple[int, int],
        mode: str = "constant",
        fill_value: float | None = None,
    ) -> None:
        self.shape = shape
        self.mode = mode
        self.fill_value = fill_value

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, "PadTo")
        height, width = gt.shape[-2:]
        pad_y = max(self.shape[0] - height, 0)
        pad_x = max(self.shape[1] - width, 0)
        if pad_y == 0 and pad_x == 0:
            return gt
        pad_yx = (
            (pad_y // 2, pad_y - pad_y // 2),
            (pad_x // 2, pad_x - pad_x // 2),
        )
        carrier_fill = gt.fill_value if isinstance(gt, GeoArray) else None
        constant = self.fill_value
        if constant is None:
            # No explicit constant: the carrier's fill, else 0.
            constant = 0 if carrier_fill is None else carrier_fill
        if (
            isinstance(gt, GeoArray)
            and self.mode == "constant"
            and carrier_fill is not None
            and _same_fill(constant, carrier_fill)
        ):
            # Padding with the carrier's own fill is geoarray's ``pad``.
            return geoarray.pad(gt, pad_yx)
        data = gt.data if isinstance(gt, GeoArray) else np.asarray(gt)
        xp = gt.xp if isinstance(gt, GeoArray) else np
        pad_width = [(0, 0)] * (data.ndim - 2) + list(pad_yx)
        if self.mode == "constant":
            padded = xp.pad(data, pad_width, mode="constant", constant_values=constant)
        else:
            # `mode` is user-supplied (a numpy / jax.numpy pad-mode name);
            # the stubs only accept the literal names, so widen it for ty.
            padded = xp.pad(data, pad_width, mode=cast("Any", self.mode))
        if not isinstance(gt, GeoArray):
            return padded
        # geoarray's pad moves the transform on either backend (and under
        # jax.jit); the pixels are the ones padded above
        moved = geoarray.pad(gt.replace(fill_value=None), pad_yx, fill_value=0)
        return moved.with_data(padded, fill_value=carrier_fill)

    def get_config(self) -> dict[str, Any]:
        return {
            "shape": list(self.shape),
            "mode": self.mode,
            "fill_value": self.fill_value,
        }

PhaseAlign

Bases: Operator

Sub-pixel image registration via phase cross-correlation.

Arrays are interpreted as (H, W) or channel-first (C, H, W); the selected registration band is taken from the band axis (-3). A 4-D (T, C, H, W) stack raises ValueError: register each frame separately. The estimated (dy, dx) shift (nodata pixels of either registration band set to that band's valid mean, so a fill value never drives the correlation) is applied with linear interpolation (scipy.ndimage.shift) when apply=True.

The registration math is pixel-space, so plain np.ndarray inputs are supported: they come back as plain shifted arrays. For GeoArray input the shifted array keeps the input's affine transform (which must share the reference's grid), so a feature at pixel (r, c) of the output sits at the same world coordinate as pixel (r, c) of the reference. Nodata pixels (fill or non-finite) are shifted as nodata, and edge pixels the shift uncovers have no data either: every output pixel interpolated from one holds the input's fill value (NaN for a fill-less float input), so a sub-pixel shift grows a nodata region by up to one pixel. An integer input without a fill_value cannot mark nodata; its uncovered edge repeats the nearest edge pixel.

Called as op(moving, reference): reference is the fixed scene the input is registered against, on the input's pixel grid (ValueError otherwise).

Parameters:

Name Type Description Default
upsample_factor int

Sub-pixel upsampling factor passed to :func:skimage.registration.phase_cross_correlation.

10
band int

Band index (along the band axis) used for registration on 3-D inputs.

0
apply bool

If True (default), return the shifted image; if False, return the raw (shift_y, shift_x, error) tuple instead; the operator is then terminal (last step only) in a Sequential.

True
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class PhaseAlign(Operator):
    """Sub-pixel image registration via phase cross-correlation.

    Arrays are interpreted as ``(H, W)`` or channel-first ``(C, H, W)``;
    the selected registration band is taken from the band axis (``-3``).
    A 4-D ``(T, C, H, W)`` stack raises ``ValueError``: register each
    frame separately. The estimated
    ``(dy, dx)`` shift (nodata pixels of either registration band set to
    that band's valid mean, so a fill value never drives the
    correlation) is applied with linear interpolation
    (``scipy.ndimage.shift``) when ``apply=True``.

    The registration math is pixel-space, so plain ``np.ndarray`` inputs
    are supported: they come back as plain shifted arrays. For
    ``GeoArray`` input the shifted array keeps the input's affine
    transform (which must share the reference's grid), so a feature at
    pixel ``(r, c)`` of the output sits at the same world coordinate as
    pixel ``(r, c)`` of the reference. Nodata pixels (fill or
    non-finite) are shifted as nodata, and edge pixels the shift uncovers
    have no data either: every output pixel interpolated from one holds
    the input's fill value (``NaN`` for a fill-less float input), so a
    sub-pixel shift grows a nodata region by up to one pixel. An integer
    input without a ``fill_value`` cannot mark nodata; its
    uncovered edge repeats the nearest edge pixel.

    Called as ``op(moving, reference)``: ``reference`` is the fixed scene
    the input is registered against, on the input's pixel grid
    (``ValueError`` otherwise).

    Args:
        upsample_factor: Sub-pixel upsampling factor passed to
            :func:`skimage.registration.phase_cross_correlation`.
        band: Band index (along the band axis) used for registration on
            3-D inputs.
        apply: If ``True`` (default), return the shifted image; if
            ``False``, return the raw ``(shift_y, shift_x, error)``
            tuple instead; the operator is then terminal (last step
            only) in a ``Sequential``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a shift estimated by cross-correlation over the scene, then applied
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        upsample_factor: int = 10,
        band: int = 0,
        apply: bool = True,
    ) -> None:
        self.upsample_factor = upsample_factor
        self.band = band
        self.apply = apply

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """The ``apply=False`` tuple breaks carrier-in / carrier-out."""
        return not self.apply

    def _apply(
        self, gt: GeoArray | np.ndarray, reference: GeoArray | np.ndarray
    ) -> GeoArray | np.ndarray | tuple[float, float, float]:
        phase_cross_correlation = optional_name(
            "skimage.registration",
            "phase_cross_correlation",
            "morph",
            feature="geoops.geom.PhaseAlign",
        )
        require_grid_match(gt, reference, "PhaseAlign", names=("moving", "reference"))
        arr = np.asarray(gt)
        mov_band = _mean_imputed(
            _registration_band(
                mask_invalid_to_nan(gt, dtype=np.float64), self.band, "PhaseAlign"
            )
        )
        ref_band = _mean_imputed(
            _registration_band(
                mask_invalid_to_nan(reference, dtype=np.float64),
                self.band,
                "PhaseAlign reference",
            )
        )
        shift, error, _phase = phase_cross_correlation(
            ref_band,
            mov_band,
            upsample_factor=self.upsample_factor,
        )
        shift_y = float(shift[0])
        shift_x = float(shift[1])
        if not self.apply:
            return shift_y, shift_x, float(error)
        # Shift the validity alongside the values so the linear
        # interpolation never blends a fill value into valid data: an
        # output pixel that draws any weight from a nodata pixel -- or from
        # beyond the edge -- is nodata. An integer carrier without a fill
        # value cannot mark nodata, so its uncovered edge repeats the edge
        # pixels instead.
        inexact = np.issubdtype(arr.dtype, np.inexact)
        fill = carried_fill(gt, arr.dtype)
        in_valid = valid_pixels(gt)
        values = np.where(in_valid, arr.astype(np.float64), 0.0)
        spatial_shift = (shift_y, shift_x)
        shifted = ndi_shift(
            values,
            shift=(0.0, *spatial_shift) if arr.ndim == 3 else spatial_shift,
            order=1,
            mode="nearest",
        )
        weight = ndi_shift(
            in_valid.astype(np.float64),
            shift=spatial_shift,
            order=1,
            mode="constant" if inexact or fill is not None else "nearest",
            cval=0.0,
        )
        valid = weight > 1.0 - 1e-9
        out = (
            shifted.astype(arr.dtype) if inexact else np.rint(shifted).astype(arr.dtype)
        )
        # The array shift already moves the content onto the reference
        # grid; keep the original transform (translating it as well would
        # cancel the alignment in world coordinates, #118).
        return wrap_filled(gt, out, fill_value=fill, valid=valid)

Rasterize

Bases: Operator

Rasterize geometries onto the input GeoArray's grid.

Burns geometries into a fresh array aligned with the input's CRS and transform. Accepts either:

  • a list of shapely geometries (each gets value 1); or
  • a :class:geopandas.GeoDataFrame (the column argument selects which attribute supplies the burn-in value; without one every geometry burns 1, as for a list).

Delegates to :func:georeader.rasterize.rasterize_geopandas_like or :func:georeader.rasterize.rasterize_geometry_like.

Geo-dependent: requires a georeferenced GeoArray input (its transform + CRS define the burn grid); plain arrays raise TypeError.

The output is one (H, W) raster whatever the input's rank: every band and every frame of a (T, C, H, W) stack share the grid, so one burn serves them all. Its fill_value is fill_value in the output dtype (0 for the default uint8 burn), and pixels that are nodata in the input (in any band or frame) hold it.

Note

Carries Python-level geometry objects (shapely / geopandas), so flagged forbid_in_yaml = True.

Parameters:

Name Type Description Default
geometries list[BaseGeometry] | GeoDataFrame

Shapely geometries or a GeoDataFrame.

required
column str | None

For GeoDataFrame inputs, the column with burn-in values. None means "burn 1".

None
all_touched bool

Whether to mark every pixel the geometry touches (vs. only those whose centre is inside).

False
fill_value float

Background value. Default 0. Without a column the output is uint8 when fill_value is an integer in [0, 255] and float32 otherwise (e.g. np.nan).

0.0

Examples:

>>> import geoops as gz
>>> from shapely.geometry import box
>>> aoi_mask = gz.geom.Rasterize(geometries=[box(*aoi_bounds)])(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Rasterize(Operator):
    """Rasterize geometries onto the input `GeoArray`'s grid.

    Burns ``geometries`` into a fresh array aligned with the input's
    CRS and transform. Accepts either:

    - a ``list`` of shapely geometries (each gets value ``1``); or
    - a :class:`geopandas.GeoDataFrame` (the ``column`` argument
      selects which attribute supplies the burn-in value; without one
      every geometry burns ``1``, as for a list).

    Delegates to :func:`georeader.rasterize.rasterize_geopandas_like`
    or :func:`georeader.rasterize.rasterize_geometry_like`.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (its
    transform + CRS define the burn grid); plain arrays raise
    ``TypeError``.

    The output is one ``(H, W)`` raster whatever the input's rank: every
    band and every frame of a ``(T, C, H, W)`` stack share the grid, so
    one burn serves them all. Its ``fill_value`` is ``fill_value``
    in the output dtype (``0`` for the default ``uint8`` burn), and
    pixels that are nodata in the input (in any band or frame) hold it.

    Note:
        Carries Python-level geometry objects (shapely / geopandas),
        so flagged ``forbid_in_yaml = True``.

    Args:
        geometries: Shapely geometries or a `GeoDataFrame`.
        column: For `GeoDataFrame` inputs, the column with burn-in
            values. ``None`` means "burn ``1``".
        all_touched: Whether to mark every pixel the geometry touches
            (vs. only those whose centre is inside).
        fill_value: Background value. Default ``0``. Without a
            ``column`` the output is ``uint8`` when ``fill_value`` is an
            integer in ``[0, 255]`` and ``float32`` otherwise (e.g.
            ``np.nan``).

    Examples:
        >>> import geoops as gz
        >>> from shapely.geometry import box
        >>> aoi_mask = gz.geom.Rasterize(geometries=[box(*aoi_bounds)])(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # depends only on the grid and the geometries
    coupling: ClassVar[Coupling] = Coupling(reads_values=False)

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        geometries: list[BaseGeometry] | gpd.GeoDataFrame,
        column: str | None = None,
        all_touched: bool = False,
        fill_value: float = 0.0,
    ) -> None:
        self.geometries = geometries
        self.column = column
        self.all_touched = all_touched
        self.fill_value = fill_value

    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "Rasterize")
        return _burn_onto(
            self.geometries,
            gt,
            column=self.column,
            fill=self.fill_value,
            all_touched=self.all_touched,
            nodata_from=(gt,),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "geometries": f"<{type(self.geometries).__name__} n={len(self.geometries)}>",
            "column": self.column,
            "all_touched": self.all_touched,
            "fill_value": self.fill_value,
        }

RasterizeLike

Bases: Operator

Rasterize geometries onto a stored reference grid.

Same as :class:Rasterize but the reference grid is pinned at construction (like) rather than supplied per call. The operator takes no positional input (it is a producer) -- useful as the head of a Sequential pipeline that consumes the burned mask -- or a GeoArray on like's grid (ValueError otherwise), whose nodata pixels then hold the fill as in :class:Rasterize (like only supplies the grid). The output is one (H, W) raster whatever the input's rank.

Note

Flagged forbid_in_yaml = True.

Parameters:

Name Type Description Default
like GeoArray

Reference GeoArray whose CRS + transform + shape define the output grid.

required
geometries GeoDataFrame

Shapely geometries or a GeoDataFrame.

required
column str | None

Attribute column for the burn-in value, or None.

None
all_touched bool

As in :class:Rasterize.

False
fill_value float

Background value.

0.0

Examples:

>>> import geoops as gz
>>> burner = gz.geom.RasterizeLike(
...     like=ref_scene, geometries=polygons_gdf, column="class_id"
... )
>>> labels = burner()
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class RasterizeLike(Operator):
    """Rasterize geometries onto a stored reference grid.

    Same as :class:`Rasterize` but the reference grid is pinned at
    construction (``like``) rather than supplied per call. The
    operator takes *no* positional input (it is a producer) -- useful as
    the head of a `Sequential` pipeline that consumes the burned mask --
    or a `GeoArray` on ``like``'s grid (``ValueError`` otherwise), whose
    nodata pixels then hold the fill as in :class:`Rasterize` (``like``
    only supplies the grid). The output is one ``(H, W)`` raster whatever
    the input's rank.

    Note:
        Flagged ``forbid_in_yaml = True``.

    Args:
        like: Reference `GeoArray` whose CRS + transform + shape define
            the output grid.
        geometries: Shapely geometries or a `GeoDataFrame`.
        column: Attribute column for the burn-in value, or ``None``.
        all_touched: As in :class:`Rasterize`.
        fill_value: Background value.

    Examples:
        >>> import geoops as gz
        >>> burner = gz.geom.RasterizeLike(
        ...     like=ref_scene, geometries=polygons_gdf, column="class_id"
        ... )
        >>> labels = burner()
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # depends only on the grid and the geometries
    coupling: ClassVar[Coupling] = Coupling(reads_values=False)

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        like: GeoArray,
        geometries: gpd.GeoDataFrame,
        column: str | None = None,
        all_touched: bool = False,
        fill_value: float = 0.0,
    ) -> None:
        self.like = like
        self.geometries = geometries
        self.column = column
        self.all_touched = all_touched
        self.fill_value = fill_value

    def _apply(self, gt: GeoArray | None = None) -> GeoArray:
        reject_georeader(self.like, "RasterizeLike (like)")
        if gt is not None:
            reject_geotensor(gt, "RasterizeLike")
        if gt is not None and not grid_matches(gt, self.like):
            raise ValueError(
                "RasterizeLike: the input is not on `like`'s grid (spatial "
                "shape, transform, CRS); call it with no input, or use "
                "Rasterize to burn onto the input's own grid."
            )
        return _burn_onto(
            self.geometries,
            self.like,
            column=self.column,
            fill=self.fill_value,
            all_touched=self.all_touched,
            nodata_from=() if gt is None else (gt,),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "like": repr(self.like),
            "geometries": f"<{type(self.geometries).__name__} n={len(self.geometries)}>",
            "column": self.column,
            "all_touched": self.all_touched,
            "fill_value": self.fill_value,
        }

Reproject

Bases: Operator

Reproject a GeoArray to a destination CRS or onto a target grid.

Two engines. engine="gdal" (the default) wraps :func:georeader.read.read_to_crs: the destination grid is anchored to the input's bounding box reprojected into dst_crs, and the resolution defaults to the input's pixel size expressed in the destination CRS; it runs on NumPy only (a JAX carrier goes to the host and back, and a trace is refused). engine="interp" warps onto target through a functax plan (the [interp] extra): the target pixel centres go through pyproj to the source CRS once, a scheme plans the read-out H on the source grid, and every frame and band is H y. It runs on NumPy and on JAX, under jax.jit / eqx.filter_jit too, and the centres are computed once per source CRS and reused.

Geo-dependent: requires a georeferenced GeoArray input (transform + CRS); plain arrays raise TypeError.

Parameters:

Name Type Description Default
dst_crs str | None

Target CRS as a string (EPSG code, WKT, PROJ string, or anything :class:pyproj.CRS.from_user_input accepts). Give dst_crs or target, not both.

None
resolution tuple[float, float] | None

Optional (pixel_size_x, pixel_size_y) in destination-CRS units, with dst_crs. None lets georeader derive it from the source pixel size. Honoured even when dst_crs equals the input CRS (the call then acts as a resample).

None
resampling str

One of "nearest", "bilinear" / "linear", "cubic" / "bicubic", "cubic_spline", "lanczos", "average", "mode". engine="interp" takes the first four: functax's Nearest, Linear, Cubic (Keys, a = −½) and BSpline(3).

'bilinear'
engine Literal['gdal', 'interp']

"gdal" or "interp".

'gdal'
target Grid | Mapping[str, Any] | None

The output grid (a hashable geoarray.Grid, CRS included, or its get_config()), instead of dst_crs; engine="interp" needs it. Target pixels off the source grid, or reading its nodata with a non-zero weight, hold the fill (NaN for a float input without one).

None

Examples:

>>> import geoops as gz
>>> # Reproject a UTM scene into geographic coords for plotting.
>>> reproj = gz.geom.Reproject(
...     dst_crs="EPSG:4326", resampling="bilinear"
... )
>>> geographic = reproj(utm_scene)
>>> # The same warp onto a fixed grid, on JAX and under jit.
>>> import equinox as eqx
>>> import geoarray as ga
>>> target = ga.Grid((0.001, 0.0, -104.0, 0.0, -0.001, 32.0), "EPSG:4326", (500, 500))
>>> warp = eqx.filter_jit(
...     gz.geom.Reproject(target=target, resampling="bilinear", engine="interp")
... )
>>> frames = warp(utm_scene.to_jax())  # (T, C, H, W) -> (T, C, 500, 500)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Reproject(Operator):
    """Reproject a `GeoArray` to a destination CRS or onto a target grid.

    Two engines. ``engine="gdal"`` (the default) wraps
    :func:`georeader.read.read_to_crs`: the destination grid is anchored to
    the input's bounding box reprojected into ``dst_crs``, and the
    resolution defaults to the input's pixel size expressed in the
    destination CRS; it runs on NumPy only (a JAX carrier goes to the host
    and back, and a trace is refused). ``engine="interp"`` warps onto ``target``
    through a functax plan (the ``[interp]`` extra): the target pixel
    centres go through pyproj to the source CRS once, a scheme plans the
    read-out H on the source grid, and every frame and band is H y. It runs
    on NumPy and on JAX, under ``jax.jit`` / ``eqx.filter_jit`` too, and the
    centres are computed once per source CRS and reused.

    Geo-dependent: requires a georeferenced ``GeoArray`` input
    (transform + CRS); plain arrays raise ``TypeError``.

    Args:
        dst_crs: Target CRS as a string (EPSG code, WKT, PROJ string, or
            anything :class:`pyproj.CRS.from_user_input` accepts). Give
            ``dst_crs`` or ``target``, not both.
        resolution: Optional ``(pixel_size_x, pixel_size_y)`` in
            destination-CRS units, with ``dst_crs``. ``None`` lets georeader
            derive it from the source pixel size. Honoured even when
            ``dst_crs`` equals the input CRS (the call then acts as a
            resample).
        resampling: One of ``"nearest"``, ``"bilinear"`` /
            ``"linear"``, ``"cubic"`` / ``"bicubic"``,
            ``"cubic_spline"``, ``"lanczos"``, ``"average"``, ``"mode"``.
            ``engine="interp"`` takes the first four: functax's
            ``Nearest``, ``Linear``, ``Cubic`` (Keys, a = −½) and
            ``BSpline(3)``.
        engine: ``"gdal"`` or ``"interp"``.
        target: The output grid (a hashable `geoarray.Grid`, CRS
            included, or its ``get_config()``), instead of ``dst_crs``;
            ``engine="interp"`` needs it.
            Target pixels off the source grid, or reading its nodata with a
            non-zero weight, hold the fill (NaN for a float input without
            one).

    Examples:
        >>> import geoops as gz
        >>> # Reproject a UTM scene into geographic coords for plotting.
        >>> reproj = gz.geom.Reproject(
        ...     dst_crs="EPSG:4326", resampling="bilinear"
        ... )
        >>> geographic = reproj(utm_scene)
        >>> # The same warp onto a fixed grid, on JAX and under jit.
        >>> import equinox as eqx
        >>> import geoarray as ga
        >>> target = ga.Grid((0.001, 0.0, -104.0, 0.0, -0.001, 32.0), "EPSG:4326", (500, 500))
        >>> warp = eqx.filter_jit(
        ...     gz.geom.Reproject(target=target, resampling="bilinear", engine="interp")
        ... )
        >>> frames = warp(utm_scene.to_jax())  # (T, C, H, W) -> (T, C, 500, 500)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # resampled onto a new grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    def __init__(
        self,
        *,
        dst_crs: str | None = None,
        resolution: tuple[float, float] | None = None,
        resampling: str = "bilinear",
        engine: Literal["gdal", "interp"] = "gdal",
        target: geoarray.Grid | Mapping[str, Any] | None = None,
    ) -> None:
        if isinstance(target, Mapping):
            # a Grid's get_config, as from_state and YAML hand it back
            target = geoarray.Grid.from_config(dict(target.items()))
        if engine not in ("gdal", "interp"):
            raise ValueError(f"Reproject.engine is 'gdal' or 'interp', got {engine!r}")
        if (dst_crs is None) == (target is None):
            raise ValueError("Reproject takes dst_crs or target, not both or neither")
        if target is not None and resolution is not None:
            raise ValueError("Reproject: target fixes the resolution; drop resolution")
        if target is not None and not isinstance(target, geoarray.Grid):
            raise TypeError(
                f"Reproject.target is a geoarray.Grid, got {type(target).__name__}"
            )
        if engine == "interp":
            if target is None:
                raise ValueError("Reproject(engine='interp') needs target=")
            interp_resampling(resampling)
        self.dst_crs = dst_crs
        self.resolution = resolution
        self.resampling = resampling
        self.engine = engine
        self.target = target
        # runtime only: X_* = φ(target centres) per source CRS, not config
        self._coordinates: dict[Any, np.ndarray] = {}

    def _place_inputs(
        self,
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
        backends: tuple[str, ...] | None = None,
    ) -> tuple[tuple[Any, ...], dict[str, Any], bool]:
        # the functax engine runs on NumPy and JAX; GDAL on NumPy only
        if self.engine == "interp":
            return args, kwargs, False
        return super()._place_inputs(args, kwargs, backends)

    def _apply(self, gt: GeoArray) -> GeoArray:
        if self.engine == "interp":
            require_geoarray(gt, "Reproject")
            return self._warp(gt)
        read = optional_name(
            "georeader", "read", "sensors", feature="geoops.geom.Reproject"
        )
        require_geoarray(gt, "Reproject")
        resampling = resolve_resampling(self.resampling)
        engine_gt = to_engine(gt)
        if self.target is not None:
            window_type = optional_name(
                "rasterio.windows", "Window", "raster", feature="geoops.geom.Reproject"
            )
            target = self.target
            return adopt_attrs(
                gt,
                read.read_reproject(
                    engine_gt,
                    dst_crs=None if target.crs is None else target.crs.to_string(),
                    dst_transform=target.affine,
                    window_out=window_type(0, 0, target.width, target.height),
                    resampling=resampling,
                ),
            )
        if self.resolution is None:
            return adopt_attrs(
                gt, read.read_to_crs(engine_gt, self.dst_crs, resampling=resampling)
            )
        # ``read_to_crs`` returns its input untouched when the CRS already
        # matches, silently dropping ``resolution``; build the destination
        # grid explicitly so a same-CRS call still resamples.
        window, dst_transform = read.calculate_transform_window(
            engine_gt, self.dst_crs, self.resolution
        )
        return adopt_attrs(
            gt,
            read.read_reproject(
                engine_gt,
                dst_crs=self.dst_crs,
                dst_transform=dst_transform,
                window_out=window,
                resampling=resampling,
            ),
        )

    def _warp(self, gt: GeoArray) -> GeoArray:
        """The functax engine: f̂(X_*) = H y onto ``target``."""
        target = self.target
        assert target is not None  # the constructor requires it
        scheme, boundary = resolve_scheme(self.resampling)
        import jax

        coordinates = self._coordinates.get(gt.crs)
        if coordinates is None:
            coordinates = target_coordinates(target, gt.crs)
            self._coordinates[gt.crs] = coordinates
        host = gt.backend == "numpy"
        with x64("geoops.geom.Reproject") if host else nullcontext():
            values, fill = warp(gt, target, scheme, boundary, coordinates)
            if host:
                values = jax.device_get(values)
                transform: Any = np.asarray(target.transform)
            else:
                transform = jax.numpy.asarray(target.transform, dtype=jax.numpy.float64)
        return wrap_like(
            gt, values, transform=transform, fill_value=fill, crs=target.crs
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "dst_crs": self.dst_crs,
            "resolution": (None if self.resolution is None else list(self.resolution)),
            "resampling": self.resampling,
            "engine": self.engine,
            "target": None if self.target is None else self.target.get_config(),
        }

ReprojectLike

Bases: Operator

Reproject a GeoArray onto another GeoArray's CRS + grid.

Wraps :func:georeader.read.read_reproject_like: the output has the same CRS, transform, and spatial shape as like. Useful for aligning auxiliary data (DEMs, masks, predictions from another sensor) onto a reference scene grid before downstream pipelines.

Geo-dependent: requires a georeferenced GeoArray input (transform + CRS); plain arrays raise TypeError.

Note

like is a concrete GeoArray, so this Operator is flagged forbid_in_yaml = True.

Parameters:

Name Type Description Default
like GeoArray

The reference GeoArray whose grid (CRS + transform + spatial shape) is matched.

required
resampling str

See :class:Reproject.

'bilinear'

Examples:

>>> import geoops as gz
>>> # Align a coarse cloud mask onto the scene grid.
>>> aligned_mask = gz.geom.ReprojectLike(
...     like=scene, resampling="nearest"
... )(coarse_mask)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class ReprojectLike(Operator):
    """Reproject a `GeoArray` onto another `GeoArray`'s CRS + grid.

    Wraps :func:`georeader.read.read_reproject_like`: the output has the
    same CRS, transform, and spatial shape as ``like``. Useful for
    aligning auxiliary data (DEMs, masks, predictions from another
    sensor) onto a reference scene grid before downstream pipelines.

    Geo-dependent: requires a georeferenced ``GeoArray`` input
    (transform + CRS); plain arrays raise ``TypeError``.

    Note:
        ``like`` is a concrete ``GeoArray``, so this Operator is
        flagged ``forbid_in_yaml = True``.

    Args:
        like: The reference `GeoArray` whose grid (CRS + transform +
            spatial shape) is matched.
        resampling: See :class:`Reproject`.

    Examples:
        >>> import geoops as gz
        >>> # Align a coarse cloud mask onto the scene grid.
        >>> aligned_mask = gz.geom.ReprojectLike(
        ...     like=scene, resampling="nearest"
        ... )(coarse_mask)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # resampled onto another grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, like: GeoArray, resampling: str = "bilinear") -> None:
        self.like = like
        self.resampling = resampling

    def _apply(self, gt: GeoArray) -> GeoArray:
        read = optional_name(
            "georeader", "read", "sensors", feature="geoops.geom.ReprojectLike"
        )
        name = type(self).__name__
        require_geoarray(gt, name)
        reject_georeader(self.like, f"{name} (like)")
        return adopt_attrs(
            gt,
            read.read_reproject_like(
                to_engine(gt),
                to_engine(self.like),
                resampling=resolve_resampling(self.resampling),
            ),
        )

    def get_config(self) -> dict[str, Any]:
        return {"like": repr(self.like), "resampling": self.resampling}

Resample

Bases: Operator

Resample a GeoArray to a target spatial resolution.

The output shape is derived per axis from the ratio of the input pixel size to the requested resolution, (round(H * res_y / dst_y), round(W * res_x / dst_x)), and the resize is delegated to georeader's GeoTensor.resize (through the engine boundary). The geographic extent is preserved, so the achieved pixel size matches resolution exactly only when it divides the extent.

Geo-dependent: the target resolution is expressed in CRS units, so a georeferenced GeoArray input is required; plain arrays raise TypeError.

Parameters:

Name Type Description Default
resolution tuple[float, float]

Target (pixel_size_x, pixel_size_y) in input-CRS units.

required
resampling str

Interpolation mode. Default "bilinear".

'bilinear'
anti_aliasing bool

Whether to anti-alias before downscaling. Default True.

True

Examples:

>>> import geoops as gz
>>> # Downsample a 10 m raster to 30 m.
>>> coarse = gz.geom.Resample(resolution=(30.0, 30.0))(fine_10m)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Resample(Operator):
    """Resample a `GeoArray` to a target spatial resolution.

    The output shape is derived per axis from the ratio of the input
    pixel size to the requested resolution,
    ``(round(H * res_y / dst_y), round(W * res_x / dst_x))``, and the
    resize is delegated to georeader's ``GeoTensor.resize`` (through the
    engine boundary).
    The geographic extent is preserved, so the achieved pixel size
    matches ``resolution`` exactly only when it divides the extent.

    Geo-dependent: the target resolution is expressed in CRS units, so
    a georeferenced ``GeoArray`` input is required; plain arrays raise
    ``TypeError``.

    Args:
        resolution: Target ``(pixel_size_x, pixel_size_y)`` in
            input-CRS units.
        resampling: Interpolation mode. Default ``"bilinear"``.
        anti_aliasing: Whether to anti-alias before downscaling.
            Default ``True``.

    Examples:
        >>> import geoops as gz
        >>> # Downsample a 10 m raster to 30 m.
        >>> coarse = gz.geom.Resample(resolution=(30.0, 30.0))(fine_10m)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    def __init__(
        self,
        *,
        resolution: tuple[float, float],
        resampling: str = "bilinear",
        anti_aliasing: bool = True,
    ) -> None:
        self.resolution = resolution
        self.resampling = resampling
        self.anti_aliasing = anti_aliasing

    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "Resample")
        res_x, res_y = gt.res
        dst_x, dst_y = self.resolution
        height, width = gt.shape[-2:]
        # Derive the shape per axis here instead of passing
        # ``resolution_dst`` to georeader's ``resize``, which scales the
        # height by the *x* resolution ratio (wrong for non-square pixels).
        shape = (
            max(round(height * res_y / abs(dst_y)), 1),
            max(round(width * res_x / abs(dst_x)), 1),
        )
        return _resize_to_shape(
            gt,
            shape,
            anti_aliasing=self.anti_aliasing,
            interpolation=resolve_interpolation(self.resampling),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "resolution": list(self.resolution),
            "resampling": self.resampling,
            "anti_aliasing": self.anti_aliasing,
        }

ResampleLike

Bases: ReprojectLike

Resample a GeoArray onto another GeoArray's spatial grid.

Alias of :class:ReprojectLike. The intent of the rename is purely pipeline-readability: in workflows where both inputs already share a CRS, ResampleLike reads as "match this grid" rather than "warp into a new projection".

Examples:

>>> import geoops as gz
>>> # Downsample a 10 m S2 band onto a 20 m reference grid.
>>> rs = gz.geom.ResampleLike(like=s2_20m, resampling="average")
>>> b04_20m = rs(b04_10m)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class ResampleLike(ReprojectLike):
    """Resample a `GeoArray` onto another `GeoArray`'s spatial grid.

    Alias of :class:`ReprojectLike`. The intent of the rename is purely
    pipeline-readability: in workflows where both inputs already share a
    CRS, ``ResampleLike`` reads as "match this grid" rather than
    "warp into a new projection".

    Examples:
        >>> import geoops as gz
        >>> # Downsample a 10 m S2 band onto a 20 m reference grid.
        >>> rs = gz.geom.ResampleLike(like=s2_20m, resampling="average")
        >>> b04_20m = rs(b04_10m)
    """

Resize

Bases: Operator

Resize a GeoArray to a target spatial shape.

Delegates to georeader's GeoTensor.resize (through the engine boundary), re-basing the affine transform so the geographic extent is preserved while the pixel grid is densified or coarsened. anti_aliasing applies a Gaussian pre-filter when downscaling (recommended).

Geo-dependent (transform-updating): requires a georeferenced GeoArray input; plain arrays raise TypeError.

Note

The interpolation name is mapped onto :func:skimage.transform.resize's conventions ("bilinear", "bicubic", "nearest").

Parameters:

Name Type Description Default
shape tuple[int, int]

Target spatial shape (H, W) in pixels.

required
anti_aliasing bool

Whether to anti-alias before downscaling. Default True.

True
resampling str

Interpolation mode. Default "bilinear".

'bilinear'

Examples:

>>> import geoops as gz
>>> tile = gz.geom.Resize(shape=(256, 256))(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Resize(Operator):
    """Resize a `GeoArray` to a target spatial shape.

    Delegates to georeader's ``GeoTensor.resize`` (through the engine
    boundary), re-basing the affine transform so the geographic extent is preserved
    while the pixel grid is densified or coarsened. ``anti_aliasing``
    applies a Gaussian pre-filter when downscaling (recommended).

    Geo-dependent (transform-updating): requires a georeferenced
    ``GeoArray`` input; plain arrays raise ``TypeError``.

    Note:
        The interpolation name is mapped onto
        :func:`skimage.transform.resize`'s conventions
        (``"bilinear"``, ``"bicubic"``, ``"nearest"``).

    Args:
        shape: Target spatial shape ``(H, W)`` in pixels.
        anti_aliasing: Whether to anti-alias before downscaling.
            Default ``True``.
        resampling: Interpolation mode. Default ``"bilinear"``.

    Examples:
        >>> import geoops as gz
        >>> tile = gz.geom.Resize(shape=(256, 256))(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    def __init__(
        self,
        *,
        shape: tuple[int, int],
        anti_aliasing: bool = True,
        resampling: str = "bilinear",
    ) -> None:
        self.shape = shape
        self.anti_aliasing = anti_aliasing
        self.resampling = resampling

    def _apply(self, gt: GeoArray) -> GeoArray:
        require_geoarray(gt, "Resize")
        return _resize_to_shape(
            gt,
            self.shape,
            anti_aliasing=self.anti_aliasing,
            interpolation=resolve_interpolation(self.resampling),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "shape": list(self.shape),
            "anti_aliasing": self.anti_aliasing,
            "resampling": self.resampling,
        }

SegmentStitch

Bases: Operator

Assemble indexed sensor segments into one contiguous GeoArray.

Segment order is read from each input's attrs["__geotoolz_segment_meta__"] mapping (a nested dict, frozen by the carrier) with segment_index and n_segments keys. Both zero-based (0..n_segments-1) and one-based (1..n_segments) indexing are accepted. One-based indexing is selected only when an index equal to n_segments is present; ambiguous missing-edge cases default to zero-based. Missing segments are filled with fill_value.

Geo-dependent: every segment must be a georeferenced GeoArray (attrs metadata + transform bookkeeping); plain arrays raise TypeError.

Parameters:

Name Type Description Default
direction str

Stitching direction: "scan" / "y" for along-track, or "sample" / "x" for cross-track.

'scan'
fill_value float | None

Value used for missing segments. None (default) means NaN; a NaN argument is stored as None so the config stays strict JSON.

None
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class SegmentStitch(Operator):
    """Assemble indexed sensor segments into one contiguous ``GeoArray``.

    Segment order is read from each input's
    ``attrs["__geotoolz_segment_meta__"]`` mapping (a nested dict, frozen
    by the carrier) with ``segment_index`` and ``n_segments`` keys. Both zero-based
    (``0..n_segments-1``) and one-based (``1..n_segments``) indexing are
    accepted. One-based indexing is selected only when an index equal to
    ``n_segments`` is present; ambiguous missing-edge cases default to
    zero-based. Missing segments are filled with ``fill_value``.

    Geo-dependent: every segment must be a georeferenced ``GeoArray``
    (attrs metadata + transform bookkeeping); plain arrays raise
    ``TypeError``.

    Args:
        direction: Stitching direction: ``"scan"`` / ``"y"`` for
            along-track, or ``"sample"`` / ``"x"`` for cross-track.
        fill_value: Value used for missing segments. ``None`` (default) means
            ``NaN``; a ``NaN`` argument is stored as ``None`` so the config
            stays strict JSON.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # segments joined into one carrier
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "join"})

    def __init__(
        self, *, direction: str = "scan", fill_value: float | None = None
    ) -> None:
        self.direction = direction
        self.fill_value = (
            None if fill_value is None or np.isnan(fill_value) else fill_value
        )

    def _apply(self, segments: list[GeoArray]) -> GeoArray:
        _require_carrier_list(segments, "SegmentStitch", "segments")
        if len(segments) == 0:
            raise ValueError("SegmentStitch requires at least one segment.")
        for segment in segments:
            require_geoarray(segment, "SegmentStitch")
        axis_num = _segment_axis(self.direction)
        metas = [_segment_meta(segment) for segment in segments]
        n_segments = metas[0][1]
        if any(n != n_segments for _, n in metas):
            raise ValueError("All segments must declare the same n_segments.")
        index_offset = 1 if max(index for index, _ in metas) == n_segments else 0
        by_index: dict[int, GeoArray] = {}
        for (index, _), segment in zip(metas, segments, strict=True):
            normalised = index - index_offset
            if normalised in by_index:
                raise ValueError(
                    f"Duplicate segment_index {index} after index_offset "
                    f"normalisation; each segment must declare a unique index."
                )
            by_index[normalised] = segment
        if any(index < 0 or index >= n_segments for index in by_index):
            raise ValueError("segment_index is outside the declared n_segments range.")
        first_index = min(by_index)
        first = by_index[first_index]
        for segment in segments:
            _validate_segment_compatible(first, segment, axis_num)
        # Choose a fill that is representable in the segment dtype: integer
        # tensors cannot hold NaN, so fall back to the first segment's own
        # fill (or zero) when the requested fill is non-finite.
        fill = np.nan if self.fill_value is None else self.fill_value
        segment_fill = _coerce_segment_fill(fill, first)
        pieces: list[np.ndarray] = []
        segment_shape = first.shape
        for index in range(n_segments):
            if index in by_index:
                pieces.append(np.asarray(by_index[index]))
            else:
                pieces.append(np.full(segment_shape, segment_fill, dtype=first.dtype))
        values = np.concatenate(pieces, axis=axis_num)
        row_before = first_index * segment_shape[-2] if axis_num == -2 else 0
        col_before = first_index * segment_shape[-1] if axis_num == -1 else 0
        transform = affine_of(first) * Affine.translation(-col_before, -row_before)
        out = wrap_like(first, values, transform=transform, fill_value=segment_fill)
        return out.with_attrs(
            **{
                _SEGMENT_META: {
                    "segment_index": 0,
                    "n_segments": 1,
                    "source_n_segments": n_segments,
                }
            }
        )

SlidingWindow

Bases: Tile

Split a GeoArray into overlapping sliding-window tiles.

Convenience subclass of :class:Tile that takes a scalar overlap (in pixels) and derives the stride. Equivalent to Tile(size=size, stride=(size[0] - overlap, size[1] - overlap)).

Parameters:

Name Type Description Default
size tuple[int, int]

Tile spatial shape (H, W).

required
overlap int

Overlap in pixels along both axes. Default 0.

0

Examples:

>>> import geoops as gz
>>> # 256x256 tiles, 32-pixel overlap on every side.
>>> tiles = gz.geom.SlidingWindow(size=(256, 256), overlap=32)(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class SlidingWindow(Tile):
    """Split a `GeoArray` into overlapping sliding-window tiles.

    Convenience subclass of :class:`Tile` that takes a scalar
    ``overlap`` (in pixels) and derives the stride. Equivalent to
    ``Tile(size=size, stride=(size[0] - overlap, size[1] - overlap))``.

    Args:
        size: Tile spatial shape ``(H, W)``.
        overlap: Overlap in pixels along both axes. Default ``0``.

    Examples:
        >>> import geoops as gz
        >>> # 256x256 tiles, 32-pixel overlap on every side.
        >>> tiles = gz.geom.SlidingWindow(size=(256, 256), overlap=32)(scene)
    """

    def __init__(self, *, size: tuple[int, int], overlap: int = 0) -> None:
        self.overlap = overlap
        super().__init__(
            size=size,
            stride=(size[0] - overlap, size[1] - overlap),
            include_incomplete=True,
        )

    def get_config(self) -> dict[str, Any]:
        return {"size": list(self.size), "overlap": self.overlap}

Stitch

Bases: Operator

Stitch georeferenced tiles back into one GeoArray.

Blends a list[GeoArray] (typically the output of :class:Tile) onto a unioning north-up grid, masking out the fill_value sentinels that :class:Tile introduces along the bottom / right edges with boundless=True.

Supported blend modes:

  • "average" — unweighted mean of overlapping pixels.
  • "feather" — overlap-add with triangular edge weights, kernel from :func:geoops.geom._src.array.feather_weights.
  • "first" — first tile wins on overlap.
  • "max" — element-wise maximum across overlapping tiles.

The mathematical model for "average" / "feather" is the standard overlap-add reconstruction:

.. math::

\hat{x}_{ij} \;=\; \frac{\sum_k w_k(i, j)\, m_k(i, j)\, x_k(i, j)}
                        {\sum_k w_k(i, j)\, m_k(i, j)}

where m_k is the validity mask of tile k and w_k is the weight kernel (1 everywhere for "average", the feather kernel otherwise). Pixels with no valid contributor are filled with fill_value (default: the first tile's fill_value).

Unless target_shape is pinned, trailing bottom rows / right columns with no valid contributor (the sentinel padding :class:Tile adds to its edge tiles) are cropped off, so a Tile → Stitch round trip recovers the source extent. Pin target_shape to keep them.

Geo-dependent: every tile must be a georeferenced GeoArray — the tile transforms place each tile on the output grid. Plain-array tiles raise TypeError. Every tile must be north-up (b == d == 0, a > 0, e < 0) and share the first tile's pixel size; otherwise ValueError is raised.

Parameters:

Name Type Description Default
blend str

Blend mode (see above). Default "average".

'average'
feather_width int

Pixel ramp width for "feather" blending.

16
target_shape tuple[int, int] | None

Optional (H, W) override for the output grid.

None
target_transform Affine | Sequence[float] | None

Optional :class:affine.Affine override for the output grid origin, or its first six coefficients [a, b, c, d, e, f] (the form get_config emits). Must be north-up with the tiles' pixel size.

None
target_crs str | None

Optional CRS override for the output. Defaults to the first tile's CRS.

None
fill_value float | int | None

Output fill value. None (default) inherits from the first tile.

None

Examples:

>>> import geoops as gz
>>> # Round-trip a tiled inference pipeline.
>>> tiles = gz.geom.Tile(size=(256, 256))(scene)
>>> predictions = [model(tile) for tile in tiles]
>>> stitched = gz.geom.Stitch(blend="feather", feather_width=16)(
...     predictions
... )
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Stitch(Operator):
    r"""Stitch georeferenced tiles back into one `GeoArray`.

    Blends a ``list[GeoArray]`` (typically the output of :class:`Tile`)
    onto a unioning north-up grid, masking out the
    ``fill_value`` sentinels that :class:`Tile` introduces
    along the bottom / right edges with ``boundless=True``.

    Supported blend modes:

    - ``"average"`` — unweighted mean of overlapping pixels.
    - ``"feather"`` — overlap-add with triangular edge weights, kernel from
      :func:`geoops.geom._src.array.feather_weights`.
    - ``"first"`` — first tile wins on overlap.
    - ``"max"`` — element-wise maximum across overlapping tiles.

    The mathematical model for ``"average"`` / ``"feather"`` is the
    standard overlap-add reconstruction:

    .. math::

        \hat{x}_{ij} \;=\; \frac{\sum_k w_k(i, j)\, m_k(i, j)\, x_k(i, j)}
                                {\sum_k w_k(i, j)\, m_k(i, j)}

    where ``m_k`` is the validity mask of tile ``k`` and ``w_k`` is the
    weight kernel (1 everywhere for ``"average"``, the feather kernel
    otherwise). Pixels with no valid contributor are filled with
    ``fill_value`` (default: the first tile's ``fill_value``).

    Unless ``target_shape`` is pinned, trailing bottom rows / right
    columns with no valid contributor (the sentinel padding
    :class:`Tile` adds to its edge tiles) are cropped off, so a
    ``Tile`` → ``Stitch`` round trip recovers the source extent. Pin
    ``target_shape`` to keep them.

    Geo-dependent: every tile must be a georeferenced ``GeoArray`` —
    the tile transforms place each tile on the output grid. Plain-array
    tiles raise ``TypeError``. Every tile must be north-up
    (``b == d == 0``, ``a > 0``, ``e < 0``) and share the first tile's
    pixel size; otherwise ``ValueError`` is raised.

    Args:
        blend: Blend mode (see above). Default ``"average"``.
        feather_width: Pixel ramp width for ``"feather"`` blending.
        target_shape: Optional ``(H, W)`` override for the output grid.
        target_transform: Optional :class:`affine.Affine` override for
            the output grid origin, or its first six coefficients
            ``[a, b, c, d, e, f]`` (the form ``get_config`` emits). Must
            be north-up with the tiles' pixel size.
        target_crs: Optional CRS override for the output. Defaults to
            the first tile's CRS.
        fill_value: Output fill value. ``None`` (default) inherits from the
            first tile.

    Examples:
        >>> import geoops as gz
        >>> # Round-trip a tiled inference pipeline.
        >>> tiles = gz.geom.Tile(size=(256, 256))(scene)
        >>> predictions = [model(tile) for tile in tiles]
        >>> stitched = gz.geom.Stitch(blend="feather", feather_width=16)(
        ...     predictions
        ... )
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # tiles joined onto one grid, overlaps blended
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "join"})

    def __init__(
        self,
        *,
        blend: str = "average",
        feather_width: int = 16,
        target_shape: tuple[int, int] | None = None,
        target_transform: Affine | Sequence[float] | None = None,
        target_crs: str | None = None,
        fill_value: float | int | None = None,
    ) -> None:
        self.blend = blend
        self.feather_width = feather_width
        self.target_shape = as_tuple(target_shape)
        if target_transform is not None and not isinstance(target_transform, Affine):
            target_transform = Affine(*target_transform[:6])
        self.target_transform = target_transform
        self.target_crs = target_crs
        self.fill_value = fill_value

    def _apply(self, tiles: list[GeoArray]) -> GeoArray:
        _require_carrier_list(tiles, "Stitch", "tiles")
        if len(tiles) == 0:
            raise ValueError("Stitch requires at least one tile.")
        if self.blend not in {"average", "feather", "max", "first"}:
            raise ValueError("blend must be 'average', 'feather', 'max', or 'first'.")
        first = tiles[0]
        for index, tile in enumerate(tiles):
            require_geoarray(tile, "Stitch", arg=f"tile at index {index}")
            if not is_north_up(affine_of(tile)):
                raise ValueError(
                    f"Stitch only supports north-up, non-rotated GeoArrays; "
                    f"tile {index} has a rotated/sheared or flipped transform "
                    f"({tuple(np.asarray(tile.transform).tolist())})."
                )
            # ``target_slices`` places tiles by origin only and assumes one
            # pixel size, so a coarser/finer tile would be pasted at the
            # wrong scale.
            if not np.allclose(tile.res, first.res):
                raise ValueError(
                    f"Stitch requires every tile to share the first tile's "
                    f"resolution {tuple(first.res)}; tile {index} has "
                    f"{tuple(tile.res)}."
                )
        if self.target_transform is not None and not (
            is_north_up(self.target_transform)
            and np.allclose(
                (self.target_transform.a, -self.target_transform.e), first.res
            )
        ):
            raise ValueError(
                f"target_transform must be north-up with the tiles' resolution "
                f"{tuple(first.res)}; got {tuple(self.target_transform)[:6]}."
            )
        transform, shape = self._target_grid(tiles)
        fill = first.fill_value if self.fill_value is None else self.fill_value
        dtype = first.dtype if self.blend in {"first", "max"} else np.float32
        out_shape = first.shape[:-2] + shape
        if self.blend == "max":
            values = np.full(out_shape, fill, dtype=dtype)
            covered = np.zeros(shape, dtype=bool)
            self._stitch_max(tiles, transform, values, covered, fill)
        elif self.blend == "first":
            values = np.full(out_shape, fill, dtype=dtype)
            covered = np.zeros(shape, dtype=bool)
            self._stitch_first(tiles, transform, values, covered, fill)
        else:  # average / feather
            values = np.zeros(out_shape, dtype=dtype)
            weights = np.zeros(shape, dtype=np.float32)
            self._stitch_average(tiles, transform, values, weights, fill)
            covered = weights > 0
            normalize_overlap_add(values, weights, fill)
        if self.target_shape is None:
            # Drop the trailing rows / columns that only :class:`Tile`'s
            # sentinel padding reached, recovering the source extent.
            rows = np.flatnonzero(covered.any(axis=1))
            cols = np.flatnonzero(covered.any(axis=0))
            if rows.size and cols.size:
                values = values[..., : rows[-1] + 1, : cols[-1] + 1]
        return GeoArray(
            values,
            transform,
            self.target_crs or first.crs,
            fill_value=fill,
            # a carrier's attrs, carried: the 0.2 per-band keys stay as they are
            attrs=FrozenAttrs(_copied_attrs(first, values)),
            dims=DIMS[-values.ndim :],
        )

    def _target_grid(
        self,
        tiles: list[GeoArray],
    ) -> tuple[Affine, tuple[int, int]]:
        first = tiles[0]
        if self.target_transform is not None:
            transform = self.target_transform
        else:
            bounds = [tile.bounds for tile in tiles]
            minx = min(bound[0] for bound in bounds)
            maxy = max(bound[3] for bound in bounds)
            first_transform = affine_of(first)
            transform = Affine(
                first_transform.a, 0.0, minx, 0.0, first_transform.e, maxy
            )
        if self.target_shape is not None:
            return transform, self.target_shape
        bounds = [tile.bounds for tile in tiles]
        maxx = max(bound[2] for bound in bounds)
        miny = min(bound[1] for bound in bounds)
        height = round((transform.f - miny) / abs(transform.e))
        width = round((maxx - transform.c) / abs(transform.a))
        return transform, (height, width)

    def _stitch_average(
        self,
        tiles: list[GeoArray],
        transform: Affine,
        values: np.ndarray,
        weights: np.ndarray,
        fill: float | int | None,
    ) -> None:
        for tile in tiles:
            arr = np.asarray(tile)
            out_slices, tile_slices = target_slices(
                affine_of(tile), tile.shape[-2:], transform, weights.shape
            )
            mask_tile = valid_pixel_mask(arr, fill)
            kernel = (
                feather_weights(tile.shape[-2:], self.feather_width)
                if self.blend == "feather"
                else np.ones(tile.shape[-2:], dtype=np.float32)
            )
            overlap_add(
                values, weights, arr, out_slices, tile_slices, kernel, mask_tile
            )

    def _stitch_first(
        self,
        tiles: list[GeoArray],
        transform: Affine,
        values: np.ndarray,
        filled: np.ndarray,
        fill: float | int | None,
    ) -> None:
        for tile in tiles:
            arr = np.asarray(tile)
            out_slices, tile_slices = target_slices(
                affine_of(tile), tile.shape[-2:], transform, filled.shape
            )
            mask_tile = valid_pixel_mask(arr, fill)[tile_slices]
            mask = (~filled[out_slices]) & mask_tile
            values_window = values[..., out_slices[0], out_slices[1]]
            tile_window = arr[..., tile_slices[0], tile_slices[1]]
            values_window[..., mask] = tile_window[..., mask]
            filled[out_slices] |= mask

    def _stitch_max(
        self,
        tiles: list[GeoArray],
        transform: Affine,
        values: np.ndarray,
        filled: np.ndarray,
        fill: float | int | None,
    ) -> None:
        for tile in tiles:
            arr = np.asarray(tile)
            out_slices, tile_slices = target_slices(
                affine_of(tile), tile.shape[-2:], transform, filled.shape
            )
            mask_tile = valid_pixel_mask(arr, fill)[tile_slices]
            values_window = values[..., out_slices[0], out_slices[1]]
            tile_window = arr[..., tile_slices[0], tile_slices[1]]
            both = filled[out_slices] & mask_tile
            only_tile = (~filled[out_slices]) & mask_tile
            values_window[..., both] = np.maximum(
                values_window[..., both],
                tile_window[..., both],
            )
            values_window[..., only_tile] = tile_window[..., only_tile]
            filled[out_slices] |= mask_tile

    def get_config(self) -> dict[str, Any]:
        return {
            "blend": self.blend,
            "feather_width": self.feather_width,
            "target_shape": (
                None if self.target_shape is None else list(self.target_shape)
            ),
            "target_transform": (
                None
                if self.target_transform is None
                else list(self.target_transform)[:6]
            ),
            "target_crs": self.target_crs,
            "fill_value": self.fill_value,
        }

Tile

Bases: Operator

Split a GeoArray into spatial tiles.

Wraps :func:georeader.slices.create_windows (with trim_incomplete=False) and then reads each window with boundless=True so the trailing-edge tiles match size exactly. Out-of-bounds areas are padded with the carrier's fill_value; use :func:Stitch (which masks the sentinel) to recover the original extent. A GeoArray with fill_value=None is zero-padded instead — Stitch cannot tell that padding from data, so pin its target_shape / target_transform to the source grid to drop it.

Pixel-space tiling: plain np.ndarray inputs are supported and yield a list of plain arrays (out-of-bounds areas zero-padded, since a plain array carries no fill_value). Note that :class:Stitch cannot reassemble plain-array tiles — it needs each tile's transform to place it.

Parameters:

Name Type Description Default
size tuple[int, int]

Tile spatial shape (H, W).

required
stride tuple[int, int] | None

Step between consecutive tile origins (sy, sx). The implied overlap is size - stride. None (default) means non-overlapping tiles (stride == size).

None
include_incomplete bool

Whether to keep edge tiles that don't fully fit (still emitted at size shape, padded as above). False drops them, so the trailing rows / columns that no full tile covers are not emitted at all.

True

Examples:

>>> import geoops as gz
>>> # 512x512 tiles with 64-pixel overlap.
>>> tiles = gz.geom.Tile(size=(512, 512), stride=(448, 448))(scene)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Tile(Operator):
    """Split a `GeoArray` into spatial tiles.

    Wraps :func:`georeader.slices.create_windows` (with
    ``trim_incomplete=False``) and then reads each window with
    ``boundless=True`` so the trailing-edge tiles match ``size``
    exactly. Out-of-bounds areas are padded with the carrier's
    ``fill_value``; use :func:`Stitch` (which masks the
    sentinel) to recover the original extent. A ``GeoArray`` with
    ``fill_value=None`` is zero-padded instead — ``Stitch``
    cannot tell that padding from data, so pin its ``target_shape`` /
    ``target_transform`` to the source grid to drop it.

    Pixel-space tiling: plain ``np.ndarray`` inputs are supported and
    yield a list of plain arrays (out-of-bounds areas zero-padded, since
    a plain array carries no ``fill_value``). Note that
    :class:`Stitch` cannot reassemble plain-array tiles — it needs each
    tile's transform to place it.

    Args:
        size: Tile spatial shape ``(H, W)``.
        stride: Step between consecutive tile origins ``(sy, sx)``. The
            implied overlap is ``size - stride``. ``None`` (default)
            means non-overlapping tiles (``stride == size``).
        include_incomplete: Whether to keep edge tiles that don't fully
            fit (still emitted at ``size`` shape, padded as above).
            ``False`` drops them, so the trailing rows / columns that no
            full tile covers are not emitted at all.

    Examples:
        >>> import geoops as gz
        >>> # 512x512 tiles with 64-pixel overlap.
        >>> tiles = gz.geom.Tile(size=(512, 512), stride=(448, 448))(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "split"}, kind="fan-out")

    def __init__(
        self,
        *,
        size: tuple[int, int],
        stride: tuple[int, int] | None = None,
        include_incomplete: bool = True,
    ) -> None:
        self.size = size
        self.stride = stride
        self.include_incomplete = include_incomplete

    def _apply(self, gt: GeoArray | np.ndarray) -> list[GeoArray] | list[np.ndarray]:
        rasterio = optional_root(
            "rasterio.windows", "raster", feature="geoops.geom.Tile"
        )
        slices = optional_name(
            "georeader",
            "slices",
            "sensors",
            feature="geoops.geom.Tile",
        )
        overlap: tuple[int, int] | None = None
        if self.stride is not None:
            overlap = (self.size[0] - self.stride[0], self.size[1] - self.stride[1])
            if overlap[0] < 0 or overlap[1] < 0:
                raise ValueError("stride must be less than or equal to size.")
        # ``trim_incomplete=False`` keeps every window at ``size`` so the
        # trailing tiles extend past the raster and get padded below
        # (georeader's default trims them to the raster bounds instead).
        windows = slices.create_windows(
            gt.shape[-2:],
            self.size,
            overlap=overlap,
            include_incomplete=self.include_incomplete,
            trim_incomplete=False,
        )
        reject_geotensor(gt, type(self).__name__)
        if not isinstance(gt, GeoArray):
            arr = np.asarray(gt)
            return [_read_window_boundless(arr, window) for window in windows]
        if gt.fill_value is not None:
            return [
                gt.read_window(as_pixel_window(window), boundless=True)
                for window in windows
            ]
        # ``read_window(boundless=True)`` refuses to pad without a fill
        # value; zero-pad like the plain-array path (the fill stays None).
        transform = affine_of(gt)
        return [
            wrap_like(
                gt,
                _read_window_boundless(np.asarray(gt), window),
                transform=rasterio.windows.transform(window, transform),
            )
            for window in windows
        ]

    def get_config(self) -> dict[str, Any]:
        return {
            "size": list(self.size),
            "stride": None if self.stride is None else list(self.stride),
            "include_incomplete": self.include_incomplete,
        }

Vectorize

Bases: Operator

Vectorize non-zero regions of a mask GeoArray into polygons.

Wraps :func:georeader.vectorize.get_polygons. The carrier's transform is used to express polygons in geographic coordinates. Polygons with area below min_area_px (in square pixels of the mask) are dropped.

Geo-dependent: requires a georeferenced GeoArray input (the transform maps pixels to polygon coordinates); plain arrays raise TypeError. The mask must be single-band, (H, W) or (1, H, W); other shapes raise ValueError.

Parameters:

Name Type Description Default
min_area_px float

Minimum polygon area in square pixels. Default 25.5 (~5×5 px), matching the georeader default.

25.5
simplify_tolerance float | None

Optional post-hoc :meth:shapely.simplify tolerance (in CRS units). None (default) leaves the staircase pixel boundaries intact.

None

Examples:

>>> import geoops as gz
>>> polys = gz.geom.Vectorize(min_area_px=100.0)(water_mask)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/operators.py
class Vectorize(Operator):
    """Vectorize non-zero regions of a mask `GeoArray` into polygons.

    Wraps :func:`georeader.vectorize.get_polygons`. The carrier's
    transform is used to express polygons in geographic coordinates.
    Polygons with area below ``min_area_px`` (in square pixels of the
    mask) are dropped.

    Geo-dependent: requires a georeferenced ``GeoArray`` input (the
    transform maps pixels to polygon coordinates); plain arrays raise
    ``TypeError``. The mask must be single-band, ``(H, W)`` or
    ``(1, H, W)``; other shapes raise ``ValueError``.

    Args:
        min_area_px: Minimum polygon area in square *pixels*. Default
            ``25.5`` (~5×5 px), matching the georeader default.
        simplify_tolerance: Optional post-hoc :meth:`shapely.simplify`
            tolerance (in CRS units). ``None`` (default) leaves the
            staircase pixel boundaries intact.

    Examples:
        >>> import geoops as gz
        >>> polys = gz.geom.Vectorize(min_area_px=100.0)(water_mask)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # polygons from connected regions
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        min_area_px: float = 25.5,
        simplify_tolerance: float | None = None,
    ) -> None:
        self.min_area_px = min_area_px
        self.simplify_tolerance = simplify_tolerance

    def _apply(self, gt: GeoArray) -> list[BaseGeometry]:
        vectorize = optional_name(
            "georeader",
            "vectorize",
            "sensors",
            feature="geoops.geom.Vectorize",
        )
        require_geoarray(gt, "Vectorize")
        # ``get_polygons`` asserts a 2-D mask; squeeze the canonical
        # ``(1, H, W)`` band axis and pass the transform explicitly.
        mask = single_band(np.asarray(gt), name="Vectorize")
        polygons = vectorize.get_polygons(
            mask, min_area=self.min_area_px, tolerance=0.0, transform=affine_of(gt)
        )
        if self.simplify_tolerance is None:
            return polygons
        return [polygon.simplify(self.simplify_tolerance) for polygon in polygons]

adaptive_curl_2d(u, v, dy=1.0, dx=1.0, *, mask=None, accuracy=1, periodic_x=False)

Mask-aware curl: :func:adaptive_difference for each derivative.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch h w']

The component along columns.

required
v Float[ndarray, '*batch h w']

The component along rows.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
mask Bool[ndarray, '*batch h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The curl, u's shape, NaN only where a cell is dropped.

Example

y, x = np.mgrid[0:5, 0:6].astype(float) wall = x == 2 zeta = adaptive_curl_2d(-y, x, mask=wall) int(np.isnan(zeta).sum()), float(np.nanmax(np.abs(zeta - 2.0))) (5, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_curl_2d(
    u: Float[np.ndarray, "*batch h w"],
    v: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    mask: Bool[np.ndarray, "*batch h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    """Mask-aware curl: :func:`adaptive_difference` for each derivative.

    Args:
        u: The component along columns.
        v: The component along rows.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The curl, ``u``'s shape, ``NaN`` only where a cell is dropped.

    Example:
        >>> y, x = np.mgrid[0:5, 0:6].astype(float)
        >>> wall = x == 2
        >>> zeta = adaptive_curl_2d(-y, x, mask=wall)
        >>> int(np.isnan(zeta).sum()), float(np.nanmax(np.abs(zeta - 2.0)))
        (5, 0.0)
    """
    reject_geotensor(u, "adaptive_curl_2d")
    reject_geotensor(v, "adaptive_curl_2d")
    reject_geotensor(mask, "adaptive_curl_2d")
    d_v = adaptive_difference(
        v, mask=mask, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x
    )
    return d_v - adaptive_difference(u, mask=mask, axis=-2, step=dy, accuracy=accuracy)

adaptive_curl_3d(u, v, w, dz=1.0, dy=1.0, dx=1.0, *, z=None, mask=None, accuracy=1, periodic_x=False)

Mask-aware 3-D curl: :func:adaptive_difference for each derivative.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch d h w']

The component along columns.

required
v Float[ndarray, '*batch d h w']

The component along rows.

required
w Float[ndarray, '*batch d h w']

The component along levels.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions; replaces dz.

None
mask Bool[ndarray, '*batch d h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '3 *batch d h w']

(ω_z, ω_y, ω_x) stacked on a new leading axis.

Example

z, y, x = np.mgrid[0:4, 0:5, 0:6].astype(float) rock = (z == 2) & (y == 2) & (x == 3) zeta_z = adaptive_curl_3d(-y, x, 0.0 * z, mask=rock)[0] int(np.isnan(zeta_z).sum()), float(np.nanmax(np.abs(zeta_z - 2.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_curl_3d(
    u: Float[np.ndarray, "*batch d h w"],
    v: Float[np.ndarray, "*batch d h w"],
    w: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    mask: Bool[np.ndarray, "*batch d h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "3 *batch d h w"]:
    """Mask-aware 3-D curl: :func:`adaptive_difference` for each derivative.

    Args:
        u: The component along columns.
        v: The component along rows.
        w: The component along levels.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions; replaces ``dz``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        ``(ω_z, ω_y, ω_x)`` stacked on a new leading axis.

    Example:
        >>> z, y, x = np.mgrid[0:4, 0:5, 0:6].astype(float)
        >>> rock = (z == 2) & (y == 2) & (x == 3)
        >>> zeta_z = adaptive_curl_3d(-y, x, 0.0 * z, mask=rock)[0]
        >>> int(np.isnan(zeta_z).sum()), float(np.nanmax(np.abs(zeta_z - 2.0)))
        (1, 0.0)
    """
    for c in (u, v, w, mask):
        reject_geotensor(c, "adaptive_curl_3d")
    xp = array_namespace(u)
    kw = {"mask": mask, "accuracy": accuracy}
    d_x = functools.partial(
        adaptive_difference, axis=-1, step=dx, periodic=periodic_x, **kw
    )
    d_y = functools.partial(adaptive_difference, axis=-2, step=dy, **kw)
    d_z = functools.partial(adaptive_difference, axis=-3, step=dz, coords=z, **kw)
    return xp.stack([d_x(v) - d_y(u), d_z(u) - d_x(w), d_y(w) - d_z(v)])

adaptive_difference(f, *, mask=None, axis=-1, step=1.0, coords=None, derivative=1, accuracy=1, periodic=False)

Mask-aware finite difference: the widest stencil that fits on valid data.

Near a mask (land, a swath edge, a cloud) the centred stencil reads a masked cell and :func:difference loses the valid cells next to it. This keeps, per point, the first finite result among the central, forward and backward stencils at accuracy, then at each lower accuracy down to 1, so a narrow channel still gets a first-order estimate. Recovered cells carry one order less than the interior.

NaN is its own support detector: a stencil that reads a masked cell returns NaN (0 * nan is nan), so the selection needs no mask arithmetic (xrtoolz docs/design/xrgrad-nan-masks.md, where it beat fill-then-differentiate by ~90x at the coast). Every candidate is computed, so the call costs 3 * accuracy stencils and runs under jax.jit. Masked cells are NaN in the result.

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
mask Bool[ndarray, '*shape'] | None

True drops the cell (geoops' mask convention), on f's shape; None drops only non-finite cells.

None
axis int

The axis to differentiate.

-1
step Float[ndarray, '*shape'] | float

The signed step between centres along axis.

1.0
coords Float[ndarray, ' n'] | None

The centres' positions along axis, for an unevenly spaced axis (see :func:difference); replaces step.

None
derivative int

The derivative order.

1
accuracy int

The highest accuracy order to try.

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

The derivative, f's shape, NaN where f is masked or no

Float[ndarray, '*shape']

stencil fits on valid data.

Example

f = np.array([0.0, 1.0, 2.0, np.nan, 4.0, 5.0, 6.0]) # f = x difference(f) array([ 1., 1., nan, nan, nan, 1., 1.]) adaptive_difference(f) array([ 1., 1., 1., nan, 1., 1., 1.])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_difference(
    f: Float[np.ndarray, "*shape"],
    *,
    mask: Bool[np.ndarray, "*shape"] | None = None,
    axis: int = -1,
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    coords: Float[np.ndarray, " n"] | None = None,
    derivative: int = 1,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    r"""Mask-aware finite difference: the widest stencil that fits on valid data.

    Near a mask (land, a swath edge, a cloud) the centred stencil reads a
    masked cell and :func:`difference` loses the valid cells next to it.
    This keeps, per point, the first finite result among the central,
    forward and backward stencils at ``accuracy``, then at each lower
    accuracy down to 1, so a narrow channel still gets a first-order
    estimate. Recovered cells carry one order less than the interior.

    NaN is its own support detector: a stencil that reads a masked cell
    returns NaN (``0 * nan`` is ``nan``), so the selection needs no mask
    arithmetic (xrtoolz ``docs/design/xrgrad-nan-masks.md``, where it beat
    fill-then-differentiate by ~90x at the coast). Every candidate is
    computed, so the call costs ``3 * accuracy`` stencils and runs under
    ``jax.jit``. Masked cells are ``NaN`` in the result.

    Args:
        f: The field; any shape.
        mask: ``True`` drops the cell (geoops' mask convention), on ``f``'s
            shape; ``None`` drops only non-finite cells.
        axis: The axis to differentiate.
        step: The signed step between centres along ``axis``.
        coords: The centres' positions along ``axis``, for an unevenly spaced
            axis (see :func:`difference`); replaces ``step``.
        derivative: The derivative order.
        accuracy: The highest accuracy order to try.
        periodic: The axis wraps.

    Returns:
        The derivative, ``f``'s shape, ``NaN`` where ``f`` is masked or no
        stencil fits on valid data.

    Example:
        >>> f = np.array([0.0, 1.0, 2.0, np.nan, 4.0, 5.0, 6.0])  # f = x
        >>> difference(f)
        array([ 1.,  1., nan, nan, nan,  1.,  1.])
        >>> adaptive_difference(f)
        array([ 1.,  1.,  1., nan,  1.,  1.,  1.])
    """
    reject_geotensor(f, "adaptive_difference")
    reject_geotensor(mask, "adaptive_difference")
    xp = array_namespace(f)
    dropped = ~xp.isfinite(f)
    if mask is not None:
        dropped = dropped | mask
    field = xp.where(dropped, xp.nan, f)
    out = None
    for acc in range(accuracy, 0, -1):
        for method in METHODS:
            try:
                candidate = difference(
                    field,
                    axis=axis,
                    step=step,
                    coords=coords,
                    derivative=derivative,
                    accuracy=acc,
                    method=method,
                    periodic=periodic,
                )
            except ValueError:
                continue  # a stencil wider than the axis: try a narrower one
            out = (
                candidate if out is None else xp.where(xp.isfinite(out), out, candidate)
            )
    if out is None:
        raise ValueError(
            f"axis of length {f.shape[axis]} is too short for derivative {derivative}"
        )
    return xp.where(dropped, xp.nan, out)

adaptive_divergence_1d(u, step=1.0, *, axis=-1, coords=None, mask=None, accuracy=1, periodic=False)

Mask-aware 1-D divergence: :func:adaptive_difference of u.

Parameters:

Name Type Description Default
u Float[ndarray, '*shape']

The flux component along axis.

required
step Float[ndarray, '*shape'] | float

The signed step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis; replaces step.

None
mask Bool[ndarray, '*shape'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

The divergence, u's shape, NaN only where a cell is dropped.

Example

adaptive_divergence_1d(np.array([0.0, 2.0, np.nan, 6.0, 8.0]), 2.0) array([ 1., 1., nan, 1., 1.])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_divergence_1d(
    u: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    mask: Bool[np.ndarray, "*shape"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    """Mask-aware 1-D divergence: :func:`adaptive_difference` of ``u``.

    Args:
        u: The flux component along ``axis``.
        step: The signed step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis``; replaces ``step``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic: The axis wraps.

    Returns:
        The divergence, ``u``'s shape, ``NaN`` only where a cell is dropped.

    Example:
        >>> adaptive_divergence_1d(np.array([0.0, 2.0, np.nan, 6.0, 8.0]), 2.0)
        array([ 1.,  1., nan,  1.,  1.])
    """
    reject_geotensor(u, "adaptive_divergence_1d")
    return adaptive_difference(
        u,
        mask=mask,
        axis=axis,
        step=step,
        coords=coords,
        accuracy=accuracy,
        periodic=periodic,
    )

adaptive_divergence_2d(u, v, dy=1.0, dx=1.0, *, mask=None, accuracy=1, periodic_x=False)

Mask-aware divergence: :func:adaptive_difference for each derivative.

Each term uses, per point, the widest stencil lying on valid data, so a linear field stays exact up to the coast. A cell is NaN where mask drops it or either component is non-finite.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch h w']

The component along columns.

required
v Float[ndarray, '*batch h w']

The component along rows.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
mask Bool[ndarray, '*batch h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The divergence, u's shape.

Example

y, x = np.mgrid[0:5, 0:6].astype(float) land = (y == 2) & (x == 3) div = adaptive_divergence_2d(x, y, mask=land) int(np.isnan(div).sum()), float(np.nanmax(np.abs(div - 2.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_divergence_2d(
    u: Float[np.ndarray, "*batch h w"],
    v: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    mask: Bool[np.ndarray, "*batch h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    """Mask-aware divergence: :func:`adaptive_difference` for each derivative.

    Each term uses, per point, the widest stencil lying on valid data, so a
    linear field stays exact up to the coast. A cell is ``NaN`` where ``mask``
    drops it or either component is non-finite.

    Args:
        u: The component along columns.
        v: The component along rows.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The divergence, ``u``'s shape.

    Example:
        >>> y, x = np.mgrid[0:5, 0:6].astype(float)
        >>> land = (y == 2) & (x == 3)
        >>> div = adaptive_divergence_2d(x, y, mask=land)
        >>> int(np.isnan(div).sum()), float(np.nanmax(np.abs(div - 2.0)))
        (1, 0.0)
    """
    reject_geotensor(u, "adaptive_divergence_2d")
    reject_geotensor(v, "adaptive_divergence_2d")
    reject_geotensor(mask, "adaptive_divergence_2d")
    d_u = adaptive_difference(
        u, mask=mask, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x
    )
    return d_u + adaptive_difference(v, mask=mask, axis=-2, step=dy, accuracy=accuracy)

adaptive_divergence_3d(u, v, w, dz=1.0, dy=1.0, dx=1.0, *, z=None, mask=None, accuracy=1, periodic_x=False)

Mask-aware 3-D divergence: :func:adaptive_difference for each term.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch d h w']

The component along columns.

required
v Float[ndarray, '*batch d h w']

The component along rows.

required
w Float[ndarray, '*batch d h w']

The component along levels.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions; replaces dz.

None
mask Bool[ndarray, '*batch d h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch d h w']

The divergence, u's shape, NaN only where a cell is dropped.

Example

z, y, x = np.mgrid[0:5, 0:5, 0:6].astype(float) rock = (z == 2) & (y == 2) & (x == 3) # off every edge div = adaptive_divergence_3d(x, y, z, mask=rock) int(np.isnan(div).sum()), float(np.nanmax(np.abs(div - 3.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_divergence_3d(
    u: Float[np.ndarray, "*batch d h w"],
    v: Float[np.ndarray, "*batch d h w"],
    w: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    mask: Bool[np.ndarray, "*batch d h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch d h w"]:
    """Mask-aware 3-D divergence: :func:`adaptive_difference` for each term.

    Args:
        u: The component along columns.
        v: The component along rows.
        w: The component along levels.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions; replaces ``dz``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The divergence, ``u``'s shape, ``NaN`` only where a cell is dropped.

    Example:
        >>> z, y, x = np.mgrid[0:5, 0:5, 0:6].astype(float)
        >>> rock = (z == 2) & (y == 2) & (x == 3)  # off every edge
        >>> div = adaptive_divergence_3d(x, y, z, mask=rock)
        >>> int(np.isnan(div).sum()), float(np.nanmax(np.abs(div - 3.0)))
        (1, 0.0)
    """
    for c in (u, v, w, mask):
        reject_geotensor(c, "adaptive_divergence_3d")
    kw = {"mask": mask, "accuracy": accuracy}
    return (
        adaptive_difference(u, axis=-1, step=dx, periodic=periodic_x, **kw)
        + adaptive_difference(v, axis=-2, step=dy, **kw)
        + adaptive_difference(w, axis=-3, step=dz, coords=z, **kw)
    )

adaptive_gradient_1d(f, step=1.0, *, axis=-1, coords=None, mask=None, accuracy=1, periodic=False)

Mask-aware ∂f/∂s along one axis: :func:adaptive_difference.

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
step Float[ndarray, '*shape'] | float

The signed step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis; replaces step.

None
mask Bool[ndarray, '*shape'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

The derivative, f's shape, NaN only where a cell is dropped.

Example

adaptive_gradient_1d(np.array([0.0, 1.0, np.nan, 3.0, 4.0])) array([ 1., 1., nan, 1., 1.])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_gradient_1d(
    f: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    mask: Bool[np.ndarray, "*shape"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    """Mask-aware ``∂f/∂s`` along one axis: :func:`adaptive_difference`.

    Args:
        f: The field; any shape.
        step: The signed step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis``; replaces ``step``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic: The axis wraps.

    Returns:
        The derivative, ``f``'s shape, ``NaN`` only where a cell is dropped.

    Example:
        >>> adaptive_gradient_1d(np.array([0.0, 1.0, np.nan, 3.0, 4.0]))
        array([ 1.,  1., nan,  1.,  1.])
    """
    reject_geotensor(f, "adaptive_gradient_1d")
    return adaptive_difference(
        f,
        mask=mask,
        axis=axis,
        step=step,
        coords=coords,
        accuracy=accuracy,
        periodic=periodic,
    )

adaptive_gradient_2d(f, dy=1.0, dx=1.0, *, mask=None, accuracy=1, periodic_x=False)

Mask-aware (∂f/∂y, ∂f/∂x): :func:adaptive_difference on both axes.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch h w']

The field, rows and columns last.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
mask Bool[ndarray, '*batch h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '2 *batch h w']

(∂f/∂y, ∂f/∂x) stacked on a new leading axis, NaN on masked

Float[ndarray, '2 *batch h w']

cells only (a linear field stays exact up to the coast).

Example

y, x = np.mgrid[0:4, 0:5].astype(float) land = (y == 1) & (x == 2) d_y, d_x = adaptive_gradient_2d(y + x, mask=land) int(np.isnan(d_x).sum()), float(np.nanmax(np.abs(d_x - 1.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_gradient_2d(
    f: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    mask: Bool[np.ndarray, "*batch h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "2 *batch h w"]:
    """Mask-aware ``(∂f/∂y, ∂f/∂x)``: :func:`adaptive_difference` on both axes.

    Args:
        f: The field, rows and columns last.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        ``(∂f/∂y, ∂f/∂x)`` stacked on a new leading axis, ``NaN`` on masked
        cells only (a linear field stays exact up to the coast).

    Example:
        >>> y, x = np.mgrid[0:4, 0:5].astype(float)
        >>> land = (y == 1) & (x == 2)
        >>> d_y, d_x = adaptive_gradient_2d(y + x, mask=land)
        >>> int(np.isnan(d_x).sum()), float(np.nanmax(np.abs(d_x - 1.0)))
        (1, 0.0)
    """
    reject_geotensor(f, "adaptive_gradient_2d")
    reject_geotensor(mask, "adaptive_gradient_2d")
    xp = array_namespace(f)
    d_y = adaptive_difference(f, mask=mask, axis=-2, step=dy, accuracy=accuracy)
    d_x = adaptive_difference(
        f, mask=mask, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x
    )
    return xp.stack([d_y, d_x])

adaptive_gradient_3d(f, dz=1.0, dy=1.0, dx=1.0, *, z=None, mask=None, accuracy=1, periodic_x=False)

Mask-aware (∂f/∂z, ∂f/∂y, ∂f/∂x): :func:adaptive_difference per axis.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch d h w']

The field, levels, rows and columns last.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions; replaces dz.

None
mask Bool[ndarray, '*batch d h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '3 *batch d h w']

The three components stacked on a new leading axis.

Example

z, y, x = np.mgrid[0:4, 0:4, 0:5].astype(float) seabed = (z == 3) & (x == 2) d_z, _, _ = adaptive_gradient_3d(z + y + x, mask=seabed) int(np.isnan(d_z).sum()), float(np.nanmax(np.abs(d_z - 1.0))) (4, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_gradient_3d(
    f: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    mask: Bool[np.ndarray, "*batch d h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "3 *batch d h w"]:
    """Mask-aware ``(∂f/∂z, ∂f/∂y, ∂f/∂x)``: :func:`adaptive_difference` per axis.

    Args:
        f: The field, levels, rows and columns last.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions; replaces ``dz``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The three components stacked on a new leading axis.

    Example:
        >>> z, y, x = np.mgrid[0:4, 0:4, 0:5].astype(float)
        >>> seabed = (z == 3) & (x == 2)
        >>> d_z, _, _ = adaptive_gradient_3d(z + y + x, mask=seabed)
        >>> int(np.isnan(d_z).sum()), float(np.nanmax(np.abs(d_z - 1.0)))
        (4, 0.0)
    """
    reject_geotensor(f, "adaptive_gradient_3d")
    reject_geotensor(mask, "adaptive_gradient_3d")
    xp = array_namespace(f)
    kw = {"mask": mask, "accuracy": accuracy}
    d_z = adaptive_difference(f, axis=-3, step=dz, coords=z, **kw)
    d_y = adaptive_difference(f, axis=-2, step=dy, **kw)
    d_x = adaptive_difference(f, axis=-1, step=dx, periodic=periodic_x, **kw)
    return xp.stack([d_z, d_y, d_x])

adaptive_laplacian_1d(f, step=1.0, *, axis=-1, coords=None, mask=None, accuracy=1, periodic=False)

Mask-aware ∂²f/∂s² along one axis: :func:adaptive_difference of order 2.

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
step Float[ndarray, '*shape'] | float

The step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis; replaces step.

None
mask Bool[ndarray, '*shape'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

The second derivative, f's shape, NaN only where dropped.

Example

s = np.arange(8.0) f = s**2 f[3] = np.nan adaptive_laplacian_1d(f) array([ 2., 2., 2., nan, 2., 2., 2., 2.])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_laplacian_1d(
    f: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    mask: Bool[np.ndarray, "*shape"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    """Mask-aware ``∂²f/∂s²`` along one axis: :func:`adaptive_difference` of order 2.

    Args:
        f: The field; any shape.
        step: The step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis``; replaces ``step``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic: The axis wraps.

    Returns:
        The second derivative, ``f``'s shape, ``NaN`` only where dropped.

    Example:
        >>> s = np.arange(8.0)
        >>> f = s**2
        >>> f[3] = np.nan
        >>> adaptive_laplacian_1d(f)
        array([ 2.,  2.,  2., nan,  2.,  2.,  2.,  2.])
    """
    reject_geotensor(f, "adaptive_laplacian_1d")
    return adaptive_difference(
        f,
        mask=mask,
        axis=axis,
        step=step,
        coords=coords,
        derivative=2,
        accuracy=accuracy,
        periodic=periodic,
    )

adaptive_laplacian_2d(f, dy=1.0, dx=1.0, *, mask=None, accuracy=1, periodic_x=False)

Mask-aware Laplacian: :func:adaptive_difference of second order on each axis.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch h w']

The field, rows and columns last.

required
dy Float[ndarray, 'h w'] | float

The step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The step between column centres.

1.0
mask Bool[ndarray, '*batch h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The Laplacian, f's shape; a quadratic stays exact next to the mask.

Example

y, x = np.mgrid[0:7, 0:8].astype(float) island = (y == 3) & (x == 4) # two cells from every edge lap = adaptive_laplacian_2d(x2 + y2, mask=island) int(np.isnan(lap).sum()), float(np.nanmax(np.abs(lap - 4.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_laplacian_2d(
    f: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    mask: Bool[np.ndarray, "*batch h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    """Mask-aware Laplacian: :func:`adaptive_difference` of second order on each axis.

    Args:
        f: The field, rows and columns last.
        dy: The step between row centres.
        dx: The step between column centres.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The Laplacian, ``f``'s shape; a quadratic stays exact next to the mask.

    Example:
        >>> y, x = np.mgrid[0:7, 0:8].astype(float)
        >>> island = (y == 3) & (x == 4)  # two cells from every edge
        >>> lap = adaptive_laplacian_2d(x**2 + y**2, mask=island)
        >>> int(np.isnan(lap).sum()), float(np.nanmax(np.abs(lap - 4.0)))
        (1, 0.0)
    """
    reject_geotensor(f, "adaptive_laplacian_2d")
    reject_geotensor(mask, "adaptive_laplacian_2d")
    d_xx = adaptive_difference(
        f,
        mask=mask,
        axis=-1,
        step=dx,
        derivative=2,
        accuracy=accuracy,
        periodic=periodic_x,
    )
    return d_xx + adaptive_difference(
        f, mask=mask, axis=-2, step=dy, derivative=2, accuracy=accuracy
    )

adaptive_laplacian_3d(f, dz=1.0, dy=1.0, dx=1.0, *, z=None, mask=None, accuracy=1, periodic_x=False)

Mask-aware 3-D Laplacian: :func:adaptive_difference of order 2 per axis.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch d h w']

The field, levels, rows and columns last.

required
dz Float[ndarray, 'd h w'] | float

The step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions; replaces dz.

None
mask Bool[ndarray, '*batch d h w'] | None

True drops the cell; None drops only non-finite cells.

None
accuracy int

The highest accuracy order to try.

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch d h w']

The Laplacian, f's shape; a quadratic stays exact next to the mask.

Example

z, y, x = np.mgrid[0:7, 0:7, 0:8].astype(float) rock = (z == 3) & (y == 3) & (x == 4) lap = adaptive_laplacian_3d(x2 + y2 + z**2, mask=rock) int(np.isnan(lap).sum()), float(np.nanmax(np.abs(lap - 6.0))) (1, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def adaptive_laplacian_3d(
    f: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    mask: Bool[np.ndarray, "*batch d h w"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch d h w"]:
    """Mask-aware 3-D Laplacian: :func:`adaptive_difference` of order 2 per axis.

    Args:
        f: The field, levels, rows and columns last.
        dz: The step between level centres.
        dy: The step between row centres.
        dx: The step between column centres.
        z: The level centres' positions; replaces ``dz``.
        mask: ``True`` drops the cell; ``None`` drops only non-finite cells.
        accuracy: The highest accuracy order to try.
        periodic_x: The columns wrap.

    Returns:
        The Laplacian, ``f``'s shape; a quadratic stays exact next to the mask.

    Example:
        >>> z, y, x = np.mgrid[0:7, 0:7, 0:8].astype(float)
        >>> rock = (z == 3) & (y == 3) & (x == 4)
        >>> lap = adaptive_laplacian_3d(x**2 + y**2 + z**2, mask=rock)
        >>> int(np.isnan(lap).sum()), float(np.nanmax(np.abs(lap - 6.0)))
        (1, 0.0)
    """
    reject_geotensor(f, "adaptive_laplacian_3d")
    reject_geotensor(mask, "adaptive_laplacian_3d")
    kw = {"mask": mask, "derivative": 2, "accuracy": accuracy}
    return (
        adaptive_difference(f, axis=-1, step=dx, periodic=periodic_x, **kw)
        + adaptive_difference(f, axis=-2, step=dy, **kw)
        + adaptive_difference(f, axis=-3, step=dz, coords=z, **kw)
    )

curl_2d(u, v, dy=1.0, dx=1.0, *, accuracy=1, periodic_x=False)

Curl2D (relative vorticity) ∂v/∂x − ∂u/∂y over the last two axes.

.. math::

\zeta = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y}

A NaN propagates through the stencils that read it.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch h w']

The component along columns, rows and columns last.

required
v Float[ndarray, '*batch h w']

The component along rows, on u's shape.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres, a scalar or (H, W).

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres, a scalar or (H, W).

1.0
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap (a global longitude).

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The curl, u's shape.

Examples:

>>> y, x = np.mgrid[0:4, 0:5].astype(float)
>>> float(curl_2d(-y, x).min()), float(curl_2d(-y, x).max())  # solid-body rotation
(2.0, 2.0)
>>> float(np.abs(curl_2d(x, y)).max())  # an irrotational expansion
0.0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def curl_2d(
    u: Float[np.ndarray, "*batch h w"],
    v: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    r"""Curl2D (relative vorticity) ``∂v/∂x − ∂u/∂y`` over the last two axes.

    .. math::

        \zeta = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y}

    A NaN propagates through the stencils that read it.

    Args:
        u: The component along columns, rows and columns last.
        v: The component along rows, on ``u``'s shape.
        dy: The signed step between row centres, a scalar or ``(H, W)``.
        dx: The signed step between column centres, a scalar or ``(H, W)``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap (a global longitude).

    Returns:
        The curl, ``u``'s shape.

    Examples:
        >>> y, x = np.mgrid[0:4, 0:5].astype(float)
        >>> float(curl_2d(-y, x).min()), float(curl_2d(-y, x).max())  # solid-body rotation
        (2.0, 2.0)
        >>> float(np.abs(curl_2d(x, y)).max())  # an irrotational expansion
        0.0
    """
    reject_geotensor(u, "curl_2d")
    reject_geotensor(v, "curl_2d")
    d_v = difference(v, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x)
    return d_v - difference(u, axis=-2, step=dy, accuracy=accuracy)

curl_3d(u, v, w, dz=1.0, dy=1.0, dx=1.0, *, z=None, accuracy=1, periodic_x=False)

Curl (vorticity vector) over the last three axes; a NaN propagates.

.. math::

\boldsymbol{\omega} = \nabla \times \mathbf{u}, \quad
\omega_z = \partial_x v - \partial_y u, \;
\omega_y = \partial_z u - \partial_x w, \;
\omega_x = \partial_y w - \partial_z v

Components in axis order, (ω_z, ω_y, ω_x), as :func:gradient_3d. The curl is right-handed in (x, y, z) with z the level coordinate as stored and w along increasing z: on a positive="down" axis (depth, pressure) that system is left-handed, so ω_y and ω_x have the opposite sign of the curl in upward height.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch d h w']

The component along columns.

required
v Float[ndarray, '*batch d h w']

The component along rows.

required
w Float[ndarray, '*batch d h w']

The component along levels.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions for uneven levels; replaces dz.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '3 *batch d h w']

(ω_z, ω_y, ω_x) stacked on a new leading axis.

Example

z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float) zeta_z, zeta_y, zeta_x = curl_3d(-y, x, 0.0 * z) # rotation about z float(zeta_z.min()), float(np.abs(zeta_y).max()), float(np.abs(zeta_x).max()) (2.0, 0.0, 0.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def curl_3d(
    u: Float[np.ndarray, "*batch d h w"],
    v: Float[np.ndarray, "*batch d h w"],
    w: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "3 *batch d h w"]:
    r"""Curl (vorticity vector) over the last three axes; a NaN propagates.

    .. math::

        \boldsymbol{\omega} = \nabla \times \mathbf{u}, \quad
        \omega_z = \partial_x v - \partial_y u, \;
        \omega_y = \partial_z u - \partial_x w, \;
        \omega_x = \partial_y w - \partial_z v

    Components in axis order, ``(ω_z, ω_y, ω_x)``, as :func:`gradient_3d`.
    The curl is right-handed in ``(x, y, z)`` with ``z`` the level
    coordinate as stored and ``w`` along increasing ``z``: on a
    ``positive="down"`` axis (depth, pressure) that system is left-handed, so
    ``ω_y`` and ``ω_x`` have the opposite sign of the curl in upward height.

    Args:
        u: The component along columns.
        v: The component along rows.
        w: The component along levels.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions for uneven levels; replaces ``dz``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap.

    Returns:
        ``(ω_z, ω_y, ω_x)`` stacked on a new leading axis.

    Example:
        >>> z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float)
        >>> zeta_z, zeta_y, zeta_x = curl_3d(-y, x, 0.0 * z)  # rotation about z
        >>> float(zeta_z.min()), float(np.abs(zeta_y).max()), float(np.abs(zeta_x).max())
        (2.0, 0.0, 0.0)
    """
    for c in (u, v, w):
        reject_geotensor(c, "curl_3d")
    xp = array_namespace(u)
    kw = {"accuracy": accuracy}
    d_x = functools.partial(difference, axis=-1, step=dx, periodic=periodic_x, **kw)
    d_y = functools.partial(difference, axis=-2, step=dy, **kw)
    d_z = functools.partial(difference, axis=-3, step=dz, coords=z, **kw)
    return xp.stack([d_x(v) - d_y(u), d_z(u) - d_x(w), d_y(w) - d_z(v)])

difference(f, *, axis=-1, step=1.0, coords=None, derivative=1, accuracy=1, method='central', periodic=False)

Finite-difference derivative along one axis; a NaN propagates.

The plain stencil, finitediffx's difference on any backend: with method="central" the centred stencil of order accuracy + 1 inside and forward / backward stencils of order accuracy on the edges, nothing wrapping around (accuracy=1 is numpy.gradient's scheme). "forward" / "backward" use that stencil everywhere it fits and the other one-sided stencil where it does not.

A stencil that reads a NaN returns NaN, so a masked cell costs a halo of about accuracy cells; :func:adaptive_difference recovers them.

.. math::

\partial^n_s f(x_i) \approx h^{-n} \sum_k c_k\, f(x_{i + s_k})

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
axis int

The axis to differentiate.

-1
step Float[ndarray, '*shape'] | float

The signed step :math:h between centres along axis: a scalar, or an array broadcasting against f.

1.0
coords Float[ndarray, ' n'] | None

The positions of the centres along axis, one per entry, for an unevenly spaced axis (depth or pressure levels, irregular times); replaces step. Each point's stencil is then solved for its actual distances (nonuniform_coeffs), exact for polynomials of the stencil's degree.

None
derivative int

The derivative order :math:n.

1
accuracy int

The accuracy order of the one-sided stencils.

1
method Method

"central", "forward" or "backward".

'central'
periodic bool

The axis wraps (a global longitude): every point uses the method stencil, reading across the seam. Not with coords.

False

Returns:

Type Description
Float[ndarray, '*shape']

math:\partial^n f / \partial s^n, f's shape.

Raises:

Type Description
ValueError

The axis is shorter than the stencil needs, coords has the wrong length, or coords meets periodic.

Examples:

>>> f = np.array([0.0, 1.0, 4.0, 9.0, 16.0])  # x², x = 0…4
>>> difference(f)
array([1., 2., 4., 6., 7.])
>>> difference(f, accuracy=2)
array([0., 2., 4., 6., 8.])
>>> difference(f, derivative=2)
array([2., 2., 2., 2., 2.])
>>> z = np.array([0.0, 1.0, 3.0, 7.0, 15.0])  # uneven levels
>>> difference(z**2, coords=z, derivative=2)  # exact for a quadratic
array([2., 2., 2., 2., 2.])
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def difference(
    f: Float[np.ndarray, "*shape"],
    *,
    axis: int = -1,
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    coords: Float[np.ndarray, " n"] | None = None,
    derivative: int = 1,
    accuracy: int = 1,
    method: Method = "central",
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    r"""Finite-difference derivative along one axis; a NaN propagates.

    The plain stencil, finitediffx's ``difference`` on any backend: with
    ``method="central"`` the centred stencil of order ``accuracy + 1`` inside
    and forward / backward stencils of order ``accuracy`` on the edges,
    nothing wrapping around (``accuracy=1`` is ``numpy.gradient``'s
    scheme). ``"forward"`` / ``"backward"`` use that stencil everywhere it
    fits and the other one-sided stencil where it does not.

    A stencil that reads a NaN returns NaN, so a masked cell costs a halo of
    about ``accuracy`` cells; :func:`adaptive_difference` recovers them.

    .. math::

        \partial^n_s f(x_i) \approx h^{-n} \sum_k c_k\, f(x_{i + s_k})

    Args:
        f: The field; any shape.
        axis: The axis to differentiate.
        step: The signed step :math:`h` between centres along ``axis``: a
            scalar, or an array broadcasting against ``f``.
        coords: The positions of the centres along ``axis``, one per entry,
            for an unevenly spaced axis (depth or pressure levels, irregular
            times); replaces ``step``. Each point's stencil is then solved for
            its actual distances (`nonuniform_coeffs`), exact for polynomials
            of the stencil's degree.
        derivative: The derivative order :math:`n`.
        accuracy: The accuracy order of the one-sided stencils.
        method: ``"central"``, ``"forward"`` or ``"backward"``.
        periodic: The axis wraps (a global longitude): every point uses the
            ``method`` stencil, reading across the seam. Not with ``coords``.

    Returns:
        :math:`\partial^n f / \partial s^n`, ``f``'s shape.

    Raises:
        ValueError: The axis is shorter than the stencil needs, ``coords`` has
            the wrong length, or ``coords`` meets ``periodic``.

    Examples:
        >>> f = np.array([0.0, 1.0, 4.0, 9.0, 16.0])  # x², x = 0…4
        >>> difference(f)
        array([1., 2., 4., 6., 7.])
        >>> difference(f, accuracy=2)
        array([0., 2., 4., 6., 8.])
        >>> difference(f, derivative=2)
        array([2., 2., 2., 2., 2.])
        >>> z = np.array([0.0, 1.0, 3.0, 7.0, 15.0])  # uneven levels
        >>> difference(z**2, coords=z, derivative=2)  # exact for a quadratic
        array([2., 2., 2., 2., 2.])
    """
    reject_geotensor(f, "difference")
    xp = array_namespace(f)
    axis = axis % f.ndim
    if coords is not None:
        if periodic:
            raise ValueError("difference: coords= does not combine with periodic=True")
        if coords.shape != (f.shape[axis],):
            raise ValueError(
                f"difference: coords has shape {tuple(coords.shape)}; the axis has "
                f"{f.shape[axis]} entries"
            )
        return _bounded(xp, f, axis, derivative, accuracy, method, coords)
    if periodic:
        out = _periodic(xp, f, axis, derivative, accuracy, method)
    else:
        out = _bounded(xp, f, axis, derivative, accuracy, method)
    return out / step**derivative

difference_coeffs(offsets, derivative=1) cached

The coefficients of a stencil on offsets, from the Taylor conditions.

Solves :math:\sum_k c_k s_k^m = n!\,\delta_{mn} for :math:m = 0, \dots, K - 1 in float64.

Parameters:

Name Type Description Default
offsets tuple[int, ...]

The stencil's integer offsets, distinct.

required
derivative int

The derivative order; fewer than derivative + 1 offsets cannot resolve it.

1

Returns:

Type Description
One coefficient per offset;

math:`f^{(n)}(x) \approx h^{-n} \sum_k

...

c_k f(x + s_k h)`.

Raises:

Type Description
ValueError

Too few offsets for the derivative.

Examples:

>>> difference_coeffs((-1, 0, 1), derivative=2)
(1.0, -2.0, 1.0)
>>> [round(c, 6) for c in difference_coeffs((0, 1, 2), derivative=1)]
[-1.5, 2.0, -0.5]
Source code in packages/geotoolz-ops/src/geoops/geom/_src/stencils.py
@functools.lru_cache(maxsize=256)
def difference_coeffs(
    offsets: tuple[int, ...], derivative: int = 1
) -> tuple[float, ...]:
    r"""The coefficients of a stencil on ``offsets``, from the Taylor conditions.

    Solves :math:`\sum_k c_k s_k^m = n!\,\delta_{mn}` for
    :math:`m = 0, \dots, K - 1` in float64.

    Args:
        offsets: The stencil's integer offsets, distinct.
        derivative: The derivative order; fewer than ``derivative + 1``
            offsets cannot resolve it.

    Returns:
        One coefficient per offset; :math:`f^{(n)}(x) \approx h^{-n} \sum_k
        c_k f(x + s_k h)`.

    Raises:
        ValueError: Too few offsets for the derivative.

    Examples:
        >>> difference_coeffs((-1, 0, 1), derivative=2)
        (1.0, -2.0, 1.0)
        >>> [round(c, 6) for c in difference_coeffs((0, 1, 2), derivative=1)]
        [-1.5, 2.0, -0.5]
    """
    n = len(offsets)
    if derivative >= n:
        raise ValueError(
            f"{n} offsets cannot resolve derivative {derivative}; need at least "
            f"{derivative + 1}"
        )
    powers = np.vander(np.asarray(offsets, dtype=np.float64), n, increasing=True).T
    rhs = np.zeros(n)
    rhs[derivative] = math.factorial(derivative)
    coeffs = np.linalg.solve(powers, rhs)
    # round off solver noise so exact stencils stay exact (0.5, not 0.4999…)
    return tuple(float(c) for c in np.round(coeffs, 12) + 0.0)

difference_offsets(*, derivative=1, accuracy=1, method='central') cached

The offsets of one stencil, finitediffx's rules.

Parameters:

Name Type Description Default
derivative int

The derivative order, at least 1.

1
accuracy int

The accuracy order, at least 1. A central stencil is built at accuracy + 1, the order its symmetry gives for free.

1
method Method

"central", "forward" or "backward".

'central'

Returns:

Type Description
tuple[int, ...]

The integer offsets, ascending.

Raises:

Type Description
ValueError

An order below 1, or an unknown method.

Examples:

>>> difference_offsets(derivative=1, accuracy=2, method="forward")
(0, 1, 2)
>>> difference_offsets(derivative=2, accuracy=1, method="central")
(-1, 0, 1)
Source code in packages/geotoolz-ops/src/geoops/geom/_src/stencils.py
@functools.lru_cache(maxsize=256)
def difference_offsets(
    *, derivative: int = 1, accuracy: int = 1, method: Method = "central"
) -> tuple[int, ...]:
    """The offsets of one stencil, finitediffx's rules.

    Args:
        derivative: The derivative order, at least 1.
        accuracy: The accuracy order, at least 1. A central stencil is built
            at ``accuracy + 1``, the order its symmetry gives for free.
        method: ``"central"``, ``"forward"`` or ``"backward"``.

    Returns:
        The integer offsets, ascending.

    Raises:
        ValueError: An order below 1, or an unknown method.

    Examples:
        >>> difference_offsets(derivative=1, accuracy=2, method="forward")
        (0, 1, 2)
        >>> difference_offsets(derivative=2, accuracy=1, method="central")
        (-1, 0, 1)
    """
    if derivative < 1 or accuracy < 1:
        raise ValueError(
            f"derivative and accuracy must be at least 1; got {derivative}, {accuracy}"
        )
    if method == "forward":
        return tuple(range(derivative + accuracy))
    if method == "backward":
        return tuple(range(-(derivative + accuracy - 1), 1))
    if method == "central":
        half = (derivative + accuracy) // 2
        return tuple(range(-half, half + 1))
    raise ValueError(f"method must be one of {METHODS}; got {method!r}")

divergence_1d(u, step=1.0, *, axis=-1, coords=None, accuracy=1, periodic=False)

The 1-D divergence ∂u/∂s of a flux along one axis; a NaN propagates.

In one dimension the divergence of a flux is its derivative, so this is :func:gradient_1d read as a conservation term (∂F/∂z of a vertical flux, ∂q/∂x along a channel).

Parameters:

Name Type Description Default
u Float[ndarray, '*shape']

The flux component along axis.

required
step Float[ndarray, '*shape'] | float

The signed step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis; replaces step.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

math:\partial u / \partial s, u's shape.

Example

divergence_1d(np.array([0.0, 1.0, 4.0, 9.0])) # u = s², s = 0…3 array([1., 2., 4., 5.])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def divergence_1d(
    u: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    r"""The 1-D divergence ``∂u/∂s`` of a flux along one axis; a NaN propagates.

    In one dimension the divergence of a flux is its derivative, so this is
    :func:`gradient_1d` read as a conservation term (``∂F/∂z`` of a vertical
    flux, ``∂q/∂x`` along a channel).

    Args:
        u: The flux component along ``axis``.
        step: The signed step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis``; replaces ``step``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic: The axis wraps.

    Returns:
        :math:`\partial u / \partial s`, ``u``'s shape.

    Example:
        >>> divergence_1d(np.array([0.0, 1.0, 4.0, 9.0]))  # u = s², s = 0…3
        array([1., 2., 4., 5.])
    """
    reject_geotensor(u, "divergence_1d")
    return difference(
        u, axis=axis, step=step, coords=coords, accuracy=accuracy, periodic=periodic
    )

divergence_2d(u, v, dy=1.0, dx=1.0, *, accuracy=1, periodic_x=False)

Divergence ∂u/∂x + ∂v/∂y over the last two axes; a NaN propagates.

.. math::

\nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
                        + \frac{\partial v}{\partial y}

:func:difference of u along columns (axis=-1, step dx) plus that of v along rows (axis=-2, step dy), so a uniform-grid field needs no carrier.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch h w']

The component along columns, rows and columns last.

required
v Float[ndarray, '*batch h w']

The component along rows, on u's shape.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres, a scalar or (H, W).

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres, a scalar or (H, W).

1.0
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap (a global longitude).

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The divergence, u's shape.

Examples:

>>> y, x = np.mgrid[0:4, 0:5].astype(float)
>>> float(np.abs(divergence_2d(-y, x)).max())  # solid-body rotation
0.0
>>> float(divergence_2d(x, y).min())  # a uniform expansion
2.0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def divergence_2d(
    u: Float[np.ndarray, "*batch h w"],
    v: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    r"""Divergence ``∂u/∂x + ∂v/∂y`` over the last two axes; a NaN propagates.

    .. math::

        \nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
                                + \frac{\partial v}{\partial y}

    :func:`difference` of ``u`` along columns (``axis=-1``, step ``dx``) plus
    that of ``v`` along rows (``axis=-2``, step ``dy``), so a uniform-grid
    field needs no carrier.

    Args:
        u: The component along columns, rows and columns last.
        v: The component along rows, on ``u``'s shape.
        dy: The signed step between row centres, a scalar or ``(H, W)``.
        dx: The signed step between column centres, a scalar or ``(H, W)``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap (a global longitude).

    Returns:
        The divergence, ``u``'s shape.

    Examples:
        >>> y, x = np.mgrid[0:4, 0:5].astype(float)
        >>> float(np.abs(divergence_2d(-y, x)).max())  # solid-body rotation
        0.0
        >>> float(divergence_2d(x, y).min())  # a uniform expansion
        2.0
    """
    reject_geotensor(u, "divergence_2d")
    reject_geotensor(v, "divergence_2d")
    d_u = difference(u, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x)
    return d_u + difference(v, axis=-2, step=dy, accuracy=accuracy)

divergence_3d(u, v, w, dz=1.0, dy=1.0, dx=1.0, *, z=None, accuracy=1, periodic_x=False)

Divergence ∂u/∂x + ∂v/∂y + ∂w/∂z over the last three axes.

.. math::

\nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
  + \frac{\partial v}{\partial y} + \frac{\partial w}{\partial z}

w is the component along increasing z (the level coordinate as stored), so on pressure levels this is the pressure-coordinate divergence with :math:\omega in w. A NaN propagates.

Parameters:

Name Type Description Default
u Float[ndarray, '*batch d h w']

The component along columns.

required
v Float[ndarray, '*batch d h w']

The component along rows.

required
w Float[ndarray, '*batch d h w']

The component along levels.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions for uneven levels; replaces dz.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch d h w']

The divergence, u's shape.

Example

z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float) float(divergence_3d(x, y, -2.0 * z).max()) # incompressible 0.0

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def divergence_3d(
    u: Float[np.ndarray, "*batch d h w"],
    v: Float[np.ndarray, "*batch d h w"],
    w: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch d h w"]:
    r"""Divergence ``∂u/∂x + ∂v/∂y + ∂w/∂z`` over the last three axes.

    .. math::

        \nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x}
          + \frac{\partial v}{\partial y} + \frac{\partial w}{\partial z}

    ``w`` is the component along increasing ``z`` (the level coordinate as
    stored), so on pressure levels this is the pressure-coordinate divergence
    with :math:`\omega` in ``w``. A NaN propagates.

    Args:
        u: The component along columns.
        v: The component along rows.
        w: The component along levels.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions for uneven levels; replaces ``dz``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap.

    Returns:
        The divergence, ``u``'s shape.

    Example:
        >>> z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float)
        >>> float(divergence_3d(x, y, -2.0 * z).max())  # incompressible
        0.0
    """
    for c in (u, v, w):
        reject_geotensor(c, "divergence_3d")
    kw = {"accuracy": accuracy}
    return (
        difference(u, axis=-1, step=dx, periodic=periodic_x, **kw)
        + difference(v, axis=-2, step=dy, **kw)
        + difference(w, axis=-3, step=dz, coords=z, **kw)
    )

gradient_1d(f, step=1.0, *, axis=-1, coords=None, accuracy=1, periodic=False)

∂f/∂s along one axis; a NaN propagates.

:func:difference of first order, named for the calculus family.

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
step Float[ndarray, '*shape'] | float

The signed step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis for an unevenly spaced axis (depth or pressure levels, irregular times); replaces step.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

math:\partial f / \partial s, f's shape.

Examples:

>>> gradient_1d(np.array([0.0, 2.0, 4.0, 6.0]), 2.0)
array([1., 1., 1., 1.])
>>> z = np.array([0.0, 10.0, 30.0, 70.0])  # uneven levels
>>> gradient_1d(3.0 * z, coords=z)
array([3., 3., 3., 3.])
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def gradient_1d(
    f: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    r"""``∂f/∂s`` along one axis; a NaN propagates.

    :func:`difference` of first order, named for the calculus family.

    Args:
        f: The field; any shape.
        step: The signed step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis`` for an unevenly spaced
            axis (depth or pressure levels, irregular times); replaces ``step``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic: The axis wraps.

    Returns:
        :math:`\partial f / \partial s`, ``f``'s shape.

    Examples:
        >>> gradient_1d(np.array([0.0, 2.0, 4.0, 6.0]), 2.0)
        array([1., 1., 1., 1.])
        >>> z = np.array([0.0, 10.0, 30.0, 70.0])  # uneven levels
        >>> gradient_1d(3.0 * z, coords=z)
        array([3., 3., 3., 3.])
    """
    reject_geotensor(f, "gradient_1d")
    return difference(
        f, axis=axis, step=step, coords=coords, accuracy=accuracy, periodic=periodic
    )

gradient_2d(f, dy=1.0, dx=1.0, *, accuracy=1, periodic_x=False)

(∂f/∂y, ∂f/∂x) over the last two axes; a NaN propagates.

:func:difference along rows (axis=-2, step dy) and columns (axis=-1, step dx). At accuracy=1: second-order centred differences inside, first-order one-sided on the edges, exact for a linear field everywhere.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch h w']

The field, rows and columns last; leading axes are mapped.

required
dy Float[ndarray, 'h w'] | float

The signed step between row centres, a scalar or (H, W).

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres, a scalar or (H, W).

1.0
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap (a global longitude).

False

Returns:

Type Description
Float[ndarray, '2 *batch h w']

(∂f/∂y, ∂f/∂x) stacked on a new leading axis.

Example

y, x = np.mgrid[0:3, 0:4].astype(float) d_y, d_x = gradient_2d(2.0 * y + 3.0 * x) float(d_y.min()), float(d_y.max()), float(d_x.min()), float(d_x.max()) (2.0, 2.0, 3.0, 3.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def gradient_2d(
    f: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "2 *batch h w"]:
    r"""``(∂f/∂y, ∂f/∂x)`` over the last two axes; a NaN propagates.

    :func:`difference` along rows (``axis=-2``, step ``dy``) and columns
    (``axis=-1``, step ``dx``). At ``accuracy=1``: second-order centred
    differences inside, first-order one-sided on the edges, exact for a
    linear field everywhere.

    Args:
        f: The field, rows and columns last; leading axes are mapped.
        dy: The signed step between row centres, a scalar or ``(H, W)``.
        dx: The signed step between column centres, a scalar or ``(H, W)``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap (a global longitude).

    Returns:
        ``(∂f/∂y, ∂f/∂x)`` stacked on a new leading axis.

    Example:
        >>> y, x = np.mgrid[0:3, 0:4].astype(float)
        >>> d_y, d_x = gradient_2d(2.0 * y + 3.0 * x)
        >>> float(d_y.min()), float(d_y.max()), float(d_x.min()), float(d_x.max())
        (2.0, 2.0, 3.0, 3.0)
    """
    reject_geotensor(f, "gradient_2d")
    xp = array_namespace(f)
    d_y = difference(f, axis=-2, step=dy, accuracy=accuracy)
    d_x = difference(f, axis=-1, step=dx, accuracy=accuracy, periodic=periodic_x)
    return xp.stack([d_y, d_x])

gradient_3d(f, dz=1.0, dy=1.0, dx=1.0, *, z=None, accuracy=1, periodic_x=False)

(∂f/∂z, ∂f/∂y, ∂f/∂x) over the last three axes; a NaN propagates.

The components follow the axes, levels (axis=-3) then rows then columns, as :func:gradient_2d gives rows then columns.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch d h w']

The field, levels, rows and columns last.

required
dz Float[ndarray, 'd h w'] | float

The signed step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The signed step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The signed step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions for uneven levels; replaces dz.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap (a global longitude).

False

Returns:

Type Description
Float[ndarray, '3 *batch d h w']

(∂f/∂z, ∂f/∂y, ∂f/∂x) stacked on a new leading axis.

Example

z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float) tuple(float(d.max()) for d in gradient_3d(4.0 * z + 2.0 * y + x)) (4.0, 2.0, 1.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def gradient_3d(
    f: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "3 *batch d h w"]:
    r"""``(∂f/∂z, ∂f/∂y, ∂f/∂x)`` over the last three axes; a NaN propagates.

    The components follow the axes, levels (``axis=-3``) then rows then
    columns, as :func:`gradient_2d` gives rows then columns.

    Args:
        f: The field, levels, rows and columns last.
        dz: The signed step between level centres.
        dy: The signed step between row centres.
        dx: The signed step between column centres.
        z: The level centres' positions for uneven levels; replaces ``dz``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap (a global longitude).

    Returns:
        ``(∂f/∂z, ∂f/∂y, ∂f/∂x)`` stacked on a new leading axis.

    Example:
        >>> z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float)
        >>> tuple(float(d.max()) for d in gradient_3d(4.0 * z + 2.0 * y + x))
        (4.0, 2.0, 1.0)
    """
    reject_geotensor(f, "gradient_3d")
    xp = array_namespace(f)
    kw = {"accuracy": accuracy}
    d_z = difference(f, axis=-3, step=dz, coords=z, **kw)
    d_y = difference(f, axis=-2, step=dy, **kw)
    d_x = difference(f, axis=-1, step=dx, periodic=periodic_x, **kw)
    return xp.stack([d_z, d_y, d_x])

interp_at(grid, points, method='bilinear', *, frame=None, along='time')

H(x): grid read at the positions of points.

The read-out is a functax plan on the grid (functax.interp.Linear or Nearest). A point is inside when its fractional pixel position lies in [−½, R − ½] × [−½, C − ½] (extent="cells"), and taps past the last row or column read the edge pixel (boundary="edge"), so the half pixel at the border takes the edge value. Nearest-neighbour ties (a position exactly half way between two pixel centres) go to the lower pixel, as functax's Nearest does. A point outside the grid's extent, at a non-finite position, or reading a nodata pixel (non-finite or the grid's fill, in any band, with a non-zero weight) gives NaN and valid=False; nodata never blends into a value. A padded point (valid=False on points) gives 0 and stays invalid, so a masked cost and its gradient are finite and unchanged by the padding (GA-G16). JAX points read a NumPy grid on JAX (a constant under jit), so the values can be differentiated with respect to the positions.

Parameters:

Name Type Description Default
grid GeoArray

A carrier (..., y, x); its leading dims stay, before obs.

required
points GeoPoints

Where to read, in grid's CRS.

required
method str

"bilinear" or "nearest".

'bilinear'
frame Any

Optional (obs,) integer index into along per point: each observation reads its own frame of a series (tracks over a GeoMapSeries); along is then dropped from the result.

None
along str

The dim frame indexes.

'time'

Returns:

Type Description
GeoPoints

A GeoPoints with points' leaves, valid combining the

GeoPoints

points' validity and being inside the grid, and the grid's leading

dims and coordinates

a (time, variable, y, x) stack sampled at

GeoPoints

stations is a GeoTimeSeries.

Raises:

Type Description
ValueError

The CRSs differ, the grid is batched, or method is unknown.

ImportError

functax's plans are missing (the [interp] extra).

Example

import numpy as np from geoarray import GeoArray, GeoPoints from geoops.geom import interp_at t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0) g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x") p = GeoPoints(np.zeros(2), xy=np.array([[0.5, 3.5], [9.0, 9.0]]), ... dims="obs", crs=None) out = interp_at(g, p) out.data.tolist(), out.valid.tolist() ([0.0, nan], [True, False])

Source code in packages/geotoolz-ops/src/geoops/geom/_src/sampling.py
def interp_at(
    grid: GeoArray,
    points: GeoPoints,
    method: str = "bilinear",
    *,
    frame: Any = None,
    along: str = "time",
) -> GeoPoints:
    """H(x): ``grid`` read at the positions of ``points``.

    The read-out is a functax plan on the grid (`functax.interp.Linear` or
    `Nearest`). A point is inside when its fractional pixel position lies in
    [−½, R − ½] × [−½, C − ½] (``extent="cells"``), and taps past the last
    row or column read the edge pixel (``boundary="edge"``), so the half
    pixel at the border takes the edge value. Nearest-neighbour ties (a
    position exactly half way between two pixel centres) go to the lower
    pixel, as functax's ``Nearest`` does. A point outside the grid's
    extent, at a non-finite position, or reading a nodata pixel (non-finite
    or the grid's fill, in any band, with a non-zero weight) gives NaN and
    ``valid=False``; nodata never blends into a value. A padded point
    (``valid=False`` on ``points``) gives 0 and stays invalid, so a masked
    cost and its gradient are finite and unchanged by the padding (GA-G16).
    JAX points read a NumPy grid on JAX (a constant under ``jit``), so the
    values can be differentiated with respect to the positions.

    Args:
        grid: A carrier ``(..., y, x)``; its leading dims stay, before ``obs``.
        points: Where to read, in ``grid``'s CRS.
        method: ``"bilinear"`` or ``"nearest"``.
        frame: Optional ``(obs,)`` integer index into ``along`` per point:
            each observation reads its own frame of a series (tracks over a
            ``GeoMapSeries``); ``along`` is then dropped from the result.
        along: The dim ``frame`` indexes.

    Returns:
        A `GeoPoints` with ``points``' leaves, ``valid`` combining the
        points' validity and being inside the grid, and the grid's leading
        dims and coordinates: a ``(time, variable, y, x)`` stack sampled at
        stations is a ``GeoTimeSeries``.

    Raises:
        ValueError: The CRSs differ, the grid is batched, or ``method`` is
            unknown.
        ImportError: functax's plans are missing (the ``[interp]`` extra).

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray, GeoPoints
        >>> from geoops.geom import interp_at
        >>> t = (1.0, 0.0, 0.0, 0.0, -1.0, 4.0)
        >>> g = GeoArray(np.arange(16.0).reshape(4, 4), t, None, dims="y x")
        >>> p = GeoPoints(np.zeros(2), xy=np.array([[0.5, 3.5], [9.0, 9.0]]),
        ...               dims="obs", crs=None)
        >>> out = interp_at(g, p)
        >>> out.data.tolist(), out.valid.tolist()
        ([0.0, nan], [True, False])
    """
    check_args(grid, points, method)
    return interp_with_plan(grid, points, method, frame=frame, along=along)

laplacian_1d(f, step=1.0, *, axis=-1, coords=None, accuracy=1, periodic=False)

∂²f/∂s² along one axis, a second-derivative stencil; a NaN propagates.

Parameters:

Name Type Description Default
f Float[ndarray, '*shape']

The field; any shape.

required
step Float[ndarray, '*shape'] | float

The step between centres along axis.

1.0
axis int

The axis to differentiate.

-1
coords Float[ndarray, ' n'] | None

The centres' positions along axis; replaces step.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic bool

The axis wraps.

False

Returns:

Type Description
Float[ndarray, '*shape']

math:\partial^2 f / \partial s^2, f's shape.

Examples:

>>> laplacian_1d(np.array([0.0, 1.0, 4.0, 9.0]))  # f = s²
array([2., 2., 2., 2.])
>>> z = np.array([0.0, 5.0, 15.0, 30.0])  # uneven levels
>>> laplacian_1d(z**2, coords=z)
array([2., 2., 2., 2.])
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def laplacian_1d(
    f: Float[np.ndarray, "*shape"],
    step: Float[np.ndarray, "*shape"] | float = 1.0,
    *,
    axis: int = -1,
    coords: Float[np.ndarray, " n"] | None = None,
    accuracy: int = 1,
    periodic: bool = False,
) -> Float[np.ndarray, "*shape"]:
    r"""``∂²f/∂s²`` along one axis, a second-derivative stencil; a NaN propagates.

    Args:
        f: The field; any shape.
        step: The step between centres along ``axis``.
        axis: The axis to differentiate.
        coords: The centres' positions along ``axis``; replaces ``step``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic: The axis wraps.

    Returns:
        :math:`\partial^2 f / \partial s^2`, ``f``'s shape.

    Examples:
        >>> laplacian_1d(np.array([0.0, 1.0, 4.0, 9.0]))  # f = s²
        array([2., 2., 2., 2.])
        >>> z = np.array([0.0, 5.0, 15.0, 30.0])  # uneven levels
        >>> laplacian_1d(z**2, coords=z)
        array([2., 2., 2., 2.])
    """
    reject_geotensor(f, "laplacian_1d")
    return difference(
        f,
        axis=axis,
        step=step,
        coords=coords,
        derivative=2,
        accuracy=accuracy,
        periodic=periodic,
    )

laplacian_2d(f, dy=1.0, dx=1.0, *, accuracy=1, periodic_x=False)

Laplacian ∂²f/∂x² + ∂²f/∂y² over the last two axes; a NaN propagates.

.. math::

\nabla^2 f = \frac{\partial^2 f}{\partial x^2}
           + \frac{\partial^2 f}{\partial y^2}

Second-derivative stencils (derivative=2), not two first derivatives: the 3-point centred stencil inside and 3-point one-sided ones on the edges at accuracy=1, all exact for a quadratic.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch h w']

The field, rows and columns last; leading axes are mapped.

required
dy Float[ndarray, 'h w'] | float

The step between row centres, a scalar or (H, W).

1.0
dx Float[ndarray, 'h w'] | float

The step between column centres, a scalar or (H, W).

1.0
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap (a global longitude).

False

Returns:

Type Description
Float[ndarray, '*batch h w']

The Laplacian, f's shape.

Examples:

>>> y, x = np.mgrid[0:4, 0:5].astype(float)
>>> lap = laplacian_2d(x**2 + y**2)
>>> float(lap.min()), float(lap.max())  # exact, edges included
(4.0, 4.0)
>>> float(laplacian_2d(x**2, dx=0.5).max())  # steps in coordinate units
8.0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def laplacian_2d(
    f: Float[np.ndarray, "*batch h w"],
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch h w"]:
    r"""Laplacian ``∂²f/∂x² + ∂²f/∂y²`` over the last two axes; a NaN propagates.

    .. math::

        \nabla^2 f = \frac{\partial^2 f}{\partial x^2}
                   + \frac{\partial^2 f}{\partial y^2}

    Second-derivative stencils (``derivative=2``), not two first derivatives:
    the 3-point centred stencil inside and 3-point one-sided ones on the edges
    at ``accuracy=1``, all exact for a quadratic.

    Args:
        f: The field, rows and columns last; leading axes are mapped.
        dy: The step between row centres, a scalar or ``(H, W)``.
        dx: The step between column centres, a scalar or ``(H, W)``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap (a global longitude).

    Returns:
        The Laplacian, ``f``'s shape.

    Examples:
        >>> y, x = np.mgrid[0:4, 0:5].astype(float)
        >>> lap = laplacian_2d(x**2 + y**2)
        >>> float(lap.min()), float(lap.max())  # exact, edges included
        (4.0, 4.0)
        >>> float(laplacian_2d(x**2, dx=0.5).max())  # steps in coordinate units
        8.0
    """
    reject_geotensor(f, "laplacian_2d")
    d_xx = difference(
        f, axis=-1, step=dx, derivative=2, accuracy=accuracy, periodic=periodic_x
    )
    return d_xx + difference(f, axis=-2, step=dy, derivative=2, accuracy=accuracy)

laplacian_3d(f, dz=1.0, dy=1.0, dx=1.0, *, z=None, accuracy=1, periodic_x=False)

Laplacian ∂²f/∂x² + ∂²f/∂y² + ∂²f/∂z², second-derivative stencils.

Parameters:

Name Type Description Default
f Float[ndarray, '*batch d h w']

The field, levels, rows and columns last.

required
dz Float[ndarray, 'd h w'] | float

The step between level centres.

1.0
dy Float[ndarray, 'h w'] | float

The step between row centres.

1.0
dx Float[ndarray, 'h w'] | float

The step between column centres.

1.0
z Float[ndarray, ' d'] | None

The level centres' positions for uneven levels; replaces dz.

None
accuracy int

The accuracy order (see :func:difference).

1
periodic_x bool

The columns wrap.

False

Returns:

Type Description
Float[ndarray, '*batch d h w']

The Laplacian, f's shape.

Example

z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float) lap = laplacian_3d(x2 + y2 + z**2) float(lap.min()), float(lap.max()) # exact, edges included (6.0, 6.0)

Source code in packages/geotoolz-ops/src/geoops/geom/_src/array.py
def laplacian_3d(
    f: Float[np.ndarray, "*batch d h w"],
    dz: Float[np.ndarray, "d h w"] | float = 1.0,
    dy: Float[np.ndarray, "h w"] | float = 1.0,
    dx: Float[np.ndarray, "h w"] | float = 1.0,
    *,
    z: Float[np.ndarray, " d"] | None = None,
    accuracy: int = 1,
    periodic_x: bool = False,
) -> Float[np.ndarray, "*batch d h w"]:
    r"""Laplacian ``∂²f/∂x² + ∂²f/∂y² + ∂²f/∂z²``, second-derivative stencils.

    Args:
        f: The field, levels, rows and columns last.
        dz: The step between level centres.
        dy: The step between row centres.
        dx: The step between column centres.
        z: The level centres' positions for uneven levels; replaces ``dz``.
        accuracy: The accuracy order (see :func:`difference`).
        periodic_x: The columns wrap.

    Returns:
        The Laplacian, ``f``'s shape.

    Example:
        >>> z, y, x = np.mgrid[0:3, 0:4, 0:5].astype(float)
        >>> lap = laplacian_3d(x**2 + y**2 + z**2)
        >>> float(lap.min()), float(lap.max())  # exact, edges included
        (6.0, 6.0)
    """
    reject_geotensor(f, "laplacian_3d")
    kw = {"derivative": 2, "accuracy": accuracy}
    return (
        difference(f, axis=-1, step=dx, periodic=periodic_x, **kw)
        + difference(f, axis=-2, step=dy, **kw)
        + difference(f, axis=-3, step=dz, coords=z, **kw)
    )

nonuniform_coeffs(dz, derivative=1)

Stencil coefficients for points at arbitrary distances, on any backend.

The non-uniform form of :func:difference_coeffs: for each point, the weights :math:c_k with :math:f^{(n)}(z) \approx \sum_k c_k f(z + \delta_k) solve the Taylor conditions :math:\sum_k c_k \delta_k^m / m! = \delta_{mn} for :math:m = 0, \dots, K - 1, so the stencil is exact for polynomials of degree :math:K - 1. Each row is solved in units of its own widest distance, which keeps the system well conditioned for coordinates in metres or pascals. Written on the array namespace, so traced distances (a TimeAxis under jax.jit) work too.

Parameters:

Name Type Description Default
dz Any

(..., K) signed distances :math:\delta_k from each point to its stencil's points; one of them is 0.

required
derivative int

The derivative order :math:n, below K.

1

Returns:

Type Description
Any

(..., K) coefficients, in units of dz to the power -n.

Raises:

Type Description
ValueError

Too few points for the derivative.

Examples:

>>> nonuniform_coeffs(np.array([-1.0, 0.0, 1.0]))  # the uniform stencil
array([-0.5,  0. ,  0.5])
>>> # uneven levels at 0, 1 and 3 m: still exact for a quadratic
>>> c = nonuniform_coeffs(np.array([-1.0, 0.0, 2.0]), derivative=2)
>>> float(c @ np.array([-1.0, 0.0, 2.0]) ** 2)
2.0
Source code in packages/geotoolz-ops/src/geoops/geom/_src/stencils.py
def nonuniform_coeffs(dz: Any, derivative: int = 1) -> Any:
    r"""Stencil coefficients for points at arbitrary distances, on any backend.

    The non-uniform form of :func:`difference_coeffs`: for each point, the
    weights :math:`c_k` with :math:`f^{(n)}(z) \approx \sum_k c_k f(z + \delta_k)`
    solve the Taylor conditions :math:`\sum_k c_k \delta_k^m / m! = \delta_{mn}`
    for :math:`m = 0, \dots, K - 1`, so the stencil is exact for polynomials of
    degree :math:`K - 1`. Each row is solved in units of its own widest
    distance, which keeps the system well conditioned for coordinates in
    metres or pascals. Written on the array namespace, so traced distances
    (a ``TimeAxis`` under ``jax.jit``) work too.

    Args:
        dz: ``(..., K)`` signed distances :math:`\delta_k` from each point to
            its stencil's points; one of them is ``0``.
        derivative: The derivative order :math:`n`, below ``K``.

    Returns:
        ``(..., K)`` coefficients, in units of ``dz`` to the power ``-n``.

    Raises:
        ValueError: Too few points for the derivative.

    Examples:
        >>> nonuniform_coeffs(np.array([-1.0, 0.0, 1.0]))  # the uniform stencil
        array([-0.5,  0. ,  0.5])
        >>> # uneven levels at 0, 1 and 3 m: still exact for a quadratic
        >>> c = nonuniform_coeffs(np.array([-1.0, 0.0, 2.0]), derivative=2)
        >>> float(c @ np.array([-1.0, 0.0, 2.0]) ** 2)
        2.0
    """
    from pipekit_array import array_namespace

    xp = array_namespace(dz)
    n_points = dz.shape[-1]
    if derivative >= n_points:
        raise ValueError(
            f"{n_points} points cannot resolve derivative {derivative}; need at "
            f"least {derivative + 1}"
        )
    scale = xp.max(xp.abs(dz), axis=-1, keepdims=True)
    unit = dz / scale
    # A[..., m, k] = δ_k^m / m!, in units of the row's widest distance
    powers = xp.stack([unit**m / math.factorial(m) for m in range(n_points)], axis=-2)
    rhs = xp.zeros((*dz.shape[:-1], n_points), dtype=unit.dtype)
    rhs = xp.where(xp.arange(n_points) == derivative, 1.0, rhs)
    coeffs = xp.linalg.solve(powers, rhs[..., None])[..., 0]
    return coeffs / scale**derivative

Coregistration

geom.coregister aligns one source onto another's support — the coregistration callables for geopatcher.matched.MatchedField: RasterToRasterLike, RasterToPoints / PointsToRaster ([vector-cube] extra), RasterToPointCloud / PointCloudToRaster, VectorToRasterAgg, and SwathToGrid(target=grid), which grids a GeoSwath onto a geoarray.Grid (pass raster.grid to match a raster). The IDW and nearest paths run on functax plans ([interp] extra).

geoops.geom.coregister

geoops.geom.coregister — cross-modality coregistration operators.

Public re-exports of the operators implemented in geoops.geom._src.coregister. The subnamespace lives under geom because these are genuine geometric operations — the same module that owns Reproject / Resample / Rasterize. Like every public operator, each is also re-exported at the top level (gz.RasterToRasterLike, ...).

See docs/catalog/design/query-matchup.md §5.

PointCloudToRaster

Bases: Operator

Rasterize a point cloud onto a target grid.

Numpy-first counterpart to PointsToRaster. The cloud input is a tuple (xy_array, values_array) so callers don't need to wrap their raw arrays in a GeoDataFrame.

Geo-dependent: like must be a georeferenced GeoArray (its transform defines the target grid); plain arrays raise TypeError.

Parameters:

Name Type Description Default
method Literal['binned_stat', 'idw']

"binned_stat" (scipy binned_statistic_2d — fast, no smoothing) or "idw" (inverse-distance weighting of the k nearest points through functax.interp.InverseDistance, the [interp] extra; smoother but slower).

'binned_stat'
stat Literal['mean', 'median', 'sum', 'count', 'max', 'min']

For "binned_stat": one of "mean", "median", "sum", "count", "max", "min".

'mean'
power float

For "idw": inverse-distance exponent.

2.0
k int

For "idw": how many nearest points contribute to each pixel. Defaults to 8 (a reasonable balance between smoothness and locality).

8
max_radius float | None

For "idw": distance ceiling in CRS units. Pixels with no points within this radius receive NaN.

None
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class PointCloudToRaster(Operator):
    """Rasterize a point cloud onto a target grid.

    Numpy-first counterpart to `PointsToRaster`. The cloud input is
    a tuple ``(xy_array, values_array)`` so callers don't need to
    wrap their raw arrays in a GeoDataFrame.

    Geo-dependent: ``like`` must be a georeferenced ``GeoArray``
    (its transform defines the target grid); plain arrays raise
    ``TypeError``.

    Args:
        method: ``"binned_stat"`` (scipy ``binned_statistic_2d`` —
            fast, no smoothing) or ``"idw"`` (inverse-distance weighting
            of the ``k`` nearest points through
            ``functax.interp.InverseDistance``, the ``[interp]`` extra;
            smoother but slower).
        stat: For ``"binned_stat"``: one of ``"mean"``, ``"median"``,
            ``"sum"``, ``"count"``, ``"max"``, ``"min"``.
        power: For ``"idw"``: inverse-distance exponent.
        k: For ``"idw"``: how many nearest points contribute to each
            pixel. Defaults to 8 (a reasonable balance between
            smoothness and locality).
        max_radius: For ``"idw"``: distance ceiling in CRS units.
            Pixels with no points within this radius receive NaN.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # points binned or interpolated onto the grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        method: Literal["binned_stat", "idw"] = "binned_stat",
        stat: Literal["mean", "median", "sum", "count", "max", "min"] = "mean",
        power: float = 2.0,
        k: int = 8,
        max_radius: float | None = None,
    ) -> None:
        if method not in {"binned_stat", "idw"}:
            raise ValueError(
                f"PointCloudToRaster.method must be 'binned_stat' or 'idw'; "
                f"got {method!r}"
            )
        if k < 1:
            raise ValueError(f"k must be >= 1; got {k}")
        self.method = method
        self.stat = stat
        self.power = power
        self.k = k
        self.max_radius = max_radius

    def _apply(self, cloud: Any, like: GeoArray) -> GeoArray:
        require_geoarray(like, "PointCloudToRaster", arg="like")
        _require_axis_aligned(like, "PointCloudToRaster")
        xy, values = _cloud_to_xy_values(cloud)
        if self.method == "binned_stat":
            result = points_to_raster_binned(
                xy,
                values,
                dst_shape=like.shape[-2:],
                dst_transform=affine_of(like),
                stat=self.stat,
            )
            return wrap_like(like, result, fill_value=_binned_fill(self.stat))
        result = points_to_raster_idw(
            xy,
            values,
            dst_shape=like.shape[-2:],
            dst_transform=affine_of(like),
            k=self.k,
            power=self.power,
            max_radius=self.max_radius,
        )
        return wrap_like(like, result, fill_value=np.nan)

PointsToRaster

Bases: Operator

Bin a vector cube of point measurements onto a target raster grid.

"binned_stat" uses scipy.stats.binned_statistic_2d with the like raster's pixel-edge grid as bins. "idw" takes, at each pixel centre, the inverse-distance weighted mean of the k nearest points (functax.interp.InverseDistance, the [interp] extra), as PointCloudToRaster does; a pixel centre on a point takes that point's value.

The points input accepts:

  • a geopandas.GeoSeries / GeoDataFrame (uses .geometry; requires the attribute argument naming the column to bin).
  • an xarray.DataArray with an xvec geometry index (values taken from the array itself, no attribute needed).

A bare (geoms, values) form is not supported — wrap in a GeoDataFrame or DataArray upfront. Like RasterToPoints, only Point geometries are accepted; non-axis-aligned target rasters are rejected.

Geo-dependent: like must be a georeferenced GeoArray (its transform defines the bin grid); plain arrays raise TypeError.

Parameters:

Name Type Description Default
method Literal['binned_stat', 'idw']

Reduction strategy — "binned_stat" (scipy binned_statistic_2d, default) or "idw".

'binned_stat'
stat Literal['mean', 'median', 'sum', 'count', 'max', 'min']

For "binned_stat": one of "mean", "median", "sum", "count", "max", "min".

'mean'
attribute str | None

For GeoDataFrame inputs, the column to bin. Required for GeoDataFrame; ignored for xvec-indexed DataArray.

None
power float

For "idw": inverse-distance exponent.

2.0
k int

For "idw": how many nearest points contribute to each pixel.

8
max_radius float | None

For "idw": distance ceiling in CRS units; pixels whose nearest point is farther are NaN.

None
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class PointsToRaster(Operator):
    """Bin a vector cube of point measurements onto a target raster grid.

    ``"binned_stat"`` uses ``scipy.stats.binned_statistic_2d`` with the
    ``like`` raster's pixel-edge grid as bins. ``"idw"`` takes, at each
    pixel centre, the inverse-distance weighted mean of the ``k`` nearest
    points (``functax.interp.InverseDistance``, the ``[interp]`` extra),
    as `PointCloudToRaster` does; a pixel centre on a point takes that
    point's value.

    The ``points`` input accepts:

    * a `geopandas.GeoSeries` / `GeoDataFrame` (uses ``.geometry``;
      requires the ``attribute`` argument naming the column to bin).
    * an `xarray.DataArray` with an xvec geometry index (values
      taken from the array itself, no ``attribute`` needed).

    A bare ``(geoms, values)`` form is **not** supported — wrap in
    a `GeoDataFrame` or DataArray upfront. Like `RasterToPoints`,
    only `Point` geometries are accepted; non-axis-aligned target
    rasters are rejected.

    Geo-dependent: ``like`` must be a georeferenced ``GeoArray``
    (its transform defines the bin grid); plain arrays raise
    ``TypeError``.

    Args:
        method: Reduction strategy — ``"binned_stat"`` (scipy
            ``binned_statistic_2d``, default) or ``"idw"``.
        stat: For ``"binned_stat"``: one of ``"mean"``, ``"median"``,
            ``"sum"``, ``"count"``, ``"max"``, ``"min"``.
        attribute: For GeoDataFrame inputs, the column to bin.
            Required for GeoDataFrame; ignored for xvec-indexed
            DataArray.
        power: For ``"idw"``: inverse-distance exponent.
        k: For ``"idw"``: how many nearest points contribute to each pixel.
        max_radius: For ``"idw"``: distance ceiling in CRS units; pixels
            whose nearest point is farther are NaN.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # points binned onto the grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        method: Literal["binned_stat", "idw"] = "binned_stat",
        stat: Literal["mean", "median", "sum", "count", "max", "min"] = "mean",
        attribute: str | None = None,
        power: float = 2.0,
        k: int = 8,
        max_radius: float | None = None,
    ) -> None:
        if method not in {"binned_stat", "idw"}:
            raise ValueError(
                f"PointsToRaster.method must be 'binned_stat' or 'idw'; got {method!r}"
            )
        if k < 1:
            raise ValueError(f"k must be >= 1; got {k}")
        self.method = method
        self.stat = stat
        self.attribute = attribute
        self.power = power
        self.k = k
        self.max_radius = max_radius

    def _apply(self, points: Any, like: GeoArray) -> GeoArray:
        require_geoarray(like, "PointsToRaster", arg="like")
        # Reject non-axis-aligned target rasters — bin edges derived
        # from only a/c and e/f would silently drop rotation/shear.
        _require_axis_aligned(like, "PointsToRaster")

        # CRS sanity check happens inside `_points_with_values` for
        # GeoDataFrame inputs where the .crs attribute is set.
        xs, ys, values = _points_with_values(
            points, attribute=self.attribute, like_crs=like.crs
        )
        if self.method == "idw":
            result = points_to_raster_idw(
                np.column_stack([xs, ys]),
                values,
                dst_shape=like.shape[-2:],
                dst_transform=affine_of(like),
                k=self.k,
                power=self.power,
                max_radius=self.max_radius,
            )
            return wrap_like(like, result, fill_value=np.nan)
        result = points_to_raster_binned(
            np.column_stack([xs, ys]),
            values,
            dst_shape=like.shape[-2:],
            dst_transform=affine_of(like),
            stat=self.stat,
        )
        # The binned statistic is a new quantity: empty cells are NaN
        # (0 for counts), never ``like``'s fill.
        return wrap_like(like, result, fill_value=_binned_fill(self.stat))

RasterToPointCloud

Bases: Operator

Sample raster values onto each node of a point cloud.

A point cloud here is an (N, 2) numpy array of XY coordinates in the raster's CRS (Z columns, if present, are ignored — sampling is 2-D). For shapely-Point inputs use RasterToPoints; the distinction is the input form, not the underlying op.

Geo-dependent: the raster must be a georeferenced GeoArray (transform + CRS); plain raster arrays raise TypeError.

Parameters:

Name Type Description Default
k int

Number of nearest pixels per point. k=1 is plain nearest-neighbour (matches RasterToPoints with extract='nearest'). k>1 requires method="idw" since "nearest" / "bilinear" are k=1 concepts.

1
max_radius float | None

Optional distance ceiling in CRS units. Points farther than this from any pixel center get NaN. None disables the radius gate.

None
method Literal['nearest', 'bilinear', 'idw']

"nearest" (k=1; KDTree single-NN), "bilinear" (k=1; bilinear interp via xarray.interp), or "idw" (k>=1; inverse-distance weighted mean of the k nearest).

'nearest'
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class RasterToPointCloud(Operator):
    """Sample raster values onto each node of a point cloud.

    A point cloud here is an ``(N, 2)`` numpy array of XY coordinates
    in the raster's CRS (Z columns, if present, are ignored —
    sampling is 2-D). For shapely-Point inputs use `RasterToPoints`;
    the distinction is the input form, not the underlying op.

    Geo-dependent: the raster must be a georeferenced ``GeoArray``
    (transform + CRS); plain raster arrays raise ``TypeError``.

    Args:
        k: Number of nearest pixels per point. ``k=1`` is plain
            nearest-neighbour (matches `RasterToPoints` with
            ``extract='nearest'``). ``k>1`` requires ``method="idw"``
            since "nearest" / "bilinear" are k=1 concepts.
        max_radius: Optional distance ceiling in CRS units. Points
            farther than this from any pixel center get ``NaN``.
            ``None`` disables the radius gate.
        method: ``"nearest"`` (k=1; KDTree single-NN), ``"bilinear"``
            (k=1; bilinear interp via xarray.interp), or ``"idw"``
            (k>=1; inverse-distance weighted mean of the k nearest).
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # values read at points from their neighbours
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        k: int = 1,
        max_radius: float | None = None,
        method: Literal["nearest", "bilinear", "idw"] = "nearest",
        power: float = 2.0,
    ) -> None:
        if k < 1:
            raise ValueError(f"k must be >= 1; got {k}")
        if method in {"nearest", "bilinear"} and k != 1:
            raise ValueError(
                f"method={method!r} only supports k=1; got k={k}. "
                "Use method='idw' for k>1."
            )
        self.k = k
        self.max_radius = max_radius
        self.method = method
        self.power = power

    def _apply(self, raster: GeoArray, cloud: Any) -> Any:
        require_geoarray(raster, "RasterToPointCloud")
        _require_axis_aligned(raster, "RasterToPointCloud")
        require_ndim(raster, (2, 3), "RasterToPointCloud")
        xy = _cloud_to_xy_array(cloud, src_crs=raster.crs)
        return raster_to_point_cloud(
            np.asarray(raster),
            affine_of(raster),
            xy,
            k=self.k,
            max_radius=self.max_radius,
            method=self.method,
            power=self.power,
        )

RasterToPoints

Bases: Operator

Extract raster values at a vector cube of points.

Requires the [vector-cube] extra (xvec).

The points input accepts three forms:

  • a sequence of shapely.Point (or any iterable of shapely geometries),
  • a geopandas.GeoSeries / GeoDataFrame (uses .geometry),
  • an xarray.DataArray with an xvec geometry index (uses .xvec.geom_coords).

The return value is an xarray.DataArray indexed by a geometry dim, with the raster's values sampled at each point. For 3-D (C, H, W) rasters the result carries an additional band dim.

Geo-dependent: the raster must be a georeferenced GeoArray (transform + CRS); plain arrays raise TypeError.

Parameters:

Name Type Description Default
extract Literal['nearest', 'bilinear']

Interpolation mode — "nearest" (default; uses xvec's per-pixel nearest sampling) or "bilinear" (uses xarray's linear interpolation on the raster DataArray before extraction).

'nearest'
out_var str

Name attached to the output DataArray.

'value'
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class RasterToPoints(Operator):
    """Extract raster values at a vector cube of points.

    Requires the ``[vector-cube]`` extra (``xvec``).

    The ``points`` input accepts three forms:

    * a sequence of `shapely.Point` (or any iterable of shapely
      geometries),
    * a `geopandas.GeoSeries` / `GeoDataFrame` (uses ``.geometry``),
    * an `xarray.DataArray` with an xvec geometry index (uses
      ``.xvec.geom_coords``).

    The return value is an `xarray.DataArray` indexed by a
    ``geometry`` dim, with the raster's values sampled at each
    point. For 3-D ``(C, H, W)`` rasters the result carries an
    additional ``band`` dim.

    Geo-dependent: the raster must be a georeferenced ``GeoArray``
    (transform + CRS); plain arrays raise ``TypeError``.

    Args:
        extract: Interpolation mode — ``"nearest"`` (default; uses
            xvec's per-pixel nearest sampling) or ``"bilinear"``
            (uses xarray's linear interpolation on the raster
            DataArray before extraction).
        out_var: Name attached to the output DataArray.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # values read at points
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        extract: Literal["nearest", "bilinear"] = "nearest",
        out_var: str = "value",
    ) -> None:
        if extract not in {"nearest", "bilinear"}:
            raise ValueError(
                f"RasterToPoints.extract must be 'nearest' or 'bilinear'; got {extract!r}"
            )
        self.extract = extract
        self.out_var = out_var

    def _apply(self, raster: GeoArray, points: Any) -> Any:
        require_geoarray(raster, "RasterToPoints")
        try:
            import xvec  # noqa: F401 — registers the .xvec accessor
        except ImportError as exc:
            raise ImportError(
                "RasterToPoints requires the `[vector-cube]` extra (xvec). "
                "Install with `pip install 'geotoolz-ops[vector-cube]'`."
            ) from exc

        da = _geoarray_to_dataarray(raster, "RasterToPoints")
        geoms = _resolve_geometries(points)
        crs = str(raster.crs)

        if self.extract == "bilinear":
            # xarray's `interp` does linear interpolation in 1-D per
            # axis; combining x + y gives bilinear. Apply before
            # extract_points so the points sample the interpolated
            # raster.
            point_xs = np.asarray([g.x for g in geoms])
            point_ys = np.asarray([g.y for g in geoms])
            interp = da.interp(x=("geometry", point_xs), y=("geometry", point_ys))
            result = interp.rename(self.out_var)
            # Attach the geometry array as a coord so the output
            # matches the nearest-mode shape (geometry-indexed).

            result = result.assign_coords(geometry=("geometry", list(geoms)))
            return result

        # Nearest: defer to xvec.extract_points.
        result = da.xvec.extract_points(geoms, x_coords="x", y_coords="y", crs=crs)
        return result.rename(self.out_var)

RasterToRasterLike

Bases: Operator

Align one raster onto another's CRS + grid in a single op.

Thin binary wrapper around geom.ReprojectLike — the underlying rasterio warp handles both CRS reprojection and target-grid resampling in one pass. The wrapper exists because ReprojectLike pins like at construction (unary call), whereas matchup coregistration needs both inputs at call time to match the (secondary_raw, primary_patch) -> aligned_secondary shape of MatchedField.coreg.

Useful as a default in MatchedField.coreg for raster↔raster pairs where the secondary needs to be coregistered to the primary's grid before stacking.

Geo-dependent: both inputs must be georeferenced GeoArrays (transform + CRS); plain arrays raise TypeError.

Parameters:

Name Type Description Default
resampling str

One of "nearest", "bilinear", "cubic", "cubic_spline", "lanczos", "average", "mode".

'bilinear'

Examples:

>>> import geoops as gz
>>> coreg = gz.geom.coregister.RasterToRasterLike(resampling="bilinear")
>>> aligned_s2 = coreg(s2_chip, modis_chip)
>>> # `aligned_s2` has MODIS's CRS, transform, and spatial shape.
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class RasterToRasterLike(Operator):
    """Align one raster onto another's CRS + grid in a single op.

    Thin binary wrapper around `geom.ReprojectLike` — the underlying
    rasterio warp handles both CRS reprojection and target-grid
    resampling in one pass. The wrapper exists because
    `ReprojectLike` pins ``like`` at construction (unary call),
    whereas matchup coregistration needs both inputs at call time
    to match the ``(secondary_raw, primary_patch) -> aligned_secondary``
    shape of `MatchedField.coreg`.

    Useful as a default in ``MatchedField.coreg`` for raster↔raster
    pairs where the secondary needs to be coregistered to the
    primary's grid before stacking.

    Geo-dependent: both inputs must be georeferenced ``GeoArray``s
    (transform + CRS); plain arrays raise ``TypeError``.

    Args:
        resampling: One of ``"nearest"``, ``"bilinear"``, ``"cubic"``,
            ``"cubic_spline"``, ``"lanczos"``, ``"average"``,
            ``"mode"``.

    Examples:
        >>> import geoops as gz
        >>> coreg = gz.geom.coregister.RasterToRasterLike(resampling="bilinear")
        >>> aligned_s2 = coreg(s2_chip, modis_chip)
        >>> # `aligned_s2` has MODIS's CRS, transform, and spatial shape.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # resampled onto another grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "regrid"}, reach=None
    )

    def __init__(self, *, resampling: str = "bilinear") -> None:
        self.resampling = resampling

    def _apply(self, src: GeoArray, like: GeoArray) -> GeoArray:
        require_geoarray(src, "RasterToRasterLike", arg="src")
        require_geoarray(like, "RasterToRasterLike", arg="like")
        # Delegate to the existing single-input `ReprojectLike` so
        # we share the rasterio warp code path. The price is one
        # extra Python-level Operator construction per call; the
        # warp itself dominates, so it's negligible.
        return ReprojectLike(like=like, resampling=self.resampling)(src)

SwathToGrid

Bases: Operator

Grid a swath onto a target grid by inverse-distance weighting.

# Shapes: C bands; Nr × Nc swath (row, col); Ny′ × Nx′ target grid; Q = k

to_grid = SwathToGrid(target=grid, method="idw", k=4, power=2.0)
# f̂(x*) = ∑ⱼ wⱼ yⱼ over the Q nearest valid swath pixels, wⱼ ∝ max(dⱼ, ε)⁻ᵖ
gridded = to_grid(swath)              # (C, Nr, Nc) -> (C, Ny′, Nx′)

Each swath pixel is a source at its geolocation (swath.lon, swath.lat, transformed from swath.crs into target.crs); each target is a pixel centre of target. One plan, functax.interp.InverseDistance(k, power).plan(sources, targets) (the [interp] extra), reads every band, with distances measured in the target CRS's units (ε = 10⁻¹², so a pixel centre on a swath pixel takes its value). "nearest" is the k = 1 case.

Nodata: a swath pixel that is invalid in any band (non-finite or the swath's fill) or has a non-finite geolocation is skipped, so its targets read their k nearest valid pixels instead. A target whose nearest valid pixel is farther than max_radius is NaN, the output's fill.

The output's grid (transform, CRS, (y, x) shape) is target; its leading dims, their coordinates and its attrs are the swath's. To grid onto a raster's grid, pass target=raster.grid.

This is the cross-track resampler BowtieCorrection leaves to a later step: grid its output with this operator.

Parameters:

Name Type Description Default
target Grid | Mapping[str, Any]

The output grid, a geoarray.Grid (transform, CRS and shape, no pixels; hashable configuration), or its get_config().

required
method Literal['idw', 'nearest']

"idw" (default) or "nearest".

'idw'
k int

For "idw": swath pixels per target.

4
power float

For "idw": inverse-distance exponent.

2.0
max_radius float | None

Distance ceiling in the target CRS's units, or None.

None

Raises:

Type Description
ValueError

An unknown method, k < 1 or a target with rotation / shear; at call time, a swath that is not (row, col) or (band, row, col) with one geolocation.

TypeError

target is not a geoarray.Grid; at call time, swath is not a geoarray.GeoSwath.

ImportError

Without the [interp] extra (functax).

Examples:

>>> grid = ga.Grid((10.0, 0.0, 500000.0, 0.0, -10.0, 4e6), "EPSG:32629", (8, 10))
>>> to_grid = gz.geom.coregister.SwathToGrid(target=grid, method="idw", k=4)
>>> gridded = to_grid(swath)  # GeoArray on grid
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class SwathToGrid(Operator):
    """Grid a swath onto a target grid by inverse-distance weighting.

    ```
    # Shapes: C bands; Nr × Nc swath (row, col); Ny′ × Nx′ target grid; Q = k

    to_grid = SwathToGrid(target=grid, method="idw", k=4, power=2.0)
    # f̂(x*) = ∑ⱼ wⱼ yⱼ over the Q nearest valid swath pixels, wⱼ ∝ max(dⱼ, ε)⁻ᵖ
    gridded = to_grid(swath)              # (C, Nr, Nc) -> (C, Ny′, Nx′)
    ```

    Each swath pixel is a source at its geolocation (``swath.lon``,
    ``swath.lat``, transformed from ``swath.crs`` into ``target.crs``); each
    target is a pixel centre of ``target``. One plan,
    ``functax.interp.InverseDistance(k, power).plan(sources, targets)``
    (the ``[interp]`` extra), reads every band, with distances measured in
    the target CRS's units (``ε = 10⁻¹²``, so a pixel centre on a swath
    pixel takes its value). ``"nearest"`` is the ``k = 1`` case.

    Nodata: a swath pixel that is invalid in any band (non-finite or the
    swath's fill) or has a non-finite geolocation is skipped, so its
    targets read their ``k`` nearest *valid* pixels instead. A target
    whose nearest valid pixel is farther than ``max_radius`` is ``NaN``,
    the output's fill.

    The output's grid (transform, CRS, ``(y, x)`` shape) is ``target``; its
    leading dims, their coordinates and its attrs are the swath's. To grid
    onto a raster's grid, pass ``target=raster.grid``.

    This is the cross-track resampler `BowtieCorrection` leaves to a
    later step: grid its output with this operator.

    Args:
        target: The output grid, a `geoarray.Grid` (transform, CRS and
            shape, no pixels; hashable configuration), or its
            ``get_config()``.
        method: ``"idw"`` (default) or ``"nearest"``.
        k: For ``"idw"``: swath pixels per target.
        power: For ``"idw"``: inverse-distance exponent.
        max_radius: Distance ceiling in the target CRS's units, or ``None``.

    Raises:
        ValueError: An unknown ``method``, ``k < 1`` or a ``target`` with
            rotation / shear; at call time, a swath that is not
            ``(row, col)`` or ``(band, row, col)`` with one geolocation.
        TypeError: ``target`` is not a `geoarray.Grid`; at call time,
            ``swath`` is not a `geoarray.GeoSwath`.
        ImportError: Without the ``[interp]`` extra (functax).

    Examples:
        >>> grid = ga.Grid((10.0, 0.0, 500000.0, 0.0, -10.0, 4e6), "EPSG:32629", (8, 10))
        >>> to_grid = gz.geom.coregister.SwathToGrid(target=grid, method="idw", k=4)
        >>> gridded = to_grid(swath)  # GeoArray on grid
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # swath pixels interpolated onto the grid
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        target: geoarray.Grid | Mapping[str, Any],
        method: Literal["idw", "nearest"] = "idw",
        k: int = 4,
        power: float = 2.0,
        max_radius: float | None = None,
    ) -> None:
        if isinstance(target, Mapping):
            # a Grid's get_config, as from_state and YAML hand it back
            target = geoarray.Grid.from_config(dict(target.items()))
        if not isinstance(target, geoarray.Grid):
            raise TypeError(
                f"SwathToGrid.target is a geoarray.Grid, got {type(target).__name__}"
            )
        # pixel centres from the a/c and e/f terms only, as for PointCloudToRaster
        _require_axis_aligned(target.transform, "SwathToGrid")
        if method not in {"idw", "nearest"}:
            raise ValueError(
                f"SwathToGrid.method must be 'idw' or 'nearest'; got {method!r}"
            )
        if k < 1:
            raise ValueError(f"k must be >= 1; got {k}")
        self.target = target
        self.method = method
        self.k = k
        self.power = power
        self.max_radius = max_radius

    def _apply(self, swath: GeoSwath) -> GeoArray:
        if not isinstance(swath, geoarray.GeoSwath):
            raise TypeError(
                "SwathToGrid expects a geoarray.GeoSwath (data with per-pixel "
                f"lat/lon); got {type(swath).__name__}."
            )
        values = np.asarray(swath, dtype=np.float64)
        require_ndim(values, (2, 3), "SwathToGrid")
        if np.ndim(swath.lat) != 2:
            raise ValueError(
                "SwathToGrid grids one granule: lat/lon must be (row, col); got "
                f"{np.shape(swath.lat)}"
            )
        target = self.target
        x, y = _swath_xy(swath, target.crs)
        invalid = invalid_values(swath, fill_value=swath.fill_value)
        if invalid.ndim == 3:
            invalid = invalid.any(axis=0)
        valid = ~invalid & np.isfinite(x) & np.isfinite(y)
        result = points_to_raster_idw(
            np.column_stack([x.ravel(), y.ravel()]),
            values.reshape(*values.shape[:-2], -1),
            dst_shape=target.shape,
            dst_transform=target.affine,
            k=1 if self.method == "nearest" else self.k,
            power=self.power,
            max_radius=self.max_radius,
            valid=valid.ravel(),
        )
        # no carrier holds the target grid, so the output is built on it: the
        # grid is target's; the leading dims, their coords and attrs the swath's
        leading = tuple(swath.dims[:-2])
        return GeoArray(
            result,
            target.transform,
            target.crs,
            fill_value=np.nan,
            attrs=FrozenAttrs(dict(swath.attrs)),
            dims=(*leading, "y", "x"),
            coords=tuple(c for c in swath.coords if c.dim in leading),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "target": self.target.get_config(),
            "method": self.method,
            "k": self.k,
            "power": self.power,
            "max_radius": self.max_radius,
        }

VectorToRasterAgg

Bases: Operator

Rasterize a vector layer with an aggregation policy for overlaps.

Extends geom.Rasterize (which burns features in order and lets later ones overwrite earlier ones) with a per-pixel aggregation when multiple features overlap a pixel — useful for mean of an attribute, count of features per pixel, etc.

Implementation strategy: rasterize each feature separately to a boolean mask (O(H*W) per feature, single accumulator pass) and update a running aggregator. This is more memory-friendly than stacking N feature rasters and reducing.

Geo-dependent: like must be a georeferenced GeoArray (its transform defines the burn grid); plain arrays raise TypeError.

Parameters:

Name Type Description Default
agg Literal['mean', 'majority', 'count', 'sum', 'max', 'min', 'first', 'last']

One of "mean", "count", "sum", "max", "min", "first", "last". "majority" is deferred (raises at call time so YAML round-trip works).

'mean'
attribute str | None

Column name to aggregate. Required for mean / sum / max / min / first / last; ignored for count.

None
all_touched bool

If True, every pixel whose envelope is touched by the geometry counts. If False (the rasterio default — and ours), only pixels whose centre falls inside the geometry contribute.

False
Source code in packages/geotoolz-ops/src/geoops/geom/_src/coregister/operators.py
class VectorToRasterAgg(Operator):
    """Rasterize a vector layer with an aggregation policy for overlaps.

    Extends `geom.Rasterize` (which burns features in order and lets
    later ones overwrite earlier ones) with a per-pixel aggregation
    when multiple features overlap a pixel — useful for mean of an
    attribute, count of features per pixel, etc.

    Implementation strategy: rasterize each feature separately to a
    boolean mask (O(H*W) per feature, single accumulator pass) and
    update a running aggregator. This is more memory-friendly than
    stacking N feature rasters and reducing.

    Geo-dependent: ``like`` must be a georeferenced ``GeoArray``
    (its transform defines the burn grid); plain arrays raise
    ``TypeError``.

    Args:
        agg: One of ``"mean"``, ``"count"``, ``"sum"``, ``"max"``,
            ``"min"``, ``"first"``, ``"last"``. ``"majority"`` is
            deferred (raises at call time so YAML round-trip works).
        attribute: Column name to aggregate. Required for
            ``mean / sum / max / min / first / last``; ignored for
            ``count``.
        all_touched: If ``True``, every pixel whose envelope is
            touched by the geometry counts. If ``False`` (the
            rasterio default — and ours), only pixels whose centre
            falls inside the geometry contribute.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # values aggregated per geometry
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        agg: Literal[
            "mean", "majority", "count", "sum", "max", "min", "first", "last"
        ] = "mean",
        attribute: str | None = None,
        all_touched: bool = False,
    ) -> None:
        valid = {"mean", "majority", "count", "sum", "max", "min", "first", "last"}
        if agg not in valid:
            raise ValueError(
                f"VectorToRasterAgg.agg must be one of {sorted(valid)!r}; got {agg!r}"
            )
        if agg != "count" and agg != "majority" and attribute is None:
            raise ValueError(
                f"VectorToRasterAgg(agg={agg!r}) requires `attribute` naming "
                "the column to aggregate."
            )
        self.agg = agg
        self.attribute = attribute
        self.all_touched = all_touched

    def _apply(self, vector: Any, like: GeoArray) -> GeoArray:
        if self.agg == "majority":
            raise NotImplementedError(
                "VectorToRasterAgg(agg='majority') not yet implemented; "
                "the others (mean / count / sum / max / min / first / last) "
                "are wired up."
            )
        require_geoarray(like, "VectorToRasterAgg", arg="like")
        _require_axis_aligned(like, "VectorToRasterAgg")
        feature = "geoops.geom.coregister.VectorToRasterAgg"
        gpd = optional_module("geopandas", "vector", feature=feature)
        rio_rasterize = optional_name(
            "rasterio.features", "rasterize", "raster", feature=feature
        )

        if not isinstance(vector, gpd.GeoDataFrame):
            raise TypeError(
                "VectorToRasterAgg expects a geopandas.GeoDataFrame; got "
                f"{type(vector).__name__}."
            )
        if vector.crs is not None and like.crs is not None:
            import pyproj as _pp

            src = _pp.CRS.from_user_input(vector.crs)
            dst = _pp.CRS.from_user_input(like.crs)
            if src != dst:
                raise ValueError(
                    f"VectorToRasterAgg: vector CRS {src.to_string()!r} differs "
                    f"from raster CRS {dst.to_string()!r}. Reproject the input "
                    "first (e.g. `gdf.to_crs(like.crs)`)."
                )

        h, w = like.shape[-2], like.shape[-1]
        like_transform = affine_of(like)
        # Per-feature mask burned at value=1 using the like raster's affine.
        # For pixel-centre semantics use all_touched=False; for envelope-
        # overlap use all_touched=True.

        # Pull attribute values once (None for count / majority).
        attr_values = (
            vector[self.attribute].to_numpy() if self.attribute is not None else None
        )

        # Initialise the accumulator(s).
        sum_arr = (
            np.zeros((h, w), dtype=np.float64) if self.agg in {"mean", "sum"} else None
        )
        count_arr = np.zeros((h, w), dtype=np.int64)
        max_arr = (
            np.full((h, w), -np.inf, dtype=np.float64) if self.agg == "max" else None
        )
        min_arr = (
            np.full((h, w), np.inf, dtype=np.float64) if self.agg == "min" else None
        )
        # For "first" / "last": keep an array of attribute values written
        # in order. "first" walks the GDF in reverse so the *first* feature
        # writes last and wins; "last" walks forwards so the *last* feature
        # writes last and wins.
        ordinal_arr = (
            np.full((h, w), np.nan, dtype=np.float64)
            if self.agg in {"first", "last"}
            else None
        )

        iterator = (
            zip(
                reversed(range(len(vector))),
                reversed(list(vector.geometry)),
                strict=True,
            )
            if self.agg == "first"
            else zip(range(len(vector)), vector.geometry, strict=True)
        )

        for idx, geom in iterator:
            mask = rio_rasterize(
                [(geom, 1)],
                out_shape=(h, w),
                transform=like_transform,
                all_touched=self.all_touched,
                dtype=np.uint8,
            ).astype(bool)
            if not mask.any():
                continue
            count_arr += mask.astype(np.int64)
            if self.agg == "count":
                continue
            v = float(attr_values[idx]) if attr_values is not None else 1.0
            if self.agg in {"sum", "mean"}:
                assert sum_arr is not None
                sum_arr[mask] += v
            elif self.agg == "max":
                assert max_arr is not None
                np.maximum(max_arr, np.where(mask, v, -np.inf), out=max_arr)
            elif self.agg == "min":
                assert min_arr is not None
                np.minimum(min_arr, np.where(mask, v, np.inf), out=min_arr)
            elif self.agg in {"first", "last"}:
                assert ordinal_arr is not None
                ordinal_arr[mask] = v

        # Build the result per agg policy.
        if self.agg == "count":
            result = count_arr.astype(np.float64)
        elif self.agg == "sum":
            assert sum_arr is not None
            result = sum_arr
            # Pixels with no features: NaN (sum of nothing is undefined
            # in the aggregate-attribute sense).
            result = np.where(count_arr > 0, result, np.nan)
        elif self.agg == "mean":
            assert sum_arr is not None
            result = np.where(count_arr > 0, sum_arr / np.maximum(count_arr, 1), np.nan)
        elif self.agg == "max":
            assert max_arr is not None
            result = np.where(count_arr > 0, max_arr, np.nan)
        elif self.agg == "min":
            assert min_arr is not None
            result = np.where(count_arr > 0, min_arr, np.nan)
        else:  # first / last
            assert ordinal_arr is not None
            result = ordinal_arr

        # Empty cells are NaN (0 for counts), never ``like``'s fill.
        return wrap_like(like, result, fill_value=_binned_fill(self.agg))