Skip to content

Matched Filter

Pure-NumPy matched-filter family for hyperspectral retrieval (CH₄ / CO₂ / arbitrary trace gases). Each piece — background mean, covariance, target spectrum, scoring — is a separate Operator so the algebra is composable.

  • Core scoring: MatchedFilter, MatchedFilterPixel, MatchedFilterSNR
  • Background statistics:
  • EstimateMean, EstimateCovEmpirical, EstimateCovLowRank, EstimateCovShrunk
  • StreamingBackground — Welford accumulator + shrunk covariance across many cubes
  • AdaptiveWindowBackground / ApplyAdaptiveMF — sliding-window local mean + diagonal variance, scored per pixel with α = tᵀΛ⁻¹(x − μ) / (tᵀΛ⁻¹t), Λ = diag(σ² + ridge)
  • GMMClusterBackground / ApplyClusterMF — cluster-conditional background
  • Target construction: LinearTargetFromObs, NonlinearTargetFromObs
  • Composed: ColumnEnhancement — mean → cov → target → MF in one operator
  • Result containers: NumpyLinearOperator (dense covariance with solve), AdaptiveBackground, ClusterBackground, StreamingBackgroundResult, WelfordAccumulator
  • Post-processing: DetectionThreshold, ValidateMFInputs
  • Array primitives (no GeoArray): apply_image, apply_pixel, apply_adaptive_mf, matched_filter_snr, estimate_mean, estimate_cov_empirical, estimate_cov_shrunk, estimate_cov_lowrank, shrink_covariance, detection_threshold, validate_mf_inputs

Covariance shrinkage ("ledoit_wolf", the default, and "oas") reproduces sklearn.covariance.ledoit_wolf / sklearn.covariance.oas: the shrinkage intensity is identical on the same centred samples, and because this package uses the 1/(n − 1) sample covariance the shrunk matrix is exactly n/(n − 1) times sklearn's (matched-filter scores are invariant to that scale). Ledoit-Wolf needs the sample fourth moment m₄ = mean‖xₖ − x̄‖⁴: estimate_cov_shrunk computes it from the pixels, StreamingBackground streams it through WelfordAccumulator.m4, and a direct shrink_covariance(method="ledoit_wolf", ...) call must pass fourth_moment=.

geoops.matched_filter

Composable pure-NumPy matched-filter operators.

AdaptiveBackground dataclass

Local per-pixel background statistics from square-window filtering.

Produced by adaptive_window_background. The covariance model is diagonal: only per-band local variances are stored.

Attributes:

Name Type Description
mean Float[ndarray, 'c h w']

Per-pixel local mean cube, shaped like the input (c, h, w).

variance Float[ndarray, 'c h w']

Per-pixel local (diagonal, unbiased) variance cube, shaped like the input (c, h, w).

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@dataclass(frozen=True)
class AdaptiveBackground:
    """Local per-pixel background statistics from square-window filtering.

    Produced by `adaptive_window_background`. The covariance model is
    diagonal: only per-band local variances are stored.

    Attributes:
        mean: Per-pixel local mean cube, shaped like the input
            ``(c, h, w)``.
        variance: Per-pixel local (diagonal, unbiased) variance cube,
            shaped like the input ``(c, h, w)``.
    """

    mean: Float[np.ndarray, "c h w"]
    variance: Float[np.ndarray, "c h w"]

AdaptiveWindowBackground

Bases: Operator

Per-pixel local mean and diagonal variance over a square window.

