Skip to content

Einx

geoops.einx wraps einx — universal einstein-notation tensor ops — as carrier-aware Operators. einx is a core dependency: the same notation also powers the internal linear algebra of the Tier-A primitives (covariance products, matched-filter scoring, PCA projections, channel-order flips).

The spatial-survival rule decides what a pattern does to geospatial metadata: if the output expression ends in the bare spatial axes (... y x) and neither axis is composed anywhere in the pattern, a GeoArray input returns a GeoArray (transform/CRS/fill preserved). Any pattern that consumes, moves, or recomposes a spatial axis returns a plain np.ndarray. SpatialPool is the deliberate exception — it rescales the transform to the pooled grid.

Nodata. SpatialPool and PerBandReduce exclude invalid pixels (non-finite, or equal to the carrier's fill_value in any band) with NaN-aware reductions; SpatialPool writes its output fill into blocks with no valid pixel (NaN for float results of an integer input, otherwise the input's fill). Einx runs einx on the raw values, and a value-changing, spatially-surviving output declares an explicit fill (NaN for floats, False for booleans) written into the carrier's invalid pixels. As everywhere in geotoolz, fill_value=0 means 0 is nodata — set it to None or NaN when 0 is real data.

All presets broadcast over leading axes, so (T, C, H, W) time stacks work too.

import geoops as gz

mean_map = gz.Einx(op="mean", pattern="c y x -> y x")     # GeoArray -> GeoArray
band_stats = gz.PerBandReduce(reduce="std")               # GeoArray -> (C,) ndarray
scores = gz.Einx(op="dot", pattern="band y x, sig band -> sig y x")
coarse = gz.SpatialPool(reduce="mean", factor=4)          # transform rescaled
pooled = gz.Einx(op="mean", pattern="c (y py) (x px) -> c y x", op_kwargs={"py": 2, "px": 2})

geoops.einx.Einx

Bases: Operator

Apply any einx operation to the carrier, geo-aware.

The pattern is analyzed once at construction with geoops.einx._src.array.spatial_survives: when the trailing two axes of both the output and the carrier's (first) input expression are the bare spatial axes (default ("y", "x")) and no spatial axis is composed anywhere, a GeoArray input comes back as a GeoArray (transform / CRS propagated via wrap_like, with fresh attrs whose per-band keys are dropped when the band count changes); otherwise the result is a plain np.ndarray. Plain-array input always returns a plain array.

Nodata: einx runs on the raw values. For a spatially-surviving output the pixel grid is unchanged, so:

  • "id" / "rearrange" only move values and inherit the carrier's fill_value;
  • every other op changes the values, so the output gets an explicit fill — NaN for float outputs, False for boolean outputs, the input's fill for integer outputs when representable (else none) — written into every pixel that was invalid in the carrier (non-finite or equal to its fill in any band; see geoops._src.valid). With fill_value=0 on the input, 0 is nodata (georeader's convention); pass None or NaN on the carrier when 0 is real data.

Non-surviving outputs (e.g. "c y x -> c") are raw einx results: a fill or NaN pixel enters the statistic. Use PerBandReduce / SpatialPool for nodata-aware reductions.

Multi-input patterns work by passing extra arrays at call time — the first argument is the carrier, the rest are unwrapped to plain arrays.

Parameters:

Name Type Description Default
op str

einx entry-point name ("id", "mean", "sum", "max", "dot", "add", ...). Callable-taking entry points ("vmap", ...) are rejected — configs must stay YAML-serializable.

required
pattern str

The einx pattern string.

required
spatial_axes tuple[str, str] | list[str]

Names of the (row, column) axes in the pattern. Default ("y", "x").

('y', 'x')
op_kwargs Mapping[str, Any] | Iterable[Any] | None

Extra keyword arguments forwarded to the einx call: axis sizes named in pattern ({"py": 2}) or einx's backend / keepdims. Must be JSON-serializable. get_config nests them under "op_kwargs" as [[name, value], ...] pairs (Operator.from_state rejects dict values); that form is accepted back here.

