Skip to content

Compositing

Per-pixel composites over co-registered frame stacks and matched multi-source tuples.

  • Temporal composites: MedianComposite, MaxNDVIComposite (NDVI via geoops.indices.ndvi), CloudFreeComposite, MinCloudComposite, BAPComposite
  • Multi-source fusion: StackMatched, BlendMatched
  • Calling convention: every composite is an N-ary reducer — frames as positional arguments (MedianComposite()(f1, f2, f3), so op(Input("a"), Input("b")) works in a Graph) or one sequence; MedianComposite / MaxNDVIComposite also take one (T, C, H, W) stack, the cloud-aware composites take (frame, mask_or_metadata) pairs, StackMatched / BlendMatched also take one Mapping, and BlendMatched(method="ivw") takes (tensor, variance) pairs
  • Tier-A primitives (plain (T, ..., H, W) numpy stacks, NaN = missing): median_composite, mean_composite, take_by_spatial_index, mask_frames, blend_weighted, bap_scores and the per-criterion BAP scores doy_distance, doy_score, view_angle_score, cloud_distance_score, opacity_score
  • Nodata-aware reductions: reduce, argreduce (a GeoArray, GeoPoints or GeoSwath, any dim)

Reductions that leave nodata out

reduce(x, fn, dim) and argreduce(x, fn, dim) are pipekit-array's reduce / argreduce with the carrier's nodata read first, by the stack's rule (GeoArray.valid_mask): a value that is non-finite or equals the fill, every band of a pixel where any band is, and on GeoPoints a sample that is not valid, never count. They agree with MedianComposite on a (time, band, y, x) stack. A named reduction runs as its NaN-skipping form, a position with no valid entry is NaN, and the result's fill is NaN. pipekit_array.reduce reduces the raw values, so on a scene with fill 0 a time mean averages the zeros in. geoarray does not re-export either (GA-B6). They run on NumPy and under jax.jit.

import numpy as np
import pipekit_array as pa
from geoarray import GeoArray

from geoops.compositing import argreduce, reduce

stack: GeoArray = GeoArray(
    np.array([[[1.0]], [[0.0]], [[3.0]]]),             # (T, H, W) float64, 0 = nodata
    (20.0, 0.0, 600000.0, 0.0, -20.0, 3550000.0),
    "EPSG:32613",
    fill_value=0.0,
    dims=("time", "y", "x"),
)
mean: GeoArray = reduce(stack, "mean", "time")         # (H, W) float64: 2.0
raw: GeoArray = pa.reduce(stack, "mean", "time")       # (H, W) float64: 1.33, fill counted
best = argreduce(stack, "argmax", "time")              # (H, W) int: 2, never the fill
picked = pa.take_along(stack, best, "time")            # (H, W) float64: 3.0

geoops.compositing

Compositing operators for co-registered GeoArray stacks, and the nodata-aware reductions they are built from (reduce, argreduce).

BAPComposite

Bases: Operator

Best Available Pixel compositing from quality-score metadata.

Each frame-pixel gets a weighted sum of per-criterion scores in [0, 1] and the highest-scoring valid frame wins (Griffiths et al., 2013; White et al., 2014):

S = w_view · S_view + w_recency · S_doy
    + w_cloud · S_cloud + w_opacity · S_opacity

Metadata may give precomputed view_angle_score, recency_score, cloud_distance_score and opacity_score values, or the raw values the scores are built from:

  • doy / day_of_year → Gaussian of the circular DOY distance (Griffiths et al.), so late December is close to early January::

    Δ = |doy − target_doy| mod 365, d = min(Δ, 365 − Δ) S_doy = exp(−½ · (d / σ_doy)²)

  • view_angle (view zenith angle, degrees; sign ignored)::

    S_view = exp(−½ · (θ / σ_θ)²)

  • cloud_distance (distance to the nearest cloud / shadow, in the unit of cloud_distance_req, e.g. pixels) → Griffiths et al. eq. 2 sigmoid::

    S_cloud = 1 / (1 + exp(−k · (min(D, D_req) − (D_req − D_min) / 2)))

  • opacity (unitless atmospheric opacity τ, e.g. LEDAPS atmos_opacity) → White et al. (2014) ramp::

    S_opacity = clip((τ_high − τ) / (τ_high − τ_low), 0, 1)