Accepts a GeoArray or plain np.ndarray 3-D cube and returns an AdaptiveBackground (a pair of statistic cubes, not a carrier). Nodata pixels (non-finite or equal to the input's fill value in any band) carry no window weight and are NaN in both cubes.

Parameters:

Name Type Description Default
window int

Side length of the square window; positive odd integer. Default 7.

7
pad_mode str

Boundary mode forwarded to :func:scipy.ndimage.uniform_filter. Default "reflect".

'reflect'
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class AdaptiveWindowBackground(Operator):
    """Per-pixel local mean and diagonal variance over a square window.

    Accepts a ``GeoArray`` or plain ``np.ndarray`` 3-D cube and returns
    an `AdaptiveBackground` (a pair of statistic cubes, not a carrier).
    Nodata pixels (non-finite or equal to the input's fill value in any
    band) carry no window weight and are ``NaN`` in both cubes.

    Args:
        window: Side length of the square window; positive odd
            integer. Default ``7``.
        pad_mode: Boundary mode forwarded to
            :func:`scipy.ndimage.uniform_filter`. Default ``"reflect"``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a local mean and covariance per window
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        window: int = 7,
        pad_mode: str = "reflect",
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.window = window
        self.pad_mode = pad_mode
        self.dim = band_dim(dim, axis, "AdaptiveWindowBackground")

    def _apply(self, gt: GeoArray | np.ndarray) -> AdaptiveBackground:
        axis = dim_axis(gt, self.dim, name="AdaptiveWindowBackground")
        require_ndim(gt, 3, type(self).__name__)
        return adaptive_window_background(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            window=self.window,
            pad_mode=self.pad_mode,
            axis=axis,
        )

ApplyAdaptiveMF

Bases: Operator

Apply a matched filter against per-pixel local window statistics.

Scores each pixel with α = tᵀΛ⁻¹(x − μ) / (tᵀΛ⁻¹t) where μ and Λ = diag(σ² + ridge) are the pixel's own local mean and diagonal variance from :class:AdaptiveWindowBackground (see :func:geoops.matched_filter._src.array.apply_adaptive_mf). Accepts a GeoArray or plain np.ndarray 3-D cube and returns the score map as the same carrier kind. Nodata pixels (non-finite or equal to the input's fill value in any band) and pixels whose window statistics are undefined hold NaN (fill_value=NaN).

The background is supplied at apply time as a runtime input so the config (target, ridge, axis) stays hydra-/YAML-safe; pair it with :class:AdaptiveWindowBackground in a pipeline::

bg = AdaptiveWindowBackground(window=7)(gt)
scores = ApplyAdaptiveMF(target=t)(gt, bg)

Parameters:

Name Type Description Default
target ndarray

Target signature (c,).

required
ridge float

Non-negative variance floor added to every local σ². Default 0.0.

0.0
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class ApplyAdaptiveMF(Operator):
    """Apply a matched filter against per-pixel local window statistics.

    Scores each pixel with ``α = tᵀΛ⁻¹(x − μ) / (tᵀΛ⁻¹t)`` where ``μ`` and
    ``Λ = diag(σ² + ridge)`` are the pixel's own local mean and diagonal
    variance from :class:`AdaptiveWindowBackground` (see
    :func:`geoops.matched_filter._src.array.apply_adaptive_mf`).
    Accepts a ``GeoArray`` or plain ``np.ndarray`` 3-D cube and returns
    the score map as the same carrier kind. Nodata pixels (non-finite or
    equal to the input's fill value in any band) and pixels whose window
    statistics are undefined hold ``NaN`` (``fill_value=NaN``).

    The ``background`` is supplied at apply time as a runtime input so the
    config (``target``, ``ridge``, ``axis``) stays hydra-/YAML-safe; pair
    it with :class:`AdaptiveWindowBackground` in a pipeline::

        bg = AdaptiveWindowBackground(window=7)(gt)
        scores = ApplyAdaptiveMF(target=t)(gt, bg)

    Args:
        target: Target signature ``(c,)``.
        ridge: Non-negative variance floor added to every local ``σ²``.
            Default ``0.0``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the background is a second input
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        target: np.ndarray,
        ridge: float = 0.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.target = target
        self.ridge = ridge
        self.dim = band_dim(dim, axis, "ApplyAdaptiveMF")

    def _apply(
        self, gt: GeoArray | np.ndarray, background: AdaptiveBackground
    ) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="ApplyAdaptiveMF")
        require_ndim(gt, 3, type(self).__name__)
        cube, valid = _mask_invalid(gt, axis, type(self).__name__)
        out = apply_adaptive_mf(
            cube,
            background=background,
            target=self.target,
            ridge=self.ridge,
            axis=axis,
        )
        return wrap_like(
            gt,
            keep_band_axis(_restore(gt, out, valid), gt),
            fill_value=np.nan,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "target": np.asarray(self.target).tolist(),
            "ridge": self.ridge,
            "dim": self.dim,
        }

ApplyClusterMF

Bases: Operator

Apply a matched filter dispatched by per-pixel cluster label.

Accepts a GeoArray or plain np.ndarray cube and returns the score map as the same carrier kind. Nodata pixels (non-finite or equal to the input's fill value in any band, or labelled -1) hold NaN (fill_value=NaN).

The cluster background is supplied at apply time as a runtime input so the operator config (target, axis) is hydra-/YAML-safe and fully describes the operator's init-time state. Pair this operator with :class:GMMClusterBackground in a pipeline to wire the cluster state through dataflow.

Parameters:

Name Type Description Default
target ndarray

Target signature (c,).

required
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class ApplyClusterMF(Operator):
    """Apply a matched filter dispatched by per-pixel cluster label.

    Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns the
    score map as the same carrier kind. Nodata pixels (non-finite or
    equal to the input's fill value in any band, or labelled ``-1``)
    hold ``NaN`` (``fill_value=NaN``).

    The ``cluster`` background is supplied at apply time as a runtime input
    so the operator config (``target``, ``axis``) is hydra-/YAML-safe and
    fully describes the operator's init-time state. Pair this operator
    with :class:`GMMClusterBackground` in a pipeline to wire the cluster
    state through dataflow.

    Args:
        target: Target signature ``(c,)``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the background is a second input
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        target: np.ndarray,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.target = target
        self.dim = band_dim(dim, axis, "ApplyClusterMF")

    def _apply(
        self, gt: GeoArray | np.ndarray, cluster: ClusterBackground
    ) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="ApplyClusterMF")
        cube, valid = _mask_invalid(gt, axis, type(self).__name__)
        out = apply_cluster_mf(cube, cluster=cluster, target=self.target, axis=axis)
        return wrap_like(
            gt,
            keep_band_axis(_restore(gt, out, valid), gt),
            fill_value=np.nan,
        )

    def get_config(self) -> dict[str, Any]:
        return {"target": np.asarray(self.target).tolist(), "dim": self.dim}

ClusterBackground dataclass

Cluster labels with per-cluster matched-filter background statistics.

Produced by gmm_cluster_background and consumed by apply_cluster_mf, which scores each pixel against the statistics of its own cluster.

Attributes:

Name Type Description
labels Int[ndarray, 'h w']

Integer cluster-label map over the cube's spatial shape; values index into means and cov_ops. Invalid (non-finite) pixels are labelled -1.

means Float[ndarray, 'k c']

Per-cluster mean spectra, shaped (k, c).

cov_ops tuple[NumpyLinearOperator, ...]

Per-cluster (c, c) covariance operators, one entry per cluster.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@dataclass(frozen=True)
class ClusterBackground:
    """Cluster labels with per-cluster matched-filter background statistics.

    Produced by `gmm_cluster_background` and consumed by
    `apply_cluster_mf`, which scores each pixel against the statistics
    of its own cluster.

    Attributes:
        labels: Integer cluster-label map over the cube's spatial shape;
            values index into ``means`` and ``cov_ops``. Invalid
            (non-finite) pixels are labelled ``-1``.
        means: Per-cluster mean spectra, shaped ``(k, c)``.
        cov_ops: Per-cluster ``(c, c)`` covariance operators, one entry
            per cluster.
    """

    labels: Int[np.ndarray, "h w"]
    means: Float[np.ndarray, "k c"]
    cov_ops: tuple[NumpyLinearOperator, ...]

ColumnEnhancement

Bases: Operator

Convenience trace-gas column-enhancement matched-filter composite.

Chains :class:EstimateMean, a covariance estimator, an optional :class:LinearTargetFromObs, and :class:MatchedFilter into one call. With obs_model=None the target defaults to a uniform unit spectrum. Accepts a GeoArray or plain np.ndarray cube and returns the enhancement score map as the same carrier kind.

Parameters:

Name Type Description Default
gas str

Gas label recorded in the config (e.g. "CH4"); metadata only, not used in the math.

'CH4'
sensor str

Sensor label recorded in the config (e.g. "EMIT"); metadata only.

'EMIT'
obs_model Any | None

Optional callable observation model used to derive a linearised target; a uniform target is used when None.

None
mean_method MeanMethod

Background-mean estimator. Default "median".

'median'
cov_method CovShrinkageMethod | Literal['lowrank']

Covariance estimator — "ledoit_wolf", "oas", or "lowrank". Default "ledoit_wolf".

'ledoit_wolf'
target_pattern str

Perturbation pattern for target linearisation.

'uniform'
rank int | None

Rank for cov_method="lowrank"; None means the default 10.

None
tikhonov float | None

Tikhonov regulariser for cov_method="lowrank"; None means the default 1e-3.

None
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class ColumnEnhancement(Operator):
    """Convenience trace-gas column-enhancement matched-filter composite.

    Chains :class:`EstimateMean`, a covariance estimator, an optional
    :class:`LinearTargetFromObs`, and :class:`MatchedFilter` into one
    call. With ``obs_model=None`` the target defaults to a uniform unit
    spectrum. Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and
    returns the enhancement score map as the same carrier kind.

    Args:
        gas: Gas label recorded in the config (e.g. ``"CH4"``); metadata
            only, not used in the math.
        sensor: Sensor label recorded in the config (e.g. ``"EMIT"``);
            metadata only.
        obs_model: Optional callable observation model used to derive a
            linearised target; a uniform target is used when ``None``.
        mean_method: Background-mean estimator. Default ``"median"``.
        cov_method: Covariance estimator — ``"ledoit_wolf"``, ``"oas"``,
            or ``"lowrank"``. Default ``"ledoit_wolf"``.
        target_pattern: Perturbation pattern for target linearisation.
        rank: Rank for ``cov_method="lowrank"``; ``None`` means the
            default ``10``.
        tikhonov: Tikhonov regulariser for ``cov_method="lowrank"``;
            ``None`` means the default ``1e-3``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the background is fitted on every call
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band", "space", "time"}, effects={"band": "reduce"}, reach=None
    )

    def __init__(
        self,
        *,
        gas: str = "CH4",
        sensor: str = "EMIT",
        obs_model: Any | None = None,
        mean_method: MeanMethod = "median",
        cov_method: CovShrinkageMethod | Literal["lowrank"] = "ledoit_wolf",
        target_pattern: str = "uniform",
        rank: int | None = None,
        tikhonov: float | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.gas = gas
        self.sensor = sensor
        self.obs_model = reject_config_summary(obs_model, "obs_model")
        self.mean_method = mean_method
        self.cov_method = cov_method
        self.target_pattern = target_pattern
        self.rank = rank
        self.tikhonov = tikhonov
        self.dim = band_dim(dim, axis, "ColumnEnhancement")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="ColumnEnhancement")
        _check_spectral_axis(gt, axis, type(self).__name__)
        mean = EstimateMean(method=self.mean_method, dim=self.dim)(gt)
        if self.cov_method == "lowrank":
            cov_op = EstimateCovLowRank(
                mean=mean,
                rank=10 if self.rank is None else self.rank,
                tikhonov=1e-3 if self.tikhonov is None else self.tikhonov,
                dim=self.dim,
            )(gt)
        else:
            cov_op = EstimateCovShrunk(mean=mean, method=self.cov_method, dim=self.dim)(
                gt
            )
        if self.obs_model is None:
            target = np.ones_like(mean)
        else:
            target = LinearTargetFromObs(
                obs_model=self.obs_model,
                pattern=self.target_pattern,
                dim=self.dim,
            )(gt)
        return MatchedFilter(mean=mean, cov_op=cov_op, target=target, dim=self.dim)(gt)

    def get_config(self) -> dict[str, Any]:
        return {
            "gas": self.gas,
            "sensor": self.sensor,
            # A callable has no config form: the summary makes from_state
            # refuse the reload instead of silently using a uniform target.
            "obs_model": None
            if self.obs_model is None
            else {"callable": callable_name(self.obs_model)},
            "mean_method": self.mean_method,
            "cov_method": self.cov_method,
            "target_pattern": self.target_pattern,
            "rank": self.rank,
            "tikhonov": self.tikhonov,
            "dim": self.dim,
        }

DetectionThreshold

Bases: Operator

Gaussian false-alarm score threshold.

Graph source: computed from its configuration alone. An optional input is accepted and ignored, so it can close a Sequential; it returns the scalar score threshold whose exceedance probability under the Gaussian no-target null equals false_alarm_rate.

Parameters:

Name Type Description Default
false_alarm_rate float

Desired false-alarm probability, strictly between 0 and 1.

required
cov_op NumpyLinearOperator | ndarray

Background covariance as a NumpyLinearOperator or raw (c, c) matrix.

required
target ndarray

Target signature (c,).

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class DetectionThreshold(Operator):
    """Gaussian false-alarm score threshold.

    Graph source: computed from its configuration alone. An optional
    input is accepted and ignored, so it can close a ``Sequential``;
    it returns the scalar score
    threshold whose exceedance probability under the Gaussian no-target
    null equals ``false_alarm_rate``.

    Args:
        false_alarm_rate: Desired false-alarm probability, strictly
            between 0 and 1.
        cov_op: Background covariance as a `NumpyLinearOperator` or raw
            ``(c, c)`` matrix.
        target: Target signature ``(c,)``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(kind="conversion")

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        false_alarm_rate: float,
        cov_op: NumpyLinearOperator | np.ndarray,
        target: np.ndarray,
    ) -> None:
        self.false_alarm_rate = false_alarm_rate
        self.cov_op = cov_op
        self.target = target

    def _apply(self, _input: Any | None = None) -> float:
        reject_geotensor(_input, type(self).__name__)
        return detection_threshold(
            false_alarm_rate=self.false_alarm_rate,
            cov_op=self.cov_op,
            target=self.target,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "false_alarm_rate": self.false_alarm_rate,
            "cov_op": _cov_config(self.cov_op),
            "target": np.asarray(self.target).tolist(),
        }

EstimateCovEmpirical

Bases: Operator

Estimate an empirical covariance operator.

Accepts a GeoArray or plain np.ndarray cube and returns a NumpyLinearOperator (not a carrier) wrapping the (c, c) sample covariance. Nodata pixels (non-finite or equal to the input's fill value in any band) are ignored.

Parameters:

Name Type Description Default
mean ndarray | None

Optional precomputed mean spectrum (c,) to centre on; the sample mean is used when None.

None
ridge float

Optional Tikhonov ridge added to the diagonal.

0.0
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class EstimateCovEmpirical(Operator):
    """Estimate an empirical covariance operator.

    Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns a
    `NumpyLinearOperator` (not a carrier) wrapping the ``(c, c)`` sample
    covariance. Nodata pixels (non-finite or equal to the input's fill
    value in any band) are ignored.

    Args:
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            the sample mean is used when ``None``.
        ridge: Optional Tikhonov ridge added to the diagonal.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

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

    def __init__(
        self,
        *,
        mean: np.ndarray | None = None,
        ridge: float = 0.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.mean = mean
        self.ridge = ridge
        self.dim = band_dim(dim, axis, "EstimateCovEmpirical")

    def _apply(self, gt: GeoArray | np.ndarray) -> NumpyLinearOperator:
        axis = dim_axis(gt, self.dim, name="EstimateCovEmpirical")
        return estimate_cov_empirical(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            mean=self.mean,
            ridge=self.ridge,
            axis=axis,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": None if self.mean is None else np.asarray(self.mean).tolist(),
            "ridge": self.ridge,
            "dim": self.dim,
        }

EstimateCovLowRank

Bases: Operator

Estimate a low-rank-plus-Tikhonov covariance operator.

Accepts a GeoArray or plain np.ndarray cube and returns a NumpyLinearOperator (not a carrier) approximating the covariance by its top-rank eigenpairs plus a Tikhonov diagonal. Nodata pixels (non-finite or equal to the input's fill value in any band) are ignored.

Parameters:

Name Type Description Default
mean ndarray | None

Optional precomputed mean spectrum (c,) to centre on; the sample mean is used when None.

None
rank int

Number of leading eigenpairs kept.

10
tikhonov float

Diagonal regulariser added after the low-rank reconstruction.

0.001
seed int | None

Seed for the randomized range finder; the default 0 makes the estimate deterministic.

0
n_oversamples int

Extra random probe vectors beyond rank.

10
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class EstimateCovLowRank(Operator):
    """Estimate a low-rank-plus-Tikhonov covariance operator.

    Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns a
    `NumpyLinearOperator` (not a carrier) approximating the covariance
    by its top-``rank`` eigenpairs plus a Tikhonov diagonal. Nodata
    pixels (non-finite or equal to the input's fill value in any band)
    are ignored.

    Args:
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            the sample mean is used when ``None``.
        rank: Number of leading eigenpairs kept.
        tikhonov: Diagonal regulariser added after the low-rank
            reconstruction.
        seed: Seed for the randomized range finder; the default
            ``0`` makes the estimate deterministic.
        n_oversamples: Extra random probe vectors beyond ``rank``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

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

    def __init__(
        self,
        *,
        mean: np.ndarray | None = None,
        rank: int = 10,
        tikhonov: float = 1e-3,
        seed: int | None = 0,
        n_oversamples: int = 10,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.mean = mean
        self.rank = rank
        self.tikhonov = tikhonov
        self.seed = seed
        self.n_oversamples = n_oversamples
        self.dim = band_dim(dim, axis, "EstimateCovLowRank")

    def _apply(self, gt: GeoArray | np.ndarray) -> NumpyLinearOperator:
        axis = dim_axis(gt, self.dim, name="EstimateCovLowRank")
        return estimate_cov_lowrank(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            mean=self.mean,
            rank=self.rank,
            tikhonov=self.tikhonov,
            seed=self.seed,
            n_oversamples=self.n_oversamples,
            axis=axis,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": None if self.mean is None else np.asarray(self.mean).tolist(),
            "rank": self.rank,
            "tikhonov": self.tikhonov,
            "seed": self.seed,
            "n_oversamples": self.n_oversamples,
            "dim": self.dim,
        }

EstimateCovShrunk

Bases: Operator

Estimate a diagonal-target shrinkage covariance operator.

Accepts a GeoArray or plain np.ndarray cube and returns a NumpyLinearOperator (not a carrier) wrapping the covariance shrunk toward a scaled-identity target. Nodata pixels (non-finite or equal to the input's fill value in any band) are ignored.

Parameters:

Name Type Description Default
mean ndarray | None

Optional precomputed mean spectrum (c,) to centre on; the sample mean is used when None.

None
method CovShrinkageMethod

Shrinkage-intensity estimator, "ledoit_wolf" or "oas".

'ledoit_wolf'
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class EstimateCovShrunk(Operator):
    """Estimate a diagonal-target shrinkage covariance operator.

    Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns a
    `NumpyLinearOperator` (not a carrier) wrapping the covariance shrunk
    toward a scaled-identity target. Nodata pixels (non-finite or equal
    to the input's fill value in any band) are ignored.

    Args:
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            the sample mean is used when ``None``.
        method: Shrinkage-intensity estimator, ``"ledoit_wolf"`` or
            ``"oas"``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

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

    def __init__(
        self,
        *,
        mean: np.ndarray | None = None,
        method: CovShrinkageMethod = "ledoit_wolf",
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.mean = mean
        self.method = method
        self.dim = band_dim(dim, axis, "EstimateCovShrunk")

    def _apply(self, gt: GeoArray | np.ndarray) -> NumpyLinearOperator:
        axis = dim_axis(gt, self.dim, name="EstimateCovShrunk")
        return estimate_cov_shrunk(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            mean=self.mean,
            method=self.method,
            axis=axis,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": None if self.mean is None else np.asarray(self.mean).tolist(),
            "method": self.method,
            "dim": self.dim,
        }

EstimateMean

Bases: Operator

Estimate a spectral background mean vector from a cube.

Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns the
plain ``(c,)`` mean spectrum (a vector, not a carrier). See

:func:geoops.matched_filter._src.array.estimate_mean for the estimator details. Nodata pixels (non-finite or equal to the input's fill value in any band) are ignored.

Args:
    method: Mean estimator — ``"mean"``, ``"median"``, ``"trimmed"``,
        or ``"huber"``.
    trim_proportion: Fraction cut from each tail for
        ``method="trimmed"``.
    huber_c: Huber tuning constant for ``method="huber"``.
    dim: Name of the band dim (default ``"band"``); its position is read
        from the carrier's dims.
    axis: Deprecated: the band axis position. ``-3`` maps to
        ``dim="band"``; removed in the next minor release.
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class EstimateMean(Operator):
    """Estimate a spectral background mean vector from a cube.

        Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns the
        plain ``(c,)`` mean spectrum (a vector, not a carrier). See
    :func:`geoops.matched_filter._src.array.estimate_mean` for the
        estimator details. Nodata pixels (non-finite or equal to the input's
        fill value in any band) are ignored.

        Args:
            method: Mean estimator — ``"mean"``, ``"median"``, ``"trimmed"``,
                or ``"huber"``.
            trim_proportion: Fraction cut from each tail for
                ``method="trimmed"``.
            huber_c: Huber tuning constant for ``method="huber"``.
            dim: Name of the band dim (default ``"band"``); its position is read
                from the carrier's dims.
            axis: Deprecated: the band axis position. ``-3`` maps to
                ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a mean spectrum over the scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"space"}, reach=None, kind="conversion"
    )

    def __init__(
        self,
        *,
        method: MeanMethod = "mean",
        trim_proportion: float = 0.1,
        huber_c: float = 1.345,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.method = method
        self.trim_proportion = trim_proportion
        self.huber_c = huber_c
        self.dim = band_dim(dim, axis, "EstimateMean")

    def _apply(self, gt: GeoArray | np.ndarray) -> np.ndarray:
        axis = dim_axis(gt, self.dim, name="EstimateMean")
        return estimate_mean(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            method=self.method,
            trim_proportion=self.trim_proportion,
            huber_c=self.huber_c,
            axis=axis,
        )

GMMClusterBackground

Bases: Operator

Estimate clustered background statistics with a NumPy GMM backend.

Runs the deterministic diagonal-GMM clustering (k-means initialised) of :func:geoops.matched_filter._src.array.gmm_cluster_background. Accepts a GeoArray or plain np.ndarray cube and returns a ClusterBackground (labels plus per-cluster statistics, not a carrier), typically wired into :class:ApplyClusterMF. Nodata pixels (non-finite or equal to the input's fill value in any band) are left out of the fit and labelled -1.

Parameters:

Name Type Description Default
n_clusters int

Number of mixture components.

required
cov_estimator Literal['empirical', 'ledoit_wolf', 'oas']

Per-cluster covariance estimator — "empirical", "ledoit_wolf", or "oas".

'ledoit_wolf'
seed int | None

Seed for the clustering; fixed seeds give reproducible backgrounds.

0
bayesian bool

If True, prune components with negligible mixture weight, so fewer than n_clusters clusters may remain.

False
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class GMMClusterBackground(Operator):
    """Estimate clustered background statistics with a NumPy GMM backend.

    Runs the deterministic diagonal-GMM clustering (k-means initialised)
    of :func:`geoops.matched_filter._src.array.gmm_cluster_background`.
    Accepts a ``GeoArray`` or plain ``np.ndarray`` cube and returns a
    `ClusterBackground` (labels plus per-cluster statistics, not a
    carrier), typically wired into :class:`ApplyClusterMF`. Nodata pixels
    (non-finite or equal to the input's fill value in any band) are left
    out of the fit and labelled ``-1``.

    Args:
        n_clusters: Number of mixture components.
        cov_estimator: Per-cluster covariance estimator —
            ``"empirical"``, ``"ledoit_wolf"``, or ``"oas"``.
        seed: Seed for the clustering; fixed seeds give
            reproducible backgrounds.
        bayesian: If ``True``, prune components with negligible mixture
            weight, so fewer than ``n_clusters`` clusters may remain.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

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

    def __init__(
        self,
        *,
        n_clusters: int,
        cov_estimator: Literal["empirical", "ledoit_wolf", "oas"] = "ledoit_wolf",
        seed: int | None = 0,
        bayesian: bool = False,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.n_clusters = n_clusters
        self.cov_estimator = cov_estimator
        self.seed = seed
        self.bayesian = bayesian
        self.dim = band_dim(dim, axis, "GMMClusterBackground")

    def _apply(self, gt: GeoArray | np.ndarray) -> ClusterBackground:
        axis = dim_axis(gt, self.dim, name="GMMClusterBackground")
        return gmm_cluster_background(
            _mask_invalid(gt, axis, type(self).__name__)[0],
            n_clusters=self.n_clusters,
            cov_estimator=self.cov_estimator,
            seed=self.seed,
            bayesian=self.bayesian,
            axis=axis,
        )

LinearTargetFromObs

Bases: Operator

Finite-difference tangent-linear target from an observation model.

Perturbs the background state by a small scaled pattern, pushes both states through obs_model, and divides the response difference by the perturbation size — a per-band linearised (Jacobian-action) target signature (c,). Accepts a GeoArray or plain np.ndarray cube and returns a plain vector (not a carrier).

Parameters:

Name Type Description Default
obs_model Any

Callable mapping a state cube to a spectral response (either a per-band vector or a cube that is averaged over space). Must be callable.

required
vmr_background ndarray | None

Optional explicit background state; the incoming cube is used when None.

None
pattern str | ndarray

Perturbation pattern — "uniform", "impulse", or an explicit array broadcastable to the background state.

'uniform'
pixel tuple[int, int] | None

Spatial index of the impulse for pattern="impulse"; the first flat pixel when None.

None
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class LinearTargetFromObs(Operator):
    """Finite-difference tangent-linear target from an observation model.

    Perturbs the background state by a small scaled pattern, pushes both
    states through ``obs_model``, and divides the response difference by
    the perturbation size — a per-band linearised (Jacobian-action)
    target signature ``(c,)``. Accepts a ``GeoArray`` or plain
    ``np.ndarray`` cube and returns a plain vector (not a carrier).

    Args:
        obs_model: Callable mapping a state cube to a spectral response
            (either a per-band vector or a cube that is averaged over
            space). Must be callable.
        vmr_background: Optional explicit background state; the incoming
            cube is used when ``None``.
        pattern: Perturbation pattern — ``"uniform"``, ``"impulse"``, or
            an explicit array broadcastable to the background state.
        pixel: Spatial index of the impulse for ``pattern="impulse"``;
            the first flat pixel when ``None``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a target spectrum
    coupling: ClassVar[Coupling] = Coupling(kind="conversion")

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        obs_model: Any,
        vmr_background: np.ndarray | None = None,
        pattern: str | np.ndarray = "uniform",
        pixel: tuple[int, int] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.obs_model = obs_model
        self.vmr_background = vmr_background
        self.pattern = pattern
        self.pixel = pixel
        self.dim = band_dim(dim, axis, "LinearTargetFromObs")

    def _apply(self, gt: GeoArray | np.ndarray) -> np.ndarray:
        return (
            _target_from_obs(
                self.obs_model,
                gt,
                vmr_background=self.vmr_background,
                pattern=self.pattern,
                pixel=self.pixel,
                amplitude=TARGET_FINITE_DIFFERENCE_EPSILON,
                axis=dim_axis(gt, self.dim, name="LinearTargetFromObs"),
            )
            / TARGET_FINITE_DIFFERENCE_EPSILON
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "vmr_background": None
            if self.vmr_background is None
            else np.asarray(self.vmr_background).tolist(),
            "pattern": self.pattern
            if isinstance(self.pattern, str)
            else np.asarray(self.pattern).tolist(),
            "obs_model": callable_name(self.obs_model),
            "pixel": self.pixel,
            "dim": self.dim,
        }

MatchedFilter

Bases: Operator

Per-pixel matched-filter score map.

Computes y = (x - mu)^T Sigma^-1 t / (t^T Sigma^-1 t) for every pixel spectrum and returns a single-band score map. Accepts either a GeoArray (georeferencing preserved on the output) or a plain np.ndarray (plain array returned) — the math is metadata-free.

Fitted operator (see Fitted operators in the concepts guide):

  • :meth:fit estimates the background statistics the constructor left unset (mean and / or cov_op) with mean_method / cov_method and stores the full background in mean_ / cov_op_ (supplied components are copied through unchanged);
  • :meth:transform scores a cube with that background without mutating the operator;
  • calling the operator fits the missing statistics once, on the first call (fit_on_call=False), or estimates them from each cube without storing anything (fit_on_call=True, a per-scene background). Neither path writes fitted arrays into get_config().

Nodata pixels (non-finite or equal to the input's fill value in any band) are left out of the fit and hold NaN in the score map, which declares fill_value=NaN.

Parameters:

Name Type Description Default
mean ndarray | None

Background mean spectrum (c,); fitted from the data when None.

None
cov_op NumpyLinearOperator | ndarray | None

Background covariance as a NumpyLinearOperator or raw (c, c) matrix (a nested list, e.g. from a config reload, is coerced to an ndarray); fitted from the data when None.

None
target ndarray | None

Target signature (c,). Must be set before applying.

None
fit_on_call bool

Estimate mean and covariance from every cube the operator is called on (a per-scene background, ignoring any supplied or fitted statistics) instead of fitting the missing ones once.

False
mean_method MeanMethod

Mean estimator used when fitting. Default "median".

'median'
cov_method CovMethod

Covariance estimator used when fitting — "empirical", "ledoit_wolf", "oas", or "lowrank". Default "ledoit_wolf".

'ledoit_wolf'
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None

Attributes:

Name Type Description
mean_ ndarray | None

Background mean from :meth:fit, or None.

cov_op_ NumpyLinearOperator | ndarray | None

Background covariance from :meth:fit, or None.

Examples:

>>> mf = MatchedFilter(target=t).fit(background_scene)
>>> scores = mf(scene)  # reuses the fitted background
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class MatchedFilter(Operator):
    """Per-pixel matched-filter score map.

    Computes ``y = (x - mu)^T Sigma^-1 t / (t^T Sigma^-1 t)`` for every
    pixel spectrum and returns a single-band score map. Accepts either a
    ``GeoArray`` (georeferencing preserved on the output) or a plain
    ``np.ndarray`` (plain array returned) — the math is metadata-free.

    Fitted operator (see *Fitted operators* in the concepts guide):

    * :meth:`fit` estimates the background statistics the constructor
      left unset (``mean`` and / or ``cov_op``) with ``mean_method`` /
      ``cov_method`` and stores the full background in ``mean_`` /
      ``cov_op_`` (supplied components are copied through unchanged);
    * :meth:`transform` scores a cube with that background without
      mutating the operator;
    * calling the operator fits the missing statistics once, on the first
      call (``fit_on_call=False``), or estimates them from each cube
      without storing anything (``fit_on_call=True``, a per-scene
      background). Neither path writes fitted arrays into
      ``get_config()``.

    Nodata pixels (non-finite or equal to the input's fill value in any
    band) are left out of the fit and hold ``NaN`` in the score map,
    which declares ``fill_value=NaN``.

    Args:
        mean: Background mean spectrum ``(c,)``; fitted from the data
            when ``None``.
        cov_op: Background covariance as a `NumpyLinearOperator` or raw
            ``(c, c)`` matrix (a nested list, e.g. from a config reload,
            is coerced to an ndarray); fitted from the data when ``None``.
        target: Target signature ``(c,)``. Must be set before applying.
        fit_on_call: Estimate mean and covariance from every cube the
            operator is called on (a per-scene background, ignoring any
            supplied or fitted statistics) instead of fitting the missing
            ones once.
        mean_method: Mean estimator used when fitting. Default
            ``"median"``.
        cov_method: Covariance estimator used when fitting —
            ``"empirical"``, ``"ledoit_wolf"``, ``"oas"``, or
            ``"lowrank"``. Default ``"ledoit_wolf"``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Attributes:
        mean_: Background mean from :meth:`fit`, or ``None``.
        cov_op_: Background covariance from :meth:`fit`, or ``None``.

    Examples:
        >>> mf = MatchedFilter(target=t).fit(background_scene)
        >>> scores = mf(scene)  # reuses the fitted background
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # alpha = t^T S^-1 (x - mu) / t^T S^-1 t per pixel; mu, S fitted over the scene
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}, fit={"space", "time"}
    )

    def __init__(
        self,
        *,
        mean: np.ndarray | None = None,
        cov_op: NumpyLinearOperator | np.ndarray | None = None,
        target: np.ndarray | None = None,
        fit_on_call: bool = False,
        mean_method: MeanMethod = "median",
        cov_method: CovMethod = "ledoit_wolf",
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.mean = None if mean is None else np.asarray(mean, dtype=float)
        self.cov_op = (
            cov_op
            if cov_op is None or isinstance(cov_op, NumpyLinearOperator)
            else np.asarray(cov_op, dtype=float)
        )
        self.target = None if target is None else np.asarray(target, dtype=float)
        self.fit_on_call = fit_on_call
        self.mean_method = mean_method
        self.cov_method = cov_method
        self.dim = band_dim(dim, axis, "MatchedFilter")
        self.mean_: np.ndarray | None = None
        self.cov_op_: NumpyLinearOperator | np.ndarray | None = None

    def _estimate(
        self, cube: np.ndarray, *, axis: int, keep_supplied: bool
    ) -> tuple[np.ndarray, NumpyLinearOperator | np.ndarray]:
        """Background ``(mean, cov_op)`` of ``cube``.

        ``axis`` is the band position, resolved from the carrier before its
        names were dropped. ``keep_supplied`` keeps the constructor's
        ``mean`` / ``cov_op`` and only estimates the missing ones.
        """
        mean = self.mean if keep_supplied else None
        cov_op = self.cov_op if keep_supplied else None
        if mean is None:
            mean = estimate_mean(cube, method=self.mean_method, axis=axis)
        if cov_op is None:
            if self.cov_method == "empirical":
                cov_op = estimate_cov_empirical(cube, mean=mean, ridge=1e-8, axis=axis)
            elif self.cov_method == "lowrank":
                cov_op = estimate_cov_lowrank(cube, mean=mean, axis=axis)
            else:
                cov_op = estimate_cov_shrunk(
                    cube, mean=mean, method=self.cov_method, axis=axis
                )
        return np.asarray(mean, dtype=float), cov_op

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Estimate the unset background statistics from the valid pixels of ``gt``.

        Returns:
            This operator, for chaining.
        """
        axis = dim_axis(gt, self.dim, name="MatchedFilter")
        cube, _ = _mask_invalid(gt, axis, type(self).__name__)
        mean, cov_op = self._estimate(cube, axis=axis, keep_supplied=True)
        self.cov_op_ = cov_op
        self.mean_ = mean  # published last: the fit-once check reads ``mean_``
        return self

    def _background(self) -> tuple[np.ndarray, NumpyLinearOperator | np.ndarray]:
        if self.mean_ is not None and self.cov_op_ is not None:
            return self.mean_, self.cov_op_
        if self.mean is not None and self.cov_op is not None:
            return self.mean, self.cov_op
        raise ValueError(
            "MatchedFilter requires mean and cov_op, fit(), or a call on data"
        )

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Score ``gt`` against the fitted (or supplied) background.

        Raises:
            ValueError: If no background is available yet or ``target``
                is unset.
        """
        mean, cov_op = self._background()
        return self._score(gt, mean, cov_op)

    def _score(
        self,
        gt: GeoArray | np.ndarray,
        mean: np.ndarray,
        cov_op: NumpyLinearOperator | np.ndarray,
        masked: tuple[np.ndarray, np.ndarray | None] | None = None,
    ) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="MatchedFilter")
        if self.target is None:
            raise ValueError("target must be supplied before applying MatchedFilter")
        cube, valid = (
            _mask_invalid(gt, axis, type(self).__name__) if masked is None else masked
        )
        out = apply_image(cube, mean=mean, cov_op=cov_op, target=self.target, axis=axis)
        return wrap_like(
            gt,
            keep_band_axis(_restore(gt, out, valid), gt),
            fill_value=np.nan,
        )

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.fit_on_call:
            # Per-scene background: estimated locally, never stored, so
            # concurrent calls share no mutable state.
            axis = dim_axis(gt, self.dim, name="MatchedFilter")
            masked = _mask_invalid(gt, axis, type(self).__name__)
            mean, cov_op = self._estimate(masked[0], axis=axis, keep_supplied=False)
            return self._score(gt, mean, cov_op, masked)
        if self.mean is None or self.cov_op is None:
            fit_once(self, gt, lambda: self.mean_ is not None)
        return self.transform(gt)

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": None if self.mean is None else np.asarray(self.mean).tolist(),
            "cov_op": _cov_config(self.cov_op),
            "target": None if self.target is None else np.asarray(self.target).tolist(),
            "fit_on_call": self.fit_on_call,
            "mean_method": self.mean_method,
            "cov_method": self.cov_method,
            "dim": self.dim,
        }

fit(gt)

Estimate the unset background statistics from the valid pixels of gt.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Estimate the unset background statistics from the valid pixels of ``gt``.

    Returns:
        This operator, for chaining.
    """
    axis = dim_axis(gt, self.dim, name="MatchedFilter")
    cube, _ = _mask_invalid(gt, axis, type(self).__name__)
    mean, cov_op = self._estimate(cube, axis=axis, keep_supplied=True)
    self.cov_op_ = cov_op
    self.mean_ = mean  # published last: the fit-once check reads ``mean_``
    return self

transform(gt)

Score gt against the fitted (or supplied) background.

Raises:

Type Description
ValueError

If no background is available yet or target is unset.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Score ``gt`` against the fitted (or supplied) background.

    Raises:
        ValueError: If no background is available yet or ``target``
            is unset.
    """
    mean, cov_op = self._background()
    return self._score(gt, mean, cov_op)

MatchedFilterPixel

Bases: Operator

Single-pixel matched-filter score.

Scalar counterpart of :class:MatchedFilter: scores one pixel spectrum (any 1-D array-like) against fixed background statistics and returns a float.

Parameters:

Name Type Description Default
mean ndarray

Background mean spectrum (c,).

required
cov_op NumpyLinearOperator | ndarray

Background covariance as a NumpyLinearOperator or raw (c, c) matrix.

required
target ndarray

Target signature (c,).

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class MatchedFilterPixel(Operator):
    """Single-pixel matched-filter score.

    Scalar counterpart of :class:`MatchedFilter`: scores one pixel
    spectrum (any 1-D array-like) against fixed background statistics
    and returns a ``float``.

    Args:
        mean: Background mean spectrum ``(c,)``.
        cov_op: Background covariance as a `NumpyLinearOperator` or raw
            ``(c, c)`` matrix.
        target: Target signature ``(c,)``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # mean and covariance given
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        mean: np.ndarray,
        cov_op: NumpyLinearOperator | np.ndarray,
        target: np.ndarray,
    ) -> None:
        self.mean = mean
        self.cov_op = cov_op
        self.target = target

    def _apply(self, pixel: np.ndarray) -> float:
        return apply_pixel(
            pixel, mean=self.mean, cov_op=self.cov_op, target=self.target
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": np.asarray(self.mean).tolist(),
            "cov_op": _cov_config(self.cov_op),
            "target": np.asarray(self.target).tolist(),
        }

MatchedFilterSNR

Bases: Operator

Theoretical detection SNR amplitude * sqrt(t^T Sigma^-1 t).

Graph source: computed from its configuration alone. An optional input is accepted and ignored, so it can close a Sequential; it returns the scalar matched-filter output SNR for the configured amplitude, background covariance, and target.

Parameters:

Name Type Description Default
amplitude float

Target amplitude.

required
cov_op NumpyLinearOperator | ndarray

Background covariance as a NumpyLinearOperator or raw (c, c) matrix.

required
target ndarray

Target signature (c,).

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class MatchedFilterSNR(Operator):
    """Theoretical detection SNR ``amplitude * sqrt(t^T Sigma^-1 t)``.

    Graph source: computed from its configuration alone. An optional
    input is accepted and ignored, so it can close a ``Sequential``;
    it returns the scalar
    matched-filter output SNR for the configured amplitude, background
    covariance, and target.

    Args:
        amplitude: Target amplitude.
        cov_op: Background covariance as a `NumpyLinearOperator` or raw
            ``(c, c)`` matrix.
        target: Target signature ``(c,)``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    coupling: ClassVar[Coupling] = Coupling(kind="conversion")

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        amplitude: float,
        cov_op: NumpyLinearOperator | np.ndarray,
        target: np.ndarray,
    ) -> None:
        self.amplitude = amplitude
        self.cov_op = cov_op
        self.target = target

    def _apply(self, _input: Any | None = None) -> float:
        reject_geotensor(_input, type(self).__name__)
        return matched_filter_snr(
            amplitude=self.amplitude, cov_op=self.cov_op, target=self.target
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "amplitude": self.amplitude,
            "cov_op": _cov_config(self.cov_op),
            "target": np.asarray(self.target).tolist(),
        }

NonlinearTargetFromObs

Bases: Operator

Finite-amplitude target from a callable observation model.

Like :class:LinearTargetFromObs but with a caller-chosen finite perturbation amplitude and no division by it: the returned (c,) signature is the raw response difference, which retains the observation model's nonlinearity at that amplitude. Accepts a GeoArray or plain np.ndarray cube and returns a plain vector (not a carrier).

Parameters:

Name Type Description Default
obs_model Any

Callable mapping a state cube to a spectral response. Must be callable.

required
vmr_background ndarray | None

Optional explicit background state; the incoming cube is used when None.

None
amplitude float

Finite perturbation amplitude. Default 1.0.

1.0
pattern str | ndarray

Perturbation pattern — "uniform", "impulse", or an explicit array broadcastable to the background state.

'uniform'
pixel tuple[int, int] | None

Spatial index of the impulse for pattern="impulse"; the first flat pixel when None.

None
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class NonlinearTargetFromObs(Operator):
    """Finite-amplitude target from a callable observation model.

    Like :class:`LinearTargetFromObs` but with a caller-chosen finite
    perturbation ``amplitude`` and no division by it: the returned
    ``(c,)`` signature is the raw response difference, which retains the
    observation model's nonlinearity at that amplitude. Accepts a
    ``GeoArray`` or plain ``np.ndarray`` cube and returns a plain
    vector (not a carrier).

    Args:
        obs_model: Callable mapping a state cube to a spectral response.
            Must be callable.
        vmr_background: Optional explicit background state; the incoming
            cube is used when ``None``.
        amplitude: Finite perturbation amplitude. Default ``1.0``.
        pattern: Perturbation pattern — ``"uniform"``, ``"impulse"``, or
            an explicit array broadcastable to the background state.
        pixel: Spatial index of the impulse for ``pattern="impulse"``;
            the first flat pixel when ``None``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a target spectrum
    coupling: ClassVar[Coupling] = Coupling(kind="conversion")

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(
        self,
        *,
        obs_model: Any,
        vmr_background: np.ndarray | None = None,
        amplitude: float = 1.0,
        pattern: str | np.ndarray = "uniform",
        pixel: tuple[int, int] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.obs_model = obs_model
        self.vmr_background = vmr_background
        self.amplitude = amplitude
        self.pattern = pattern
        self.pixel = pixel
        self.dim = band_dim(dim, axis, "NonlinearTargetFromObs")

    def _apply(self, gt: GeoArray | np.ndarray) -> np.ndarray:
        return _target_from_obs(
            self.obs_model,
            gt,
            vmr_background=self.vmr_background,
            pattern=self.pattern,
            pixel=self.pixel,
            amplitude=self.amplitude,
            axis=dim_axis(gt, self.dim, name="NonlinearTargetFromObs"),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "vmr_background": None
            if self.vmr_background is None
            else np.asarray(self.vmr_background).tolist(),
            "amplitude": self.amplitude,
            "pattern": self.pattern
            if isinstance(self.pattern, str)
            else np.asarray(self.pattern).tolist(),
            "obs_model": callable_name(self.obs_model),
            "pixel": self.pixel,
            "dim": self.dim,
        }

NumpyLinearOperator dataclass

Dense NumPy linear operator with a small solve interface.

Wraps a square (covariance) matrix behind the minimal interface the matched-filter kernels need — shape and solve — so callers don't depend on how the operator is represented. The matrix is coerced to a float ndarray at construction.

Attributes:

Name Type Description
matrix Float[ndarray, 'c c']

Square (c, c) float matrix.

Raises:

Type Description
ValueError

If matrix is not a square 2-D array.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@dataclass(frozen=True)
class NumpyLinearOperator:
    """Dense NumPy linear operator with a small ``solve`` interface.

    Wraps a square (covariance) matrix behind the minimal interface the
    matched-filter kernels need — ``shape`` and ``solve`` — so callers
    don't depend on how the operator is represented. The matrix is
    coerced to a float ndarray at construction.

    Attributes:
        matrix: Square ``(c, c)`` float matrix.

    Raises:
        ValueError: If ``matrix`` is not a square 2-D array.
    """

    matrix: Float[np.ndarray, "c c"]

    def __post_init__(self) -> None:
        mat = np.asarray(self.matrix, dtype=float)
        if mat.ndim != 2 or mat.shape[0] != mat.shape[1]:
            raise ValueError("matrix must be a square 2-D array")
        object.__setattr__(self, "matrix", mat)

    @property
    def shape(self) -> tuple[int, int]:
        """Matrix shape ``(c, c)``."""
        return self.matrix.shape

    def solve(self, rhs: Float[np.ndarray, " c"]) -> Float[np.ndarray, " c"]:
        """Solve ``matrix @ x = rhs`` for ``x``.

        Args:
            rhs: Right-hand-side vector with one entry per band.

        Returns:
            The solution vector ``x``.

        Raises:
            numpy.linalg.LinAlgError: If the matrix is singular.
        """
        return np.linalg.solve(self.matrix, np.asarray(rhs, dtype=float))

shape property

Matrix shape (c, c).

solve(rhs)

Solve matrix @ x = rhs for x.

Parameters:

Name Type Description Default
rhs Float[ndarray, ' c']

Right-hand-side vector with one entry per band.

required

Returns:

Type Description
Float[ndarray, ' c']

The solution vector x.

Raises:

Type Description
LinAlgError

If the matrix is singular.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def solve(self, rhs: Float[np.ndarray, " c"]) -> Float[np.ndarray, " c"]:
    """Solve ``matrix @ x = rhs`` for ``x``.

    Args:
        rhs: Right-hand-side vector with one entry per band.

    Returns:
        The solution vector ``x``.

    Raises:
        numpy.linalg.LinAlgError: If the matrix is singular.
    """
    return np.linalg.solve(self.matrix, np.asarray(rhs, dtype=float))

StreamingBackground

Bases: Operator

Aggregate mean/covariance across an iterable of cubes.

Streams every cube through a WelfordAccumulator and returns a StreamingBackgroundResult (mean vector plus covariance operator, not a carrier). Cubes may be GeoArray or plain np.ndarray and can be mixed freely. Nodata pixels (non-finite or equal to each cube's fill value in any band) are not accumulated.

The cubes iterable is supplied at apply time (runtime dataflow) so the operator config remains hydra-/YAML-serialisable: cov_kind and axis fully describe the operator's init-time state.

Parameters:

Name Type Description Default
cov_kind Literal['empirical', 'shrunk']

"shrunk" (Ledoit-Wolf toward scaled identity, default — identical to estimate_cov_shrunk on the concatenated pixels, since the accumulator streams the fourth moment LW needs) or "empirical". A 1e-8 ridge is added to the diagonal in both cases.

'shrunk'
dim str

Name of the band dim (default "band"); its position is read from the carrier's dims.

'band'
axis int | None

Deprecated: the band axis position. -3 maps to dim="band"; removed in the next minor release.

None
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class StreamingBackground(Operator):
    """Aggregate mean/covariance across an iterable of cubes.

    Streams every cube through a `WelfordAccumulator` and returns a
    `StreamingBackgroundResult` (mean vector plus covariance operator,
    not a carrier). Cubes may be ``GeoArray`` or plain ``np.ndarray``
    and can be mixed freely. Nodata pixels (non-finite or equal to each
    cube's fill value in any band) are not accumulated.

    The cubes iterable is supplied at apply time (runtime dataflow) so the
    operator config remains hydra-/YAML-serialisable: ``cov_kind`` and
    ``axis`` fully describe the operator's init-time state.

    Args:
        cov_kind: ``"shrunk"`` (Ledoit-Wolf toward scaled identity,
            default — identical to `estimate_cov_shrunk` on the
            concatenated pixels, since the accumulator streams the
            fourth moment LW needs) or ``"empirical"``. A ``1e-8`` ridge
            is added to the diagonal in both cases.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.
    """

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

    def __init__(
        self,
        *,
        cov_kind: Literal["empirical", "shrunk"] = "shrunk",
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.cov_kind = cov_kind
        self.dim = band_dim(dim, axis, "StreamingBackground")

    def _apply(
        self, cubes: Iterable[GeoArray | np.ndarray]
    ) -> StreamingBackgroundResult:
        acc: WelfordAccumulator | None = None
        for cube in cubes:
            axis = dim_axis(cube, self.dim, name="StreamingBackground")
            samples, _ = cube_to_samples(
                _mask_invalid(cube, axis, type(self).__name__)[0],
                band_axis=axis,
                dtype=float,
            )
            if acc is None:
                acc = WelfordAccumulator.empty(samples.shape[1])
            acc.update(samples)
        if acc is None:
            raise ValueError("cubes must contain at least one cube")
        cov = acc.covariance()
        if self.cov_kind == "shrunk":
            # Exact Ledoit-Wolf: the accumulator's streamed m4 = Σ‖xₖ − x̄‖⁴
            # gives the fourth moment LW needs without holding the samples.
            cov = shrink_covariance(
                cov,
                method="ledoit_wolf",
                n_samples=acc.count,
                fourth_moment=acc.m4 / acc.count,
            )
        elif self.cov_kind != "empirical":
            raise ValueError(f"unknown cov_kind {self.cov_kind!r}")
        cov = cov + 1e-8 * np.eye(cov.shape[0], dtype=float)
        return StreamingBackgroundResult(mean=acc.mean, cov_op=NumpyLinearOperator(cov))

StreamingBackgroundResult dataclass

Mean and covariance operator estimated from streamed cubes.

Attributes:

Name Type Description
mean Float[ndarray, ' c']

Background mean spectrum (c,) over all streamed pixels.

cov_op NumpyLinearOperator

Background (c, c) covariance operator.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@dataclass(frozen=True)
class StreamingBackgroundResult:
    """Mean and covariance operator estimated from streamed cubes.

    Attributes:
        mean: Background mean spectrum ``(c,)`` over all streamed pixels.
        cov_op: Background ``(c, c)`` covariance operator.
    """

    mean: Float[np.ndarray, " c"]
    cov_op: NumpyLinearOperator

ValidateMFInputs

Bases: Operator

Fail-fast pass-through validator for matched-filter inputs.

Raises ValueError early for an all-zero target, a singular covariance, or a non-positive filter gain; otherwise returns its runtime input unchanged (whatever its type), so it can be inserted anywhere in a pipeline as a guard.

Parameters:

Name Type Description Default
cov_op NumpyLinearOperator | ndarray

Background covariance as a NumpyLinearOperator or raw (c, c) matrix.

required
target ndarray

Target signature (c,).

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/operators.py
class ValidateMFInputs(Operator):
    """Fail-fast pass-through validator for matched-filter inputs.

    Raises ``ValueError`` early for an all-zero target, a singular
    covariance, or a non-positive filter gain; otherwise returns its
    runtime input unchanged (whatever its type), so it can be inserted
    anywhere in a pipeline as a guard.

    Args:
        cov_op: Background covariance as a `NumpyLinearOperator` or raw
            ``(c, c)`` matrix.
        target: Target signature ``(c,)``.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax")
    # checks and passes its input through
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(
        self,
        *,
        cov_op: NumpyLinearOperator | np.ndarray,
        target: np.ndarray,
    ) -> None:
        self.cov_op = cov_op
        self.target = target

    def _apply(self, value: Any = None) -> Any:
        reject_geotensor(value, type(self).__name__)
        validate_mf_inputs(cov_op=self.cov_op, target=self.target)
        return value

    def get_config(self) -> dict[str, Any]:
        return {
            "cov_op": _cov_config(self.cov_op),
            "target": np.asarray(self.target).tolist(),
        }

WelfordAccumulator dataclass

Streaming mean/covariance accumulator using Chan-Welford updates.

Accumulates first and second moments over batches of spectra without holding them all in memory, using the numerically stable pairwise (Chan et al.) merge of Welford statistics. Feed sample batches with update (or combine partial accumulators with merge) and read the result off mean / covariance.

Attributes:

Name Type Description
count int

Number of samples absorbed so far.

mean Float[ndarray, ' c']

Running mean spectrum (c,).

m2 Float[ndarray, 'c c']

Running centred sum-of-products matrix (c, c); m2 / (count - ddof) is the sample covariance.

m3 Float[ndarray, ' c']

Running centred third-moment vector Σₖ ‖xₖ − x̄‖² (xₖ − x̄) (c,); only needed to merge m4.

m4 float

Running centred fourth moment Σₖ ‖xₖ − x̄‖⁴; m4 / count is the Ledoit-Wolf fourth_moment of shrink_covariance.

Merging two accumulators A, B with pooled mean x̄ and offsets δ_X = x̄_X − x̄ (all sums centred, so Σ d = 0)::

M2 = Σ_X [M2_X + n_X δ_X δ_Xᵀ]
M3 = Σ_X [M3_X + tr(M2_X) δ_X + 2 M2_X δ_X + n_X ‖δ_X‖² δ_X]
M4 = Σ_X [M4_X + 4 δ_Xᵀ M3_X + 4 δ_Xᵀ M2_X δ_X
          + 2 ‖δ_X‖² tr(M2_X) + n_X ‖δ_X‖⁴]

which follows from expanding ‖d + δ‖² with d = x − x̄_X.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@dataclass
class WelfordAccumulator:
    """Streaming mean/covariance accumulator using Chan-Welford updates.

    Accumulates first and second moments over batches of spectra without
    holding them all in memory, using the numerically stable pairwise
    (Chan et al.) merge of Welford statistics. Feed sample batches with
    `update` (or combine partial accumulators with `merge`) and read the
    result off ``mean`` / `covariance`.

    Attributes:
        count: Number of samples absorbed so far.
        mean: Running mean spectrum ``(c,)``.
        m2: Running centred sum-of-products matrix ``(c, c)``;
            ``m2 / (count - ddof)`` is the sample covariance.
        m3: Running centred third-moment vector
            ``Σₖ ‖xₖ − x̄‖² (xₖ − x̄)`` ``(c,)``; only needed to merge ``m4``.
        m4: Running centred fourth moment ``Σₖ ‖xₖ − x̄‖⁴``;
            ``m4 / count`` is the Ledoit-Wolf ``fourth_moment`` of
            `shrink_covariance`.

    Merging two accumulators ``A``, ``B`` with pooled mean ``x̄`` and
    offsets ``δ_X = x̄_X − x̄`` (all sums centred, so ``Σ d = 0``)::

        M2 = Σ_X [M2_X + n_X δ_X δ_Xᵀ]
        M3 = Σ_X [M3_X + tr(M2_X) δ_X + 2 M2_X δ_X + n_X ‖δ_X‖² δ_X]
        M4 = Σ_X [M4_X + 4 δ_Xᵀ M3_X + 4 δ_Xᵀ M2_X δ_X
                  + 2 ‖δ_X‖² tr(M2_X) + n_X ‖δ_X‖⁴]

    which follows from expanding ``‖d + δ‖²`` with ``d = x − x̄_X``.
    """

    count: int
    mean: Float[np.ndarray, " c"]
    m2: Float[np.ndarray, "c c"]
    m3: Float[np.ndarray, " c"]
    m4: float

    @classmethod
    def empty(cls, n_features: int) -> WelfordAccumulator:
        """Create an empty accumulator for ``n_features`` spectral bands.

        Args:
            n_features: Number of bands ``c`` of the incoming samples.

        Returns:
            A zero-count accumulator ready for `update` / `merge`.
        """
        return cls(
            count=0,
            mean=np.zeros(n_features, dtype=float),
            m2=np.zeros((n_features, n_features), dtype=float),
            m3=np.zeros(n_features, dtype=float),
            m4=0.0,
        )

    def update(self, values: Float[np.ndarray, "n c"]) -> None:
        """Absorb a batch of samples into the running statistics.

        Args:
            values: Sample rows shaped ``(n, c)``; a single 1-D spectrum
                is treated as one row. Empty batches are a no-op.
        """
        x = _as_2d_samples(values)
        if x.size == 0:
            return
        other = WelfordAccumulator.from_values(x)
        self.merge(other)

    def merge(self, other: WelfordAccumulator) -> None:
        """Merge another accumulator into this one in place.

        Uses the pairwise Chan update, so merging accumulators built
        from disjoint batches is exact (equivalent to a single pass over
        the concatenated samples).

        Args:
            other: Accumulator over the same number of bands.
        """
        if other.count == 0:
            return
        if self.count == 0:
            self.count = other.count
            self.mean = other.mean.copy()
            self.m2 = other.m2.copy()
            self.m3 = other.m3.copy()
            self.m4 = other.m4
            return
        total = self.count + other.count
        mean = self.mean + (other.mean - self.mean) * (other.count / total)
        m2 = np.zeros_like(self.m2)
        m3 = np.zeros_like(self.m3)
        m4 = 0.0
        for part in (self, other):
            # δ = x̄_part − x̄ shifts the part's centred sums to the pooled mean.
            delta = part.mean - mean
            delta_sq = float(delta @ delta)
            m2_delta = part.m2 @ delta
            trace_m2 = float(np.trace(part.m2))
            m2 = m2 + part.m2 + part.count * einx.dot("c, d -> c d", delta, delta)
            m3 = (
                m3
                + part.m3
                + trace_m2 * delta
                + 2.0 * m2_delta
                + part.count * delta_sq * delta
            )
            m4 += (
                part.m4
                + 4.0 * float(part.m3 @ delta)
                + 4.0 * float(delta @ m2_delta)
                + 2.0 * delta_sq * trace_m2
                + part.count * delta_sq * delta_sq
            )
        self.mean = mean
        self.m2 = m2
        self.m3 = m3
        self.m4 = m4
        self.count = total

    @classmethod
    def from_values(cls, values: Float[np.ndarray, "n c"]) -> WelfordAccumulator:
        """Create an accumulator from a batch of sample rows.

        Args:
            values: Sample rows shaped ``(n, c)``; a single 1-D spectrum
                is treated as one row.

        Returns:
            An accumulator holding the batch's exact mean and centred
            sum-of-products. Rows with a non-finite value are skipped.
        """
        x = _finite_rows(_as_2d_samples(values))
        if x.shape[0] == 0:
            return cls.empty(x.shape[1])
        mean = np.mean(x, axis=0)
        centered = x - mean
        sq_norm = np.sum(centered * centered, axis=1)
        return cls(
            count=x.shape[0],
            mean=mean,
            m2=einx.dot("n c, n d -> c d", centered, centered),
            m3=sq_norm @ centered,
            m4=float(sq_norm @ sq_norm),
        )

    def covariance(
        self, *, ddof: int = 1, ridge: float = 0.0
    ) -> Float[np.ndarray, "c c"]:
        """Return the sample covariance matrix of the absorbed samples.

        Args:
            ddof: Delta degrees of freedom; the default ``1`` gives the
                unbiased estimator.
            ridge: Optional Tikhonov ridge added to the diagonal to keep
                the matrix invertible.

        Returns:
            The ``(c, c)`` covariance matrix.

        Raises:
            ValueError: If fewer than ``ddof + 1`` samples were absorbed.
        """
        if self.count <= ddof:
            raise ValueError("at least two samples are required for covariance")
        cov = self.m2 / (self.count - ddof)
        if ridge:
            cov = cov + float(ridge) * np.eye(cov.shape[0], dtype=float)
        return cov

covariance(*, ddof=1, ridge=0.0)

Return the sample covariance matrix of the absorbed samples.

Parameters:

Name Type Description Default
ddof int

Delta degrees of freedom; the default 1 gives the unbiased estimator.

1
ridge float

Optional Tikhonov ridge added to the diagonal to keep the matrix invertible.

0.0

Returns:

Type Description
Float[ndarray, 'c c']

The (c, c) covariance matrix.

Raises:

Type Description
ValueError

If fewer than ddof + 1 samples were absorbed.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def covariance(
    self, *, ddof: int = 1, ridge: float = 0.0
) -> Float[np.ndarray, "c c"]:
    """Return the sample covariance matrix of the absorbed samples.

    Args:
        ddof: Delta degrees of freedom; the default ``1`` gives the
            unbiased estimator.
        ridge: Optional Tikhonov ridge added to the diagonal to keep
            the matrix invertible.

    Returns:
        The ``(c, c)`` covariance matrix.

    Raises:
        ValueError: If fewer than ``ddof + 1`` samples were absorbed.
    """
    if self.count <= ddof:
        raise ValueError("at least two samples are required for covariance")
    cov = self.m2 / (self.count - ddof)
    if ridge:
        cov = cov + float(ridge) * np.eye(cov.shape[0], dtype=float)
    return cov

empty(n_features) classmethod

Create an empty accumulator for n_features spectral bands.

Parameters:

Name Type Description Default
n_features int

Number of bands c of the incoming samples.

required

Returns:

Type Description
WelfordAccumulator

A zero-count accumulator ready for update / merge.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@classmethod
def empty(cls, n_features: int) -> WelfordAccumulator:
    """Create an empty accumulator for ``n_features`` spectral bands.

    Args:
        n_features: Number of bands ``c`` of the incoming samples.

    Returns:
        A zero-count accumulator ready for `update` / `merge`.
    """
    return cls(
        count=0,
        mean=np.zeros(n_features, dtype=float),
        m2=np.zeros((n_features, n_features), dtype=float),
        m3=np.zeros(n_features, dtype=float),
        m4=0.0,
    )

from_values(values) classmethod

Create an accumulator from a batch of sample rows.

Parameters:

Name Type Description Default
values Float[ndarray, 'n c']

Sample rows shaped (n, c); a single 1-D spectrum is treated as one row.

required

Returns:

Type Description
WelfordAccumulator

An accumulator holding the batch's exact mean and centred

WelfordAccumulator

sum-of-products. Rows with a non-finite value are skipped.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
@classmethod
def from_values(cls, values: Float[np.ndarray, "n c"]) -> WelfordAccumulator:
    """Create an accumulator from a batch of sample rows.

    Args:
        values: Sample rows shaped ``(n, c)``; a single 1-D spectrum
            is treated as one row.

    Returns:
        An accumulator holding the batch's exact mean and centred
        sum-of-products. Rows with a non-finite value are skipped.
    """
    x = _finite_rows(_as_2d_samples(values))
    if x.shape[0] == 0:
        return cls.empty(x.shape[1])
    mean = np.mean(x, axis=0)
    centered = x - mean
    sq_norm = np.sum(centered * centered, axis=1)
    return cls(
        count=x.shape[0],
        mean=mean,
        m2=einx.dot("n c, n d -> c d", centered, centered),
        m3=sq_norm @ centered,
        m4=float(sq_norm @ sq_norm),
    )

merge(other)

Merge another accumulator into this one in place.

Uses the pairwise Chan update, so merging accumulators built from disjoint batches is exact (equivalent to a single pass over the concatenated samples).

Parameters:

Name Type Description Default
other WelfordAccumulator

Accumulator over the same number of bands.

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def merge(self, other: WelfordAccumulator) -> None:
    """Merge another accumulator into this one in place.

    Uses the pairwise Chan update, so merging accumulators built
    from disjoint batches is exact (equivalent to a single pass over
    the concatenated samples).

    Args:
        other: Accumulator over the same number of bands.
    """
    if other.count == 0:
        return
    if self.count == 0:
        self.count = other.count
        self.mean = other.mean.copy()
        self.m2 = other.m2.copy()
        self.m3 = other.m3.copy()
        self.m4 = other.m4
        return
    total = self.count + other.count
    mean = self.mean + (other.mean - self.mean) * (other.count / total)
    m2 = np.zeros_like(self.m2)
    m3 = np.zeros_like(self.m3)
    m4 = 0.0
    for part in (self, other):
        # δ = x̄_part − x̄ shifts the part's centred sums to the pooled mean.
        delta = part.mean - mean
        delta_sq = float(delta @ delta)
        m2_delta = part.m2 @ delta
        trace_m2 = float(np.trace(part.m2))
        m2 = m2 + part.m2 + part.count * einx.dot("c, d -> c d", delta, delta)
        m3 = (
            m3
            + part.m3
            + trace_m2 * delta
            + 2.0 * m2_delta
            + part.count * delta_sq * delta
        )
        m4 += (
            part.m4
            + 4.0 * float(part.m3 @ delta)
            + 4.0 * float(delta @ m2_delta)
            + 2.0 * delta_sq * trace_m2
            + part.count * delta_sq * delta_sq
        )
    self.mean = mean
    self.m2 = m2
    self.m3 = m3
    self.m4 = m4
    self.count = total

update(values)

Absorb a batch of samples into the running statistics.

Parameters:

Name Type Description Default
values Float[ndarray, 'n c']

Sample rows shaped (n, c); a single 1-D spectrum is treated as one row. Empty batches are a no-op.

required
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def update(self, values: Float[np.ndarray, "n c"]) -> None:
    """Absorb a batch of samples into the running statistics.

    Args:
        values: Sample rows shaped ``(n, c)``; a single 1-D spectrum
            is treated as one row. Empty batches are a no-op.
    """
    x = _as_2d_samples(values)
    if x.size == 0:
        return
    other = WelfordAccumulator.from_values(x)
    self.merge(other)

apply_adaptive_mf(cube, *, background, target, ridge=0.0, axis=-3)

Apply a matched filter against a local diagonal-covariance background.

Scores every pixel against its own window statistics from adaptive_window_background: local mean μ(r) and diagonal covariance Λ(r) = diag(σ²(r) + ridge). With the same amplitude normalisation as apply_image (the Manolakis MF with Σ → Λ(r))::

α(r) = tᵀ Λ(r)⁻¹ (x(r) − μ(r)) / (tᵀ Λ(r)⁻¹ t)
     = Σ_c t_c (x_c − μ_c) / σ²_c  /  Σ_c t_c² / σ²_c

i.e. the per-pixel maximum-likelihood target amplitude under an independent-band Gaussian background. The window includes the pixel itself, so a strong target slightly biases its own μ and σ².

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w); must have the shape of background.mean / background.variance.

required
background AdaptiveBackground

Local statistics from adaptive_window_background on the same cube (or a compatible background cube).

required
target Float[ndarray, ' c']

Target signature (c,).

required
ridge float

Non-negative variance floor added to every σ² before inversion; use it when flat windows give zero variance.

0.0
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
Float[ndarray, 'h w']

Score map with the cube's spatial shape; NaN where the pixel,

Float[ndarray, 'h w']

its local mean, or its local variance is non-finite, or where a

Float[ndarray, 'h w']

band's σ² + ridge is not positive.

Raises:

Type Description
ValueError

If the background shapes differ from the cube's, the target length disagrees with the band count, ridge is negative, or the target is all-zero.

Examples:

>>> import numpy as np
>>> cube = np.random.default_rng(0).normal(size=(3, 8, 8))
>>> bg = adaptive_window_background(cube, window=3)
>>> apply_adaptive_mf(cube, background=bg, target=np.ones(3)).shape
(8, 8)
>>> apply_adaptive_mf(
...     cube, background=bg, target=np.array([1.0, 0.0, 0.0]), ridge=1e-6
... ).shape
(8, 8)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def apply_adaptive_mf(
    cube: Float[np.ndarray, "c h w"],
    *,
    background: AdaptiveBackground,
    target: Float[np.ndarray, " c"],
    ridge: float = 0.0,
    axis: int = -3,
) -> Float[np.ndarray, "h w"]:
    """Apply a matched filter against a local diagonal-covariance background.

    Scores every pixel against its own window statistics from
    `adaptive_window_background`: local mean ``μ(r)`` and diagonal
    covariance ``Λ(r) = diag(σ²(r) + ridge)``. With the same amplitude
    normalisation as `apply_image` (the Manolakis MF with ``Σ → Λ(r)``)::

        α(r) = tᵀ Λ(r)⁻¹ (x(r) − μ(r)) / (tᵀ Λ(r)⁻¹ t)
             = Σ_c t_c (x_c − μ_c) / σ²_c  /  Σ_c t_c² / σ²_c

    i.e. the per-pixel maximum-likelihood target amplitude under an
    independent-band Gaussian background. The window includes the pixel
    itself, so a strong target slightly biases its own ``μ`` and ``σ²``.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``; must have the
            shape of ``background.mean`` / ``background.variance``.
        background: Local statistics from `adaptive_window_background`
            on the same cube (or a compatible background cube).
        target: Target signature ``(c,)``.
        ridge: Non-negative variance floor added to every ``σ²`` before
            inversion; use it when flat windows give zero variance.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        Score map with the cube's spatial shape; ``NaN`` where the pixel,
        its local mean, or its local variance is non-finite, or where a
        band's ``σ² + ridge`` is not positive.

    Raises:
        ValueError: If the background shapes differ from the cube's, the
            target length disagrees with the band count, ``ridge`` is
            negative, or the target is all-zero.

    Examples:
        >>> import numpy as np
        >>> cube = np.random.default_rng(0).normal(size=(3, 8, 8))
        >>> bg = adaptive_window_background(cube, window=3)
        >>> apply_adaptive_mf(cube, background=bg, target=np.ones(3)).shape
        (8, 8)
        >>> apply_adaptive_mf(
        ...     cube, background=bg, target=np.array([1.0, 0.0, 0.0]), ridge=1e-6
        ... ).shape
        (8, 8)
    """
    if ridge < 0:
        raise ValueError("ridge must be non-negative")
    arr = np.asarray(cube, dtype=float)
    for name, stat in (("mean", background.mean), ("variance", background.variance)):
        if np.shape(stat) != arr.shape:
            raise ValueError(
                f"background {name} shape {np.shape(stat)} does not match "
                f"cube shape {arr.shape}"
            )
    x, spatial_shape = _cube_samples(arr, axis)
    mean, _ = _cube_samples(background.mean, axis)
    variance, _ = _cube_samples(background.variance, axis)
    target_vec = _as_vector(target, x.shape[1], "target")
    if not np.any(target_vec):
        raise ValueError("target must contain at least one non-zero value")
    variance = variance + float(ridge)
    with np.errstate(divide="ignore", invalid="ignore"):
        # Λ⁻¹ per pixel; bands with σ² ≤ 0 make the pixel unscoreable.
        inv_var = np.where(variance > 0, 1.0 / variance, np.nan)
        numer = ((x - mean) * inv_var) @ target_vec  # tᵀ Λ⁻¹ (x − μ)
        denom = inv_var @ (target_vec * target_vec)  # tᵀ Λ⁻¹ t
        scores = numer / denom
    scores = np.where(np.isfinite(scores), scores, np.nan)
    return scores.reshape(spatial_shape)

apply_image(cube, *, mean, cov_op, target, axis=-3)

Apply a matched filter over a hyperspectral image cube.

The covariance system is solved once for the target and reused for every pixel, so the per-pixel work is a single dot product. See apply_pixel for the scalar kernel and its formula.

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w); any number of non-band dimensions is supported.

required
mean Float[ndarray, ' c']

Background mean spectrum (c,).

required
cov_op NumpyLinearOperator | Float[ndarray, 'c c']

Background covariance as a NumpyLinearOperator or a raw (c, c) matrix.

required
target Float[ndarray, ' c']

Target signature (c,).

required
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
Float[ndarray, 'h w']

Matched-filter score map with the cube's spatial shape (e.g.

Float[ndarray, 'h w']

(h, w) for a (c, h, w) cube); NaN at pixels with a

Float[ndarray, 'h w']

non-finite band.

Raises:

Type Description
ValueError

If vector lengths disagree with the band count, or the target/covariance pair produces a non-positive filter denominator.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def apply_image(
    cube: Float[np.ndarray, "c h w"],
    *,
    mean: Float[np.ndarray, " c"],
    cov_op: NumpyLinearOperator | Float[np.ndarray, "c c"],
    target: Float[np.ndarray, " c"],
    axis: int = -3,
) -> Float[np.ndarray, "h w"]:
    """Apply a matched filter over a hyperspectral image cube.

    The covariance system is solved once for the target and reused for
    every pixel, so the per-pixel work is a single dot product. See
    `apply_pixel` for the scalar kernel and its formula.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``; any number of
            non-band dimensions is supported.
        mean: Background mean spectrum ``(c,)``.
        cov_op: Background covariance as a `NumpyLinearOperator` or a
            raw ``(c, c)`` matrix.
        target: Target signature ``(c,)``.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        Matched-filter score map with the cube's spatial shape (e.g.
        ``(h, w)`` for a ``(c, h, w)`` cube); ``NaN`` at pixels with a
        non-finite band.

    Raises:
        ValueError: If vector lengths disagree with the band count, or
            the target/covariance pair produces a non-positive filter
            denominator.
    """
    x, spatial_shape = _cube_samples(cube, axis)
    mean_vec = _as_vector(mean, x.shape[1], "mean")
    target_vec = _as_vector(target, x.shape[1], "target")
    solved_target = solve(cov_op, target_vec)
    denom = float(target_vec @ solved_target)
    if not np.isfinite(denom) or denom <= 0:
        raise ValueError("target/covariance produce a non-positive MF denominator")
    scores = einx.dot("n c, c -> n", x - mean_vec, solved_target) / denom
    return scores.reshape(spatial_shape)

apply_pixel(pixel, *, mean, cov_op, target)

Score one pixel spectrum with the matched filter.

Computes the maximum-likelihood target-amplitude estimate

.. math::

\alpha \;=\; \frac{(x - \mu)^\top \Sigma^{-1} t}
                     {t^\top \Sigma^{-1} t}

for a single spectrum x. See apply_image for whole cubes.

Parameters:

Name Type Description Default
pixel Float[ndarray, ' c']

Pixel spectrum (c,).

required
mean Float[ndarray, ' c']

Background mean spectrum (c,).

required
cov_op NumpyLinearOperator | Float[ndarray, 'c c']

Background covariance as a NumpyLinearOperator or a raw (c, c) matrix.

required
target Float[ndarray, ' c']

Target signature (c,).

required

Returns:

Type Description
float

The scalar matched-filter score (estimated target amplitude).

Raises:

Type Description
ValueError

If vector lengths disagree with the band count, or the target/covariance pair produces a non-positive filter denominator.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def apply_pixel(
    pixel: Float[np.ndarray, " c"],
    *,
    mean: Float[np.ndarray, " c"],
    cov_op: NumpyLinearOperator | Float[np.ndarray, "c c"],
    target: Float[np.ndarray, " c"],
) -> float:
    """Score one pixel spectrum with the matched filter.

    Computes the maximum-likelihood target-amplitude estimate

    .. math::

        \\alpha \\;=\\; \\frac{(x - \\mu)^\\top \\Sigma^{-1} t}
                             {t^\\top \\Sigma^{-1} t}

    for a single spectrum ``x``. See `apply_image` for whole cubes.

    Args:
        pixel: Pixel spectrum ``(c,)``.
        mean: Background mean spectrum ``(c,)``.
        cov_op: Background covariance as a `NumpyLinearOperator` or a
            raw ``(c, c)`` matrix.
        target: Target signature ``(c,)``.

    Returns:
        The scalar matched-filter score (estimated target amplitude).

    Raises:
        ValueError: If vector lengths disagree with the band count, or
            the target/covariance pair produces a non-positive filter
            denominator.
    """
    mean_vec = _as_vector(mean, np.asarray(pixel).shape[0], "mean")
    target_vec = _as_vector(target, mean_vec.shape[0], "target")
    solved_target = solve(cov_op, target_vec)
    denom = float(target_vec @ solved_target)
    if not np.isfinite(denom) or denom <= 0:
        raise ValueError("target/covariance produce a non-positive MF denominator")
    centered = np.asarray(pixel, dtype=float) - mean_vec
    return float((centered @ solved_target) / denom)

detection_threshold(*, false_alarm_rate, cov_op, target)

Return the score threshold for a Gaussian false-alarm rate.

Under the no-target null hypothesis the matched-filter score is zero-mean Gaussian with standard deviation :math:1 / \sqrt{t^\top \Sigma^{-1} t}, so thresholding scores at :math:\Phi^{-1}(1 - \text{FAR}) / \sqrt{t^\top \Sigma^{-1} t} yields the requested false-alarm probability.

Parameters:

Name Type Description Default
false_alarm_rate float

Desired false-alarm probability, strictly between 0 and 1.

required
cov_op NumpyLinearOperator | Float[ndarray, 'c c']

Background covariance as a NumpyLinearOperator or a raw (c, c) matrix.

required
target Float[ndarray, ' c']

Target signature (c,).

required

Returns:

Type Description
float

The scalar score threshold.

Raises:

Type Description
ValueError

If false_alarm_rate is outside (0, 1) or the target/covariance pair produces a non-positive filter gain.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def detection_threshold(
    *,
    false_alarm_rate: float,
    cov_op: NumpyLinearOperator | Float[np.ndarray, "c c"],
    target: Float[np.ndarray, " c"],
) -> float:
    """Return the score threshold for a Gaussian false-alarm rate.

    Under the no-target null hypothesis the matched-filter score is
    zero-mean Gaussian with standard deviation
    :math:`1 / \\sqrt{t^\\top \\Sigma^{-1} t}`, so thresholding scores at
    :math:`\\Phi^{-1}(1 - \\text{FAR}) / \\sqrt{t^\\top \\Sigma^{-1} t}`
    yields the requested false-alarm probability.

    Args:
        false_alarm_rate: Desired false-alarm probability, strictly
            between 0 and 1.
        cov_op: Background covariance as a `NumpyLinearOperator` or a
            raw ``(c, c)`` matrix.
        target: Target signature ``(c,)``.

    Returns:
        The scalar score threshold.

    Raises:
        ValueError: If ``false_alarm_rate`` is outside ``(0, 1)`` or the
            target/covariance pair produces a non-positive filter gain.
    """
    if not 0.0 < false_alarm_rate < 1.0:
        raise ValueError("false_alarm_rate must be between 0 and 1")
    gain = matched_filter_snr(amplitude=1.0, cov_op=cov_op, target=target)
    return float(stats.norm.ppf(1.0 - false_alarm_rate) / gain)

estimate_cov_empirical(cube, *, mean=None, ridge=0.0, axis=-3)

Estimate an empirical covariance operator from a cube.

Computes the standard ddof=1 sample covariance of the vectorised pixel spectra, optionally centred on a caller-supplied (e.g. robust) mean and regularised with a diagonal ridge.

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w).

required
mean Float[ndarray, ' c'] | None

Optional precomputed mean spectrum (c,) to centre on; when None the arithmetic sample mean is used.

None
ridge float

Optional Tikhonov ridge added to the diagonal to keep the matrix invertible for near-degenerate backgrounds.

0.0
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
NumpyLinearOperator

NumpyLinearOperator wrapping the (c, c) sample covariance

NumpyLinearOperator

of the valid pixels (pixels with any non-finite band are

NumpyLinearOperator

ignored).

Raises:

Type Description
ValueError

If mean length does not match the band count.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def estimate_cov_empirical(
    cube: Float[np.ndarray, "c h w"],
    *,
    mean: Float[np.ndarray, " c"] | None = None,
    ridge: float = 0.0,
    axis: int = -3,
) -> NumpyLinearOperator:
    """Estimate an empirical covariance operator from a cube.

    Computes the standard ``ddof=1`` sample covariance of the vectorised
    pixel spectra, optionally centred on a caller-supplied (e.g. robust)
    mean and regularised with a diagonal ridge.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``.
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            when ``None`` the arithmetic sample mean is used.
        ridge: Optional Tikhonov ridge added to the diagonal to keep the
            matrix invertible for near-degenerate backgrounds.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        `NumpyLinearOperator` wrapping the ``(c, c)`` sample covariance
        of the valid pixels (pixels with any non-finite band are
        ignored).

    Raises:
        ValueError: If ``mean`` length does not match the band count.
    """
    x = _finite_rows(_cube_samples(cube, axis)[0])
    mu = np.mean(x, axis=0) if mean is None else _as_vector(mean, x.shape[1], "mean")
    centered = x - mu
    denom = max(x.shape[0] - 1, 1)
    cov = einx.dot("n c, n d -> c d", centered, centered) / denom
    if ridge:
        cov = cov + float(ridge) * np.eye(cov.shape[0], dtype=float)
    return NumpyLinearOperator(cov)

estimate_cov_lowrank(cube, *, mean=None, rank=10, tikhonov=0.001, seed=0, n_oversamples=10, axis=-3)

Estimate a low-rank-plus-Tikhonov dense covariance operator.

Approximates the empirical covariance by its top-rank eigenpairs — found with a randomized range finder (Halko et al. 2011) followed by an SVD of the projected matrix — and adds a Tikhonov diagonal, so the result is the dense, well-conditioned matrix U_k S_k U_k^T + tikhonov * I. Useful when the band count is large and the background is dominated by a few spectral modes.

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w).

