Skip to content

Carrier helpers and contract checks

The helpers every geotoolz operator uses to keep the GeoArray carrier contract, public so an operator written on top of the stack keeps it the same way, and check_operator, which runs the package's own contract checks on any operator. The rules are in Concepts and Define an operator.

geoops.carrier

The GeoArray carrier contract, as public helpers.

Every geotoolz operator keeps the same carrier rules: a geoarray.GeoArray in comes back as a GeoArray on the input's grid (a plain array as a plain array), with per-band metadata that matches the output bands and a fill_value that marks its nodata; a georeader GeoTensor is refused, naming geoarray.interop.georeader.from_georeader. These are the helpers the built-in operators use to keep them; an operator you write on top of the stack uses the same ones, so it composes with everything else. The rules themselves are in the repository's AGENTS.md ("The two contracts") and docs/operators/concepts.md.

Rewrap

wrap_like puts a result back on the input's carrier (transform= for a new grid); INHERIT is its "take the input's fill" default.

Nodata

valid_pixels / invalid_values (a pixel is invalid when any band is non-finite or equals the fill), mask_invalid_to_nan before NaN-aware statistics, restore_fill / wrap_filled to write the output's fill back, and carried_fill for an output that carries the input's values.

Bands

resolve_band / resolve_bands (an integer position or a name looked up in band_names, descriptions, bands), band_names; BandRef (the type of a band reference) and SENTINEL2_L2A_BANDS (the canonical Sentinel-2 L2A band order).

Shape

band_axis, band_dim / dim_axis (an operator's dim=, and where that dim sits in a carrier), require_ndim, map_frames / over_frames (run a per-scene function on each frame of a (T, C, H, W) stack), keep_band_axis (a band-collapsing result keeps its time axis) and single_band (pick one band as a 2-D plane).

Samples

cube_to_samples / samples_to_cube turn a (c, h, w) cube into an (n, c) sample matrix for a per-pixel estimator and back; sample_layout / SampleLayout describe the round trip.

Grids

require_geoarray, reject_geotensor (a georeader GeoTensor carrier), reject_georeader (any georeader object, e.g. a raster an operator holds in its constructor), require_projected_crs, require_grid_match, grid_matches, affine_of (the transform as an affine.Affine) and pixel_xy (map coordinates of pixel centres).

Dtypes and fitting

as_float (promote integer DNs before arithmetic) and fit_once (fit on first call, once, without races).

Config

The operator side of the contract: jsonable coerces a get_config() value to JSON builtins, as_tuple turns lists back into tuples on reload, mapping_to_pairs / mapping_from_pairs carry non-string-keyed mappings, nested_config / callable_name describe a nested operator or a callable, and reject_config_summary refuses a debug summary passed back to a constructor.

Coupling

Coupling is the record an operator class declares as coupling: the dims its output reads across (band, level, space, time), what it does to each, its spatial reach and the dims a fit reads. reach_of gives an operator's reach (spatial_reach() when it depends on an argument). geoops.testing.measure_coupling and geoops.testing.assert_coupling check a declaration.

Optional dependencies

optional_module imports an extra's module inside the function that needs it, with an error naming the extra; optional_name is the from a import b form and optional_root the import a.b one.

Example

An operator that keeps the carrier contract::

import numpy as np
from pipekit_ops import Operator

from geoops.carrier import mask_invalid_to_nan, over_frames, wrap_like


class ZScore(Operator):
    backends = ("numpy",)  # refuses JAX carriers (pipekit's check)

    def __init__(self, *, mean: float, std: float) -> None:
        self.mean = mean
        self.std = std

    @over_frames  # (T, C, H, W) stacks run frame by frame
    def _apply(self, gt):  # (C, H, W) -> (C, H, W) float
        values = mask_invalid_to_nan(gt)  # nodata -> NaN, whole pixel
        out = (values - self.mean) / self.std
        return wrap_like(gt, out, fill_value=np.nan)

Check it with geoops.testing.check_operator.

Coupling dataclass

Which dims an operator's output reads across, and what it does to each.

An operator class declares it as coupling, beside backends. geoops.testing.assert_coupling checks it against a measurement.

Parameters:

Name Type Description Default
couples Iterable[str]

The dims along which an output depends on two or more input values once any state is fitted (K_apply).

()
effects Mapping[str, str] | Iterable[tuple[str, str]]

What the operator does to each dim it changes (EFFECTS); a dim left out is kept.

()
reach int | None

The spatial reach in pixels at the default settings: the largest distance between an output pixel and an input pixel it depends on. None for a global or unbounded reach. 0 unless space is coupled. An operator whose reach depends on a constructor argument also defines spatial_reach().

0
fit Iterable[str]

The further dims a fitted state is estimated over, beyond couples (StandardScaler applies pointwise but fits its mean and spread over space).

()
kind str

"transform" (raster in, raster out), "fan-out" (a list of rasters), "conversion" (a table, geometry, scalar or model), "source" (no raster in) or "sink".

'transform'
reads_values bool

False when the output depends only on the input's grid, never on its values (a rasterised polygon, a land mask): one result then serves every frame of a stack.

True

Raises:

Type Description
ValueError

An unknown dim, effect or kind; a dim both coupled and fitted; a reach that does not fit the coupled dims.

Example

ndvi = Coupling(couples={"band"}, effects={"band": "reduce"}) ndvi.name, ndvi.effect("band"), ndvi.effect("space") ('spectral', 'reduce', 'keep') Coupling(fit={"space"}).name 'pointwise'

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
@dataclasses.dataclass(frozen=True, init=False)
class Coupling:
    """Which dims an operator's output reads across, and what it does to each.

    An operator class declares it as ``coupling``, beside ``backends``.
    `geoops.testing.assert_coupling` checks it against a measurement.

    Args:
        couples: The dims along which an output depends on two or more input
            values once any state is fitted (K_apply).
        effects: What the operator does to each dim it changes (`EFFECTS`);
            a dim left out is kept.
        reach: The spatial reach in pixels at the default settings: the
            largest distance between an output pixel and an input pixel it
            depends on. ``None`` for a global or unbounded reach. ``0``
            unless ``space`` is coupled. An operator whose reach depends on
            a constructor argument also defines ``spatial_reach()``.
        fit: The further dims a fitted state is estimated over, beyond
            ``couples`` (``StandardScaler`` applies pointwise but fits its
            mean and spread over ``space``).
        kind: ``"transform"`` (raster in, raster out), ``"fan-out"`` (a list
            of rasters), ``"conversion"`` (a table, geometry, scalar or
            model), ``"source"`` (no raster in) or ``"sink"``.
        reads_values: ``False`` when the output depends only on the input's
            grid, never on its values (a rasterised polygon, a land mask):
            one result then serves every frame of a stack.

    Raises:
        ValueError: An unknown dim, effect or kind; a dim both coupled and
            fitted; a reach that does not fit the coupled dims.

    Example:
        >>> ndvi = Coupling(couples={"band"}, effects={"band": "reduce"})
        >>> ndvi.name, ndvi.effect("band"), ndvi.effect("space")
        ('spectral', 'reduce', 'keep')
        >>> Coupling(fit={"space"}).name
        'pointwise'
    """

    couples: frozenset[str]
    effects: tuple[tuple[str, str], ...]
    reach: int | None
    fit: frozenset[str]
    kind: str
    reads_values: bool

    def __init__(
        self,
        *,
        couples: Iterable[str] = (),
        effects: Mapping[str, str] | Iterable[tuple[str, str]] = (),
        reach: int | None = 0,
        fit: Iterable[str] = (),
        kind: str = "transform",
        reads_values: bool = True,
    ) -> None:
        coupled = _dims(couples, "couples")
        fitted = _dims(fit, "fit")
        pairs = dict(effects.items() if isinstance(effects, Mapping) else effects)
        _dims(pairs, "effects")
        bad = sorted(v for v in pairs.values() if v not in EFFECTS)
        if bad:
            raise ValueError(f"Coupling effects: unknown {bad}; use {EFFECTS}")
        pairs = {d: e for d, e in pairs.items() if e != "keep"}
        if kind not in KINDS:
            raise ValueError(f"Coupling kind {kind!r}: use one of {KINDS}")
        if coupled & fitted:
            raise ValueError(
                f"Coupling: {sorted(coupled & fitted)} both coupled and fitted; "
                "fit lists only the further dims a fit reads"
            )
        if reach is not None and (
            isinstance(reach, bool) or not isinstance(reach, int)
        ):
            raise TypeError(f"Coupling reach must be an int or None, got {reach!r}")
        if reach is not None and reach < 0:
            raise ValueError(f"Coupling reach must be >= 0, got {reach}")
        if "space" in coupled and reach == 0:
            raise ValueError(
                "Coupling: a spatial coupling needs a reach >= 1, or None for global"
            )
        if "space" not in coupled and reach != 0:
            raise ValueError("Coupling: a reach other than 0 needs 'space' in couples")
        object.__setattr__(self, "couples", coupled)
        object.__setattr__(self, "effects", tuple(sorted(pairs.items())))
        object.__setattr__(self, "reach", reach)
        object.__setattr__(self, "fit", fitted)
        object.__setattr__(self, "kind", kind)
        object.__setattr__(self, "reads_values", bool(reads_values))

    @property
    def name(self) -> str:
        """The class name of ``couples``: ``"pointwise"``, ``"spectral"``, …"""
        return class_name(self.couples)

    def effect(self, dim: str) -> str:
        """What the operator does to ``dim``: ``"keep"`` unless listed."""
        return dict(self.effects).get(dim, "keep")

name property

The class name of couples: "pointwise", "spectral", …

effect(dim)

What the operator does to dim: "keep" unless listed.

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
def effect(self, dim: str) -> str:
    """What the operator does to ``dim``: ``"keep"`` unless listed."""
    return dict(self.effects).get(dim, "keep")

SampleLayout dataclass

How a cube was flattened by :func:cube_to_samples.

Attributes:

Name Type Description
shape tuple[int, ...]

Shape of the original cube.

sample_axes tuple[int, ...]

Axes (non-negative) flattened into rows, in row-major order.

band_axes tuple[int, ...]

Axes (non-negative) flattened into columns, in order; empty when the cube has no band axis (one column).

Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
@dataclass(frozen=True)
class SampleLayout:
    """How a cube was flattened by :func:`cube_to_samples`.

    Attributes:
        shape: Shape of the original cube.
        sample_axes: Axes (non-negative) flattened into rows, in row-major
            order.
        band_axes: Axes (non-negative) flattened into columns, in order;
            empty when the cube has no band axis (one column).
    """

    shape: tuple[int, ...]
    sample_axes: tuple[int, ...]
    band_axes: tuple[int, ...]

    @property
    def sample_shape(self) -> tuple[int, ...]:
        """Sizes of :attr:`sample_axes`, in row-major order."""
        return tuple(self.shape[axis] for axis in self.sample_axes)

    @property
    def band_shape(self) -> tuple[int, ...]:
        """Sizes of :attr:`band_axes`."""
        return tuple(self.shape[axis] for axis in self.band_axes)

    @property
    def n_samples(self) -> int:
        """Number of rows."""
        return prod(self.sample_shape)

    @property
    def n_bands(self) -> int:
        """Number of columns (``1`` when there is no band axis)."""
        return prod(self.band_shape)

band_shape property

Sizes of :attr:band_axes.

n_bands property

Number of columns (1 when there is no band axis).

n_samples property

Number of rows.

sample_shape property

Sizes of :attr:sample_axes, in row-major order.

affine_of(x)

The transform of x as an affine.Affine (~T, T * (c, r)).

Parameters:

Name Type Description Default
x Any

A GeoArray (concrete, not batched), an Affine, six numbers or a (6,) array.

required

Returns:

Type Description
Affine

The Affine.

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 2)), (10, 0, 500000, 0, -10, 4e6), 32629) affine_of(g).c 500000.0

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def affine_of(x: Any) -> Affine:
    """The transform of ``x`` as an ``affine.Affine`` (``~T``, ``T * (c, r)``).

    Args:
        x: A `GeoArray` (concrete, not batched), an ``Affine``, six
            numbers or a ``(6,)`` array.

    Returns:
        The ``Affine``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 2)), (10, 0, 500000, 0, -10, 4e6), 32629)
        >>> affine_of(g).c
        500000.0
    """
    if isinstance(x, GeoArray):
        return x.grid.affine
    return Affine(*as_transform(x))

as_float(arr, min_dtype=np.float32)

Promote integer / boolean arr to floating point before arithmetic.

Floating-point (and complex) input is returned unchanged, without a copy. Anything else is cast to np.result_type(arr, min_dtype): with the default float32 floor, (u)int8 / (u)int16 / bool become float32 and wider integers become float64.

Parameters:

Name Type Description Default
arr Num[ndarray, '*dims'] | Shaped[ndarray, '*dims']

Any numeric array-like.

required
min_dtype DTypeLike

Smallest float dtype integer input is promoted to. Default np.float32; pass np.float64 where the caller documents a float64 result for integer input.

float32

JAX and dask arrays (an Array API array with a dtype) stay on their backend, so a kernel can promote its input under jax.jit; anything without a dtype goes through np.asarray first.

Returns:

Type Description
Float[ndarray, '*dims']

A floating-point array with the same shape and values, on the

Float[ndarray, '*dims']

input's backend.

Source code in packages/geotoolz-ops/src/geoops/_src/dtype.py
def as_float(
    arr: Num[np.ndarray, "*dims"] | Shaped[np.ndarray, "*dims"],
    min_dtype: DTypeLike = np.float32,
) -> Float[np.ndarray, "*dims"]:
    """Promote integer / boolean ``arr`` to floating point before arithmetic.

    Floating-point (and complex) input is returned unchanged, without a
    copy. Anything else is cast to ``np.result_type(arr, min_dtype)``:
    with the default ``float32`` floor, ``(u)int8`` / ``(u)int16`` /
    ``bool`` become ``float32`` and wider integers become ``float64``.

    Args:
        arr: Any numeric array-like.
        min_dtype: Smallest float dtype integer input is promoted to.
            Default ``np.float32``; pass ``np.float64`` where the
            caller documents a ``float64`` result for integer input.

    JAX and dask arrays (an Array API array with a ``dtype``) stay on their
    backend, so a kernel can promote its input under ``jax.jit``; anything
    without a ``dtype`` goes through ``np.asarray`` first.

    Returns:
        A floating-point array with the same shape and values, on the
        input's backend.
    """
    if not hasattr(arr, "dtype") or isinstance(arr, np.ndarray):
        arr = np.asarray(arr)
        if np.issubdtype(arr.dtype, np.inexact):
            return arr
        return arr.astype(np.result_type(arr, min_dtype), copy=False)
    if np.issubdtype(arr.dtype, np.inexact):
        return arr
    return arr.astype(np.result_type(arr.dtype, min_dtype))

as_tuple(value)

Normalise a list or tuple constructor argument to a tuple.

JSON and YAML have no tuple type, so a config reloaded through Operator.from_state hands the constructor a list where a tuple was emitted. Constructors call this on tuple-typed parameters so the reloaded operator is identical; scalars and None pass through.

