Skip to content

spectral#

Spectral transforms for EO rasters — operations that rotate or combine a sensor's reflectance bands into a derived, physically meaningful space, using the per-sensor knowledge in the registry.

Currently the Kauth-Thomas tasseled cap (tasseled_cap): brightness / greenness / wetness from a multi-band reflectance Dataset, with the coefficients selected by sensor and the band order handled by name rather than assumed — a named stack is reordered to the coefficient order, an unnamed one is taken in the sensor's documented order, and a stack whose names are ambiguous or do not match the sensor is rejected — so a mis-ordered stack never silently produces a plausible-looking but meaningless raster. The per-sensor coefficient tables themselves live in the registry (get_tasseled_cap, sensors/registry/data/tasseled_cap.yaml).

pyramids_eo.spectral #

Spectral transforms for EO rasters.

Operations that rotate or combine a sensor's reflectance bands into a derived, physically meaningful space, using the per-sensor knowledge in pyramids_eo.sensors.registry:

  • tasseled_cap — the Kauth-Thomas brightness / greenness / wetness transform, applied to a multi-band reflectance Dataset with the sensor's coefficients.

pyramids_eo.spectral.tasseled_cap #

Tasseled-cap (Kauth-Thomas) transform for a multi-band reflectance raster.

tasseled_cap(dataset, *, sensor, components=...) rotates a stack of reflectance bands into the tasseled-cap components -- brightness, greenness, wetness -- using the per-sensor coefficients from the registry (pyramids_eo.sensors.registry.get_tasseled_cap). It returns a Dataset with the requested components as named bands, carrying the input's grid and CRS, so it stays composable with the rest of the stack.

The coefficients are a fixed linear combination tied to a specific band order, so a silently wrong band order yields a plausible-looking but meaningless raster -- the failure this transform is designed against. When the input Dataset's bands are named (blue/green/... or a sensor spelling such as B4 / SR_B5), they are matched to the sensor's roles and reordered to the coefficient order; when they are unnamed (generic), the stack is assumed to already be in the sensor's documented band order and only its band count is checked.

tasseled_cap(dataset, *, sensor, components=_DEFAULT_COMPONENTS) #

Rotate a reflectance band stack into its tasseled-cap components.

Applies the sensor's tasseled-cap coefficients (see pyramids_eo.sensors.registry.get_tasseled_cap) to the bands of dataset and returns a Dataset whose bands are the requested components, in the order given, carrying dataset's geotransform and CRS. The input bands must be in the sensor's documented reflectance domain (TOA / reflectance factor, not raw DN) and in the sensor's band order -- which is enforced by name when the bands are named and by count otherwise (see the module docstring).

The whole band stack is read into memory and processed at full resolution (several float64 arrays at once: the input, and one per requested component); there is no windowing, so a full scene is sized accordingly.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset whose bands are the sensor's reflectance bands (a (band, row, col) stack). Read via read_array; its geotransform, epsg (and crs, when it has no EPSG code) and per-band no_data_value are carried onto / used for the result. Band names, when present, drive band-order validation.

required
sensor str

The sensor whose coefficient table to use (e.g. "landsat8_oli", "landsat5_tm", "landsat7_etm"); case-insensitive.

required
components Sequence[str]

The components to compute, in output-band order. Defaults to ("brightness", "greenness", "wetness"). Each must be defined in the sensor's table.

_DEFAULT_COMPONENTS

Returns:

Type Description
Any

A pyramids Dataset of shape (len(components), row, col) with the

Any

components as its band names, dataset's geotransform / CRS, and NaN as

Any

its nodata value. A pixel that is the input's nodata, or non-finite in any

Any

band, is NaN in every component.

Raises:

Type Description
TransformError

When components is empty, names a component the sensor's table does not define, or when the input is not a band stack whose band count / order matches the sensor.

UnknownSensorError

When sensor has no bundled coefficient table.

Examples:

  • Brightness / greenness / wetness from a Landsat 8 OLI reflectance stack:
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from pyramids_eo.spectral import tasseled_cap
    >>> stack = np.ones((6, 1, 1), dtype=float)  # blue..swir2, reflectance 1.0
    >>> ds = Dataset.from_array(
    ...     stack, geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 1.0, 0.0, -1.0), epsg=4326)
    ... )
    >>> ds.band_names = ["blue", "green", "red", "nir", "swir1", "swir2"]
    >>> tc = tasseled_cap(ds, sensor="landsat8_oli")
    >>> tc.band_names
    ['brightness', 'greenness', 'wetness']
    >>> float(tc.read_array()[0, 0, 0].round(4))  # sum of the brightness row
    2.3099
    
  • Pick a single component; its coefficients are a sensor-specific constant:
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from pyramids_eo.spectral import tasseled_cap
    >>> stack = np.ones((6, 1, 1), dtype=float)
    >>> ds = Dataset.from_array(
    ...     stack, geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 1.0, 0.0, -1.0), epsg=4326)
    ... )
    >>> ds.band_names = ["blue", "green", "red", "nir", "swir1", "swir2"]
    >>> wet = tasseled_cap(ds, sensor="landsat8_oli", components=["wetness"])
    >>> wet.band_names
    ['wetness']
    
