Skip to content

Normalize

Per-band scaling and contrast operators for model inputs and display.

  • Per-band scalers: StandardScaler (z-score), RobustScaler (median / IQR), MinMaxScaler, ZeroOne
  • Fixed statistics: Normalize (z-score with given per-band mean / std), PerBandStats (compute and cache NaN-aware per-band statistics)
  • Non-linear scaling: LogScale, AsinhScale, PowerScale
  • Contrast / histogram: HistogramStretch, HistogramMatch, CLAHE
  • Tier-A primitives: standard_scale, robust_scale, minmax_scale (and their inverses inverse_standard_scale, inverse_robust_scale, inverse_minmax_scale), log_scale, asinh_scale, power_scale, histogram_match, reference_cdf, match_cdf, clahe, per_band_stats
  • Per-band statistics on every backend: band_stats, band_quantiles (arrays, band axis by position) and carrier_band_stats (a carrier, band dim by name), mask-aware on NumPy, JAX (under jax.jit too) and dask

See the Normalization guide for when to use which.

geoops.normalize

Normalization operators for remote-sensing GeoArrays.

AsinhScale

Bases: Operator

Inverse-hyperbolic-sine scaling.

.. math::

y \;=\; \mathrm{asinh}(x / a)

Linear near zero, logarithmic for |x| >> a. Symmetric and well-defined for negative values (unlike log) — a common pick for astronomy and signed radar quantities. Nodata (fill / non-finite) pixels hold the output fill value.

Parameters:

Name Type Description Default
a float

Scale parameter. Must be strictly positive. Default 1.0.

1.0

Examples:

