Skip to content

Spectral

Band-space operators — selection, math, spectral response, continuum removal — for hyperspectral and multispectral cubes.

  • Band selection: SelectBands, ReorderBands, SplitBands, StackBands — by index or name (StackBands requires every input on the same grid with the same fill_value)
  • Band math: BandMath (restricted arithmetic expression over named bands), BandRatio
  • Spectral resampling: SpectralBinning, SpectralSmoothing
  • Continuum removal: ContinuumRemoval
  • Tier-A primitives: select_bands, reorder_bands, band_ratio, evaluate_band_math, spectral_binning, spectral_smoothing, continuum_removal

The normalized difference is indices.NormalizedDifference and the Gaussian spectral-response convolution is radiometry.ApplySRF; the former spectral.NormalizedDifference, spectral.ApplySRF and spectral.GaussianSRF duplicates were removed.

geoops.spectral

Band-space operators for spectral remote-sensing workflows.

Band selection / reordering / stacking / splitting, band math and ratios, spectral binning and smoothing, and continuum removal. The normalized difference lives in :mod:geoops.indices (:class:~geoops.indices.NormalizedDifference) and the Gaussian-SRF convolution in :mod:geoops.radiometry (:class:~geoops.radiometry.ApplySRF).

BandMath

Bases: Operator

Evaluate a restricted arithmetic expression over named bands.

The expression is parsed with Python's ast module and only permits constants, unary +/-, binary + - * / **, and the whitelisted functions abs, sqrt, log, log10, exp, where, minimum, maximum, clip. Band variables resolve to slices along the band axis named by band_names (default: the carrier's band names from gt.attrs — band_names, then descriptions, then bands — or synthetic B0, B1, ... labels). Plain np.ndarray input is supported (synthetic B0, B1, ... names apply unless band_names is given) and returns a plain array.

Parameters:

Name Type Description Default
expression str

Arithmetic expression over band names, e.g. "(B8 - B4) / (B8 + B4 + 1e-6)".

required
band_names list[str] | None