None
**axis_kwargs Any

Shorthand for op_kwargs entries (Einx(..., py=2)); merged into op_kwargs with the same validation, so a misspelled keyword such as spatial_axis= raises instead of reaching einx.

{}

Raises:

Type Description
ValueError

Unsupported op, unbalanced pattern, wrong number of spatial_axes, or an op_kwargs name that is neither an axis of pattern nor backend / keepdims; at call time, a pattern that does not match the input's rank / shape.

Examples:

>>> import geoops as gz
>>> # Per-pixel mean over bands; spatial survives -> GeoArray out.
>>> mean_map = gz.Einx(op="mean", pattern="c y x -> y x")
>>> # Matched-filter scoring against a signature matrix.
>>> score = gz.Einx(op="dot", pattern="band y x, sig band -> sig y x")
>>> scores = score(reflectance_gt, signatures)
>>> # Axis sizes for composed axes.
>>> pooled = gz.Einx(
...     op="mean",
...     pattern="c (y py) (x px) -> c y x",
...     op_kwargs={"py": 2, "px": 2},
... )
Source code in packages/geotoolz-ops/src/geoops/einx/_src/operators.py
class Einx(Operator):
    """Apply any einx operation to the carrier, geo-aware.

    The pattern is analyzed once at construction with
    `geoops.einx._src.array.spatial_survives`: when the trailing two
    axes of both the output and the carrier's (first) input expression
    are the bare spatial axes (default ``("y", "x")``) and no spatial
    axis is composed anywhere, a ``GeoArray`` input comes
    back as a ``GeoArray`` (transform / CRS propagated via
    ``wrap_like``, with fresh ``attrs`` whose per-band keys are dropped
    when the band count changes); otherwise the result is a plain
    ``np.ndarray``. Plain-array input always returns a plain array.

    Nodata: einx runs on the raw values. For a spatially-surviving
    output the pixel grid is unchanged, so:

    - ``"id"`` / ``"rearrange"`` only move values and inherit the
      carrier's ``fill_value``;
    - every other op changes the values, so the output gets an explicit
      fill — ``NaN`` for float outputs, ``False`` for boolean outputs,
      the input's fill for integer outputs when representable (else
      none) — written into every pixel that was invalid in the carrier
      (non-finite or equal to its fill in any band; see
      `geoops._src.valid`). With ``fill_value=0`` on the
      input, 0 is nodata (georeader's convention); pass ``None`` or
      ``NaN`` on the carrier when 0 is real data.

    Non-surviving outputs (e.g. ``"c y x -> c"``) are raw einx results:
    a fill or NaN pixel enters the statistic. Use `PerBandReduce` /
    `SpatialPool` for nodata-aware reductions.

    Multi-input patterns work by passing extra arrays at call time —
    the first argument is the carrier, the rest are unwrapped to plain
    arrays.

    Args:
        op: einx entry-point name (``"id"``, ``"mean"``, ``"sum"``,
            ``"max"``, ``"dot"``, ``"add"``, ...). Callable-taking
            entry points (``"vmap"``, ...) are rejected — configs must
            stay YAML-serializable.
        pattern: The einx pattern string.
        spatial_axes: Names of the (row, column) axes in the pattern.
            Default ``("y", "x")``.
        op_kwargs: Extra keyword arguments forwarded to the einx call:
            axis sizes named in ``pattern`` (``{"py": 2}``) or einx's
            ``backend`` / ``keepdims``. Must be JSON-serializable.
            ``get_config`` nests them under ``"op_kwargs"`` as
            ``[[name, value], ...]`` pairs (``Operator.from_state`` rejects
            dict values); that form is accepted back here.
        **axis_kwargs: Shorthand for ``op_kwargs`` entries
            (``Einx(..., py=2)``); merged into ``op_kwargs`` with the same
            validation, so a misspelled keyword such as ``spatial_axis=``
            raises instead of reaching einx.

    Raises:
        ValueError: Unsupported ``op``, unbalanced pattern, wrong number
            of ``spatial_axes``, or an ``op_kwargs`` name that is neither
            an axis of ``pattern`` nor ``backend`` / ``keepdims``; at call
            time, a pattern that does not match the input's rank / shape.

    Examples:
        >>> import geoops as gz
        >>> # Per-pixel mean over bands; spatial survives -> GeoArray out.
        >>> mean_map = gz.Einx(op="mean", pattern="c y x -> y x")
        >>> # Matched-filter scoring against a signature matrix.
        >>> score = gz.Einx(op="dot", pattern="band y x, sig band -> sig y x")
        >>> scores = score(reflectance_gt, signatures)  # doctest: +SKIP
        >>> # Axis sizes for composed axes.
        >>> pooled = gz.Einx(
        ...     op="mean",
        ...     pattern="c (y py) (x px) -> c y x",
        ...     op_kwargs={"py": 2, "px": 2},
        ... )
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # any einx pattern: unknown until configured
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"}, reach=None
    )

    def __init__(
        self,
        *,
        op: str,
        pattern: str,
        spatial_axes: tuple[str, str] | list[str] = ("y", "x"),
        op_kwargs: Mapping[str, Any] | Iterable[Any] | None = None,
        **axis_kwargs: Any,
    ) -> None:
        self.op = op
        self.pattern = pattern
        self.spatial_axes = tuple(spatial_axes)
        if len(self.spatial_axes) != 2:
            raise ValueError(
                f"Einx: spatial_axes must name exactly two axes; got {spatial_axes!r}"
            )
        kwargs = mapping_from_pairs(op_kwargs) or {}
        clash = sorted(set(kwargs) & set(axis_kwargs))
        if clash:
            raise ValueError(f"Einx: {clash} given both in op_kwargs and as keywords")
        kwargs.update(axis_kwargs)
        allowed = _pattern_axis_names(pattern) | _EINX_CALL_KWARGS
        unknown = sorted(set(kwargs) - allowed)
        if unknown:
            raise ValueError(
                f"Einx: unknown keyword argument(s) {unknown}: op_kwargs must "
                f"name axes of the pattern {pattern!r} or be one of "
                f"{sorted(_EINX_CALL_KWARGS)}"
            )
        self.op_kwargs = kwargs
        self._fn = _resolve_op(op)
        # Also validates bracket balance eagerly (raises ValueError).
        self._survives = spatial_survives(pattern, self.spatial_axes)

    def _apply(
        self, gt: GeoArray | np.ndarray, *extra: GeoArray | np.ndarray
    ) -> GeoArray | np.ndarray:
        for a in (gt, *extra):
            reject_geotensor(a, type(self).__name__)
        arrays = [np.asarray(a) for a in (gt, *extra)]
        try:
            out = np.asarray(self._fn(self.pattern, *arrays, **self.op_kwargs))
        except Exception as exc:
            # einx's rank / solver errors don't say which operator or shape
            # failed; re-raise them as a ValueError that does.
            if not type(exc).__module__.startswith("einx"):
                raise
            shapes = ", ".join(str(a.shape) for a in arrays)
            raise ValueError(
                f"Einx: pattern {self.pattern!r} does not match input shape(s) "
                f"{shapes}: {type(exc).__name__}"
            ) from exc
        if not self._survives:
            return out
        if self.op in _VALUE_PRESERVING_OPS or not isinstance(gt, GeoArray):
            return wrap_like(gt, out)
        fill = _output_fill(out.dtype, carrier_fill_value(gt))
        valid = self._valid_mask(gt, out)
        if fill is not None:
            out = restore_fill(out, valid, fill)
        return wrap_like(gt, out, fill_value=fill)

    def _valid_mask(self, gt: GeoArray, out: np.ndarray) -> np.ndarray:
        """Carrier validity mask broadcastable against ``out``.

        Per-frame ``(T, H, W)`` when a 4-D carrier's leading (time) axis
        is also the output's leading axis; otherwise a conservative
        ``(H, W)`` mask (a pixel invalid in any frame / band).
        """
        if np.ndim(gt) == 4 and out.ndim >= 3:
            lhs = self.pattern.split("->", 1)[0].split(",", 1)[0]
            in_tokens = _tokenize(lhs, pattern=self.pattern)
            out_tokens = _tokenize(
                self.pattern.rsplit("->", 1)[1], pattern=self.pattern
            )
            same_time = (
                len(in_tokens) == 4
                and len(out_tokens) == out.ndim
                and in_tokens[0] == out_tokens[0]
                and _AXIS_NAME.fullmatch(in_tokens[0]) is not None
            )
            if same_time:
                return valid_pixels(gt, keep_time=True)
        return valid_pixels(gt)

    def get_config(self) -> dict[str, Any]:
        return {
            "op": self.op,
            "pattern": self.pattern,
            "spatial_axes": list(self.spatial_axes),
            "op_kwargs": mapping_to_pairs(self.op_kwargs),
        }

geoops.einx.CHWtoHWC

Bases: Einx

Reorder a (..., C, H, W) cube to channels-last (..., H, W, C).

Display / ML-interop helper (matplotlib imshow, most vision frameworks expect channels-last). Leading axes (e.g. time) are kept. The output is always a plain np.ndarray: with channels trailing, the spatial axes no longer sit in the trailing-two positions a GeoArray requires.

Examples:

>>> import geoops as gz
>>> rgb = gz.CHWtoHWC()(composite_gt)  # (H, W, C) ndarray
Source code in packages/geotoolz-ops/src/geoops/einx/_src/operators.py
class CHWtoHWC(Einx):
    """Reorder a ``(..., C, H, W)`` cube to channels-last ``(..., H, W, C)``.

    Display / ML-interop helper (matplotlib ``imshow``, most vision
    frameworks expect channels-last). Leading axes (e.g. time) are kept.
    The output is always a plain ``np.ndarray``: with channels trailing,
    the spatial axes no longer sit in the trailing-two positions a
    ``GeoArray`` requires.

    Examples:
        >>> import geoops as gz
        >>> rgb = gz.CHWtoHWC()(composite_gt)  # (H, W, C) ndarray  # doctest: +SKIP
    """

    # a reordering of the axes
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self) -> None:
        super().__init__(op="id", pattern="... c y x -> ... y x c")

    def get_config(self) -> dict[str, Any]:
        return {}

geoops.einx.HWCtoCHW

Bases: Einx

Reorder a channels-last (..., H, W, C) array to (..., C, H, W).

Inverse of CHWtoHWC, for bringing external channels-last arrays into geotoolz's channel-first convention. Input is typically a plain array (channels-last carriers can't be GeoArrays), and the output is a plain array — rewrapping needs a reference carrier's metadata, e.g. wrap_like(reference_gt, out) downstream.

Examples:

>>> import geoops as gz
>>> chw = gz.HWCtoCHW()(hwc_array)
Source code in packages/geotoolz-ops/src/geoops/einx/_src/operators.py
class HWCtoCHW(Einx):
    """Reorder a channels-last ``(..., H, W, C)`` array to ``(..., C, H, W)``.

    Inverse of `CHWtoHWC`, for bringing external channels-last arrays
    into geotoolz's channel-first convention. Input is typically a
    plain array (channels-last carriers can't be GeoArrays), and the
    output is a plain array — rewrapping needs a reference carrier's
    metadata, e.g. ``wrap_like(reference_gt, out)`` downstream.

    Examples:
        >>> import geoops as gz
        >>> chw = gz.HWCtoCHW()(hwc_array)
    """

    # a reordering of the axes
    coupling: ClassVar[Coupling] = Coupling(effects={"space": "regrid"})

    def __init__(self) -> None:
        # `spatial_survives` rejects this pattern (the carrier's input
        # doesn't end in `y x`), so the output is always a plain array.
        super().__init__(op="id", pattern="... y x c -> ... c y x")

    def get_config(self) -> dict[str, Any]:
        return {}

geoops.einx.PerBandReduce

Bases: Operator

Reduce each band over its spatial extent to one scalar, ignoring nodata.

(C, H, W) in, (C,) out; (T, C, H, W) in, (T, C) out (einx pattern "... c y x -> ... c") — band-wise statistics for QA summaries, normalization fitting, or feature vectors. Spatial structure is consumed, so the result is always a plain float np.ndarray regardless of carrier.

NaN-aware, like geoops.normalize.PerBandStats: invalid pixels — non-finite or equal to the carrier's fill_value in any band (per frame for 4-D input; see geoops._src.valid) — are excluded from every band's statistic. A band (frame) with no valid pixel reduces to NaN. With fill_value=0 on the input, 0 is nodata (georeader's convention); pass None or NaN on the carrier when 0 is real data.

Parameters:

Name Type Description Default
reduce str

einx reduction name: "mean" (default), "sum", "prod", "max", "min", "std", "var".

'mean'

Raises:

Type Description
ValueError

Unsupported reduce; at call time, an input with fewer than three dims (there is no band axis).

Examples:

>>> import geoops as gz
>>> band_means = gz.PerBandReduce()(reflectance_gt)  # (C,)
Source code in packages/geotoolz-ops/src/geoops/einx/_src/operators.py
class PerBandReduce(Operator):
    """Reduce each band over its spatial extent to one scalar, ignoring nodata.

    ``(C, H, W)`` in, ``(C,)`` out; ``(T, C, H, W)`` in, ``(T, C)`` out
    (einx pattern ``"... c y x -> ... c"``) — band-wise statistics for QA
    summaries, normalization fitting, or feature vectors. Spatial
    structure is consumed, so the result is always a plain float
    ``np.ndarray`` regardless of carrier.

    NaN-aware, like `geoops.normalize.PerBandStats`: invalid pixels —
    non-finite or equal to the carrier's ``fill_value`` in any
    band (per frame for 4-D input; see `geoops._src.valid`) — are
    excluded from every band's statistic. A band (frame) with no valid
    pixel reduces to ``NaN``. With ``fill_value=0`` on the input,
    0 is nodata (georeader's convention); pass ``None`` or ``NaN`` on the
    carrier when 0 is real data.

    Args:
        reduce: einx reduction name: ``"mean"`` (default), ``"sum"``,
            ``"prod"``, ``"max"``, ``"min"``, ``"std"``, ``"var"``.

    Raises:
        ValueError: Unsupported ``reduce``; at call time, an input with
            fewer than three dims (there is no band axis).

    Examples:
        >>> import geoops as gz
        >>> band_means = gz.PerBandReduce()(reflectance_gt)  # (C,)  # doctest: +SKIP
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each band reduced over the scene to one value: a vector, not a raster
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, effects={"space": "reduce"}, reach=None, kind="conversion"
    )

    pattern = "... c y x -> ... c"

    def __init__(self, *, reduce: str = "mean") -> None:
        self._fn = _resolve_reduction(reduce, name="PerBandReduce")
        self.reduce = reduce

    def _apply(self, gt: GeoArray | np.ndarray) -> np.ndarray:
        if np.ndim(gt) < 3:
            raise ValueError(
                "PerBandReduce: expected a (C, H, W) or (T, C, H, W) input; "
                f"got shape {np.shape(gt)}"
            )
        valid = valid_pixels(gt, keep_time=True)
        data = _nan_float(gt, valid)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            out = np.asarray(self._fn(self.pattern, data))
        # np.nansum / np.nanprod return 0 / 1 for all-NaN slices.
        empty = ~np.asarray(valid.any(axis=(-2, -1)))  # () or (T,)
        if empty.any():
            out = out.copy()
            out[np.broadcast_to(empty[..., None], out.shape)] = np.nan
        return out

geoops.einx.SpatialPool

Bases: Operator

Downsample the spatial grid by integer factors, updating the transform.

Non-overlapping block pooling via einx ("... (y py) (x px) -> ... y x"), so (H, W), (C, H, W) and (T, C, H, W) inputs all work. This is the one einx preset that changes the geotransform rather than preserving or dropping it: a GeoArray input returns a GeoArray whose pixel size is scaled by the pool factors (same origin, coarser grid, fresh attrs). Plain-array input returns a plain array.

Nodata: invalid pixels — non-finite, or equal to the carrier's fill_value in any band (per frame for 4-D input; see geoops._src.valid) — are excluded with a NaN-aware reduction, so a block pools only its valid pixels. A block with no valid pixel is written as the output fill, which the output also declares: NaN for float results of an integer input or of an input without a fill, otherwise the input's fill_value. With fill_value=0 on the input, 0 is nodata (georeader's convention); pass None or NaN on the carrier when 0 is real data.

Output dtype: "max" / "min" keep an integer input's dtype; every other reduction returns floats (float64 for integer input, the input's float dtype otherwise).

Parameters:

Name Type Description Default
reduce str

einx reduction applied per block: "mean" (default), "sum", "prod", "max", "min", "std", "var".

'mean'
factor int | tuple[int, int] | list[int]

Pool factor — one int for square blocks or a (row, col) pair (numpy integers accepted, bool rejected). Spatial dims must divide evenly; otherwise a ValueError names the offending shape (crop or pad first, e.g. with geom.CropTo / geom.PadTo).

2

Raises:

Type Description
TypeError

factor is not an int or a pair of ints.

ValueError

factor < 1 or not a pair, or unsupported reduce.

Examples:

>>> import geoops as gz
>>> coarse = gz.SpatialPool(reduce="mean", factor=4)(scene_gt)
Source code in packages/geotoolz-ops/src/geoops/einx/_src/operators.py
class SpatialPool(Operator):
    """Downsample the spatial grid by integer factors, updating the transform.

    Non-overlapping block pooling via einx
    (``"... (y py) (x px) -> ... y x"``), so ``(H, W)``, ``(C, H, W)`` and
    ``(T, C, H, W)`` inputs all work. This is the one einx preset that
    *changes* the geotransform rather than preserving or dropping it: a
    ``GeoArray`` input returns a ``GeoArray`` whose pixel size is
    scaled by the pool factors (same origin, coarser grid, fresh
    ``attrs``). Plain-array input returns a plain array.

    Nodata: invalid pixels — non-finite, or equal to the carrier's
    ``fill_value`` in any band (per frame for 4-D input; see
    `geoops._src.valid`) — are excluded with a NaN-aware reduction, so
    a block pools only its valid pixels. A block with no valid pixel is
    written as the output fill, which the output also declares: ``NaN``
    for float results of an integer input or of an input without a fill,
    otherwise the input's ``fill_value``. With
    ``fill_value=0`` on the input, 0 is nodata (georeader's
    convention); pass ``None`` or ``NaN`` on the carrier when 0 is real
    data.

    Output dtype: ``"max"`` / ``"min"`` keep an integer input's dtype;
    every other reduction returns floats (``float64`` for integer
    input, the input's float dtype otherwise).

    Args:
        reduce: einx reduction applied per block: ``"mean"`` (default),
            ``"sum"``, ``"prod"``, ``"max"``, ``"min"``, ``"std"``,
            ``"var"``.
        factor: Pool factor — one int for square blocks or a
            ``(row, col)`` pair (numpy integers accepted, ``bool``
            rejected). Spatial dims must divide evenly; otherwise a
            ``ValueError`` names the offending shape (crop or pad first,
            e.g. with ``geom.CropTo`` / ``geom.PadTo``).

    Raises:
        TypeError: ``factor`` is not an int or a pair of ints.
        ValueError: ``factor`` < 1 or not a pair, or unsupported ``reduce``.

    Examples:
        >>> import geoops as gz
        >>> coarse = gz.SpatialPool(reduce="mean", factor=4)(scene_gt)  # doctest: +SKIP
    """

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

    pattern = "... (y py) (x px) -> ... y x"

    def __init__(
        self,
        *,
        reduce: str = "mean",
        factor: int | tuple[int, int] | list[int] = 2,
    ) -> None:
        self.factor = _pool_factor(factor)
        self._fn = _resolve_reduction(reduce, name="SpatialPool")
        self.reduce = reduce

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        reject_geotensor(gt, type(self).__name__)
        arr = np.asarray(gt)
        if arr.ndim < 2:
            raise ValueError(
                f"SpatialPool: expected an (..., H, W) input; got shape {arr.shape}"
            )
        fy, fx = self.factor
        h, w = arr.shape[-2:]
        if h % fy or w % fx:
            raise ValueError(
                f"SpatialPool: spatial shape ({h}, {w}) is not divisible by "
                f"factor {self.factor}; crop or pad first"
            )
        valid = valid_pixels(gt, keep_time=True)
        data = _nan_float(gt, valid)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", RuntimeWarning)
            out = np.asarray(self._fn(self.pattern, data, py=fy, px=fx))
        block_valid = _einx.any(self.pattern, valid, py=fy, px=fx)

        if self.reduce in ("max", "min") and np.issubdtype(arr.dtype, np.integer):
            # Block extrema of integers are integers. Integer pixels are
            # only invalid when they equal the (integer) fill, so
            # all-invalid blocks hold that fill and the cast is exact.
            out_fill = carrier_fill_value(gt)
            out = restore_fill(out, block_valid, out_fill).astype(arr.dtype)
        else:
            # Float result: an integer input's fill would collide with
            # pooled values, so it becomes NaN (see ``carried_fill``).
            out_fill = carried_fill(gt, out.dtype)
            if out_fill is None:
                out_fill = np.nan
            out = restore_fill(out, block_valid, out_fill)

        if not isinstance(gt, GeoArray):
            return out
        pooled_transform = affine_of(gt) * Affine.scale(fx, fy)
        return wrap_like(gt, out, transform=pooled_transform, fill_value=out_fill)

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

Pattern analysis

These helpers are pure string processing over pattern text.

geoops.einx.spatial_survives(pattern, spatial_axes=('y', 'x'))

Return whether an einx pattern preserves the carrier's spatial grid.

True iff the output expression's trailing two top-level tokens are exactly the bare spatial_axes names in order, AND the carrier's input expression (the first comma-separated part of the input side) ends in those same bare names in the same order, AND neither spatial axis appears inside a composed / bracketed group anywhere in the pattern (composition splits or merges the axis, changing its size and invalidating the geotransform).

Parameters:

Name Type Description Default
pattern str

An einx pattern string.

required
spatial_axes tuple[str, str]

The (row, column) axis names, default ("y", "x").

('y', 'x')

Returns:

Type Description
bool

Whether a GeoArray carrier's transform / CRS remain valid

bool

for the output.

Examples:

>>> spatial_survives("c y x -> y x")
True
>>> spatial_survives("c y x -> x y")               # transposed
False
>>> spatial_survives("c x y -> c y x")             # input-side transpose
False
>>> spatial_survives("y x c -> c y x")             # channels-last input
False
>>> spatial_survives("c y x -> y x c")             # channels-last
False
>>> spatial_survives("c (y py) (x px) -> c y x")   # pooled: resized
False
>>> spatial_survives("band y x, sig band -> sig y x")
True
Source code in packages/geotoolz-ops/src/geoops/einx/_src/array.py
def spatial_survives(
    pattern: str,
    spatial_axes: tuple[str, str] = ("y", "x"),
) -> bool:
    """Return whether an einx pattern preserves the carrier's spatial grid.

    True iff the output expression's trailing two top-level tokens are
    exactly the bare ``spatial_axes`` names in order, AND the carrier's
    input expression (the first comma-separated part of the input side)
    ends in those same bare names in the same order, AND neither
    spatial axis appears inside a composed / bracketed group anywhere
    in the pattern (composition splits or merges the axis, changing its
    size and invalidating the geotransform).

    Args:
        pattern: An einx pattern string.
        spatial_axes: The (row, column) axis names, default ``("y", "x")``.

    Returns:
        Whether a ``GeoArray`` carrier's transform / CRS remain valid
        for the output.

    Examples:
        >>> spatial_survives("c y x -> y x")
        True
        >>> spatial_survives("c y x -> x y")               # transposed
        False
        >>> spatial_survives("c x y -> c y x")             # input-side transpose
        False
        >>> spatial_survives("y x c -> c y x")             # channels-last input
        False
        >>> spatial_survives("c y x -> y x c")             # channels-last
        False
        >>> spatial_survives("c (y py) (x px) -> c y x")   # pooled: resized
        False
        >>> spatial_survives("band y x, sig band -> sig y x")
        True
    """
    tokens = output_axes(pattern)
    if tokens is None or len(tokens) < 2:
        return False
    if tokens[-2] != spatial_axes[0] or tokens[-1] != spatial_axes[1]:
        return False
    # The carrier (first input) must also carry the grid in the trailing
    # two positions under the same names: otherwise the output's `y x`
    # is a transpose / rename of the input's grid and the carrier's
    # transform no longer describes it (undetectable by shape on square
    # tiles). Top-level commas separate inputs; brackets can't contain
    # a spatial axis here (rejected below), so the first split is safe.
    carrier_expr = pattern.split("->", 1)[0]
    carrier_tokens = _tokenize(carrier_expr.split(",", 1)[0], pattern=pattern)
    if carrier_tokens[-2:] != list(spatial_axes):
        return False
    # Reject patterns that compose/split a spatial axis anywhere: the
    # axis size changes, so the trailing dims can't keep their extent.
    sides = pattern.split("->")
    for side in sides:
        for token in _tokenize(side, pattern=pattern):
            if token[0] in _OPEN and any(
                re.search(rf"(?<![\w.]){re.escape(ax)}(?![\w.])", token)
                for ax in spatial_axes
            ):
                return False
    return True

geoops.einx.output_axes(pattern)

Return the top-level axis tokens of a pattern's output expression.

The output expression is everything after the last ->.

Parameters:

Name Type Description Default
pattern str

An einx pattern string, e.g. "c y x -> y x".

required

Returns:

Type Description
list[str] | None

The list of top-level output tokens, or None when the

list[str] | None

pattern has no explicit -> (einx's implicit-output forms

list[str] | None

cannot be analyzed statically here).

Raises:

Type Description
ValueError

On unbalanced brackets in the pattern.

Source code in packages/geotoolz-ops/src/geoops/einx/_src/array.py
def output_axes(pattern: str) -> list[str] | None:
    """Return the top-level axis tokens of a pattern's output expression.

    The output expression is everything after the *last* ``->``.

    Args:
        pattern: An einx pattern string, e.g. ``"c y x -> y x"``.

    Returns:
        The list of top-level output tokens, or ``None`` when the
        pattern has no explicit ``->`` (einx's implicit-output forms
        cannot be analyzed statically here).

    Raises:
        ValueError: On unbalanced brackets in the pattern.
    """
    if "->" not in pattern:
        return None
    return _tokenize(pattern.rsplit("->", 1)[1], pattern=pattern)