required
mean Float[ndarray, ' c'] | None

Optional precomputed mean spectrum (c,) to centre on; when None the arithmetic sample mean is used.

None
rank int

Number of leading eigenpairs kept. Must be positive; values above the band count are truncated to it.

10
tikhonov float

Diagonal regulariser added after the low-rank reconstruction; keeps the operator invertible even though the low-rank part is singular for rank < c.

0.001
seed int | None

Seed for the randomized range finder. The default 0 makes the estimate deterministic; None draws fresh OS entropy.

0
n_oversamples int

Extra random probe vectors beyond rank used by the range finder; improves subspace capture at negligible cost. Must be non-negative.

10
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
NumpyLinearOperator

NumpyLinearOperator wrapping the regularised (c, c)

NumpyLinearOperator

low-rank covariance.

Raises:

Type Description
ValueError

If rank is not positive, n_oversamples is negative, or mean length does not match the band count.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def estimate_cov_lowrank(
    cube: Float[np.ndarray, "c h w"],
    *,
    mean: Float[np.ndarray, " c"] | None = None,
    rank: int = 10,
    tikhonov: float = 1e-3,
    seed: int | None = 0,
    n_oversamples: int = 10,
    axis: int = -3,
) -> NumpyLinearOperator:
    """Estimate a low-rank-plus-Tikhonov dense covariance operator.

    Approximates the empirical covariance by its top-``rank`` eigenpairs
    — found with a randomized range finder (Halko et al. 2011) followed
    by an SVD of the projected matrix — and adds a Tikhonov diagonal, so
    the result is the dense, well-conditioned matrix
    ``U_k S_k U_k^T + tikhonov * I``. Useful when the band count is
    large and the background is dominated by a few spectral modes.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``.
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            when ``None`` the arithmetic sample mean is used.
        rank: Number of leading eigenpairs kept. Must be positive;
            values above the band count are truncated to it.
        tikhonov: Diagonal regulariser added after the low-rank
            reconstruction; keeps the operator invertible even though
            the low-rank part is singular for ``rank < c``.
        seed: Seed for the randomized range finder. The default
            ``0`` makes the estimate deterministic; ``None`` draws fresh
            OS entropy.
        n_oversamples: Extra random probe vectors beyond ``rank`` used
            by the range finder; improves subspace capture at negligible
            cost. Must be non-negative.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        `NumpyLinearOperator` wrapping the regularised ``(c, c)``
        low-rank covariance.

    Raises:
        ValueError: If ``rank`` is not positive, ``n_oversamples`` is
            negative, or ``mean`` length does not match the band count.
    """
    empirical = estimate_cov_empirical(cube, mean=mean, axis=axis).matrix
    if rank < 1:
        raise ValueError("rank must be positive")
    if n_oversamples < 0:
        raise ValueError("n_oversamples must be non-negative")
    n_features = empirical.shape[0]
    sample_rank = min(rank + n_oversamples, n_features)
    rng = np.random.default_rng(seed)
    omega = rng.normal(size=(n_features, sample_rank))
    basis, _ = np.linalg.qr(
        einx.dot("c d, d k -> c k", empirical, omega), mode="reduced"
    )
    u_hat, s, _ = np.linalg.svd(
        einx.dot("c k, c d -> k d", basis, empirical), full_matrices=False
    )
    u = einx.dot("c k, k d -> c d", basis, u_hat)
    k = min(rank, s.shape[0])
    cov = einx.dot("c k, d k -> c d", u[:, :k] * s[:k], u[:, :k])
    cov = cov + float(tikhonov) * np.eye(cov.shape[0], dtype=float)
    return NumpyLinearOperator(cov)