Missing raw values default to the best case (doy = target_doy, view_angle = 0, opacity = 0), except cloud_distance, which defaults to 0 (next to a cloud). Every score lies in [0, 1], so raw and precomputed values may be mixed across frames. Each value may be a scalar or a per-pixel array. Frames may be GeoArrays or plain np.ndarray maps (the scores live in the metadata dicts, not in geo-metadata). A nodata frame-pixel (non-finite or the frame's fill) or a NaN score is never selected; pixels with no valid frame hold the output fill value (also in the score output). Griffiths et al. also score acquisition year and sensor; those have no raw input here.

Parameters:

Name Type Description Default
target_doy int

Day of year (1-366) the DOY score is centred on.

required
w_view_angle float

Weight of the view-angle score.

0.3
w_recency float

Weight of the DOY score.

0.4
w_cloud_distance float

Weight of the cloud-distance score.

0.2
w_opacity float

Weight of the opacity score.

0.1
doy_sigma float

σ_doy, width of the DOY Gaussian in days. Default 30 (a scene 30 days off target scores e^(−½) ≈ 0.61).

30.0
view_angle_sigma float

σ_θ, width of the view-angle Gaussian in degrees. Default 15 (7.5°, the Landsat swath edge, scores ≈ 0.88).

15.0
cloud_distance_req float

D_req, distance at which the cloud score saturates. Default 50 (pixels; 1.5 km at 30 m).

50.0
cloud_distance_min float

D_min of the sigmoid. Default 0.

0.0
cloud_distance_slope float

Sigmoid slope k per distance unit. Default 0.2.

0.2
opacity_low float

τ_low, opacity at or below which the score is 1. Default 0.2.

0.2
opacity_high float

τ_high, opacity at or above which the score is 0. Default 0.3.

0.3
return_score bool

When true, also return a carrier holding the winning per-pixel score (float32). The output is then a tuple, so the operator is terminal (last step only) in a Sequential.

False

Raises:

Type Description
ValueError

If doy_sigma, view_angle_sigma or cloud_distance_slope is not positive, or cloud_distance_req ≤ cloud_distance_min or opacity_high ≤ opacity_low.

References

Griffiths, P., van der Linden, S., Kuemmerle, T. & Hostert, P. (2013). A pixel-based Landsat compositing algorithm for large area land cover mapping. IEEE JSTARS 6(5), 2088-2101.

White, J. C., Wulder, M. A., Hobart, G. W., et al. (2014). Pixel-based image compositing for large-area dense time series applications and science. Canadian Journal of Remote Sensing 40(3), 192-212.

Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class BAPComposite(Operator):
    """Best Available Pixel compositing from quality-score metadata.

    Each frame-pixel gets a weighted sum of per-criterion scores in
    ``[0, 1]`` and the highest-scoring valid frame wins (Griffiths et al.,
    2013; White et al., 2014):

        S = w_view · S_view + w_recency · S_doy
            + w_cloud · S_cloud + w_opacity · S_opacity

    Metadata may give precomputed ``view_angle_score``, ``recency_score``,
    ``cloud_distance_score`` and ``opacity_score`` values, or the raw
    values the scores are built from:

    * ``doy`` / ``day_of_year`` → Gaussian of the *circular* DOY distance
      (Griffiths et al.), so late December is close to early January::

          Δ = |doy − target_doy| mod 365,   d = min(Δ, 365 − Δ)
          S_doy = exp(−½ · (d / σ_doy)²)

    * ``view_angle`` (view zenith angle, degrees; sign ignored)::

          S_view = exp(−½ · (θ / σ_θ)²)

    * ``cloud_distance`` (distance to the nearest cloud / shadow, in the
      unit of ``cloud_distance_req``, e.g. pixels) → Griffiths et al.
      eq. 2 sigmoid::

          S_cloud = 1 / (1 + exp(−k · (min(D, D_req) − (D_req − D_min) / 2)))

    * ``opacity`` (unitless atmospheric opacity τ, e.g. LEDAPS
      ``atmos_opacity``) → White et al. (2014) ramp::

          S_opacity = clip((τ_high − τ) / (τ_high − τ_low), 0, 1)

    Missing raw values default to the best case (``doy = target_doy``,
    ``view_angle = 0``, ``opacity = 0``), except ``cloud_distance``, which
    defaults to ``0`` (next to a cloud). Every score lies in ``[0, 1]``, so
    raw and precomputed values may be mixed across frames. Each value may
    be a scalar or a per-pixel array. Frames may be GeoArrays or plain
    ``np.ndarray`` maps (the scores live in the metadata dicts, not in
    geo-metadata). A nodata frame-pixel (non-finite or the frame's fill)
    or a NaN score is never selected; pixels with no valid frame hold the
    output fill value (also in the score output). Griffiths et al. also
    score acquisition year and sensor; those have no raw input here.

    Args:
        target_doy: Day of year (1-366) the DOY score is centred on.
        w_view_angle: Weight of the view-angle score.
        w_recency: Weight of the DOY score.
        w_cloud_distance: Weight of the cloud-distance score.
        w_opacity: Weight of the opacity score.
        doy_sigma: ``σ_doy``, width of the DOY Gaussian in days. Default
            ``30`` (a scene 30 days off target scores e^(−½) ≈ 0.61).
        view_angle_sigma: ``σ_θ``, width of the view-angle Gaussian in
            degrees. Default ``15`` (7.5°, the Landsat swath edge, scores
            ≈ 0.88).
        cloud_distance_req: ``D_req``, distance at which the cloud
            score saturates. Default ``50`` (pixels; 1.5 km at 30 m).
        cloud_distance_min: ``D_min`` of the sigmoid. Default ``0``.
        cloud_distance_slope: Sigmoid slope ``k`` per distance unit.
            Default ``0.2``.
        opacity_low: ``τ_low``, opacity at or below which the score is 1.
            Default ``0.2``.
        opacity_high: ``τ_high``, opacity at or above which the score is
            0. Default ``0.3``.
        return_score: When true, also return a carrier holding the
            winning per-pixel score (``float32``).
            The output is then a tuple, so the operator is terminal
            (last step only) in a ``Sequential``.

    Raises:
        ValueError: If ``doy_sigma``, ``view_angle_sigma`` or
            ``cloud_distance_slope`` is not positive, or
            ``cloud_distance_req ≤ cloud_distance_min`` or
            ``opacity_high ≤ opacity_low``.

    References:
        Griffiths, P., van der Linden, S., Kuemmerle, T. & Hostert, P.
        (2013). A pixel-based Landsat compositing algorithm for large area
        land cover mapping. IEEE JSTARS 6(5), 2088-2101.

        White, J. C., Wulder, M. A., Hobart, G. W., et al. (2014).
        Pixel-based image compositing for large-area dense time series
        applications and science. Canadian Journal of Remote Sensing
        40(3), 192-212.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # per-pixel scores from metadata and the distance to clouds pick a frame
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space", "time"}, effects={"time": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        target_doy: int,
        w_view_angle: float = 0.3,
        w_recency: float = 0.4,
        w_cloud_distance: float = 0.2,
        w_opacity: float = 0.1,
        doy_sigma: float = 30.0,
        view_angle_sigma: float = 15.0,
        cloud_distance_req: float = 50.0,
        cloud_distance_min: float = 0.0,
        cloud_distance_slope: float = 0.2,
        opacity_low: float = 0.2,
        opacity_high: float = 0.3,
        return_score: bool = False,
    ) -> None:
        if min(doy_sigma, view_angle_sigma, cloud_distance_slope) <= 0:
            raise ValueError(
                "doy_sigma, view_angle_sigma and cloud_distance_slope must be positive."
            )
        if cloud_distance_req <= cloud_distance_min:
            raise ValueError("cloud_distance_req must exceed cloud_distance_min.")
        if opacity_high <= opacity_low:
            raise ValueError("opacity_high must exceed opacity_low.")
        self.target_doy = target_doy
        self.w_view_angle = w_view_angle
        self.w_recency = w_recency
        self.w_cloud_distance = w_cloud_distance
        self.w_opacity = w_opacity
        self.doy_sigma = doy_sigma
        self.view_angle_sigma = view_angle_sigma
        self.cloud_distance_req = cloud_distance_req
        self.cloud_distance_min = cloud_distance_min
        self.cloud_distance_slope = cloud_distance_slope
        self.opacity_low = opacity_low
        self.opacity_high = opacity_high
        self.return_score = return_score

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """A tuple output breaks carrier-in / carrier-out (last step only)."""
        return self.return_score

    def _frame_scores(
        self, metadata: Mapping[str, Any], spatial_shape: tuple[int, int]
    ) -> Float[np.ndarray, "4 h w"]:
        """Stack one frame's (view, DOY, cloud-distance, opacity) scores."""

        def raw(*names: str, default: float) -> Float[np.ndarray, "h w"]:
            value = _metadata_value(metadata, *names, default=default)
            return _score_array(value, spatial_shape)

        view = _metadata_value(metadata, "view_angle_score")
        if view is None:
            view = view_angle_score(
                raw("view_angle", default=0.0), self.view_angle_sigma
            )
        recency = _metadata_value(metadata, "recency_score")
        if recency is None:
            recency = doy_score(
                raw("doy", "day_of_year", default=float(self.target_doy)),
                self.target_doy,
                self.doy_sigma,
            )
        cloud = _metadata_value(metadata, "cloud_distance_score")
        if cloud is None:
            cloud = cloud_distance_score(
                raw("cloud_distance", default=0.0),
                d_req=self.cloud_distance_req,
                d_min=self.cloud_distance_min,
                slope=self.cloud_distance_slope,
            )
        opacity = _metadata_value(metadata, "opacity_score")
        if opacity is None:
            opacity = opacity_score(
                raw("opacity", default=0.0),
                low=self.opacity_low,
                high=self.opacity_high,
            )
        return np.stack(
            [_score_array(s, spatial_shape) for s in (view, recency, cloud, opacity)]
        )

    def _apply(
        self, *pairs: tuple[GeoArray | np.ndarray, Mapping[str, Any]]
    ) -> GeoArray | np.ndarray | tuple[GeoArray | np.ndarray, GeoArray | np.ndarray]:
        name = type(self).__name__
        pairs = gather_inputs(pairs, name, pairs=True)
        frames = [scene for scene, _ in pairs]
        base, stack = _stack_frames(frames, name)
        spatial_shape = base.shape[-2:]
        # (T, 4, H, W): view, DOY, cloud-distance, opacity score per frame.
        scores = np.stack(
            [self._frame_scores(metadata, spatial_shape) for _, metadata in pairs]
        )
        weights = np.array(
            [self.w_view_angle, self.w_recency, self.w_cloud_distance, self.w_opacity],
            dtype=np.float32,
        )
        score_stack = bap_scores(scores, weights)
        # A nodata frame-pixel (or a NaN score) must never win the argmax.
        frame_valid = _frame_validity(frames)
        score_stack = np.where(
            frame_valid & ~np.isnan(score_stack), score_stack, -np.inf
        ).astype(np.float32, copy=False)
        index = np.argmax(score_stack, axis=0)
        any_valid = np.isfinite(score_stack).any(axis=0)
        values = take_by_spatial_index(stack, index)
        fill = carried_fill(base, values.dtype)
        values = restore_fill(values, any_valid, fill)
        out = wrap_like(base, values, fill_value=fill)
        if not self.return_score:
            return out
        best_score = np.take_along_axis(score_stack, index[None, ...], axis=0)[0]
        best_score = restore_fill(best_score, any_valid, np.nan)
        return out, wrap_like(base, best_score, fill_value=np.nan)

BlendMatched

Bases: Operator

Weighted mean across N aligned tensors.

Three blending modes:

  • "mean" — equal-weight average across all inputs. Best for ensemble-style fusion where every source is equally trustworthy.
  • "weighted_mean" — per-source scalar weights from self.weights. Useful when one source is known to be higher-quality (e.g. ground-truth vs satellite).
  • "ivw" — inverse-variance weighting. Each input is weighted by 1 / variance, so noisier sources contribute less. Each input is then a (tensor, variance) pair, the variance an array of the tensor's full or spatial shape: BlendMatched(method="ivw")((a, var_a), (b, var_b)).

Inputs are positional, op(a, b, ...) -- so the operator wires into a pipekit_ops.Graph as BlendMatched()(Input("a"), Input("b")) -- or one sequence or mapping of them, or one (T, C, H, W) stack whose frames are the inputs.

nan_policy controls per-pixel NaN handling:

  • "ignore" — exclude NaN samples from the blend; the surviving weights renormalise. If every input is NaN at a pixel, the output is NaN.
  • "propagate" — any NaN at a pixel poisons the output pixel.

Nodata pixels of each input (non-finite, or that input's fill_value, in any band) are treated as NaN; pixels that are nodata in every input hold the output fill: the first input's fill_value, or NaN when it has none or is an integer input blended into float (see :func:geoops._src.valid.carried_fill).

All inputs must share spatial shape, transform, and CRS. The band axis must also be uniform (use StackMatched if you want cross-source band concatenation; BlendMatched is the per-pixel averaging counterpart). Plain np.ndarray inputs are also accepted (the blend is metadata-free per-pixel math); grid verification then degrades to shape equality and the output carrier follows the first input.

When the input is a Mapping, the per-source order used by weighted_mean follows the mapping's iteration order (insertion order on dicts), and weights are zipped positionally against it — pass an OrderedDict or positional inputs if you need a stable, explicit pairing.

Parameters:

Name Type Description Default
method BlendMethod

One of "mean" / "weighted_mean" / "ivw".

'mean'
weights list[float] | None

Per-source scalar weights. Required when method="weighted_mean"; must be None for the other methods (passing weights with another method raises). Length must equal the number of input tensors at call time.

None
nan_policy NanPolicy

"ignore" (default) or "propagate".

'ignore'
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class BlendMatched(Operator):
    """Weighted mean across N aligned tensors.

    Three blending modes:

    * ``"mean"`` — equal-weight average across all inputs. Best for
      ensemble-style fusion where every source is equally trustworthy.
    * ``"weighted_mean"`` — per-source scalar weights from
      ``self.weights``. Useful when one source is known to be
      higher-quality (e.g. ground-truth vs satellite).
    * ``"ivw"`` — inverse-variance weighting. Each input is weighted by
      ``1 / variance``, so noisier sources contribute less. Each input is
      then a ``(tensor, variance)`` pair, the variance an array of the
      tensor's full or spatial shape:
      ``BlendMatched(method="ivw")((a, var_a), (b, var_b))``.

    Inputs are positional, ``op(a, b, ...)`` -- so the operator wires into
    a ``pipekit_ops.Graph`` as ``BlendMatched()(Input("a"), Input("b"))`` --
    or one sequence or mapping of them, or one ``(T, C, H, W)`` stack whose
    frames are the inputs.

    `nan_policy` controls per-pixel NaN handling:

    * ``"ignore"`` — exclude NaN samples from the blend; the
      surviving weights renormalise. If every input is NaN at a pixel,
      the output is NaN.
    * ``"propagate"`` — any NaN at a pixel poisons the output pixel.

    Nodata pixels of each input (non-finite, or that input's
    ``fill_value``, in any band) are treated as NaN; pixels that
    are nodata in every input hold the output fill: the first input's
    ``fill_value``, or ``NaN`` when it has none or is an integer
    input blended into float (see :func:`geoops._src.valid.carried_fill`).

    All inputs must share spatial shape, transform, and CRS. The
    band axis must also be uniform (use `StackMatched` if you want
    cross-source band concatenation; `BlendMatched` is the per-pixel
    averaging counterpart). Plain ``np.ndarray`` inputs are also
    accepted (the blend is metadata-free per-pixel math); grid
    verification then degrades to shape equality and the output
    carrier follows the first input.

    When the input is a ``Mapping``, the per-source order used by
    ``weighted_mean`` follows the mapping's iteration order (insertion
    order on dicts), and ``weights`` are zipped positionally against it
    — pass an ``OrderedDict`` or positional inputs if you need a stable,
    explicit pairing.

    Args:
        method: One of ``"mean"`` / ``"weighted_mean"`` / ``"ivw"``.
        weights: Per-source scalar weights. Required when
            ``method="weighted_mean"``; must be ``None`` for the other
            methods (passing weights with another method raises).
            Length must equal the number of input tensors at call time.
        nan_policy: ``"ignore"`` (default) or ``"propagate"``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # weighted mean over the N inputs (time is the N-ary axis, OC-Q5)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"time"}, effects={"time": "reduce"}
    )

    def __init__(
        self,
        *,
        method: BlendMethod = "mean",
        weights: list[float] | None = None,
        nan_policy: NanPolicy = "ignore",
    ) -> None:
        if method not in {"mean", "weighted_mean", "ivw"}:
            raise ValueError(
                f"BlendMatched.method must be 'mean', 'weighted_mean', or "
                f"'ivw'; got {method!r}"
            )
        if nan_policy not in {"ignore", "propagate"}:
            raise ValueError(
                f"BlendMatched.nan_policy must be 'ignore' or 'propagate'; "
                f"got {nan_policy!r}"
            )
        if method == "weighted_mean" and weights is None:
            raise ValueError("BlendMatched(method='weighted_mean') requires `weights`.")
        if method != "weighted_mean" and weights is not None:
            raise ValueError(
                "BlendMatched `weights` only applies to "
                "method='weighted_mean'. For per-pixel variance "
                "weighting use method='ivw' with (tensor, variance) inputs."
            )
        self.method = method
        self.weights = list(weights) if weights is not None else None
        self.nan_policy = nan_policy

    def _apply(
        self,
        *tensors: Any,
    ) -> GeoArray | np.ndarray:
        seq, _names = _normalize_to_sequence(
            tensors, None, "BlendMatched", pairs=self.method == "ivw"
        )
        if not seq:
            raise ValueError("BlendMatched requires at least one input tensor.")
        is_pair = [isinstance(t, tuple) and len(t) == 2 for t in seq]
        variances: list[Any] | None = None
        if self.method == "ivw":
            if not all(is_pair):
                raise ValueError(
                    "BlendMatched(method='ivw') takes (tensor, variance) pairs "
                    "(one variance array per source, same spatial shape as "
                    "the data)."
                )
            variances = [var for _, var in seq]
            seq = [tensor for tensor, _ in seq]
        elif any(is_pair):
            raise ValueError(
                "BlendMatched: (tensor, variance) pairs are only accepted when "
                f"method='ivw'; got method={self.method!r}."
            )

        # Strict grid + band-shape validation. BlendMatched is a
        # per-pixel reduction across inputs, so any shape difference
        # would mean we're averaging different physical quantities.
        base = seq[0]
        for idx, frame in enumerate(seq[1:], start=1):
            require_grid_match(
                base, frame, "BlendMatched", names=("input 0", f"input {idx}")
            )
            if frame.shape != base.shape:
                raise ValueError(
                    "BlendMatched inputs must share full shape (including "
                    f"band axis); input 0 has shape {base.shape}, "
                    f"input {idx} has shape {frame.shape}."
                )

        # Stack along a new "source" axis at position 0. Shape is now
        # (N, ...spatial...) for 2-D or (N, C, H, W) for 3-D. Each input's
        # nodata pixels (non-finite or its own fill) become NaN in every
        # band, so the NaN policy below excludes / propagates them.
        stack = np.stack([np.asarray(t).astype(np.float64) for t in seq], axis=0)
        source_valid = np.stack([valid_pixels(t) for t in seq], axis=0)
        if not source_valid.all():
            per_source = source_valid[:, None] if stack.ndim == 4 else source_valid
            stack[~np.broadcast_to(per_source, stack.shape)] = np.nan

        # Build the per-source weight broadcastable to `stack`.
        if variances is not None:
            var_list = variances
            # Each variance must be either a full-shape array matching
            # the data or a spatial-only (H, W) array that broadcasts
            # against the band axis. Validate shape explicitly so a
            # silent broadcast can't hide a mis-shaped variance.
            var_arrays: list[np.ndarray] = []
            spatial_shape = base.shape[-2:]
            for i, v in enumerate(var_list):
                arr = np.asarray(v, dtype=np.float64)
                if arr.shape != base.shape and arr.shape != spatial_shape:
                    raise ValueError(
                        f"BlendMatched(method='ivw'): variance {i} has "
                        f"shape {arr.shape}; expected {base.shape} "
                        f"(full) or {spatial_shape} (spatial-only)."
                    )
                if not np.all(np.isfinite(arr)):
                    raise ValueError(
                        f"BlendMatched(method='ivw'): variance {i} "
                        "contains non-finite values (NaN/Inf); "
                        "IVW weights are undefined."
                    )
                if np.any(arr <= 0):
                    raise ValueError(
                        f"BlendMatched(method='ivw'): variance {i} "
                        "contains non-positive values; variances must "
                        "be strictly positive."
                    )
                var_arrays.append(np.broadcast_to(arr, base.shape))
            var_stack = np.stack(var_arrays, axis=0)
            w = 1.0 / var_stack
        elif self.method == "weighted_mean":
            assert self.weights is not None  # guarded in __init__
            if len(self.weights) != len(seq):
                raise ValueError(
                    f"BlendMatched(weights=...): got {len(self.weights)} "
                    f"weights for {len(seq)} input tensors."
                )
            w_arr = np.asarray(self.weights, dtype=np.float64)
            # Keep weights as (N, 1, ..., 1) so they broadcast against
            # `stack` without materialising a full (N, *spatial) array.
            w_shape = (len(seq),) + (1,) * (stack.ndim - 1)
            w = w_arr.reshape(w_shape)
        else:  # "mean"
            w = np.ones((len(seq),) + (1,) * (stack.ndim - 1), dtype=np.float64)

        result = blend_weighted(stack, w, nan_policy=self.nan_policy)

        fill = carried_fill(base, result.dtype)
        result = restore_fill(result, source_valid.any(axis=0), fill)
        return wrap_like(base, result, fill_value=fill)

CloudFreeComposite

Bases: Operator

Per-pixel mean over frames where the cloud mask is false.

Consumes (frame, cloud_mask) pairs as positional arguments, op((f1, m1), (f2, m2)), or one sequence of them; masks may have spatial shape (H, W), (1, H, W), or match the frame shape exactly, and a georeferenced mask must share the frames' grid. Pixels with fewer than min_valid clear contributors come out as NaN. Nodata frame-pixels (non-finite or the frame's fill) never contribute; pixels invalid in every frame hold the output fill value. Metadata-independent: plain np.ndarray frames are accepted and yield plain-array outputs.

Parameters:

Name Type Description Default
nan_policy NanPolicy

"ignore" (default) also drops NaN samples from clear pixels; "propagate" lets NaNs poison the mean.

'ignore'
min_valid int

Minimum number of clear contributors per pixel; pixels below the threshold are NaN. Must be at least 1.

1
return_count bool

When true, also return a carrier with the number of clear contributors per pixel (int64). The output is then a tuple, so the operator is terminal (last step only) in a Sequential.

False

Raises:

Type Description
ValueError

If min_valid is below 1.

Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class CloudFreeComposite(Operator):
    """Per-pixel mean over frames where the cloud mask is false.

    Consumes ``(frame, cloud_mask)`` pairs as positional arguments,
    ``op((f1, m1), (f2, m2))``, or one sequence of them; masks may have
    spatial shape ``(H, W)``, ``(1, H, W)``, or match the frame shape
    exactly, and a georeferenced mask must share the frames' grid. Pixels
    with fewer than ``min_valid`` clear contributors come out as NaN.
    Nodata frame-pixels (non-finite or the frame's fill) never contribute;
    pixels invalid in every frame hold the output fill value.
    Metadata-independent: plain ``np.ndarray`` frames are accepted and
    yield plain-array outputs.

    Args:
        nan_policy: ``"ignore"`` (default) also drops NaN samples from
            clear pixels; ``"propagate"`` lets NaNs poison the mean.
        min_valid: Minimum number of clear contributors per pixel;
            pixels below the threshold are NaN. Must be at least 1.
        return_count: When true, also return a carrier with the number
            of clear contributors per pixel (``int64``).
            The output is then a tuple, so the operator is terminal
            (last step only) in a ``Sequential``.

    Raises:
        ValueError: If ``min_valid`` is below 1.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # mean over the clear frames
    coupling: ClassVar[Coupling] = Coupling(
        couples={"time"}, effects={"time": "reduce"}
    )

    def __init__(
        self,
        *,
        nan_policy: NanPolicy = "ignore",
        min_valid: int = 1,
        return_count: bool = False,
    ) -> None:
        if min_valid < 1:
            raise ValueError("min_valid must be at least 1.")
        self.nan_policy = _validate_nan_policy(nan_policy)
        self.min_valid = min_valid
        self.return_count = return_count

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """A tuple output breaks carrier-in / carrier-out (last step only)."""
        return self.return_count

    def _apply(
        self, *pairs: tuple[GeoArray | np.ndarray, Any]
    ) -> GeoArray | np.ndarray | tuple[GeoArray | np.ndarray, GeoArray | np.ndarray]:
        name = type(self).__name__
        pairs = gather_inputs(pairs, name, pairs=True)
        base, stack, cloudy = _require_pairs(pairs, name)
        frame_valid = _frame_validity([scene for scene, _ in pairs])
        values, count = mean_composite(
            mask_frames(stack, frame_valid),
            ~cloudy,
            min_valid=self.min_valid,
            nan_policy=self.nan_policy,
        )
        fill = carried_fill(base, values.dtype)
        values = restore_fill(values, frame_valid.any(axis=0), fill)
        out = wrap_like(base, values, fill_value=fill)
        if not self.return_count:
            return out
        return out, wrap_like(base, count.astype(np.int64), fill_value=0)

MaxNDVIComposite

Bases: Operator

Pick the frame with maximum NDVI per pixel and return its band values.

Called like :class:MedianComposite (frames as arguments, one sequence, or a (T, C, H, W) stack). Inputs must be multi-band ((C, H, W)); 2-D GeoArrays raise because NDVI needs distinct red and NIR bands. Nodata frame-pixels (non-finite or the frame's fill in any band) never win the selection. Pixels with no valid NDVI in any frame hold the first frame's fill_value (NaN for float inputs without one), so the output dtype is the input dtype.

The per-pixel math is metadata-independent, so plain np.ndarray frames are accepted when red / nir are integer indices; named band references need GeoArray attrs and raise TypeError for plain arrays.

Parameters:

Name Type Description Default
red BandRef

Red band reference — integer band index or a band name resolved against the first frame's attrs.

required
nir BandRef

NIR band reference, same conventions as red.

required
return_index bool

When true, also return a carrier holding the selected frame index per pixel (int64; -1, the declared fill_value, where no frame is valid). The output is then a tuple, so the operator is terminal (last step only) in a Sequential.

False
eps float

Stabiliser added to the NDVI denominator.

1e-10
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class MaxNDVIComposite(Operator):
    """Pick the frame with maximum NDVI per pixel and return its band values.

    Called like :class:`MedianComposite` (frames as arguments, one
    sequence, or a ``(T, C, H, W)`` stack). Inputs must be multi-band
    (``(C, H, W)``); 2-D GeoArrays raise because NDVI needs distinct red
    and NIR bands. Nodata frame-pixels (non-finite or the frame's fill in
    any band) never win the selection. Pixels with
    no valid NDVI in any frame hold the first frame's
    ``fill_value`` (``NaN`` for float inputs without one), so the
    output dtype is the input dtype.

    The per-pixel math is metadata-independent, so plain ``np.ndarray``
    frames are accepted when ``red`` / ``nir`` are integer indices; named
    band references need GeoArray ``attrs`` and raise ``TypeError`` for
    plain arrays.

    Args:
        red: Red band reference — integer band index or a band name
            resolved against the first frame's attrs.
        nir: NIR band reference, same conventions as ``red``.
        return_index: When true, also return a carrier holding the
            selected frame index per pixel (``int64``; ``-1``, the
            declared ``fill_value``, where no frame is valid).
            The output is then a tuple, so the operator is terminal
            (last step only) in a ``Sequential``.
        eps: Stabiliser added to the NDVI denominator.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # NDVI across bands, then the best frame per pixel
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "time"}, effects={"time": "reduce"}
    )

    def __init__(
        self,
        *,
        red: BandRef,
        nir: BandRef,
        return_index: bool = False,
        eps: float = 1e-10,
    ) -> None:
        self.red = red
        self.nir = nir
        self.return_index = return_index
        self.eps = eps

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """A tuple output breaks carrier-in / carrier-out (last step only)."""
        return self.return_index

    def _apply(
        self, *frames: GeoArray | np.ndarray | Sequence[GeoArray | np.ndarray]
    ) -> GeoArray | np.ndarray | tuple[GeoArray | np.ndarray, GeoArray | np.ndarray]:
        name = type(self).__name__
        frames = _as_frames(frames, name)
        base, stack = _stack_frames(frames, name)
        # NDVI needs distinct red/nir bands; 2-D GeoArrays don't have a
        # band axis and would silently broadcast `:, red_idx, ...` into
        # nonsense. Fail loudly.
        if base.ndim < 3:
            raise ValueError(
                "MaxNDVIComposite requires multi-band GeoArrays (C, H, W); "
                f"got shape {base.shape}."
            )
        if (isinstance(self.red, str) or isinstance(self.nir, str)) and not isinstance(
            base, GeoArray
        ):
            raise TypeError(
                "MaxNDVIComposite with named band references requires "
                "GeoArray inputs carrying band-name attrs; got a plain "
                "array. Pass integer band indices instead."
            )
        red_idx = resolve_band(base, self.red)
        nir_idx = resolve_band(base, self.nir)
        if red_idx == nir_idx:
            raise ValueError(
                "MaxNDVIComposite requires distinct red and NIR bands; both "
                f"resolved to band index {red_idx} (red={self.red!r}, "
                f"nir={self.nir!r})."
            )
        with np.errstate(invalid="ignore", divide="ignore"):
            ndvi_map = ndvi(
                np.take(stack, nir_idx, axis=1),
                np.take(stack, red_idx, axis=1),
                eps=self.eps,
            )
        # A nodata frame (e.g. -9999 in both bands -> NDVI 0) must never win.
        frame_valid = _frame_validity(frames)
        scores = np.where(np.isnan(ndvi_map) | ~frame_valid, -np.inf, ndvi_map)
        index = np.argmax(scores, axis=0)
        values = take_by_spatial_index(stack, index)
        all_invalid = np.all(~np.isfinite(scores), axis=0)
        fill = carried_fill(base, values.dtype)
        if np.any(all_invalid):
            if np.issubdtype(values.dtype, np.floating):
                values = restore_fill(values, ~all_invalid, fill)
            else:
                # Integer / unsigned inputs can't carry NaN. Fall back to the
                # input's fill_value so the dtype is preserved.
                if fill is None:
                    raise ValueError(
                        "MaxNDVIComposite: all NDVI scores are invalid for "
                        "some pixels and the integer-dtype input carries no "
                        "fill_value to mark them; use a GeoArray "
                        "with fill_value or float frames."
                    )
                values[..., all_invalid] = fill
        out = wrap_like(base, values, fill_value=fill)
        if not self.return_index:
            return out
        # Frame 0 is a real index, so pixels no frame covers are -1.
        index = np.where(all_invalid, -1, index).astype(np.int64)
        return out, wrap_like(base, index, fill_value=-1)

MedianComposite

Bases: Operator

Per-pixel median across a stack of co-registered GeoArrays.

Called as op(f1, f2, ...), op([f1, f2, ...]) or op(stack) with a (T, C, H, W) time stack; every frame must share the first frame's grid and full shape (ValueError otherwise).

Metadata-independent: frames may also be plain np.ndarray maps, in which case the outputs are plain arrays and the grid check reduces to shape equality. Nodata frame-pixels (non-finite or the frame's fill) are treated like NaN; pixels invalid in every frame hold the output fill.

Parameters:

Name Type Description Default
nan_policy NanPolicy

"ignore" skips NaN / nodata samples with np.nanmedian; "propagate" uses np.median so any nodata sample makes the pixel NaN.

'ignore'
return_count bool

When true, also return a carrier with the number of valid contributors per output pixel. The output is then a tuple, so the operator is terminal (last step only) in a Sequential.

False
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class MedianComposite(Operator):
    """Per-pixel median across a stack of co-registered GeoArrays.

    Called as ``op(f1, f2, ...)``, ``op([f1, f2, ...])`` or ``op(stack)``
    with a ``(T, C, H, W)`` time stack; every frame must share the first
    frame's grid and full shape (``ValueError`` otherwise).

    Metadata-independent: frames may also be plain ``np.ndarray`` maps, in
    which case the outputs are plain arrays and the grid check reduces to
    shape equality. Nodata frame-pixels (non-finite or the frame's fill)
    are treated like NaN; pixels invalid in every frame hold the output fill.

    Args:
        nan_policy: ``"ignore"`` skips NaN / nodata samples with
            ``np.nanmedian``; ``"propagate"`` uses ``np.median`` so any
            nodata sample makes the pixel NaN.
        return_count: When true, also return a carrier with the number
            of valid contributors per output pixel.
            The output is then a tuple, so the operator is terminal
            (last step only) in a ``Sequential``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(
        couples={"time"}, effects={"time": "reduce"}
    )

    def __init__(
        self, *, nan_policy: NanPolicy = "ignore", return_count: bool = False
    ) -> None:
        self.nan_policy = _validate_nan_policy(nan_policy)
        self.return_count = return_count

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """A tuple output breaks carrier-in / carrier-out (last step only)."""
        return self.return_count

    def _apply(
        self, *frames: GeoArray | np.ndarray | Sequence[GeoArray | np.ndarray]
    ) -> GeoArray | np.ndarray | tuple[GeoArray | np.ndarray, GeoArray | np.ndarray]:
        name = type(self).__name__
        frames = _as_frames(frames, name)
        base, stack = _stack_frames(frames, name)
        valid = _frame_validity(frames)
        masked = mask_frames(stack, valid)
        # All-nodata pixels come out NaN; they get the output fill below.
        values = median_composite(masked, nan_policy=self.nan_policy)
        fill = carried_fill(base, values.dtype)
        values = restore_fill(values, valid.any(axis=0), fill)
        out = wrap_like(base, values, fill_value=fill)
        if not self.return_count:
            return out
        count = np.sum(~np.isnan(masked), axis=0).astype(np.int64)
        return out, wrap_like(base, count, fill_value=0)

MinCloudComposite

Bases: Operator

Pick each pixel from the scene with the lowest global cloud coverage.

For every pixel, the selected frame is the one with the smallest scene-wide cloud fraction among those where the pixel is clear. Pixels cloudy in every frame fall back to the globally least-cloudy frame so the output is a complete composite. Nodata frame-pixels (non-finite or the frame's fill) are never picked and do not count towards a scene's cloud fraction; pixels invalid in every frame hold the output fill.

This is a coarse cloud-aware composite, not a per-pixel cloud-distance composite — frames are ranked by their overall cloud coverage rather than by distance-to-nearest-cloud at each pixel. Use :class:BAPComposite with per-pixel cloud_distance metadata when that finer granularity is needed.

Metadata-independent: plain np.ndarray frames are accepted and yield plain-array outputs.

Parameters:

Name Type Description Default
return_count bool

When true, also return a carrier with the number of clear contributors per pixel (int64). The output is then a tuple, so the operator is terminal (last step only) in a Sequential.

False
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class MinCloudComposite(Operator):
    """Pick each pixel from the scene with the lowest *global* cloud coverage.

    For every pixel, the selected frame is the one with the smallest
    scene-wide cloud fraction among those where the pixel is clear. Pixels
    cloudy in every frame fall back to the globally least-cloudy frame so
    the output is a complete composite. Nodata frame-pixels (non-finite or
    the frame's fill) are never picked and do not count towards a scene's
    cloud fraction; pixels invalid in every frame hold the output fill.

    This is a coarse cloud-aware composite, not a per-pixel
    cloud-distance composite — frames are ranked by their overall cloud
    coverage rather than by distance-to-nearest-cloud at each pixel. Use
    :class:`BAPComposite` with per-pixel ``cloud_distance`` metadata when
    that finer granularity is needed.

    Metadata-independent: plain ``np.ndarray`` frames are accepted and
    yield plain-array outputs.

    Args:
        return_count: When true, also return a carrier with the number
            of clear contributors per pixel (``int64``).
            The output is then a tuple, so the operator is terminal
            (last step only) in a ``Sequential``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the frame with the lowest cloud fraction over the scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space", "time"}, effects={"time": "reduce"}, reach=None
    )

    def __init__(self, *, return_count: bool = False) -> None:
        self.return_count = return_count

    @property
    def _terminal(self) -> bool:  # ty: ignore[invalid-attribute-override]
        """A tuple output breaks carrier-in / carrier-out (last step only)."""
        return self.return_count

    def _apply(
        self, *pairs: tuple[GeoArray | np.ndarray, Any]
    ) -> GeoArray | np.ndarray | tuple[GeoArray | np.ndarray, GeoArray | np.ndarray]:
        name = type(self).__name__
        pairs = gather_inputs(pairs, name, pairs=True)
        base, stack, cloudy = _require_pairs(pairs, name)
        valid = broadcast_frame_valid(
            _frame_validity([scene for scene, _ in pairs]), cloudy.shape
        )
        clear = ~cloudy & valid
        # Scene-wide cloud fraction over each frame's *valid* pixels only; a
        # frame with no valid pixel counts as fully cloudy.
        n_valid = valid.reshape((valid.shape[0], -1)).sum(axis=1)
        n_cloudy = (cloudy & valid).reshape((valid.shape[0], -1)).sum(axis=1)
        cloud_coverage = np.where(
            n_valid > 0, n_cloudy / np.maximum(n_valid, 1), 1.0
        ).reshape((-1, *([1] * (clear.ndim - 1))))
        # Clear pixels win; cloudy-but-valid pixels fall back to the least
        # cloudy valid frame (the +2 keeps them behind every clear option);
        # nodata frame-pixels are never picked.
        costs = np.where(
            clear, cloud_coverage, np.where(valid, cloud_coverage + 2.0, np.inf)
        )
        index = np.argmin(costs, axis=0)
        values = take_by_spatial_index(stack, index)
        fill = carried_fill(base, values.dtype)
        values = restore_fill(values, valid.any(axis=0), fill)
        out = wrap_like(base, values, fill_value=fill)
        if not self.return_count:
            return out
        count = np.sum(clear, axis=0).astype(np.int64)
        return out, wrap_like(base, count, fill_value=0)

StackMatched

Bases: Operator

Concatenate aligned tensors along the band axis.

Inputs are positional, op(a, b, ...) -- so the operator wires into a pipekit_ops.Graph as StackMatched()(Input("a"), Input("b")) -- or one Sequence[GeoArray] or Mapping[str, GeoArray] -- typical when called on MatchedPatch.members -- or one (T, C, H, W) stack whose frames are the inputs. All inputs must share spatial shape, transform, and CRS; the per-tensor band count may differ. Plain np.ndarray inputs are also accepted (the concatenation itself is metadata-free); grid verification then degrades to spatial-shape equality and the output carrier follows the first input.

Parameters:

Name Type Description Default
order list[str] | None

When the input is a Mapping, this list fixes the stacking order. Must cover every key of the input mapping exactly — extra or missing names raise. (If you want a subset, slice the input dict before passing it in; this avoids silently dropping a key the user forgot to update.) Ignored for Sequence inputs.

None

Examples:

>>> import geoops as gz
>>> stack = gz.compositing.StackMatched(order=["modis", "s2"])
>>> fused = stack({"modis": modis_chip, "s2": s2_chip_aligned})
>>> fused.shape  # (modis_bands + s2_bands, H, W)
(5, 256, 256)
Notes

Per-band attrs (band_names, descriptions, wavelengths, ...) are concatenated in stacking order when every input carries them; a key missing from any input is dropped. Other attrs follow the first input. NaN-fill padding on grid mismatch is not implemented; the operator requires strict grid equality. Pre-coregister with geoops.geom.coregister.RasterToRasterLike if the inputs aren't already on the same grid. Nodata pixels of each input (non-finite or that input's fill) are rewritten to the output's fill (the first input's fill_value) in that input's bands, when the output dtype can represent it.

Where :func:geoarray.concatenate applies (3-D GeoArray inputs with equal fills and no nodata pixels) the output matches it. The operator does not delegate to it because concatenate refuses 2-D inputs and plain arrays, and leaves each input's nodata pixels as they are.

Source code in packages/geotoolz-ops/src/geoops/compositing/_src/operators.py
class StackMatched(Operator):
    """Concatenate aligned tensors along the band axis.

    Inputs are positional, ``op(a, b, ...)`` -- so the operator wires into
    a ``pipekit_ops.Graph`` as ``StackMatched()(Input("a"), Input("b"))`` --
    or one ``Sequence[GeoArray]`` or ``Mapping[str, GeoArray]`` --
    typical when called on `MatchedPatch.members` -- or one ``(T, C, H, W)``
    stack whose frames are the inputs. All inputs must share spatial shape,
    transform, and CRS; the per-tensor band count may differ. Plain
    ``np.ndarray`` inputs are also accepted (the concatenation itself is
    metadata-free); grid verification then degrades to spatial-shape
    equality and the output carrier follows the first input.

    Args:
        order: When the input is a Mapping, this list fixes the
            stacking order. Must cover every key of the input
            mapping **exactly** — extra or missing names raise. (If
            you want a subset, slice the input dict before passing
            it in; this avoids silently dropping a key the user
            forgot to update.) Ignored for Sequence inputs.

    Examples:
        >>> import geoops as gz
        >>> stack = gz.compositing.StackMatched(order=["modis", "s2"])
        >>> fused = stack({"modis": modis_chip, "s2": s2_chip_aligned})
        >>> fused.shape  # (modis_bands + s2_bands, H, W)
        (5, 256, 256)

    Notes:
        Per-band attrs (``band_names``, ``descriptions``, ``wavelengths``,
        ...) are concatenated in stacking order when every input carries
        them; a key missing from any input is dropped. Other attrs follow
        the first input. NaN-fill padding on grid mismatch is not
        implemented; the operator requires strict grid
        equality. Pre-coregister with
        ``geoops.geom.coregister.RasterToRasterLike`` if the
        inputs aren't already on the same grid. Nodata pixels of each
        input (non-finite or that input's fill) are rewritten to the
        output's fill (the first input's ``fill_value``) in that
        input's bands, when the output dtype can represent it.

        Where :func:`geoarray.concatenate` applies (3-D GeoArray inputs
        with equal fills and no nodata pixels) the output matches it. The
        operator does not delegate to it because ``concatenate`` refuses
        2-D inputs and plain arrays, and leaves each input's nodata
        pixels as they are.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the N inputs joined along the band axis
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "join"})

    def __init__(
        self,
        *,
        order: list[str] | None = None,
    ) -> None:
        self.order = list(order) if order is not None else None

    def _apply(
        self,
        *tensors: GeoArray
        | np.ndarray
        | Sequence[GeoArray | np.ndarray]
        | Mapping[str, GeoArray | np.ndarray],
    ) -> GeoArray | np.ndarray:
        seq, _names = _normalize_to_sequence(tensors, self.order, "StackMatched")
        if not seq:
            raise ValueError("StackMatched requires at least one input tensor.")

        # Validate grids exactly — silent affine drift on a per-pixel
        # fused stack is a real bug source; we'd rather fail loudly
        # than emit subtly misregistered output.
        base = seq[0]
        for idx, frame in enumerate(seq[1:], start=1):
            require_grid_match(
                base, frame, "StackMatched", names=("input 0", f"input {idx}")
            )

        arrays = [_as_band_first(np.asarray(t)) for t in seq]
        stacked = np.concatenate(arrays, axis=0)
        fill = carried_fill(base, stacked.dtype)
        stacked = _translate_fills(stacked, seq, arrays, fill)
        attrs = strip_band_attrs(getattr(base, "attrs", None))
        attrs.update(
            concat_band_attrs(
                [getattr(t, "attrs", None) for t in seq],
                [arr.shape[0] for arr in arrays],
            )
        )
        return wrap_like(base, stacked, fill_value=fill, attrs=attrs)

argreduce(x, fn, dim)

pipekit_array.argreduce that never picks an invalid entry.

Parameters:

Name Type Description Default
x Any

A GeoArray, GeoPoints or GeoSwath.

required
fn str

"argmax" or "argmin".

required
dim str

The dim to pick an index along.

required

Returns:

Type Description
Any

The integer index carrier pipekit_array.argreduce returns. Where

Any

every entry along dim is invalid the index is 0, so

``take_along`` there gathers an invalid entry

the nodata survives.

Raises:

Type Description
TypeError

x is not a geoarray carrier.

ValueError

fn is not "argmax" or "argmin".

Example

import numpy as np from geoarray import GeoArray from geoops.compositing import argreduce t = (20.0, 0.0, 0.0, 0.0, -20.0, 0.0) ndvi = GeoArray( ... np.array([[[0.4]], [[9.0]], [[0.7]]]), t, None, fill_value=9.0, ... dims="time y x", ... ) argreduce(ndvi, "argmax", "time").data.tolist() # 9.0 is the fill [[2]]

Source code in packages/geotoolz-ops/src/geoops/compositing/_src/reduce.py
def argreduce(x: Any, fn: str, dim: str) -> Any:
    """``pipekit_array.argreduce`` that never picks an invalid entry.

    Args:
        x: A `GeoArray`, `GeoPoints` or `GeoSwath`.
        fn: ``"argmax"`` or ``"argmin"``.
        dim: The dim to pick an index along.

    Returns:
        The integer index carrier `pipekit_array.argreduce` returns. Where
        every entry along ``dim`` is invalid the index is 0, so
        ``take_along`` there gathers an invalid entry: the nodata survives.

    Raises:
        TypeError: ``x`` is not a geoarray carrier.
        ValueError: ``fn`` is not ``"argmax"`` or ``"argmin"``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> from geoops.compositing import argreduce
        >>> t = (20.0, 0.0, 0.0, 0.0, -20.0, 0.0)
        >>> ndvi = GeoArray(
        ...     np.array([[[0.4]], [[9.0]], [[0.7]]]), t, None, fill_value=9.0,
        ...     dims="time y x",
        ... )
        >>> argreduce(ndvi, "argmax", "time").data.tolist()  # 9.0 is the fill
        [[2]]
    """
    if fn not in _ARG_FILLS:
        raise ValueError(f"argreduce: fn is 'argmax' or 'argmin', got {fn!r}")
    masked = _masked(x, "argreduce")
    xp = masked.xp
    loser = _ARG_FILLS[fn]
    func = getattr(xp, fn)

    def skipping(data: Any, axis: Any) -> Any:
        # an invalid entry takes the value that can never win
        return func(xp.where(xp.isnan(data), loser, data), axis=axis)

    return pipekit_array.argreduce(masked, skipping, dim)

bap_scores(scores, weights)

Weighted Best-Available-Pixel score per frame-pixel.

S_t(y, x) = Σ_k w_k · s_{t,k}(y, x)

Parameters:

Name Type Description Default
scores Float[ndarray, 't k h w']

(T, K, H, W) per-criterion scores in [0, 1] (e.g. view, DOY, cloud distance, opacity).

required
weights Float[ndarray, ' k']

(K,) criterion weights.

required

Returns:

Type Description
Float[ndarray, 't h w']

The (T, H, W) float32 total score.

Examples:

>>> scores = np.ones((2, 4, 1, 1))
>>> bap_scores(scores, np.array([0.3, 0.4, 0.2, 0.1]))[:, 0, 0]
array([1., 1.], dtype=float32)
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def bap_scores(
    scores: Float[np.ndarray, "t k h w"], weights: Float[np.ndarray, " k"]
) -> Float[np.ndarray, "t h w"]:
    """Weighted Best-Available-Pixel score per frame-pixel.

        S_t(y, x) = Σ_k w_k · s_{t,k}(y, x)

    Args:
        scores: ``(T, K, H, W)`` per-criterion scores in ``[0, 1]``
            (e.g. view, DOY, cloud distance, opacity).
        weights: ``(K,)`` criterion weights.

    Returns:
        The ``(T, H, W)`` ``float32`` total score.

    Examples:
        >>> scores = np.ones((2, 4, 1, 1))
        >>> bap_scores(scores, np.array([0.3, 0.4, 0.2, 0.1]))[:, 0, 0]
        array([1., 1.], dtype=float32)
    """
    weights = np.asarray(weights, dtype=np.float32)
    return np.einsum("k,tkhw->thw", weights, scores).astype(np.float32, copy=False)

blend_weighted(stack, weights, *, nan_policy='ignore')

Weighted mean over the leading source axis of a NaN-masked stack.

x̄ = Σ_n w_n · x_n / Σ_n w_n

Parameters:

Name Type Description Default
stack Float[ndarray, 'n *dims h w']

(N, ...) float stack; missing samples are NaN.

required
weights Float[ndarray, 'n *dims h w']

Weights broadcastable to stack ((N, 1, ..., 1) scalars per source, or per-pixel inverse variances).

required
nan_policy NanPolicy

"ignore" drops NaN samples and renormalises the surviving weights (all-NaN pixels become NaN); "propagate" makes any NaN sample poison the pixel.

'ignore'

Returns:

Type Description
Float[ndarray, '*dims']

The blended (...) array; NaN where no weight survives.

Examples:

>>> stack = np.array([[1.0, np.nan], [3.0, 5.0]])
>>> blend_weighted(stack, np.ones((2, 1)))
array([2., 5.])
>>> blend_weighted(stack, np.ones((2, 1)), nan_policy="propagate")
array([ 2., nan])
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def blend_weighted(
    stack: Float[np.ndarray, "n *dims h w"],
    weights: Float[np.ndarray, "n *dims h w"],
    *,
    nan_policy: NanPolicy = "ignore",
) -> Float[np.ndarray, "*dims"]:
    """Weighted mean over the leading source axis of a NaN-masked stack.

        x̄ = Σ_n w_n · x_n / Σ_n w_n

    Args:
        stack: ``(N, ...)`` float stack; missing samples are NaN.
        weights: Weights broadcastable to ``stack`` (``(N, 1, ..., 1)``
            scalars per source, or per-pixel inverse variances).
        nan_policy: ``"ignore"`` drops NaN samples and renormalises the
            surviving weights (all-NaN pixels become NaN);
            ``"propagate"`` makes any NaN sample poison the pixel.

    Returns:
        The blended ``(...)`` array; NaN where no weight survives.

    Examples:
        >>> stack = np.array([[1.0, np.nan], [3.0, 5.0]])
        >>> blend_weighted(stack, np.ones((2, 1)))
        array([2., 5.])
        >>> blend_weighted(stack, np.ones((2, 1)), nan_policy="propagate")
        array([ 2., nan])
    """
    if nan_policy == "propagate":
        # Any NaN in any source ↦ NaN output at that pixel.
        nan_mask = np.isnan(stack).any(axis=0)
        num = (stack * weights).sum(axis=0)
        den = np.broadcast_to(weights, stack.shape).sum(axis=0)
        with np.errstate(invalid="ignore", divide="ignore"):
            result = np.where(den > 0, num / den, np.nan)
        return np.where(nan_mask, np.nan, result)
    # Zero the weight wherever the value is NaN, then drop NaNs from the
    # numerator. The denominator is the sum of surviving weights -- a
    # pixel with all-NaN inputs ends up with den == 0 and becomes NaN.
    valid = ~np.isnan(stack)
    safe_values = np.where(valid, stack, 0.0)
    safe_weights = np.where(valid, weights, 0.0)
    num = (safe_values * safe_weights).sum(axis=0)
    den = safe_weights.sum(axis=0)
    with np.errstate(invalid="ignore", divide="ignore"):
        return np.where(den > 0, num / den, np.nan)

cloud_distance_score(distance, *, d_req, d_min, slope)

Sigmoid distance-to-cloud score (Griffiths et al., 2013, eq. 2).

S_cloud = 1 / (1 + exp(−k · (min(D, D_req) − (D_req − D_min) / 2)))

Parameters:

Name Type Description Default
distance Float[ndarray, '*dims']

D, distance to the nearest cloud / shadow.

required
d_req float

D_req, distance at which the score saturates.

required
d_min float

D_min, the minimum distance.

required
slope float

k, sigmoid slope per distance unit.

required

Returns:

Type Description
Float[ndarray, '*dims']

The score in (0, 1).

Examples:

>>> float(cloud_distance_score(np.array(25.0), d_req=50, d_min=0, slope=0.2))
0.5
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def cloud_distance_score(
    distance: Float[np.ndarray, "*dims"], *, d_req: float, d_min: float, slope: float
) -> Float[np.ndarray, "*dims"]:
    """Sigmoid distance-to-cloud score (Griffiths et al., 2013, eq. 2).

        S_cloud = 1 / (1 + exp(−k · (min(D, D_req) − (D_req − D_min) / 2)))

    Args:
        distance: ``D``, distance to the nearest cloud / shadow.
        d_req: ``D_req``, distance at which the score saturates.
        d_min: ``D_min``, the minimum distance.
        slope: ``k``, sigmoid slope per distance unit.

    Returns:
        The score in ``(0, 1)``.

    Examples:
        >>> float(cloud_distance_score(np.array(25.0), d_req=50, d_min=0, slope=0.2))
        0.5
    """
    d = np.minimum(np.asarray(distance, dtype=np.float64), d_req)
    return 1.0 / (1.0 + np.exp(-slope * (d - (d_req - d_min) / 2.0)))

doy_distance(doy, target_doy)

Circular day-of-year distance to target_doy, in days.

Δ = |doy − target_doy| mod 365,   d = min(Δ, 365 − Δ)

so DOY 360 and target DOY 5 are 10 days apart, not 355. A 365-day year is assumed (DOY 366 coincides with DOY 1).

Parameters:

Name Type Description Default
doy Float[ndarray, '*dims']

Day(s) of year.

required
target_doy float

Reference day of year.

required

Returns:

Type Description
Float[ndarray, '*dims']

The circular distance, float64.

Examples:

>>> float(doy_distance(np.array(360.0), 5))
10.0
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def doy_distance(
    doy: Float[np.ndarray, "*dims"], target_doy: float
) -> Float[np.ndarray, "*dims"]:
    """Circular day-of-year distance to ``target_doy``, in days.

        Δ = |doy − target_doy| mod 365,   d = min(Δ, 365 − Δ)

    so DOY 360 and target DOY 5 are 10 days apart, not 355. A 365-day
    year is assumed (DOY 366 coincides with DOY 1).

    Args:
        doy: Day(s) of year.
        target_doy: Reference day of year.

    Returns:
        The circular distance, ``float64``.

    Examples:
        >>> float(doy_distance(np.array(360.0), 5))
        10.0
    """
    delta = np.mod(
        np.abs(np.asarray(doy, dtype=np.float64) - target_doy), _DAYS_PER_YEAR
    )
    return np.minimum(delta, _DAYS_PER_YEAR - delta)

doy_score(doy, target_doy, sigma)

Gaussian day-of-year score (Griffiths et al., 2013), peak-normalised.

S_doy = exp(−½ · (d / σ_doy)²),   d = circular DOY distance

Griffiths et al. score DOY with a Gaussian centred on the target DOY; the 1/(σ√(2π)) density factor is dropped so S_doy ∈ (0, 1] shares a scale with the other scores (S_doy = e^(−½) ≈ 0.61 at d = σ_doy).

Parameters:

Name Type Description Default
doy Float[ndarray, '*dims']

Day(s) of year.

required
target_doy float

Day of year the Gaussian is centred on.

required
sigma float

σ_doy in days.

required

Returns:

Type Description
Float[ndarray, '*dims']

The score in (0, 1].

Examples:

>>> float(doy_score(np.array(180.0), 180, 30.0))
1.0
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def doy_score(
    doy: Float[np.ndarray, "*dims"], target_doy: float, sigma: float
) -> Float[np.ndarray, "*dims"]:
    """Gaussian day-of-year score (Griffiths et al., 2013), peak-normalised.

        S_doy = exp(−½ · (d / σ_doy)²),   d = circular DOY distance

    Griffiths et al. score DOY with a Gaussian centred on the target DOY;
    the ``1/(σ√(2π))`` density factor is dropped so ``S_doy ∈ (0, 1]``
    shares a scale with the other scores (``S_doy = e^(−½) ≈ 0.61`` at
    ``d = σ_doy``).

    Args:
        doy: Day(s) of year.
        target_doy: Day of year the Gaussian is centred on.
        sigma: ``σ_doy`` in days.

    Returns:
        The score in ``(0, 1]``.

    Examples:
        >>> float(doy_score(np.array(180.0), 180, 30.0))
        1.0
    """
    d = doy_distance(doy, target_doy)
    return np.exp(-0.5 * (d / sigma) ** 2)

mask_frames(stack, valid)

Float copy of stack with every invalid frame-pixel set to NaN.

Float stacks keep their dtype; integer stacks become float64 -- the dtype np.median / integer division already produced for them.

Parameters:

Name Type Description Default
stack Num[ndarray, 't *dims h w']

(T, ..., H, W) frame stack.

required
valid Bool[ndarray, 't h w']

(T, H, W) per-frame validity; False becomes NaN in every band of that frame-pixel.

required

Returns:

Type Description
Float[ndarray, 't *dims h w']

The masked float copy.

Examples:

>>> stack = np.ones((2, 1, 2), dtype=np.int16)
>>> mask_frames(stack, np.array([[[True, False]], [[True, True]]]))[0]
array([[ 1., nan]])
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def mask_frames(
    stack: Num[np.ndarray, "t *dims h w"], valid: Bool[np.ndarray, "t h w"]
) -> Float[np.ndarray, "t *dims h w"]:
    """Float copy of ``stack`` with every invalid frame-pixel set to NaN.

    Float stacks keep their dtype; integer stacks become ``float64`` --
    the dtype ``np.median`` / integer division already produced for them.

    Args:
        stack: ``(T, ..., H, W)`` frame stack.
        valid: ``(T, H, W)`` per-frame validity; ``False`` becomes NaN in
            every band of that frame-pixel.

    Returns:
        The masked float copy.

    Examples:
        >>> stack = np.ones((2, 1, 2), dtype=np.int16)
        >>> mask_frames(stack, np.array([[[True, False]], [[True, True]]]))[0]
        array([[ 1., nan]])
    """
    dtype = stack.dtype if np.issubdtype(stack.dtype, np.inexact) else np.float64
    out = stack.astype(dtype, copy=True)
    out[~broadcast_frame_valid(valid, out.shape)] = np.nan
    return out

mean_composite(stack, clear, *, min_valid=1, nan_policy='ignore')

Per-pixel mean over the clear samples of a frame stack.

μ(y, x) = Σ_t [clear_t] · x_t / Σ_t [clear_t]

Parameters:

Name Type Description Default
stack Float[ndarray, 't *dims h w']

(T, ..., H, W) float stack; missing samples are NaN.

required
clear Bool[ndarray, 't *dims h w']

Same-shape mask of samples allowed to contribute.

required
min_valid int

Minimum contributors per pixel; pixels with fewer come out NaN.

1
nan_policy NanPolicy

"ignore" also drops NaN samples from clear; "propagate" lets a NaN clear sample poison the mean.

'ignore'

Returns:

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

(mean, count) -- the mean (float, NaN below min_valid) and

Int[ndarray, '*dims h w']

the per-pixel contributor count.

Examples:

>>> stack = np.array([[[1.0]], [[3.0]], [[np.nan]]])
>>> mean, count = mean_composite(stack, np.ones_like(stack, bool))
>>> mean, count
(array([[2.]]), array([[2]]))
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def mean_composite(
    stack: Float[np.ndarray, "t *dims h w"],
    clear: Bool[np.ndarray, "t *dims h w"],
    *,
    min_valid: int = 1,
    nan_policy: NanPolicy = "ignore",
) -> tuple[Float[np.ndarray, "*dims h w"], Int[np.ndarray, "*dims h w"]]:
    """Per-pixel mean over the clear samples of a frame stack.

        μ(y, x) = Σ_t [clear_t] · x_t / Σ_t [clear_t]

    Args:
        stack: ``(T, ..., H, W)`` float stack; missing samples are NaN.
        clear: Same-shape mask of samples allowed to contribute.
        min_valid: Minimum contributors per pixel; pixels with fewer
            come out NaN.
        nan_policy: ``"ignore"`` also drops NaN samples from ``clear``;
            ``"propagate"`` lets a NaN clear sample poison the mean.

    Returns:
        ``(mean, count)`` -- the mean (float, NaN below ``min_valid``) and
        the per-pixel contributor count.

    Examples:
        >>> stack = np.array([[[1.0]], [[3.0]], [[np.nan]]])
        >>> mean, count = mean_composite(stack, np.ones_like(stack, bool))
        >>> mean, count
        (array([[2.]]), array([[2]]))
    """
    valid = clear & ~np.isnan(stack) if nan_policy == "ignore" else clear
    count = np.sum(valid, axis=0)
    total = np.sum(np.where(valid, stack, 0), axis=0)
    with np.errstate(invalid="ignore", divide="ignore"):
        values = total / count
    values = np.where(count >= min_valid, values, np.nan)
    return values.astype(np.result_type(values.dtype, np.float32), copy=False), count

median_composite(stack, *, nan_policy='ignore')

Per-pixel median over the frame axis of a NaN-masked stack.

m(y, x) = median_t stack[t, ..., y, x]

Parameters:

Name Type Description Default
stack Float[ndarray, 't *dims h w']

(T, ..., H, W) float stack; missing samples are NaN (see :func:mask_frames).

required
nan_policy NanPolicy

"ignore" skips NaN samples (np.nanmedian); "propagate" makes any NaN sample poison the pixel.

'ignore'

Returns:

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

The (..., H, W) median; pixels with no finite sample are NaN.

Examples:

>>> stack = np.array([[[1.0]], [[np.nan]], [[3.0]]])
>>> median_composite(stack)
array([[2.]])
>>> median_composite(stack, nan_policy="propagate")
array([[nan]])
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def median_composite(
    stack: Float[np.ndarray, "t *dims h w"], *, nan_policy: NanPolicy = "ignore"
) -> Float[np.ndarray, "*dims h w"]:
    """Per-pixel median over the frame axis of a NaN-masked stack.

        m(y, x) = median_t stack[t, ..., y, x]

    Args:
        stack: ``(T, ..., H, W)`` float stack; missing samples are NaN
            (see :func:`mask_frames`).
        nan_policy: ``"ignore"`` skips NaN samples (``np.nanmedian``);
            ``"propagate"`` makes any NaN sample poison the pixel.

    Returns:
        The ``(..., H, W)`` median; pixels with no finite sample are NaN.

    Examples:
        >>> stack = np.array([[[1.0]], [[np.nan]], [[3.0]]])
        >>> median_composite(stack)
        array([[2.]])
        >>> median_composite(stack, nan_policy="propagate")
        array([[nan]])
    """
    with warnings.catch_warnings():
        # All-NaN pixels are expected; callers overwrite them with a fill.
        warnings.filterwarnings("ignore", "All-NaN slice", RuntimeWarning)
        if nan_policy == "ignore":
            return np.nanmedian(stack, axis=0)
        return np.median(stack, axis=0)

opacity_score(opacity, *, low, high)

Piecewise-linear atmospheric-opacity score (White et al., 2014).

S_opacity = clip((τ_high − τ) / (τ_high − τ_low), 0, 1)

i.e. 1 for τ ≤ τ_low, 0 for τ ≥ τ_high, linear between.

Parameters:

Name Type Description Default
opacity Float[ndarray, '*dims']

Unitless atmospheric opacity τ.

required
low float

τ_low.

required
high float

τ_high.

required

Returns:

Type Description
Float[ndarray, '*dims']

The score in [0, 1].

Examples:

>>> float(opacity_score(np.array(0.25), low=0.2, high=0.3))
0.5
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def opacity_score(
    opacity: Float[np.ndarray, "*dims"], *, low: float, high: float
) -> Float[np.ndarray, "*dims"]:
    """Piecewise-linear atmospheric-opacity score (White et al., 2014).

        S_opacity = clip((τ_high − τ) / (τ_high − τ_low), 0, 1)

    i.e. 1 for ``τ ≤ τ_low``, 0 for ``τ ≥ τ_high``, linear between.

    Args:
        opacity: Unitless atmospheric opacity ``τ``.
        low: ``τ_low``.
        high: ``τ_high``.

    Returns:
        The score in ``[0, 1]``.

    Examples:
        >>> float(opacity_score(np.array(0.25), low=0.2, high=0.3))
        0.5
    """
    tau = np.asarray(opacity, dtype=np.float64)
    return np.clip((high - tau) / (high - low), 0.0, 1.0)

reduce(x, fn, dim)

pipekit_array.reduce over the valid entries of a geoarray carrier.

Parameters:

Name Type Description Default
x Any

A GeoArray, GeoPoints or GeoSwath: anything with data, fill_value and with_data.

required
fn str | Callable[..., Any]

A named reduction ("mean", "median", "max", …, or its nan* form), or a function taking axis=, which gets float data with NaN at invalid entries.

required
dim str | Sequence[str]

The dim to reduce over, or several.

required

Returns:

Type Description
Any

The reduced carrier, as pipekit_array.reduce returns it (a

Any

GeoArray while y and x survive), with float data and a

NaN fill

NaN where no entry along dim was valid.

Raises:

Type Description
TypeError

x is not a geoarray carrier.

ValueError

fn names a reduction with no NaN-skipping form.

Example

import numpy as np from geoarray import GeoArray from geoops.compositing import reduce t = (20.0, 0.0, 0.0, 0.0, -20.0, 0.0) stack = GeoArray( ... np.array([[[1.0]], [[0.0]], [[3.0]]]), t, None, fill_value=0.0, ... dims="time y x", ... ) reduce(stack, "mean", "time").data.tolist() # the 0 is nodata [[2.0]]

Source code in packages/geotoolz-ops/src/geoops/compositing/_src/reduce.py
def reduce(x: Any, fn: str | Callable[..., Any], dim: str | Sequence[str]) -> Any:
    """``pipekit_array.reduce`` over the valid entries of a geoarray carrier.

    Args:
        x: A `GeoArray`, `GeoPoints` or `GeoSwath`: anything with ``data``,
            ``fill_value`` and ``with_data``.
        fn: A named reduction (``"mean"``, ``"median"``, ``"max"``, …, or
            its ``nan*`` form), or a function taking ``axis=``, which gets
            float data with NaN at invalid entries.
        dim: The dim to reduce over, or several.

    Returns:
        The reduced carrier, as `pipekit_array.reduce` returns it (a
        `GeoArray` while ``y`` and ``x`` survive), with float data and a
        NaN fill: NaN where no entry along ``dim`` was valid.

    Raises:
        TypeError: ``x`` is not a geoarray carrier.
        ValueError: ``fn`` names a reduction with no NaN-skipping form.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> from geoops.compositing import reduce
        >>> t = (20.0, 0.0, 0.0, 0.0, -20.0, 0.0)
        >>> stack = GeoArray(
        ...     np.array([[[1.0]], [[0.0]], [[3.0]]]), t, None, fill_value=0.0,
        ...     dims="time y x",
        ... )
        >>> reduce(stack, "mean", "time").data.tolist()  # the 0 is nodata
        [[2.0]]
    """
    masked = _masked(x, "reduce")
    xp = masked.xp
    if callable(fn):
        return pipekit_array.reduce(masked, fn, dim)
    name = NAN_FORMS.get(fn, fn)
    if name not in NAN_FORMS.values():
        raise ValueError(
            f"reduce: {fn!r} has no NaN-skipping form; use one of "
            f"{sorted(NAN_FORMS)}, or pass a function that handles NaN"
        )
    func = getattr(xp, name)

    def skipping(data: Any, axis: Any) -> Any:
        # nodata never counts; a position with no data at all stays NaN
        # (nansum / nanprod would give 0 / 1 there)
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=RuntimeWarning)
            out = func(data, axis=axis)
        none_valid = xp.all(xp.isnan(data), axis=axis)
        return xp.where(none_valid, xp.asarray(float("nan"), dtype=out.dtype), out)

    return pipekit_array.reduce(masked, skipping, dim)

take_by_spatial_index(stack, index)

Select one frame per sample from a (T, ..., H, W) stack.

out[..., y, x] = stack[index[..., y, x], ..., y, x]

Parameters:

Name Type Description Default
stack Shaped[ndarray, 't *dims h w']

Frame stack, frame axis first.

required
index Int[ndarray, 'h w'] | Int[ndarray, '*dims h w']

Frame index in [0, T) -- one per pixel (H, W) (shared by every band), or one per sample (..., H, W).

required

Returns:

Type Description
Shaped[ndarray, '*dims h w']

A new (..., H, W) array with stack's dtype.

Examples:

>>> stack = np.arange(8).reshape(2, 2, 2)
>>> take_by_spatial_index(stack, np.array([[0, 1], [1, 0]]))
array([[0, 5],
       [6, 3]])
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def take_by_spatial_index(
    stack: Shaped[np.ndarray, "t *dims h w"],
    index: Int[np.ndarray, "h w"] | Int[np.ndarray, "*dims h w"],
) -> Shaped[np.ndarray, "*dims h w"]:
    """Select one frame per sample from a ``(T, ..., H, W)`` stack.

        out[..., y, x] = stack[index[..., y, x], ..., y, x]

    Args:
        stack: Frame stack, frame axis first.
        index: Frame index in ``[0, T)`` -- one per pixel ``(H, W)``
            (shared by every band), or one per sample ``(..., H, W)``.

    Returns:
        A new ``(..., H, W)`` array with ``stack``'s dtype.

    Examples:
        >>> stack = np.arange(8).reshape(2, 2, 2)
        >>> take_by_spatial_index(stack, np.array([[0, 1], [1, 0]]))
        array([[0, 5],
               [6, 3]])
    """
    index = np.broadcast_to(index, stack.shape[1:])
    return einx.get_at("[t] ..., ... -> ...", stack, index)

view_angle_score(view_angle, sigma)

Gaussian view-zenith-angle score, best at nadir.

S_view = exp(−½ · (θ / σ_θ)²)

Parameters:

Name Type Description Default
view_angle Float[ndarray, '*dims']

View zenith angle θ in degrees (sign ignored).

required
sigma float

σ_θ in degrees.

required

Returns:

Type Description
Float[ndarray, '*dims']

The score in (0, 1].

Examples:

>>> float(view_angle_score(np.array(0.0), 15.0))
1.0
Source code in packages/geotoolz-ops/src/geoops/compositing/_src/array.py
def view_angle_score(
    view_angle: Float[np.ndarray, "*dims"], sigma: float
) -> Float[np.ndarray, "*dims"]:
    """Gaussian view-zenith-angle score, best at nadir.

        S_view = exp(−½ · (θ / σ_θ)²)

    Args:
        view_angle: View zenith angle ``θ`` in degrees (sign ignored).
        sigma: ``σ_θ`` in degrees.

    Returns:
        The score in ``(0, 1]``.

    Examples:
        >>> float(view_angle_score(np.array(0.0), 15.0))
        1.0
    """
    theta = np.asarray(view_angle, dtype=np.float64)
    return np.exp(-0.5 * (theta / sigma) ** 2)