Source code in src/pyramids_eo/spectral/tasseled_cap.py
def tasseled_cap(
    dataset: Any,
    *,
    sensor: str,
    components: Sequence[str] = _DEFAULT_COMPONENTS,
) -> Any:
    """Rotate a reflectance band stack into its tasseled-cap components.

    Applies the sensor's tasseled-cap coefficients (see
    `pyramids_eo.sensors.registry.get_tasseled_cap`) to the bands of `dataset` and
    returns a `Dataset` whose bands are the requested `components`, in the order
    given, carrying `dataset`'s geotransform and CRS. The input bands must be in
    the sensor's documented reflectance domain (TOA / reflectance factor, not raw
    DN) and in the sensor's band order -- which is enforced by name when the bands
    are named and by count otherwise (see the module docstring).

    The whole band stack is read into memory and processed at full resolution
    (several float64 arrays at once: the input, and one per requested component);
    there is no windowing, so a full scene is sized accordingly.

    Args:
        dataset: A pyramids `Dataset` whose bands are the sensor's reflectance
            bands (a `(band, row, col)` stack). Read via `read_array`; its
            `geotransform`, `epsg` (and `crs`, when it has no EPSG code) and
            per-band `no_data_value` are carried onto / used for the result. Band
            names, when present, drive band-order validation.
        sensor: The sensor whose coefficient table to use (e.g. `"landsat8_oli"`,
            `"landsat5_tm"`, `"landsat7_etm"`); case-insensitive.
        components: The components to compute, in output-band order. Defaults to
            `("brightness", "greenness", "wetness")`. Each must be defined in the
            sensor's table.

    Returns:
        A pyramids `Dataset` of shape `(len(components), row, col)` with the
        components as its band names, `dataset`'s geotransform / CRS, and NaN as
        its nodata value. A pixel that is the input's nodata, or non-finite in any
        band, is NaN in every component.

    Raises:
        TransformError: When `components` is empty, names a component the sensor's
            table does not define, or when the input is not a band stack whose
            band count / order matches the sensor.
        UnknownSensorError: When `sensor` has no bundled coefficient table.

    Examples:
        - Brightness / greenness / wetness from a Landsat 8 OLI reflectance stack:
            ```python
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from pyramids_eo.spectral import tasseled_cap
            >>> stack = np.ones((6, 1, 1), dtype=float)  # blue..swir2, reflectance 1.0
            >>> ds = Dataset.from_array(
            ...     stack, geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 1.0, 0.0, -1.0), epsg=4326)
            ... )
            >>> ds.band_names = ["blue", "green", "red", "nir", "swir1", "swir2"]
            >>> tc = tasseled_cap(ds, sensor="landsat8_oli")
            >>> tc.band_names
            ['brightness', 'greenness', 'wetness']
            >>> float(tc.read_array()[0, 0, 0].round(4))  # sum of the brightness row
            2.3099

            ```
        - Pick a single component; its coefficients are a sensor-specific constant:
            ```python
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from pyramids_eo.spectral import tasseled_cap
            >>> stack = np.ones((6, 1, 1), dtype=float)
            >>> ds = Dataset.from_array(
            ...     stack, geo_ref=GeoReference(geo=(0.0, 1.0, 0.0, 1.0, 0.0, -1.0), epsg=4326)
            ... )
            >>> ds.band_names = ["blue", "green", "red", "nir", "swir1", "swir2"]
            >>> wet = tasseled_cap(ds, sensor="landsat8_oli", components=["wetness"])
            >>> wet.band_names
            ['wetness']

            ```
    """
    coeffs = get_tasseled_cap(sensor)
    requested = list(components)
    if not requested:
        raise TransformError("tasseled_cap: `components` is empty")
    unknown = [c for c in requested if c not in coeffs.components]
    if unknown:
        raise TransformError(
            f"tasseled_cap: {coeffs.sensor} has no component(s) {unknown}; "
            f"available: {coeffs.component_names}"
        )

    if not hasattr(dataset, "read_array"):
        raise TransformError(
            "tasseled_cap: `dataset` must be a pyramids Dataset (a band stack), "
            f"got {type(dataset).__name__}"
        )
    stack = np.asarray(dataset.read_array(), dtype=float)
    if stack.ndim != 3:
        raise TransformError(
            f"tasseled_cap: expected a (band, row, col) stack of {len(coeffs.bands)} "
            f"bands, got an array of shape {stack.shape}"
        )
    if stack.shape[0] != len(coeffs.bands):
        raise TransformError(
            f"tasseled_cap: {coeffs.sensor} expects {len(coeffs.bands)} bands "
            f"{list(coeffs.bands)}, got {stack.shape[0]}"
        )

    # Resolve (and validate) the band order first, so a band-name mismatch raises
    # before the reflectance-magnitude warning -- no spurious warning on a call
    # that was going to fail anyway.
    order = _resolve_band_order(getattr(dataset, "band_names", None), coeffs)
    ordered = stack[order] if order is not None else stack

    _warn_if_not_reflectance(stack, coeffs)

    out = np.stack(
        [
            np.tensordot(np.asarray(coeffs.components[name]), ordered, axes=(0, 0))
            for name in requested
        ],
        axis=0,
    )
    # The linear combination turns an input fill value into a plausible finite
    # number, so a pixel that is fill (or non-finite) in any band would otherwise
    # be emitted unflagged while the output declares NaN nodata. Mask those pixels
    # to NaN so the declared nodata is honest.
    out[:, _invalid_pixels(stack, dataset)] = np.nan
    return _wrap_components(out, dataset, requested)