Parameters:

Name Type Description Default
value Any

The constructor argument.

required

Returns:

Type Description
Any

tuple(value) for a non-string sequence (list, tuple, OmegaConf

Any

ListConfig), otherwise value.

Source code in packages/geotoolz-ops/src/geoops/_src/config.py
def as_tuple(value: Any) -> Any:
    """Normalise a list or tuple constructor argument to a tuple.

    JSON and YAML have no tuple type, so a config reloaded through
    ``Operator.from_state`` hands the constructor a list where a tuple
    was emitted. Constructors call this on tuple-typed parameters so the
    reloaded operator is identical; scalars and ``None`` pass through.

    Args:
        value: The constructor argument.

    Returns:
        ``tuple(value)`` for a non-string sequence (list, tuple, OmegaConf
        ``ListConfig``), otherwise ``value``.
    """
    if _is_sequence(value):
        return tuple(value)
    return value

band_axis(arr)

Axis holding the bands of a 3-D or 4-D carrier: always -3.

Parameters:

Name Type Description Default
arr Any

A (C, H, W) or (T, C, H, W) carrier (any array-like; only its rank is read).

required

Returns:

Type Description
int

-3.

Raises:

Type Description
ValueError

If arr has fewer than three dimensions -- a 2-D (H, W) map has no band axis (it is a single band; callers that accept one handle it explicitly).

Examples:

>>> band_axis(np.zeros((2, 3, 4, 4)))
-3
>>> np.zeros((2, 3, 4, 4)).shape[band_axis(np.zeros((2, 3, 4, 4)))]
3
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def band_axis(arr: Any) -> int:
    """Axis holding the bands of a 3-D or 4-D carrier: always ``-3``.

    Args:
        arr: A ``(C, H, W)`` or ``(T, C, H, W)`` carrier (any array-like;
            only its rank is read).

    Returns:
        ``-3``.

    Raises:
        ValueError: If ``arr`` has fewer than three dimensions -- a 2-D
            ``(H, W)`` map has no band axis (it is a single band; callers
            that accept one handle it explicitly).

    Examples:
        >>> band_axis(np.zeros((2, 3, 4, 4)))
        -3
        >>> np.zeros((2, 3, 4, 4)).shape[band_axis(np.zeros((2, 3, 4, 4)))]
        3
    """
    ndim = np.ndim(arr)
    if ndim < 3:
        raise ValueError(
            f"a {ndim}-D array has no band axis; expected (C, H, W) or (T, C, H, W)"
        )
    return BAND_AXIS

band_dim(dim, axis, name, *, legacy=(BAND_AXIS,))

The dim an operator works over, from dim= or the deprecated axis=.

axis= keeps working for one release: a band position in legacy (-3, or 0 for the per-frame skimage wrappers) maps to "band" with a DeprecationWarning.

Parameters:

Name Type Description Default
dim str | None

The dim= argument.

required
axis int | None

The deprecated axis= argument (None when not given).

required
name str

Operator name for the messages.

required
legacy tuple[int, ...]

The old band positions that map to "band".

(BAND_AXIS,)

Returns:

Type Description
str | None

The dim name, or None when the operator allows "no band dim".

Raises:

Type Description
ValueError

axis is not one of the legacy band positions, or both axis and a non-default dim are given.

Examples:

>>> band_dim("band", None, "NDVI")
'band'
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def band_dim(
    dim: str | None,
    axis: int | None,
    name: str,
    *,
    legacy: tuple[int, ...] = (BAND_AXIS,),
) -> str | None:
    """The dim an operator works over, from ``dim=`` or the deprecated ``axis=``.

    ``axis=`` keeps working for one release: a band position in ``legacy``
    (``-3``, or ``0`` for the per-frame skimage wrappers) maps to
    ``"band"`` with a `DeprecationWarning`.

    Args:
        dim: The ``dim=`` argument.
        axis: The deprecated ``axis=`` argument (``None`` when not given).
        name: Operator name for the messages.
        legacy: The old band positions that map to ``"band"``.

    Returns:
        The dim name, or ``None`` when the operator allows "no band dim".

    Raises:
        ValueError: ``axis`` is not one of the ``legacy`` band positions, or
            both ``axis`` and a non-default ``dim`` are given.

    Examples:
        >>> band_dim("band", None, "NDVI")
        'band'
    """
    if axis is None:
        return dim
    warnings.warn(
        f"{name}(axis=...) is deprecated: pass dim='band' (the band dim's name). "
        "axis= is removed in the next minor release.",
        DeprecationWarning,
        stacklevel=3,
    )
    if dim != "band":
        raise ValueError(f"{name}: pass dim= or the deprecated axis=, not both")
    if axis not in legacy:
        raise ValueError(
            f"{name}: axis={axis} is not the band axis; pass dim= with the name "
            "of the dim to work over"
        )
    return "band"

band_names(gt, *, keys=DEFAULT_BAND_KEYS)

The carrier's band names, read from the first usable attrs key.

Keys are consulted in keys order (default :data:DEFAULT_BAND_KEYS: band_names, then descriptions, then bands); the first one holding a sequence or a {name: index} mapping wins. A mapping keeps its declared positions: entry i is the name mapped to band i, or None for a band the mapping does not name, and the list is padded to the carrier's band count. When several names map to one band (aliases), the first one wins.

Parameters:

Name Type Description Default
gt GeoArray | ndarray | Any

A GeoArray-like carrier with attrs, or a plain array.

required
keys tuple[str, ...]

Attribute keys to consult, in precedence order.

DEFAULT_BAND_KEYS

Returns:

Type Description
list[str | None] | None

The names as str in band order, or None when the carrier

list[str | None] | None

has no attrs (a plain ndarray) or none of keys holds

list[str | None] | None

band names.

Examples:

>>> import numpy as np
>>> class Carrier:
...     attrs = {"descriptions": ("red", "nir"), "band_names": ["B04", "B08"]}
>>> band_names(Carrier())
['B04', 'B08']
>>> band_names(np.zeros((2, 3, 3))) is None
True
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
def band_names(
    gt: GeoArray | np.ndarray | Any,
    *,
    keys: tuple[str, ...] = DEFAULT_BAND_KEYS,
) -> list[str | None] | None:
    """The carrier's band names, read from the first usable ``attrs`` key.

    Keys are consulted in ``keys`` order (default
    :data:`DEFAULT_BAND_KEYS`: ``band_names``, then ``descriptions``, then
    ``bands``); the first one holding a sequence or a ``{name: index}``
    mapping wins. A mapping keeps its declared positions: entry ``i`` is
    the name mapped to band ``i``, or ``None`` for a band the mapping
    does not name, and the list is padded to the carrier's band count.
    When several names map to one band (aliases), the first one wins.

    Args:
        gt: A GeoArray-like carrier with ``attrs``, or a plain array.
        keys: Attribute keys to consult, in precedence order.

    Returns:
        The names as ``str`` in band order, or ``None`` when the carrier
        has no ``attrs`` (a plain ndarray) or none of ``keys`` holds
        band names.

    Examples:
        >>> import numpy as np
        >>> class Carrier:
        ...     attrs = {"descriptions": ("red", "nir"), "band_names": ["B04", "B08"]}
        >>> band_names(Carrier())
        ['B04', 'B08']
        >>> band_names(np.zeros((2, 3, 3))) is None
        True
    """
    attrs = getattr(gt, "attrs", None)
    if attrs is None:
        return None
    for key in keys:
        names = _names_under(attrs, key)
        if isinstance(names, dict):
            return _slotted_names(names, gt)
        if names is not None:
            return list(names)
    return None

carried_fill(ref, dtype)

Fill value for an output that carries ref's values in dtype.

For value-preserving operators (filters, scalings, resampling, casts) whose output may change dtype. Operators whose output means something new pass the canonical fill for that meaning instead (False / 0 / NaN; see the module docstring).

Parameters:

Name Type Description Default
ref Any

The operator's input carrier.

required
dtype Any

The output dtype.

required

Returns:

Type Description
Any

False for a boolean output. For a floating-point output,

Any

NaN when ref is an integer / boolean carrier with a fill

Any

(the integer fill would collide with promoted real data, e.g.

Any

0), otherwise ref's fill (None stays None). For an

Any

integer output, ref's fill when it is representable in

Any

dtype, otherwise None.

Examples:

>>> carried_fill(np.zeros(2, dtype=np.uint16), np.float32) is None
True
>>> carried_fill(np.zeros(2), bool)
False
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def carried_fill(ref: Any, dtype: Any) -> Any:
    """Fill value for an output that carries ``ref``'s values in ``dtype``.

    For value-preserving operators (filters, scalings, resampling, casts)
    whose output may change dtype. Operators whose output *means*
    something new pass the canonical fill for that meaning instead
    (``False`` / ``0`` / ``NaN``; see the module docstring).

    Args:
        ref: The operator's input carrier.
        dtype: The output dtype.

    Returns:
        ``False`` for a boolean output. For a floating-point output,
        ``NaN`` when ``ref`` is an integer / boolean carrier with a fill
        (the integer fill would collide with promoted real data, e.g.
        ``0``), otherwise ``ref``'s fill (``None`` stays ``None``). For an
        integer output, ``ref``'s fill when it is representable in
        ``dtype``, otherwise ``None``.

    Examples:
        >>> carried_fill(np.zeros(2, dtype=np.uint16), np.float32) is None
        True
        >>> carried_fill(np.zeros(2), bool)
        False
    """
    dtype = np.dtype(dtype)
    if dtype == np.bool_:
        return False
    fill = carrier_fill_value(ref)
    if fill is None:
        return None
    if np.issubdtype(dtype, np.inexact):
        if _is_nan_scalar(fill) or not np.issubdtype(np.asarray(ref).dtype, np.inexact):
            return np.nan
        return fill
    if _is_nan_scalar(fill) or not isinstance(fill, numbers.Real):
        return None
    try:
        cast = np.asarray(fill).astype(dtype)
    except (OverflowError, ValueError):
        return None
    return fill if cast.item() == fill else None

cube_to_samples(arr, *, band_axis=-3, sample_axes=None, dtype=None)

Flatten a cube into an (n_samples, n_bands) matrix.

For a canonical (c, h, w) cube this is einx.id("c h w -> (h w) c"); a (t, c, h, w) stack with the default band_axis=-3 yields t * h * w rows. Nodata is not dropped: NaN / fill pixels stay in their rows so :func:samples_to_cube can put per-row results back in place (filter rows with e.g. np.isfinite(samples).all(axis=1)).

Parameters:

Name Type Description Default
arr Shaped[ndarray, '*dims']

Input array (any array-like), at least 1-D.

required
band_axis int | tuple[int, ...]

The band (feature) axis, or a tuple of axes flattened together into the columns in the given order. () means no band axis: every axis is a sample axis and the matrix has one column.

-3
sample_axes tuple[int, ...] | None

Axes flattened into rows, in row-major order. Defaults to every non-band axis in ascending order.

None
dtype DTypeLike | None

Optional dtype to coerce arr to first.

None

Returns:

Type Description
``(samples, layout)``

the (n, c) sample matrix and the

SampleLayout

class:SampleLayout needed by :func:samples_to_cube.

Raises:

Type Description
ValueError

If the axes are out of range, repeated, or do not cover every axis of arr exactly once.

Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
def cube_to_samples(
    arr: Shaped[np.ndarray, "*dims"],
    *,
    band_axis: int | tuple[int, ...] = -3,
    sample_axes: tuple[int, ...] | None = None,
    dtype: DTypeLike | None = None,
) -> tuple[Shaped[np.ndarray, "n c"], SampleLayout]:
    """Flatten a cube into an ``(n_samples, n_bands)`` matrix.

    For a canonical ``(c, h, w)`` cube this is ``einx.id("c h w -> (h w)
    c")``; a ``(t, c, h, w)`` stack with the default ``band_axis=-3``
    yields ``t * h * w`` rows. Nodata is not dropped: NaN / fill pixels
    stay in their rows so :func:`samples_to_cube` can put per-row
    results back in place (filter rows with e.g.
    ``np.isfinite(samples).all(axis=1)``).

    Args:
        arr: Input array (any array-like), at least 1-D.
        band_axis: The band (feature) axis, or a tuple of axes flattened
            together into the columns in the given order. ``()`` means
            no band axis: every axis is a sample axis and the matrix has
            one column.
        sample_axes: Axes flattened into rows, in row-major order.
            Defaults to every non-band axis in ascending order.
        dtype: Optional dtype to coerce ``arr`` to first.

    Returns:
        ``(samples, layout)``: the ``(n, c)`` sample matrix and the
        :class:`SampleLayout` needed by :func:`samples_to_cube`.

    Raises:
        ValueError: If the axes are out of range, repeated, or do not
            cover every axis of ``arr`` exactly once.
    """
    values = np.asarray(arr) if dtype is None else np.asarray(arr, dtype=dtype)
    layout = sample_layout(values.shape, band_axis=band_axis, sample_axes=sample_axes)
    names = [f"a{axis}" for axis in range(values.ndim)]
    rows = " ".join(names[axis] for axis in layout.sample_axes)
    cols = " ".join(names[axis] for axis in layout.band_axes)
    samples = einx.id(f"{' '.join(names)} -> ({rows}) ({cols})", values)
    return np.asarray(samples), layout

dim_axis(x, dim, *, name)

The (negative) position of dim in x.

A GeoArray answers from its stored dims; a plain array is read in the 0.2 layout, DIMS[-ndim:]. A 2-D input without a band dim (a single-band map) answers -3, the 0.2 band position, as before.

Parameters:

Name Type Description Default
x Any

The carrier, or a plain array.

required
dim str

The dim name.

required
name str

Operator name for the message.

required

Returns:

Type Description
int

The axis, counted from the end (-3 for the band dim of a

int

("band", "y", "x") carrier), so it also holds for a frame of a

int

stack.

Raises:

Type Description
ValueError

No dim in x (other than the band dim of a 2-D map); the message lists its dims.

Examples:

>>> dim_axis(np.zeros((2, 3, 4, 4)), "band", name="NDVI")
-3
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def dim_axis(x: Any, dim: str, *, name: str) -> int:
    """The (negative) position of ``dim`` in ``x``.

    A `GeoArray` answers from its stored dims; a plain array is read in the
    0.2 layout, ``DIMS[-ndim:]``. A 2-D input without a band dim (a
    single-band map) answers ``-3``, the 0.2 band position, as before.

    Args:
        x: The carrier, or a plain array.
        dim: The dim name.
        name: Operator name for the message.

    Returns:
        The axis, counted from the end (``-3`` for the band dim of a
        ``("band", "y", "x")`` carrier), so it also holds for a frame of a
        stack.

    Raises:
        ValueError: No ``dim`` in ``x`` (other than the band dim of a 2-D
            map); the message lists its dims.

    Examples:
        >>> dim_axis(np.zeros((2, 3, 4, 4)), "band", name="NDVI")
        -3
    """
    ndim = int(np.ndim(x))
    dims = x.dims if isinstance(x, GeoArray) else DIMS[-ndim:]
    if dim in dims:
        return dims.index(dim) - len(dims)
    if dim == "band" and ndim < 3:
        # a single-band map: the 0.2 band position, which callers that
        # accept a 2-D input never index with
        return BAND_AXIS
    if isinstance(x, GeoArray):
        raise ValueError(f"{name}: the carrier has no {dim!r} dim; its dims are {dims}")
    raise ValueError(f"{name}: a {np.ndim(x)}-D array has no {dim!r} dim ({dims})")