estimate_cov_shrunk(cube, *, mean=None, method='ledoit_wolf', axis=-3)

Estimate a scaled-identity-target shrinkage covariance operator.

Forms the ddof=1 empirical covariance S of the vectorised spectra and blends it toward the scaled-identity target F = tr(S)/c · I with a data-driven intensity s (see shrink_covariance) — the standard fix when the pixel count is small relative to the band count. The Ledoit-Wolf intensity needs the sample fourth moment, which is computed here from the sample matrix, so the intensity equals sklearn.covariance.ledoit_wolf / sklearn.covariance.oas on the same centred samples and the returned matrix is exactly n/(n − 1) times sklearn's (sklearn uses the 1/n scatter; this package uses 1/(n − 1)). The matched-filter score is invariant to that scale.

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w).

required
mean Float[ndarray, ' c'] | None

Optional precomputed mean spectrum (c,) to centre on; when None the arithmetic sample mean is used. A supplied mean corresponds to sklearn's assume_centered=True on x − mean.

None
method CovShrinkageMethod

Shrinkage-intensity estimator, "ledoit_wolf" or "oas".

'ledoit_wolf'
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
NumpyLinearOperator

NumpyLinearOperator wrapping the shrunk (c, c) covariance

NumpyLinearOperator

of the valid pixels (pixels with any non-finite band are

NumpyLinearOperator

ignored).

