Skip to content

Radiometry

DN ↔ radiance ↔ reflectance conversions, sun/sensor geometry, brightness temperature, and simple atmospheric correction.

  • DN / radiance / reflectance: DNToRadiance, DNToReflectance, RadianceToDN, RadianceToReflectance, ReflectanceToRadiance
  • Brightness temperature: BTFromRadiance
  • Sun geometry: ComputeSZA, EarthSunDistanceCorrection, IntegratedIrradiance
  • Atmospheric correction: DOS1 (Chavez dark-object subtraction), SimpleAtmosphericCorrection
  • Stretches: Gamma, MinMaxStretch, PercentileClip, ToFloat32
  • Spectral response: ApplySRF — Gaussian SRFs integrated on a 1-nm grid via georeader's transform_to_srf; source wavelengths from the argument or attrs["wavelengths"], optional target band_names
  • Tier-A primitives: dn_to_radiance, radiance_to_dn, dn_to_reflectance, bt_from_radiance, dos1, min_max_normalize, percentile_clip, gamma_correct

geoops.radiometry

Sensor-agnostic radiometric transforms.

A small palette of generic radiometric Operators — DN→radiance and DN→reflectance scalar decodes, dtype casts, and display-prep (min-max, percentile clip, gamma). They take user-supplied gain / offset / scale constants rather than reading sensor metadata.

Solar-geometry-aware TOA conversion is covered by RadianceToReflectance / ReflectanceToRadiance (carrier-aware wrappers over georeader.reflectance.radiance_to_reflectance), with ComputeSZA, EarthSunDistanceCorrection and IntegratedIrradiance for the individual geometry terms. Sensor presets that read these constants from product metadata are not part of this module: pass the per-band irradiance / acquisition date yourself.

Examples:

Sentinel-2 L1C display pipeline::

import geoops as gz

s2_display = (
    gz.radiometry.ToFloat32()
    | gz.radiometry.DNToReflectance(scale=1e-4)
    | gz.radiometry.PercentileClip(lower=2, upper=98)
    | gz.radiometry.Gamma(gamma=1.2)
)

rgb = s2_display(s2_dn_geoarray)

Per-band gain and offset (Landsat-style)::

import numpy as np
gains   = np.array([0.012, 0.013, 0.011, 0.009])
offsets = np.array([-60.0, -61.0, -55.0, -45.0])
op = gz.radiometry.DNToRadiance(gain=gains, offset=offsets)
radiance = op(dn_geoarray)

ApplySRF

Bases: Operator

Convolve hyperspectral bands to target Gaussian-SRF multispectral bands.

For each target band k with center wavelength λ_k and FWHM Δλ_k, build a normalised Gaussian SRF (:func:georeader.reflectance.srf) on a 1-nm wavelength grid spanning the source range, then integrate with :func:georeader.reflectance.transform_to_srf, which maps each grid wavelength to its nearest source band:

.. math::

L_k \;=\; \frac{\displaystyle \int L(\lambda) \, R_k(\lambda) \, d\lambda}
               {\displaystyle \int R_k(\lambda) \, d\lambda}

The 1-nm grid keeps the SRF well defined when a target FWHM is much narrower than the source band spacing (the target then reads its nearest source band). Targets the grid cannot represent -- a centre outside the source range, or a FWHM far below 1 nm -- raise ValueError instead of returning an all-zero band.