>>> from geoops.normalize import AsinhScale
>>> out = AsinhScale(a=0.1)(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class AsinhScale(Operator):
    r"""Inverse-hyperbolic-sine scaling.

    .. math::

        y \;=\; \mathrm{asinh}(x / a)

    Linear near zero, logarithmic for ``|x| >> a``. Symmetric and
    well-defined for negative values (unlike ``log``) — a common pick
    for astronomy and signed radar quantities. Nodata (fill /
    non-finite) pixels hold the output fill value.

    Args:
        a: Scale parameter. Must be strictly positive. Default
            ``1.0``.

    Examples:
        >>> from geoops.normalize import AsinhScale
        >>> out = AsinhScale(a=0.1)(scene)
    """

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

    def __init__(self, *, a: float = 1.0) -> None:
        self.a = a

    def _apply(self, gt: Any) -> Any:
        check_positive("a", self.a)
        return pixel_kernel(asinh_scale, gt, dim="band", name="AsinhScale", a=self.a)

CLAHE

Bases: Operator

Contrast-Limited Adaptive Histogram Equalization.

Reproduces :func:skimage.exposure.equalize_adapthist (through clahe, without scikit-image) independently per band for (C, H, W) carriers while preserving NaN positions and GeoArray metadata. Nodata (fill / non-finite) pixels are excluded from the histograms and hold the output fill.

Backends: NumPy, JAX (under jax.jit too) and dask, where each frame's whole (band, y, x) cube is one task: the tiles need every pixel, so a spatially chunked cube is rechunked per frame.

Parameters:

Name Type Description Default
window int | tuple[int, int] | list[int] | None

Contextual-region shape for the local histograms. None uses scikit-image's default (1/8 of the image height / width). Lists (e.g. from Hydra / OmegaConf round-trips) are normalised to tuples.

None
clip_limit float

Contrast-limiting clip threshold in [0, 1]. Default 0.01.

0.01
nbins int

Number of histogram bins. Default 256.

256

Examples:

>>> from geoops.normalize import CLAHE
>>> out = CLAHE(window=(8, 8), clip_limit=0.03)(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class CLAHE(Operator):
    """Contrast-Limited Adaptive Histogram Equalization.

    Reproduces :func:`skimage.exposure.equalize_adapthist` (through
    `clahe`, without scikit-image) independently per band for
    ``(C, H, W)`` carriers while preserving NaN positions and GeoArray
    metadata. Nodata (fill / non-finite) pixels are excluded from the
    histograms and hold the output fill.

    Backends: NumPy, JAX (under ``jax.jit`` too) and dask, where each
    frame's whole ``(band, y, x)`` cube is one task: the tiles need every
    pixel, so a spatially chunked cube is rechunked per frame.

    Args:
        window: Contextual-region shape for the local histograms.
            ``None`` uses scikit-image's default (1/8 of the image height /
            width). Lists (e.g. from Hydra / OmegaConf round-trips)
            are normalised to tuples.
        clip_limit: Contrast-limiting clip threshold in ``[0, 1]``.
            Default ``0.01``.
        nbins: Number of histogram bins. Default ``256``.

    Examples:
        >>> from geoops.normalize import CLAHE
        >>> out = CLAHE(window=(8, 8), clip_limit=0.03)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # contextual histograms, on intensities rescaled over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        window: int | tuple[int, int] | list[int] | None = None,
        clip_limit: float = 0.01,
        nbins: int = 256,
    ) -> None:
        # Accept list inputs (e.g. round-trips through Hydra/OmegaConf,
        # which materialise sequences as lists) and normalise to tuple
        # so `clahe` receives its expected type.
        if isinstance(window, list):
            window = tuple(window)
        self.window = window
        self.clip_limit = clip_limit
        self.nbins = nbins

    def _apply(self, gt: Any) -> Any:
        carrier, unwrap = named(gt, name="CLAHE")
        banded = "band" in tuple(get_adapter(carrier).dims(carrier))
        # the whole (band, y, x) cube of a frame in one call: tiles need every
        # pixel, and the pixel rule every band (one dask task per frame)
        op = KernelOp(
            _clahe_kernel,
            "(c,y,x)->(c,y,x)" if banded else "(y,x)->(y,x)",
            core={"c": "band", "y": "y", "x": "x"} if banded else {"y": "y", "x": "x"},
            params={
                "fill": fill_of(carrier),
                "banded": banded,
                "window": self.window,
                "clip_limit": self.clip_limit,
                "nbins": self.nbins,
            },
        )
        return unwrap(_declare_fill(op(carrier), np.nan, carrier))

    def get_config(self) -> dict[str, Any]:
        if isinstance(self.window, tuple):
            window: int | list[int] | None = list(self.window)
        else:
            window = self.window
        return {
            "window": window,
            "clip_limit": self.clip_limit,
            "nbins": self.nbins,
        }

HistogramMatch

Bases: Operator

Match a GeoArray histogram to a reference GeoArray.

Reshapes the per-band empirical CDF of the input to match the reference. Useful for visual harmonisation across scenes acquired under different illumination. Nodata (fill / non-finite) pixels of both the input and the reference are excluded from the CDFs; input nodata pixels hold the output fill value.

A (T, C, H, W) stack is matched per band with one CDF pooled over every frame (like the module's other fitted statistics), so the relative brightness of the frames survives the matching; a 4-D reference likewise pools its frames per band.

The reference is a live GeoArray — not JSON / YAML serialisable — so forbid_in_yaml = True.

Backends: exact rank matching (reference_cdf, then match_cdf: a sort and searchsorted, the same result as scikit-image's match_histograms) with static shapes, so it runs on NumPy, on JAX under jax.jit (the reference's table is a constant), and lazily on dask, where each band of the source is gathered into one block.

Parameters:

Name Type Description Default
reference GeoArray | ndarray

Reference GeoArray whose per-band CDF the input will be matched against.

required

Examples:

>>> from geoops.normalize import HistogramMatch
>>> op = HistogramMatch(reference=reference_scene)
>>> matched = op(source_scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class HistogramMatch(Operator):
    """Match a GeoArray histogram to a reference GeoArray.

    Reshapes the per-band empirical CDF of the input to match the
    reference. Useful for visual harmonisation across scenes acquired
    under different illumination. Nodata (fill / non-finite) pixels of
    both the input and the reference are excluded from the CDFs; input
    nodata pixels hold the output fill value.

    A ``(T, C, H, W)`` stack is matched per band with one CDF pooled over
    every frame (like the module's other fitted statistics), so the
    relative brightness of the frames survives the matching; a 4-D
    reference likewise pools its frames per band.

    The reference is a live GeoArray — not JSON / YAML serialisable —
    so ``forbid_in_yaml = True``.

    Backends: exact rank matching (`reference_cdf`, then `match_cdf`: a sort
    and ``searchsorted``, the same result as scikit-image's
    ``match_histograms``) with static shapes, so it runs on NumPy, on JAX
    under ``jax.jit`` (the reference's table is a constant), and lazily on
    dask, where each band of the source is gathered into one block.

    Args:
        reference: Reference GeoArray whose per-band CDF the input
            will be matched against.

    Examples:
        >>> from geoops.normalize import HistogramMatch
        >>> op = HistogramMatch(reference=reference_scene)
        >>> matched = op(source_scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # the source CDF of each band over every pixel and frame
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    # Holds a live GeoArray reference, which is not JSON/YAML
    # serialisable.
    forbid_in_yaml: ClassVar[bool] = True

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

    def _apply(self, gt: Any) -> Any:
        reject_geotensor(self.reference, "HistogramMatch (reference)")
        source = _pixel_view(gt, "band", "HistogramMatch")
        reference = self.reference
        if isinstance(reference, GeoArray) and reference.backend == "jax":
            # the table is a host constant: build it before any trace sees it
            reference = reference.to_numpy()
        ref = _pixel_view(reference, "band", "HistogramMatch (reference)")
        n_bands = (
            source.data.shape[source.band_axis] if source.band_axis is not None else 1
        )
        ref_bands = ref.data.shape[ref.band_axis] if ref.band_axis is not None else 1
        # per band when the reference has the source's bands or is one 2-D map;
        # otherwise one CDF pooled over every band of each, as before
        per_band = source.band_axis is not None and (
            ref.band_axis is None or ref_bands == n_bands
        )
        _, ref_rows, ref_valid = _as_rows(ref, per_band and ref.band_axis is not None)
        table = reference_cdf(np.asarray(ref_rows), np.asarray(ref_valid))
        if table[0].shape[0] == 1 and per_band:  # one 2-D map for every band
            table = tuple(np.repeat(t, n_bands, axis=0) for t in table)
        xp, rows, valid = _as_rows(source, per_band)
        if xp.__name__ == "dask.array":
            # every pixel of a band in one block, as band_quantiles does
            rows = rows.rechunk({0: 1, 1: -1})
            valid = valid.rechunk({0: 1, 1: -1})
            parts = [xp.from_array(t, chunks=(1, -1)) for t in table]
            matched = xp.map_blocks(match_cdf, rows, valid, *parts, dtype=float)
        else:
            matched = match_cdf(rows, valid, *table)
        return _from_rows(source, xp.where(valid, matched, xp.nan))

    def get_config(self) -> dict[str, Any]:
        # Debug payload: the reference is a runtime raster (forbid_in_yaml).
        reference = np.asarray(self.reference)
        return {
            "reference": {
                "shape": list(reference.shape),
                "dtype": str(reference.dtype),
            }
        }

HistogramStretch

Bases: Operator

Per-band percentile stretch into out_range for visualisation.

Lighter-weight cousin of :class:geoops.radiometry.PercentileClip (same shared percentile stretch, same lower / upper vocabulary): clips to [P_lower, P_upper] using NaN-aware percentiles, then maps the result into out_range instead of fixed [0, 1]. Percentiles follow the normalize per-band statistics convention: per band, pooled over the frames of a (T, C, H, W) stack (PercentileClip stretches each frame independently by default). Nodata (fill / non-finite) pixels are excluded from the percentiles and hold the output fill value.

Parameters:

Name Type Description Default
out_range tuple[float, float]

Two-element increasing tuple. Default (0.0, 1.0).

(0.0, 1.0)
lower float

Lower percentile. Default 2.0.

2.0
upper float

Upper percentile. Default 98.0; must exceed lower.

98.0

Examples:

>>> from geoops.normalize import HistogramStretch
>>> # Standard "satellite RGB to display byte range" stretch.
>>> op = HistogramStretch(out_range=(0.0, 255.0))
>>> display = op(reflectance_scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class HistogramStretch(Operator):
    r"""Per-band percentile stretch into ``out_range`` for visualisation.

    Lighter-weight cousin of :class:`geoops.radiometry.PercentileClip`
    (same shared percentile stretch, same ``lower`` / ``upper``
    vocabulary): clips to ``[P_lower, P_upper]`` using NaN-aware
    percentiles, then maps the result into ``out_range`` instead of
    fixed ``[0, 1]``. Percentiles follow the ``normalize`` per-band
    statistics convention: per band, pooled over the frames of a
    ``(T, C, H, W)`` stack (``PercentileClip`` stretches each frame
    independently by default). Nodata (fill / non-finite) pixels are
    excluded from the percentiles and hold the output fill value.

    Args:
        out_range: Two-element increasing tuple. Default
            ``(0.0, 1.0)``.
        lower: Lower percentile. Default ``2.0``.
        upper: Upper percentile. Default ``98.0``; must exceed ``lower``.

    Examples:
        >>> from geoops.normalize import HistogramStretch
        >>> # Standard "satellite RGB to display byte range" stretch.
        >>> op = HistogramStretch(out_range=(0.0, 255.0))
        >>> display = op(reflectance_scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # per-band percentiles over every pixel and frame of the input
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(
        self,
        *,
        out_range: tuple[float, float] = (0.0, 1.0),
        lower: float = 2.0,
        upper: float = 98.0,
    ) -> None:
        self.out_range = validate_out_range(tuple(out_range))
        self.lower = lower
        self.upper = upper

    def _apply(self, gt: Any) -> Any:
        check_percentiles(self.lower, self.upper)
        q = (self.lower / 100.0, self.upper / 100.0)
        lo, hi = _scene_stats(gt, stats=(), quantiles=q)["quantiles"]
        # the band dim is last inside the kernel, so (C,) bounds broadcast as is
        return pixel_kernel(
            _stretch_kernel,
            gt,
            dim="band",
            name="HistogramStretch",
            lo=lo,
            hi=hi,
            out_range=self.out_range,
        )

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

LogScale

Bases: Operator

Logarithmic scaling with an epsilon offset for zeros.

.. math::

y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)

Compresses heavy-tailed distributions (radar backscatter, fire radiative power, etc.) before downstream training. eps keeps the log finite at zero. Nodata (fill / non-finite) pixels hold the output fill value.

Parameters:

Name Type Description Default
base float

Logarithm base. Must be > 0 and != 1. Default 10.0.

10.0
eps float

Small positive offset added before the log. Default 1e-6.

1e-06

Examples:

>>> from geoops.normalize import LogScale
>>> log_sar = LogScale(base=10.0, eps=1e-6)(sar_backscatter)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class LogScale(Operator):
    r"""Logarithmic scaling with an epsilon offset for zeros.

    .. math::

        y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)

    Compresses heavy-tailed distributions (radar backscatter, fire
    radiative power, etc.) before downstream training. ``eps`` keeps
    the log finite at zero. Nodata (fill / non-finite) pixels hold the
    output fill value.

    Args:
        base: Logarithm base. Must be ``> 0`` and ``!= 1``. Default
            ``10.0``.
        eps: Small positive offset added before the log. Default
            ``1e-6``.

    Examples:
        >>> from geoops.normalize import LogScale
        >>> log_sar = LogScale(base=10.0, eps=1e-6)(sar_backscatter)
    """

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

    def __init__(self, *, base: float = 10.0, eps: float = 1e-6) -> None:
        self.base = base
        self.eps = eps

    def _apply(self, gt: Any) -> Any:
        check_log_scale(self.base, self.eps)
        return pixel_kernel(
            log_scale, gt, dim="band", name="LogScale", base=self.base, eps=self.eps
        )

MinMaxScaler

Bases: Operator

Per-band min-max scaling into an arbitrary output range.

.. math::

y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
        \cdot (o_{\max} - o_{\min}) + o_{\min}

Per-band variant of :class:geoops.radiometry.MinMaxStretch. The radiometry version takes scalar bounds and is the display-prep pick when you already know fixed reflectance limits; this version fits per-band bounds (one vmin / vmax per channel) or accepts cached training-time bounds for inference. When vmax == vmin for a band the divisor falls back to 1. Nodata (fill / non-finite) pixels are excluded from the fit and hold the output fill value.

Fitted operator with the same fit / transform / inverse contract as :class:StandardScaler (fitted state vmin_ / vmax_, never part of get_config()).

Parameters:

Name Type Description Default
vmin ndarray | list[float] | float | None

Per-band lower bound, scalar / list / ndarray, or None to fit.

None
vmax ndarray | list[float] | float | None

Per-band upper bound.

None
out_range tuple[float, float]

(out_min, out_max) range to map into. Default (0.0, 1.0).

(0.0, 1.0)
fit_on_call bool

If True and the operator is not fitted yet, fit the bounds on the first call and reuse them afterwards.

False

Attributes:

Name Type Description
vmin_ ndarray | None

Fitted per-band lower bound, or None before :meth:fit.

vmax_ ndarray | None

Fitted per-band upper bound, or None before :meth:fit.

Examples:

>>> from geoops.normalize import MinMaxScaler
>>> # Map per-band [vmin, vmax] into [0, 1]:
>>> op = MinMaxScaler(vmin=[0.0, 0.0], vmax=[0.3, 0.4])
>>> scaled = op(scene)
>>>
>>> # Or fit on the scene and emit a uint8-style range:
>>> op = MinMaxScaler(out_range=(0.0, 255.0)).fit(scene)
>>> display = op(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class MinMaxScaler(Operator):
    r"""Per-band min-max scaling into an arbitrary output range.

    .. math::

        y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
                \cdot (o_{\max} - o_{\min}) + o_{\min}

    Per-band variant of :class:`geoops.radiometry.MinMaxStretch`. The
    radiometry version takes **scalar** bounds and is the display-prep
    pick when you already know fixed reflectance limits; this version
    fits **per-band** bounds (one ``vmin`` / ``vmax`` per channel) or
    accepts cached training-time bounds for inference. When
    ``vmax == vmin`` for a band the divisor falls back to ``1``. Nodata
    (fill / non-finite) pixels are excluded from the fit and hold the
    output fill value.

    Fitted operator with the same ``fit`` / ``transform`` / ``inverse``
    contract as :class:`StandardScaler` (fitted state ``vmin_`` /
    ``vmax_``, never part of ``get_config()``).

    Args:
        vmin: Per-band lower bound, scalar / list / ndarray, or
            ``None`` to fit.
        vmax: Per-band upper bound.
        out_range: ``(out_min, out_max)`` range to map into. Default
            ``(0.0, 1.0)``.
        fit_on_call: If ``True`` and the operator is not fitted yet, fit
            the bounds on the first call and reuse them afterwards.

    Attributes:
        vmin_: Fitted per-band lower bound, or ``None`` before :meth:`fit`.
        vmax_: Fitted per-band upper bound, or ``None`` before :meth:`fit`.

    Examples:
        >>> from geoops.normalize import MinMaxScaler
        >>> # Map per-band [vmin, vmax] into [0, 1]:
        >>> op = MinMaxScaler(vmin=[0.0, 0.0], vmax=[0.3, 0.4])
        >>> scaled = op(scene)
        >>>
        >>> # Or fit on the scene and emit a uint8-style range:
        >>> op = MinMaxScaler(out_range=(0.0, 255.0)).fit(scene)
        >>> display = op(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # min and max fitted over every pixel and frame
    coupling: ClassVar[Coupling] = Coupling(fit={"space", "time"})

    def __init__(
        self,
        *,
        vmin: np.ndarray | list[float] | float | None = None,
        vmax: np.ndarray | list[float] | float | None = None,
        out_range: tuple[float, float] = (0.0, 1.0),
        fit_on_call: bool = False,
    ) -> None:
        self.vmin = _array_or_none(vmin)
        self.vmax = _array_or_none(vmax)
        self.out_range = validate_out_range(tuple(out_range))
        self.fit_on_call = fit_on_call
        self.vmin_: np.ndarray | None = None
        self.vmax_: np.ndarray | None = None

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Learn per-band ``vmin_`` / ``vmax_`` from the valid pixels of ``gt``.

        Returns:
            This operator, for chaining.
        """
        stats = _fit_stats(self, gt, stats=("min", "max"))
        self.vmax_ = stats["max"]
        self.vmin_ = stats["min"]  # published last: fit_once checks ``vmin_``
        return self

    def _stats(self) -> tuple[np.ndarray, np.ndarray]:
        if self.vmin_ is not None and self.vmax_ is not None:
            return self.vmin_, self.vmax_
        if self.vmin is not None and self.vmax is not None:
            return self.vmin, self.vmax
        raise ValueError("MinMaxScaler requires vmin/vmax, fit(), or fit_on_call=True")

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Map ``gt`` from the fitted (or constructor) bounds into ``out_range``."""
        vmin, vmax = self._stats()
        _check_per_band(vmin, gt)
        _check_per_band(vmax, gt)
        return pixel_kernel(
            minmax_scale,
            gt,
            dim="band",
            name="MinMaxScaler",
            vmin=vmin,
            vmax=vmax,
            out_range=self.out_range,
            reduce_axes=None,
        )

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.fit_on_call:
            fit_once(self, gt, lambda: self.vmin_ is not None)
        return self.transform(gt)

    def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Map ``out_range`` values back to the ``[vmin, vmax]`` input scale."""
        vmin, vmax = self._stats()
        _check_per_band(vmin, gt)
        _check_per_band(vmax, gt)
        return pixel_kernel(
            inverse_minmax_scale,
            gt,
            dim="band",
            name="MinMaxScaler.inverse",
            vmin=vmin,
            vmax=vmax,
            out_range=self.out_range,
            reduce_axes=None,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "vmin": jsonable(self.vmin),
            "vmax": jsonable(self.vmax),
            "out_range": list(self.out_range),
            "fit_on_call": self.fit_on_call,
        }

fit(gt)

Learn per-band vmin_ / vmax_ from the valid pixels of gt.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Learn per-band ``vmin_`` / ``vmax_`` from the valid pixels of ``gt``.

    Returns:
        This operator, for chaining.
    """
    stats = _fit_stats(self, gt, stats=("min", "max"))
    self.vmax_ = stats["max"]
    self.vmin_ = stats["min"]  # published last: fit_once checks ``vmin_``
    return self

inverse(gt)

Map out_range values back to the [vmin, vmax] input scale.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Map ``out_range`` values back to the ``[vmin, vmax]`` input scale."""
    vmin, vmax = self._stats()
    _check_per_band(vmin, gt)
    _check_per_band(vmax, gt)
    return pixel_kernel(
        inverse_minmax_scale,
        gt,
        dim="band",
        name="MinMaxScaler.inverse",
        vmin=vmin,
        vmax=vmax,
        out_range=self.out_range,
        reduce_axes=None,
    )

transform(gt)

Map gt from the fitted (or constructor) bounds into out_range.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Map ``gt`` from the fitted (or constructor) bounds into ``out_range``."""
    vmin, vmax = self._stats()
    _check_per_band(vmin, gt)
    _check_per_band(vmax, gt)
    return pixel_kernel(
        minmax_scale,
        gt,
        dim="band",
        name="MinMaxScaler",
        vmin=vmin,
        vmax=vmax,
        out_range=self.out_range,
        reduce_axes=None,
    )

Normalize

Bases: StandardScaler

Fixed-stats per-band z-score normaliser.

Convenience alias for :class:StandardScaler with mandatory mean / std (no fit_on_call knob exposed). The canonical inference-time normaliser: cache stats once at training time, instantiate at inference.

Parameters:

Name Type Description Default
mean ndarray | list[float] | float

Per-band mean (scalar, list, or ndarray).

required
std ndarray | list[float] | float

Per-band std (scalar, list, or ndarray).

required

Examples:

>>> from geoops.normalize import Normalize
>>> import numpy as np
>>> op = Normalize(
...     mean=np.array([0.1, 0.2, 0.15]),
...     std=np.array([0.05, 0.07, 0.06]),
... )
>>> normed = op(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class Normalize(StandardScaler):
    r"""Fixed-stats per-band z-score normaliser.

    Convenience alias for :class:`StandardScaler` with mandatory
    ``mean`` / ``std`` (no ``fit_on_call`` knob exposed). The canonical
    inference-time normaliser: cache stats once at training time,
    instantiate at inference.

    Args:
        mean: Per-band mean (scalar, list, or ndarray).
        std: Per-band std (scalar, list, or ndarray).

    Examples:
        >>> from geoops.normalize import Normalize
        >>> import numpy as np
        >>> op = Normalize(
        ...     mean=np.array([0.1, 0.2, 0.15]),
        ...     std=np.array([0.05, 0.07, 0.06]),
        ... )
        >>> normed = op(scene)
    """

    # fixed statistics: _apply never fits, so the transform runs anywhere
    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # fixed statistics: nothing is fitted
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(
        self,
        *,
        mean: np.ndarray | list[float] | float,
        std: np.ndarray | list[float] | float,
    ) -> None:
        super().__init__(mean=mean, std=std, fit_on_call=False)

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": jsonable(self.mean),
            "std": jsonable(self.std),
        }

PerBandStats

Bases: Operator

Compute NaN-aware per-band statistics and cache them.

Side-effect-only operator: returns the input unchanged after caching a stats dict containing per-band mean, std, min, max, and percentiles over the spatial (H, W) axes. Use this in a Tap-style stage to inspect a scene before applying a downstream normaliser. Nodata (fill / non-finite) pixels are excluded from every statistic.

Backends: NumPy, eager JAX and dask, where one compute of the statistics (not of the data) runs and the input passes through still lazy. Under jax.jit writing self.stats would leak tracers, so it raises; use carrier_band_stats inside a trace instead.

Parameters:

Name Type Description Default
percentiles list[float] | None

Percentiles (in [0, 100]) to cache alongside mean/std/min/max. Default [1.0, 99.0].

None

Examples:

>>> from geoops.normalize import PerBandStats
>>> op = PerBandStats(percentiles=[2.0, 98.0])
>>> _ = op(scene)
>>> op.stats["mean"]   # one entry per band
[...]
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class PerBandStats(Operator):
    """Compute NaN-aware per-band statistics and cache them.

    Side-effect-only operator: returns the input unchanged after caching
    a ``stats`` dict containing per-band ``mean``, ``std``, ``min``,
    ``max``, and ``percentiles`` over the spatial ``(H, W)`` axes. Use
    this in a ``Tap``-style stage to inspect a scene before applying a
    downstream normaliser. Nodata (fill / non-finite) pixels are
    excluded from every statistic.

    Backends: NumPy, eager JAX and dask, where one compute of the
    statistics (not of the data) runs and the input passes through still
    lazy. Under ``jax.jit`` writing ``self.stats`` would leak tracers, so it
    raises; use `carrier_band_stats` inside a trace instead.

    Args:
        percentiles: Percentiles (in ``[0, 100]``) to cache alongside
            mean/std/min/max. Default ``[1.0, 99.0]``.

    Examples:
        >>> from geoops.normalize import PerBandStats
        >>> op = PerBandStats(percentiles=[2.0, 98.0])
        >>> _ = op(scene)
        >>> op.stats["mean"]   # one entry per band
        [...]
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # returns its input; the statistics are a side effect
    coupling: ClassVar[Coupling] = Coupling()
    # writes self.stats: eager on JAX, refused under jax.jit (the contract checks)
    traceable: ClassVar[bool] = False

    def __init__(self, *, percentiles: list[float] | None = None) -> None:
        self.percentiles = [1.0, 99.0] if percentiles is None else list(percentiles)
        self.stats: dict[str, Any] = {}

    def _apply(self, gt: Any) -> Any:
        stats = _host_stats(
            gt,
            "PerBandStats",
            f"Call it eagerly, outside the trace; or use {_FUNCTIONAL}",
            quantiles=tuple(p / 100.0 for p in self.percentiles),
        )
        # no levels gives no "quantiles" entry; keep the old empty list
        stats["percentiles"] = stats.pop("quantiles", np.empty(0))
        self.stats = {key: jsonable(value) for key, value in stats.items()}
        return gt

PowerScale

Bases: Operator

Non-negative power scaling.

.. math::

y \;=\; \max(x, 0)^{\gamma}

A simple gamma-style brightness curve. gamma < 1 brightens midtones; gamma > 1 darkens. Differs from :class:geoops.radiometry.Gamma only in convention (Gamma raises to 1/g). Nodata (fill / non-finite) pixels hold the output fill value.

Parameters:

Name Type Description Default
gamma float

Power exponent. Must be strictly positive. Default 0.5 (square-root).

0.5

Examples:

>>> from geoops.normalize import PowerScale
>>> out = PowerScale(gamma=0.5)(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class PowerScale(Operator):
    r"""Non-negative power scaling.

    .. math::

        y \;=\; \max(x, 0)^{\gamma}

    A simple ``gamma``-style brightness curve. ``gamma < 1`` brightens
    midtones; ``gamma > 1`` darkens. Differs from
    :class:`geoops.radiometry.Gamma` only in convention
    (``Gamma`` raises to ``1/g``). Nodata (fill / non-finite) pixels
    hold the output fill value.

    Args:
        gamma: Power exponent. Must be strictly positive. Default
            ``0.5`` (square-root).

    Examples:
        >>> from geoops.normalize import PowerScale
        >>> out = PowerScale(gamma=0.5)(scene)
    """

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

    def __init__(self, *, gamma: float = 0.5) -> None:
        self.gamma = gamma

    def _apply(self, gt: Any) -> Any:
        check_positive("gamma", self.gamma)
        return pixel_kernel(
            power_scale, gt, dim="band", name="PowerScale", gamma=self.gamma
        )

RobustScaler

Bases: Operator

Per-band median / IQR scaling (robust to outliers).

.. math::

y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}

Identical role to :class:StandardScaler but uses the median and interquartile range instead of mean and std — robust against bright-pixel outliers (cumulus, glint, saturation). When iqr == 0 the divisor falls back to 1. Nodata (fill / non-finite) pixels are excluded from the fit and hold the output fill.

Fitted operator with the same fit / transform / inverse contract as :class:StandardScaler (fitted state median_ / iqr_, never part of get_config()).

Parameters:

Name Type Description Default
median ndarray | list[float] | float | None

Per-band median (scalar, list, or ndarray) or None.

None
iqr ndarray | list[float] | float | None

Per-band IQR (Q3 - Q1).

None
fit_on_call bool

If True and the operator is not fitted yet, fit on the first call (the 25th, 50th and 75th percentiles) and reuse the statistics afterwards.

False

Attributes:

Name Type Description
median_ ndarray | None

Fitted per-band median, or None before :meth:fit.

iqr_ ndarray | None

Fitted per-band IQR, or None before :meth:fit.

Examples:

>>> from geoops.normalize import RobustScaler
>>> op = RobustScaler().fit(scene)
>>> op.median_, op.iqr_
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class RobustScaler(Operator):
    r"""Per-band median / IQR scaling (robust to outliers).

    .. math::

        y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}

    Identical role to :class:`StandardScaler` but uses the median and
    interquartile range instead of mean and std — robust against
    bright-pixel outliers (cumulus, glint, saturation). When
    ``iqr == 0`` the divisor falls back to ``1``. Nodata (fill /
    non-finite) pixels are excluded from the fit and hold the output fill.

    Fitted operator with the same ``fit`` / ``transform`` / ``inverse``
    contract as :class:`StandardScaler` (fitted state ``median_`` /
    ``iqr_``, never part of ``get_config()``).

    Args:
        median: Per-band median (scalar, list, or ndarray) or ``None``.
        iqr: Per-band IQR (``Q3 - Q1``).
        fit_on_call: If ``True`` and the operator is not fitted yet, fit
            on the first call (the 25th, 50th and 75th percentiles) and
            reuse the statistics afterwards.

    Attributes:
        median_: Fitted per-band median, or ``None`` before :meth:`fit`.
        iqr_: Fitted per-band IQR, or ``None`` before :meth:`fit`.

    Examples:
        >>> from geoops.normalize import RobustScaler
        >>> op = RobustScaler().fit(scene)
        >>> op.median_, op.iqr_
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # median and IQR fitted over every pixel and frame
    coupling: ClassVar[Coupling] = Coupling(fit={"space", "time"})

    def __init__(
        self,
        *,
        median: np.ndarray | list[float] | float | None = None,
        iqr: np.ndarray | list[float] | float | None = None,
        fit_on_call: bool = False,
    ) -> None:
        self.median = _array_or_none(median)
        self.iqr = _array_or_none(iqr)
        self.fit_on_call = fit_on_call
        self.median_: np.ndarray | None = None
        self.iqr_: np.ndarray | None = None

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Learn per-band ``median_`` / ``iqr_`` from the valid pixels of ``gt``.

        Returns:
            This operator, for chaining.
        """
        quantiles = (0.25, 0.5, 0.75)
        q25, q50, q75 = _fit_stats(self, gt, stats=(), quantiles=quantiles)["quantiles"]
        self.iqr_ = q75 - q25
        self.median_ = q50  # published last: fit_once checks ``median_``
        return self

    def _stats(self) -> tuple[np.ndarray, np.ndarray]:
        if self.median_ is not None and self.iqr_ is not None:
            return self.median_, self.iqr_
        if self.median is not None and self.iqr is not None:
            return self.median, self.iqr
        raise ValueError("RobustScaler requires median/iqr, fit(), or fit_on_call=True")

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Scale ``gt`` with the fitted (or constructor) median / IQR."""
        median, iqr = self._stats()
        _check_per_band(median, gt)
        _check_per_band(iqr, gt)
        return pixel_kernel(
            robust_scale,
            gt,
            dim="band",
            name="RobustScaler",
            median=median,
            iqr=iqr,
            reduce_axes=None,
        )

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.fit_on_call:
            fit_once(self, gt, lambda: self.median_ is not None)
        return self.transform(gt)

    def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Invert a previously applied robust scaling (``x = y * iqr + median``)."""
        median, iqr = self._stats()
        _check_per_band(median, gt)
        _check_per_band(iqr, gt)
        return pixel_kernel(
            inverse_robust_scale,
            gt,
            dim="band",
            name="RobustScaler.inverse",
            median=median,
            iqr=iqr,
            reduce_axes=None,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "median": jsonable(self.median),
            "iqr": jsonable(self.iqr),
            "fit_on_call": self.fit_on_call,
        }

fit(gt)

Learn per-band median_ / iqr_ from the valid pixels of gt.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Learn per-band ``median_`` / ``iqr_`` from the valid pixels of ``gt``.

    Returns:
        This operator, for chaining.
    """
    quantiles = (0.25, 0.5, 0.75)
    q25, q50, q75 = _fit_stats(self, gt, stats=(), quantiles=quantiles)["quantiles"]
    self.iqr_ = q75 - q25
    self.median_ = q50  # published last: fit_once checks ``median_``
    return self

inverse(gt)

Invert a previously applied robust scaling (x = y * iqr + median).

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Invert a previously applied robust scaling (``x = y * iqr + median``)."""
    median, iqr = self._stats()
    _check_per_band(median, gt)
    _check_per_band(iqr, gt)
    return pixel_kernel(
        inverse_robust_scale,
        gt,
        dim="band",
        name="RobustScaler.inverse",
        median=median,
        iqr=iqr,
        reduce_axes=None,
    )

transform(gt)

Scale gt with the fitted (or constructor) median / IQR.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Scale ``gt`` with the fitted (or constructor) median / IQR."""
    median, iqr = self._stats()
    _check_per_band(median, gt)
    _check_per_band(iqr, gt)
    return pixel_kernel(
        robust_scale,
        gt,
        dim="band",
        name="RobustScaler",
        median=median,
        iqr=iqr,
        reduce_axes=None,
    )

StandardScaler

Bases: Operator

Per-band z-score normalisation.

.. math::

y \;=\; \frac{x - \mu}{\sigma}

Statistics reduce over the spatial axes (-2, -1) so a (C, H, W) carrier yields per-band mu / sigma of shape (C,). Pass cached training-set statistics via mean / std for inference, call :meth:fit on a training scene, or set fit_on_call=True to fit on the first scene seen. When sigma == 0 (a constant band) the divisor falls back to 1 so the band collapses to zero instead of producing inf / nan. Nodata (fill / non-finite) pixels are excluded from the fit and hold the output fill value.

Fitted operator (see Fitted operators in the concepts guide): :meth:fit learns mean_ / std_ (which then take precedence over the constructor statistics), :meth:transform applies them without mutating the operator, and :meth:inverse undoes the scaling. Learned statistics are never part of get_config(); to persist them, build StandardScaler(mean=op.mean_, std=op.std_).

Backends: :meth:fit runs on NumPy, eager JAX and dask (one compute of the statistics, not of the data) and always stores host NumPy arrays. Under jax.jit it raises, and so does a first fit_on_call call: fit eagerly, then apply the fitted operator inside the trace, where its statistics are constants. :meth:transform and :meth:inverse run everywhere, lazily on dask.

Parameters:

Name Type Description Default
mean ndarray | list[float] | float | None

Per-band mean (scalar, list, or ndarray) or None.

None
std ndarray | list[float] | float | None

Per-band std (scalar, list, or ndarray) or None.

None
fit_on_call bool

If True and the operator is not fitted yet, fit mean_ / std_ on the first call and reuse them for every later call. The fit runs once even under concurrent calls (pipekit_ops.ThreadMap), but which scene it sees is then the first to arrive -- call :meth:fit before parallel use for a deterministic fit.

False

Attributes:

Name Type Description
mean_ ndarray | None

Fitted per-band mean, or None before :meth:fit.

std_ ndarray | None

Fitted per-band std, or None before :meth:fit.

Examples:

>>> from geoops.normalize import StandardScaler
>>> # Inference: cached per-band statistics from training.
>>> scaler = StandardScaler(mean=[0.1, 0.2], std=[0.05, 0.07])
>>> normed = scaler(scene)
>>>
>>> # Training-time fit, then apply:
>>> fit = StandardScaler().fit(train_scene)
>>> normed = fit(scene)
>>> fit.mean_  # fitted per-band ndarray
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class StandardScaler(Operator):
    r"""Per-band z-score normalisation.

    .. math::

        y \;=\; \frac{x - \mu}{\sigma}

    Statistics reduce over the spatial axes ``(-2, -1)`` so a
    ``(C, H, W)`` carrier yields per-band ``mu`` / ``sigma`` of shape
    ``(C,)``. Pass cached training-set statistics via ``mean`` / ``std``
    for inference, call :meth:`fit` on a training scene, or set
    ``fit_on_call=True`` to fit on the first scene seen. When
    ``sigma == 0`` (a constant band) the divisor falls back to ``1`` so
    the band collapses to zero instead of producing ``inf`` / ``nan``.
    Nodata (fill / non-finite) pixels are excluded from the fit and hold
    the output fill value.

    Fitted operator (see *Fitted operators* in the concepts guide):
    :meth:`fit` learns ``mean_`` / ``std_`` (which then take precedence
    over the constructor statistics), :meth:`transform` applies them
    without mutating the operator, and :meth:`inverse` undoes the
    scaling. Learned statistics are never part of ``get_config()``; to
    persist them, build ``StandardScaler(mean=op.mean_, std=op.std_)``.

    Backends: :meth:`fit` runs on NumPy, eager JAX and dask (one compute of
    the statistics, not of the data) and always stores host NumPy arrays.
    Under ``jax.jit`` it raises, and so does a first ``fit_on_call``
    call: fit eagerly, then apply the fitted operator inside the trace,
    where its statistics are constants. :meth:`transform` and
    :meth:`inverse` run everywhere, lazily on dask.

    Args:
        mean: Per-band mean (scalar, list, or ndarray) or ``None``.
        std: Per-band std (scalar, list, or ndarray) or ``None``.
        fit_on_call: If ``True`` and the operator is not fitted yet,
            fit ``mean_`` / ``std_`` on the first call and reuse them for
            every later call. The fit
            runs once even under concurrent calls (``pipekit_ops.ThreadMap``),
            but which scene it sees is then the first to arrive -- call
            :meth:`fit` before parallel use for a deterministic fit.

    Attributes:
        mean_: Fitted per-band mean, or ``None`` before :meth:`fit`.
        std_: Fitted per-band std, or ``None`` before :meth:`fit`.

    Examples:
        >>> from geoops.normalize import StandardScaler
        >>> # Inference: cached per-band statistics from training.
        >>> scaler = StandardScaler(mean=[0.1, 0.2], std=[0.05, 0.07])
        >>> normed = scaler(scene)
        >>>
        >>> # Training-time fit, then apply:
        >>> fit = StandardScaler().fit(train_scene)
        >>> normed = fit(scene)
        >>> fit.mean_  # fitted per-band ndarray
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # x' = (x - mu_c) / sigma_c pointwise; mu_c, sigma_c fitted over every pixel and frame
    coupling: ClassVar[Coupling] = Coupling(fit={"space", "time"})

    def __init__(
        self,
        *,
        mean: np.ndarray | list[float] | float | None = None,
        std: np.ndarray | list[float] | float | None = None,
        fit_on_call: bool = False,
    ) -> None:
        self.mean = _array_or_none(mean)
        self.std = _array_or_none(std)
        self.fit_on_call = fit_on_call
        self.mean_: np.ndarray | None = None
        self.std_: np.ndarray | None = None

    def fit(self, gt: GeoArray | np.ndarray) -> Self:
        """Learn per-band ``mean_`` / ``std_`` from the valid pixels of ``gt``.

        Returns:
            This operator, for chaining.
        """
        stats = _fit_stats(self, gt, stats=("mean", "std"))
        self.std_ = stats["std"]
        self.mean_ = stats["mean"]  # published last: fit_once checks ``mean_``
        return self

    def _stats(self) -> tuple[np.ndarray, np.ndarray]:
        if self.mean_ is not None and self.std_ is not None:
            return self.mean_, self.std_
        if self.mean is not None and self.std is not None:
            return self.mean, self.std
        raise ValueError("StandardScaler requires mean/std, fit(), or fit_on_call=True")

    def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Z-score ``gt`` with the fitted (or constructor) statistics.

        Raises:
            ValueError: If the operator has neither fitted nor constructor
                statistics.
        """
        mean, std = self._stats()
        _check_per_band(mean, gt)
        _check_per_band(std, gt)
        # the band dim is last inside the kernel, so (C,) stats broadcast as is
        return pixel_kernel(
            standard_scale,
            gt,
            dim="band",
            name=type(self).__name__,
            mean=mean,
            std=std,
            reduce_axes=None,
        )

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.fit_on_call:
            fit_once(self, gt, lambda: self.mean_ is not None)
        return self.transform(gt)

    def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        """Invert a previously applied standard scaling.

        Args:
            gt: Scaled carrier (GeoArray or plain ndarray).

        Returns:
            The un-scaled carrier, same kind as ``gt``; nodata pixels
            hold the output fill value.

        Raises:
            ValueError: If the scaler has no statistics yet.
        """
        mean, std = self._stats()
        _check_per_band(mean, gt)
        _check_per_band(std, gt)
        return pixel_kernel(
            inverse_standard_scale,
            gt,
            dim="band",
            name=f"{type(self).__name__}.inverse",
            mean=mean,
            std=std,
            reduce_axes=None,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "mean": jsonable(self.mean),
            "std": jsonable(self.std),
            "fit_on_call": self.fit_on_call,
        }

fit(gt)

Learn per-band mean_ / std_ from the valid pixels of gt.

Returns:

Type Description
Self

This operator, for chaining.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def fit(self, gt: GeoArray | np.ndarray) -> Self:
    """Learn per-band ``mean_`` / ``std_`` from the valid pixels of ``gt``.

    Returns:
        This operator, for chaining.
    """
    stats = _fit_stats(self, gt, stats=("mean", "std"))
    self.std_ = stats["std"]
    self.mean_ = stats["mean"]  # published last: fit_once checks ``mean_``
    return self

inverse(gt)

Invert a previously applied standard scaling.

Parameters:

Name Type Description Default
gt GeoArray | ndarray

Scaled carrier (GeoArray or plain ndarray).

required

Returns:

Type Description
GeoArray | ndarray

The un-scaled carrier, same kind as gt; nodata pixels

GeoArray | ndarray

hold the output fill value.

Raises:

Type Description
ValueError

If the scaler has no statistics yet.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def inverse(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Invert a previously applied standard scaling.

    Args:
        gt: Scaled carrier (GeoArray or plain ndarray).

    Returns:
        The un-scaled carrier, same kind as ``gt``; nodata pixels
        hold the output fill value.

    Raises:
        ValueError: If the scaler has no statistics yet.
    """
    mean, std = self._stats()
    _check_per_band(mean, gt)
    _check_per_band(std, gt)
    return pixel_kernel(
        inverse_standard_scale,
        gt,
        dim="band",
        name=f"{type(self).__name__}.inverse",
        mean=mean,
        std=std,
        reduce_axes=None,
    )

transform(gt)

Z-score gt with the fitted (or constructor) statistics.

Raises:

Type Description
ValueError

If the operator has neither fitted nor constructor statistics.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def transform(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
    """Z-score ``gt`` with the fitted (or constructor) statistics.

    Raises:
        ValueError: If the operator has neither fitted nor constructor
            statistics.
    """
    mean, std = self._stats()
    _check_per_band(mean, gt)
    _check_per_band(std, gt)
    # the band dim is last inside the kernel, so (C,) stats broadcast as is
    return pixel_kernel(
        standard_scale,
        gt,
        dim="band",
        name=type(self).__name__,
        mean=mean,
        std=std,
        reduce_axes=None,
    )

ZeroOne

Bases: Operator

Scale the current scene extent into [0, 1].

.. math::

y \;=\; \frac{x - \min(x)}{\max(x) - \min(x)}

Stateless per-scene min-max stretch. per_band=True (default) stretches each band independently; per_band=False uses a single global min / max. Nodata (fill / non-finite) pixels are excluded from the min / max and hold the output fill value.

Parameters:

Name Type Description Default
per_band bool

Compute min / max per band rather than globally.

True

Examples:

>>> from geoops.normalize import ZeroOne
>>> display = ZeroOne(per_band=True)(scene)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
class ZeroOne(Operator):
    r"""Scale the current scene extent into ``[0, 1]``.

    .. math::

        y \;=\; \frac{x - \min(x)}{\max(x) - \min(x)}

    Stateless per-scene min-max stretch. ``per_band=True`` (default)
    stretches each band independently; ``per_band=False`` uses a
    single global min / max. Nodata (fill / non-finite) pixels are
    excluded from the min / max and hold the output fill value.

    Args:
        per_band: Compute min / max per band rather than globally.

    Examples:
        >>> from geoops.normalize import ZeroOne
        >>> display = ZeroOne(per_band=True)(scene)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy", "jax", "dask")
    # per-band min and max over every pixel and frame of the input
    coupling: ClassVar[Coupling] = Coupling(couples={"space", "time"}, reach=None)

    def __init__(self, *, per_band: bool = True) -> None:
        self.per_band = per_band

    def _apply(self, gt: Any) -> Any:
        stats = _scene_stats(gt, per_band=self.per_band, stats=("min", "max"))
        return pixel_kernel(
            minmax_scale,
            gt,
            dim="band",
            name="ZeroOne",
            vmin=stats["min"],
            vmax=stats["max"],
            out_range=(0.0, 1.0),
            reduce_axes=None,
        )

asinh_scale(arr, *, a=1.0)

Apply inverse-hyperbolic-sine scaling.

.. math::

y \;=\; \mathrm{asinh}(x / a)

Linear near zero, logarithmic for |x| >> a; symmetric and well-defined for negative values (unlike log).

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
a float

Scale parameter marking the linear-to-log transition. Must be strictly positive. Default 1.0.

1.0

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape.

Raises:

Type Description
ValueError

If a <= 0.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def asinh_scale(
    arr: Float[np.ndarray, "*dims"], *, a: float = 1.0
) -> Float[np.ndarray, "*dims"]:
    r"""Apply inverse-hyperbolic-sine scaling.

    .. math::

        y \;=\; \mathrm{asinh}(x / a)

    Linear near zero, logarithmic for ``|x| >> a``; symmetric and
    well-defined for negative values (unlike ``log``).

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        a: Scale parameter marking the linear-to-log transition. Must
            be strictly positive. Default ``1.0``.

    Returns:
        Float array of the same shape.

    Raises:
        ValueError: If ``a <= 0``.
    """
    check_positive("a", a)
    return array_namespace(arr).asinh(arr / a)

band_quantiles(x, valid=None, *, band_axis=BAND_AXIS, q=(0.25, 0.5, 0.75))

Per-band quantiles of the valid pixels, on any backend.

:math:q_c(p) is the :math:p-th quantile (linear interpolation, as np.nanpercentile) of the valid elements of band :math:c, pooled over every axis except band_axis.

On dask an exact quantile needs every pixel of a band in one block, so dask.array.nanquantile rechunks the reduced axes to a single chunk and the band axis to "auto": a task holds whole bands, as many as fit dask's array.chunk-size (at least one), never the whole cube.

Parameters:

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

Float array with the band axis at band_axis.

required
valid Shaped[ndarray, '*dims'] | None

Boolean array broadcasting to x; False leaves an element out. Non-finite elements are always left out; None keeps every finite element.

None
band_axis int | None

The axis kept; None gives one quantile per level.

BAND_AXIS
q tuple[float, ...] | list[float]

Quantile levels in [0, 1], static (they fix the output shape).

(0.25, 0.5, 0.75)

Returns:

Type Description
Float[ndarray, 'levels ...']

(len(q), C) (or (len(q),) for band_axis=None) on x's

Float[ndarray, 'levels ...']

backend; a band without valid elements gives NaN.

Raises:

Type Description
TypeError

x is a georeader GeoTensor.

ValueError

A level outside [0, 1].

Examples:

>>> x = np.arange(8.0).reshape(2, 2, 2)  # (C=2, H=2, W=2)
>>> band_quantiles(x, q=(0.0, 0.5, 1.0))
array([[0. , 4. ],
       [1.5, 5.5],
       [3. , 7. ]])
>>> # IQR per band, nodata left out
>>> lo, hi = band_quantiles(x, x != 0.0, q=(0.25, 0.75))
>>> (hi - lo).tolist()
[1.0, 1.5]
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def band_quantiles(
    x: Float[np.ndarray, "*dims"],
    valid: Shaped[np.ndarray, "*dims"] | None = None,
    *,
    band_axis: int | None = BAND_AXIS,
    q: tuple[float, ...] | list[float] = (0.25, 0.5, 0.75),
) -> Float[np.ndarray, "levels ..."]:
    r"""Per-band quantiles of the valid pixels, on any backend.

    :math:`q_c(p)` is the :math:`p`-th quantile (linear interpolation, as
    ``np.nanpercentile``) of the valid elements of band :math:`c`, pooled
    over every axis except ``band_axis``.

    On dask an exact quantile needs every pixel of a band in one block, so
    ``dask.array.nanquantile`` rechunks the reduced axes to a single chunk
    and the band axis to ``"auto"``: a task holds whole bands, as many as fit
    dask's ``array.chunk-size`` (at least one), never the whole cube.

    Args:
        x: Float array with the band axis at ``band_axis``.
        valid: Boolean array broadcasting to ``x``; ``False`` leaves an
            element out. Non-finite elements are always left out; ``None``
            keeps every finite element.
        band_axis: The axis kept; ``None`` gives one quantile per level.
        q: Quantile levels in ``[0, 1]``, static (they fix the output shape).

    Returns:
        ``(len(q), C)`` (or ``(len(q),)`` for ``band_axis=None``) on ``x``'s
        backend; a band without valid elements gives ``NaN``.

    Raises:
        TypeError: ``x`` is a georeader ``GeoTensor``.
        ValueError: A level outside ``[0, 1]``.

    Examples:
        >>> x = np.arange(8.0).reshape(2, 2, 2)  # (C=2, H=2, W=2)
        >>> band_quantiles(x, q=(0.0, 0.5, 1.0))
        array([[0. , 4. ],
               [1.5, 5.5],
               [3. , 7. ]])
        >>> # IQR per band, nodata left out
        >>> lo, hi = band_quantiles(x, x != 0.0, q=(0.25, 0.75))
        >>> (hi - lo).tolist()
        [1.0, 1.5]
    """
    levels = np.asarray(q, dtype=float)
    if levels.ndim != 1 or np.any((levels < 0) | (levels > 1)):
        raise ValueError(f"quantile levels must be a sequence in [0, 1]; got {q}")
    xp, data, axes = _band_reduction(x, valid, band_axis, "band_quantiles")
    return xp.nanquantile(data, xp.asarray(levels, dtype=data.dtype), axis=axes)

band_stats(x, valid=None, *, band_axis=BAND_AXIS, stats=BAND_STATS)

Per-band mean, std, min and max of the valid pixels, on any backend.

.. math::

\mu_c \;=\; \frac{1}{|V_c|} \sum_{i \in V_c} x_{c,i}

where :math:V_c is the set of valid elements of band :math:c, pooled over every axis except band_axis (the frames of a (T, C, H, W) stack too), and likewise for std, min and max. Written on the array namespace: NumPy, JAX (under jax.jit too, one trace per shape) and dask, where each statistic is a lazy tree reduction.

Parameters:

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

Float array with the band axis at band_axis.

required
valid Shaped[ndarray, '*dims'] | None

Boolean array broadcasting to x; False leaves an element out of every statistic. Non-finite elements are always left out; None keeps every finite element.

None
band_axis int | None

The axis kept, one statistic per entry; None reduces globally to scalars.

BAND_AXIS
stats tuple[str, ...] | list[str]

Which of "mean", "std", "min", "max" to compute.

BAND_STATS

Returns:

Type Description
dict[str, Float[ndarray, '*stat']]

One array per requested statistic, (C,) (or scalar for

dict[str, Float[ndarray, '*stat']]

band_axis=None), on x's backend; a band without valid

dict[str, Float[ndarray, '*stat']]

elements gives NaN.

Raises:

Type Description
TypeError

x is a georeader GeoTensor.

ValueError

An unknown statistic name.

Examples:

>>> x = np.array([[[1.0, 3.0]], [[2.0, -9.0]]])  # (C=2, H=1, W=2)
>>> band_stats(x, x != -9.0, stats=("mean", "max"))
{'mean': array([2., 2.]), 'max': array([3., 2.])}
>>> # a (T, C, H, W) stack pools its frames: still one value per band
>>> band_stats(np.ones((4, 3, 2, 2)), stats=("min",))["min"].shape
(3,)
>>> float(band_stats(x, x != -9.0, band_axis=None, stats=("min",))["min"])
1.0
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def band_stats(
    x: Float[np.ndarray, "*dims"],
    valid: Shaped[np.ndarray, "*dims"] | None = None,
    *,
    band_axis: int | None = BAND_AXIS,
    stats: tuple[str, ...] | list[str] = BAND_STATS,
) -> dict[str, Float[np.ndarray, "*stat"]]:
    r"""Per-band mean, std, min and max of the valid pixels, on any backend.

    .. math::

        \mu_c \;=\; \frac{1}{|V_c|} \sum_{i \in V_c} x_{c,i}

    where :math:`V_c` is the set of valid elements of band :math:`c`, pooled
    over every axis except ``band_axis`` (the frames of a ``(T, C, H, W)``
    stack too), and likewise for ``std``, ``min`` and ``max``. Written on the
    array namespace: NumPy, JAX (under ``jax.jit`` too, one trace per shape)
    and dask, where each statistic is a lazy tree reduction.

    Args:
        x: Float array with the band axis at ``band_axis``.
        valid: Boolean array broadcasting to ``x``; ``False`` leaves an
            element out of every statistic. Non-finite elements are always
            left out; ``None`` keeps every finite element.
        band_axis: The axis kept, one statistic per entry; ``None`` reduces
            globally to scalars.
        stats: Which of ``"mean"``, ``"std"``, ``"min"``, ``"max"`` to compute.

    Returns:
        One array per requested statistic, ``(C,)`` (or scalar for
        ``band_axis=None``), on ``x``'s backend; a band without valid
        elements gives ``NaN``.

    Raises:
        TypeError: ``x`` is a georeader ``GeoTensor``.
        ValueError: An unknown statistic name.

    Examples:
        >>> x = np.array([[[1.0, 3.0]], [[2.0, -9.0]]])  # (C=2, H=1, W=2)
        >>> band_stats(x, x != -9.0, stats=("mean", "max"))
        {'mean': array([2., 2.]), 'max': array([3., 2.])}
        >>> # a (T, C, H, W) stack pools its frames: still one value per band
        >>> band_stats(np.ones((4, 3, 2, 2)), stats=("min",))["min"].shape
        (3,)
        >>> float(band_stats(x, x != -9.0, band_axis=None, stats=("min",))["min"])
        1.0
    """
    unknown = [name for name in stats if name not in BAND_STATS]
    if unknown:
        raise ValueError(f"unknown statistics {unknown}; choose from {BAND_STATS}")
    xp, data, axes = _band_reduction(x, valid, band_axis, "band_stats")
    reducers = {
        "mean": xp.nanmean,
        "std": xp.nanstd,
        "min": xp.nanmin,
        "max": xp.nanmax,
    }
    return {name: reducers[name](data, axis=axes) for name in stats}

carrier_band_stats(x, *, dim='band', per_band=True, stats=BAND_STATS, quantiles=())

Per-band statistics of a carrier's valid pixels, by dim name, on its backend.

The carrier form of band_stats and band_quantiles. The band dim is found by name, so a (time, band, y, x) stack pools its frames into one (C,) statistic per band. Nodata follows geoops' pixel rule (geoops._src.valid): a pixel is invalid in every band when any of its bands is non-finite or equals the carrier's fill, judged per frame.

Parameters:

Name Type Description Default
x Any

A NumPy or JAX GeoArray (under jax.jit too), an xr.DataArray (NumPy or dask), a DimArray or a plain 2-D to 4-D array in the layout ("time", "band", "y", "x")[-ndim:].

required
dim str

The band dim. A carrier without it gives scalar statistics.

'band'
per_band bool

False reduces over every dim, bands too, to scalars (the pixel rule still uses dim).

True
stats tuple[str, ...] | list[str]

Names for band_stats; () for none.

BAND_STATS
quantiles tuple[float, ...] | list[float]

Levels in [0, 1] for band_quantiles, returned under "quantiles" as (len(quantiles), C); () for none.

()

Returns:

Type Description
One array per statistic on the data's backend

NumPy, JAX (tracers

dict[str, Any]

under jit), or lazy dask arrays to compute together

dict[str, Any]

(dask.compute(*out.values())).

Raises:

Type Description
TypeError

x is a georeader GeoTensor.

ValueError

An unknown statistic, or a level outside [0, 1].

Examples:

>>> scene = np.array([[[1.0, 3.0]], [[2.0, np.nan]]])  # (band, y, x)
>>> # the NaN in band 1 invalidates that pixel in band 0 too
>>> carrier_band_stats(scene, stats=("mean",))
{'mean': array([1., 2.])}
>>> out = carrier_band_stats(scene, stats=(), quantiles=(0.5,))
>>> out["quantiles"].shape  # (len(quantiles), C)
(1, 2)
>>> float(carrier_band_stats(scene, per_band=False, stats=("max",))["max"])
2.0
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/operators.py
def carrier_band_stats(
    x: Any,
    *,
    dim: str = "band",
    per_band: bool = True,
    stats: tuple[str, ...] | list[str] = BAND_STATS,
    quantiles: tuple[float, ...] | list[float] = (),
) -> dict[str, Any]:
    """Per-band statistics of a carrier's valid pixels, by dim name, on its backend.

    The carrier form of `band_stats` and `band_quantiles`. The band dim is
    found by name, so a ``(time, band, y, x)`` stack pools its frames into
    one ``(C,)`` statistic per band. Nodata follows geoops' pixel rule
    (`geoops._src.valid`): a pixel is invalid in every band when any of its
    bands is non-finite or equals the carrier's fill, judged per frame.

    Args:
        x: A NumPy or JAX `GeoArray` (under ``jax.jit`` too), an
            ``xr.DataArray`` (NumPy or dask), a `DimArray` or a plain 2-D to
            4-D array in the layout ``("time", "band", "y", "x")[-ndim:]``.
        dim: The band dim. A carrier without it gives scalar statistics.
        per_band: ``False`` reduces over every dim, bands too, to scalars
            (the pixel rule still uses ``dim``).
        stats: Names for `band_stats`; ``()`` for none.
        quantiles: Levels in ``[0, 1]`` for `band_quantiles`, returned under
            ``"quantiles"`` as ``(len(quantiles), C)``; ``()`` for none.

    Returns:
        One array per statistic on the data's backend: NumPy, JAX (tracers
        under ``jit``), or lazy dask arrays to compute together
        (``dask.compute(*out.values())``).

    Raises:
        TypeError: ``x`` is a georeader ``GeoTensor``.
        ValueError: An unknown statistic, or a level outside ``[0, 1]``.

    Examples:
        >>> scene = np.array([[[1.0, 3.0]], [[2.0, np.nan]]])  # (band, y, x)
        >>> # the NaN in band 1 invalidates that pixel in band 0 too
        >>> carrier_band_stats(scene, stats=("mean",))
        {'mean': array([1., 2.])}
        >>> out = carrier_band_stats(scene, stats=(), quantiles=(0.5,))
        >>> out["quantiles"].shape  # (len(quantiles), C)
        (1, 2)
        >>> float(carrier_band_stats(scene, per_band=False, stats=("max",))["max"])
        2.0
    """
    view = _pixel_view(x, dim, "carrier_band_stats")
    axis = view.band_axis if per_band else None
    out = dict(band_stats(view.data, view.valid, band_axis=axis, stats=stats))
    if quantiles:
        out["quantiles"] = band_quantiles(
            view.data, view.valid, band_axis=axis, q=quantiles
        )
    return out

clahe(arr, *, window=None, clip_limit=0.01, nbins=256)

Apply contrast-limited adaptive histogram equalization per image band.

The algorithm of :func:skimage.exposure.equalize_adapthist, written on the array namespace so it runs on NumPy and on JAX (under jax.jit too, one trace per shape) without scikit-image. Each (H, W) slice (every band of a (C, H, W) cube, every band of every frame of a (T, C, H, W) stack) is equalized independently:

  1. rescale to [0, 1] over its finite range, quantise to 14-bit grey levels and bin them into nbins;
  2. reflect-pad to whole tiles of window, take each tile's histogram, clip it at clip_limit times the tile size and redistribute the excess as scikit-image does;
  3. map each pixel through the cumulative histograms of its four nearest tiles, blended bilinearly, and map the result back to native units.

NaN pixels are excluded (filled with the slice median before the histograms, as before) and stay NaN. A constant or all-NaN slice is returned unchanged.

Parameters:

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

Input array; trailing axes are (H, W).

required
window int | tuple[int, int] | None

Contextual-region shape for the local histograms. None uses scikit-image's default (1/8 of the slice height / width).

None
clip_limit float

Contrast-limiting clip threshold in [0, 1]. Default 0.01.

0.01
nbins int

Number of histogram bins. Default 256.

256

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape, equalized per band.

Examples:

>>> ramp = np.linspace(0.0, 1.0, 64).reshape(8, 8) ** 2
>>> out = clahe(ramp, window=4)
>>> out.shape, float(out.min()), float(out.max())
((8, 8), 0.0, 1.0)
>>> # a stack is equalized slice by slice
>>> clahe(np.stack([ramp, ramp]), window=4).shape
(2, 8, 8)
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def clahe(
    arr: Shaped[np.ndarray, "*dims"],
    *,
    window: int | tuple[int, int] | None = None,
    clip_limit: float = 0.01,
    nbins: int = 256,
) -> Float[np.ndarray, "*dims"]:
    """Apply contrast-limited adaptive histogram equalization per image band.

    The algorithm of :func:`skimage.exposure.equalize_adapthist`, written on
    the array namespace so it runs on NumPy and on JAX (under ``jax.jit`` too,
    one trace per shape) without scikit-image. Each ``(H, W)`` slice (every
    band of a ``(C, H, W)`` cube, every band of every frame of a
    ``(T, C, H, W)`` stack) is equalized independently:

    1. rescale to ``[0, 1]`` over its finite range, quantise to 14-bit grey
       levels and bin them into ``nbins``;
    2. reflect-pad to whole tiles of ``window``, take each tile's histogram,
       clip it at ``clip_limit`` times the tile size and redistribute the
       excess as scikit-image does;
    3. map each pixel through the cumulative histograms of its four nearest
       tiles, blended bilinearly, and map the result back to native units.

    NaN pixels are excluded (filled with the slice median before the
    histograms, as before) and stay NaN. A constant or all-NaN slice is
    returned unchanged.

    Args:
        arr: Input array; trailing axes are ``(H, W)``.
        window: Contextual-region shape for the local histograms.
            ``None`` uses scikit-image's default (1/8 of the slice height /
            width).
        clip_limit: Contrast-limiting clip threshold in ``[0, 1]``.
            Default ``0.01``.
        nbins: Number of histogram bins. Default ``256``.

    Returns:
        Float array of the same shape, equalized per band.

    Examples:
        >>> ramp = np.linspace(0.0, 1.0, 64).reshape(8, 8) ** 2
        >>> out = clahe(ramp, window=4)
        >>> out.shape, float(out.min()), float(out.max())
        ((8, 8), 0.0, 1.0)
        >>> # a stack is equalized slice by slice
        >>> clahe(np.stack([ramp, ramp]), window=4).shape
        (2, 8, 8)
    """
    xp = namespace_of(arr)
    values = arr if arr.dtype == np.float64 else arr.astype(np.float64)
    shape = values.shape
    height, width = shape[-2:]
    kernel = _clahe_kernel(window, (height, width))
    v = xp.reshape(values, (-1, height, width))
    valid = xp.isfinite(v)
    vmin = xp.min(xp.where(valid, v, xp.inf), axis=(-2, -1), keepdims=True)
    vmax = xp.max(xp.where(valid, v, -xp.inf), axis=(-2, -1), keepdims=True)
    ok = vmax > vmin  # False for a constant or all-NaN slice
    span = xp.where(ok, vmax - vmin, 1.0)
    low = xp.where(ok, vmin, 0.0)
    median = xp.nanmedian(xp.where(ok & valid, v, xp.nan), axis=(-2, -1), keepdims=True)
    unit = xp.where(valid, (v - low) / span, (median - low) / span)
    unit = xp.where(ok, xp.clip(unit, 0.0, 1.0), 0.0)
    equalized = _equalize_adapthist(unit, kernel, clip_limit, nbins, xp)
    out = xp.where(valid & ok, equalized * span + low, v)
    return xp.reshape(out, shape)

histogram_match(source, reference)

Match source values to the empirical CDF of reference.

Per-band monotone remapping: each source value is replaced by the reference value at the same empirical quantile (reference_cdf then match_cdf). NaN pixels in the source are left untouched; NaNs in the reference are excluded from its CDF.

Parameters:

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

Array to remap. If 3-D+ ((C, H, W)), bands are matched independently.

required
reference Float[ndarray, '*ref']

Reference array. Either band-matched (same leading band count as source) or a single 2-D map applied to every source band.

required

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as source with its per-band

Float[ndarray, '*dims']

histograms reshaped to the reference.

Example

histogram_match(np.array([[0.0, 1.0, 2.0]]), np.array([[10.0, 20.0, 30.0]])) array([[10., 20., 30.]])

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def histogram_match(
    source: Float[np.ndarray, "*dims"],
    reference: Float[np.ndarray, "*ref"],
) -> Float[np.ndarray, "*dims"]:
    """Match source values to the empirical CDF of ``reference``.

    Per-band monotone remapping: each source value is replaced by the
    reference value at the same empirical quantile (`reference_cdf` then
    `match_cdf`). NaN pixels in the source are left untouched; NaNs in the
    reference are excluded from its CDF.

    Args:
        source: Array to remap. If 3-D+ (``(C, H, W)``), bands are
            matched independently.
        reference: Reference array. Either band-matched (same leading
            band count as ``source``) or a single 2-D map applied to
            every source band.

    Returns:
        Float array of the same shape as ``source`` with its per-band
        histograms reshaped to the reference.

    Example:
        >>> histogram_match(np.array([[0.0, 1.0, 2.0]]), np.array([[10.0, 20.0, 30.0]]))
        array([[10., 20., 30.]])
    """
    source = np.asarray(source, dtype=float)
    reference = np.asarray(reference, dtype=float)
    banded = source.ndim >= 3 and (
        reference.ndim == 2
        or (reference.ndim >= 3 and source.shape[0] == reference.shape[0])
    )
    n_bands = source.shape[0] if banded else 1
    flat = source.reshape(n_bands, -1)
    ref = reference.reshape(1 if reference.ndim == 2 or not banded else n_bands, -1)
    table = reference_cdf(ref, np.isfinite(ref))
    if table[0].shape[0] != n_bands:  # one 2-D map for every band
        table = tuple(np.repeat(t, n_bands, axis=0) for t in table)
    return match_cdf(flat, np.isfinite(flat), *table).reshape(source.shape)

inverse_minmax_scale(arr, vmin, vmax, *, out_range=(0.0, 1.0), reduce_axes=(-2, -1))

Undo :func:minmax_scale: map out_range back onto [vmin, vmax].

.. math::

x \;=\; \frac{y - o_{\min}}{o_{\max} - o_{\min}}
        \cdot (v_{\max} - v_{\min}) + v_{\min}

Parameters:

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

Scaled float array. NaN pixels propagate through untouched.

required
vmin Float[ndarray, '*stat'] | float

Scalar or per-band lower bound, as for minmax_scale.

required
vmax Float[ndarray, '*stat'] | float

Scalar or per-band upper bound; vmax <= vmin reads the span as 1.

required
out_range tuple[float, float]

The (out_min, out_max) range minmax_scale mapped into. Default (0.0, 1.0).

(0.0, 1.0)
reduce_axes tuple[int, ...] | None

Axes the bounds were reduced over. Default (-2, -1); None for global bounds.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr.

Raises:

Type Description
TypeError

arr is a georeader GeoTensor.

ValueError

If out_range is not a two-element increasing tuple.

Examples:

>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_minmax_scale(minmax_scale(x, 1.0, 3.0), 1.0, 3.0)
array([[[1., 3.]]])
>>> y = minmax_scale(x, 1.0, 3.0, out_range=(0.0, 255.0))
>>> inverse_minmax_scale(y, 1.0, 3.0, out_range=(0.0, 255.0))
array([[[1., 3.]]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def inverse_minmax_scale(
    arr: Float[np.ndarray, "*dims"],
    vmin: Float[np.ndarray, "*stat"] | float,
    vmax: Float[np.ndarray, "*stat"] | float,
    *,
    out_range: tuple[float, float] = (0.0, 1.0),
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Undo :func:`minmax_scale`: map ``out_range`` back onto ``[vmin, vmax]``.

    .. math::

        x \;=\; \frac{y - o_{\min}}{o_{\max} - o_{\min}}
                \cdot (v_{\max} - v_{\min}) + v_{\min}

    Args:
        arr: Scaled float array. NaN pixels propagate through untouched.
        vmin: Scalar or per-band lower bound, as for `minmax_scale`.
        vmax: Scalar or per-band upper bound; ``vmax <= vmin`` reads the
            span as ``1``.
        out_range: The ``(out_min, out_max)`` range `minmax_scale` mapped
            into. Default ``(0.0, 1.0)``.
        reduce_axes: Axes the bounds were reduced over. Default
            ``(-2, -1)``; ``None`` for global bounds.

    Returns:
        Float array of the same shape as ``arr``.

    Raises:
        TypeError: ``arr`` is a georeader ``GeoTensor``.
        ValueError: If ``out_range`` is not a two-element increasing tuple.

    Examples:
        >>> x = np.array([[[1.0, 3.0]]])
        >>> inverse_minmax_scale(minmax_scale(x, 1.0, 3.0), 1.0, 3.0)
        array([[[1., 3.]]])
        >>> y = minmax_scale(x, 1.0, 3.0, out_range=(0.0, 255.0))
        >>> inverse_minmax_scale(y, 1.0, 3.0, out_range=(0.0, 255.0))
        array([[[1., 3.]]])
    """
    reject_geotensor(arr, "inverse_minmax_scale")
    out_min, out_max = validate_out_range(out_range)
    vmin_b = reshape_stat(vmin, arr, reduce_axes)
    vmax_b = reshape_stat(vmax, arr, reduce_axes)
    span = namespace_of(arr).where(vmax_b > vmin_b, vmax_b - vmin_b, 1.0)
    return (arr - out_min) / (out_max - out_min) * span + vmin_b

inverse_robust_scale(arr, median, iqr, *, reduce_axes=(-2, -1))

Undo :func:robust_scale.

.. math::

x \;=\; y \cdot (Q_{3} - Q_{1}) + \mathrm{median}

Parameters:

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

Scaled float array. NaN pixels propagate through untouched.

required
median Float[ndarray, '*stat'] | float

Scalar or per-band median, as for robust_scale.

required
iqr Float[ndarray, '*stat'] | float

Scalar or per-band interquartile range; a zero iqr is read as 1.

required
reduce_axes tuple[int, ...] | None

Axes the statistics were reduced over. Default (-2, -1); None for global statistics.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr.

Raises:

Type Description
TypeError

arr is a georeader GeoTensor.

Examples:

>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_robust_scale(robust_scale(x, 2.0, 4.0), 2.0, 4.0)
array([[[1., 3.]]])
>>> # per-band statistics for a (C, H, W) cube
>>> cube = np.ones((2, 1, 2))
>>> inverse_robust_scale(cube, [0.0, 1.0], [2.0, 3.0])[:, 0, 0]
array([2., 4.])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def inverse_robust_scale(
    arr: Float[np.ndarray, "*dims"],
    median: Float[np.ndarray, "*stat"] | float,
    iqr: Float[np.ndarray, "*stat"] | float,
    *,
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Undo :func:`robust_scale`.

    .. math::

        x \;=\; y \cdot (Q_{3} - Q_{1}) + \mathrm{median}

    Args:
        arr: Scaled float array. NaN pixels propagate through untouched.
        median: Scalar or per-band median, as for `robust_scale`.
        iqr: Scalar or per-band interquartile range; a zero ``iqr`` is
            read as ``1``.
        reduce_axes: Axes the statistics were reduced over. Default
            ``(-2, -1)``; ``None`` for global statistics.

    Returns:
        Float array of the same shape as ``arr``.

    Raises:
        TypeError: ``arr`` is a georeader ``GeoTensor``.

    Examples:
        >>> x = np.array([[[1.0, 3.0]]])
        >>> inverse_robust_scale(robust_scale(x, 2.0, 4.0), 2.0, 4.0)
        array([[[1., 3.]]])
        >>> # per-band statistics for a (C, H, W) cube
        >>> cube = np.ones((2, 1, 2))
        >>> inverse_robust_scale(cube, [0.0, 1.0], [2.0, 3.0])[:, 0, 0]
        array([2., 4.])
    """
    reject_geotensor(arr, "inverse_robust_scale")
    median_b = reshape_stat(median, arr, reduce_axes)
    iqr_b = reshape_stat(iqr, arr, reduce_axes)
    return arr * namespace_of(arr).where(iqr_b != 0, iqr_b, 1.0) + median_b

inverse_standard_scale(arr, mean, std, *, reduce_axes=(-2, -1))

Undo :func:standard_scale.

.. math::

x \;=\; y \cdot \sigma + \mu

Parameters:

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

Scaled float array. NaN pixels propagate through untouched.

required
mean Float[ndarray, '*stat'] | float

Scalar or per-band mean :math:\mu, as for standard_scale.

required
std Float[ndarray, '*stat'] | float

Scalar or per-band standard deviation :math:\sigma; a zero std is read as 1, as standard_scale divides by it.

required
reduce_axes tuple[int, ...] | None

Axes the statistics were reduced over. Default (-2, -1); None for global statistics.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr.

Raises:

Type Description
TypeError

arr is a georeader GeoTensor.

Examples:

>>> x = np.array([[[1.0, 3.0]]])
>>> inverse_standard_scale(standard_scale(x, 2.0, 0.5), 2.0, 0.5)
array([[[1., 3.]]])
>>> # a constant band (std 0) round-trips too
>>> inverse_standard_scale(standard_scale(x, 1.0, 0.0), 1.0, 0.0)
array([[[1., 3.]]])
Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def inverse_standard_scale(
    arr: Float[np.ndarray, "*dims"],
    mean: Float[np.ndarray, "*stat"] | float,
    std: Float[np.ndarray, "*stat"] | float,
    *,
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Undo :func:`standard_scale`.

    .. math::

        x \;=\; y \cdot \sigma + \mu

    Args:
        arr: Scaled float array. NaN pixels propagate through untouched.
        mean: Scalar or per-band mean :math:`\mu`, as for `standard_scale`.
        std: Scalar or per-band standard deviation :math:`\sigma`; a zero
            ``std`` is read as ``1``, as `standard_scale` divides by it.
        reduce_axes: Axes the statistics were reduced over. Default
            ``(-2, -1)``; ``None`` for global statistics.

    Returns:
        Float array of the same shape as ``arr``.

    Raises:
        TypeError: ``arr`` is a georeader ``GeoTensor``.

    Examples:
        >>> x = np.array([[[1.0, 3.0]]])
        >>> inverse_standard_scale(standard_scale(x, 2.0, 0.5), 2.0, 0.5)
        array([[[1., 3.]]])
        >>> # a constant band (std 0) round-trips too
        >>> inverse_standard_scale(standard_scale(x, 1.0, 0.0), 1.0, 0.0)
        array([[[1., 3.]]])
    """
    reject_geotensor(arr, "inverse_standard_scale")
    mean_b = reshape_stat(mean, arr, reduce_axes)
    std_b = reshape_stat(std, arr, reduce_axes)
    return arr * namespace_of(arr).where(std_b != 0, std_b, 1.0) + mean_b

log_scale(arr, *, base=10.0, eps=1e-06)

Apply log scaling with a small offset for zero-valued pixels.

.. math::

y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)

Compresses heavy-tailed distributions (radar backscatter, fire radiative power, ...). Negative inputs are clipped to zero before the log; eps keeps the log finite at zero.

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
base float

Logarithm base. Must be positive and not equal to 1. Default 10.0.

10.0
eps float

Small positive offset added before the log. Default 1e-6.

1e-06

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape.

Raises:

Type Description
ValueError

If base or eps is out of range.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def log_scale(
    arr: Float[np.ndarray, "*dims"], *, base: float = 10.0, eps: float = 1e-6
) -> Float[np.ndarray, "*dims"]:
    r"""Apply log scaling with a small offset for zero-valued pixels.

    .. math::

        y \;=\; \log_{\text{base}}(\max(x, 0) + \epsilon)

    Compresses heavy-tailed distributions (radar backscatter, fire
    radiative power, ...). Negative inputs are clipped to zero before
    the log; ``eps`` keeps the log finite at zero.

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        base: Logarithm base. Must be positive and not equal to ``1``.
            Default ``10.0``.
        eps: Small positive offset added before the log. Default
            ``1e-6``.

    Returns:
        Float array of the same shape.

    Raises:
        ValueError: If ``base`` or ``eps`` is out of range.
    """
    check_log_scale(base, eps)
    xp = array_namespace(arr)
    return xp.log(xp.maximum(arr, 0.0) + eps) / math.log(base)

match_cdf(x, valid, levels, values, ok)

Map each band of x through its CDF onto a reference_cdf table.

.. math::

y \;=\; G_c^{-1}\big(F_c(x)\big), \qquad
F_c(x) \;=\; \frac{\#\{\text{valid } x' \le x\}}{n_c}

:math:F_c comes from a sort and searchsorted (invalid values sort last as +inf), and :math:G_c^{-1} is a linear interpolation through the table, so this is exact rank matching with static shapes: it runs on NumPy and JAX, under jax.jit too (one trace per shape), and on a dask block holding whole bands.

Parameters:

Name Type Description Default
x Float[ndarray, 'C N']

(C, N) float values, one band per row.

required
valid Shaped[ndarray, 'C N']

(C, N) booleans; False leaves a value out of the CDF.

required
levels Float[ndarray, 'C M']

(C, M) fractions from reference_cdf.

required
values Float[ndarray, 'C M']

(C, M) values from reference_cdf.

required
ok Shaped[ndarray, 'C 1']

(C, 1) from reference_cdf; a band whose reference has no valid value keeps x.

required

Returns:

Type Description
Float[ndarray, 'C N']

(C, N) on x's backend; invalid entries keep x's value.

Example

table = reference_cdf(np.array([[10.0, 20.0, 30.0]]), None) x = np.array([[2.0, 0.0, 1.0]]) match_cdf(x, np.isfinite(x), *table) array([[30., 10., 20.]])

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def match_cdf(
    x: Float[np.ndarray, "C N"],
    valid: Shaped[np.ndarray, "C N"],
    levels: Float[np.ndarray, "C M"],
    values: Float[np.ndarray, "C M"],
    ok: Shaped[np.ndarray, "C 1"],
) -> Float[np.ndarray, "C N"]:
    r"""Map each band of ``x`` through its CDF onto a `reference_cdf` table.

    .. math::

        y \;=\; G_c^{-1}\big(F_c(x)\big), \qquad
        F_c(x) \;=\; \frac{\#\{\text{valid } x' \le x\}}{n_c}

    :math:`F_c` comes from a sort and ``searchsorted`` (invalid values sort
    last as ``+inf``), and :math:`G_c^{-1}` is a linear interpolation through
    the table, so this is exact rank matching with static shapes: it runs on
    NumPy and JAX, under ``jax.jit`` too (one trace per shape), and on a
    dask block holding whole bands.

    Args:
        x: ``(C, N)`` float values, one band per row.
        valid: ``(C, N)`` booleans; ``False`` leaves a value out of the CDF.
        levels: ``(C, M)`` fractions from `reference_cdf`.
        values: ``(C, M)`` values from `reference_cdf`.
        ok: ``(C, 1)`` from `reference_cdf`; a band whose reference has no
            valid value keeps ``x``.

    Returns:
        ``(C, N)`` on ``x``'s backend; invalid entries keep ``x``'s value.

    Example:
        >>> table = reference_cdf(np.array([[10.0, 20.0, 30.0]]), None)
        >>> x = np.array([[2.0, 0.0, 1.0]])
        >>> match_cdf(x, np.isfinite(x), *table)
        array([[30., 10., 20.]])
    """
    xp = namespace_of(x)
    count = xp.sum(valid, axis=-1, keepdims=True)
    ordered = xp.sort(xp.where(valid, x, xp.inf), axis=-1)
    rows = []
    for band in range(x.shape[0]):
        rank = xp.searchsorted(ordered[band], x[band], side="right")
        fraction = rank / xp.maximum(count[band], 1)
        rows.append(xp.interp(fraction, levels[band], values[band]))
    matched = xp.stack(rows)
    return xp.where(valid & (count > 0) & ok, matched, x)

minmax_scale(arr, vmin, vmax, *, out_range=(0.0, 1.0), reduce_axes=(-2, -1))

Linearly map [vmin, vmax] into out_range.

.. math::

y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
        \cdot (o_{\max} - o_{\min}) + o_{\min}

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
vmin Float[ndarray, '*stat'] | float

Scalar or per-band lower bound (maps to out_range[0]).

required
vmax Float[ndarray, '*stat'] | float

Scalar or per-band upper bound (maps to out_range[1]). Bands with vmax <= vmin fall back to a divisor of 1.

required
out_range tuple[float, float]

(out_min, out_max) target range; must be increasing. Default (0.0, 1.0).

(0.0, 1.0)
reduce_axes tuple[int, ...] | None

Axes the bounds were reduced over. Default (-2, -1); None for global bounds.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr. Values outside

Float[ndarray, '*dims']

[vmin, vmax] are not clipped.

Raises:

Type Description
ValueError

If out_range is not a two-element increasing tuple.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def minmax_scale(
    arr: Float[np.ndarray, "*dims"],
    vmin: Float[np.ndarray, "*stat"] | float,
    vmax: Float[np.ndarray, "*stat"] | float,
    *,
    out_range: tuple[float, float] = (0.0, 1.0),
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Linearly map ``[vmin, vmax]`` into ``out_range``.

    .. math::

        y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}
                \cdot (o_{\max} - o_{\min}) + o_{\min}

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        vmin: Scalar or per-band lower bound (maps to ``out_range[0]``).
        vmax: Scalar or per-band upper bound (maps to ``out_range[1]``).
            Bands with ``vmax <= vmin`` fall back to a divisor of ``1``.
        out_range: ``(out_min, out_max)`` target range; must be
            increasing. Default ``(0.0, 1.0)``.
        reduce_axes: Axes the bounds were reduced over. Default ``(-2, -1)``;
            ``None`` for global bounds.

    Returns:
        Float array of the same shape as ``arr``. Values outside
        ``[vmin, vmax]`` are *not* clipped.

    Raises:
        ValueError: If ``out_range`` is not a two-element increasing
            tuple.
    """
    out_min, out_max = validate_out_range(out_range)
    vmin_b = reshape_stat(vmin, arr, reduce_axes)
    vmax_b = reshape_stat(vmax, arr, reduce_axes)
    denom = namespace_of(arr).where(vmax_b > vmin_b, vmax_b - vmin_b, 1.0)
    return (arr - vmin_b) / denom * (out_max - out_min) + out_min

per_band_stats(arr, *, percentiles=(1.0, 99.0), reduce_axes=(-2, -1))

Compute NaN-aware statistics over spatial axes.

Parameters:

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

Input float array, typically a channel-first (C, H, W) cube. NaN pixels are excluded from every statistic.

required
percentiles list[float] | tuple[float, ...]

Percentiles (in [0, 100]) to compute alongside the moments. Default (1.0, 99.0).

(1.0, 99.0)
reduce_axes tuple[int, ...] | None

Axes to reduce over. Default (-2, -1) yields one value per band; None reduces globally.

(-2, -1)

Returns:

Type Description
dict[str, ndarray]

Dict with keys "mean", "std", "min", "max"

dict[str, ndarray]

(each shaped like the kept axes, e.g. (C,)) and

dict[str, ndarray]

"percentiles" of shape (len(percentiles), C).

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def per_band_stats(
    arr: Float[np.ndarray, "*dims"],
    *,
    percentiles: list[float] | tuple[float, ...] = (1.0, 99.0),
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> dict[str, np.ndarray]:
    """Compute NaN-aware statistics over spatial axes.

    Args:
        arr: Input float array, typically a channel-first ``(C, H, W)``
            cube. NaN pixels are excluded from every statistic.
        percentiles: Percentiles (in ``[0, 100]``) to compute alongside
            the moments. Default ``(1.0, 99.0)``.
        reduce_axes: Axes to reduce over. Default ``(-2, -1)`` yields one value
            per band; ``None`` reduces globally.

    Returns:
        Dict with keys ``"mean"``, ``"std"``, ``"min"``, ``"max"``
        (each shaped like the kept axes, e.g. ``(C,)``) and
        ``"percentiles"`` of shape ``(len(percentiles), C)``.
    """
    return {
        "mean": np.nanmean(arr, axis=reduce_axes),
        "std": np.nanstd(arr, axis=reduce_axes),
        "min": np.nanmin(arr, axis=reduce_axes),
        "max": np.nanmax(arr, axis=reduce_axes),
        "percentiles": np.nanpercentile(arr, percentiles, axis=reduce_axes),
    }

power_scale(arr, *, gamma=0.5)

Apply non-negative power scaling.

.. math::

y \;=\; \max(x, 0)^{\gamma}

A simple gamma-style brightness curve; negative inputs are clipped to zero before the power to avoid complex results.

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
gamma float

Power exponent. < 1 brightens midtones, > 1 darkens. Must be strictly positive. Default 0.5.

0.5

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape.

Raises:

Type Description
ValueError

If gamma <= 0.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def power_scale(
    arr: Float[np.ndarray, "*dims"], *, gamma: float = 0.5
) -> Float[np.ndarray, "*dims"]:
    r"""Apply non-negative power scaling.

    .. math::

        y \;=\; \max(x, 0)^{\gamma}

    A simple gamma-style brightness curve; negative inputs are clipped
    to zero before the power to avoid complex results.

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        gamma: Power exponent. ``< 1`` brightens midtones, ``> 1``
            darkens. Must be strictly positive. Default ``0.5``.

    Returns:
        Float array of the same shape.

    Raises:
        ValueError: If ``gamma <= 0``.
    """
    check_positive("gamma", gamma)
    return array_namespace(arr).maximum(arr, 0.0) ** gamma

reference_cdf(reference, valid)

The per-band empirical CDF of reference, as a padded table for match_cdf.

For each band, the distinct valid values :math:v_1 < \dots < v_m and their cumulative fractions :math:G(v_k) = \#\{x \le v_k\} / n, the points that scikit-image's match_histograms interpolates through. Bands have different numbers of distinct values, so each row is padded to the longest with levels above 1 and its maximum, which an interpolation at a fraction in [0, 1] never reaches. Host NumPy only: a reference is concrete, and its table is a constant for match_cdf.

Parameters:

Name Type Description Default
reference Float[ndarray, 'C N']

(C, N) values, one band per row.

required
valid Shaped[ndarray, 'C N']

(C, N) booleans; False leaves a value out.

required

Returns:

Type Description
``(levels, values, ok)``

(C, M) fractions, (C, M) values, and

Float[ndarray, 'C M']

(C, 1) whether the band has any valid value.

Example

levels, values, ok = reference_cdf(np.array([[1.0, 1.0, 3.0]]), None) levels.tolist(), values.tolist(), ok.tolist() ([[0.6666666666666666, 1.0]], [[1.0, 3.0]], [[True]])

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def reference_cdf(
    reference: Float[np.ndarray, "C N"], valid: Shaped[np.ndarray, "C N"]
) -> tuple[
    Float[np.ndarray, "C M"], Float[np.ndarray, "C M"], Shaped[np.ndarray, "C 1"]
]:
    r"""The per-band empirical CDF of ``reference``, as a padded table for `match_cdf`.

    For each band, the distinct valid values :math:`v_1 < \dots < v_m` and
    their cumulative fractions :math:`G(v_k) = \#\{x \le v_k\} / n`, the
    points that scikit-image's ``match_histograms`` interpolates through.
    Bands have different numbers of distinct values, so each row is padded to
    the longest with levels above ``1`` and its maximum, which an
    interpolation at a fraction in ``[0, 1]`` never reaches. Host NumPy only:
    a reference is concrete, and its table is a constant for `match_cdf`.

    Args:
        reference: ``(C, N)`` values, one band per row.
        valid: ``(C, N)`` booleans; ``False`` leaves a value out.

    Returns:
        ``(levels, values, ok)``: ``(C, M)`` fractions, ``(C, M)`` values, and
        ``(C, 1)`` whether the band has any valid value.

    Example:
        >>> levels, values, ok = reference_cdf(np.array([[1.0, 1.0, 3.0]]), None)
        >>> levels.tolist(), values.tolist(), ok.tolist()
        ([[0.6666666666666666, 1.0]], [[1.0, 3.0]], [[True]])
    """
    reference = np.asarray(reference, dtype=float)
    if valid is None:
        valid = np.isfinite(reference)
    rows = []
    for band, keep in zip(reference, np.asarray(valid, dtype=bool), strict=True):
        values, counts = np.unique(band[keep], return_counts=True)
        rows.append((np.cumsum(counts) / max(int(keep.sum()), 1), values))
    width = max(1, *(values.size for _, values in rows))
    levels = np.empty((len(rows), width))
    table = np.empty((len(rows), width))
    for row, (fractions, values) in enumerate(rows):
        m = values.size
        levels[row, :m] = fractions
        levels[row, m:] = 2.0 + np.arange(width - m)
        table[row, :m] = values
        table[row, m:] = values[-1] if m else np.nan
    ok = np.array([[values.size > 0] for _, values in rows], dtype=bool)
    return levels, table, ok

robust_scale(arr, median, iqr, *, reduce_axes=(-2, -1))

Apply median/IQR scaling while preserving NaN pixels.

.. math::

y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}

The outlier-robust counterpart of :func:standard_scale — bright outliers (clouds, glint, saturation) barely move the median and interquartile range.

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
median Float[ndarray, '*stat'] | float

Scalar or per-band median (shape matching the kept axes).

required
iqr Float[ndarray, '*stat'] | float

Scalar or per-band interquartile range Q3 - Q1. Bands with iqr == 0 fall back to a divisor of 1.

required
reduce_axes tuple[int, ...] | None

Axes the statistics were reduced over. Default (-2, -1); None for global statistics.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def robust_scale(
    arr: Float[np.ndarray, "*dims"],
    median: Float[np.ndarray, "*stat"] | float,
    iqr: Float[np.ndarray, "*stat"] | float,
    *,
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Apply median/IQR scaling while preserving NaN pixels.

    .. math::

        y \;=\; \frac{x - \mathrm{median}}{Q_{3} - Q_{1}}

    The outlier-robust counterpart of :func:`standard_scale` — bright
    outliers (clouds, glint, saturation) barely move the median and
    interquartile range.

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        median: Scalar or per-band median (shape matching the kept
            axes).
        iqr: Scalar or per-band interquartile range ``Q3 - Q1``. Bands
            with ``iqr == 0`` fall back to a divisor of ``1``.
        reduce_axes: Axes the statistics were reduced over. Default
            ``(-2, -1)``; ``None`` for global statistics.

    Returns:
        Float array of the same shape as ``arr``.
    """
    median_b = reshape_stat(median, arr, reduce_axes)
    iqr_b = reshape_stat(iqr, arr, reduce_axes)
    denom = namespace_of(arr).where(iqr_b != 0, iqr_b, 1.0)
    return (arr - median_b) / denom

standard_scale(arr, mean, std, *, reduce_axes=(-2, -1))

Apply z-score scaling while preserving NaN pixels.

.. math::

y \;=\; \frac{x - \mu}{\sigma}

Parameters:

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

Input float array. NaN pixels propagate through untouched.

required
mean Float[ndarray, '*stat'] | float

Scalar or per-band mean :math:\mu (shape matching the kept axes, e.g. (C,) for a (C, H, W) input).

required
std Float[ndarray, '*stat'] | float

Scalar or per-band standard deviation :math:\sigma. Bands with std == 0 fall back to a divisor of 1 so a constant band maps to zero instead of inf / nan.

required
reduce_axes tuple[int, ...] | None

Axes the statistics were reduced over. Default (-2, -1); None for global statistics.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape as arr.

Source code in packages/geotoolz-ops/src/geoops/normalize/_src/array.py
def standard_scale(
    arr: Float[np.ndarray, "*dims"],
    mean: Float[np.ndarray, "*stat"] | float,
    std: Float[np.ndarray, "*stat"] | float,
    *,
    reduce_axes: tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Apply z-score scaling while preserving NaN pixels.

    .. math::

        y \;=\; \frac{x - \mu}{\sigma}

    Args:
        arr: Input float array. NaN pixels propagate through untouched.
        mean: Scalar or per-band mean :math:`\mu` (shape matching the
            kept axes, e.g. ``(C,)`` for a ``(C, H, W)`` input).
        std: Scalar or per-band standard deviation :math:`\sigma`. Bands
            with ``std == 0`` fall back to a divisor of ``1`` so a
            constant band maps to zero instead of ``inf`` / ``nan``.
        reduce_axes: Axes the statistics were reduced over. Default
            ``(-2, -1)``; ``None`` for global statistics.

    Returns:
        Float array of the same shape as ``arr``.
    """
    mean_b = reshape_stat(mean, arr, reduce_axes)
    std_b = reshape_stat(std, arr, reduce_axes)
    denom = namespace_of(arr).where(std_b != 0, std_b, 1.0)
    return (arr - mean_b) / denom