Raises:

Type Description
ValueError

If mean length does not match the band count or method is unknown.

Examples:

>>> import numpy as np
>>> cube = np.random.default_rng(0).normal(size=(4, 5, 5))
>>> estimate_cov_shrunk(cube).shape
(4, 4)
>>> estimate_cov_shrunk(cube, method="oas").shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def estimate_cov_shrunk(
    cube: Float[np.ndarray, "c h w"],
    *,
    mean: Float[np.ndarray, " c"] | None = None,
    method: CovShrinkageMethod = "ledoit_wolf",
    axis: int = -3,
) -> NumpyLinearOperator:
    """Estimate a scaled-identity-target shrinkage covariance operator.

    Forms the ``ddof=1`` empirical covariance ``S`` of the vectorised
    spectra and blends it toward the scaled-identity target
    ``F = tr(S)/c · I`` with a data-driven intensity ``s`` (see
    `shrink_covariance`) — the standard fix when the pixel count is small
    relative to the band count. The Ledoit-Wolf intensity needs the
    sample fourth moment, which is computed here from the sample matrix,
    so the intensity equals ``sklearn.covariance.ledoit_wolf`` /
    ``sklearn.covariance.oas`` on the same centred samples and the
    returned matrix is exactly ``n/(n − 1)`` times sklearn's (sklearn
    uses the ``1/n`` scatter; this package uses ``1/(n − 1)``). The
    matched-filter score is invariant to that scale.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``.
        mean: Optional precomputed mean spectrum ``(c,)`` to centre on;
            when ``None`` the arithmetic sample mean is used. A supplied
            mean corresponds to sklearn's ``assume_centered=True`` on
            ``x − mean``.
        method: Shrinkage-intensity estimator, ``"ledoit_wolf"`` or
            ``"oas"``.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        `NumpyLinearOperator` wrapping the shrunk ``(c, c)`` covariance
        of the valid pixels (pixels with any non-finite band are
        ignored).

    Raises:
        ValueError: If ``mean`` length does not match the band count or
            ``method`` is unknown.

    Examples:
        >>> import numpy as np
        >>> cube = np.random.default_rng(0).normal(size=(4, 5, 5))
        >>> estimate_cov_shrunk(cube).shape
        (4, 4)
        >>> estimate_cov_shrunk(cube, method="oas").shape
        (4, 4)
    """
    x = _finite_rows(_cube_samples(cube, axis)[0])
    mu = np.mean(x, axis=0) if mean is None else _as_vector(mean, x.shape[1], "mean")
    return NumpyLinearOperator(_shrunk_cov_from_samples(x, mu, method=method))