fit_once(op, x, is_fitted)

Call op.fit(x) unless is_fitted(); at most once across threads.

Double-checked: the cheap unlocked check keeps already-fitted calls lock-free; the locked re-check makes concurrent first calls fit once. op.fit must publish its state only after computing all of it.

Source code in packages/geotoolz-ops/src/geoops/_src/fitted.py
def fit_once(op: Any, x: Any, is_fitted: Callable[[], bool]) -> None:
    """Call ``op.fit(x)`` unless ``is_fitted()``; at most once across threads.

    Double-checked: the cheap unlocked check keeps already-fitted calls
    lock-free; the locked re-check makes concurrent first calls fit once.
    ``op.fit`` must publish its state only after computing all of it.
    """
    if is_fitted():
        return
    with fit_lock(op):
        if not is_fitted():
            op.fit(x)

grid_matches(a, b, *, atol=0.0, spatial_only=True)

Return whether two rasters share a pixel grid.

Semantics (the one definition used package-wide):

  1. Shape -- the spatial shape shape[-2:] must be equal; with spatial_only=False the full shape must be equal (band / time axes included), for per-pixel reductions over a stack.
  2. Georeferencing -- only when both sides carry a transform (plain arrays have no georeferencing, so the check degrades to the shape comparison). Then the CRS must compare equal and the six affine coefficients must agree within atol (absolute, no relative term): np.allclose(a.transform, b.transform, rtol=0, atol=atol).

The default atol=0.0 is exact equality: sub-pixel grid drift is a real bug source and fails loudly. Pass a small atol explicitly where float round-off in derived transforms must be tolerated.

Parameters:

Name Type Description Default
a Any

First raster (GeoArray or plain array).

required
b Any

Second raster.

required
atol float

Absolute tolerance on each transform coefficient, in CRS units. 0.0 means exact.

0.0
spatial_only bool

Compare only the trailing (H, W) axes (default) instead of the full shape.

True

Returns:

Type Description
bool

True when the grids match.

Raises:

Type Description
TypeError

Either side is a georeader GeoTensor.

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def grid_matches(
    a: Any, b: Any, *, atol: float = 0.0, spatial_only: bool = True
) -> bool:
    """Return whether two rasters share a pixel grid.

    Semantics (the one definition used package-wide):

    1. **Shape** -- the spatial shape ``shape[-2:]`` must be equal; with
       ``spatial_only=False`` the *full* shape must be equal (band / time
       axes included), for per-pixel reductions over a stack.
    2. **Georeferencing** -- only when *both* sides carry a ``transform``
       (plain arrays have no georeferencing, so the check degrades to the
       shape comparison). Then the CRS must compare equal and the six
       affine coefficients must agree within ``atol`` (absolute, no
       relative term): ``np.allclose(a.transform, b.transform, rtol=0,
       atol=atol)``.

    The default ``atol=0.0`` is exact equality: sub-pixel grid drift is a
    real bug source and fails loudly. Pass a small ``atol`` explicitly
    where float round-off in derived transforms must be tolerated.

    Args:
        a: First raster (GeoArray or plain array).
        b: Second raster.
        atol: Absolute tolerance on each transform coefficient, in CRS
            units. ``0.0`` means exact.
        spatial_only: Compare only the trailing ``(H, W)`` axes (default)
            instead of the full shape.

    Returns:
        ``True`` when the grids match.

    Raises:
        TypeError: Either side is a georeader ``GeoTensor``.
    """
    reject_geotensor(a, "grid_matches")
    reject_geotensor(b, "grid_matches")
    shape_a, shape_b = np.shape(a), np.shape(b)
    if spatial_only:
        shape_a, shape_b = shape_a[-2:], shape_b[-2:]
    if shape_a != shape_b:
        return False
    if not (isinstance(a, GeoArray) and isinstance(b, GeoArray)):
        return True
    transform_a, transform_b = a.transform, b.transform
    if a.crs != b.crs:
        return False
    return bool(
        np.allclose(
            np.asarray(tuple(transform_a), dtype=float),
            np.asarray(tuple(transform_b), dtype=float),
            rtol=0.0,
            atol=atol,
        )
    )

invalid_values(x, *, fill_value=INHERIT)

Elementwise invalid mask: non-finite, or equal to the fill value.

Parameters:

Name Type Description Default
x Any

A carrier (GeoArray or plain array) of any shape.

required
fill_value FillValue

Fill value to match. :data:~geoops._src.wrap.INHERIT (default) uses x.fill_value (none for plain arrays); pass one explicitly to override it.

INHERIT

Returns:

Type Description
Bool[ndarray, '*dims']

A boolean array shaped like x; True marks invalid elements.

Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def invalid_values(
    x: Any, *, fill_value: FillValue = INHERIT
) -> Bool[np.ndarray, "*dims"]:
    """Elementwise invalid mask: non-finite, or equal to the fill value.

    Args:
        x: A carrier (GeoArray or plain array) of any shape.
        fill_value: Fill value to match. :data:`~geoops._src.wrap.INHERIT`
            (default) uses ``x.fill_value`` (none for plain
            arrays); pass one explicitly to override it.

    Returns:
        A boolean array shaped like ``x``; ``True`` marks invalid elements.
    """
    values = np.asarray(x)
    invalid = is_fill(values, carrier_fill_value(x, fill_value))
    if np.issubdtype(values.dtype, np.inexact):
        invalid |= ~np.isfinite(values)
    return invalid

jsonable(value, *, strict=False)

Recursively coerce a config value into JSON/YAML-safe builtins.

Parameters:

Name Type Description Default
value Any

Any get_config() leaf or container. Dicts (and other mappings) and lists/tuples are converted recursively (tuples become lists, per strict-JSON convention; keys become strings); numpy arrays become (nested) lists of Python scalars; numpy scalars become their Python equivalents; bytes are decoded as UTF-8 (undecodable bytes replaced); datetime / date become ISO-8601 strings; paths become strings.

required
strict bool

What to do with anything left over. False (default) passes it through unchanged -- the caller knows the value is serialisable, or wants the runtime object back. True guarantees the result survives json.dumps(..., allow_nan=False): any value that is not None / bool / int / str / finite float becomes its repr string (so non-finite floats become 'nan' / 'inf', and runtime objects such as nested estimators, callables or RandomState instances become e.g. 'StandardScaler()') instead of being dropped.

False

Returns:

Type Description
Any

A structure of dicts, lists, and JSON-safe scalars.