Override for the names used in expression. Default None (read from the carrier's attrs).

None
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # NDVI by name (assumes gt.attrs["band_names"] contains B4/B8).
>>> ndvi = spectral.BandMath(expression="(B8 - B4) / (B8 + B4 + 1e-6)")
>>> ndvi_map = ndvi(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class BandMath(Operator):
    """Evaluate a restricted arithmetic expression over named bands.

    The expression is parsed with Python's ``ast`` module and only
    permits constants, unary +/-, binary ``+ - * / **``, and the
    whitelisted functions ``abs, sqrt, log, log10, exp, where, minimum,
    maximum, clip``. Band variables resolve to slices along the band
    axis named by ``band_names`` (default: the carrier's band names from
    ``gt.attrs`` — ``band_names``, then ``descriptions``, then ``bands`` —
    or synthetic ``B0, B1, ...`` labels). Plain ``np.ndarray`` input is
    supported (synthetic ``B0, B1, ...`` names apply unless
    ``band_names`` is given) and returns a plain array.

    Args:
        expression: Arithmetic expression over band names, e.g.
            ``"(B8 - B4) / (B8 + B4 + 1e-6)"``.
        band_names: Override for the names used in ``expression``.
            Default ``None`` (read from the carrier's ``attrs``).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # NDVI by name (assumes gt.attrs["band_names"] contains B4/B8).
        >>> ndvi = spectral.BandMath(expression="(B8 - B4) / (B8 + B4 + 1e-6)")
        >>> ndvi_map = ndvi(reflectance_geoarray)
    """

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

    def __init__(
        self,
        *,
        expression: str,
        band_names: list[str] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.expression = expression
        self.band_names = band_names
        self.dim = band_dim(dim, axis, "BandMath")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="BandMath")
        arr = np.asarray(gt)
        names = _names_or_attrs(gt, self.band_names) or _default_band_names(
            arr.shape[axis]
        )
        variables = {
            name: np.take(arr, idx, axis=axis)
            for idx, name in enumerate(names)
            if name is not None
        }
        out = keep_band_axis(
            np.asarray(evaluate_band_math(self.expression, variables)), gt
        )
        # A float result is a new quantity (NaN nodata); an integer or
        # boolean one (``b0 + b1`` on DN, ``b0 > b1``) keeps a fill its
        # dtype can hold.
        if np.issubdtype(out.dtype, np.inexact):
            fill = np.nan
        else:
            fill = carried_fill(gt, out.dtype)
        return wrap_filled(gt, out, fill_value=fill, attrs=strip_band_attrs(_attrs(gt)))

BandRatio

Bases: Operator

Simple two-band ratio numerator / (denominator + eps).

Plain np.ndarray input is supported for integer keys and returns a plain array; string names require carrier attrs.

Parameters:

Name Type Description Default
numerator BandRef

Index or name of the numerator band.

required
denominator BandRef

Index or name of the denominator band.

required
eps float

Denominator stabiliser. Default 1e-10 (the package-wide value, as in :func:geoops.indices.iron_oxide).

1e-10
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # Simple Ratio Vegetation Index (NIR / Red).
>>> srvi = spectral.BandRatio(numerator="B8", denominator="B4")
>>> ratio = srvi(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class BandRatio(Operator):
    r"""Simple two-band ratio ``numerator / (denominator + eps)``.

    Plain ``np.ndarray`` input is supported for integer keys and
    returns a plain array; string names require carrier attrs.

    Args:
        numerator: Index or name of the numerator band.
        denominator: Index or name of the denominator band.
        eps: Denominator stabiliser. Default ``1e-10`` (the package-wide
            value, as in :func:`geoops.indices.iron_oxide`).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # Simple Ratio Vegetation Index (NIR / Red).
        >>> srvi = spectral.BandRatio(numerator="B8", denominator="B4")
        >>> ratio = srvi(reflectance_geoarray)
    """

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

    def __init__(
        self,
        *,
        numerator: BandRef,
        denominator: BandRef,
        eps: float = 1e-10,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.numerator = numerator
        self.denominator = denominator
        self.eps = eps
        self.dim = band_dim(dim, axis, "BandRatio")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = band_ratio(
            np.asarray(gt),
            resolve_band(gt, self.numerator),
            resolve_band(gt, self.denominator),
            axis=dim_axis(gt, self.dim, name="BandRatio"),
            eps=self.eps,
        )
        return wrap_filled(
            gt,
            keep_band_axis(out, gt),
            fill_value=np.nan,
            attrs=strip_band_attrs(_attrs(gt)),
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "numerator": jsonable(self.numerator),
            "denominator": jsonable(self.denominator),
            "eps": self.eps,
            "dim": self.dim,
        }

ContinuumRemoval

Bases: Operator

Hull-quotient continuum removal along the band axis.

For each spectrum (each spatial pixel along the band axis), divides by an envelope:

  • method="convex_hull" — the upper convex hull of the spectrum vs wavelength. Output is the spectrum / hull, in (0, 1], with absorption features pulled to <1 and the hull itself at 1.
  • method="linear" — a straight line between the first and last band. Cheaper but only valid when no spectral curvature lives outside the absorption band of interest.

Plain np.ndarray input is supported when wavelengths is given explicitly and returns a plain array.

Parameters:

Name Type Description Default
method str

"convex_hull" or "linear". Default "convex_hull".

'convex_hull'
wavelengths ndarray | list[float] | None

Source wavelengths in strictly increasing order. Default None (read from gt.attrs["wavelengths"]).

None
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # Continuum-remove a SWIR-2 mineral absorption window.
>>> cr = spectral.ContinuumRemoval(method="convex_hull")
>>> band_depth = cr(swir2_geoarray)  # (B, H, W), values in (0, 1]
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class ContinuumRemoval(Operator):
    """Hull-quotient continuum removal along the band axis.

    For each spectrum (each spatial pixel along the band axis), divides
    by an envelope:

    * ``method="convex_hull"`` — the upper convex hull of the spectrum
      vs wavelength. Output is the spectrum / hull, in ``(0, 1]``, with
      absorption features pulled to <1 and the hull itself at 1.
    * ``method="linear"`` — a straight line between the first and last
      band. Cheaper but only valid when no spectral curvature lives
      outside the absorption band of interest.

    Plain ``np.ndarray`` input is supported when ``wavelengths`` is
    given explicitly and returns a plain array.

    Args:
        method: ``"convex_hull"`` or ``"linear"``. Default
            ``"convex_hull"``.
        wavelengths: Source wavelengths in strictly increasing order.
            Default ``None`` (read from ``gt.attrs["wavelengths"]``).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # Continuum-remove a SWIR-2 mineral absorption window.
        >>> cr = spectral.ContinuumRemoval(method="convex_hull")
        >>> band_depth = cr(swir2_geoarray)  # (B, H, W), values in (0, 1]
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the hull runs along each pixel's spectrum
    coupling: ClassVar[Coupling] = Coupling(couples={"band"}, effects={"band": "mix"})

    def __init__(
        self,
        *,
        method: str = "convex_hull",
        wavelengths: np.ndarray | list[float] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.method = method
        self.wavelengths = wavelengths
        self.dim = band_dim(dim, axis, "ContinuumRemoval")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = continuum_removal(
            np.asarray(gt),
            resolve_wavelengths(gt, self.wavelengths),
            axis=dim_axis(gt, self.dim, name="ContinuumRemoval"),
            method=self.method,
        )
        return wrap_filled(gt, out, fill_value=np.nan)

    def get_config(self) -> dict[str, Any]:
        return {
            "method": self.method,
            "wavelengths": None
            if self.wavelengths is None
            else jsonable(np.asarray(self.wavelengths, dtype=float)),
            "dim": self.dim,
        }

ReorderBands

Bases: SelectBands

Reorder bands by integer index or band name.

Same semantics as :class:SelectBands but emphasises that the output keeps every input band — just in a new order. Length of order should equal the number of bands on the input.

Parameters:

Name Type Description Default
order list[BandRef]

New band ordering. Items are integer positions or names.

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # Reorder a BGRN stack to RGBN.
>>> reorder = spectral.ReorderBands(order=[2, 1, 0, 3])
>>> rgbn = reorder(bgrn_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class ReorderBands(SelectBands):
    """Reorder bands by integer index or band name.

    Same semantics as :class:`SelectBands` but emphasises that the
    output keeps every input band — just in a new order. Length of
    ``order`` should equal the number of bands on the input.

    Args:
        order: New band ordering. Items are integer positions or names.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # Reorder a BGRN stack to RGBN.
        >>> reorder = spectral.ReorderBands(order=[2, 1, 0, 3])
        >>> rgbn = reorder(bgrn_geoarray)
    """

    def __init__(
        self, *, order: list[BandRef], dim: str = "band", axis: int | None = None
    ) -> None:
        super().__init__(bands=order, dim=dim, axis=axis)
        self.order = order

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

SelectBands

Bases: Operator

Select bands by integer index or band name along the band axis.

Resolves string keys with the package-wide band resolver (gt.attrs band_names, then descriptions, then bands). Selected band_names and wavelengths attrs travel with the output. Plain np.ndarray input is supported for integer positions (a plain array comes back); string names require carrier attrs.

Parameters:

Name Type Description Default
bands list[BandRef]

Bands to keep, in output order. Items are either integer positions along axis or band names resolved against gt.attrs.

required
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # Sentinel-2 RGB stacked as (B2, B3, B4, B8) -> keep (B4, B3, B2).
>>> rgb = spectral.SelectBands(bands=["B4", "B3", "B2"])
>>> out = rgb(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class SelectBands(Operator):
    """Select bands by integer index or band name along the band axis.

    Resolves string keys with the package-wide band resolver
    (``gt.attrs`` ``band_names``, then ``descriptions``, then
    ``bands``). Selected
    ``band_names`` and ``wavelengths`` attrs travel with the output.
    Plain ``np.ndarray`` input is supported for integer positions (a
    plain array comes back); string names require carrier attrs.

    Args:
        bands: Bands to keep, in output order. Items are either
            integer positions along ``axis`` or band names resolved
            against ``gt.attrs``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # Sentinel-2 RGB stacked as (B2, B3, B4, B8) -> keep (B4, B3, B2).
        >>> rgb = spectral.SelectBands(bands=["B4", "B3", "B2"])
        >>> out = rgb(reflectance_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each output band is one input band
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "select"})

    def __init__(
        self, *, bands: list[BandRef], dim: str = "band", axis: int | None = None
    ) -> None:
        self.bands = bands
        self.dim = band_dim(dim, axis, "SelectBands")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="SelectBands")
        arr = np.asarray(gt)
        indexes = resolve_bands(gt, self.bands)
        attrs = _attrs(gt)
        band_axis_len = arr.shape[axis]
        wavelengths = attrs.get("wavelengths")
        if wavelengths is not None:
            wavelengths_arr = np.asarray(wavelengths, dtype=float)
            if wavelengths_arr.size != band_axis_len:
                raise ValueError(
                    "gt.attrs['wavelengths'] length "
                    f"({wavelengths_arr.size}) does not match the band axis "
                    f"length ({band_axis_len}) at axis {axis}"
                )
        out = select_bands(arr, indexes, axis=axis)
        return wrap_like(
            gt,
            out,
            attrs=take_band_attrs(attrs, indexes, n_bands=band_axis_len),
            # the coordinate follows the pixels, or sel(band="red") gives NIR
            coords=take_band_coords(gt, indexes, axis=axis),
        )

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

SpectralBinning

Bases: Operator

Aggregate source bands into wavelength-centered bins.

For each target_wavelength :math:\lambda_c with bin width :math:w, aggregates source bands with :math:|\lambda_s - \lambda_c| \le w/2. Aggregation modes:

  • "mean" — uniform average.
  • "median" — robust to outliers in narrow bins.
  • "weighted_mean" — Gaussian weights with :math:\sigma = w / (2 \sqrt{2 \ln 2}) (FWHM equals width).

Plain np.ndarray input is supported when source_wavelengths is given explicitly and returns a plain array.

Parameters:

Name Type Description Default
target_wavelengths ndarray | list[float]

Center wavelengths of the output bins.

required
width float | ndarray | list[float]

Scalar or per-bin widths (same units as wavelengths).

required
method str

"mean", "median", or "weighted_mean". Default "mean".

'mean'
source_wavelengths ndarray | list[float] | None

Source band wavelengths. Default None (read from gt.attrs["wavelengths"]).

None
axis int | None

Position of the band axis. Default -3.

None

Examples:

>>> from geoops import spectral
>>> # Coarsen hyperspectral cube to broad-band averages.
>>> binner = spectral.SpectralBinning(
...     target_wavelengths=[490.0, 560.0, 665.0],
...     width=30.0,
...     method="weighted_mean",
... )
>>> coarse = binner(hyperspectral_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class SpectralBinning(Operator):
    """Aggregate source bands into wavelength-centered bins.

    For each ``target_wavelength`` :math:`\\lambda_c` with bin width
    :math:`w`, aggregates source bands with
    :math:`|\\lambda_s - \\lambda_c| \\le w/2`. Aggregation modes:

    * ``"mean"`` — uniform average.
    * ``"median"`` — robust to outliers in narrow bins.
    * ``"weighted_mean"`` — Gaussian weights with
      :math:`\\sigma = w / (2 \\sqrt{2 \\ln 2})` (FWHM equals ``width``).

    Plain ``np.ndarray`` input is supported when ``source_wavelengths``
    is given explicitly and returns a plain array.

    Args:
        target_wavelengths: Center wavelengths of the output bins.
        width: Scalar or per-bin widths (same units as wavelengths).
        method: ``"mean"``, ``"median"``, or ``"weighted_mean"``.
            Default ``"mean"``.
        source_wavelengths: Source band wavelengths. Default ``None``
            (read from ``gt.attrs["wavelengths"]``).
        axis: Position of the band axis. Default ``-3``.

    Examples:
        >>> from geoops import spectral
        >>> # Coarsen hyperspectral cube to broad-band averages.
        >>> binner = spectral.SpectralBinning(
        ...     target_wavelengths=[490.0, 560.0, 665.0],
        ...     width=30.0,
        ...     method="weighted_mean",
        ... )
        >>> coarse = binner(hyperspectral_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each bin averages the source bands within it
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        target_wavelengths: np.ndarray | list[float],
        width: float | np.ndarray | list[float],
        method: str = "mean",
        source_wavelengths: np.ndarray | list[float] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.target_wavelengths = target_wavelengths
        self.width = width
        self.method = method
        self.source_wavelengths = source_wavelengths
        self.dim = band_dim(dim, axis, "SpectralBinning")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        target_wavelengths = np.asarray(self.target_wavelengths, dtype=float)
        out = spectral_binning(
            np.asarray(gt),
            resolve_wavelengths(gt, self.source_wavelengths, name="source_wavelengths"),
            target_wavelengths,
            self.width,
            axis=dim_axis(gt, self.dim, name="SpectralBinning"),
            method=self.method,
        )
        # Band axis is reshaped; band_names from the source no longer
        # apply, but new wavelengths do.
        attrs = strip_band_attrs(_attrs(gt))
        attrs["wavelengths"] = jsonable(target_wavelengths)
        return wrap_filled(
            gt,
            out,
            fill_value=carried_fill(gt, out.dtype),
            attrs=attrs,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "target_wavelengths": jsonable(
                np.asarray(self.target_wavelengths, dtype=float)
            ),
            "width": jsonable(self.width),
            "method": self.method,
            "source_wavelengths": (
                None
                if self.source_wavelengths is None
                else jsonable(np.asarray(self.source_wavelengths, dtype=float))
            ),
            "dim": self.dim,
        }

SpectralSmoothing

Bases: Operator

Smooth spectra along the band axis.

Pure per-spectrum math — accepts a GeoArray or a plain np.ndarray and returns the same carrier kind.

Parameters:

Name Type Description Default
method str

"savgol" (Savitzky-Golay), "gaussian", or "moving_average". Default "savgol".

'savgol'
window int

Filter window length in bands. Must be odd for "savgol". Default 7.

7
polyorder int

Polynomial order for Savitzky-Golay (ignored by the other methods). Default 2.

2
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> # De-noise hyperspectral spectra before continuum removal.
>>> smooth = spectral.SpectralSmoothing(
...     method="savgol", window=9, polyorder=2
... )
>>> denoised = smooth(hyperspectral_geoarray)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class SpectralSmoothing(Operator):
    """Smooth spectra along the band axis.

    Pure per-spectrum math — accepts a GeoArray or a plain
    ``np.ndarray`` and returns the same carrier kind.

    Args:
        method: ``"savgol"`` (Savitzky-Golay), ``"gaussian"``, or
            ``"moving_average"``. Default ``"savgol"``.
        window: Filter window length in bands. Must be odd for
            ``"savgol"``. Default ``7``.
        polyorder: Polynomial order for Savitzky-Golay (ignored by the
            other methods). Default ``2``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> # De-noise hyperspectral spectra before continuum removal.
        >>> smooth = spectral.SpectralSmoothing(
        ...     method="savgol", window=9, polyorder=2
        ... )
        >>> denoised = smooth(hyperspectral_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # a smoothing window along each pixel's spectrum
    coupling: ClassVar[Coupling] = Coupling(couples={"band"}, effects={"band": "mix"})

    def __init__(
        self,
        *,
        method: str = "savgol",
        window: int = 7,
        polyorder: int = 2,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.method = method
        self.window = window
        self.polyorder = polyorder
        self.dim = band_dim(dim, axis, "SpectralSmoothing")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = spectral_smoothing(
            np.asarray(gt),
            axis=dim_axis(gt, self.dim, name="SpectralSmoothing"),
            method=self.method,
            window=self.window,
            polyorder=self.polyorder,
        )
        return wrap_filled(gt, out, fill_value=carried_fill(gt, out.dtype))

SplitBands

Bases: Operator

Split a multiband GeoArray into one single-band GeoArray per band.

Plain np.ndarray input is supported and yields a list of plain single-band arrays.

Parameters:

Name Type Description Default
names list[str] | None

Optional override for band names. If omitted, names are read from gt.attrs (band_names, then descriptions, then bands).

None
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops import spectral
>>> bands = spectral.SplitBands()(rgb_geoarray)  # list of (1, H, W)
>>> red, green, blue = bands
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class SplitBands(Operator):
    """Split a multiband GeoArray into one single-band GeoArray per band.

    Plain ``np.ndarray`` input is supported and yields a list of plain
    single-band arrays.

    Args:
        names: Optional override for band names. If omitted, names are
            read from ``gt.attrs`` (``band_names``, then ``descriptions``,
            then ``bands``).
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops import spectral
        >>> bands = spectral.SplitBands()(rgb_geoarray)  # list of (1, H, W)
        >>> red, green, blue = bands
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # one single-band carrier per band
    coupling: ClassVar[Coupling] = Coupling(effects={"band": "split"}, kind="fan-out")

    def __init__(
        self,
        *,
        names: list[str] | None = None,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.names = names
        self.dim = band_dim(dim, axis, "SplitBands")

    def _apply(self, gt: GeoArray | np.ndarray) -> list[GeoArray | np.ndarray]:
        band_pos = dim_axis(gt, self.dim, name="SplitBands")
        arr = np.asarray(gt)
        axis = band_pos + arr.ndim if band_pos < 0 else band_pos
        if not 0 <= axis < arr.ndim:
            raise ValueError(
                f"SplitBands axis {band_pos} is out of range for a "
                f"{arr.ndim}-D tensor (valid axes: "
                f"{-arr.ndim} to {arr.ndim - 1})"
            )
        n_bands = arr.shape[axis]
        source_names = _names_or_attrs(gt, self.names)
        if source_names is not None and len(source_names) != n_bands:
            raise ValueError("names length must match the number of bands")
        attrs = _attrs(gt)
        outputs = []
        for idx in range(n_bands):
            out = np.take(arr, [idx], axis=axis)
            outputs.append(
                wrap_like(
                    gt,
                    out,
                    attrs=take_band_attrs(attrs, [idx], n_bands=n_bands),
                    band_names=None if self.names is None else [self.names[idx]],
                    coords=take_band_coords(gt, [idx], axis=axis),
                )
            )
        return outputs

StackBands

Bases: Operator

Concatenate carriers along the band axis.

The checks of :func:geoarray.concatenate, extended to plain arrays, 2-D inputs and any band axis: every input must sit on the first input's pixel grid (:func:geoops._src.geo.grid_matches -- equal spatial shape, CRS and transform) and declare the same fill_value (NaN matches NaN), since the stack can declare only one fill. Each per-band attrs key (band_names, descriptions, wavelengths, ...) is concatenated in input order when every input carries it with one entry per band; otherwise that key is dropped on the output. Other attrs come from the first input. Plain np.ndarray inputs are supported (only the spatial shape is checked and a plain array is returned); mixing GeoArrays and plain arrays raises because their georeferencing cannot agree.

Parameters:

Name Type Description Default
dim str

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

'band'
axis int | None

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

None

Raises:

Type Description
TypeError

If given a single array instead of a sequence.

ValueError

If the sequence is empty, mixes GeoArrays and plain arrays, or the inputs differ in grid or fill value.

Examples:

>>> from geoops import spectral
>>> stack = spectral.StackBands()
>>> stacked = stack([gt_b4, gt_b8])  # (2, H, W)
Source code in packages/geotoolz-ops/src/geoops/spectral/_src/operators.py
class StackBands(Operator):
    """Concatenate carriers along the band axis.

    The checks of :func:`geoarray.concatenate`, extended to plain arrays,
    2-D inputs and any band ``axis``: every input must sit on the first
    input's pixel grid (:func:`geoops._src.geo.grid_matches` -- equal
    spatial shape, CRS and transform) and declare the same
    ``fill_value`` (``NaN`` matches ``NaN``), since the stack can
    declare only one fill. Each per-band attrs key (``band_names``,
    ``descriptions``, ``wavelengths``, ...) is concatenated in input order
    when every input carries it with one entry per band; otherwise that
    key is dropped on the output. Other attrs come from the first input.
    Plain ``np.ndarray`` inputs are supported (only the spatial shape is
    checked and a plain array is returned); mixing GeoArrays and plain
    arrays raises because their georeferencing cannot agree.

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

    Raises:
        TypeError: If given a single array instead of a sequence.
        ValueError: If the sequence is empty, mixes GeoArrays and plain
            arrays, or the inputs differ in grid or fill value.

    Examples:
        >>> from geoops import spectral
        >>> stack = spectral.StackBands()
        >>> stacked = stack([gt_b4, gt_b8])  # (2, H, W)
    """

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

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

    def _apply(self, tensors: list[GeoArray | np.ndarray]) -> GeoArray | np.ndarray:
        if isinstance(tensors, np.ndarray | GeoArray):
            raise TypeError(
                "StackBands takes a sequence of carriers to concatenate along the "
                f"band axis; got a single {tensors.ndim}-D array"
            )
        if not tensors:
            raise ValueError("StackBands requires at least one GeoArray")
        for gt in tensors:
            reject_geotensor(gt, "StackBands")
        first = tensors[0]
        axis = dim_axis(first, self.dim, name="StackBands")
        georeferenced = isinstance(first, GeoArray)
        first_fill = getattr(first, "fill_value", None)
        for idx, gt in enumerate(tensors[1:], start=1):
            if isinstance(gt, GeoArray) != georeferenced:
                raise ValueError(
                    "StackBands cannot mix GeoArrays and plain arrays; input "
                    f"{idx} differs from input 0"
                )
            if not grid_matches(first, gt):
                raise ValueError(
                    "All inputs must share spatial shape, transform and CRS; "
                    f"input {idx} (shape {np.shape(gt)}) is on a different grid "
                    f"than input 0 (shape {np.shape(first)})"
                )
            fill = getattr(gt, "fill_value", None)
            if not _same_fill(fill, first_fill):
                raise ValueError(
                    "All inputs must share fill_value; input "
                    f"{idx} has {fill!r}, input 0 has {first_fill!r}"
                )
        arrays = [
            np.expand_dims(arr, axis=axis) if arr.ndim == 2 else arr
            for arr in (np.asarray(gt) for gt in tensors)
        ]
        out = np.concatenate(arrays, axis=axis)
        attrs = strip_band_attrs(_attrs(first))
        attrs.update(
            concat_band_attrs(
                [_attrs(gt) for gt in tensors],
                [arr.shape[axis] for arr in arrays],
            )
        )
        return wrap_like(first, out, attrs=attrs)

band_ratio(arr, numerator_idx, denominator_idx, *, axis=-3, eps=1e-10)

Compute numerator / (denominator + eps) with the band axis collapsed.

Parameters:

Name Type Description Default
arr Num[ndarray, 'c h w']

Input array with the band axis at position axis. Any other dimensions are preserved untouched.

required
numerator_idx int

Integer position of the numerator band.

required
denominator_idx int

Integer position of the denominator band.

required
axis int

Position of the band axis. Default -3.

-3
eps float

Small constant added to the denominator to shadow division by zero on no-data / saturated pixels. Default 1e-10, the package-wide denominator stabiliser shared with every ratio / normalized-difference primitive in :mod:geoops.indices (e.g. iron_oxide, clay_minerals). Pass 0.0 to see inf/nan on zero pixels instead.

1e-10

Returns:

Type Description
Float[ndarray, 'h w']

Float ratio array with the band axis collapsed. Integer input is

Float[ndarray, 'h w']

promoted to float first (see geoops._src.dtype.as_float).

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def band_ratio(
    arr: Num[np.ndarray, "c h w"],
    numerator_idx: int,
    denominator_idx: int,
    *,
    axis: int = -3,
    eps: float = 1e-10,
) -> Float[np.ndarray, "h w"]:
    """Compute ``numerator / (denominator + eps)`` with the band axis collapsed.

    Args:
        arr: Input array with the band axis at position ``axis``. Any
            other dimensions are preserved untouched.
        numerator_idx: Integer position of the numerator band.
        denominator_idx: Integer position of the denominator band.
        axis: Position of the band axis. Default ``-3``.
        eps: Small constant added to the denominator to shadow division
            by zero on no-data / saturated pixels. Default ``1e-10``, the
            package-wide denominator stabiliser shared with every
            ratio / normalized-difference primitive in
            :mod:`geoops.indices` (e.g. ``iron_oxide``, ``clay_minerals``).
            Pass ``0.0`` to see ``inf``/``nan`` on zero pixels instead.

    Returns:
        Float ratio array with the band axis collapsed. Integer input is
        promoted to float first (see `geoops._src.dtype.as_float`).
    """
    arr = as_float(arr)
    numerator = np.take(arr, numerator_idx, axis=axis)
    denominator = np.take(arr, denominator_idx, axis=axis)
    return numerator / (denominator + eps)

continuum_removal(arr, wavelengths, *, axis=-3, method='convex_hull')

Apply hull-quotient continuum removal along the band axis.

Each spectrum (the 1-D slice along axis at every remaining position) is divided by a continuum envelope so absorption features stand out as dips below 1:

  • method="convex_hull" — the envelope is the upper convex hull of the spectrum vs wavelength. Output values lie in (0, 1], with hull touch-points exactly at 1.
  • method="linear" — the envelope is the straight line between the first and last band. Cheaper, but only appropriate when no spectral curvature lies outside the absorption feature of interest.

Where the continuum is exactly zero the quotient is defined as 1 (flat), avoiding division-by-zero artefacts on empty pixels.

Parameters:

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

Spectral cube with the band axis at position axis. Any number of trailing/leading non-band dimensions is supported.

required
wavelengths Float[ndarray, ' c']

Band-center wavelengths, strictly increasing, with length equal to arr.shape[axis].

required
axis int

Position of the band axis. Default -3.

-3
method str

Continuum model, "convex_hull" (default) or "linear".

'convex_hull'

Returns:

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

Float array of the same shape as arr holding the

Float[ndarray, 'c h w']

continuum-removed (hull-quotient) spectra.

Raises:

Type Description
ValueError

If wavelengths length does not match the band axis, is not strictly increasing, or method is unknown.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def continuum_removal(
    arr: Float[np.ndarray, "c h w"],
    wavelengths: Float[np.ndarray, " c"],
    *,
    axis: int = -3,
    method: str = "convex_hull",
) -> Float[np.ndarray, "c h w"]:
    """Apply hull-quotient continuum removal along the band axis.

    Each spectrum (the 1-D slice along ``axis`` at every remaining
    position) is divided by a continuum envelope so absorption features
    stand out as dips below 1:

    * ``method="convex_hull"`` — the envelope is the upper convex hull
      of the spectrum vs wavelength. Output values lie in ``(0, 1]``,
      with hull touch-points exactly at 1.
    * ``method="linear"`` — the envelope is the straight line between
      the first and last band. Cheaper, but only appropriate when no
      spectral curvature lies outside the absorption feature of
      interest.

    Where the continuum is exactly zero the quotient is defined as 1
    (flat), avoiding division-by-zero artefacts on empty pixels.

    Args:
        arr: Spectral cube with the band axis at position ``axis``. Any
            number of trailing/leading non-band dimensions is supported.
        wavelengths: Band-center wavelengths, strictly increasing, with
            length equal to ``arr.shape[axis]``.
        axis: Position of the band axis. Default ``-3``.
        method: Continuum model, ``"convex_hull"`` (default) or
            ``"linear"``.

    Returns:
        Float array of the same shape as ``arr`` holding the
        continuum-removed (hull-quotient) spectra.

    Raises:
        ValueError: If ``wavelengths`` length does not match the band
            axis, is not strictly increasing, or ``method`` is unknown.
    """
    arr_axis0 = np.moveaxis(np.asarray(arr, dtype=float), axis, 0)
    if arr_axis0.shape[0] != wavelengths.size:
        raise ValueError("wavelengths length must match the band axis")
    _validate_strictly_increasing(wavelengths, context="continuum_removal")

    if method == "linear":
        continuum = _linear_continuum(arr_axis0, wavelengths)
    elif method == "convex_hull":
        continuum = _convex_hull_continuum(arr_axis0, wavelengths)
    else:
        raise ValueError("method must be 'convex_hull' or 'linear'")

    out = np.divide(
        arr_axis0, continuum, out=np.ones_like(arr_axis0), where=continuum != 0
    )
    return np.moveaxis(out, 0, axis)

evaluate_band_math(expression, variables)

Evaluate a restricted arithmetic expression over named band arrays.

The expression is parsed with Python's :mod:ast module — never eval — and only a small arithmetic grammar is permitted:

  • numeric constants,
  • unary + / -,
  • binary + - * / **,
  • calls to the whitelisted numpy functions abs, sqrt, log, log10, exp, where, minimum, maximum, and clip.

Bare names resolve against variables; anything else (comparison operators, attribute access, subscripts, lambdas, ...) raises. With no comparisons in the grammar, where's condition is a numeric expression read as truthy where non-zero (e.g. where(clip(B8 - B4, 0, 1), B8, B4)), not B8 > B4.

Parameters:

Name Type Description Default
expression str

Arithmetic expression over the keys of variables, e.g. "(B8 - B4) / (B8 + B4 + 1e-6)".

required
variables Mapping[str, Num[ndarray, 'h w']]

Mapping from band name to band array. All arrays should broadcast against each other (typically identical (H, W) slices of one cube).

required

Every band array is promoted to floating point before evaluation (see geoops._src.dtype.as_float), so integer DN never wrap around or overflow: "a - b" over uint16 bands 1000 and 3000 gives -2000.0, not 63536.

Returns:

Type Description
Num[ndarray, 'h w']

The evaluated result as a float ndarray (broadcast shape of the

Num[ndarray, 'h w']

participating bands).

Raises:

Type Description
ValueError

If the expression references an unknown band name, uses a non-numeric constant, or contains any construct outside the grammar above.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def evaluate_band_math(
    expression: str, variables: Mapping[str, Num[np.ndarray, "h w"]]
) -> Num[np.ndarray, "h w"]:
    """Evaluate a restricted arithmetic expression over named band arrays.

    The expression is parsed with Python's :mod:`ast` module — never
    ``eval`` — and only a small arithmetic grammar is permitted:

    * numeric constants,
    * unary ``+`` / ``-``,
    * binary ``+ - * / **``,
    * calls to the whitelisted numpy functions ``abs``, ``sqrt``,
      ``log``, ``log10``, ``exp``, ``where``, ``minimum``, ``maximum``,
      and ``clip``.

    Bare names resolve against ``variables``; anything else (comparison
    operators, attribute access, subscripts, lambdas, ...) raises. With
    no comparisons in the grammar, ``where``'s condition is a numeric
    expression read as truthy where non-zero (e.g.
    ``where(clip(B8 - B4, 0, 1), B8, B4)``), not ``B8 > B4``.

    Args:
        expression: Arithmetic expression over the keys of
            ``variables``, e.g. ``"(B8 - B4) / (B8 + B4 + 1e-6)"``.
        variables: Mapping from band name to band array. All arrays
            should broadcast against each other (typically identical
            ``(H, W)`` slices of one cube).

    Every band array is promoted to floating point before evaluation
    (see `geoops._src.dtype.as_float`), so integer DN never wrap
    around or overflow: ``"a - b"`` over ``uint16`` bands ``1000`` and
    ``3000`` gives ``-2000.0``, not ``63536``.

    Returns:
        The evaluated result as a float ndarray (broadcast shape of the
        participating bands).

    Raises:
        ValueError: If the expression references an unknown band name,
            uses a non-numeric constant, or contains any construct
            outside the grammar above.
    """
    tree = ast.parse(expression, mode="eval")
    float_vars = {name: as_float(value) for name, value in variables.items()}
    return np.asarray(_eval_node(tree.body, float_vars))

reorder_bands(arr, order, *, axis=-3)

Reorder bands by integer index along the configured band axis.

Alias of :func:select_bands that emphasises intent: order should be a permutation of range(arr.shape[axis]) so every input band appears exactly once in the output (this is not enforced).

Parameters:

Name Type Description Default
arr Shaped[ndarray, 'c h w']

Input array with the band axis at position axis.

required
order list[int]

New band ordering as integer positions.

required
axis int

Position of the band axis. Default -3.

-3

Returns:

Type Description
Shaped[ndarray, 'c h w']

Array with the same shape as arr and the band axis permuted

Shaped[ndarray, 'c h w']

according to order.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def reorder_bands(
    arr: Shaped[np.ndarray, "c h w"], order: list[int], *, axis: int = -3
) -> Shaped[np.ndarray, "c h w"]:
    """Reorder bands by integer index along the configured band axis.

    Alias of :func:`select_bands` that emphasises intent: ``order``
    should be a permutation of ``range(arr.shape[axis])`` so every input
    band appears exactly once in the output (this is not enforced).

    Args:
        arr: Input array with the band axis at position ``axis``.
        order: New band ordering as integer positions.
        axis: Position of the band axis. Default ``-3``.

    Returns:
        Array with the same shape as ``arr`` and the band axis permuted
        according to ``order``.
    """
    return select_bands(arr, order, axis=axis)

select_bands(arr, indexes, *, axis=-3)

Select bands by integer index along the configured band axis.

Thin wrapper over :func:numpy.take. Shapes are shown for the default channel-first (C, H, W) layout, but any number of dimensions is supported — only the axis at position axis is touched.

Parameters:

Name Type Description Default
arr Shaped[ndarray, 'c h w']

Input array with the band axis at position axis.

required
indexes list[int]

Integer band positions to keep, in output order. Repeats are allowed (the band is duplicated in the output).

required
axis int

Position of the band axis. Default -3 (the carrier's (C, H, W) / (T, C, H, W) layout; matches rasterio.read() output).

-3

Returns:

Type Description
Shaped[ndarray, 'k h w']

Array with the band axis replaced by the len(indexes)

Shaped[ndarray, 'k h w']

selected bands; all other axes are unchanged.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def select_bands(
    arr: Shaped[np.ndarray, "c h w"], indexes: list[int], *, axis: int = -3
) -> Shaped[np.ndarray, "k h w"]:
    """Select bands by integer index along the configured band axis.

    Thin wrapper over :func:`numpy.take`. Shapes are shown for the
    default channel-first ``(C, H, W)`` layout, but any number of
    dimensions is supported — only the axis at position ``axis`` is
    touched.

    Args:
        arr: Input array with the band axis at position ``axis``.
        indexes: Integer band positions to keep, in output order.
            Repeats are allowed (the band is duplicated in the output).
        axis: Position of the band axis. Default ``-3`` (the carrier's
            ``(C, H, W)`` / ``(T, C, H, W)`` layout; matches
            ``rasterio.read()`` output).

    Returns:
        Array with the band axis replaced by the ``len(indexes)``
        selected bands; all other axes are unchanged.
    """
    return np.take(arr, indexes, axis=axis)

spectral_binning(arr, source_wavelengths, target_wavelengths, width, *, axis=-3, method='mean')

Aggregate source bands into wavelength-centered bins.

For each target bin center :math:\lambda_c with width :math:w, the source bands satisfying :math:|\lambda_s - \lambda_c| \le w/2 are aggregated into one output band. Aggregation modes:

  • method="mean" — uniform average of the in-bin bands.
  • method="median" — per-pixel median; robust to outlier bands in narrow bins.
  • method="weighted_mean" — Gaussian weights centered on :math:\lambda_c with :math:\sigma = w / (2\sqrt{2\ln 2}), i.e. the bin width is interpreted as the FWHM of a synthetic Gaussian response; weights are normalised to sum to one.

Parameters:

Name Type Description Default
arr Num[ndarray, 'c h w']

Spectral cube with the band axis at position axis. Any number of non-band dimensions is supported.

required
source_wavelengths Float[ndarray, ' c']

Wavelengths of the source bands, strictly increasing, with length equal to arr.shape[axis].

required
target_wavelengths Float[ndarray, ' k']

Center wavelengths of the output bins, shape (K,).

required
width float | Float[ndarray, ' k']

Bin width(s) in the same units as the wavelengths — a scalar applied to every bin, or a per-bin array broadcast against target_wavelengths. Must be strictly positive.

required
axis int

Position of the band axis. Default -3.

-3
method str

"mean" (default), "median", or "weighted_mean".

'mean'

Returns:

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

Float array with the band axis replaced by the K binned

Float[ndarray, 'k h w']

bands; all other axes are unchanged.

Raises:

Type Description
ValueError

If source_wavelengths is not strictly increasing, any width is non-positive, a bin captures no source band, or method is unknown.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def spectral_binning(
    arr: Num[np.ndarray, "c h w"],
    source_wavelengths: Float[np.ndarray, " c"],
    target_wavelengths: Float[np.ndarray, " k"],
    width: float | Float[np.ndarray, " k"],
    *,
    axis: int = -3,
    method: str = "mean",
) -> Float[np.ndarray, "k h w"]:
    """Aggregate source bands into wavelength-centered bins.

    For each target bin center :math:`\\lambda_c` with width :math:`w`,
    the source bands satisfying
    :math:`|\\lambda_s - \\lambda_c| \\le w/2` are aggregated into one
    output band. Aggregation modes:

    * ``method="mean"`` — uniform average of the in-bin bands.
    * ``method="median"`` — per-pixel median; robust to outlier bands
      in narrow bins.
    * ``method="weighted_mean"`` — Gaussian weights centered on
      :math:`\\lambda_c` with :math:`\\sigma = w / (2\\sqrt{2\\ln 2})`,
      i.e. the bin width is interpreted as the FWHM of a synthetic
      Gaussian response; weights are normalised to sum to one.

    Args:
        arr: Spectral cube with the band axis at position ``axis``. Any
            number of non-band dimensions is supported.
        source_wavelengths: Wavelengths of the source bands, strictly
            increasing, with length equal to ``arr.shape[axis]``.
        target_wavelengths: Center wavelengths of the output bins,
            shape ``(K,)``.
        width: Bin width(s) in the same units as the wavelengths — a
            scalar applied to every bin, or a per-bin array broadcast
            against ``target_wavelengths``. Must be strictly positive.
        axis: Position of the band axis. Default ``-3``.
        method: ``"mean"`` (default), ``"median"``, or
            ``"weighted_mean"``.

    Returns:
        Float array with the band axis replaced by the ``K`` binned
        bands; all other axes are unchanged.

    Raises:
        ValueError: If ``source_wavelengths`` is not strictly
            increasing, any width is non-positive, a bin captures no
            source band, or ``method`` is unknown.
    """
    arr_axis0 = np.moveaxis(np.asarray(arr), axis, 0)
    _validate_strictly_increasing(source_wavelengths, context="spectral_binning")
    widths = np.broadcast_to(np.asarray(width, dtype=float), target_wavelengths.shape)
    if np.any(widths <= 0):
        bad = int(np.flatnonzero(widths <= 0)[0])
        raise ValueError(
            "spectral_binning widths must be strictly positive; "
            f"got width={float(widths[bad])} at index {bad}"
        )
    out = np.empty((target_wavelengths.size, *arr_axis0.shape[1:]), dtype=float)

    for idx, (center, bin_width) in enumerate(
        zip(target_wavelengths, widths, strict=True)
    ):
        half_width = bin_width / 2.0
        mask = np.abs(source_wavelengths - center) <= half_width
        if not np.any(mask):
            raise ValueError(
                f"No source wavelengths found within +/-{half_width} "
                f"of target bin center {center}; source range: "
                f"[{source_wavelengths.min()}, {source_wavelengths.max()}]"
            )
        values = arr_axis0[mask]
        if method == "mean":
            out[idx] = np.mean(values, axis=0)
        elif method == "median":
            out[idx] = np.median(values, axis=0)
        elif method == "weighted_mean":
            sigma = bin_width / (2.0 * np.sqrt(2.0 * np.log(2.0)))
            weights = np.exp(
                -((source_wavelengths[mask] - center) ** 2) / (2.0 * sigma**2)
            )
            weights = weights / weights.sum()
            out[idx] = np.sum(
                weights.reshape((-1,) + (1,) * (values.ndim - 1)) * values, axis=0
            )
        else:
            raise ValueError("method must be 'mean', 'median', or 'weighted_mean'")
    return np.moveaxis(out, 0, axis)

spectral_smoothing(arr, *, axis=-3, method='savgol', window=7, polyorder=2)

Smooth spectra along the band axis.

Filters each spectrum (1-D slice along axis) independently:

  • method="savgol" — Savitzky-Golay least-squares polynomial fit of order polyorder over an odd window of bands. Preserves peak shape better than a plain average.
  • method="gaussian" — Gaussian filter with sigma = window / 2 bands (polyorder ignored).
  • method="moving_average" — uniform boxcar of window bands via np.convolve(..., mode="same") (polyorder ignored); spectrum edges taper because the kernel overhangs zeros.

Parameters:

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

Spectral cube with the band axis at position axis. Any number of non-band dimensions is supported.

required
axis int

Position of the band axis. Default -3.

-3
method str

"savgol" (default), "gaussian", or "moving_average".

'savgol'
window int

Filter window length in bands. Must be odd for "savgol". Default 7.

7
polyorder int

Polynomial order of the Savitzky-Golay fit; must be less than window. Default 2.

2

Returns:

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

Float array of the same shape as arr holding the smoothed

Float[ndarray, 'c h w']

spectra. Integer input is promoted to float64 first (see

Float[ndarray, 'c h w']

geoops._src.dtype.as_float), so every method returns a

Float[ndarray, 'c h w']

float array rather than a truncated integer one.

Raises:

Type Description
ValueError

If method is unknown, or method="savgol" with an even window.

Source code in packages/geotoolz-ops/src/geoops/spectral/_src/array.py
def spectral_smoothing(
    arr: Float[np.ndarray, "c h w"],
    *,
    axis: int = -3,
    method: str = "savgol",
    window: int = 7,
    polyorder: int = 2,
) -> Float[np.ndarray, "c h w"]:
    """Smooth spectra along the band axis.

    Filters each spectrum (1-D slice along ``axis``) independently:

    * ``method="savgol"`` — Savitzky-Golay least-squares polynomial
      fit of order ``polyorder`` over an odd ``window`` of bands.
      Preserves peak shape better than a plain average.
    * ``method="gaussian"`` — Gaussian filter with
      ``sigma = window / 2`` bands (``polyorder`` ignored).
    * ``method="moving_average"`` — uniform boxcar of ``window`` bands
      via ``np.convolve(..., mode="same")`` (``polyorder`` ignored);
      spectrum edges taper because the kernel overhangs zeros.

    Args:
        arr: Spectral cube with the band axis at position ``axis``. Any
            number of non-band dimensions is supported.
        axis: Position of the band axis. Default ``-3``.
        method: ``"savgol"`` (default), ``"gaussian"``, or
            ``"moving_average"``.
        window: Filter window length in bands. Must be odd for
            ``"savgol"``. Default ``7``.
        polyorder: Polynomial order of the Savitzky-Golay fit; must be
            less than ``window``. Default ``2``.

    Returns:
        Float array of the same shape as ``arr`` holding the smoothed
        spectra. Integer input is promoted to float64 first (see
        `geoops._src.dtype.as_float`), so every method returns a
        float array rather than a truncated integer one.

    Raises:
        ValueError: If ``method`` is unknown, or ``method="savgol"``
            with an even ``window``.
    """
    arr = as_float(arr, np.float64)
    if method == "savgol":
        if window % 2 == 0:
            raise ValueError(f"savgol window must be odd, got {window}")
        return signal.savgol_filter(
            arr, window_length=window, polyorder=polyorder, axis=axis
        )
    if method == "gaussian":
        return ndimage.gaussian_filter1d(arr, sigma=window / 2.0, axis=axis)
    if method == "moving_average":
        kernel = np.ones(window, dtype=float) / float(window)
        return np.apply_along_axis(
            lambda x: np.convolve(x, kernel, mode="same"), axis, arr
        )
    raise ValueError("method must be 'savgol', 'gaussian', or 'moving_average'")