estimate_mean(cube, *, method='mean', trim_proportion=0.1, huber_c=1.345, axis=-3)

Estimate a per-band background mean spectrum from a cube.

Robustness matters for matched filtering: sparse bright targets (plumes, panels) bias the plain mean toward the target itself, so the median, trimmed, or huber estimators usually give a cleaner background.

Parameters:

Name Type Description Default
cube Float[ndarray, 'c h w']

Spectral cube, canonically (c, h, w); any number of non-band dimensions is supported.

required
method MeanMethod

Mean estimator — "mean" (arithmetic), "median", "trimmed" (symmetric trimmed mean), or "huber" (iteratively reweighted Huber M-estimator).

'mean'
trim_proportion float

Fraction cut from each tail for method="trimmed"; must satisfy 0 <= p < 0.5.

0.1
huber_c float

Huber tuning constant in robust z-score units for method="huber"; smaller values down-weight outliers more aggressively. Must be positive.

1.345
axis int

Position of the spectral axis. Default -3.

-3

Returns:

Type Description
Float[ndarray, ' c']

Mean spectrum with one entry per band, fitted on valid pixels

Float[ndarray, ' c']

only (pixels with any non-finite band are ignored).

Raises:

Type Description
ValueError

If method is unknown, trim_proportion is out of range, or huber_c is not positive.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def estimate_mean(
    cube: Float[np.ndarray, "c h w"],
    *,
    method: MeanMethod = "mean",
    trim_proportion: float = 0.1,
    huber_c: float = 1.345,
    axis: int = -3,
) -> Float[np.ndarray, " c"]:
    """Estimate a per-band background mean spectrum from a cube.

    Robustness matters for matched filtering: sparse bright targets
    (plumes, panels) bias the plain mean toward the target itself, so
    the ``median``, ``trimmed``, or ``huber`` estimators usually give a
    cleaner background.

    Args:
        cube: Spectral cube, canonically ``(c, h, w)``; any number of
            non-band dimensions is supported.
        method: Mean estimator — ``"mean"`` (arithmetic), ``"median"``,
            ``"trimmed"`` (symmetric trimmed mean), or ``"huber"``
            (iteratively reweighted Huber M-estimator).
        trim_proportion: Fraction cut from *each* tail for
            ``method="trimmed"``; must satisfy ``0 <= p < 0.5``.
        huber_c: Huber tuning constant in robust z-score units for
            ``method="huber"``; smaller values down-weight outliers more
            aggressively. Must be positive.
        axis: Position of the spectral axis. Default ``-3``.

    Returns:
        Mean spectrum with one entry per band, fitted on valid pixels
        only (pixels with any non-finite band are ignored).

    Raises:
        ValueError: If ``method`` is unknown, ``trim_proportion`` is out
            of range, or ``huber_c`` is not positive.
    """
    x = _finite_rows(_cube_samples(cube, axis)[0])
    if method == "mean":
        return np.mean(x, axis=0)
    if method == "median":
        return np.median(x, axis=0)
    if method == "trimmed":
        if not 0 <= trim_proportion < 0.5:
            raise ValueError("trim_proportion must satisfy 0 <= p < 0.5")
        return stats.trim_mean(x, proportiontocut=trim_proportion, axis=0)
    if method == "huber":
        return _huber_mean(x, c=huber_c)
    raise ValueError(f"unknown mean method {method!r}")