Source code in packages/geotoolz-ops/src/geoops/_src/config.py
def jsonable(value: Any, *, strict: bool = False) -> Any:
    """Recursively coerce a config value into JSON/YAML-safe builtins.

    Args:
        value: Any ``get_config()`` leaf or container. Dicts (and other
            mappings) and lists/tuples are converted recursively (tuples
            become lists, per strict-JSON convention; keys become
            strings); numpy arrays become (nested) lists of Python
            scalars; numpy scalars become their Python equivalents;
            ``bytes`` are decoded as UTF-8 (undecodable bytes replaced);
            ``datetime`` / ``date`` become ISO-8601 strings; paths become
            strings.
        strict: What to do with anything left over. ``False`` (default)
            passes it through unchanged -- the caller knows the value
            is serialisable, or wants the runtime object back. ``True``
            guarantees the result survives ``json.dumps(...,
            allow_nan=False)``: any value that is not ``None`` / ``bool``
            / ``int`` / ``str`` / finite ``float`` becomes its ``repr``
            string (so non-finite floats become ``'nan'`` / ``'inf'``,
            and runtime objects such as nested estimators, callables or
            ``RandomState`` instances become e.g. ``'StandardScaler()'``)
            instead of being dropped.

    Returns:
        A structure of dicts, lists, and JSON-safe scalars.
    """
    if isinstance(value, Mapping):
        return {str(k): jsonable(v, strict=strict) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [jsonable(v, strict=strict) for v in value]
    if isinstance(value, np.ndarray):
        return jsonable(value.tolist(), strict=strict)
    if isinstance(value, np.generic):
        # ``.item()`` can itself yield bytes / datetime (``np.bytes_``,
        # ``np.datetime64``), so coerce the Python scalar in turn.
        item = value.item()
        if isinstance(item, np.generic):
            # ``np.longdouble`` / ``np.clongdouble`` have no lossless
            # builtin, so ``.item()`` hands back the numpy scalar itself;
            # narrow to float / complex rather than recursing forever.
            item = complex(item) if np.iscomplexobj(item) else float(item)
        return jsonable(item, strict=strict)
    if isinstance(value, bytes):
        return value.decode("utf-8", errors="replace")
    if isinstance(value, (datetime, date)):
        return value.isoformat()
    if isinstance(value, PurePath):
        return str(value)
    if strict and not _is_strict_json_scalar(value):
        return repr(value)
    return value

keep_band_axis(out, ref)

Keep the time axis of a band-collapsing result on a 4-D input.

Operators that collapse the band axis (a spectral index, a score map) turn (C, H, W) into (H, W). The same reduction over a (T, C, H, W) stack gives (T, H, W), which every carrier would read as (band, y, x); re-inserting a singleton band axis keeps it a time series of single-band maps.

Parameters:

Name Type Description Default
out Any

The reduced result.

required
ref Any

The operator input.

required

Returns:

Type Description
Any

out with a singleton axis inserted at -3 when ref is

Any

4-D and out is 3-D; otherwise out unchanged.

Examples:

>>> keep_band_axis(np.zeros((2, 4, 4)), np.zeros((2, 3, 4, 4))).shape
(2, 1, 4, 4)
>>> keep_band_axis(np.zeros((4, 4)), np.zeros((3, 4, 4))).shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def keep_band_axis(out: Any, ref: Any) -> Any:
    """Keep the time axis of a band-collapsing result on a 4-D input.

    Operators that collapse the band axis (a spectral index, a score map)
    turn ``(C, H, W)`` into ``(H, W)``. The same reduction over a
    ``(T, C, H, W)`` stack gives ``(T, H, W)``, which every carrier would
    read as ``(band, y, x)``; re-inserting a singleton band axis keeps it a
    time series of single-band maps.

    Args:
        out: The reduced result.
        ref: The operator input.

    Returns:
        ``out`` with a singleton axis inserted at ``-3`` when ``ref`` is
        4-D and ``out`` is 3-D; otherwise ``out`` unchanged.

    Examples:
        >>> keep_band_axis(np.zeros((2, 4, 4)), np.zeros((2, 3, 4, 4))).shape
        (2, 1, 4, 4)
        >>> keep_band_axis(np.zeros((4, 4)), np.zeros((3, 4, 4))).shape
        (4, 4)
    """
    if np.ndim(ref) == 4 and np.ndim(out) == 3:
        return np.expand_dims(np.asarray(out), BAND_AXIS)
    return out

map_frames(fn, x, *, name)

Apply a per-scene function to every frame of a (T, C, H, W) stack.

For operators whose semantics are per scene (a segmentation, a QA decode, a colour composite): the result is exactly the per-frame results restacked along a new leading time axis. A time series is a GeoArray whose first dim is named time (("time", "band", "y", "x") or a single-band ("time", "y", "x")), or a 4-D plain array. On a stack with bands, a 2-D per-frame result gains a singleton band axis ((T, 1, H, W), see :func:keep_band_axis); a single-band series stays ("time", "y", "x").

Parameters:

Name Type Description Default
fn Callable[[Any], Any]

Function of one (C, H, W) frame returning an (H, W) or (C', H', W') carrier (GeoArray or ndarray).

required
x Any

The input. Only a time series is split; anything else is passed to fn unchanged.

required
name str

Operator name for error messages.

required

Returns:

Type Description
Any

The (T, C', H', W') restacked result, a GeoArray (georeferenced

Any

like the first frame's result, with its attrs and fill value) when

Any

the per-frame results are GeoArrays, else an ndarray.

Raises:

Type Description
ValueError

If a per-frame result is not a 2-D / 3-D array, or the frames' results differ in shape or grid.

Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def map_frames(fn: Callable[[Any], Any], x: Any, *, name: str) -> Any:
    """Apply a per-scene function to every frame of a ``(T, C, H, W)`` stack.

    For operators whose semantics are per scene (a segmentation, a QA
    decode, a colour composite): the result is exactly the per-frame
    results restacked along a new leading time axis. A time series is a
    `GeoArray` whose first dim is named ``time`` (``("time", "band", "y",
    "x")`` or a single-band ``("time", "y", "x")``), or a 4-D plain array.
    On a stack with bands, a 2-D per-frame result gains a singleton band
    axis (``(T, 1, H, W)``, see :func:`keep_band_axis`); a single-band
    series stays ``("time", "y", "x")``.

    Args:
        fn: Function of one ``(C, H, W)`` frame returning an ``(H, W)`` or
            ``(C', H', W')`` carrier (GeoArray or ndarray).
        x: The input. Only a time series is split; anything else is passed
            to ``fn`` unchanged.
        name: Operator name for error messages.

    Returns:
        The ``(T, C', H', W')`` restacked result, a GeoArray (georeferenced
        like the first frame's result, with its attrs and fill value) when
        the per-frame results are GeoArrays, else an ndarray.

    Raises:
        ValueError: If a per-frame result is not a 2-D / 3-D array, or the
            frames' results differ in shape or grid.
    """
    if not _is_time_stack(x):
        return fn(x)
    outs = [fn(_frame(x, t)) for t in range(np.shape(x)[0])]
    arrays = []
    for out in outs:
        if not isinstance(out, np.ndarray | GeoArray) or out.ndim not in (2, 3):
            raise ValueError(
                f"{name} returns {type(out).__name__} per frame, which cannot be "
                "restacked into a (T, C, H, W) time series; apply it to each "
                "frame separately"
            )
        arr = np.asarray(out)
        arrays.append(arr[None] if arr.ndim == 2 else arr)
    first = outs[0]
    if len({a.shape for a in arrays}) != 1 or any(
        isinstance(o, GeoArray) != isinstance(first, GeoArray)
        or (
            isinstance(o, GeoArray)
            and not np.array_equal(np.asarray(o.transform), np.asarray(first.transform))
        )
        for o in outs[1:]
    ):
        raise ValueError(
            f"{name} produced per-frame results on different grids; they cannot "
            "be restacked into a (T, C, H, W) time series"
        )
    stacked = np.stack(arrays)
    if not isinstance(first, GeoArray):
        return stacked
    # a 2-D result keeps a singleton axis, named like the input's, on a stack
    # with a dim between time and the grid ("band", or any other name;
    # #147); a single-band ("time", "y", "x") series stays one
    channel = (
        "band" if not isinstance(x, GeoArray) else (x.dims[1] if x.ndim > 3 else None)
    )
    if first.ndim == 2 and channel is None:
        stacked = stacked[:, 0]
    frame_dims = (
        first.dims if first.ndim == 3 or channel is None else (channel, *first.dims)
    )
    # each frame lost the time coordinate; the frames are in order, so the
    # input's comes back with the restacked time dim
    time = tuple(c for c in getattr(x, "coords", ()) if c.dim == "time")
    return first.with_data(
        stacked,
        attrs=first.attrs,
        dims=("time", *frame_dims),
        coords=time + tuple(c for c in first.coords if c.dim in frame_dims),
    )

mapping_from_pairs(value)

Accept a mapping or its [[key, value], ...] config form.

Parameters:

Name Type Description Default
value Mapping[Any, Any] | Iterable[Any] | None

A mapping, an iterable of (key, value) pairs as emitted by :func:mapping_to_pairs, or None.

required

Returns:

Type Description
dict[Any, Any] | None

A dict (list-valued keys become tuples), or None.

Raises:

Type Description
ValueError

if an item of the iterable form is not a pair.

Source code in packages/geotoolz-ops/src/geoops/_src/config.py
def mapping_from_pairs(
    value: Mapping[Any, Any] | Iterable[Any] | None,
) -> dict[Any, Any] | None:
    """Accept a mapping or its ``[[key, value], ...]`` config form.

    Args:
        value: A mapping, an iterable of ``(key, value)`` pairs as emitted
            by :func:`mapping_to_pairs`, or ``None``.

    Returns:
        A ``dict`` (list-valued keys become tuples), or ``None``.

    Raises:
        ValueError: if an item of the iterable form is not a pair.
    """
    if value is None:
        return None
    if isinstance(value, Mapping):
        return dict(value)
    out: dict[Any, Any] = {}
    for item in value:
        if not _is_sequence(item) or len(item) != 2:
            raise ValueError(f"expected a mapping or [key, value] pairs; got {item!r}")
        key, val = item
        out[as_tuple(key)] = val
    return out

mapping_to_pairs(mapping)

Emit a mapping config value as [[key, value], ...].

Operator.from_state rejects dict config values (they are reserved for nested-operator payloads) and JSON would stringify non-string keys, so mapping-valued parameters are emitted as a list of pairs. Constructors accept that form back through :func:mapping_from_pairs.

Parameters:

Name Type Description Default
mapping Mapping[Any, Any] | None

The mapping to emit, or None.

required

Returns:

Type Description
list[list[Any]] | None

A JSON-safe list of [key, value] pairs, or None.

Source code in packages/geotoolz-ops/src/geoops/_src/config.py
def mapping_to_pairs(mapping: Mapping[Any, Any] | None) -> list[list[Any]] | None:
    """Emit a mapping config value as ``[[key, value], ...]``.

    ``Operator.from_state`` rejects dict config values (they are reserved
    for nested-operator payloads) and JSON would stringify non-string
    keys, so mapping-valued parameters are emitted as a list of pairs.
    Constructors accept that form back through :func:`mapping_from_pairs`.

    Args:
        mapping: The mapping to emit, or ``None``.

    Returns:
        A JSON-safe list of ``[key, value]`` pairs, or ``None``.
    """
    if mapping is None:
        return None
    return [[jsonable(k), jsonable(v)] for k, v in mapping.items()]

mask_invalid_to_nan(x, *, fill_value=INHERIT, valid=None, dtype=None)

Float copy of x with every invalid pixel set to NaN in all bands.

The result feeds np.nan* reductions (and NaN-propagating filters) so fill pixels never enter a statistic.

Parameters:

Name Type Description Default
x Any

A carrier (GeoArray or plain array) with >= 2 dims.

required
fill_value FillValue

Fill value override (see :func:valid_pixels).

INHERIT
valid ndarray | None

Precomputed validity mask -- (H, W), per-frame (T, H, W) for 4-D input, or x's full shape. Computed with :func:valid_pixels when None.

None
dtype Any

Float dtype of the result. None keeps a float input's dtype and promotes integer input to float32 / float64 (see :func:geoops._src.dtype.as_float).

None

Returns:

Type Description
Float[ndarray, '*dims']

A new float ndarray shaped like x.

Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def mask_invalid_to_nan(
    x: Any,
    *,
    fill_value: FillValue = INHERIT,
    valid: np.ndarray | None = None,
    dtype: Any = None,
) -> Float[np.ndarray, "*dims"]:
    """Float copy of ``x`` with every invalid pixel set to ``NaN`` in all bands.

    The result feeds ``np.nan*`` reductions (and NaN-propagating filters)
    so fill pixels never enter a statistic.

    Args:
        x: A carrier (GeoArray or plain array) with >= 2 dims.
        fill_value: Fill value override (see :func:`valid_pixels`).
        valid: Precomputed validity mask -- ``(H, W)``, per-frame
            ``(T, H, W)`` for 4-D input, or ``x``'s full shape. Computed
            with :func:`valid_pixels` when ``None``.
        dtype: Float dtype of the result. ``None`` keeps a float input's
            dtype and promotes integer input to ``float32`` / ``float64``
            (see :func:`geoops._src.dtype.as_float`).

    Returns:
        A new float ndarray shaped like ``x``.
    """
    from geoops._src.dtype import as_float

    values = np.asarray(x)
    if valid is None:
        valid = valid_pixels(x, fill_value=fill_value)
    out = (
        as_float(values).copy()
        if dtype is None
        else values.astype(np.result_type(dtype, np.float32), copy=True)
    )
    out[~_broadcast_valid(valid, out.shape)] = np.nan
    return out

optional_module(module, extra, *, feature)

Import module, or raise an ImportError naming the extra.

It is pipekit_ops.import_optional with geotoolz-ops's install command. A module that is installed and fails while it is imported raises its own error.

Parameters:

Name Type Description Default
module str

Dotted module name to import (e.g. "sklearn.impute").

required
extra str

The geotoolz extra that provides it (e.g. "learn").

required
feature str

What needs it, for the message (e.g. "ModelOp.save").

required

Returns:

Type Description
ModuleType

The imported module.

Raises:

Type Description
ImportError

module is not installed; the message names the geotoolz-ops[extra] install command.

Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
def optional_module(module: str, extra: str, *, feature: str) -> ModuleType:
    """Import ``module``, or raise an ``ImportError`` naming the extra.

    It is `pipekit_ops.import_optional` with geotoolz-ops's install command. A module
    that is installed and fails while it is imported raises its own error.

    Args:
        module: Dotted module name to import (e.g. ``"sklearn.impute"``).
        extra: The geotoolz extra that provides it (e.g. ``"learn"``).
        feature: What needs it, for the message (e.g. ``"ModelOp.save"``).

    Returns:
        The imported module.

    Raises:
        ImportError: ``module`` is not installed; the message names the
            ``geotoolz-ops[extra]`` install command.
    """
    return import_optional(module, install=f"geotoolz-ops[{extra}]", needed_by=feature)

optional_name(module, name, extra, *, feature)

from module import name lazily, with the extra's install hint.

name may be an attribute of module or one of its submodules (from georeader import read).

Example

optional_name("json", "decoder", "base", feature="doc").name 'json.decoder'

Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
def optional_name(module: str, name: str, extra: str, *, feature: str) -> Any:
    """``from module import name`` lazily, with the extra's install hint.

    ``name`` may be an attribute of ``module`` or one of its submodules
    (``from georeader import read``).

    Example:
        >>> optional_name("json", "decoder", "base", feature="doc").__name__
        'json.decoder'
    """
    parent = optional_module(module, extra, feature=feature)
    try:
        return getattr(parent, name)
    except AttributeError:
        return optional_module(f"{module}.{name}", extra, feature=feature)

optional_root(module, extra, *, feature)

import a.b lazily: import module and return its top package a.

Example

optional_root("json.decoder", "base", feature="doc").name 'json'

Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
def optional_root(module: str, extra: str, *, feature: str) -> ModuleType:
    """``import a.b`` lazily: import ``module`` and return its top package ``a``.

    Example:
        >>> optional_root("json.decoder", "base", feature="doc").__name__
        'json'
    """
    optional_module(module, extra, feature=feature)
    return sys.modules[module.split(".")[0]]

over_frames(apply)

Decorate an operator's _apply to run per frame on a time series.

@over_frames on def _apply(self, x, ...) routes a time series (a carrier led by a time dim, or a 4-D plain array) through :func:map_frames (each frame handled by the undecorated _apply, named after the operator class in errors); other inputs are unaffected. The wrapper keeps the wrapped signature, so pipekit's input introspection is unchanged.

Parameters:

Name Type Description Default
apply Callable[..., Any]

The _apply method; its first positional argument after self is the carrier.

required

Returns:

Type Description
Callable[..., Any]

The wrapped method.

Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def over_frames(apply: Callable[..., Any]) -> Callable[..., Any]:
    """Decorate an operator's ``_apply`` to run per frame on a time series.

    ``@over_frames`` on ``def _apply(self, x, ...)`` routes a time series
    (a carrier led by a ``time`` dim, or a 4-D plain array) through
    :func:`map_frames` (each frame handled by the undecorated ``_apply``,
    named after the operator class in errors); other inputs are
    unaffected. The wrapper keeps the
    wrapped signature, so pipekit's input introspection is unchanged.

    Args:
        apply: The ``_apply`` method; its first positional argument after
            ``self`` is the carrier.

    Returns:
        The wrapped method.
    """

    @functools.wraps(apply)
    def wrapper(self: Any, x: Any, *args: Any, **kwargs: Any) -> Any:
        return map_frames(
            lambda frame: apply(self, frame, *args, **kwargs),
            x,
            name=type(self).__name__,
        )

    return wrapper

pixel_xy(transform, rows, cols)

Return CRS coordinates of pixel centres, vectorised.

Pixel (row, col) covers [row, row + 1) x [col, col + 1) in pixel space, so its centre is (row + 0.5, col + 0.5). Fractional rows / cols (e.g. sub-pixel contour vertices) are offset the same way.

Parameters:

Name Type Description Default
transform Any

The geotransform mapping (col, row) to CRS (x, y): an Affine, six numbers, a (6,) array, or a GeoArray (its transform).

required
rows Any

Row indices (scalar or array).

required
cols Any

Column indices, broadcastable against rows.

required

Returns:

Type Description
Float[ndarray, ...]

(xs, ys) float64 arrays of the broadcast shape of rows and

Float[ndarray, ...]

cols.

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def pixel_xy(
    transform: Any, rows: Any, cols: Any
) -> tuple[Float[np.ndarray, ...], Float[np.ndarray, ...]]:
    """Return CRS coordinates of pixel centres, vectorised.

    Pixel ``(row, col)`` covers ``[row, row + 1) x [col, col + 1)`` in
    pixel space, so its centre is ``(row + 0.5, col + 0.5)``. Fractional
    ``rows`` / ``cols`` (e.g. sub-pixel contour vertices) are offset the
    same way.

    Args:
        transform: The geotransform mapping ``(col, row)`` to CRS
            ``(x, y)``: an ``Affine``, six numbers, a ``(6,)`` array, or a
            `GeoArray` (its transform).
        rows: Row indices (scalar or array).
        cols: Column indices, broadcastable against ``rows``.

    Returns:
        ``(xs, ys)`` float64 arrays of the broadcast shape of ``rows`` and
        ``cols``.
    """
    transform = affine_of(transform)
    rows = np.asarray(rows, dtype=np.float64) + 0.5
    cols = np.asarray(cols, dtype=np.float64) + 0.5
    xs = transform.c + transform.a * cols + transform.b * rows
    ys = transform.f + transform.d * cols + transform.e * rows
    return np.asarray(xs, dtype=np.float64), np.asarray(ys, dtype=np.float64)

reach_of(op)

op's spatial reach in pixels; None for a global one.

op.spatial_reach() when the operator defines it (a reach that depends on a constructor argument), else op.coupling.reach.

Raises:

Type Description
TypeError

op declares no Coupling.

Example

class Box3: ... coupling = Coupling(couples={"space"}, reach=1) reach_of(Box3()) 1

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
def reach_of(op: Any) -> int | None:
    """``op``'s spatial reach in pixels; ``None`` for a global one.

    ``op.spatial_reach()`` when the operator defines it (a reach that depends
    on a constructor argument), else ``op.coupling.reach``.

    Raises:
        TypeError: ``op`` declares no `Coupling`.

    Example:
        >>> class Box3:
        ...     coupling = Coupling(couples={"space"}, reach=1)
        >>> reach_of(Box3())
        1
    """
    method = getattr(op, "spatial_reach", None)
    if callable(method):
        return method()
    coupling = getattr(op, "coupling", None)
    if not isinstance(coupling, Coupling):
        raise TypeError(f"{type(op).__name__} declares no Coupling")
    return coupling.reach

reject_config_summary(value, name)

Refuse a debug summary passed back as a runtime constructor argument.

Operators with an optional runtime argument (an array, a callable) stay reloadable when it is unset, and summarise it as a dict in get_config when it is set. Operator.from_state refuses dict values, but a YAML / Hydra loader would hand the summary back to the constructor; this turns that into a clear error.

Parameters:

Name Type Description Default
value Any

The constructor argument.

required
name str

Parameter name for the error message.

required

Returns:

Type Description
Any

value unchanged.

Raises:

Type Description
TypeError

if value is a mapping (a config summary).

Source code in packages/geotoolz-ops/src/geoops/_src/config.py
def reject_config_summary(value: Any, name: str) -> Any:
    """Refuse a debug summary passed back as a runtime constructor argument.

    Operators with an *optional* runtime argument (an array, a callable)
    stay reloadable when it is unset, and summarise it as a dict in
    ``get_config`` when it is set. ``Operator.from_state`` refuses dict
    values, but a YAML / Hydra loader would hand the summary back to the
    constructor; this turns that into a clear error.

    Args:
        value: The constructor argument.
        name: Parameter name for the error message.

    Returns:
        ``value`` unchanged.

    Raises:
        TypeError: if ``value`` is a mapping (a config summary).
    """
    if isinstance(value, Mapping):
        raise TypeError(
            f"{name} got a config summary; runtime values cannot be rebuilt "
            "from a config — construct the operator in code instead."
        )
    return value

reject_georeader(x, op_name='geotoolz')

Raise TypeError for any georeader object; pass anything else.

A GeoTensor gets reject_geotensor's message (convert it with from_georeader); any other georeader object (a reader, a GeoData) is told to wrap it with source_from_georeader.

Parameters:

Name Type Description Default
x Any

The value to check.

required
op_name str

Who refuses it, for the message.

'geotoolz'

Raises:

Type Description
TypeError

x is a georeader object.

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def reject_georeader(x: Any, op_name: str = "geotoolz") -> None:
    """Raise ``TypeError`` for any georeader object; pass anything else.

    A ``GeoTensor`` gets `reject_geotensor`'s message (convert it with
    ``from_georeader``); any other georeader object (a reader, a
    ``GeoData``) is told to wrap it with ``source_from_georeader``.

    Args:
        x: The value to check.
        op_name: Who refuses it, for the message.

    Raises:
        TypeError: ``x`` is a georeader object.
    """
    reject_geotensor(x, op_name)
    if is_georeader_object(x):
        raise TypeError(
            f"{op_name} takes a geoarray.GeoArray or geoarray.RasterSource, not a "
            f"georeader {type(x).__name__}; wrap the reader at the boundary with "
            "geoarray.interop.georeader.source_from_georeader(reader)"
        )

reject_geotensor(x, op_name='geotoolz')

Raise TypeError for a georeader GeoTensor; pass anything else.

A GeoTensor is an np.ndarray subclass, so np.asarray would take it silently as a plain array and the output would lose its georeferencing. geotoolz takes geoarray.GeoArray instead.

Parameters:

Name Type Description Default
x Any

The value to check.

required
op_name str

Who refuses it, for the message.

'geotoolz'

Raises:

Type Description
TypeError

x is a GeoTensor; the message names from_georeader.

Source code in packages/geotoolz-ops/src/geoops/_src/geotensor.py
def reject_geotensor(x: Any, op_name: str = "geotoolz") -> None:
    """Raise ``TypeError`` for a georeader ``GeoTensor``; pass anything else.

    A ``GeoTensor`` is an ``np.ndarray`` subclass, so ``np.asarray`` would
    take it silently as a plain array and the output would lose its
    georeferencing. geotoolz takes `geoarray.GeoArray` instead.

    Args:
        x: The value to check.
        op_name: Who refuses it, for the message.

    Raises:
        TypeError: ``x`` is a ``GeoTensor``; the message names
            ``from_georeader``.
    """
    if is_geotensor(x):
        raise TypeError(
            f"{op_name} takes a geoarray.GeoArray, not a georeader GeoTensor; "
            f"{_FROM_GEOREADER}"
        )

require_geoarray(x, op_name, *, arg='input', hint='')

Return x if it is a GeoArray, else raise a clear TypeError.

Geo-dependent operators (reprojection, rasterisation, metre-based measurements, ...) are only meaningful with an affine transform attached, so a plain array is refused (and a GeoTensor is refused naming from_georeader).

Parameters:

Name Type Description Default
x Any

The carrier to check.

required
op_name str

Operator name, used as the message prefix.

required
arg str

Which argument x is ("input", "like", "src", ...), for operators with several raster arguments.

'input'
hint str

Optional extra sentence appended to the message (e.g. how to call the plain-array primitive instead).

''

Returns:

Type Description
GeoArray

x unchanged.

Raises:

Type Description
TypeError

"<op_name> requires a georeferenced GeoArray <arg>; got a plain array (<type>)."

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def require_geoarray(
    x: Any, op_name: str, *, arg: str = "input", hint: str = ""
) -> GeoArray:
    """Return ``x`` if it is a `GeoArray`, else raise a clear ``TypeError``.

    Geo-dependent operators (reprojection, rasterisation, metre-based
    measurements, ...) are only meaningful with an affine transform
    attached, so a plain array is refused (and a ``GeoTensor`` is refused
    naming ``from_georeader``).

    Args:
        x: The carrier to check.
        op_name: Operator name, used as the message prefix.
        arg: Which argument ``x`` is (``"input"``, ``"like"``, ``"src"``,
            ...), for operators with several raster arguments.
        hint: Optional extra sentence appended to the message (e.g. how
            to call the plain-array primitive instead).

    Returns:
        ``x`` unchanged.

    Raises:
        TypeError: ``"<op_name> requires a georeferenced GeoArray
            <arg>; got a plain array (<type>)."``
    """
    reject_geotensor(x, op_name)
    if not isinstance(x, GeoArray):
        message = (
            f"{op_name} requires a georeferenced GeoArray {arg}; "
            f"got a plain array ({type(x).__name__})."
        )
        if hint:
            message = f"{message} {hint}"
        raise TypeError(message)
    return x

require_grid_match(a, b, op_name, *, names=('input', 'other'), atol=0.0, spatial_only=True)

Raise unless two carriers of a multi-input operator share a pixel grid.

The one guard behind every multi-input operator (#141): the carriers are combined pixel by pixel, so a second carrier on another grid (a 20 m mask against a 10 m enhancement, a DEM over a neighbouring tile) would give a silently wrong answer. Semantics are those of :func:grid_matches.

Parameters:

Name Type Description Default
a Any

The primary carrier.

required
b Any

The second carrier.

required
op_name str

Operator name for the error message.

required
names tuple[str, str]

How the message refers to a and b.

('input', 'other')
atol float

Absolute tolerance on each transform coefficient.

0.0
spatial_only bool

Compare only the trailing (H, W) axes.

True

Raises:

Type Description
ValueError

The grids differ; the message names the operator and both grids.

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def require_grid_match(
    a: Any,
    b: Any,
    op_name: str,
    *,
    names: tuple[str, str] = ("input", "other"),
    atol: float = 0.0,
    spatial_only: bool = True,
) -> None:
    """Raise unless two carriers of a multi-input operator share a pixel grid.

    The one guard behind every multi-input operator (#141): the carriers
    are combined pixel by pixel, so a second carrier on another grid (a
    20 m mask against a 10 m enhancement, a DEM over a neighbouring
    tile) would give a silently wrong answer. Semantics are those of
    :func:`grid_matches`.

    Args:
        a: The primary carrier.
        b: The second carrier.
        op_name: Operator name for the error message.
        names: How the message refers to ``a`` and ``b``.
        atol: Absolute tolerance on each transform coefficient.
        spatial_only: Compare only the trailing ``(H, W)`` axes.

    Raises:
        ValueError: The grids differ; the message names the operator and
            both grids.
    """
    reject_geotensor(a, op_name)
    reject_geotensor(b, op_name)
    if not grid_matches(a, b, atol=atol, spatial_only=spatial_only):
        raise ValueError(
            f"{op_name}: the {names[1]} pixel grid "
            f"({_describe_grid(b, spatial_only)}) does not match the "
            f"{names[0]} pixel grid ({_describe_grid(a, spatial_only)}). Resample one "
            "onto the other first, e.g. with geoops.geom.ResampleLike."
        )

require_ndim(arr, allowed, name)

Raise a clear ValueError unless arr has an accepted rank.

Parameters:

Name Type Description Default
arr Any

The operator input (any array-like; only its rank is read).

required
allowed int | Iterable[int]

Accepted number(s) of dimensions.

required
name str

Operator name, placed at the start of the message so the failure is attributable (e.g. "OpticalFlowTVL1").

required

Returns:

Type Description
int

arr's number of dimensions.

Raises:

Type Description
ValueError

If arr.ndim is not in allowed. The message names the operator, the accepted ranks and layouts, and the shape.

Examples:

>>> require_ndim(np.zeros((3, 4, 4)), (2, 3), "PhaseAlign")
3
>>> require_ndim(np.zeros((2, 3, 4, 4)), (2, 3), "PhaseAlign")
Traceback (most recent call last):
...
ValueError: PhaseAlign accepts 2-D (H, W) or 3-D (C, H, W) input; ...
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def require_ndim(arr: Any, allowed: int | Iterable[int], name: str) -> int:
    """Raise a clear ``ValueError`` unless ``arr`` has an accepted rank.

    Args:
        arr: The operator input (any array-like; only its rank is read).
        allowed: Accepted number(s) of dimensions.
        name: Operator name, placed at the start of the message so the
            failure is attributable (e.g. ``"OpticalFlowTVL1"``).

    Returns:
        ``arr``'s number of dimensions.

    Raises:
        ValueError: If ``arr.ndim`` is not in ``allowed``. The message names
            the operator, the accepted ranks and layouts, and the shape.

    Examples:
        >>> require_ndim(np.zeros((3, 4, 4)), (2, 3), "PhaseAlign")
        3
        >>> require_ndim(np.zeros((2, 3, 4, 4)), (2, 3), "PhaseAlign")
        Traceback (most recent call last):
        ...
        ValueError: PhaseAlign accepts 2-D (H, W) or 3-D (C, H, W) input; ...
    """
    ranks = (allowed,) if isinstance(allowed, int) else tuple(allowed)
    ndim = int(np.ndim(arr))
    if ndim not in ranks:
        raise ValueError(
            f"{name} accepts {_describe_ranks(ranks)} input; got a {ndim}-D "
            f"array of shape {tuple(np.shape(arr))}"
        )
    return ndim

require_projected_crs(gt, op_name, *, what='areas and distances', metres=True)

Raise unless gt is in a projected CRS (with metre units).

Operators that treat the affine transform as a length (pixel areas, distances, slopes) would silently work in degrees on a geographic CRS, so it is rejected with a hint to reproject first. A carrier without a CRS is accepted as-is: its transform is then assumed to be linear.

Parameters:

Name Type Description Default
gt Any

Georeferenced carrier (anything exposing .crs).

required
op_name str

Operator name used in the error message.

required
what str

What the operator computes, for the message ("areas and distances", "slopes", ...).

'areas and distances'
metres bool

Also require metre linear units (default). Pass False where any linear unit works as long as the data agree with it (e.g. a slope from feet elevations on a US-feet grid).

True

Raises:

Type Description
ValueError

If the CRS is geographic (or otherwise not projected), or -- with metres=True -- projected with non-metre linear units.

Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
def require_projected_crs(
    gt: Any,
    op_name: str,
    *,
    what: str = "areas and distances",
    metres: bool = True,
) -> None:
    """Raise unless ``gt`` is in a projected CRS (with metre units).

    Operators that treat the affine transform as a length (pixel areas,
    distances, slopes) would silently work in degrees on a geographic CRS,
    so it is rejected with a hint to reproject first. A carrier without a
    CRS is accepted as-is: its transform is then assumed to be linear.

    Args:
        gt: Georeferenced carrier (anything exposing ``.crs``).
        op_name: Operator name used in the error message.
        what: What the operator computes, for the message (``"areas and
            distances"``, ``"slopes"``, ...).
        metres: Also require metre linear units (default). Pass
            ``False`` where any linear unit works as long as the data
            agree with it (e.g. a slope from feet elevations on a
            US-feet grid).

    Raises:
        ValueError: If the CRS is geographic (or otherwise not
            projected), or -- with ``metres=True`` -- projected with
            non-metre linear units.
    """
    crs_input = getattr(gt, "crs", None)
    if crs_input is None:
        return
    crs = CRS.from_user_input(crs_input)
    hint = (
        "Reproject to a projected metric CRS (e.g. the local UTM zone) first, "
        "e.g. with geoops.geom.Reproject(dst_crs=...) or "
        "geoops.geom.ReprojectLike."
    )
    if not crs.is_projected:
        kind = "geographic" if crs.is_geographic else "not projected"
        raise ValueError(
            f"{op_name} computes {what} from linear pixel sizes and needs a "
            f"projected CRS; got {crs.name!r} ({kind}). {hint}"
        )
    if metres and any(axis.unit_conversion_factor != 1.0 for axis in crs.axis_info):
        units = sorted({axis.unit_name for axis in crs.axis_info})
        raise ValueError(
            f"{op_name} computes {what} in metres; CRS "
            f"{crs.name!r} has linear units {units}. {hint}"
        )

resolve_band(gt, ref, *, keys=DEFAULT_BAND_KEYS, fallback=None)

Resolve a band reference to an integer band-axis index.

This is the one band-name resolver every operator family uses, so "B04" means the same band in indices, spectral, qa, augment, viz, compositing and plume.

Integer references (any :class:numbers.Integral except bool, so np.int64 works) pass through as int for any carrier — plain ndarrays included. String references are looked up against gt.attrs[key] for each key in keys (in order). The first key whose names contain the requested one wins; a key that exists but doesn't contain the name hands over to the next key. Each value may be a sequence of names (position = band index) or a {name: index} mapping. Missing keys, None values and non-iterable values are skipped silently.

Parameters:

Name Type Description Default
gt GeoArray | ndarray | Any

Carrier GeoArray (its attrs dict is consulted for named lookups) or a plain ndarray.

required
ref BandRef

An integer index (returned as int) or a band name.

required
keys tuple[str, ...]

Attribute keys to consult, in precedence order. Defaults to :data:DEFAULT_BAND_KEYS — ("band_names", "descriptions", "bands").

DEFAULT_BAND_KEYS
fallback Sequence[str] | None

Band names in array order, used only when gt has no attrs at all (a plain ndarray). plume.SBMP passes :data:SENTINEL2_L2A_BANDS here so its "B11" / "B12" defaults work on a bare 12-band L2A array. A GeoArray never uses the fallback.

None

Returns:

Type Description
int

The integer position of the band along the carrier's band axis.

Raises:

Type Description
TypeError

If ref is neither a string nor an integer, or ref is a string, the carrier has no attrs (e.g. a plain np.ndarray) and no fallback was given.

ValueError

If ref is a string and the name is not found under any of the configured keys (or in fallback).

Examples:

>>> import numpy as np
>>> from geoarray import GeoArray
>>> gt = GeoArray(
...     np.zeros((4, 2, 2), dtype=np.float32),
...     (1.0, 0.0, 0.0, 0.0, -1.0, 0.0),
...     "EPSG:4326",
...     attrs={"band_names": ("B02", "B03", "B04", "B08")},
... )
>>> resolve_band(gt, "B04")
2
>>> resolve_band(gt, np.int64(7))  # integers pass through as int
7
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
def resolve_band(
    gt: GeoArray | np.ndarray | Any,
    ref: BandRef,
    *,
    keys: tuple[str, ...] = DEFAULT_BAND_KEYS,
    fallback: Sequence[str] | None = None,
) -> int:
    """Resolve a band reference to an integer band-axis index.

    This is the one band-name resolver every operator family uses, so
    ``"B04"`` means the same band in ``indices``, ``spectral``, ``qa``,
    ``augment``, ``viz``, ``compositing`` and ``plume``.

    Integer references (any :class:`numbers.Integral` except ``bool``,
    so ``np.int64`` works) pass through as ``int`` for any carrier —
    plain ndarrays included. String references are looked up against
    ``gt.attrs[key]`` for each ``key`` in ``keys`` (in order). The first
    key whose names contain the requested one wins; a key that exists
    but doesn't contain the name hands over to the next key. Each value
    may be a sequence of names (position = band index) or a
    ``{name: index}`` mapping. Missing keys, ``None`` values and
    non-iterable values are skipped silently.

    Args:
        gt: Carrier ``GeoArray`` (its ``attrs`` dict is consulted for
            named lookups) or a plain ndarray.
        ref: An integer index (returned as ``int``) or a band name.
        keys: Attribute keys to consult, in precedence order. Defaults
            to :data:`DEFAULT_BAND_KEYS` —
            ``("band_names", "descriptions", "bands")``.
        fallback: Band names in array order, used *only* when ``gt``
            has no ``attrs`` at all (a plain ndarray). ``plume.SBMP``
            passes :data:`SENTINEL2_L2A_BANDS` here so its ``"B11"`` /
            ``"B12"`` defaults work on a bare 12-band L2A array. A
            GeoArray never uses the fallback.

    Returns:
        The integer position of the band along the carrier's band axis.

    Raises:
        TypeError: If ``ref`` is neither a string nor an integer, or
            ``ref`` is a string, the carrier has no ``attrs`` (e.g. a
            plain ``np.ndarray``) and no ``fallback`` was given.
        ValueError: If ``ref`` is a string and the name is not found
            under any of the configured ``keys`` (or in ``fallback``).

    Examples:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> gt = GeoArray(
        ...     np.zeros((4, 2, 2), dtype=np.float32),
        ...     (1.0, 0.0, 0.0, 0.0, -1.0, 0.0),
        ...     "EPSG:4326",
        ...     attrs={"band_names": ("B02", "B03", "B04", "B08")},
        ... )
        >>> resolve_band(gt, "B04")
        2
        >>> resolve_band(gt, np.int64(7))  # integers pass through as int
        7
    """
    if isinstance(ref, numbers.Integral) and not isinstance(ref, bool):
        return int(ref)
    if not isinstance(ref, str):
        raise TypeError(
            f"Band reference must be an integer index or a band name; got {ref!r}"
        )

    attrs = getattr(gt, "attrs", None)
    if attrs is None:
        if fallback is not None:
            try:
                return list(fallback).index(ref)
            except ValueError:
                raise ValueError(
                    f"Band {ref!r} is not one of the default band names "
                    f"{tuple(fallback)} assumed for a plain array; pass an "
                    "integer index or a GeoArray carrying band names."
                ) from None
        raise TypeError(
            f"Named-band resolution ({ref!r}) requires a georeferenced "
            "GeoArray input carrying band-name metadata in `attrs`; got a "
            "plain array. Pass an integer band index instead."
        )

    for key in keys:
        names = _names_under(attrs, key)
        if names is None:
            continue
        if isinstance(names, dict):
            if ref in names:
                return names[ref]
            continue
        if ref in names:
            return names.index(ref)

    raise ValueError(
        f"Band {ref!r} was not found in the band names under GeoArray attrs "
        + ", ".join(f"{k!r}" for k in keys)
        + "."
    )

resolve_bands(gt, refs, *, keys=DEFAULT_BAND_KEYS, fallback=None)

Resolve several band references with :func:resolve_band.

Parameters:

Name Type Description Default
gt GeoArray | ndarray | Any

Carrier whose attrs name the bands.

required
refs Iterable[BandRef]

Integer indices and/or band names, in output order.

required
keys tuple[str, ...]

Attribute keys to consult, in precedence order.

DEFAULT_BAND_KEYS
fallback Sequence[str] | None

Plain-array fallback names (see :func:resolve_band).

None

Returns:

Type Description
list[int]

One integer index per reference, in refs order.

Examples:

>>> class Carrier:
...     attrs = {"band_names": ["B02", "B03", "B04"]}
>>> resolve_bands(Carrier(), ["B04", 0, "B03"])
[2, 0, 1]
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
def resolve_bands(
    gt: GeoArray | np.ndarray | Any,
    refs: Iterable[BandRef],
    *,
    keys: tuple[str, ...] = DEFAULT_BAND_KEYS,
    fallback: Sequence[str] | None = None,
) -> list[int]:
    """Resolve several band references with :func:`resolve_band`.

    Args:
        gt: Carrier whose ``attrs`` name the bands.
        refs: Integer indices and/or band names, in output order.
        keys: Attribute keys to consult, in precedence order.
        fallback: Plain-array fallback names (see :func:`resolve_band`).

    Returns:
        One integer index per reference, in ``refs`` order.

    Examples:
        >>> class Carrier:
        ...     attrs = {"band_names": ["B02", "B03", "B04"]}
        >>> resolve_bands(Carrier(), ["B04", 0, "B03"])
        [2, 0, 1]
    """
    return [resolve_band(gt, ref, keys=keys, fallback=fallback) for ref in refs]

restore_fill(out, valid, fill_value)

Write fill_value into every invalid pixel of an operator output.

Parameters:

Name Type Description Default
out Any

The operator's computed output, (H, W), (C, H, W) or (T, C, H, W).

required
valid ndarray

Validity mask from :func:valid_pixels -- (H, W), (T, H, W) for a 4-D out, or out's full shape.

required
fill_value Any

The output's fill value. None or NaN writes NaN (floating-point outputs only).

required

Returns:

Type Description
ndarray

A copy of out (as an ndarray) whose invalid pixels hold the

ndarray

fill value. When every pixel is valid, out is returned as-is.

Raises:

Type Description
ValueError

If fill_value cannot be represented in out.dtype (None / NaN for an integer or boolean output, or an integer fill outside the dtype's range).

Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def restore_fill(out: Any, valid: np.ndarray, fill_value: Any) -> np.ndarray:
    """Write ``fill_value`` into every invalid pixel of an operator output.

    Args:
        out: The operator's computed output, ``(H, W)``, ``(C, H, W)`` or
            ``(T, C, H, W)``.
        valid: Validity mask from :func:`valid_pixels` -- ``(H, W)``,
            ``(T, H, W)`` for a 4-D ``out``, or ``out``'s full shape.
        fill_value: The *output's* fill value. ``None`` or ``NaN`` writes
            ``NaN`` (floating-point outputs only).

    Returns:
        A copy of ``out`` (as an ndarray) whose invalid pixels hold the
        fill value. When every pixel is valid, ``out`` is returned as-is.

    Raises:
        ValueError: If ``fill_value`` cannot be represented in
            ``out.dtype`` (``None`` / ``NaN`` for an integer or boolean
            output, or an integer fill outside the dtype's range).
    """
    arr = np.asarray(out)
    invalid = ~_broadcast_valid(valid, arr.shape)
    if not invalid.any():
        return arr
    value = np.nan if fill_value is None else fill_value
    if not np.issubdtype(arr.dtype, np.inexact):
        representable = (
            not _is_nan_scalar(value)
            and np.asarray(value).astype(arr.dtype).item() == value
        )
        if not representable:
            raise ValueError(
                f"Cannot write fill value {fill_value!r} into a {arr.dtype} output"
            )
    arr = arr.copy()
    arr[invalid] = value
    return arr

sample_layout(shape, *, band_axis=-3, sample_axes=None)

The :class:SampleLayout :func:cube_to_samples uses for shape.

Lets a caller that only kept the cube's shape rebuild the layout for :func:samples_to_cube. Arguments as in :func:cube_to_samples.

Raises:

Type Description
ValueError

If the axes are out of range, repeated, or do not cover every axis exactly once.

Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
def sample_layout(
    shape: tuple[int, ...],
    *,
    band_axis: int | tuple[int, ...] = -3,
    sample_axes: tuple[int, ...] | None = None,
) -> SampleLayout:
    """The :class:`SampleLayout` :func:`cube_to_samples` uses for ``shape``.

    Lets a caller that only kept the cube's shape rebuild the layout for
    :func:`samples_to_cube`. Arguments as in :func:`cube_to_samples`.

    Raises:
        ValueError: If the axes are out of range, repeated, or do not
            cover every axis exactly once.
    """
    shape = tuple(int(size) for size in shape)
    ndim = len(shape)
    if ndim < 1:
        raise ValueError("cube_to_samples needs at least a 1-D array")
    bands = (band_axis,) if isinstance(band_axis, int) else tuple(band_axis)
    bands = tuple(_normalise(axis, ndim) for axis in bands)
    if sample_axes is None:
        samples = tuple(axis for axis in range(ndim) if axis not in bands)
    else:
        samples = tuple(_normalise(axis, ndim) for axis in sample_axes)
    if sorted(bands + samples) != list(range(ndim)):
        raise ValueError(
            f"band axes {bands} and sample axes {samples} must cover each of "
            f"the {ndim} axes exactly once"
        )
    return SampleLayout(shape=shape, sample_axes=samples, band_axes=bands)

samples_to_cube(samples, layout)

Inverse of :func:cube_to_samples for per-row results.

samples may have any number of columns k (e.g. scores, components, cluster probabilities), not only the original band count. The sample axes are restored in their original (ascending) order and the k columns become a single axis at the position of the first band axis -- the leading axis when the layout had no band axis. A 1-D samples restores just the sample axes. For a single-band-axis layout and k equal to the band count this is the exact inverse of :func:cube_to_samples.

Parameters:

Name Type Description Default
samples Shaped[ndarray, ' n'] | Shaped[ndarray, 'n k']

(n,) or (n, k) array with n == layout.n_samples.

required
layout SampleLayout

The layout returned by :func:cube_to_samples.

required

Returns:

Type Description
ndarray

The reshaped array.

Raises:

Type Description
ValueError

If samples is not 1-D / 2-D or its row count does not match the layout.

Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
def samples_to_cube(
    samples: Shaped[np.ndarray, " n"] | Shaped[np.ndarray, "n k"],
    layout: SampleLayout,
) -> np.ndarray:
    """Inverse of :func:`cube_to_samples` for per-row results.

    ``samples`` may have any number of columns ``k`` (e.g. scores,
    components, cluster probabilities), not only the original band
    count. The sample axes are restored in their original (ascending)
    order and the ``k`` columns become a single axis at the position of
    the first band axis -- the leading axis when the layout had no band
    axis. A 1-D ``samples`` restores just the sample axes. For a
    single-band-axis layout and ``k`` equal to the band count this is the
    exact inverse of :func:`cube_to_samples`.

    Args:
        samples: ``(n,)`` or ``(n, k)`` array with ``n ==
            layout.n_samples``.
        layout: The layout returned by :func:`cube_to_samples`.

    Returns:
        The reshaped array.

    Raises:
        ValueError: If ``samples`` is not 1-D / 2-D or its row count does
            not match the layout.
    """
    values = np.asarray(samples)
    if values.ndim not in (1, 2) or values.shape[0] != layout.n_samples:
        raise ValueError(
            f"samples must be (n,) or (n, k) with n={layout.n_samples}; "
            f"got shape {values.shape}"
        )
    names = {axis: f"a{axis}" for axis in layout.sample_axes}
    sizes: dict[str, Any] = {names[axis]: layout.shape[axis] for axis in names}
    rows = " ".join(names[axis] for axis in layout.sample_axes)
    order = [names[axis] for axis in sorted(layout.sample_axes)]
    if values.ndim == 1:
        return np.asarray(einx.id(f"({rows}) -> {' '.join(order)}", values, **sizes))
    out_axis = min(layout.band_axes) if layout.band_axes else 0
    position = sum(axis < out_axis for axis in layout.sample_axes)
    order.insert(position, "k")
    return np.asarray(einx.id(f"({rows}) k -> {' '.join(order)}", values, **sizes))

single_band(values, *, name='input')

Return the 2-D view of a single-band array.

Parameters:

Name Type Description Default
values Shaped[ndarray, 'h w'] | Shaped[ndarray, '1 h w']

A (H, W) array, or a (1, H, W) cube whose leading band axis is squeezed away. Any array-like is accepted.

required
name str

Label used in the error message so callers can attribute the failure to their own operator (e.g. "Otsu").

'input'

Returns:

Type Description
Shaped[ndarray, 'h w']

The (H, W) array. No copy is made for ndarray input.

Raises:

Type Description
ValueError

If values is neither (H, W) nor (1, H, W).

Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
def single_band(
    values: Shaped[np.ndarray, "h w"] | Shaped[np.ndarray, "1 h w"],
    *,
    name: str = "input",
) -> Shaped[np.ndarray, "h w"]:
    """Return the 2-D view of a single-band array.

    Args:
        values: A ``(H, W)`` array, or a ``(1, H, W)`` cube whose leading
            band axis is squeezed away. Any array-like is accepted.
        name: Label used in the error message so callers can attribute
            the failure to their own operator (e.g. ``"Otsu"``).

    Returns:
        The ``(H, W)`` array. No copy is made for ndarray input.

    Raises:
        ValueError: If ``values`` is neither ``(H, W)`` nor ``(1, H, W)``.
    """
    arr = np.asarray(values)
    if arr.ndim == 2:
        return arr
    if arr.ndim == 3 and arr.shape[0] == 1:
        return arr[0]
    raise ValueError(
        f"{name} expects a single-band map with shape (H, W) or (1, H, W); "
        f"got shape {arr.shape}"
    )

valid_pixels(x, *, fill_value=INHERIT, keep_time=False)

Boolean validity mask over the spatial grid of x.

A pixel is valid when every band at that location is finite and differs from the fill value (see the module docstring for why "any band invalid" invalidates the pixel). Like GeoArray.valid_mask, this recognises NaN fills and non-finite values.

Parameters:

Name Type Description Default
x Any

(H, W), (C, H, W) or (T, C, H, W) carrier.

required
fill_value FillValue

Fill value override; defaults to x.fill_value (none for plain arrays).

INHERIT
keep_time bool

For a 4-D input, return a per-frame (T, H, W) mask instead of reducing over time as well. Ignored for 2-D / 3-D.

False

Returns:

Type Description
Bool[ndarray, '*spatial']

(H, W) boolean mask ((T, H, W) with keep_time on 4-D

Bool[ndarray, '*spatial']

input); True marks valid pixels.

Raises:

Type Description
ValueError

If x has fewer than two dimensions.

Examples:

>>> cube = np.array([[[1.0, np.nan]], [[2.0, 3.0]]])  # (2, 1, 2)
>>> valid_pixels(cube).tolist()
[[True, False]]
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def valid_pixels(
    x: Any, *, fill_value: FillValue = INHERIT, keep_time: bool = False
) -> Bool[np.ndarray, "*spatial"]:
    """Boolean validity mask over the spatial grid of ``x``.

    A pixel is valid when *every* band at that location is finite and
    differs from the fill value (see the module docstring for why "any
    band invalid" invalidates the pixel). Like ``GeoArray.valid_mask``,
    this recognises ``NaN`` fills and non-finite values.

    Args:
        x: ``(H, W)``, ``(C, H, W)`` or ``(T, C, H, W)`` carrier.
        fill_value: Fill value override; defaults to
            ``x.fill_value`` (none for plain arrays).
        keep_time: For a 4-D input, return a per-frame ``(T, H, W)`` mask
            instead of reducing over time as well. Ignored for 2-D / 3-D.

    Returns:
        ``(H, W)`` boolean mask (``(T, H, W)`` with ``keep_time`` on 4-D
        input); ``True`` marks valid pixels.

    Raises:
        ValueError: If ``x`` has fewer than two dimensions.

    Examples:
        >>> cube = np.array([[[1.0, np.nan]], [[2.0, 3.0]]])  # (2, 1, 2)
        >>> valid_pixels(cube).tolist()
        [[True, False]]
    """
    invalid = invalid_values(x, fill_value=fill_value)
    if invalid.ndim < 2:
        raise ValueError(
            f"valid_pixels needs a carrier with >= 2 dims; got shape {invalid.shape}"
        )
    if invalid.ndim == 4 and keep_time:
        return ~invalid.any(axis=1)
    if invalid.ndim > 2:
        invalid = invalid.any(axis=tuple(range(invalid.ndim - 2)))
    return ~invalid

wrap_filled(ref, out, *, fill_value, valid=None, **wrap_kwargs)

Write an explicit fill into ref's invalid pixels and rewrap out.

The one-call form of restore_fill + wrap_like that keeps the declared fill_value in step with the values written.

Parameters:

Name Type Description Default
ref Any

The operator's input carrier.

required
out Any

The computed output, on ref's grid.

required
fill_value Any

The output's fill value (None writes NaN into a float output, and nothing is declared).

required
valid ndarray | None

Validity mask (see :func:restore_fill); defaults to valid_pixels(ref) (per frame for 4-D input).

None
**wrap_kwargs Any

Forwarded to :func:~geoops._src.wrap.wrap_like (attrs, band_names, transform).

{}

Returns:

Type Description
Any

out rewrapped like ref with fill_value declared.

Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
def wrap_filled(
    ref: Any,
    out: Any,
    *,
    fill_value: Any,
    valid: np.ndarray | None = None,
    **wrap_kwargs: Any,
) -> Any:
    """Write an explicit fill into ``ref``'s invalid pixels and rewrap ``out``.

    The one-call form of ``restore_fill`` + ``wrap_like`` that keeps the
    declared ``fill_value`` in step with the values written.

    Args:
        ref: The operator's input carrier.
        out: The computed output, on ``ref``'s grid.
        fill_value: The output's fill value (``None`` writes ``NaN``
            into a float output, and nothing is declared).
        valid: Validity mask (see :func:`restore_fill`); defaults to
            ``valid_pixels(ref)`` (per frame for 4-D input).
        **wrap_kwargs: Forwarded to :func:`~geoops._src.wrap.wrap_like`
            (``attrs``, ``band_names``, ``transform``).

    Returns:
        ``out`` rewrapped like ``ref`` with ``fill_value`` declared.
    """
    if valid is None:
        valid = valid_pixels(ref, keep_time=np.ndim(out) == 4)
    filled = restore_fill(out, valid, fill_value)
    return wrap_like(ref, filled, fill_value=fill_value, **wrap_kwargs)

wrap_like(ref, out, *, fill_value=INHERIT, attrs=None, transform=None, band_names=None, coords=None, crs=INHERIT, dims=None)

Rewrap a computed array to match the carrier of ref.

On a JAX carrier a JAX result stays JAX (under jax.jit too); every other result becomes a NumPy array, as on a NumPy carrier.

Parameters:

Name Type Description Default
ref GeoArray | ndarray

The operator's input carrier -- a geoarray.GeoArray or any plain array-like. A georeader GeoTensor raises.

required
out ndarray

The result array produced by a Tier-A primitive. Unless transform is given, its trailing two (spatial) dims must match ref's when ref is a GeoArray.

required
fill_value FillValue

Fill value for the returned GeoArray. The default, :data:INHERIT, propagates ref.fill_value when out's dtype can hold it, and otherwise takes the output's canonical fill (False for a boolean output, 0 for an integer one: a NaN- or -9999-filled input's mask or labels); any other value is used verbatim, so None means "no fill value" and NaN / False / 0 are explicit fills. Ignored for plain-array carriers.

INHERIT
attrs Mapping[str, Any] | None

Attributes for the output. None (default) derives them from ref.attrs via :func:rewrap_attrs: per-band keys dropped when the band count changes. An explicit mapping is used as-is (the caller owns its band keys); band_names is still written into it.

None
transform Affine | Any | None

Transform for the output (an Affine, six numbers or a (6,) array). None (default) keeps ref.transform and requires out to share ref's spatial shape; pass one for outputs on a new grid (crops, resampling) -- the spatial-shape check is then skipped.

None
band_names Sequence[str] | None

Names of the output bands, written under attrs["band_names"]. Must have one entry per output band (out.shape[-3] for 3-D / 4-D outputs, 1 for 2-D).

None
coords Sequence[Any] | None

Coordinates for the output's non-spatial dims. None (default) keeps each of ref's coordinates whose dim keeps its size; an operator that reorders or picks entries of a dim (band selection) passes them re-indexed, or the old labels would name the wrong pixels.

None
crs Any

CRS for the output (anything geoarray.as_crs accepts), for outputs on a grid in another CRS (a warp). :data:INHERIT (default) keeps ref.crs.

INHERIT
dims Sequence[str] | None

The output's dims, for an output whose non-spatial dims come from another carrier than ref (a swath gridded onto ref's grid). None (default) keeps ref's while the rank holds.

None

Returns:

Type Description
GeoArray | ndarray

A new GeoArray with ref's CRS when ref is a GeoArray,

GeoArray | ndarray

otherwise out as a plain np.ndarray.

Raises:

Type Description
TypeError

ref is a georeader GeoTensor.

ValueError

If transform is None and the spatial shape of out differs from ref's, or if band_names has the wrong length.

Source code in packages/geotoolz-ops/src/geoops/_src/wrap.py
def wrap_like(
    ref: GeoArray | np.ndarray,
    out: np.ndarray,
    *,
    fill_value: FillValue = INHERIT,
    attrs: Mapping[str, Any] | None = None,
    transform: Affine | Any | None = None,
    band_names: Sequence[str] | None = None,
    coords: Sequence[Any] | None = None,
    crs: Any = INHERIT,
    dims: Sequence[str] | None = None,
) -> GeoArray | np.ndarray:
    """Rewrap a computed array to match the carrier of ``ref``.

    On a JAX carrier a JAX result stays JAX (under ``jax.jit`` too); every
    other result becomes a NumPy array, as on a NumPy carrier.

    Args:
        ref: The operator's input carrier -- a `geoarray.GeoArray` or any
            plain array-like. A georeader ``GeoTensor`` raises.
        out: The result array produced by a Tier-A primitive. Unless
            ``transform`` is given, its trailing two (spatial) dims must
            match ``ref``'s when ``ref`` is a GeoArray.
        fill_value: Fill value for the returned GeoArray. The default,
            :data:`INHERIT`, propagates ``ref.fill_value`` when ``out``'s
            dtype can hold it, and otherwise takes the output's canonical
            fill (``False`` for a boolean output, ``0`` for an integer
            one: a NaN- or ``-9999``-filled input's mask or labels); any
            other value is used verbatim, so ``None`` means "no fill value" and
            ``NaN`` / ``False`` / ``0`` are explicit fills. Ignored for
            plain-array carriers.
        attrs: Attributes for the output. ``None`` (default) derives them
            from ``ref.attrs`` via :func:`rewrap_attrs`: per-band keys
            dropped when the band count changes. An explicit mapping is
            used as-is (the caller owns its band keys); ``band_names`` is
            still written into it.
        transform: Transform for the output (an ``Affine``, six numbers or
            a ``(6,)`` array). ``None`` (default) keeps ``ref.transform``
            and requires ``out`` to share ``ref``'s spatial shape; pass one
            for outputs on a new grid (crops, resampling) -- the
            spatial-shape check is then skipped.
        band_names: Names of the output bands, written under
            ``attrs["band_names"]``. Must have one entry per output band
            (``out.shape[-3]`` for 3-D / 4-D outputs, 1 for 2-D).
        coords: Coordinates for the output's non-spatial dims. ``None``
            (default) keeps each of ``ref``'s coordinates whose dim keeps its
            size; an operator that reorders or picks entries of a dim (band
            selection) passes them re-indexed, or the old labels would name
            the wrong pixels.
        crs: CRS for the output (anything ``geoarray.as_crs`` accepts), for
            outputs on a grid in another CRS (a warp). :data:`INHERIT`
            (default) keeps ``ref.crs``.
        dims: The output's dims, for an output whose non-spatial dims come
            from another carrier than ``ref`` (a swath gridded onto ``ref``'s
            grid). ``None`` (default) keeps ``ref``'s while the rank holds.

    Returns:
        A new GeoArray with ``ref``'s CRS when ``ref`` is a GeoArray,
        otherwise ``out`` as a plain ``np.ndarray``.

    Raises:
        TypeError: ``ref`` is a georeader ``GeoTensor``.
        ValueError: If ``transform`` is ``None`` and the spatial shape of
            ``out`` differs from ``ref``'s, or if ``band_names`` has the
            wrong length.
    """
    reject_geotensor(ref)
    if not isinstance(ref, GeoArray):
        return np.asarray(out)

    # a JAX result on a JAX carrier stays JAX (np.asarray would copy it to the
    # host, and fail on a tracer); anything else is NumPy, as before
    on_jax = ref.backend == "jax" and backend_of(out) == "jax"
    values = out if on_jax else np.asarray(out)
    ref_shape = tuple(ref.shape)
    if transform is None:
        if values.shape[-2:] != ref_shape[-2:]:
            raise ValueError(
                "Operation altered spatial dimensions! "
                f"{ref_shape[-2:]} -> {values.shape[-2:]}; pass transform= "
                "for outputs on a new grid."
            )
        transform = ref.transform if on_jax else np.asarray(ref.transform)
    out_bands = band_count(values.shape)
    if attrs is None:
        new_attrs = rewrap_attrs(
            ref.attrs,
            in_bands=band_count(ref_shape),
            out_bands=out_bands,
            band_names=band_names,
        )
    else:
        new_attrs = rewrap_attrs(
            attrs, in_bands=out_bands, out_bands=out_bands, band_names=band_names
        )
    if fill_value is INHERIT:
        # The input's fill when the output dtype holds it; otherwise the
        # canonical fill of the output's meaning (False for a mask, 0 for
        # labels / counts), never a fill the data would read as a value.
        fill_value = fill_for(values.dtype, ref.fill_value)
    # the input's dims while the rank holds; the 0.2 layout otherwise
    # (geoops reads the band axis as -3 until its kernels take dim=, W3)
    if dims is None:
        dims = ref.dims if values.ndim == ref.ndim else DIMS[-values.ndim :]
    extra = {} if coords is None else {"coords": tuple(coords)}
    wrapped = ref.with_data(
        values,
        transform=transform,
        fill_value=fill_value,
        attrs=FrozenAttrs(new_attrs),
        dims=dims,
        **extra,
    )
    return wrapped if crs is INHERIT else wrapped.replace(crs=as_crs(crs))

geoops.testing

Check that an operator keeps the stack's contracts.

check_operator runs, on one operator and one sample scene, the checks geotoolz runs on every built-in operator (tests/test_operator_contract.py): the pipekit Operator contract (keyword-only constructor, JSON config that round-trips, graph mode) and the GeoArray carrier contract (same carrier out, consistent per-band attrs, a fill that suits the output, the input left untouched, (T, C, H, W) stacks handled or rejected, a georeader GeoTensor refused, backends declared and kept). Use it in the tests of an operator you write on top of the stack.

measure_coupling (and measure_frames for an N-ary reducer) measure which dims an operator's output reads across by perturbing a sample, and assert_coupling holds the operator's declared coupling to that measurement.

Example

::

from geoops.testing import check_operator

def test_zscore(scene):  # scene: GeoArray (C, H, W) with some nodata
    out = check_operator(ZScore(mean=0.3, std=0.1), scene)
    assert out.shape == scene.shape

Measured dataclass

What a perturbation probe saw. A lower bound on the true coupling.

Attributes:

Name Type Description
couples frozenset[str]

The dims an output moved across, with a fresh operator per run (a fit on first call fits on the perturbed input).

frozen_space bool | None

Whether a change far from the centre still moved the centre output through an operator fitted once on the unperturbed input (None when not measured).

reach int | None

The largest pixel distance at which a one-pixel change moved an output; None when a far change moved the centre.

regrids bool

The output is on another grid than the input.

kind str

What came out: "transform", "fan-out", "conversion" or "sink".

reads_values bool

Whether any perturbation moved the output.

effects Mapping[str, str]

The measured effect on each dim that is not kept.

time str | None

The time probe: "per frame", "pooled", "reduce", "rejects stack", or None when not run.

stochastic bool

Two identical runs differ, so nothing above is reliable.

notes tuple[str, ...]

Free-form remarks (bands not read, …).

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
@dataclasses.dataclass(frozen=True)
class Measured:
    """What a perturbation probe saw. A lower bound on the true coupling.

    Attributes:
        couples: The dims an output moved across, with a fresh operator per
            run (a fit on first call fits on the perturbed input).
        frozen_space: Whether a change far from the centre still moved the
            centre output through an operator fitted once on the unperturbed
            input (``None`` when not measured).
        reach: The largest pixel distance at which a one-pixel change moved
            an output; ``None`` when a far change moved the centre.
        regrids: The output is on another grid than the input.
        kind: What came out: ``"transform"``, ``"fan-out"``,
            ``"conversion"`` or ``"sink"``.
        reads_values: Whether any perturbation moved the output.
        effects: The measured effect on each dim that is not kept.
        time: The time probe: ``"per frame"``, ``"pooled"``, ``"reduce"``,
            ``"rejects stack"``, or ``None`` when not run.
        stochastic: Two identical runs differ, so nothing above is reliable.
        notes: Free-form remarks (bands not read, …).
    """

    couples: frozenset[str] = frozenset()
    frozen_space: bool | None = None
    reach: int | None = 0
    regrids: bool = False
    kind: str = "transform"
    reads_values: bool = True
    effects: Mapping[str, str] = dataclasses.field(default_factory=dict)
    time: str | None = None
    stochastic: bool = False
    notes: tuple[str, ...] = ()

    @property
    def name(self) -> str:
        """The class name of the measured couples."""
        return class_name(self.couples)

name property

The class name of the measured couples.

assert_coupling(op, measured, *, exact=False)

Assert that op's declared Coupling contains what was measured.

The rules, each a lower bound the declaration must meet:

  • every measured coupled dim is declared, in couples or fit;
  • a change far away that moved the centre output needs a global declaration (reach=None), or space in fit when only a fresh operator moved;
  • a measured reach needs a declared reach at least as large (from reach_of), unless space is fitted;
  • a grid change needs effects={"space": "regrid"};
  • the declared kind is the measured one (source and sink are not measured);
  • an output that moved with the input's values is not declared reads_values=False.

With exact=True the declared couples | fit must also equal the measured couples. A stochastic measurement checks nothing, and neither does a declared source: its output comes from its configuration.

Parameters:

Name Type Description Default
op Any

The operator (an instance; a class attribute is read through it).

required
measured Measured

From measure_coupling or measure_frames.

required
exact bool

Require equality, not just containment.

False

Raises:

Type Description
AssertionError

Naming the operator and every rule it breaks.

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
def assert_coupling(op: Any, measured: Measured, *, exact: bool = False) -> None:
    """Assert that ``op``'s declared `Coupling` contains what was ``measured``.

    The rules, each a lower bound the declaration must meet:

    * every measured coupled dim is declared, in ``couples`` or ``fit``;
    * a change far away that moved the centre output needs a global
      declaration (``reach=None``), or ``space`` in ``fit`` when only a
      fresh operator moved;
    * a measured reach needs a declared reach at least as large (from
      `reach_of`), unless ``space`` is fitted;
    * a grid change needs ``effects={"space": "regrid"}``;
    * the declared ``kind`` is the measured one (``source`` and ``sink``
      are not measured);
    * an output that moved with the input's values is not declared
      ``reads_values=False``.

    With ``exact=True`` the declared ``couples | fit`` must also equal the
    measured couples. A stochastic measurement checks nothing, and neither
    does a declared ``source``: its output comes from its configuration.

    Args:
        op: The operator (an instance; a class attribute is read through it).
        measured: From `measure_coupling` or `measure_frames`.
        exact: Require equality, not just containment.

    Raises:
        AssertionError: Naming the operator and every rule it breaks.
    """
    name = type(op).__name__
    declared = getattr(op, "coupling", None)
    if not isinstance(declared, Coupling):
        raise AssertionError(f"{name} declares no `coupling` (geoops.carrier.Coupling)")
    if measured.stochastic or declared.kind == "source":
        return  # a source's output comes from its configuration, not its input
    problems: list[str] = []
    allowed = declared.couples | declared.fit
    if declared.kind not in ("source", "sink") and measured.kind != declared.kind:
        problems.append(f"kind is {measured.kind!r}, declared {declared.kind!r}")
    if measured.kind == "sink" and declared.kind != "sink":
        problems.append("returns None: declare kind='sink'")
    missing = sorted(measured.couples - allowed)
    if missing:
        problems.append(f"output reads across {missing}, not declared")
    if "space" in measured.couples and "space" in allowed:
        reach = reach_of(op)
        fitted = "space" in declared.fit
        if measured.frozen_space and reach is not None:
            problems.append(
                "a far change moves the centre even with the fit frozen: "
                "declare reach=None"
            )
        if measured.reach is None and reach is not None and not fitted:
            problems.append("a far change moves the centre: declare reach=None")
        if (
            measured.reach is not None
            and reach is not None
            and not fitted
            and measured.reach > reach
        ):
            problems.append(f"measured reach {measured.reach} px > declared {reach} px")
    if measured.reads_values and not declared.reads_values:
        problems.append("the output moves with the input's values: reads_values=True")
    if exact and not measured.reads_values and declared.reads_values:
        problems.append("exact: no perturbation moved the output; reads_values=False")
    if measured.regrids and declared.effect("space") not in ("regrid", "reduce"):
        problems.append("changes the grid: declare effects={'space': 'regrid'}")
    if exact and measured.couples != allowed:
        problems.append(
            f"exact: measured {sorted(measured.couples)}, declared {sorted(allowed)}"
        )
    if problems:
        raise AssertionError(f"{name} coupling: " + "; ".join(problems))

check_operator(op, sample, *others, gap_filler=False)

Assert that op keeps the pipekit Operator and GeoArray contracts.

Parameters:

Name Type Description Default
op Any

The operator instance to check.

required
sample Any

A geoarray.GeoArray scene op accepts — ideally (C, H, W) with band_names in its attrs and a few nodata pixels, so the attrs and nodata checks have something to check.

required
*others Any

Further carriers of a multi-input operator, on sample's grid.

()
gap_filler bool

True for an operator that fills nodata by design; the input's nodata pixels may then become valid.

False

Returns:

Type Description
Any

op(sample, *others), for further assertions.

Raises:

Type Description
AssertionError

Naming the first broken rule.

Source code in packages/geotoolz-ops/src/geoops/testing.py
def check_operator(op: Any, sample: Any, *others: Any, gap_filler: bool = False) -> Any:
    """Assert that ``op`` keeps the pipekit `Operator` and `GeoArray` contracts.

    Args:
        op: The operator instance to check.
        sample: A `geoarray.GeoArray` scene ``op`` accepts — ideally ``(C, H, W)``
            with ``band_names`` in its ``attrs`` and a few nodata pixels, so
            the attrs and nodata checks have something to check.
        *others: Further carriers of a multi-input operator, on ``sample``'s
            grid.
        gap_filler: ``True`` for an operator that fills nodata by design;
            the input's nodata pixels may then become valid.

    Returns:
        ``op(sample, *others)``, for further assertions.

    Raises:
        AssertionError: Naming the first broken rule.
    """
    cls = type(op)
    contract.assert_keyword_only(cls)
    contract.assert_config_round_trips(op)
    contract.assert_graph_mode(op, 1 + len(others))

    before = np.array(sample, copy=True)
    attrs_before = dict(getattr(sample, "attrs", {}) or {})
    out = op(sample, *others)
    np.testing.assert_array_equal(
        np.asarray(sample), before, err_msg=f"{cls.__name__} mutated its input"
    )
    assert dict(getattr(sample, "attrs", {}) or {}) == attrs_before, (
        f"{cls.__name__} mutated its input's attrs"
    )
    if cls._terminal:
        contract.assert_rejects_geotensor(op, sample, *others)
        return out
    contract.assert_same_carrier(sample, out)
    contract.assert_consistent_attrs(sample, out)
    for gt in contract.geoarrays(out):
        contract.assert_fill_matches_dtype(sample, gt, gap_filler=gap_filler)

    try:
        plain = op(np.asarray(sample), *(np.asarray(o) for o in others))
    except (TypeError, ValueError):
        pass  # needs georeferencing or band names: a documented rejection
    else:
        contract.assert_same_carrier(np.asarray(sample), plain)

    if not others and np.ndim(sample) in (2, 3):
        contract.assert_time_stack(op, sample)
    contract.assert_rejects_geotensor(op, sample, *others)
    contract.assert_backends(op, sample, *others)
    return out

measure_coupling(build, sample, *others, call=None)

Measure which dims build()'s output reads across, on sample.

Four probes, each on a fresh operator from build (so a fit on first call fits on the perturbed input):

  1. bump one band at the centre pixel, for each band: which outputs move gives the band dependence and the spatial reach;
  2. bump, darken and brighten a 3 x 3 block in the far corner: if the centre output moves, the operator reads the whole scene;
  3. probe 2 through an operator called once on sample first, so a state fitted on first call is frozen (frozen_space);
  4. on a two-frame (T, C, H, W) stack of a 3-D GeoArray sample, bump frame 0: if frame 1's output moves, the operator pools over time.

Parameters:

Name Type Description Default
build Callable[[], Any]

Builds the operator, with no arguments (a lambda).

required
sample Any

A raster the operator accepts, at least 12 x 12. A local reach is read up to half the sample's side, so a larger sample tells a longer reach from a global one. A (C, H, W) GeoArray probes band and time too.

required
*others Any

Further carriers of a multi-input operator, passed unchanged on every call.

()
call Callable[[Any, Any], Any] | None

call(op, x) instead of op(x, *others), for further carriers built from x.

None

Returns:

Type Description
The `Measured` coupling

a lower bound.

Example

import numpy as np from geoarray import GeoArray scene = GeoArray(np.ones((2, 16, 16)), (10, 0, 0, 0, -10, 0), 32629, ... dims="band y x") measure_coupling(lambda: (lambda x: x.map(np.sqrt)), scene).name 'pointwise'

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
def measure_coupling(
    build: Callable[[], Any],
    sample: Any,
    *others: Any,
    call: Callable[[Any, Any], Any] | None = None,
) -> Measured:
    """Measure which dims ``build()``'s output reads across, on ``sample``.

    Four probes, each on a fresh operator from ``build`` (so a fit on first
    call fits on the perturbed input):

    1. bump one band at the centre pixel, for each band: which outputs move
       gives the band dependence and the spatial reach;
    2. bump, darken and brighten a 3 x 3 block in the far corner: if the
       centre output moves, the operator reads the whole scene;
    3. probe 2 through an operator called once on ``sample`` first, so a
       state fitted on first call is frozen (``frozen_space``);
    4. on a two-frame ``(T, C, H, W)`` stack of a 3-D GeoArray ``sample``,
       bump frame 0: if frame 1's output moves, the operator pools over
       ``time``.

    Args:
        build: Builds the operator, with no arguments (a lambda).
        sample: A raster the operator accepts, at least 12 x 12. A local
            reach is read up to half the sample's side, so a larger sample
            tells a longer reach from a global one. A ``(C, H, W)``
            GeoArray probes ``band`` and ``time`` too.
        *others: Further carriers of a multi-input operator, passed
            unchanged on every call.
        call: ``call(op, x)`` instead of ``op(x, *others)``, for further
            carriers built from ``x``.

    Returns:
        The `Measured` coupling: a lower bound.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> scene = GeoArray(np.ones((2, 16, 16)), (10, 0, 0, 0, -10, 0), 32629,
        ...                  dims="band y x")
        >>> measure_coupling(lambda: (lambda x: x.map(np.sqrt)), scene).name
        'pointwise'
    """
    if min(np.shape(sample)[-2:]) < _MIN_SIDE:
        raise ValueError("measure_coupling needs a sample of at least 12 x 12 pixels")
    centre = _centre(np.shape(sample))

    def run(op: Any, x: Any) -> Any:
        return _quiet(lambda: call(op, x) if call is not None else op(x, *others))

    values = np.asarray(sample)
    y0 = run(build(), sample)
    kind = _kind(y0)
    if bool(np.any(_changed(run(build(), sample), y0))):
        return Measured(kind=kind, stochastic=True, notes=("output varies run to run",))
    grid_kept = _same_grid(sample, y0)
    lead = values.shape[:-2]
    n_lead = prod(lead)
    flat = values.reshape(n_lead, *values.shape[-2:])
    dims = tuple(getattr(sample, "dims", ()) or ())
    lead_dim = "level" if "level" in dims else "band"

    rows: dict[int, set[int]] = {}
    moved_per_band: list[bool] = []
    reach = 0
    for c in range(n_lead):
        bumped = _bump(flat, (c, *centre)).reshape(values.shape)
        moved = _changed(y0, run(build(), _with(sample, bumped)))
        moved_per_band.append(bool(np.any(moved)))
        if isinstance(moved, np.ndarray) and grid_kept and moved.ndim >= 2:
            by_row = moved.reshape(-1, *moved.shape[-2:])
            ys, xs = np.nonzero(by_row.any(axis=0))
            if ys.size:
                dist = np.maximum(abs(ys - centre[0]), abs(xs - centre[1]))
                reach = max(reach, int(dist.max()))
            for k in np.nonzero(by_row[:, centre[0], centre[1]])[0]:
                rows.setdefault(int(k), set()).add(c)

    global_fresh = global_frozen = False
    if grid_kept:
        for far in _far_variants(flat):
            far_x = _with(sample, far.reshape(values.shape))
            moved = _changed(y0, run(build(), far_x))
            global_fresh |= _centre_moved(moved)
            fitted = build()
            first = run(fitted, sample)
            global_frozen |= _centre_moved(_changed(first, run(fitted, far_x)))
        global_fresh |= _hole_reads_scene(build, sample, flat, centre, run)

    reads_values = any(moved_per_band) or global_fresh
    couples: set[str] = set()
    effects: dict[str, str] = {}
    notes: list[str] = []
    if kind != "transform":
        return Measured(kind=kind, reads_values=reads_values, reach=0)

    out_lead = prod(np.shape(y0)[:-2])
    if n_lead > 1:
        mixes = any(len(v) >= 2 for v in rows.values())
        moves = out_lead == n_lead and any(k != c for k, v in rows.items() for c in v)
        read = sum(moved_per_band)
        if mixes:
            couples.add(lead_dim)
        if out_lead == n_lead:
            effect = "mix" if mixes else "select" if moves else "keep"
        elif out_lead < n_lead:
            effect = "reduce" if lead_dim in couples else "select"
        else:
            effect = "expand"
        if effect != "keep":
            effects[lead_dim] = effect
        if read < n_lead:
            notes.append(f"reads {read} of {n_lead} {lead_dim}s")

    measured_reach: int | None = reach
    if grid_kept:
        if reach > 0 or global_fresh:
            couples.add("space")
        if global_fresh:
            measured_reach = None
    else:
        # a new grid: no per-pixel map to read, so no spatial coupling is
        # measured (a lower bound); the effect is what the probe can see
        effects["space"] = "regrid"

    time = _probe_time(build, sample, run)
    if time in ("pooled", "reduce"):
        couples.add("time")
    if time in ("reduce", "select"):
        effects["time"] = time
    return Measured(
        couples=frozenset(couples),
        frozen_space=global_frozen if grid_kept else None,
        reach=measured_reach,
        regrids=not grid_kept,
        kind=kind,
        reads_values=reads_values,
        effects=effects,
        time=time,
        notes=tuple(notes),
    )

measure_frames(build, frames, *, as_list=False)

Measure an N-ary reducer: which input frames reach its output.

Each frame in turn gets its centre pixel bumped. Two or more frames reaching the output is a time coupling; one is a selection.

Parameters:

Name Type Description Default
build Callable[[], Any]

Builds the operator, with no arguments.

required
frames Sequence[Any]

The inputs, one per frame; an item may be a tuple whose first element is the raster ((frame, mask)).

required
as_list bool

Call op(frames) instead of op(*frames).

False

Returns:

Type Description
Measured

The Measured coupling along time (or a band join).

Example

import numpy as np frames = [np.full((16, 16), float(t)) for t in range(3)] mean = lambda: (lambda *xs: np.mean(np.stack(xs), axis=0)) measure_frames(mean, frames).name 'temporal'

Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
def measure_frames(
    build: Callable[[], Any], frames: Sequence[Any], *, as_list: bool = False
) -> Measured:
    """Measure an N-ary reducer: which input frames reach its output.

    Each frame in turn gets its centre pixel bumped. Two or more frames
    reaching the output is a ``time`` coupling; one is a selection.

    Args:
        build: Builds the operator, with no arguments.
        frames: The inputs, one per frame; an item may be a tuple whose
            first element is the raster (``(frame, mask)``).
        as_list: Call ``op(frames)`` instead of ``op(*frames)``.

    Returns:
        The `Measured` coupling along ``time`` (or a band join).

    Example:
        >>> import numpy as np
        >>> frames = [np.full((16, 16), float(t)) for t in range(3)]
        >>> mean = lambda: (lambda *xs: np.mean(np.stack(xs), axis=0))
        >>> measure_frames(mean, frames).name
        'temporal'
    """

    def run(items: Sequence[Any]) -> Any:
        op = build()
        return _quiet(lambda: op(list(items)) if as_list else op(*items))

    y0 = run(frames)
    first = frames[0][0] if isinstance(frames[0], tuple) else frames[0]
    arrays = _arrays(y0)
    in_lead = prod(np.shape(first)[:-2])
    if arrays is not None and len(arrays) == 1:
        out_lead = prod(arrays[0].shape[:-2])
        if out_lead == len(frames) * in_lead > in_lead:
            return Measured(effects={"band": "join"})
    reaches = 0
    for t, item in enumerate(frames):
        frame = item[0] if isinstance(item, tuple) else item
        index = (..., *_centre(np.shape(frame)))
        new = _with(frame, _bump(np.asarray(frame), index))
        bumped = list(frames)
        bumped[t] = (new, *item[1:]) if isinstance(item, tuple) else new
        reaches += bool(np.any(_changed(y0, run(bumped))))
    if arrays is None or len(arrays) != 1:
        effect = "keep"
    else:
        effect = "reduce" if reaches >= 2 else "select"
    return Measured(
        couples=frozenset({"time"}) if reaches >= 2 else frozenset(),
        effects={"time": effect},
        kind=_kind(y0) if arrays is None else "transform",
    )