Nodata: the GeoArray goes to transform_to_srf (as georeader's carrier, through :func:geoops._src.engine.to_engine), which marks a target pixel missing when any source band that target reads (weight above epsilon_srf) equals the input's fill_value; non-finite source values propagate through the weighted sum the same way. Those pixels hold the carried fill (:func:geoops._src.valid.carried_fill: the input's fill for float input, NaN for integer DN promoted to float). Source bands a target does not read never invalidate it.

Output attrs: source per-band keys are dropped; wavelengths holds the target centres and band_names the given band_names. A (T, C, H, W) stack is convolved frame by frame. Plain np.ndarray input (B, H, W) returns a plain float32 array (NaN at non-finite pixels; there is no fill value to match).

Parameters:

Name Type Description Default
target_center_wavelengths ndarray | list[float]

λ_k for each target band (nm).

required
target_fwhm ndarray | list[float]

FWHM for each target band (nm).

required
source_wavelengths ndarray | list[float] | None

Source hyperspectral band centres (nm). Default None reads gt.attrs["wavelengths"].

None
band_names list[str] | None

Optional names for the target bands, written to the output's attrs["band_names"]. Default None (no names).

None
epsilon_srf float

SRF threshold below which contribution is ignored. Default 1e-4.

0.0001
extrapolate bool

Let georeader map grid wavelengths outside the source range to the nearest edge band (only matters for fractional source wavelengths). Default False.

False

Raises:

Type Description
ValueError

On inconsistent target arrays, a non-positive FWHM, a target the source range / 1-nm grid cannot represent, or source wavelengths missing or not matching the band count.

Examples:

>>> from geoops.radiometry import ApplySRF
>>> # Collapse a 5-band hyperspectral cube to two 20-nm-FWHM
>>> # Gaussian bands at 500 nm and 520 nm.
>>> op = ApplySRF(
...     target_center_wavelengths=[500.0, 520.0],
...     target_fwhm=[20.0, 20.0],
...     source_wavelengths=[480.0, 490.0, 500.0, 510.0, 520.0],
...     band_names=["b500", "b520"],
... )
>>> multispectral = op(hyperspectral_geoarray)
>>> # Source wavelengths can come from gt.attrs["wavelengths"].
>>> s2_like = ApplySRF(
...     target_center_wavelengths=[490.0, 665.0, 842.0],
...     target_fwhm=[65.0, 30.0, 115.0],
... )(emit_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class ApplySRF(Operator):
    r"""Convolve hyperspectral bands to target Gaussian-SRF multispectral bands.

    For each target band ``k`` with center wavelength ``λ_k`` and FWHM
    ``Δλ_k``, build a normalised Gaussian SRF (:func:`georeader.reflectance.srf`)
    on a 1-nm wavelength grid spanning the source range, then integrate
    with :func:`georeader.reflectance.transform_to_srf`, which maps each
    grid wavelength to its nearest source band:

    .. math::

        L_k \;=\; \frac{\displaystyle \int L(\lambda) \, R_k(\lambda) \, d\lambda}
                       {\displaystyle \int R_k(\lambda) \, d\lambda}

    The 1-nm grid keeps the SRF well defined when a target FWHM is much
    narrower than the source band spacing (the target then reads its
    nearest source band). Targets the grid cannot represent -- a centre
    outside the source range, or a FWHM far below 1 nm -- raise
    ``ValueError`` instead of returning an all-zero band.

    Nodata: the GeoArray goes to ``transform_to_srf`` (as georeader's
    carrier, through :func:`geoops._src.engine.to_engine`), which
    marks a target pixel missing when any source band *that target reads*
    (weight above ``epsilon_srf``) equals the input's
    ``fill_value``; non-finite source values propagate through the
    weighted sum the same way. Those pixels hold the carried fill
    (:func:`geoops._src.valid.carried_fill`: the input's fill for float
    input, ``NaN`` for integer DN promoted to float). Source bands a
    target does not read never invalidate it.

    Output ``attrs``: source per-band keys are dropped; ``wavelengths``
    holds the target centres and ``band_names`` the given ``band_names``.
    A ``(T, C, H, W)`` stack is convolved frame by frame. Plain
    ``np.ndarray`` input ``(B, H, W)`` returns a plain float32 array
    (``NaN`` at non-finite pixels; there is no fill value to match).

    Args:
        target_center_wavelengths: ``λ_k`` for each target band (nm).
        target_fwhm: FWHM for each target band (nm).
        source_wavelengths: Source hyperspectral band centres (nm).
            Default ``None`` reads ``gt.attrs["wavelengths"]``.
        band_names: Optional names for the target bands, written to the
            output's ``attrs["band_names"]``. Default ``None`` (no names).
        epsilon_srf: SRF threshold below which contribution is ignored.
            Default ``1e-4``.
        extrapolate: Let georeader map grid wavelengths outside the source
            range to the nearest edge band (only matters for fractional
            source wavelengths). Default ``False``.

    Raises:
        ValueError: On inconsistent target arrays, a non-positive FWHM, a
            target the source range / 1-nm grid cannot represent, or
            source wavelengths missing or not matching the band count.

    Examples:
        >>> from geoops.radiometry import ApplySRF
        >>> # Collapse a 5-band hyperspectral cube to two 20-nm-FWHM
        >>> # Gaussian bands at 500 nm and 520 nm.
        >>> op = ApplySRF(
        ...     target_center_wavelengths=[500.0, 520.0],
        ...     target_fwhm=[20.0, 20.0],
        ...     source_wavelengths=[480.0, 490.0, 500.0, 510.0, 520.0],
        ...     band_names=["b500", "b520"],
        ... )
        >>> multispectral = op(hyperspectral_geoarray)
        >>> # Source wavelengths can come from gt.attrs["wavelengths"].
        >>> s2_like = ApplySRF(
        ...     target_center_wavelengths=[490.0, 665.0, 842.0],
        ...     target_fwhm=[65.0, 30.0, 115.0],
        ... )(emit_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # each target band integrates the source bands under its SRF
    coupling: ClassVar[Coupling] = Coupling(
        couples={"band"}, effects={"band": "reduce"}
    )

    def __init__(
        self,
        *,
        target_center_wavelengths: np.ndarray | list[float],
        target_fwhm: np.ndarray | list[float],
        source_wavelengths: np.ndarray | list[float] | None = None,
        band_names: list[str] | None = None,
        epsilon_srf: float = 1e-4,
        extrapolate: bool = False,
    ) -> None:
        self.target_center_wavelengths = target_center_wavelengths
        self.target_fwhm = target_fwhm
        self.source_wavelengths = source_wavelengths
        self.band_names = band_names
        self.epsilon_srf = epsilon_srf
        self.extrapolate = extrapolate

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        srf = optional_name(
            "georeader.reflectance",
            "srf",
            "sensors",
            feature="geoops.radiometry.ApplySRF",
        )
        transform_to_srf = optional_name(
            "georeader.reflectance",
            "transform_to_srf",
            "sensors",
            feature="geoops.radiometry.ApplySRF",
        )
        n_bands = np.shape(gt)[0] if np.ndim(gt) == 3 else None
        if n_bands is None:
            raise ValueError(
                f"ApplySRF expects a (B, H, W) cube or a (T, B, H, W) stack; "
                f"got shape {np.shape(gt)}"
            )
        source_wavelengths = resolve_wavelengths(
            gt, self.source_wavelengths, n_bands=n_bands, name="source_wavelengths"
        )
        centers = np.asarray(self.target_center_wavelengths, dtype=float)
        fwhm = np.asarray(self.target_fwhm, dtype=float)
        if self.band_names is not None and len(self.band_names) != centers.size:
            raise ValueError(
                f"band_names has {len(self.band_names)} entries but there are "
                f"{centers.size} target band(s)"
            )
        grid = _srf_grid(source_wavelengths, extrapolate=self.extrapolate)
        _check_srf_targets(
            centers, fwhm, source_wavelengths, grid, epsilon_srf=self.epsilon_srf
        )
        with warnings.catch_warnings():
            # georeader normalises with ``np.divide(..., where=sum > 0)`` and
            # no ``out``; every column has a positive sum (checked above), so
            # the "uninitialized memory" warning does not apply.
            warnings.filterwarnings("ignore", message="'where' used without 'out'")
            srf_df = pd.DataFrame(srf(centers, fwhm, grid), index=grid)
        # A NaN fill_value makes every georeader-detected missing
        # pixel NaN, so it is found below together with pixels made
        # non-finite by NaN / inf source values.
        out = np.asarray(
            transform_to_srf(
                to_engine(gt),
                srf_df,
                source_wavelengths.tolist(),
                fill_value_default=np.nan,
                epsilon_srf=self.epsilon_srf,
                extrapolate=self.extrapolate,
            )
        )
        fill = carried_fill(gt, out.dtype)
        out = restore_fill(out, np.isfinite(out), fill)
        attrs = strip_band_attrs(getattr(gt, "attrs", None))
        attrs["wavelengths"] = jsonable(centers)
        return wrap_like(
            gt,
            out,
            fill_value=fill,
            attrs=attrs,
            band_names=self.band_names,
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "target_center_wavelengths": jsonable(
                np.asarray(self.target_center_wavelengths, dtype=float)
            ),
            "target_fwhm": jsonable(np.asarray(self.target_fwhm, dtype=float)),
            "source_wavelengths": (
                None
                if self.source_wavelengths is None
                else jsonable(np.asarray(self.source_wavelengths, dtype=float))
            ),
            "band_names": None if self.band_names is None else list(self.band_names),
            "epsilon_srf": self.epsilon_srf,
            "extrapolate": self.extrapolate,
        }

BTFromRadiance

Bases: Operator

Convert thermal at-sensor radiance to brightness temperature (Kelvin).

Inversion of the Planck blackbody radiation law, in the standard Landsat/MTL form:

.. math::

T_B \;=\; \frac{K_2}{\ln\!\bigl(K_1 / L + 1\bigr)}

where L is at-sensor thermal radiance and K1/K2 are sensor-specific pre-computed Planck constants supplied by the product metadata (Landsat-8 OLI/TIRS Band 10 example: K1=774.8853, K2=1321.0789). The output T_B is in Kelvin and represents the temperature a blackbody would need to emit the observed radiance — not the true surface temperature, which additionally requires emissivity and atmospheric correction.

Nodata pixels hold the output fill (see the module docstring).

Parameters:

Name Type Description Default
K1 float | ndarray | list

Per-band Planck constant K1. Scalar or per-band 1-D sequence (in radiance units, matching L).

required
K2 float | ndarray | list

Per-band Planck constant K2. Scalar or per-band 1-D sequence (Kelvin).

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.radiometry import BTFromRadiance
>>> # Landsat-8 TIRS Band 10 published constants.
>>> op = BTFromRadiance(K1=774.8853, K2=1321.0789)
>>> brightness_temp = op(radiance_geoarray)  # Kelvin
References

Planck, M. (1901). Ueber das Gesetz der Energieverteilung im Normalspectrum. Annalen der Physik 309, 553–563.

USGS Landsat-8 Data Users Handbook, §5.1 (TIRS thermal constants).

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class BTFromRadiance(Operator):
    r"""Convert thermal at-sensor radiance to brightness temperature (Kelvin).

    Inversion of the Planck blackbody radiation law, in the standard
    Landsat/MTL form:

    .. math::

        T_B \;=\; \frac{K_2}{\ln\!\bigl(K_1 / L + 1\bigr)}

    where ``L`` is at-sensor thermal radiance and ``K1``/``K2`` are
    sensor-specific pre-computed Planck constants supplied by the
    product metadata (Landsat-8 OLI/TIRS Band 10 example:
    ``K1=774.8853``, ``K2=1321.0789``). The output ``T_B`` is in
    Kelvin and represents the temperature a blackbody would need to
    emit the observed radiance — not the true surface temperature,
    which additionally requires emissivity and atmospheric correction.

    Nodata pixels hold the output fill (see the module docstring).

    Args:
        K1: Per-band Planck constant ``K1``. Scalar or per-band 1-D
            sequence (in radiance units, matching ``L``).
        K2: Per-band Planck constant ``K2``. Scalar or per-band 1-D
            sequence (Kelvin).
        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.radiometry import BTFromRadiance
        >>> # Landsat-8 TIRS Band 10 published constants.
        >>> op = BTFromRadiance(K1=774.8853, K2=1321.0789)
        >>> brightness_temp = op(radiance_geoarray)  # Kelvin

    References:
        Planck, M. (1901). Ueber das Gesetz der Energieverteilung im
        Normalspectrum. *Annalen der Physik* 309, 553–563.

        USGS Landsat-8 Data Users Handbook, §5.1 (TIRS thermal
        constants).
    """

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

    def __init__(
        self,
        *,
        K1: float | np.ndarray | list,
        K2: float | np.ndarray | list,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.K1 = K1
        self.K2 = K2
        self.dim = band_dim(dim, axis, "BTFromRadiance")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="BTFromRadiance")
        arr = np.asarray(gt)
        n_bands = arr.shape[axis] if arr.ndim > 2 else 1
        k1 = _broadcast_to_band_axis(self.K1, n_bands, axis, arr.ndim)
        k2 = _broadcast_to_band_axis(self.K2, n_bands, axis, arr.ndim)
        # NaN out nodata before the log so we don't pollute valid pixels
        # with -inf / 0; the output fill is written back afterwards.
        work = np.where(invalid_values(gt), np.nan, arr.astype(float, copy=False))
        out = bt_from_radiance(work, k1, k2)
        return _rewrap_carried(gt, out)

    def get_config(self) -> dict[str, Any]:
        return {
            "K1": jsonable(np.asarray(self.K1, dtype=float)),
            "K2": jsonable(np.asarray(self.K2, dtype=float)),
            "dim": self.dim,
        }

ComputeSZA

Bases: Operator

Compute the solar zenith angle (degrees) for a location and UTC datetime.

Graph source: computed from its configuration alone. An optional input is accepted and ignored, so it can close a Sequential.

The Astronomical Almanac's solar position (radiomax.geometry.solar_zenith), without refraction, within 0.0121° of SPA over 2000–2050. The SZA is the complement of the solar altitude — SZA = 90° - altitude — and enters the TOA reflectance equation through cos(θ_z).

Parameters:

Name Type Description Default
center_coords tuple[float, float]

(x, y) location. If crs_coords is None, interpreted as (lon, lat) in EPSG:4326.

required
acquisition_date datetime | str

UTC datetime of acquisition.

required
crs_coords str | None

CRS of center_coords. None → EPSG:4326.

None

Examples:

>>> from datetime import datetime
>>> from geoops.radiometry import ComputeSZA
>>> # Summer solstice noon at San Francisco.
>>> op = ComputeSZA(
...     center_coords=(-122.4, 37.8),
...     acquisition_date=datetime(2024, 6, 21, 20, 0),  # UTC
... )
>>> sza_deg = op()  # ~16° (close to local solar noon)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class ComputeSZA(Operator):
    """Compute the solar zenith angle (degrees) for a location and UTC datetime.

    Graph source: computed from its configuration alone. An optional
    input is accepted and ignored, so it can close a ``Sequential``.

    The Astronomical Almanac's solar position
    (`radiomax.geometry.solar_zenith`), without refraction, within 0.0121°
    of SPA over 2000–2050. The SZA is the complement of the
    solar altitude — ``SZA = 90° - altitude`` — and enters the TOA
    reflectance equation through ``cos(θ_z)``.

    Args:
        center_coords: ``(x, y)`` location. If ``crs_coords`` is
            ``None``, interpreted as ``(lon, lat)`` in EPSG:4326.
        acquisition_date: UTC datetime of acquisition.
        crs_coords: CRS of ``center_coords``. ``None`` → EPSG:4326.

    Examples:
        >>> from datetime import datetime
        >>> from geoops.radiometry import ComputeSZA
        >>> # Summer solstice noon at San Francisco.
        >>> op = ComputeSZA(
        ...     center_coords=(-122.4, 37.8),
        ...     acquisition_date=datetime(2024, 6, 21, 20, 0),  # UTC
        ... )
        >>> sza_deg = op()  # ~16° (close to local solar noon)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # computed from the location and time
    coupling: ClassVar[Coupling] = Coupling(kind="source")

    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        center_coords: tuple[float, float],
        acquisition_date: datetime | str,
        crs_coords: str | None = None,
    ) -> None:
        self.center_coords = center_coords
        self.acquisition_date = _parse_datetime(acquisition_date)
        self.crs_coords = crs_coords

    def _apply(self, _input: Any | None = None) -> float:
        reject_geotensor(_input, type(self).__name__)
        return compute_sza(
            self.center_coords,
            self.acquisition_date,
            crs_coords=self.crs_coords,
        )

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

DNToRadiance

Bases: Operator

Convert DN to at-sensor radiance.

.. math::

L \;=\; \text{gain} \cdot DN / \text{scale} + \text{offset}

Pure linear decode; gain and offset come from sensor metadata. Pass scalars for uniform per-pixel coefficients, or 1-D sequences with one entry per band to apply different coefficients along the band axis.

See :func:~geoops.radiometry._src.array.dn_to_radiance for the physics. The Operator additionally reshapes 1-D coefficients so they broadcast along the configured axis.

Parameters:

Name Type Description Default
gain float | ndarray | list

Slope of the DN→L decode. Scalar or per-band sequence.

required
offset float | ndarray | list

Intercept. Default 0.0.

0.0
scale float | ndarray | list

DN scale divisor, applied before the gain. Scalar or per-band sequence. Default 1.0.

1.0
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import numpy as np
>>> from geoops.radiometry import DNToRadiance
>>> # Landsat-8 OLI per-band radiance multiplicative + additive
>>> # constants from the MTL file (just illustrative numbers):
>>> gains   = np.array([0.012, 0.013, 0.011, 0.009])
>>> offsets = np.array([-60.0, -61.0, -55.0, -45.0])
>>> dn_to_rad = DNToRadiance(gain=gains, offset=offsets)
>>> radiance = dn_to_rad(dn_geoarray)  # shape preserved
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class DNToRadiance(Operator):
    r"""Convert DN to at-sensor radiance.

    .. math::

        L \;=\; \text{gain} \cdot DN / \text{scale} + \text{offset}

    Pure linear decode; gain and offset come from sensor metadata. Pass
    scalars for uniform per-pixel coefficients, or 1-D sequences with
    one entry per band to apply different coefficients along the band
    axis.

    See :func:`~geoops.radiometry._src.array.dn_to_radiance` for the
    physics. The Operator additionally reshapes 1-D coefficients so
    they broadcast along the configured ``axis``.

    Args:
        gain: Slope of the DN→L decode. Scalar or per-band sequence.
        offset: Intercept. Default ``0.0``.
        scale: DN scale divisor, applied before the gain. Scalar or
            per-band sequence. Default ``1.0``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import numpy as np
        >>> from geoops.radiometry import DNToRadiance
        >>> # Landsat-8 OLI per-band radiance multiplicative + additive
        >>> # constants from the MTL file (just illustrative numbers):
        >>> gains   = np.array([0.012, 0.013, 0.011, 0.009])
        >>> offsets = np.array([-60.0, -61.0, -55.0, -45.0])
        >>> dn_to_rad = DNToRadiance(gain=gains, offset=offsets)
        >>> radiance = dn_to_rad(dn_geoarray)  # shape preserved
    """

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

    def __init__(
        self,
        *,
        gain: float | np.ndarray | list,
        offset: float | np.ndarray | list = 0.0,
        scale: float | np.ndarray | list = 1.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.gain = gain
        self.offset = offset
        self.scale = scale
        self.dim = band_dim(dim, axis, "DNToRadiance")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="DNToRadiance")
        arr = np.asarray(gt)
        n_bands = arr.shape[axis] if arr.ndim > 2 else 1
        gain = _broadcast_to_band_axis(self.gain, n_bands, axis, arr.ndim)
        offset = _broadcast_to_band_axis(self.offset, n_bands, axis, arr.ndim)
        scale = _broadcast_to_band_axis(self.scale, n_bands, axis, arr.ndim)
        out = dn_to_radiance(arr, gain, offset, scale)
        return _rewrap_carried(gt, out)

    def get_config(self) -> dict[str, Any]:
        return {
            "gain": jsonable(np.asarray(self.gain, dtype=float)),
            "offset": jsonable(np.asarray(self.offset, dtype=float)),
            "scale": jsonable(np.asarray(self.scale, dtype=float)),
            "dim": self.dim,
        }

DNToReflectance

Bases: Operator

Convert DN to TOA / surface reflectance via a linear affine decode.

.. math::

\rho \;=\; \text{scale} \cdot DN + \text{offset}

scale is the slope (reflectance per DN unit) and offset is the reflectance-units intercept — the canonical y = m * x + b form. Matches Landsat Collection-2 SR verbatim and absorbs the Sentinel-2 L1C RADIO_ADD_OFFSET after multiplying it through the scale.

For sensors without a pre-scaled-reflectance product (raw radiance only), use DNToRadiance then call georeader.reflectance.radiance_to_reflectance (which handles solar geometry properly).

Parameters:

Name Type Description Default
scale float | ndarray | list

Quantification slope (reflectance per DN unit). Scalar or per-band 1-D sequence.

required
offset float | ndarray | list

Reflectance-units intercept. Default 0.0.

0.0
dim str

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

'band'
axis int | None

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

None

Examples:

>>> from geoops.radiometry import DNToReflectance
>>> # Sentinel-2 L1C pre-2022: a single global scale, no offset.
>>> op = DNToReflectance(scale=1e-4)
>>> reflectance = op(s2_l1c_dn_geoarray)
>>>
>>> # Post-2022 S2 L1C: RADIO_ADD_OFFSET=-1000 in DN units
>>> # collapses to -0.1 in reflectance units (-1000 * 1e-4).
>>> op_v2 = DNToReflectance(scale=1e-4, offset=-0.1)
>>> reflectance = op_v2(s2_l1c_modern_dn_geoarray)
>>>
>>> # Landsat-8/9 Collection-2 surface reflectance.
>>> op_l8 = DNToReflectance(scale=2.75e-5, offset=-0.2)
>>> reflectance = op_l8(landsat_c2_sr_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class DNToReflectance(Operator):
    r"""Convert DN to TOA / surface reflectance via a linear affine decode.

    .. math::

        \rho \;=\; \text{scale} \cdot DN + \text{offset}

    ``scale`` is the slope (reflectance per DN unit) and ``offset`` is
    the *reflectance-units* intercept — the canonical
    ``y = m * x + b`` form. Matches Landsat Collection-2 SR verbatim
    and absorbs the Sentinel-2 L1C ``RADIO_ADD_OFFSET`` after
    multiplying it through the scale.

    For sensors without a pre-scaled-reflectance product (raw radiance
    only), use `DNToRadiance` then call
    `georeader.reflectance.radiance_to_reflectance` (which handles
    solar geometry properly).

    Args:
        scale: Quantification slope (reflectance per DN unit). Scalar
            or per-band 1-D sequence.
        offset: Reflectance-units intercept. Default ``0.0``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> from geoops.radiometry import DNToReflectance
        >>> # Sentinel-2 L1C pre-2022: a single global scale, no offset.
        >>> op = DNToReflectance(scale=1e-4)
        >>> reflectance = op(s2_l1c_dn_geoarray)
        >>>
        >>> # Post-2022 S2 L1C: RADIO_ADD_OFFSET=-1000 in DN units
        >>> # collapses to -0.1 in reflectance units (-1000 * 1e-4).
        >>> op_v2 = DNToReflectance(scale=1e-4, offset=-0.1)
        >>> reflectance = op_v2(s2_l1c_modern_dn_geoarray)
        >>>
        >>> # Landsat-8/9 Collection-2 surface reflectance.
        >>> op_l8 = DNToReflectance(scale=2.75e-5, offset=-0.2)
        >>> reflectance = op_l8(landsat_c2_sr_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # rho = scale * DN + offset, per band and pixel
    coupling: ClassVar[Coupling] = Coupling()

    def __init__(
        self,
        *,
        scale: float | np.ndarray | list,
        offset: float | np.ndarray | list = 0.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.scale = scale
        self.offset = offset
        self.dim = band_dim(dim, axis, "DNToReflectance")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="DNToReflectance")
        arr = np.asarray(gt)
        n_bands = arr.shape[axis] if arr.ndim > 2 else 1
        scale = _broadcast_to_band_axis(self.scale, n_bands, axis, arr.ndim)
        offset = _broadcast_to_band_axis(self.offset, n_bands, axis, arr.ndim)
        out = dn_to_reflectance(arr, scale, offset)
        return _rewrap_carried(gt, out)

    def get_config(self) -> dict[str, Any]:
        return {
            "scale": jsonable(np.asarray(self.scale, dtype=float)),
            "offset": jsonable(np.asarray(self.offset, dtype=float)),
            "dim": self.dim,
        }

DOS1

Bases: Operator

Apply a Chavez (1988) Dark-Object Subtraction (DOS1) approximation.

The simplest atmospheric correction in the DOS family: for each band, estimate the path-radiance / haze contribution as the darkest pixel (or low-percentile value) in the scene, then subtract it. Pixels in deep shadow or clear water should approach zero reflectance in the absence of atmospheric scattering, so any observed positive minimum is taken as the haze offset.

.. math::

\rho_{\text{surface},\,k}(x, y) \;=\; \max\!\bigl(\,\rho_{\text{TOA},\,k}(x, y) - \rho_{\text{dark},\,k},\; 0\bigr)

where ρ_dark,k is the configured low-percentile of band k over the spatial axes. DOS1 assumes a single-scattering atmosphere with no transmission correction — the more accurate variants (DOS2, DOS3, DOS4 from Chavez 1996) layer atmospheric transmission and Rayleigh modelling on top.

Fill-value pixels are excluded from the dark-object percentile and hold the output fill (see the module docstring).

Parameters:

Name Type Description Default
dark_percentile float

Spatial percentile in [0, 100] taken as the dark-object value per band. Default 1.0 (1st percentile is more robust than the absolute minimum against single-pixel sensor noise).

1.0

Examples:

>>> from geoops.radiometry import DOS1
>>> # Subtract the 1st-percentile haze per band from TOA
>>> # reflectance to approximate surface reflectance.
>>> op = DOS1(dark_percentile=1.0)
>>> surface = op(toa_reflectance_geoarray)
References

Chavez, P. S. (1988). An improved dark-object subtraction technique for atmospheric scattering correction of multispectral data. Remote Sensing of Environment 24(3), 459–479.

Chavez, P. S. (1996). Image-based atmospheric corrections — Revisited and improved. Photogrammetric Engineering & Remote Sensing 62(9), 1025–1036.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class DOS1(Operator):
    r"""Apply a Chavez (1988) Dark-Object Subtraction (DOS1) approximation.

    The simplest atmospheric correction in the DOS family: for each
    band, estimate the path-radiance / haze contribution as the
    darkest pixel (or low-percentile value) in the scene, then
    subtract it. Pixels in deep shadow or clear water should approach
    zero reflectance in the absence of atmospheric scattering, so any
    observed positive minimum is taken as the haze offset.

    .. math::

        \rho_{\text{surface},\,k}(x, y) \;=\; \max\!\bigl(\,\rho_{\text{TOA},\,k}(x, y) - \rho_{\text{dark},\,k},\; 0\bigr)

    where ``ρ_dark,k`` is the configured low-percentile of band ``k``
    over the spatial axes. DOS1 assumes a single-scattering atmosphere
    with no transmission correction — the more accurate variants
    (DOS2, DOS3, DOS4 from Chavez 1996) layer atmospheric transmission
    and Rayleigh modelling on top.

    Fill-value pixels are excluded from the dark-object percentile and
    hold the output fill (see the module docstring).

    Args:
        dark_percentile: Spatial percentile in ``[0, 100]`` taken as
            the dark-object value per band. Default ``1.0`` (1st
            percentile is more robust than the absolute minimum
            against single-pixel sensor noise).

    Examples:
        >>> from geoops.radiometry import DOS1
        >>> # Subtract the 1st-percentile haze per band from TOA
        >>> # reflectance to approximate surface reflectance.
        >>> op = DOS1(dark_percentile=1.0)
        >>> surface = op(toa_reflectance_geoarray)

    References:
        Chavez, P. S. (1988). An improved dark-object subtraction
        technique for atmospheric scattering correction of multispectral
        data. *Remote Sensing of Environment* 24(3), 459–479.

        Chavez, P. S. (1996). Image-based atmospheric corrections —
        Revisited and improved. *Photogrammetric Engineering & Remote
        Sensing* 62(9), 1025–1036.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # the dark object is a low percentile of each band over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

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

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        # NaN out nodata so the percentile reflects only valid data.
        work = mask_invalid_to_nan(gt, dtype=float)
        out = dos1(work, dark_percentile=self.dark_percentile, reduce_axes=(-2, -1))
        return _rewrap_carried(gt, out)

EarthSunDistanceCorrection

Bases: Operator

Compute the Earth–Sun distance d (in AU) for an acquisition date.

Graph source: computed from its configuration alone. An optional input is accepted and ignored, so it can close a Sequential.

The Astronomical Almanac's formula (radiomax.geometry.earth_sun_distance), within 8.7e-5 AU of SPA over 2000–2050.

Perihelion (~Jan 3-4) → d ≈ 0.983 AU; aphelion (~Jul 4) → d ≈ 1.017 AU. The irradiance reaching Earth scales as 1/d² (inverse square law); the d² factor appears in the TOA-reflectance equation.

Returns a scalar — useful as a building block inside Graph pipelines that need to thread the value through to a downstream operator (e.g. an in-graph reflectance conversion).

Parameters:

Name Type Description Default
acquisition_date datetime | str

Date and time of acquisition, UTC unless it carries a time zone.

required

Examples:

>>> from datetime import datetime
>>> from geoops.radiometry import EarthSunDistanceCorrection
>>> d = EarthSunDistanceCorrection(acquisition_date=datetime(2024, 1, 3))()
>>> # Perihelion -> ~0.983 AU.
>>> round(d, 3)
0.983
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class EarthSunDistanceCorrection(Operator):
    r"""Compute the Earth–Sun distance ``d`` (in AU) for an acquisition date.

    Graph source: computed from its configuration alone. An optional
    input is accepted and ignored, so it can close a ``Sequential``.

    The Astronomical Almanac's formula (`radiomax.geometry.earth_sun_distance`),
    within 8.7e-5 AU of SPA over 2000–2050.

    Perihelion (~Jan 3-4) → ``d ≈ 0.983 AU``; aphelion (~Jul 4) →
    ``d ≈ 1.017 AU``. The irradiance reaching Earth scales as
    ``1/d²`` (inverse square law); the ``d²`` factor appears in the
    TOA-reflectance equation.

    Returns a scalar — useful as a building block inside `Graph`
    pipelines that need to thread the value through to a downstream
    operator (e.g. an in-graph reflectance conversion).

    Args:
        acquisition_date: Date and time of acquisition, UTC unless it
            carries a time zone.

    Examples:
        >>> from datetime import datetime
        >>> from geoops.radiometry import EarthSunDistanceCorrection
        >>> d = EarthSunDistanceCorrection(acquisition_date=datetime(2024, 1, 3))()
        >>> # Perihelion -> ~0.983 AU.
        >>> round(d, 3)
        0.983
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # computed from the acquisition date
    coupling: ClassVar[Coupling] = Coupling(kind="source")

    _terminal: ClassVar[bool] = True

    def __init__(self, *, acquisition_date: datetime | str) -> None:
        self.acquisition_date = _parse_datetime(acquisition_date)

    def _apply(self, _input: Any | None = None) -> float:
        reject_geotensor(_input, type(self).__name__)
        return earth_sun_distance_correction_factor(self.acquisition_date)

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

Gamma

Bases: Operator

Power-law gamma correction.

.. math::

y \;=\; x^{1/\gamma}

Display-prep — gamma > 1 brightens midtones, gamma < 1 darkens them. A gentle gamma = 1.2 is the workhorse "satellite RGB pop" default; sRGB encoding uses gamma ≈ 2.2. Values above 1 are not clipped; :class:geoops.viz.GammaCorrect is the display-range variant (clips floats to [0, 1], handles byte carriers) built on the same :func:gamma_correct.

Parameters:

Name Type Description Default
gamma float

Gamma factor (must be strictly positive). Default 1.2.

1.2

Examples:

>>> import geoops as gz
>>> # Classic display pipeline: stretch, then gamma-brighten.
>>> pipe = (
...     gz.radiometry.PercentileClip()
...     | gz.radiometry.Gamma(gamma=1.4)
... )
>>> rgb = pipe(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class Gamma(Operator):
    r"""Power-law gamma correction.

    .. math::

        y \;=\; x^{1/\gamma}

    Display-prep — ``gamma > 1`` brightens midtones, ``gamma < 1``
    darkens them. A gentle ``gamma = 1.2`` is the workhorse "satellite
    RGB pop" default; sRGB encoding uses ``gamma ≈ 2.2``. Values above
    ``1`` are not clipped; :class:`geoops.viz.GammaCorrect` is the
    display-range variant (clips floats to ``[0, 1]``, handles byte
    carriers) built on the same :func:`gamma_correct`.

    Args:
        gamma: Gamma factor (must be strictly positive). Default ``1.2``.

    Examples:
        >>> import geoops as gz
        >>> # Classic display pipeline: stretch, then gamma-brighten.
        >>> pipe = (
        ...     gz.radiometry.PercentileClip()
        ...     | gz.radiometry.Gamma(gamma=1.4)
        ... )
        >>> rgb = pipe(reflectance_geoarray)
    """

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

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

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = gamma_correct(np.asarray(gt), gamma=self.gamma)
        return _rewrap_stretch(gt, out)

IntegratedIrradiance

Bases: Operator

Compute band-integrated TOA solar irradiance from an SRF table.

Graph source: computed from its configuration alone. An optional input is accepted and ignored, so it can close a Sequential.

.. math::

E_k \;=\; \frac{\displaystyle \int E_{\text{sun}}(\lambda) \, R_k(\lambda) \, d\lambda}
               {\displaystyle \int R_k(\lambda) \, d\lambda}

Integrates a TOA solar spectrum (Thuillier 2003 by default, from georeader) over a per-band spectral response function R_k(λ), both read as linear between their samples (radiomax.radiometry.response_matrix), to yield the band-effective irradiance E_k that feeds RadianceToReflectance. Output units match the input solar spectrum (mW/m²/nm for the default Thuillier table — divide by 1000 before handing to the reflectance equation, which expects SI W/m²/nm).

Holds a pandas.DataFrame — not YAML-serialisable, hence forbid_in_yaml = True.

Parameters:

Name Type Description Default
srf DataFrame

Spectral response DataFrame. Index = wavelength (nm), columns = band names. Shape (N, K).

required
solar_irradiance DataFrame | None

Optional solar-spectrum DataFrame with columns ["Nanometer", "Radiance(mW/m2/nm)"]. Defaults to Thuillier 2003.

None
epsilon_srf float

The ends of the SRF table where no band's response is above this are dropped. Default 1e-4.

0.0001

Examples:

>>> import numpy as np
>>> import pandas as pd
>>> from geoops.radiometry import IntegratedIrradiance
>>> # Toy 3-wavelength SRF for a single band.
>>> srf_df = pd.DataFrame({"B1": [1.0, 1.0, 1.0]}, index=[499.0, 500.0, 501.0])
>>> # Flat 2 mW/m²/nm solar spectrum.
>>> solar = pd.DataFrame(
...     {"Nanometer": [499.0, 500.0, 501.0],
...      "Radiance(mW/m2/nm)": [2.0, 2.0, 2.0]}
... )
>>> e_band = IntegratedIrradiance(srf=srf_df, solar_irradiance=solar)()
>>> e_band
array([2.])
References

Thuillier, G. et al. (2003). The Solar Spectral Irradiance from 200 to 2400 nm as Measured by the SOLSPEC Spectrometer. Solar Physics 214(1), 1–22.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class IntegratedIrradiance(Operator):
    r"""Compute band-integrated TOA solar irradiance from an SRF table.

    Graph source: computed from its configuration alone. An optional
    input is accepted and ignored, so it can close a ``Sequential``.

    .. math::

        E_k \;=\; \frac{\displaystyle \int E_{\text{sun}}(\lambda) \, R_k(\lambda) \, d\lambda}
                       {\displaystyle \int R_k(\lambda) \, d\lambda}

    Integrates a TOA solar spectrum (Thuillier 2003 by default, from
    georeader) over a per-band spectral response function ``R_k(λ)``,
    both read as linear between their samples
    (`radiomax.radiometry.response_matrix`), to yield the
    band-effective irradiance ``E_k`` that feeds
    `RadianceToReflectance`. Output units match the input solar
    spectrum (``mW/m²/nm`` for the default Thuillier table — divide by
    1000 before handing to the reflectance equation, which expects
    SI ``W/m²/nm``).

    Holds a ``pandas.DataFrame`` — not YAML-serialisable, hence
    ``forbid_in_yaml = True``.

    Args:
        srf: Spectral response DataFrame. Index = wavelength (nm),
            columns = band names. Shape ``(N, K)``.
        solar_irradiance: Optional solar-spectrum DataFrame with
            columns ``["Nanometer", "Radiance(mW/m2/nm)"]``. Defaults
            to Thuillier 2003.
        epsilon_srf: The ends of the SRF table where no band's response is
            above this are dropped. Default ``1e-4``.

    Examples:
        >>> import numpy as np
        >>> import pandas as pd
        >>> from geoops.radiometry import IntegratedIrradiance
        >>> # Toy 3-wavelength SRF for a single band.
        >>> srf_df = pd.DataFrame({"B1": [1.0, 1.0, 1.0]}, index=[499.0, 500.0, 501.0])
        >>> # Flat 2 mW/m²/nm solar spectrum.
        >>> solar = pd.DataFrame(
        ...     {"Nanometer": [499.0, 500.0, 501.0],
        ...      "Radiance(mW/m2/nm)": [2.0, 2.0, 2.0]}
        ... )
        >>> e_band = IntegratedIrradiance(srf=srf_df, solar_irradiance=solar)()
        >>> e_band
        array([2.])

    References:
        Thuillier, G. et al. (2003). The Solar Spectral Irradiance from
        200 to 2400 nm as Measured by the SOLSPEC Spectrometer. *Solar
        Physics* 214(1), 1–22.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # computed from the SRF table
    coupling: ClassVar[Coupling] = Coupling(kind="source")

    # Holds a ``pandas.DataFrame``, not YAML-serialisable.
    forbid_in_yaml: ClassVar[bool] = True
    _terminal: ClassVar[bool] = True

    def __init__(
        self,
        *,
        srf: pd.DataFrame,
        solar_irradiance: pd.DataFrame | None = None,
        epsilon_srf: float = 1e-4,
    ) -> None:
        self.srf = srf
        self.solar_irradiance = solar_irradiance
        self.epsilon_srf = epsilon_srf

    def _apply(self, _input: Any | None = None) -> np.ndarray:
        reject_geotensor(_input, type(self).__name__)
        solar = self.solar_irradiance
        if solar is None:
            solar = optional_name(
                "georeader.reflectance",
                "load_thuillier_irradiance",
                "sensors",
                feature="geoops.radiometry.IntegratedIrradiance (the default "
                "solar spectrum)",
            )()
        # the table without its tails, where every band is at most epsilon
        seen = np.flatnonzero((self.srf > self.epsilon_srf).any(axis=1))
        if seen.size == 0:
            raise ValueError(
                f"no band of the SRF has a response above {self.epsilon_srf:g}"
            )
        table = self.srf.iloc[seen[0] : seen[-1] + 1]
        wavelength = table.index.to_numpy(dtype=float)
        nodes = solar["Nanometer"].to_numpy(dtype=float)
        inside = (nodes >= wavelength[0]) & (nodes <= wavelength[-1])
        matrix = response_matrix(
            table.to_numpy(dtype=float).T, wavelength, nodes[inside]
        )
        # E_k = ∫ E R_k dλ / ∫ R_k dλ
        return matrix @ solar["Radiance(mW/m2/nm)"].to_numpy(dtype=float)[inside]

    def get_config(self) -> dict[str, Any]:
        # Debug payload: summarise the DataFrames instead of embedding them.
        def summary(frame: pd.DataFrame | None) -> dict[str, Any] | None:
            if frame is None:
                return None
            return {"columns": [str(c) for c in frame.columns], "n_rows": len(frame)}

        return {
            "srf": summary(self.srf),
            "solar_irradiance": summary(self.solar_irradiance),
            "epsilon_srf": self.epsilon_srf,
        }

MinMaxStretch

Bases: Operator

Linear contrast stretch into [0, 1].

.. math::

y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}

Display-prep — no physics; just a fixed-bound rescale. See PercentileClip for the more robust per-scene variant.

Parameters:

Name Type Description Default
vmin float

Lower bound (maps to 0).

required
vmax float

Upper bound (maps to 1). Must be strictly greater than vmin.

required
clip bool

Whether to clamp output to [0, 1]. Default True.

True

Examples:

>>> from geoops.radiometry import MinMaxStretch
>>> # Stretch reflectance in [0, 0.3] to display range.
>>> op = MinMaxStretch(vmin=0.0, vmax=0.3)
>>> display_ready = op(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class MinMaxStretch(Operator):
    r"""Linear contrast stretch into ``[0, 1]``.

    .. math::

        y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}

    Display-prep — no physics; just a fixed-bound rescale. See
    `PercentileClip` for the more robust per-scene variant.

    Args:
        vmin: Lower bound (maps to 0).
        vmax: Upper bound (maps to 1). Must be strictly greater than
            ``vmin``.
        clip: Whether to clamp output to ``[0, 1]``. Default ``True``.

    Examples:
        >>> from geoops.radiometry import MinMaxStretch
        >>> # Stretch reflectance in [0, 0.3] to display range.
        >>> op = MinMaxStretch(vmin=0.0, vmax=0.3)
        >>> display_ready = op(reflectance_geoarray)
    """

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

    def __init__(self, *, vmin: float, vmax: float, clip: bool = True) -> None:
        self.vmin = vmin
        self.vmax = vmax
        self.clip = clip

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        out = min_max_normalize(np.asarray(gt), self.vmin, self.vmax, clip=self.clip)
        return _rewrap_stretch(gt, out)

PercentileClip

Bases: Operator

Per-band robust contrast stretch using percentile thresholds.

Computes :math:v_{lo} = P_{\text{lower}}(\text{arr}) and :math:v_{hi} = P_{\text{upper}}(\text{arr}) over the configured reduce_axes and rescales each slice into [0, 1]. NaN-safe: nodata (fill / non-finite) pixels never enter the percentiles and come back NaN. This is the one percentile stretch the display operators build on — :class:geoops.viz.StretchToUint8 is this operator followed by a byte cast, and :class:geoops.normalize.HistogramStretch rescales its output into an arbitrary out_range; all three share the lower / upper / reduce_axes vocabulary.

Robust against bright outliers (cumulus, specular reflection, sensor saturation): a tiny sub-percent population of bright pixels won't crush the rest of the histogram the way a true min/max would.

Parameters:

Name Type Description Default
lower float

Lower percentile. Default 2.0.

2.0
upper float

Upper percentile. Default 98.0; must exceed lower.

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

Axis (or tuple) to compute percentiles over. (-2, -1) is per-band/-time. None is global.

(-2, -1)

Examples:

>>> from geoops.radiometry import PercentileClip
>>> # Standard "satellite RGB" stretch -- per-band 2-98 %.
>>> op = PercentileClip(lower=2.0, upper=98.0)
>>> rgb = op(reflectance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class PercentileClip(Operator):
    r"""Per-band robust contrast stretch using percentile thresholds.

    Computes :math:`v_{lo} = P_{\text{lower}}(\text{arr})` and
    :math:`v_{hi} = P_{\text{upper}}(\text{arr})` over the configured
    ``reduce_axes`` and rescales each slice into ``[0, 1]``. NaN-safe: nodata
    (fill / non-finite) pixels never enter the percentiles and come back
    ``NaN``. This is the one percentile stretch the display operators
    build on — :class:`geoops.viz.StretchToUint8` is this operator
    followed by a byte cast, and :class:`geoops.normalize.HistogramStretch`
    rescales its output into an arbitrary ``out_range``; all three share
    the ``lower`` / ``upper`` / ``reduce_axes`` vocabulary.

    Robust against bright outliers (cumulus, specular reflection, sensor
    saturation): a tiny sub-percent population of bright pixels won't
    crush the rest of the histogram the way a true min/max would.

    Args:
        lower: Lower percentile. Default ``2.0``.
        upper: Upper percentile. Default ``98.0``; must exceed ``lower``.
        reduce_axes: Axis (or tuple) to compute percentiles over.
            ``(-2, -1)`` is per-band/-time. ``None`` is global.

    Examples:
        >>> from geoops.radiometry import PercentileClip
        >>> # Standard "satellite RGB" stretch -- per-band 2-98 %.
        >>> op = PercentileClip(lower=2.0, upper=98.0)
        >>> rgb = op(reflectance_geoarray)
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # per-band percentiles over the scene, then a pointwise stretch
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        lower: float = 2.0,
        upper: float = 98.0,
        reduce_axes: int | tuple[int, ...] | None = (-2, -1),
    ) -> None:
        self.lower = lower
        self.upper = upper
        self.reduce_axes = as_tuple(reduce_axes)

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        # Nodata never enters the percentiles (``nanpercentile``). The mask
        # is per frame, so a pixel missing in one frame of a (T, C, H, W)
        # stack stays valid in the others.
        values = (
            mask_invalid_to_nan(gt, valid=valid_pixels(gt, keep_time=True))
            if np.ndim(gt) >= 2
            else np.asarray(gt)
        )
        out = percentile_clip(
            values, lower=self.lower, upper=self.upper, reduce_axes=self.reduce_axes
        )
        return _rewrap_stretch(gt, out)

RadianceToDN

Bases: Operator

Convert at-sensor radiance back to raw DN — inverse of DNToRadiance.

.. math::

DN \;=\; (L - \text{offset}) \cdot \text{scale} / \text{gain}

The exact algebraic inverse of DNToRadiance; mostly useful when you've manipulated radiance in physical units and want to round-trip back to a sensor-native integer encoding (e.g. for re-quantisation studies or for round-trip testing of an end-to-end pipeline).

Parameters:

Name Type Description Default
gain float | ndarray | list

Slope used by the forward decode. Scalar or per-band.

required
offset float | ndarray | list

Intercept used by the forward decode. Default 0.0.

0.0
scale float | ndarray | list

DN scale divisor used by the forward decode. Default 1.0.

1.0
dim str

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

'band'
axis int | None

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

None

Examples:

>>> import numpy as np
>>> from geoops.radiometry import DNToRadiance, RadianceToDN
>>> # Round-trip a synthetic radiance back to DN.
>>> radiance = DNToRadiance(gain=0.012, offset=-60.0)(dn_geoarray)
>>> dn = RadianceToDN(gain=0.012, offset=-60.0)(radiance)
>>> np.allclose(np.asarray(dn), np.asarray(dn_geoarray))
True
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class RadianceToDN(Operator):
    r"""Convert at-sensor radiance back to raw DN — inverse of `DNToRadiance`.

    .. math::

        DN \;=\; (L - \text{offset}) \cdot \text{scale} / \text{gain}

    The exact algebraic inverse of `DNToRadiance`; mostly useful when
    you've manipulated radiance in physical units and want to round-trip
    back to a sensor-native integer encoding (e.g. for re-quantisation
    studies or for round-trip testing of an end-to-end pipeline).

    Args:
        gain: Slope used by the forward decode. Scalar or per-band.
        offset: Intercept used by the forward decode. Default ``0.0``.
        scale: DN scale divisor used by the forward decode.
            Default ``1.0``.
        dim: Name of the band dim (default ``"band"``); its position is read
            from the carrier's dims.
        axis: Deprecated: the band axis position. ``-3`` maps to
            ``dim="band"``; removed in the next minor release.

    Examples:
        >>> import numpy as np
        >>> from geoops.radiometry import DNToRadiance, RadianceToDN
        >>> # Round-trip a synthetic radiance back to DN.
        >>> radiance = DNToRadiance(gain=0.012, offset=-60.0)(dn_geoarray)
        >>> dn = RadianceToDN(gain=0.012, offset=-60.0)(radiance)
        >>> np.allclose(np.asarray(dn), np.asarray(dn_geoarray))
        True
    """

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

    def __init__(
        self,
        *,
        gain: float | np.ndarray | list,
        offset: float | np.ndarray | list = 0.0,
        scale: float | np.ndarray | list = 1.0,
        dim: str = "band",
        axis: int | None = None,
    ) -> None:
        self.gain = gain
        self.offset = offset
        self.scale = scale
        self.dim = band_dim(dim, axis, "RadianceToDN")

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        axis = dim_axis(gt, self.dim, name="RadianceToDN")
        arr = np.asarray(gt)
        n_bands = arr.shape[axis] if arr.ndim > 2 else 1
        gain = _broadcast_to_band_axis(self.gain, n_bands, axis, arr.ndim)
        offset = _broadcast_to_band_axis(self.offset, n_bands, axis, arr.ndim)
        scale = _broadcast_to_band_axis(self.scale, n_bands, axis, arr.ndim)
        out = radiance_to_dn(arr, gain, offset, scale)
        return _rewrap_carried(gt, out)

    def get_config(self) -> dict[str, Any]:
        return {
            "gain": jsonable(np.asarray(self.gain, dtype=float)),
            "offset": jsonable(np.asarray(self.offset, dtype=float)),
            "scale": jsonable(np.asarray(self.scale, dtype=float)),
            "dim": self.dim,
        }

RadianceToReflectance

Bases: Operator

Convert at-sensor radiance to TOA reflectance with solar geometry.

.. math::

\rho \;=\; \frac{L \, \pi \, d^{2}}{E_{\text{sun}} \, \cos(\theta_z)}

where L is at-sensor radiance, E_sun is per-band TOA solar irradiance in :math:W \cdot m^{-2} \cdot nm^{-1}, d is the Earth–Sun distance (AU) for the acquisition date and θ_z is the solar zenith angle. The factor π·d²/cos(θ_z) is the observation-date correction factor — pass sza_deg to provide the angle from metadata, or center_coords to compute one angle there for the whole scene.

This is a carrier-aware wrapper around radiomax.radiometry.reflectance, with the unit table and the JSON-safe get_config.

Geo-dependence: when neither sza_deg nor center_coords is provided, the solar zenith is computed at every pixel, so the input must be a georeferenced GeoArray (plain arrays raise TypeError in that mode). Pixels at night (a zenith of 90° or more) hold the fill.

Parameters:

Name Type Description Default
solar_irradiance ndarray | list

Per-band TOA solar irradiance in W/m²/nm, shape (C,).

required
acquisition_date datetime | str

UTC datetime of acquisition.

required
center_coords tuple[float, float] | None

Optional (lon, lat) for the SZA computation. Without it, every pixel has its own.

None
sza_deg float | None

Optional pre-computed solar zenith angle in degrees. If provided, center_coords is ignored.

None
crs_coords str | None

CRS of center_coords. None → EPSG:4326.

None
units str

Radiance units. One of "W/m2/sr/nm", "mW/m2/sr/nm", "uW/cm^2/SR/nm".

'W/m2/sr/nm'

Examples:

>>> from datetime import datetime
>>> import numpy as np
>>> from geoops.radiometry import RadianceToReflectance
>>> op = RadianceToReflectance(
...     solar_irradiance=np.array([1.95, 1.85, 1.55]),
...     acquisition_date=datetime(2024, 6, 21, 10, 30),
...     sza_deg=27.0,
...     units="W/m2/sr/nm",
... )
>>> reflectance = op(radiance_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class RadianceToReflectance(Operator):
    r"""Convert at-sensor radiance to TOA reflectance with solar geometry.

    .. math::

        \rho \;=\; \frac{L \, \pi \, d^{2}}{E_{\text{sun}} \, \cos(\theta_z)}

    where ``L`` is at-sensor radiance, ``E_sun`` is per-band TOA solar
    irradiance in :math:`W \cdot m^{-2} \cdot nm^{-1}`, ``d`` is the
    Earth–Sun distance (AU) for the acquisition date and ``θ_z`` is the
    solar zenith angle. The factor ``π·d²/cos(θ_z)`` is the
    *observation-date correction factor* — pass ``sza_deg`` to provide
    the angle from metadata, or ``center_coords`` to compute one angle
    there for the whole scene.

    This is a carrier-aware wrapper around
    `radiomax.radiometry.reflectance`, with the unit table and the
    JSON-safe ``get_config``.

    Geo-dependence: when neither ``sza_deg`` nor ``center_coords`` is
    provided, the solar zenith is computed at every pixel, so the
    input must be a georeferenced GeoArray (plain arrays raise
    ``TypeError`` in that mode). Pixels at night (a zenith of 90° or more)
    hold the fill.

    Args:
        solar_irradiance: Per-band TOA solar irradiance in W/m²/nm,
            shape ``(C,)``.
        acquisition_date: UTC datetime of acquisition.
        center_coords: Optional ``(lon, lat)`` for the SZA computation.
            Without it, every pixel has its own.
        sza_deg: Optional pre-computed solar zenith angle in degrees.
            If provided, ``center_coords`` is ignored.
        crs_coords: CRS of ``center_coords``. ``None`` → EPSG:4326.
        units: Radiance units. One of ``"W/m2/sr/nm"``,
            ``"mW/m2/sr/nm"``, ``"uW/cm^2/SR/nm"``.

    Examples:
        >>> from datetime import datetime
        >>> import numpy as np
        >>> from geoops.radiometry import RadianceToReflectance
        >>> op = RadianceToReflectance(
        ...     solar_irradiance=np.array([1.95, 1.85, 1.55]),
        ...     acquisition_date=datetime(2024, 6, 21, 10, 30),
        ...     sza_deg=27.0,
        ...     units="W/m2/sr/nm",
        ... )
        >>> reflectance = op(radiance_geoarray)
    """

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

    def __init__(
        self,
        *,
        solar_irradiance: np.ndarray | list,
        acquisition_date: datetime | str,
        center_coords: tuple[float, float] | None = None,
        sza_deg: float | None = None,
        crs_coords: str | None = None,
        units: str = "W/m2/sr/nm",
    ) -> None:
        self.solar_irradiance = solar_irradiance
        self.acquisition_date = _parse_datetime(acquisition_date)
        self.center_coords = center_coords
        self.sza_deg = sza_deg
        self.crs_coords = crs_coords
        self.units = units

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        zenith = _zenith(self, gt, "RadianceToReflectance")
        if self.units not in _PER_SI_RADIANCE:
            raise ValueError(
                f"units must be one of {sorted(_PER_SI_RADIANCE)}; got {self.units!r}"
            )
        radiance = np.asarray(gt) / _PER_SI_RADIANCE[self.units]
        out = reflectance(
            radiance,
            _per_band(self.solar_irradiance, radiance, "RadianceToReflectance"),
            zenith,
            earth_sun_distance_correction_factor(self.acquisition_date),
            max_zenith=90.0,
        )
        return _rewrap_lit(gt, out, zenith)

    def get_config(self) -> dict[str, Any]:
        return {
            "solar_irradiance": jsonable(
                np.asarray(self.solar_irradiance, dtype=float)
            ),
            "acquisition_date": jsonable(self.acquisition_date),
            "center_coords": (
                list(self.center_coords) if self.center_coords is not None else None
            ),
            "sza_deg": self.sza_deg,
            "crs_coords": self.crs_coords,
            "units": self.units,
        }

ReflectanceToRadiance

Bases: Operator

Convert TOA reflectance back to at-sensor radiance — inverse of RadianceToReflectance.

.. math::

L \;=\; \frac{\rho \, E_{\text{sun}} \, \cos(\theta_z)}{\pi \, d^{2}}

Same solar-geometry inputs as the forward direction: pass sza_deg for a metadata-driven SZA or center_coords for one angle computed there.

Geo-dependence: when neither sza_deg nor center_coords is provided, the solar zenith is computed at every pixel, so the input must be a georeferenced GeoArray (plain arrays raise TypeError in that mode).

Parameters:

Name Type Description Default
solar_irradiance ndarray | list

Per-band TOA solar irradiance in W/m²/nm.

required
acquisition_date datetime | str

UTC datetime of acquisition.

required
center_coords tuple[float, float] | None

Optional (lon, lat) for SZA.

None
sza_deg float | None

Optional pre-computed solar zenith angle (degrees).

None
crs_coords str | None

CRS of center_coords. None → EPSG:4326.

None

Examples:

>>> from datetime import datetime
>>> import numpy as np
>>> from geoops.radiometry import (
...     RadianceToReflectance,
...     ReflectanceToRadiance,
... )
>>> solar = np.array([1.95, 1.85])
>>> date = datetime(2024, 7, 14, 11, 32)
>>> fwd = RadianceToReflectance(
...     solar_irradiance=solar, acquisition_date=date, sza_deg=30.0
... )
>>> inv = ReflectanceToRadiance(
...     solar_irradiance=solar, acquisition_date=date, sza_deg=30.0
... )
>>> # Round-trip preserves radiance up to float precision.
>>> radiance_out = inv(fwd(radiance_geoarray))
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class ReflectanceToRadiance(Operator):
    r"""Convert TOA reflectance back to at-sensor radiance — inverse of `RadianceToReflectance`.

    .. math::

        L \;=\; \frac{\rho \, E_{\text{sun}} \, \cos(\theta_z)}{\pi \, d^{2}}

    Same solar-geometry inputs as the forward direction: pass
    ``sza_deg`` for a metadata-driven SZA or ``center_coords`` for one
    angle computed there.

    Geo-dependence: when neither ``sza_deg`` nor ``center_coords`` is
    provided, the solar zenith is computed at every pixel, so the
    input must be a georeferenced GeoArray (plain arrays raise
    ``TypeError`` in that mode).

    Args:
        solar_irradiance: Per-band TOA solar irradiance in W/m²/nm.
        acquisition_date: UTC datetime of acquisition.
        center_coords: Optional ``(lon, lat)`` for SZA.
        sza_deg: Optional pre-computed solar zenith angle (degrees).
        crs_coords: CRS of ``center_coords``. ``None`` → EPSG:4326.

    Examples:
        >>> from datetime import datetime
        >>> import numpy as np
        >>> from geoops.radiometry import (
        ...     RadianceToReflectance,
        ...     ReflectanceToRadiance,
        ... )
        >>> solar = np.array([1.95, 1.85])
        >>> date = datetime(2024, 7, 14, 11, 32)
        >>> fwd = RadianceToReflectance(
        ...     solar_irradiance=solar, acquisition_date=date, sza_deg=30.0
        ... )
        >>> inv = ReflectanceToRadiance(
        ...     solar_irradiance=solar, acquisition_date=date, sza_deg=30.0
        ... )
        >>> # Round-trip preserves radiance up to float precision.
        >>> radiance_out = inv(fwd(radiance_geoarray))
    """

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

    def __init__(
        self,
        *,
        solar_irradiance: np.ndarray | list,
        acquisition_date: datetime | str,
        center_coords: tuple[float, float] | None = None,
        sza_deg: float | None = None,
        crs_coords: str | None = None,
    ) -> None:
        self.solar_irradiance = solar_irradiance
        self.acquisition_date = _parse_datetime(acquisition_date)
        self.center_coords = center_coords
        self.sza_deg = sza_deg
        self.crs_coords = crs_coords

    @over_frames
    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        zenith = _zenith(self, gt, "ReflectanceToRadiance")
        values = np.asarray(gt)
        out = radiance_from_reflectance(
            values,
            _per_band(self.solar_irradiance, values, "ReflectanceToRadiance"),
            zenith,
            earth_sun_distance_correction_factor(self.acquisition_date),
        )
        return _rewrap_lit(gt, out, zenith)

    def get_config(self) -> dict[str, Any]:
        return {
            "solar_irradiance": jsonable(
                np.asarray(self.solar_irradiance, dtype=float)
            ),
            "acquisition_date": jsonable(self.acquisition_date),
            "center_coords": (
                list(self.center_coords) if self.center_coords is not None else None
            ),
            "sza_deg": self.sza_deg,
            "crs_coords": self.crs_coords,
        }

SimpleAtmosphericCorrection

Bases: Operator

Dispatch simple BOA approximations; currently supports method='dos1'.

Convenience entry point that picks an atmospheric-correction strategy by name. Only "dos1" is implemented today; the aod parameter is accepted but ignored — it's reserved for future DOS2/DOS3/SMAC variants that will layer aerosol optical depth on top of the dark-object estimate.

Parameters:

Name Type Description Default
method str

Correction strategy. Currently only "dos1".

'dos1'
dark_percentile float

Forwarded to DOS1 when method='dos1'.

1.0
aod float | None

Aerosol optical depth (reserved; currently ignored).

None

Examples:

>>> from geoops.radiometry import SimpleAtmosphericCorrection
>>> op = SimpleAtmosphericCorrection(method="dos1", dark_percentile=1.0)
>>> surface = op(toa_reflectance_geoarray)
References

See DOS1 for the Chavez 1988/1996 references.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class SimpleAtmosphericCorrection(Operator):
    """Dispatch simple BOA approximations; currently supports ``method='dos1'``.

    Convenience entry point that picks an atmospheric-correction
    strategy by name. Only ``"dos1"`` is implemented today; the
    ``aod`` parameter is accepted but ignored — it's reserved for
    future DOS2/DOS3/SMAC variants that will layer aerosol optical
    depth on top of the dark-object estimate.

    Args:
        method: Correction strategy. Currently only ``"dos1"``.
        dark_percentile: Forwarded to `DOS1` when ``method='dos1'``.
        aod: Aerosol optical depth (reserved; currently ignored).

    Examples:
        >>> from geoops.radiometry import SimpleAtmosphericCorrection
        >>> op = SimpleAtmosphericCorrection(method="dos1", dark_percentile=1.0)
        >>> surface = op(toa_reflectance_geoarray)

    References:
        See `DOS1` for the Chavez 1988/1996 references.
    """

    backends: ClassVar[tuple[str, ...]] = ("numpy",)
    # DOS1: a per-band dark object over the scene
    coupling: ClassVar[Coupling] = Coupling(couples={"space"}, reach=None)

    def __init__(
        self,
        *,
        method: str = "dos1",
        dark_percentile: float = 1.0,
        aod: float | None = None,
    ) -> None:
        self.method = method
        self.dark_percentile = dark_percentile
        self.aod = aod

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        if self.method.lower() != "dos1":
            raise NotImplementedError(
                "SimpleAtmosphericCorrection currently supports only "
                f"method='dos1'; got {self.method!r}"
            )
        return DOS1(dark_percentile=self.dark_percentile)(gt)

ToFloat32

Bases: Operator

Cast the carrier's values to float32.

The first stop on most radiometric pipelines: sensor DN are usually uint16, and downstream arithmetic (division for indices, gain application, etc.) wants float. float32 is the right default for imagery — half the memory of float64 with plenty of dynamic range for reflectance.

Integer input with a fill value comes back with fill_value=NaN and NaN at its nodata pixels (an integer fill such as 0 would be a valid float value); float input keeps its fill.

Examples:

>>> import geoops as gz
>>> # Standard first stage of a TOA-reflectance pipeline:
>>> pipe = (
...     gz.radiometry.ToFloat32()
...     | gz.radiometry.DNToReflectance(scale=1e-4)
... )
>>> reflectance = pipe(uint16_dn_geoarray)
Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/operators.py
class ToFloat32(Operator):
    """Cast the carrier's values to ``float32``.

    The first stop on most radiometric pipelines: sensor DN are usually
    ``uint16``, and downstream arithmetic (division for indices, gain
    application, etc.) wants float. ``float32`` is the right default for
    imagery — half the memory of ``float64`` with plenty of dynamic
    range for reflectance.

    Integer input with a fill value comes back with
    ``fill_value=NaN`` and ``NaN`` at its nodata pixels (an
    integer fill such as ``0`` would be a valid float value); float input
    keeps its fill.

    Examples:
        >>> import geoops as gz
        >>> # Standard first stage of a TOA-reflectance pipeline:
        >>> pipe = (
        ...     gz.radiometry.ToFloat32()
        ...     | gz.radiometry.DNToReflectance(scale=1e-4)
        ... )
        >>> reflectance = pipe(uint16_dn_geoarray)
    """

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

    def _apply(self, gt: GeoArray | np.ndarray) -> GeoArray | np.ndarray:
        # Rewrap (not `GeoArray.astype`) so integer DN promoted to float
        # get the carried NaN fill at their nodata pixels.
        return _rewrap_carried(gt, np.asarray(gt).astype(np.float32))

bt_from_radiance(radiance, k1, k2)

Convert thermal radiance to brightness temperature.

.. math::

T = K_2 / \ln(K_1 / L + 1)

Parameters:

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

Thermal at-sensor radiance L.

required
k1 float | Float[ndarray, '*coef']

Planck K1 constant. Scalar or per-band array.

required
k2 float | Float[ndarray, '*coef']

Planck K2 constant. Scalar or per-band array.

required

Returns:

Type Description
Float[ndarray, '*dims']

Brightness temperature in Kelvin; NaN where the radiance is not

Float[ndarray, '*dims']

positive.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def bt_from_radiance(
    radiance: Float[np.ndarray, "*dims"],
    k1: float | Float[np.ndarray, "*coef"],
    k2: float | Float[np.ndarray, "*coef"],
) -> Float[np.ndarray, "*dims"]:
    r"""Convert thermal radiance to brightness temperature.

    .. math::

        T = K_2 / \ln(K_1 / L + 1)

    Args:
        radiance: Thermal at-sensor radiance ``L``.
        k1: Planck ``K1`` constant. Scalar or per-band array.
        k2: Planck ``K2`` constant. Scalar or per-band array.

    Returns:
        Brightness temperature in Kelvin; NaN where the radiance is not
        positive.
    """
    return brightness_temperature_band(radiance, PlanckLinear(k1, k2))

dn_to_radiance(dn, gain, offset=0.0, scale=1.0)

Convert raw DN to at-sensor radiance via per-band gain/offset.

.. math::

L \;=\; \text{gain} \cdot DN / \text{scale} + \text{offset}

The gain and offset come from the sensor metadata file (Landsat MTL, Sentinel-2 MTD, EMIT L1B, etc.). Pass scalars for single-band / uniform gain, or 1-D arrays shaped like the band axis to apply different coefficients per band — broadcasting handles the arithmetic.

Units of L are whatever the gain/offset are calibrated in, typically :math:W \cdot m^{-2} \cdot sr^{-1} \cdot \mu m^{-1}. The primitive itself is unit-agnostic.

Parameters:

Name Type Description Default
dn Num[ndarray, '*dims']

Raw DN array. Any shape; the gain/offset broadcast across it. A common pattern is (C, H, W) with per-band coefficients shape == (C, 1, 1).

required
gain float | Float[ndarray, '*coef']

Slope of the linear decode. Scalar or array.

required
offset float | Float[ndarray, '*coef']

Intercept. Scalar or array. Default 0.

0.0
scale float | Float[ndarray, '*coef']

Optional DN scale divisor. Default 1.

1.0

Returns:

Type Description
Float[ndarray, '*dims']

Radiance array of the same shape as dn. Integer DN are

Float[ndarray, '*dims']

promoted to float64 before any arithmetic, so integer

Float[ndarray, '*dims']

coefficients can't overflow the DN dtype (cast outside if you

Float[ndarray, '*dims']

want float32 to save memory); float input keeps its precision.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def dn_to_radiance(
    dn: Num[np.ndarray, "*dims"],
    gain: float | Float[np.ndarray, "*coef"],
    offset: float | Float[np.ndarray, "*coef"] = 0.0,
    scale: float | Float[np.ndarray, "*coef"] = 1.0,
) -> Float[np.ndarray, "*dims"]:
    r"""Convert raw DN to at-sensor radiance via per-band gain/offset.

    .. math::

        L \;=\; \text{gain} \cdot DN / \text{scale} + \text{offset}

    The gain and offset come from the sensor metadata file (Landsat MTL,
    Sentinel-2 MTD, EMIT L1B, etc.). Pass scalars for single-band /
    uniform gain, or 1-D arrays shaped like the band axis to apply
    different coefficients per band — broadcasting handles the
    arithmetic.

    Units of ``L`` are whatever the gain/offset are calibrated in,
    typically :math:`W \cdot m^{-2} \cdot sr^{-1} \cdot \mu m^{-1}`. The
    primitive itself is unit-agnostic.

    Args:
        dn: Raw DN array. Any shape; the gain/offset broadcast across
            it. A common pattern is ``(C, H, W)`` with per-band
            coefficients ``shape == (C, 1, 1)``.
        gain: Slope of the linear decode. Scalar or array.
        offset: Intercept. Scalar or array. Default ``0``.
        scale: Optional DN scale divisor. Default ``1``.

    Returns:
        Radiance array of the same shape as ``dn``. Integer DN are
        promoted to float64 before any arithmetic, so integer
        coefficients can't overflow the DN dtype (cast outside if you
        want float32 to save memory); float input keeps its precision.
    """
    # L = (gain / scale) DN + offset
    return counts_to_radiance(dn, _over(gain, scale), offset)

dn_to_reflectance(dn, scale, offset=0.0)

Convert DN to TOA / surface reflectance via a linear affine decode.

.. math::

\rho \;=\; \text{scale} \cdot DN + \text{offset}

The canonical pre-scaled-reflectance decode: scale is the slope (reflectance per DN unit) and offset is the reflectance-units intercept. This convention matches Landsat Collection-2 surface reflectance verbatim and absorbs the Sentinel-2 L1C RADIO_ADD_OFFSET after multiplying it out (see notes below).

Sensor-specific coefficients (illustrative — always consult the product MTL / metadata):

  • Sentinel-2 L1C (pre-2022-01-25): scale=1e-4, offset=0.
  • Sentinel-2 L1C (post-2022-01-25): the per-band RADIO_ADD_OFFSET=-1000 is in DN units; multiplied through the scale it becomes offset = -1000 * 1e-4 = -0.1, so use scale=1e-4, offset=-0.1.
  • Landsat-8/9 Collection-2 SR: scale=2.75e-5, offset=-0.2.

For sensors where the metadata gives gain/offset to radiance but not a direct DN→ρ shortcut, do the two-step decode via dn_to_radiance then the RadianceToReflectance operator (a wrapper over georeader.reflectance.radiance_to_reflectance) for the proper solar-geometry correction.

Parameters:

Name Type Description Default
dn Num[ndarray, '*dims']

Raw DN array.

required
scale float | Float[ndarray, '*coef']

Quantification slope (reflectance per DN unit). Scalar or per-band 1-D array.

required
offset float | Float[ndarray, '*coef']

Reflectance-units intercept. Scalar or per-band 1-D array. Default 0.0.

0.0

Returns:

Type Description
Reflectance array; values should fall in

math:[0, 1] for

Float[ndarray, '*dims']

well-calibrated inputs. Integer DN are promoted to float64

Float[ndarray, '*dims']

before any arithmetic.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def dn_to_reflectance(
    dn: Num[np.ndarray, "*dims"],
    scale: float | Float[np.ndarray, "*coef"],
    offset: float | Float[np.ndarray, "*coef"] = 0.0,
) -> Float[np.ndarray, "*dims"]:
    r"""Convert DN to TOA / surface reflectance via a linear affine decode.

    .. math::

        \rho \;=\; \text{scale} \cdot DN + \text{offset}

    The canonical pre-scaled-reflectance decode: ``scale`` is the slope
    (reflectance per DN unit) and ``offset`` is the *reflectance-units*
    intercept. This convention matches Landsat Collection-2 surface
    reflectance verbatim and absorbs the Sentinel-2 L1C ``RADIO_ADD_OFFSET``
    after multiplying it out (see notes below).

    Sensor-specific coefficients (illustrative — always consult the
    product MTL / metadata):

    - **Sentinel-2 L1C** (pre-2022-01-25): ``scale=1e-4, offset=0``.
    - **Sentinel-2 L1C** (post-2022-01-25): the per-band
      ``RADIO_ADD_OFFSET=-1000`` is in DN units; multiplied through the
      scale it becomes ``offset = -1000 * 1e-4 = -0.1``, so use
      ``scale=1e-4, offset=-0.1``.
    - **Landsat-8/9 Collection-2 SR**: ``scale=2.75e-5, offset=-0.2``.

    For sensors where the metadata gives gain/offset to radiance but
    *not* a direct DN→ρ shortcut, do the two-step decode via
    `dn_to_radiance` then the `RadianceToReflectance` operator (a
    wrapper over `georeader.reflectance.radiance_to_reflectance`) for
    the proper solar-geometry correction.

    Args:
        dn: Raw DN array.
        scale: Quantification slope (reflectance per DN unit). Scalar
            or per-band 1-D array.
        offset: Reflectance-units intercept. Scalar or per-band 1-D
            array. Default ``0.0``.

    Returns:
        Reflectance array; values should fall in :math:`[0, 1]` for
        well-calibrated inputs. Integer DN are promoted to float64
        before any arithmetic.
    """
    # rho = scale DN + offset
    return counts_to_reflectance(dn, scale, offset)

dos1(reflectance, dark_percentile=1.0, *, reduce_axes=(-2, -1))

Apply a simple DOS1 dark-object subtraction to reflectance.

Parameters:

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

TOA reflectance array.

required
dark_percentile float

Percentile used as the dark-object estimate.

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

Axes over which to estimate the dark-object value.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Reflectance with per-band dark-object values subtracted and clipped

Float[ndarray, '*dims']

to zero.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def dos1(
    reflectance: Float[np.ndarray, "*dims"],
    dark_percentile: float = 1.0,
    *,
    reduce_axes: int | tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    """Apply a simple DOS1 dark-object subtraction to reflectance.

    Args:
        reflectance: TOA reflectance array.
        dark_percentile: Percentile used as the dark-object estimate.
        reduce_axes: Axes over which to estimate the dark-object value.

    Returns:
        Reflectance with per-band dark-object values subtracted and clipped
        to zero.
    """
    if not 0.0 <= dark_percentile <= 100.0:
        raise ValueError(
            f"dos1 requires dark_percentile in [0, 100]; got {dark_percentile}"
        )
    dark = np.nanpercentile(
        reflectance, dark_percentile, axis=reduce_axes, keepdims=True
    )
    return np.maximum(reflectance - dark, 0.0)

gamma_correct(arr, gamma=1.2)

Apply a gamma (power-law) correction.

.. math::

y \;=\; x^{1/\gamma}

Display-prep helper: human visual perception of brightness is nonlinear, so a power-law tweak after a min-max stretch brightens midtones (gamma > 1) or darkens them (gamma < 1). Standard sRGB encoding uses gamma ≈ 2.2; a gentle gamma = 1.2 is a common "make satellite RGBs pop" default.

Negative inputs are clipped to zero before the power to avoid complex-number warnings; reflectance should be non-negative anyway. Values above 1 are not clipped (the display-range variant, :func:geoops.viz.gamma_correct_display, clips to [0, 1]).

Parameters:

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

Input float array, ideally already in [0, 1].

required
gamma float

Gamma factor. > 1 brightens; < 1 darkens. Default 1.2.

1.2

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape, gamma-corrected.

Raises:

Type Description
ValueError

If gamma <= 0.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def gamma_correct(
    arr: Float[np.ndarray, "*dims"], gamma: float = 1.2
) -> Float[np.ndarray, "*dims"]:
    r"""Apply a gamma (power-law) correction.

    .. math::

        y \;=\; x^{1/\gamma}

    Display-prep helper: human visual perception of brightness is
    nonlinear, so a power-law tweak after a min-max stretch brightens
    midtones (``gamma > 1``) or darkens them (``gamma < 1``). Standard
    sRGB encoding uses ``gamma ≈ 2.2``; a gentle ``gamma = 1.2`` is a
    common "make satellite RGBs pop" default.

    Negative inputs are clipped to zero before the power to avoid
    complex-number warnings; reflectance should be non-negative anyway.
    Values above ``1`` are *not* clipped (the display-range variant,
    :func:`geoops.viz.gamma_correct_display`, clips to ``[0, 1]``).

    Args:
        arr: Input float array, ideally already in ``[0, 1]``.
        gamma: Gamma factor. ``> 1`` brightens; ``< 1`` darkens.
            Default ``1.2``.

    Returns:
        Float array of the same shape, gamma-corrected.

    Raises:
        ValueError: If ``gamma <= 0``.
    """
    if gamma <= 0:
        raise ValueError(f"gamma_correct requires gamma > 0; got {gamma}")
    return np.maximum(arr, 0.0) ** (1.0 / gamma)

min_max_normalize(arr, vmin, vmax, *, clip=True)

Linearly map [vmin, vmax] to [0, 1].

.. math::

y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}

A pure display-prep primitive: no physics, just a contrast stretch that gets reflectance into the byte / display range. clip=True forces out-of-range pixels to the endpoints; clip=False leaves them as-is (useful when feeding a downstream model that wants informative tails).

Parameters:

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

Input array.

required
vmin float

Lower bound (mapped to 0). Must be strictly less than vmax.

required
vmax float

Upper bound (mapped to 1).

required
clip bool

Whether to clamp output to [0, 1]. Default True.

True

Returns:

Type Description
Float[ndarray, '*dims']

Float array. Shape and broadcasting preserved. Integer input

Float[ndarray, '*dims']

(e.g. uint16 DN with integer bounds) is promoted to float64

Float[ndarray, '*dims']

before subtracting vmin, so values below vmin map below

Float[ndarray, '*dims']

0 instead of wrapping around.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def min_max_normalize(
    arr: Num[np.ndarray, "*dims"],
    vmin: float,
    vmax: float,
    *,
    clip: bool = True,
) -> Float[np.ndarray, "*dims"]:
    r"""Linearly map ``[vmin, vmax]`` to ``[0, 1]``.

    .. math::

        y \;=\; \frac{x - v_{\min}}{v_{\max} - v_{\min}}

    A pure display-prep primitive: no physics, just a contrast stretch
    that gets reflectance into the byte / display range. ``clip=True``
    forces out-of-range pixels to the endpoints; ``clip=False`` leaves
    them as-is (useful when feeding a downstream model that wants
    informative tails).

    Args:
        arr: Input array.
        vmin: Lower bound (mapped to 0). Must be strictly less than
            ``vmax``.
        vmax: Upper bound (mapped to 1).
        clip: Whether to clamp output to ``[0, 1]``. Default ``True``.

    Returns:
        Float array. Shape and broadcasting preserved. Integer input
        (e.g. ``uint16`` DN with integer bounds) is promoted to float64
        before subtracting ``vmin``, so values below ``vmin`` map below
        0 instead of wrapping around.
    """
    if vmax <= vmin:
        raise ValueError(
            f"min_max_normalize requires vmax > vmin; got {vmin=}, {vmax=}"
        )
    arr = as_float(arr, np.float64)
    out = (arr - vmin) / (vmax - vmin)
    if clip:
        out = np.clip(out, 0.0, 1.0)
    return out

percentile_clip(arr, lower=2.0, upper=98.0, *, reduce_axes=(-2, -1))

Robust contrast stretch using percentile thresholds.

Computes :math:v_{lo} = P_{\text{lower}}(\text{arr}) and :math:v_{hi} = P_{\text{upper}}(\text{arr}) over the configured reduce_axes, then min-max normalises arr between them with clipping. The percentile thresholds are far more robust than fixed vmin / vmax against bright outliers (cumulus clouds, specular water glint, sensor saturation).

NaN-safe: thin wrapper over the shared :func:geoops._src.stretch.percentile_stretch, whose percentiles are np.nanpercentile (NaN pixels never shift the thresholds and stay NaN in the output).

Default reduce_axes=(-2, -1) computes percentiles per leading band / time slice — the typical "RGB display per band" mode. Pass reduce_axes=None for a single global percentile across the whole array.

Parameters:

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

Input float array.

required
lower float

Lower percentile (in [0, 100]). Default 2.0.

2.0
upper float

Upper percentile. Default 98.0. Must be strictly greater than lower.

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

Axis (or tuple of axes) to compute percentiles over. (-2, -1) -> per-band/-time stretch. None -> global.

(-2, -1)

Returns:

Type Description
Float[ndarray, '*dims']

Float array of the same shape, values in [0, 1].

Raises:

Type Description
ValueError

If upper <= lower.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def percentile_clip(
    arr: Shaped[np.ndarray, "*dims"],
    lower: float = 2.0,
    upper: float = 98.0,
    *,
    reduce_axes: int | tuple[int, ...] | None = (-2, -1),
) -> Float[np.ndarray, "*dims"]:
    r"""Robust contrast stretch using percentile thresholds.

    Computes :math:`v_{lo} = P_{\text{lower}}(\text{arr})` and
    :math:`v_{hi} = P_{\text{upper}}(\text{arr})` over the configured
    ``reduce_axes``, then min-max normalises ``arr`` between them with
    clipping. The percentile thresholds are far more robust than fixed
    ``vmin / vmax`` against bright outliers (cumulus clouds, specular
    water glint, sensor saturation).

    NaN-safe: thin wrapper over the shared
    :func:`geoops._src.stretch.percentile_stretch`, whose percentiles
    are ``np.nanpercentile`` (NaN pixels never shift the thresholds and
    stay NaN in the output).

    Default ``reduce_axes=(-2, -1)`` computes percentiles per leading band /
    time slice — the typical "RGB display per band" mode. Pass
    ``reduce_axes=None`` for a single global percentile across the whole
    array.

    Args:
        arr: Input float array.
        lower: Lower percentile (in ``[0, 100]``). Default ``2.0``.
        upper: Upper percentile. Default ``98.0``. Must be strictly
            greater than ``lower``.
        reduce_axes: Axis (or tuple of axes) to compute percentiles over.
            ``(-2, -1)`` -> per-band/-time stretch. ``None`` -> global.

    Returns:
        Float array of the same shape, values in ``[0, 1]``.

    Raises:
        ValueError: If ``upper <= lower``.
    """
    return percentile_stretch(arr, lower, upper, reduce_axes=reduce_axes)

radiance_to_dn(radiance, gain, offset=0.0, scale=1.0)

Convert at-sensor radiance back to DN via the affine inverse.

.. math::

DN \;=\; (L - \text{offset}) \cdot \text{scale} / \text{gain}

Parameters:

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

At-sensor radiance array.

required
gain float | Float[ndarray, '*coef']

Slope used by dn_to_radiance.

required
offset float | Float[ndarray, '*coef']

Intercept used by dn_to_radiance. Default 0.

0.0
scale float | Float[ndarray, '*coef']

DN scale divisor used by dn_to_radiance. Default 1.

1.0

Returns:

Type Description
Float[ndarray, '*dims']

DN array in floating point. Cast or round outside if integer DN are

Float[ndarray, '*dims']

required. Integer radiance is promoted to float64 first.

Source code in packages/geotoolz-ops/src/geoops/radiometry/_src/array.py
def radiance_to_dn(
    radiance: Float[np.ndarray, "*dims"],
    gain: float | Float[np.ndarray, "*coef"],
    offset: float | Float[np.ndarray, "*coef"] = 0.0,
    scale: float | Float[np.ndarray, "*coef"] = 1.0,
) -> Float[np.ndarray, "*dims"]:
    r"""Convert at-sensor radiance back to DN via the affine inverse.

    .. math::

        DN \;=\; (L - \text{offset}) \cdot \text{scale} / \text{gain}

    Args:
        radiance: At-sensor radiance array.
        gain: Slope used by `dn_to_radiance`.
        offset: Intercept used by `dn_to_radiance`. Default ``0``.
        scale: DN scale divisor used by `dn_to_radiance`. Default ``1``.

    Returns:
        DN array in floating point. Cast or round outside if integer DN are
        required. Integer radiance is promoted to float64 first.
    """
    # DN = (L - offset) / (gain / scale)
    return radiance_to_counts(radiance, _over(gain, scale), offset)