matched_filter_snr(*, amplitude, cov_op, target)

Return the theoretical matched-filter detection SNR.

For a target of amplitude a in Gaussian background noise with covariance :math:\Sigma, the matched-filter output SNR is :math:a \sqrt{t^\top \Sigma^{-1} t}.

Parameters:

Name Type Description Default
amplitude float

Target amplitude a.

required
cov_op NumpyLinearOperator | Float[ndarray, 'c c']

Background covariance as a NumpyLinearOperator or a raw (c, c) matrix.

required
target Float[ndarray, ' c']

Target signature (c,).

required

Returns:

Type Description
float

The scalar SNR.

Raises:

Type Description
ValueError

If the target/covariance pair produces a non-positive filter gain.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def matched_filter_snr(
    *,
    amplitude: float,
    cov_op: NumpyLinearOperator | Float[np.ndarray, "c c"],
    target: Float[np.ndarray, " c"],
) -> float:
    """Return the theoretical matched-filter detection SNR.

    For a target of amplitude ``a`` in Gaussian background noise with
    covariance :math:`\\Sigma`, the matched-filter output SNR is
    :math:`a \\sqrt{t^\\top \\Sigma^{-1} t}`.

    Args:
        amplitude: Target amplitude ``a``.
        cov_op: Background covariance as a `NumpyLinearOperator` or a
            raw ``(c, c)`` matrix.
        target: Target signature ``(c,)``.

    Returns:
        The scalar SNR.

    Raises:
        ValueError: If the target/covariance pair produces a
            non-positive filter gain.
    """
    t = np.asarray(target, dtype=float).reshape(-1)
    gain = float(t @ solve(cov_op, t))
    if not np.isfinite(gain) or gain <= 0:
        raise ValueError("target/covariance produce a non-positive MF gain")
    return float(amplitude) * float(np.sqrt(gain))

shrink_covariance(empirical, *, method, n_samples, fourth_moment=None)

Shrink an empirical covariance toward a scaled-identity target.

Returns the convex combination (1 − s)·S + s·F with target F = μ·I, μ = tr(S)/p, where S is the ddof=1 sample covariance of n samples in p bands and the intensity s ∈ [0, 1] is estimated from the data. Both estimators reproduce scikit-learn exactly: with the 1/n scatter Sₙ = S·(n − 1)/n (sklearn's empirical_covariance), s is sklearn's shrinkage and the result is n/(n − 1) times sklearn's shrunk matrix (the intensity is scale-free, the target scales with S).

  • "ledoit_wolf" (Ledoit & Wolf 2004, sklearn's ledoit_wolf_shrinkage), with dₖ = xₖ − x̄ the centred samples and m₄ = (1/n) Σₖ ‖dₖ‖⁴::

    δ² = ‖Sₙ − μₙ I‖²_F (distance to target) β̄² = (1/n²) Σₖ ‖dₖdₖᵀ − Sₙ‖²_F = (m₄ − ‖Sₙ‖²_F) / n s = min(β̄², δ²) / δ² (0 when δ² = 0)

β̄² is the sample variance of the entries of Sₙ; it needs the fourth moment m₄, which cannot be recovered from S alone.

  • "oas" (Chen et al. 2010, as implemented by sklearn.covariance.oas)::

    s = min(1, (tr(S²) + tr(S)²) / ((n + 1)·(tr(S²) − tr(S)²/p)))

sklearn omits the 2/p terms of Chen et al. Eq. 23, ((1 − 2/p)·tr(S²) + tr(S)²) / ((n + 1 − 2/p)·(…)); they vanish for large p and are omitted here too so the two agree exactly.

Parameters:

Name Type Description Default
empirical Float[ndarray, 'c c']

ddof=1 empirical covariance matrix (c, c) (Σ dₖdₖᵀ / max(n − 1, 1)).

required
method CovShrinkageMethod

Shrinkage-intensity estimator.

required
n_samples int

Number of samples used to form empirical; more samples mean less shrinkage.

required
fourth_moment float | None

m₄ = (1/n) Σₖ ‖xₖ − x̄‖⁴ over the same centred samples. Required for method="ledoit_wolf" (ignored by "oas"); WelfordAccumulator tracks it as m4 / count. estimate_cov_shrunk computes it for you from a cube.

None

Returns:

Type Description
Float[ndarray, 'c c']

The shrunk (c, c) covariance matrix.

Raises:

Type Description
ValueError

If method is unknown or fourth_moment is missing for "ledoit_wolf".

Examples:

>>> import numpy as np
>>> x = np.random.default_rng(0).normal(size=(30, 4))
>>> d = x - x.mean(axis=0)
>>> s = d.T @ d / 29
>>> m4 = float(np.mean(np.sum(d * d, axis=1) ** 2))
>>> shrink_covariance(s, method="ledoit_wolf", n_samples=30,
...                   fourth_moment=m4).shape
(4, 4)
>>> shrink_covariance(s, method="oas", n_samples=30).shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def shrink_covariance(
    empirical: Float[np.ndarray, "c c"],
    *,
    method: CovShrinkageMethod,
    n_samples: int,
    fourth_moment: float | None = None,
) -> Float[np.ndarray, "c c"]:
    """Shrink an empirical covariance toward a scaled-identity target.

    Returns the convex combination ``(1 − s)·S + s·F`` with target
    ``F = μ·I``, ``μ = tr(S)/p``, where ``S`` is the ``ddof=1`` sample
    covariance of ``n`` samples in ``p`` bands and the intensity
    ``s ∈ [0, 1]`` is estimated from the data. Both estimators reproduce
    scikit-learn exactly: with the ``1/n`` scatter ``Sₙ = S·(n − 1)/n``
    (sklearn's ``empirical_covariance``), ``s`` is sklearn's shrinkage
    and the result is ``n/(n − 1)`` times sklearn's shrunk matrix (the
    intensity is scale-free, the target scales with ``S``).

    - ``"ledoit_wolf"`` (Ledoit & Wolf 2004, sklearn's
      ``ledoit_wolf_shrinkage``), with ``dₖ = xₖ − x̄`` the centred
      samples and ``m₄ = (1/n) Σₖ ‖dₖ‖⁴``::

          δ² = ‖Sₙ − μₙ I‖²_F                      (distance to target)
          β̄² = (1/n²) Σₖ ‖dₖdₖᵀ − Sₙ‖²_F = (m₄ − ‖Sₙ‖²_F) / n
          s  = min(β̄², δ²) / δ²                    (0 when δ² = 0)

      β̄² is the sample variance of the entries of ``Sₙ``; it needs the
      fourth moment ``m₄``, which cannot be recovered from ``S`` alone.

    - ``"oas"`` (Chen et al. 2010, as implemented by
      ``sklearn.covariance.oas``)::

          s = min(1, (tr(S²) + tr(S)²) / ((n + 1)·(tr(S²) − tr(S)²/p)))

      sklearn omits the ``2/p`` terms of Chen et al. Eq. 23,
      ``((1 − 2/p)·tr(S²) + tr(S)²) / ((n + 1 − 2/p)·(…))``; they vanish
      for large ``p`` and are omitted here too so the two agree exactly.

    Args:
        empirical: ``ddof=1`` empirical covariance matrix ``(c, c)``
            (``Σ dₖdₖᵀ / max(n − 1, 1)``).
        method: Shrinkage-intensity estimator.
        n_samples: Number of samples used to form ``empirical``; more
            samples mean less shrinkage.
        fourth_moment: ``m₄ = (1/n) Σₖ ‖xₖ − x̄‖⁴`` over the same centred
            samples. Required for ``method="ledoit_wolf"`` (ignored by
            ``"oas"``); `WelfordAccumulator` tracks it as ``m4 / count``.
            `estimate_cov_shrunk` computes it for you from a cube.

    Returns:
        The shrunk ``(c, c)`` covariance matrix.

    Raises:
        ValueError: If ``method`` is unknown or ``fourth_moment`` is
            missing for ``"ledoit_wolf"``.

    Examples:
        >>> import numpy as np
        >>> x = np.random.default_rng(0).normal(size=(30, 4))
        >>> d = x - x.mean(axis=0)
        >>> s = d.T @ d / 29
        >>> m4 = float(np.mean(np.sum(d * d, axis=1) ** 2))
        >>> shrink_covariance(s, method="ledoit_wolf", n_samples=30,
        ...                   fourth_moment=m4).shape
        (4, 4)
        >>> shrink_covariance(s, method="oas", n_samples=30).shape
        (4, 4)
    """
    cov = np.asarray(empirical, dtype=float)
    n_features = cov.shape[0]
    mu = float(np.trace(cov)) / n_features
    if method == "oas":
        # Scale-free ratio, so S (1/(n−1)) and Sₙ (1/n) give the same s.
        trace_sq = float(np.trace(cov)) ** 2
        fro_sq = float(np.sum(cov * cov))
        denom = (n_samples + 1) * (fro_sq - trace_sq / n_features)
        shrinkage = 1.0 if denom <= 0 else min(1.0, (fro_sq + trace_sq) / denom)
    elif method == "ledoit_wolf":
        if fourth_moment is None:
            raise ValueError(
                "ledoit_wolf shrinkage needs fourth_moment = mean(‖xₖ − x̄‖⁴); "
                "use estimate_cov_shrunk on the samples or WelfordAccumulator.m4"
            )
        n = max(int(n_samples), 1)
        # Sₙ = Σ dₖdₖᵀ / n — the scatter normalisation LW is defined on.
        scatter = cov * (max(n - 1, 1) / n)
        mu_n = float(np.trace(scatter)) / n_features
        diff = scatter - mu_n * np.eye(n_features, dtype=float)
        d_sq = float(np.sum(diff * diff))
        b_bar_sq = max(
            (float(fourth_moment) - float(np.sum(scatter * scatter))) / n, 0.0
        )
        b_sq = min(b_bar_sq, d_sq)
        shrinkage = 0.0 if b_sq == 0 else b_sq / d_sq
    else:
        raise ValueError(f"unknown covariance shrinkage method {method!r}")
    return (1.0 - shrinkage) * cov + shrinkage * mu * np.eye(n_features, dtype=float)

validate_mf_inputs(*, cov_op, target)

Raise ValueError for degenerate target/covariance pairs.

Checks, in order: the target has at least one non-zero entry, the covariance system is solvable, and the resulting filter gain :math:t^\top \Sigma^{-1} t is finite and positive.

Parameters:

Name Type Description Default
cov_op NumpyLinearOperator | Float[ndarray, 'c c']

Background covariance as a NumpyLinearOperator or a raw (c, c) matrix.

required
target Float[ndarray, ' c']

Target signature (c,).

required

Raises:

Type Description
ValueError

If the target is all-zero, the covariance is singular, or the filter gain is non-positive.

Source code in packages/geotoolz-ops/src/geoops/matched_filter/_src/array.py
def validate_mf_inputs(
    *,
    cov_op: NumpyLinearOperator | Float[np.ndarray, "c c"],
    target: Float[np.ndarray, " c"],
) -> None:
    """Raise ``ValueError`` for degenerate target/covariance pairs.

    Checks, in order: the target has at least one non-zero entry, the
    covariance system is solvable, and the resulting filter gain
    :math:`t^\\top \\Sigma^{-1} t` is finite and positive.

    Args:
        cov_op: Background covariance as a `NumpyLinearOperator` or a
            raw ``(c, c)`` matrix.
        target: Target signature ``(c,)``.

    Raises:
        ValueError: If the target is all-zero, the covariance is
            singular, or the filter gain is non-positive.
    """
    t = np.asarray(target, dtype=float).reshape(-1)
    if t.size == 0 or not np.any(t):
        raise ValueError("target must contain at least one non-zero value")
    try:
        gain = float(t @ solve(cov_op, t))
    except np.linalg.LinAlgError as exc:
        raise ValueError("covariance operator must be non-singular") from exc
    if not np.isfinite(gain) or gain <= 0:
        raise ValueError("target/covariance produce a non-positive MF gain")