Skip to content

composites#

Day/night compositing for EO imagery — the pyramids-eo true_color_with_night_ir chain, over NumPy + pyramids with no third-party compositing dependency. Covers the solar and viewing geometry (solar_zenith_angle, cos_solar_zenith_angle, solar_zenith_azimuth, satellite_zenith_azimuth, relative_azimuth), the solar-zenith correction / reduction (sunz_correct / sunz_reduce), a local Rayleigh atmospheric correction (rayleigh_correct), the SZA cross-fade (day_night_blend / day_weight), the alpha overlay (alpha_overlay), the static background image (static_image), the true-colour composite (true_color), and the full assembly (night_ir, true_color_with_night_ir).

The display and resampling helpers at the bottom finish the chain: stretch maps a physical composite onto a displayable range, and to_area lands a georeferenced composite on an exact target grid.

pyramids_eo.composites #

Day/night compositing for EO imagery.

The pyramids-eo day/night composite chain (the true_color_with_night_ir look), implemented over NumPy + pyramids with no third-party compositing dependency. So far:

  • solar_zenith_angle / cos_solar_zenith_angle — per-pixel solar zenith angle (degrees) and its cosine (the cos_sza form the readers expect), the geometry the day/night blend keys off.
  • sunz_correct / sunz_reduce — sun-zenith correction (divide by cos(sza), capped) and reduction (taper the signal toward the terminator), the sunz_corrected / sunz_reduced pair applied to a true-colour composite's solar bands so deep shadow renders dark rather than as a washed-out floor.
  • solar_zenith_azimuth / satellite_zenith_azimuth / relative_azimuth — the solar and geostationary viewing geometry (zenith + azimuth, degrees clockwise from north) that an atmospheric correction needs.
  • rayleigh_correct — a local, closed-form single-scattering Rayleigh correction (no third-party dependency) that removes the blue molecular-scattering veil, usable per band through true_color's rayleigh= hook.
  • day_night_blend / day_weight — the SZA-weighted cross-fade of a day and a night image.
  • alpha_overlay — the "over" composite of an RGBA foreground on an RGB(A) background.
  • static_image — load a georeferenced background image (e.g. Black Marble), caching a remote URL and warping it to a target grid.
  • true_color — true-colour RGB from calibrated reflectance bands with a CIMSS synthetic green (no Rayleigh).
  • night_ir / true_color_with_night_ir — assemble the full day/night image (RGBA IR clouds over city lights, cross-faded against the day image by SZA).

Together these compose the true_color_with_night_ir day/night look.

static_image(source, *, like=None, cache_dir=None, timeout=60.0, max_bytes=_DEFAULT_MAX_BYTES, refresh=False) #

Load a georeferenced image, caching a remote URL and warping to a grid.

Loads a georeferenced background image. source may be a local path (relative or absolute) or an http/https URL; a URL is downloaded once and cached under cache_dir. When like is given, the loaded image is warped and cropped onto that dataset's grid (CRS + rows/columns + cell size) via pyramids' align.

Parameters:

Name Type Description Default
source Any

A local filesystem path or an http/https URL to a georeferenced raster (e.g. the Black Marble GeoTIFF).

required
like Any

A pyramids Dataset whose grid the image is warped/cropped to. When None, the image is returned at its native grid.

None
cache_dir Any

Directory used to cache a downloaded URL. Defaults to ~/.cache/pyramids-eo. Ignored for a local source.

None
timeout float

Per-request download timeout in seconds (default 60).

60.0
max_bytes int

Cap on a URL download in bytes (default ~1 GB) — guards against an oversized/hostile URL filling the cache.

_DEFAULT_MAX_BYTES
refresh bool

When True, re-download a URL even if it is already cached (the cache is otherwise reused whenever the file is present).

False

Returns:

Type Description
Any

A pyramids Dataset — aligned to like's grid when like is given,

Any

otherwise the image at its native grid.

Raises:

Type Description
FileNotFoundError

When a local source does not exist.

EOError

When a URL download exceeds max_bytes.

Source code in src/pyramids_eo/composites/background.py
def static_image(
    source: Any,
    *,
    like: Any = None,
    cache_dir: Any = None,
    timeout: float = 60.0,
    max_bytes: int = _DEFAULT_MAX_BYTES,
    refresh: bool = False,
) -> Any:
    """Load a georeferenced image, caching a remote URL and warping to a grid.

    Loads a georeferenced background image. `source` may be a local path
    (relative or absolute) or an http/https URL; a URL is downloaded once and
    cached under `cache_dir`. When `like` is given, the loaded image is warped
    and cropped onto that dataset's grid (CRS + rows/columns + cell size) via
    pyramids' `align`.

    Args:
        source: A local filesystem path or an http/https URL to a georeferenced
            raster (e.g. the Black Marble GeoTIFF).
        like: A pyramids `Dataset` whose grid the image is warped/cropped to. When
            `None`, the image is returned at its native grid.
        cache_dir: Directory used to cache a downloaded URL. Defaults to
            `~/.cache/pyramids-eo`. Ignored for a local `source`.
        timeout: Per-request download timeout in seconds (default 60).
        max_bytes: Cap on a URL download in bytes (default ~1 GB) — guards against
            an oversized/hostile URL filling the cache.
        refresh: When `True`, re-download a URL even if it is already cached
            (the cache is otherwise reused whenever the file is present).

    Returns:
        A pyramids `Dataset` — aligned to `like`'s grid when `like` is given,
        otherwise the image at its native grid.

    Raises:
        FileNotFoundError: When a local `source` does not exist.
        EOError: When a URL download exceeds `max_bytes`.
    """
    path = _resolve_source(source, cache_dir, timeout, max_bytes, refresh)

    from pyramids.dataset import Dataset

    dataset = Dataset.read_file(str(path))
    if like is not None:
        dataset = dataset.align(like)
    return dataset

day_night_blend(day, night, sza, *, lim_low=78.0, lim_high=88.0, mode='day_night', keep_alpha=False) #

Cross-fade a day and a night image by solar zenith angle.

Computes a per-pixel day weight from sza (see day_weight) and mixes: day * weight + night * (1 - weight). day / night may be (H, W) or (band, H, W) arrays, or pyramids Dataset objects; the weight broadcasts across bands.

Parameters:

Name Type Description Default
day Any

The day image — array-like or a pyramids Dataset.

required
night Any

The night image — same shape/type family as day. Ignored when mode="day_only".

required
sza Any

Per-pixel solar zenith angle in degrees ((H, W)), from solar_zenith_angle.

required
lim_low float

SZA at/below which it is fully day (default 78).

78.0
lim_high float

SZA at/above which it is fully night (default 88).

88.0
mode str

"day_night" (blend, default), "day_only" (day * weight), or "night_only" (night * (1 - weight)).

'day_night'
keep_alpha bool

When True, append a coverage / alpha band — 1.0 where the contributing input(s) are finite, the geometry is defined, and the blended pixel itself is finite; 0.0 otherwise (see :func:pyramids_eo.composites._common._coverage). The band comes from data validity, not brightness, so a dark-but-valid pixel stays covered while a NaN-producing twilight pixel does not. Default False leaves the output unchanged.

False

Returns:

Type Description
Any

The blended image. A pyramids Dataset (carrying day's / night's

Any

geotransform + CRS) when either input is a Dataset, otherwise an

Any

ndarray. With keep_alpha=True the output carries one extra (alpha)

Any

band.

Raises:

Type Description
ValueError

When mode is unknown or lim_low >= lim_high.

Examples:

  • A day (1s) / night (0s) pair collapses to the day weight per pixel:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_night_blend
    >>> day = np.ones((2, 2))
    >>> night = np.zeros((2, 2))
    >>> sza = np.array([[0.0, 83.0], [88.0, 180.0]])
    >>> day_night_blend(day, night, sza).round(2).tolist()
    [[1.0, 0.5], [0.0, 0.0]]
    
  • keep_alpha appends a coverage band, giving a 4-band RGBA result:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_night_blend
    >>> day = np.ones((3, 1, 2))
    >>> night = np.zeros((3, 1, 2))
    >>> sza = np.array([[0.0, 0.0]])
    >>> day_night_blend(day, night, sza, keep_alpha=True).shape
    (4, 1, 2)
    
Source code in src/pyramids_eo/composites/blend.py
def day_night_blend(
    day: Any,
    night: Any,
    sza: Any,
    *,
    lim_low: float = 78.0,
    lim_high: float = 88.0,
    mode: str = "day_night",
    keep_alpha: bool = False,
) -> Any:
    """Cross-fade a day and a night image by solar zenith angle.

    Computes a per-pixel day weight from `sza` (see `day_weight`) and mixes:
    `day * weight + night * (1 - weight)`.
    `day` / `night` may be `(H, W)` or `(band, H, W)` arrays, or pyramids
    `Dataset` objects; the weight broadcasts across bands.

    Args:
        day: The day image — array-like or a pyramids `Dataset`.
        night: The night image — same shape/type family as `day`. Ignored when
            `mode="day_only"`.
        sza: Per-pixel solar zenith angle in degrees (`(H, W)`), from
            `solar_zenith_angle`.
        lim_low: SZA at/below which it is fully day (default 78).
        lim_high: SZA at/above which it is fully night (default 88).
        mode: `"day_night"` (blend, default), `"day_only"` (`day * weight`), or
            `"night_only"` (`night * (1 - weight)`).
        keep_alpha: When `True`, append a coverage / alpha band — `1.0` where the
            contributing input(s) are finite, the geometry is defined, and the
            blended pixel itself is finite; `0.0` otherwise (see
            :func:`pyramids_eo.composites._common._coverage`). The band comes from
            data validity, not brightness, so a dark-but-valid pixel stays covered
            while a NaN-producing twilight pixel does not. Default `False` leaves
            the output unchanged.

    Returns:
        The blended image. A pyramids `Dataset` (carrying `day`'s / `night`'s
        geotransform + CRS) when either input is a `Dataset`, otherwise an
        ndarray. With `keep_alpha=True` the output carries one extra (alpha)
        band.

    Raises:
        ValueError: When `mode` is unknown or `lim_low >= lim_high`.

    Examples:
        - A day (1s) / night (0s) pair collapses to the day weight per pixel:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_night_blend
            >>> day = np.ones((2, 2))
            >>> night = np.zeros((2, 2))
            >>> sza = np.array([[0.0, 83.0], [88.0, 180.0]])
            >>> day_night_blend(day, night, sza).round(2).tolist()
            [[1.0, 0.5], [0.0, 0.0]]

            ```
        - `keep_alpha` appends a coverage band, giving a 4-band RGBA result:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_night_blend
            >>> day = np.ones((3, 1, 2))
            >>> night = np.zeros((3, 1, 2))
            >>> sza = np.array([[0.0, 0.0]])
            >>> day_night_blend(day, night, sza, keep_alpha=True).shape
            (4, 1, 2)

            ```
    """
    if mode not in _MODES:
        raise ValueError(f"mode must be one of {_MODES}; got {mode!r}")

    weight2d = day_weight(_as_array(sza), lim_low=lim_low, lim_high=lim_high)
    day_arr = _as_array(day)
    weight = weight2d
    if weight2d.ndim == 2 and day_arr.ndim == 3:
        weight = weight2d[np.newaxis, ...]

    # np.where zeros each image's contribution where its weight is 0, so a NaN
    # in a fully-weighted-out region (e.g. sun-angle-normalised day reflectance,
    # which is NaN across the night side) does not leak through NaN * 0 = NaN.
    if mode == "day_only":
        out = np.where(weight > 0, day_arr * weight, 0.0)
    elif mode == "night_only":
        night_arr = _as_array(night)
        out = np.where(weight < 1, night_arr * (1.0 - weight), 0.0)
    else:
        night_arr = _as_array(night)
        day_term = np.where(weight > 0, day_arr * weight, 0.0)
        night_term = np.where(weight < 1, night_arr * (1.0 - weight), 0.0)
        out = day_term + night_term
    # A NaN weight means the SZA (day/night geometry) is undefined, so keep the
    # pixel masked as NaN rather than collapsing it to 0 — matching day_weight's
    # NaN propagation (the weight-zeroing above only handles image-side NaN).
    out = np.where(np.isnan(weight), np.nan, out)

    if keep_alpha:
        out = _append_alpha(out, day, night, weight2d, mode)

    return _wrap_like(out, day, night)

day_weight(sza, lim_low=78.0, lim_high=88.0) #

Per-pixel day weight in [0, 1] from the solar zenith angle.

The weight is 1 where the Sun is high (sza <= lim_low, full day), 0 where it is low (sza >= lim_high, full night), and a smooth cos-space ramp through the twilight band between them — the DayNightCompositor curve.

Parameters:

Name Type Description Default
sza Any

Solar zenith angle in degrees (scalar or array), e.g. from solar_zenith_angle.

required
lim_low float

SZA (degrees) at/below which it is fully day. Default 78.

78.0
lim_high float

SZA (degrees) at/above which it is fully night. Default 88.

88.0

Returns:

Type Description
ndarray

The day weight, same shape as sza, clipped to [0, 1].

Raises:

Type Description
ValueError

When lim_low >= lim_high.

Examples:

  • Overhead Sun is full day, horizon is full night, midway is ~0.5:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_weight
    >>> day_weight(np.array([0.0, 83.0, 90.0])).round(2).tolist()
    [1.0, 0.5, 0.0]
    
Source code in src/pyramids_eo/composites/blend.py
def day_weight(sza: Any, lim_low: float = 78.0, lim_high: float = 88.0) -> np.ndarray:
    """Per-pixel day weight in `[0, 1]` from the solar zenith angle.

    The weight is 1 where the Sun is high (`sza <= lim_low`, full day), 0 where
    it is low (`sza >= lim_high`, full night), and a smooth cos-space ramp
    through the twilight band between them — the DayNightCompositor curve.

    Args:
        sza: Solar zenith angle in degrees (scalar or array), e.g. from
            `solar_zenith_angle`.
        lim_low: SZA (degrees) at/below which it is fully day. Default 78.
        lim_high: SZA (degrees) at/above which it is fully night. Default 88.

    Returns:
        The day weight, same shape as `sza`, clipped to `[0, 1]`.

    Raises:
        ValueError: When `lim_low >= lim_high`.

    Examples:
        - Overhead Sun is full day, horizon is full night, midway is ~0.5:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_weight
            >>> day_weight(np.array([0.0, 83.0, 90.0])).round(2).tolist()
            [1.0, 0.5, 0.0]

            ```
    """
    if lim_low >= lim_high:
        raise ValueError(
            f"lim_low ({lim_low}) must be < lim_high ({lim_high}) in SZA degrees"
        )
    low = np.cos(np.deg2rad(lim_low))
    high = np.cos(np.deg2rad(lim_high))
    coszen = np.cos(np.deg2rad(np.asarray(sza, dtype=float)))
    weight = (coszen - min(low, high)) / abs(low - high)
    return np.asarray(np.clip(weight, 0.0, 1.0), dtype=float)

cos_solar_zenith_angle(time, *, lat=None, lon=None, grid=None) #

Per-pixel cosine of the solar zenith angle.

A thin wrapper over solar_zenith_angle returning cos(SZA) directly — the form the readers' and radiance_to_reflectance's cos_sza arguments expect (note solar_zenith_angle itself returns the angle in degrees). Same arguments as solar_zenith_angle.

Parameters:

Name Type Description Default
time datetime

Observation time (a naive datetime is treated as UTC).

required
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None

Returns:

Type Description
ndarray

The cosine of the solar zenith angle, same shape as the coordinates.

Source code in src/pyramids_eo/composites/geometry.py
def cos_solar_zenith_angle(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> np.ndarray:
    """Per-pixel cosine of the solar zenith angle.

    A thin wrapper over `solar_zenith_angle` returning `cos(SZA)` directly — the
    form the readers' and `radiance_to_reflectance`'s `cos_sza` arguments expect
    (note `solar_zenith_angle` itself returns the angle in *degrees*). Same
    arguments as `solar_zenith_angle`.

    Args:
        time: Observation time (a naive datetime is treated as UTC).
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.

    Returns:
        The cosine of the solar zenith angle, same shape as the coordinates.
    """
    return np.cos(np.deg2rad(solar_zenith_angle(time, lat=lat, lon=lon, grid=grid)))

relative_azimuth(sun_az, sat_az) #

Sun-satellite azimuth difference, folded into [0, 180] degrees.

The absolute difference of two azimuths (each in [0, 360), clockwise from north) folded to [0, 180] — the relative-azimuth input every atmospheric correction expects. Order-independent.

Parameters:

Name Type Description Default
sun_az Any

Solar azimuth(s) in degrees (e.g. from solar_zenith_azimuth).

required
sat_az Any

Satellite azimuth(s) in degrees (e.g. from satellite_zenith_azimuth).

required

Returns:

Type Description
ndarray

The relative azimuth in [0, 180] degrees, broadcast over the inputs.

Examples:

  • Opposed azimuths (0deg and 180deg) give the maximum, 180deg:
    >>> from pyramids_eo.composites import relative_azimuth
    >>> float(relative_azimuth(10.0, 190.0))
    180.0
    
  • Azimuths 350deg and 10deg are only 20deg apart (wrap-around):
    >>> from pyramids_eo.composites import relative_azimuth
    >>> float(relative_azimuth(350.0, 10.0))
    20.0
    
Source code in src/pyramids_eo/composites/geometry.py
def relative_azimuth(sun_az: Any, sat_az: Any) -> np.ndarray:
    """Sun-satellite azimuth difference, folded into `[0, 180]` degrees.

    The absolute difference of two azimuths (each in `[0, 360)`, clockwise from
    north) folded to `[0, 180]` — the relative-azimuth input every atmospheric
    correction expects. Order-independent.

    Args:
        sun_az: Solar azimuth(s) in degrees (e.g. from `solar_zenith_azimuth`).
        sat_az: Satellite azimuth(s) in degrees (e.g. from
            `satellite_zenith_azimuth`).

    Returns:
        The relative azimuth in `[0, 180]` degrees, broadcast over the inputs.

    Examples:
        - Opposed azimuths (0deg and 180deg) give the maximum, 180deg:
            ```python
            >>> from pyramids_eo.composites import relative_azimuth
            >>> float(relative_azimuth(10.0, 190.0))
            180.0

            ```
        - Azimuths 350deg and 10deg are only 20deg apart (wrap-around):
            ```python
            >>> from pyramids_eo.composites import relative_azimuth
            >>> float(relative_azimuth(350.0, 10.0))
            20.0

            ```
    """
    diff = (
        np.abs(np.asarray(sun_az, dtype=float) - np.asarray(sat_az, dtype=float))
        % 360.0
    )
    return np.asarray(np.where(diff > 180.0, 360.0 - diff, diff), dtype=float)

satellite_zenith_azimuth(*, lat=None, lon=None, grid=None, sat_lon=0.0, sat_radius_km=_R_GEO_KM) #

Per-pixel (zenith, azimuth) of a geostationary satellite, in degrees.

Closed-form and time-invariant (a geostationary satellite sits at a fixed sub-satellite longitude). The zenith is 0 at the sub-satellite point and rises toward 90 at the limb; the azimuth is in degrees clockwise from north ([0, 360)), the same convention as solar_zenith_azimuth, so the two feed relative_azimuth.

Parameters:

Name Type Description Default
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None
sat_lon float

Sub-satellite longitude in degrees east (default 0.0, Meteosat prime).

0.0
sat_radius_km float

Satellite orbital radius from Earth's centre in km (default 42164, geostationary) — this is a radius, not an altitude.

_R_GEO_KM

Returns:

Type Description
ndarray

(zenith, azimuth) arrays in degrees. The zenith is NaN beyond the

ndarray

geometric horizon (points that cannot see the satellite, e.g. the far

tuple[ndarray, ndarray]

side of the Earth on a full global grid).

Raises:

Type Description
ValueError

When sat_radius_km is not greater than Earth's radius (it is an orbital radius, not an altitude), or on the same coordinate-argument errors as solar_zenith_angle.

Examples:

  • The sub-satellite point sees the satellite at the local zenith (0deg):
    >>> from pyramids_eo.composites import satellite_zenith_azimuth
    >>> vza, _ = satellite_zenith_azimuth(lat=0.0, lon=0.0, sat_lon=0.0)
    >>> bool(vza < 0.01)
    True
    
  • A point due north of the sub-point sees the satellite due south (~180deg):
    >>> from pyramids_eo.composites import satellite_zenith_azimuth
    >>> _, az = satellite_zenith_azimuth(lat=30.0, lon=0.0, sat_lon=0.0)
    >>> bool(175.0 < az < 185.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def satellite_zenith_azimuth(
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
    sat_lon: float = 0.0,
    sat_radius_km: float = _R_GEO_KM,
) -> tuple[np.ndarray, np.ndarray]:
    """Per-pixel `(zenith, azimuth)` of a geostationary satellite, in degrees.

    Closed-form and time-invariant (a geostationary satellite sits at a fixed
    sub-satellite longitude). The zenith is `0` at the sub-satellite point and
    rises toward `90` at the limb; the azimuth is in **degrees clockwise from
    north** (`[0, 360)`), the same convention as `solar_zenith_azimuth`, so the
    two feed `relative_azimuth`.

    Args:
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.
        sat_lon: Sub-satellite longitude in degrees east (default 0.0, Meteosat
            prime).
        sat_radius_km: Satellite orbital **radius from Earth's centre** in km
            (default 42164, geostationary) — this is a radius, not an altitude.

    Returns:
        `(zenith, azimuth)` arrays in degrees. The zenith is NaN beyond the
        geometric horizon (points that cannot see the satellite, e.g. the far
        side of the Earth on a full global grid).

    Raises:
        ValueError: When `sat_radius_km` is not greater than Earth's radius (it is
            an orbital radius, not an altitude), or on the same coordinate-argument
            errors as `solar_zenith_angle`.

    Examples:
        - The sub-satellite point sees the satellite at the local zenith (0deg):
            ```python
            >>> from pyramids_eo.composites import satellite_zenith_azimuth
            >>> vza, _ = satellite_zenith_azimuth(lat=0.0, lon=0.0, sat_lon=0.0)
            >>> bool(vza < 0.01)
            True

            ```
        - A point due north of the sub-point sees the satellite due south (~180deg):
            ```python
            >>> from pyramids_eo.composites import satellite_zenith_azimuth
            >>> _, az = satellite_zenith_azimuth(lat=30.0, lon=0.0, sat_lon=0.0)
            >>> bool(175.0 < az < 185.0)
            True

            ```
    """
    if sat_radius_km <= _R_EARTH_KM:
        raise ValueError(
            f"sat_radius_km must exceed Earth's radius ({_R_EARTH_KM} km); got "
            f"{sat_radius_km}. Pass an orbital radius from Earth's centre, not an "
            "altitude (geostationary is ~42164 km)."
        )
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    la = np.deg2rad(lat2d)
    dlon = np.deg2rad(lon2d - sat_lon)
    cos_psi = np.clip(np.cos(la) * np.cos(dlon), -1.0, 1.0)
    psi = np.arccos(cos_psi)
    distance = np.sqrt(
        _R_EARTH_KM**2 + sat_radius_km**2 - 2.0 * _R_EARTH_KM * sat_radius_km * cos_psi
    )
    zenith = np.degrees(
        np.arcsin(np.clip(sat_radius_km * np.sin(psi) / distance, -1.0, 1.0))
    )
    # Beyond the geometric horizon (cos_psi < R_earth / R_sat) the satellite is
    # below the local horizon and cannot be seen; flag those points not-viewable
    # (NaN) rather than letting the arcsin clamp saturate them at a plausible 90.
    zenith = np.where(cos_psi >= _R_EARTH_KM / sat_radius_km, zenith, np.nan)
    azimuth = np.degrees(np.arctan2(np.sin(-dlon), -np.sin(la) * np.cos(dlon))) % 360.0
    return np.asarray(zenith, dtype=float), np.asarray(azimuth, dtype=float)

solar_zenith_angle(time, *, lat=None, lon=None, grid=None) #

Per-pixel solar zenith angle (degrees) for a UTC time and a lon/lat grid.

Computed directly with the NOAA solar-position algorithm. Provide the geographic coordinates either as lat and lon arrays/scalars, or as a grid (a pyramids Dataset in EPSG:4326, whose lat / lon cell-centre axes are meshed to 2-D).

The returned angle is the zenith angle in degrees (0 = Sun overhead, 90 = on the horizon / terminator, 180 = antisolar). day_night_blend takes this and applies cos(deg2rad(...)) internally.

Parameters:

Name Type Description Default
time datetime

Observation time. A naive datetime is treated as UTC; an aware one is converted to UTC.

required
lat Any

Latitude(s) in degrees north — scalar or array. Mutually exclusive with grid; must be paired with lon.

None
lon Any

Longitude(s) in degrees east — scalar or array, broadcast against lat. Mutually exclusive with grid; must be paired with lat.

None
grid Any

A pyramids Dataset (EPSG:4326) supplying lat / lon cell-centre axes. Mutually exclusive with lat / lon.

None

Returns:

Type Description
ndarray

The solar zenith angle in degrees. Shape follows the broadcast of lat

ndarray

and lon, or (grid.rows, grid.columns) for a grid.

Raises:

Type Description
ValueError

When neither grid nor both lat and lon are given, when both are given, or when grid is not geographic (EPSG:4326).

Examples:

  • The Sun is nearly overhead at (0degN, 0degE) at equinox noon:
    >>> import datetime as dt
    >>> from pyramids_eo.composites import solar_zenith_angle
    >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
    >>> bool(solar_zenith_angle(t, lat=0.0, lon=0.0) < 5)
    True
    
  • The antisolar point is in deep night (SZA near 180deg):
    >>> bool(solar_zenith_angle(t, lat=0.0, lon=180.0) > 175)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def solar_zenith_angle(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> np.ndarray:
    """Per-pixel solar zenith angle (degrees) for a UTC time and a lon/lat grid.

    Computed directly with the NOAA solar-position algorithm. Provide the
    geographic coordinates either as `lat`
    and `lon` arrays/scalars, or as a `grid` (a pyramids `Dataset` in EPSG:4326,
    whose `lat` / `lon` cell-centre axes are meshed to 2-D).

    The returned angle is the zenith angle in **degrees** (0 = Sun overhead,
    90 = on the horizon / terminator, 180 = antisolar). `day_night_blend` takes
    this and applies `cos(deg2rad(...))` internally.

    Args:
        time: Observation time. A naive datetime is treated as UTC; an aware one
            is converted to UTC.
        lat: Latitude(s) in degrees north — scalar or array. Mutually exclusive
            with `grid`; must be paired with `lon`.
        lon: Longitude(s) in degrees east — scalar or array, broadcast against
            `lat`. Mutually exclusive with `grid`; must be paired with `lat`.
        grid: A pyramids `Dataset` (EPSG:4326) supplying `lat` / `lon` cell-centre
            axes. Mutually exclusive with `lat` / `lon`.

    Returns:
        The solar zenith angle in degrees. Shape follows the broadcast of `lat`
        and `lon`, or `(grid.rows, grid.columns)` for a `grid`.

    Raises:
        ValueError: When neither `grid` nor both `lat` and `lon` are given, when
            both are given, or when `grid` is not geographic (EPSG:4326).

    Examples:
        - The Sun is nearly overhead at (0degN, 0degE) at equinox noon:
            ```python
            >>> import datetime as dt
            >>> from pyramids_eo.composites import solar_zenith_angle
            >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
            >>> bool(solar_zenith_angle(t, lat=0.0, lon=0.0) < 5)
            True

            ```
        - The antisolar point is in deep night (SZA near 180deg):
            ```python
            >>> bool(solar_zenith_angle(t, lat=0.0, lon=180.0) > 175)
            True

            ```
    """
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    return _solar_position(time, lat2d, lon2d)[0]

solar_zenith_azimuth(time, *, lat=None, lon=None, grid=None) #

Per-pixel solar (zenith, azimuth) in degrees.

Same coordinate inputs as solar_zenith_angle (a lat/lon pair, or an EPSG:4326 grid). The returned zenith is identical to solar_zenith_angle; the azimuth is the NOAA solar azimuth in degrees clockwise from north ([0, 360): 0 = north, 90 = east, 180 = south, 270 = west) — the same convention as satellite_zenith_azimuth, so the two feed relative_azimuth.

Parameters:

Name Type Description Default
time datetime

Observation time (a naive datetime is treated as UTC).

required
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None

Returns:

Type Description
tuple[ndarray, ndarray]

(zenith, azimuth) arrays in degrees.

Raises:

Type Description
ValueError

Same coordinate-argument errors as solar_zenith_angle.

Examples:

  • At equinox noon on the Greenwich meridian the Sun is due south:
    >>> import datetime as dt
    >>> from pyramids_eo.composites import solar_zenith_azimuth
    >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
    >>> _, az = solar_zenith_azimuth(t, lat=45.0, lon=0.0)
    >>> bool(170.0 < az < 190.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def solar_zenith_azimuth(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Per-pixel solar `(zenith, azimuth)` in degrees.

    Same coordinate inputs as `solar_zenith_angle` (a `lat`/`lon` pair, or an
    EPSG:4326 `grid`). The returned zenith is identical to `solar_zenith_angle`;
    the azimuth is the NOAA solar azimuth in **degrees clockwise from north**
    (`[0, 360)`: 0 = north, 90 = east, 180 = south, 270 = west) — the same
    convention as `satellite_zenith_azimuth`, so the two feed `relative_azimuth`.

    Args:
        time: Observation time (a naive datetime is treated as UTC).
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.

    Returns:
        `(zenith, azimuth)` arrays in degrees.

    Raises:
        ValueError: Same coordinate-argument errors as `solar_zenith_angle`.

    Examples:
        - At equinox noon on the Greenwich meridian the Sun is due south:
            ```python
            >>> import datetime as dt
            >>> from pyramids_eo.composites import solar_zenith_azimuth
            >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
            >>> _, az = solar_zenith_azimuth(t, lat=45.0, lon=0.0)
            >>> bool(170.0 < az < 190.0)
            True

            ```
    """
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    return _solar_position(time, lat2d, lon2d)

sunz_correct(band, sza, *, correction_limit=88.0, max_sza=95.0) #

Correct a solar band for the sun-zenith angle (divide by cos(sza), capped).

A plain 1 / cos(sza) diverges at the terminator, so the correction is capped: below correction_limit the factor is 1 / cos(sza); from correction_limit to max_sza it tapers from 1 / cos(correction_limit) down to 0 by an inverted-log2 ramp; beyond max_sza (and where sza is NaN) the factor is 0. The band is multiplied by this factor. This mirrors the reference sunz_corrected modifier (SunZenithCorrector), whose defaults are correction_limit=88, max_sza=95.

Parameters:

Name Type Description Default
band Any

The solar band (reflectance) — array-like or a pyramids Dataset.

required
sza Any

Per-pixel solar zenith angle in degrees (e.g. from solar_zenith_angle), broadcastable against band.

required
correction_limit float

SZA (degrees), in [0, 90), at/beyond which the 1 / cos factor is capped and starts to taper. Also the largest correction applied (1 / cos(correction_limit)).

88.0
max_sza float | None

SZA (degrees) at which the correction reaches 0, or None to hold the factor constant at 1 / cos(correction_limit) beyond the limit (no taper). Must exceed correction_limit.

95.0

Returns:

Type Description
Any

The corrected band (band times the per-pixel factor). A pyramids

Any

Dataset (carrying band's geotransform + CRS) when band is a

Any

Dataset, otherwise an ndarray (a 0-d array for scalar inputs). The

Any

factor is 0 beyond max_sza and where sza is NaN, but a NaN band

Any

value stays NaN (0 * NaN), so off-disk nodata is preserved, not blacked.

Raises:

Type Description
ValueError

When correction_limit is not in [0, 90), or max_sza is not greater than correction_limit.

Examples:

  • Overhead sun is unchanged; a 60deg zenith doubles the signal (1/cos60):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_correct
    >>> sunz_correct(np.array([1.0, 1.0]), np.array([0.0, 60.0])).round(3).tolist()
    [1.0, 2.0]
    
  • The correction stays finite at the terminator (no 1/0 blow-up):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_correct
    >>> bool(np.isfinite(sunz_correct(np.array([1.0]), np.array([90.0]))).all())
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def sunz_correct(
    band: Any,
    sza: Any,
    *,
    correction_limit: float = 88.0,
    max_sza: float | None = 95.0,
) -> Any:
    """Correct a solar band for the sun-zenith angle (divide by `cos(sza)`, capped).

    A plain `1 / cos(sza)` diverges at the terminator, so the correction is capped:
    below `correction_limit` the factor is `1 / cos(sza)`; from `correction_limit`
    to `max_sza` it tapers from `1 / cos(correction_limit)` down to `0` by an
    inverted-`log2` ramp; beyond `max_sza` (and where `sza` is NaN) the factor is
    `0`. The band is multiplied by this factor. This mirrors the reference
    `sunz_corrected` modifier (`SunZenithCorrector`), whose defaults are
    `correction_limit=88`, `max_sza=95`.

    Args:
        band: The solar band (reflectance) — array-like or a pyramids `Dataset`.
        sza: Per-pixel solar zenith angle in **degrees** (e.g. from
            `solar_zenith_angle`), broadcastable against `band`.
        correction_limit: SZA (degrees), in `[0, 90)`, at/beyond which the
            `1 / cos` factor is capped and starts to taper. Also the largest
            correction applied (`1 / cos(correction_limit)`).
        max_sza: SZA (degrees) at which the correction reaches `0`, or `None` to
            hold the factor constant at `1 / cos(correction_limit)` beyond the
            limit (no taper). Must exceed `correction_limit`.

    Returns:
        The corrected band (`band` times the per-pixel factor). A pyramids
        `Dataset` (carrying `band`'s geotransform + CRS) when `band` is a
        `Dataset`, otherwise an ndarray (a 0-d array for scalar inputs). The
        *factor* is `0` beyond `max_sza` and where `sza` is NaN, but a NaN band
        value stays NaN (`0 * NaN`), so off-disk nodata is preserved, not blacked.

    Raises:
        ValueError: When `correction_limit` is not in `[0, 90)`, or `max_sza` is
            not greater than `correction_limit`.

    Examples:
        - Overhead sun is unchanged; a 60deg zenith doubles the signal (`1/cos60`):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_correct
            >>> sunz_correct(np.array([1.0, 1.0]), np.array([0.0, 60.0])).round(3).tolist()
            [1.0, 2.0]

            ```
        - The correction stays finite at the terminator (no `1/0` blow-up):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_correct
            >>> bool(np.isfinite(sunz_correct(np.array([1.0]), np.array([90.0]))).all())
            True

            ```
    """
    if not 0.0 <= correction_limit < 90.0:
        raise ValueError(
            f"correction_limit must be in [0, 90) degrees, got {correction_limit}"
        )
    if max_sza is not None and max_sza <= correction_limit:
        raise ValueError(
            f"max_sza ({max_sza}) must be greater than correction_limit "
            f"({correction_limit})"
        )
    arr = _as_array(band)
    angle = _as_array(sza)
    cos_zen = np.cos(np.deg2rad(angle))
    limit_cos = float(np.cos(np.deg2rad(correction_limit)))

    with np.errstate(divide="ignore", invalid="ignore"):
        corr = 1.0 / cos_zen
    if max_sza is not None:
        ramp = (angle - correction_limit) / (max_sza - correction_limit)
        with np.errstate(invalid="ignore"):
            grad_factor = 1.0 - np.log2(ramp + 1.0)
        grad_factor = np.clip(grad_factor, 0.0, None)
    else:
        grad_factor = np.ones_like(cos_zen)

    corr = np.where(cos_zen > limit_cos, corr, grad_factor / limit_cos)
    corr = np.where(np.isnan(cos_zen), 0.0, corr)
    return _wrap_like(arr * corr, band)

sunz_reduce(band, sza, *, correction_limit=80.0, max_sza=90.0, strength=1.3) #

Taper a solar band's signal toward the terminator so deep shadow reads dark.

Below correction_limit the signal is unchanged; from correction_limit to max_sza it is multiplied by a factor that ramps from 1 down to 0 by an inverted-log2 curve sharpened by a strength sigmoid; at/beyond max_sza (and where sza is NaN) the factor is 0. This mirrors the reference sunz_reduced modifier (SunZenithReducer), whose defaults are correction_limit=80, max_sza=90, strength=1.3.

Parameters:

Name Type Description Default
band Any

The solar band (reflectance) — array-like or a pyramids Dataset.

required
sza Any

Per-pixel solar zenith angle in degrees (e.g. from solar_zenith_angle), broadcastable against band.

required
correction_limit float

SZA (degrees), >= 0, below which the signal is unchanged.

80.0
max_sza float | None

SZA (degrees) at which the signal is fully reduced to 0. Must exceed correction_limit; required (unlike sunz_correct, None is rejected).

90.0
strength float

Sigmoid power sharpening the reduction ramp; 1.0 leaves it as the plain inverted-log2 curve. Must be > 0.

1.3

Returns:

Type Description
Any

The reduced band (band times the per-pixel factor). A pyramids Dataset

Any

(carrying band's geotransform + CRS) when band is a Dataset,

Any

otherwise an ndarray (a 0-d array for scalar inputs). The factor is 0

Any

at/beyond max_sza and where sza is NaN, but a NaN band value stays NaN

Any

(0 * NaN), so off-disk nodata is preserved, not blacked.

Raises:

Type Description
ValueError

When max_sza is None or not greater than correction_limit, correction_limit < 0, or strength <= 0.

Examples:

  • Unchanged below the limit, fully reduced to 0 at max_sza:
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_reduce
    >>> sunz_reduce(np.array([1.0, 1.0]), np.array([70.0, 90.0])).round(3).tolist()
    [1.0, 0.0]
    
  • Inside the band the signal is dimmed (a shadow, not a grey floor):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_reduce
    >>> bool(sunz_reduce(np.array([1.0]), np.array([85.0]))[0] < 1.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def sunz_reduce(
    band: Any,
    sza: Any,
    *,
    correction_limit: float = 80.0,
    max_sza: float | None = 90.0,
    strength: float = 1.3,
) -> Any:
    """Taper a solar band's signal toward the terminator so deep shadow reads dark.

    Below `correction_limit` the signal is unchanged; from `correction_limit` to
    `max_sza` it is multiplied by a factor that ramps from `1` down to `0` by an
    inverted-`log2` curve sharpened by a `strength` sigmoid; at/beyond `max_sza`
    (and where `sza` is NaN) the factor is `0`. This mirrors the reference
    `sunz_reduced` modifier (`SunZenithReducer`), whose defaults are
    `correction_limit=80`, `max_sza=90`, `strength=1.3`.

    Args:
        band: The solar band (reflectance) — array-like or a pyramids `Dataset`.
        sza: Per-pixel solar zenith angle in **degrees** (e.g. from
            `solar_zenith_angle`), broadcastable against `band`.
        correction_limit: SZA (degrees), `>= 0`, below which the signal is
            unchanged.
        max_sza: SZA (degrees) at which the signal is fully reduced to `0`. Must
            exceed `correction_limit`; required (unlike `sunz_correct`, `None` is
            rejected).
        strength: Sigmoid power sharpening the reduction ramp; `1.0` leaves it as
            the plain inverted-`log2` curve. Must be `> 0`.

    Returns:
        The reduced band (`band` times the per-pixel factor). A pyramids `Dataset`
        (carrying `band`'s geotransform + CRS) when `band` is a `Dataset`,
        otherwise an ndarray (a 0-d array for scalar inputs). The *factor* is `0`
        at/beyond `max_sza` and where `sza` is NaN, but a NaN band value stays NaN
        (`0 * NaN`), so off-disk nodata is preserved, not blacked.

    Raises:
        ValueError: When `max_sza` is `None` or not greater than
            `correction_limit`, `correction_limit < 0`, or `strength <= 0`.

    Examples:
        - Unchanged below the limit, fully reduced to `0` at `max_sza`:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_reduce
            >>> sunz_reduce(np.array([1.0, 1.0]), np.array([70.0, 90.0])).round(3).tolist()
            [1.0, 0.0]

            ```
        - Inside the band the signal is dimmed (a shadow, not a grey floor):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_reduce
            >>> bool(sunz_reduce(np.array([1.0]), np.array([85.0]))[0] < 1.0)
            True

            ```
    """
    if max_sza is None:
        raise ValueError("max_sza is required for sunz_reduce (got None)")
    if correction_limit < 0:
        raise ValueError(f"correction_limit must be >= 0, got {correction_limit}")
    if max_sza <= correction_limit:
        raise ValueError(
            f"max_sza ({max_sza}) must be greater than correction_limit "
            f"({correction_limit})"
        )
    if strength <= 0:
        raise ValueError(f"strength must be > 0, got {strength}")
    arr = _as_array(band)
    angle = _as_array(sza)

    ramp = np.clip((angle - correction_limit) / (max_sza - correction_limit), 0.0, 1.0)
    reduction = 1.0 - np.log2(ramp + 1.0)
    reduction = reduction**strength / (
        reduction**strength + (1.0 - reduction) ** strength
    )
    corr = np.where(angle < correction_limit, 1.0, reduction)
    corr = np.where(np.isnan(angle), 0.0, corr)
    return _wrap_like(arr * corr, band)

alpha_overlay(foreground, background) #

Composite an RGBA foreground over an RGB(A) background.

Implements the "over" operator. For an opaque (RGB) background the result is fg_rgb * fg_a + bg_rgb * (1 - fg_a) (a 3-band RGB image). For an RGBA background the full premultiplied over is used, yielding a 4-band RGBA image with a_out = fg_a + bg_a * (1 - fg_a).

Parameters:

Name Type Description Default
foreground Any

The RGBA foreground — a (4, H, W) array-like (R, G, B, alpha) or a pyramids Dataset with four bands. Alpha is expected in [0, 1].

required
background Any

The background — a (3, H, W) RGB or (4, H, W) RGBA array-like or Dataset, matching the foreground's (H, W).

required

Returns:

Type Description
Any

The composited image: 3-band RGB for an RGB background, 4-band RGBA for an

Any

RGBA background. A pyramids Dataset (carrying the foreground's or

Any

background's geotransform + CRS) when either input is a Dataset,

Any

otherwise an ndarray.

Raises:

Type Description
ValueError

When foreground is not a (4, H, W) RGBA array, or when background is not a (3|4, H, W) array.

Examples:

  • A half-transparent red foreground over a blue background blends 50/50:
    >>> import numpy as np
    >>> from pyramids_eo.composites import alpha_overlay
    >>> fg = np.array([[[1.0]], [[0.0]], [[0.0]], [[0.5]]])  # red, alpha 0.5
    >>> bg = np.array([[[0.0]], [[0.0]], [[1.0]]])           # blue
    >>> alpha_overlay(fg, bg).round(2).ravel().tolist()
    [0.5, 0.0, 0.5]
    
Source code in src/pyramids_eo/composites/overlay.py
def alpha_overlay(foreground: Any, background: Any) -> Any:
    """Composite an RGBA foreground over an RGB(A) background.

    Implements the "over" operator. For an **opaque (RGB) background** the result
    is `fg_rgb * fg_a + bg_rgb * (1 - fg_a)` (a 3-band RGB image). For an **RGBA
    background** the full premultiplied over is used, yielding a 4-band RGBA image
    with `a_out = fg_a + bg_a * (1 - fg_a)`.

    Args:
        foreground: The RGBA foreground — a `(4, H, W)` array-like (R, G, B,
            alpha) or a pyramids `Dataset` with four bands. Alpha is expected in
            `[0, 1]`.
        background: The background — a `(3, H, W)` RGB or `(4, H, W)` RGBA
            array-like or `Dataset`, matching the foreground's `(H, W)`.

    Returns:
        The composited image: 3-band RGB for an RGB background, 4-band RGBA for an
        RGBA background. A pyramids `Dataset` (carrying the foreground's or
        background's geotransform + CRS) when either input is a `Dataset`,
        otherwise an ndarray.

    Raises:
        ValueError: When `foreground` is not a `(4, H, W)` RGBA array, or when
            `background` is not a `(3|4, H, W)` array.

    Examples:
        - A half-transparent red foreground over a blue background blends 50/50:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import alpha_overlay
            >>> fg = np.array([[[1.0]], [[0.0]], [[0.0]], [[0.5]]])  # red, alpha 0.5
            >>> bg = np.array([[[0.0]], [[0.0]], [[1.0]]])           # blue
            >>> alpha_overlay(fg, bg).round(2).ravel().tolist()
            [0.5, 0.0, 0.5]

            ```
    """
    fg = _as_array(foreground)
    bg = _as_array(background)
    if fg.ndim != 3 or fg.shape[0] != 4:
        raise ValueError(
            f"foreground must be a (4, H, W) RGBA array; got shape {fg.shape}"
        )
    if bg.ndim != 3 or bg.shape[0] not in (3, 4):
        raise ValueError(
            f"background must be a (3, H, W) RGB or (4, H, W) RGBA array; "
            f"got shape {bg.shape}"
        )

    fg_rgb = fg[:3]
    fg_a = fg[3]

    if bg.shape[0] == 4:
        bg_rgb = bg[:3]
        bg_a = bg[3]
        out_a = fg_a + bg_a * (1.0 - fg_a)
        premultiplied = fg_rgb * fg_a + bg_rgb * bg_a * (1.0 - fg_a)
        out_rgb = np.divide(
            premultiplied,
            out_a,
            out=np.zeros_like(premultiplied),
            where=out_a > 0,
        )
        out = np.concatenate([out_rgb, out_a[np.newaxis, ...]], axis=0)
    else:
        out = fg_rgb * fg_a + bg[:3] * (1.0 - fg_a)

    return _wrap_like(out, foreground, background)

rayleigh_correct(band, *, wavelength_um, sza, vza, azidiff, pressure_hpa=_P0_HPA) #

Rayleigh-correct a solar band by subtracting the molecular path reflectance.

Computes the single-scattering Rayleigh reflectance (see :func:rayleigh_reflectance) for the band's wavelength and geometry and subtracts it from the band, clipping the result at 0. Because the correction grows as wavelength^-4, blue is corrected far more than red. Designed to be used as the true_color rayleigh= hook (per band):

rayleigh=lambda band, *, role: rayleigh_correct(
    band, wavelength_um=WL[role], sza=sza, vza=vza, azidiff=azidiff)

Parameters:

Name Type Description Default
band Any

The solar band reflectance in [0, 1] — array-like or a pyramids Dataset.

required
wavelength_um float

The band's centre wavelength in micrometres (e.g. from the sensor registry Channel.wavelength_um).

required
sza Any

Solar zenith angle(s) in degrees.

required
vza Any

Satellite (view) zenith angle(s) in degrees.

required
azidiff Any

Sun-satellite relative azimuth in degrees.

required
pressure_hpa float

Surface pressure in hPa (default sea level).

_P0_HPA

Returns:

Type Description
Any

The corrected band. A pyramids Dataset (carrying band's geotransform +

Any

CRS) when band is a Dataset, otherwise an ndarray.

Examples:

  • Correcting reduces a band, and blue drops more than red:
    >>> import numpy as np
    >>> from pyramids_eo.composites.rayleigh import rayleigh_correct
    >>> geom = dict(sza=40.0, vza=30.0, azidiff=60.0)
    >>> blue = rayleigh_correct(np.array([0.6]), wavelength_um=0.444, **geom)
    >>> red = rayleigh_correct(np.array([0.6]), wavelength_um=0.640, **geom)
    >>> bool(blue[0] < red[0] < 0.6)
    True
    
Source code in src/pyramids_eo/composites/rayleigh.py
def rayleigh_correct(
    band: Any,
    *,
    wavelength_um: float,
    sza: Any,
    vza: Any,
    azidiff: Any,
    pressure_hpa: float = _P0_HPA,
) -> Any:
    """Rayleigh-correct a solar band by subtracting the molecular path reflectance.

    Computes the single-scattering Rayleigh reflectance (see
    :func:`rayleigh_reflectance`) for the band's wavelength and geometry and
    subtracts it from the band, clipping the result at `0`. Because the
    correction grows as `wavelength^-4`, blue is corrected far more than red.
    Designed to be used as the `true_color` `rayleigh=` hook (per band):

        rayleigh=lambda band, *, role: rayleigh_correct(
            band, wavelength_um=WL[role], sza=sza, vza=vza, azidiff=azidiff)

    Args:
        band: The solar band reflectance in `[0, 1]` — array-like or a pyramids
            `Dataset`.
        wavelength_um: The band's centre wavelength in micrometres (e.g. from the
            sensor registry `Channel.wavelength_um`).
        sza: Solar zenith angle(s) in degrees.
        vza: Satellite (view) zenith angle(s) in degrees.
        azidiff: Sun-satellite relative azimuth in degrees.
        pressure_hpa: Surface pressure in hPa (default sea level).

    Returns:
        The corrected band. A pyramids `Dataset` (carrying `band`'s geotransform +
        CRS) when `band` is a `Dataset`, otherwise an ndarray.

    Examples:
        - Correcting reduces a band, and blue drops more than red:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites.rayleigh import rayleigh_correct
            >>> geom = dict(sza=40.0, vza=30.0, azidiff=60.0)
            >>> blue = rayleigh_correct(np.array([0.6]), wavelength_um=0.444, **geom)
            >>> red = rayleigh_correct(np.array([0.6]), wavelength_um=0.640, **geom)
            >>> bool(blue[0] < red[0] < 0.6)
            True

            ```
    """
    arr = _as_array(band)
    path = rayleigh_reflectance(
        wavelength_um, sza, vza, azidiff, pressure_hpa=pressure_hpa
    )
    return _wrap_like(np.clip(arr - path, 0.0, None), band)

night_ir(red, green, blue, *, alpha=None) #

Stack three IR bands into an RGBA night-cloud image.

Stack the three IR bands (e.g. ir_38, ir_105, ir_123) as RGB and attach an alpha channel. The alpha controls where the background (city lights) shows through — pass a cloud-derived alpha (opaque over cold cloud tops, transparent over clear sky) to reproduce the reference look; the default is fully opaque (alpha = 1).

Parameters:

Name Type Description Default
red Any

The IR band mapped to red (e.g. ir_38) — array-like or Dataset.

required
green Any

The IR band mapped to green (e.g. ir_105).

required
blue Any

The IR band mapped to blue (e.g. ir_123).

required
alpha Any

Per-pixel alpha in [0, 1], or None for fully opaque.

None

Returns:

Type Description
Any

A (4, H, W) RGBA image — a pyramids Dataset when any input is a

Any

Dataset, otherwise an ndarray.

Source code in src/pyramids_eo/composites/true_color_night.py
def night_ir(red: Any, green: Any, blue: Any, *, alpha: Any = None) -> Any:
    """Stack three IR bands into an RGBA night-cloud image.

    Stack the three IR bands (e.g. `ir_38`, `ir_105`, `ir_123`) as RGB and
    attach an alpha channel. The alpha controls where the
    background (city lights) shows through — pass a cloud-derived alpha
    (opaque over cold cloud tops, transparent over clear sky) to reproduce the
    reference look; the default is fully opaque (alpha = 1).

    Args:
        red: The IR band mapped to red (e.g. `ir_38`) — array-like or `Dataset`.
        green: The IR band mapped to green (e.g. `ir_105`).
        blue: The IR band mapped to blue (e.g. `ir_123`).
        alpha: Per-pixel alpha in `[0, 1]`, or `None` for fully opaque.

    Returns:
        A `(4, H, W)` RGBA image — a pyramids `Dataset` when any input is a
        `Dataset`, otherwise an ndarray.
    """
    r = _as_array(red)
    g = _as_array(green)
    b = _as_array(blue)
    a = np.ones_like(r) if alpha is None else _as_array(alpha)
    rgba = np.stack([r, g, b, a], axis=0)
    return _wrap_like(rgba, red, green, blue)

true_color_with_night_ir(day, night_ir_rgba, background, sza, *, lim_low=78.0, lim_high=88.0, keep_alpha=False) #

Compose the full true_color_with_night_ir day/night image.

Overlays the RGBA night-IR clouds on the city-lights background (alpha_overlay), then cross-fades that night image against the day true-colour image by solar zenith angle (day_night_blend).

Parameters:

Name Type Description Default
day Any

The day image — true-colour RGB (3, H, W) array-like or Dataset.

required
night_ir_rgba Any

The RGBA night-IR clouds from night_ir.

required
background Any

The RGB city-lights background (e.g. Black Marble warped to the grid via static_image).

required
sza Any

Per-pixel solar zenith angle in degrees, from solar_zenith_angle.

required
lim_low float

SZA at/below which it is fully day (default 78).

78.0
lim_high float

SZA at/above which it is fully night (default 88).

88.0
keep_alpha bool

When True, append a coverage / alpha band to the (3, H, W) result, giving (4, H, W). Coverage is derived from the two satellite-derived inputs before the global background is merged in — the day true-colour image (valid on the day side of the disk) and the night_ir_rgba clouds (valid on the night side) — so it marks the whole sensor disk, including dark-but-valid night pixels, and is 0 off-disk. Where the band is 0 the RGB is set to a finite 0 so a premultiplied composite stays NaN-free. Default False returns the 3-band image unchanged.

False

Returns:

Type Description
Any

The composed day/night image — a pyramids Dataset when the inputs carry

Any

one, otherwise an ndarray. (4, H, W) when keep_alpha=True, else

Any

(3, H, W).

Examples:

  • Compose a day/night frame from the primitives:
    >>> import numpy as np
    >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
    >>> day = np.ones((3, 1, 2))
    >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
    >>> bg = np.zeros((3, 1, 2))
    >>> true_color_with_night_ir(day, clouds, bg, np.zeros((1, 2))).shape
    (3, 1, 2)
    
  • Keep a coverage band for edge feathering (4-band RGBA):
    >>> import numpy as np
    >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
    >>> day = np.ones((3, 1, 2))
    >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
    >>> bg = np.zeros((3, 1, 2))
    >>> out = true_color_with_night_ir(
    ...     day, clouds, bg, np.zeros((1, 2)), keep_alpha=True
    ... )
    >>> out.shape
    (4, 1, 2)
    
Source code in src/pyramids_eo/composites/true_color_night.py
def true_color_with_night_ir(
    day: Any,
    night_ir_rgba: Any,
    background: Any,
    sza: Any,
    *,
    lim_low: float = 78.0,
    lim_high: float = 88.0,
    keep_alpha: bool = False,
) -> Any:
    """Compose the full `true_color_with_night_ir` day/night image.

    Overlays the RGBA night-IR clouds on the city-lights `background`
    (`alpha_overlay`), then cross-fades that night image against the `day`
    true-colour image by solar zenith angle (`day_night_blend`).

    Args:
        day: The day image — true-colour RGB `(3, H, W)` array-like or `Dataset`.
        night_ir_rgba: The RGBA night-IR clouds from `night_ir`.
        background: The RGB city-lights background (e.g. Black Marble warped to
            the grid via `static_image`).
        sza: Per-pixel solar zenith angle in degrees, from `solar_zenith_angle`.
        lim_low: SZA at/below which it is fully day (default 78).
        lim_high: SZA at/above which it is fully night (default 88).
        keep_alpha: When `True`, append a coverage / alpha band to the `(3, H, W)`
            result, giving `(4, H, W)`. Coverage is derived from the two
            *satellite-derived* inputs before the global background is merged in —
            the `day` true-colour image (valid on the day side of the disk) and
            the `night_ir_rgba` clouds (valid on the night side) — so it marks the
            whole sensor disk, including dark-but-valid night pixels, and is `0`
            off-disk. Where the band is `0` the RGB is set to a finite `0` so a
            premultiplied composite stays NaN-free. Default `False` returns the
            3-band image unchanged.

    Returns:
        The composed day/night image — a pyramids `Dataset` when the inputs carry
        one, otherwise an ndarray. `(4, H, W)` when `keep_alpha=True`, else
        `(3, H, W)`.

    Examples:
        - Compose a day/night frame from the primitives:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
            >>> day = np.ones((3, 1, 2))
            >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
            >>> bg = np.zeros((3, 1, 2))
            >>> true_color_with_night_ir(day, clouds, bg, np.zeros((1, 2))).shape
            (3, 1, 2)

            ```
        - Keep a coverage band for edge feathering (4-band RGBA):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
            >>> day = np.ones((3, 1, 2))
            >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
            >>> bg = np.zeros((3, 1, 2))
            >>> out = true_color_with_night_ir(
            ...     day, clouds, bg, np.zeros((1, 2)), keep_alpha=True
            ... )
            >>> out.shape
            (4, 1, 2)

            ```
    """
    night = alpha_overlay(night_ir_rgba, background)
    blended = day_night_blend(day, night, sza, lim_low=lim_low, lim_high=lim_high)
    if not keep_alpha:
        return blended

    # Coverage from the satellite-derived inputs *before* the global background
    # is merged in: the day true-colour image covers the day side of the disk,
    # the night-IR clouds (RGB, ignoring their own alpha) cover the night side.
    # Their union is the sensor disk. Intersect it with the finite blended pixels
    # so alpha is never 1 over a NaN, and zero the RGB wherever it is not finite
    # so a downstream premultiplied (RGB * alpha) composite cannot leak NaN.
    disk = _coverage(day) | _coverage(_as_array(night_ir_rgba)[:3])
    blended_arr = _as_array(blended)
    rgb = blended_arr if blended_arr.ndim >= 3 else blended_arr[np.newaxis, ...]
    finite_rgb = _coverage(rgb)
    coverage = disk & finite_rgb
    rgb = np.where(finite_rgb[np.newaxis, ...], rgb, 0.0)
    rgba = np.concatenate([rgb, coverage.astype(float)[np.newaxis, ...]], axis=0)
    return _wrap_like(rgba, day, night_ir_rgba, background)

pyramids_eo.composites.geometry #

Solar geometry for day/night compositing.

solar_zenith_angle gives the per-pixel solar zenith angle (SZA) from a UTC time and a lon/lat grid, computed directly with the NOAA solar-position algorithm over NumPy. The SZA drives the day/night cross-fade (day_night_blend), which keys off the Sun's geometric position rather than how dark a pixel looks (the property that renders an eclipse shadow as day, not night).

sunz_correct and sunz_reduce consume that angle: the first divides a solar band by cos(sza) (capped, so it does not blow up at the terminator), the second tapers the signal back down toward the terminator so deep shadow renders dark rather than as a washed-out floor. Together they mirror the sunz_corrected and sunz_reduced modifiers used on every solar prerequisite of a reference true-colour composite.

For atmospheric corrections, solar_zenith_azimuth and satellite_zenith_azimuth add the viewing geometry — the Sun's and a geostationary satellite's zenith and azimuth per pixel — and relative_azimuth folds the two azimuths into the Sun-satellite difference every correction model expects. All azimuths use one convention: degrees clockwise from north ([0, 360)).

solar_zenith_angle(time, *, lat=None, lon=None, grid=None) #

Per-pixel solar zenith angle (degrees) for a UTC time and a lon/lat grid.

Computed directly with the NOAA solar-position algorithm. Provide the geographic coordinates either as lat and lon arrays/scalars, or as a grid (a pyramids Dataset in EPSG:4326, whose lat / lon cell-centre axes are meshed to 2-D).

The returned angle is the zenith angle in degrees (0 = Sun overhead, 90 = on the horizon / terminator, 180 = antisolar). day_night_blend takes this and applies cos(deg2rad(...)) internally.

Parameters:

Name Type Description Default
time datetime

Observation time. A naive datetime is treated as UTC; an aware one is converted to UTC.

required
lat Any

Latitude(s) in degrees north — scalar or array. Mutually exclusive with grid; must be paired with lon.

None
lon Any

Longitude(s) in degrees east — scalar or array, broadcast against lat. Mutually exclusive with grid; must be paired with lat.

None
grid Any

A pyramids Dataset (EPSG:4326) supplying lat / lon cell-centre axes. Mutually exclusive with lat / lon.

None

Returns:

Type Description
ndarray

The solar zenith angle in degrees. Shape follows the broadcast of lat

ndarray

and lon, or (grid.rows, grid.columns) for a grid.

Raises:

Type Description
ValueError

When neither grid nor both lat and lon are given, when both are given, or when grid is not geographic (EPSG:4326).

Examples:

  • The Sun is nearly overhead at (0degN, 0degE) at equinox noon:
    >>> import datetime as dt
    >>> from pyramids_eo.composites import solar_zenith_angle
    >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
    >>> bool(solar_zenith_angle(t, lat=0.0, lon=0.0) < 5)
    True
    
  • The antisolar point is in deep night (SZA near 180deg):
    >>> bool(solar_zenith_angle(t, lat=0.0, lon=180.0) > 175)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def solar_zenith_angle(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> np.ndarray:
    """Per-pixel solar zenith angle (degrees) for a UTC time and a lon/lat grid.

    Computed directly with the NOAA solar-position algorithm. Provide the
    geographic coordinates either as `lat`
    and `lon` arrays/scalars, or as a `grid` (a pyramids `Dataset` in EPSG:4326,
    whose `lat` / `lon` cell-centre axes are meshed to 2-D).

    The returned angle is the zenith angle in **degrees** (0 = Sun overhead,
    90 = on the horizon / terminator, 180 = antisolar). `day_night_blend` takes
    this and applies `cos(deg2rad(...))` internally.

    Args:
        time: Observation time. A naive datetime is treated as UTC; an aware one
            is converted to UTC.
        lat: Latitude(s) in degrees north — scalar or array. Mutually exclusive
            with `grid`; must be paired with `lon`.
        lon: Longitude(s) in degrees east — scalar or array, broadcast against
            `lat`. Mutually exclusive with `grid`; must be paired with `lat`.
        grid: A pyramids `Dataset` (EPSG:4326) supplying `lat` / `lon` cell-centre
            axes. Mutually exclusive with `lat` / `lon`.

    Returns:
        The solar zenith angle in degrees. Shape follows the broadcast of `lat`
        and `lon`, or `(grid.rows, grid.columns)` for a `grid`.

    Raises:
        ValueError: When neither `grid` nor both `lat` and `lon` are given, when
            both are given, or when `grid` is not geographic (EPSG:4326).

    Examples:
        - The Sun is nearly overhead at (0degN, 0degE) at equinox noon:
            ```python
            >>> import datetime as dt
            >>> from pyramids_eo.composites import solar_zenith_angle
            >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
            >>> bool(solar_zenith_angle(t, lat=0.0, lon=0.0) < 5)
            True

            ```
        - The antisolar point is in deep night (SZA near 180deg):
            ```python
            >>> bool(solar_zenith_angle(t, lat=0.0, lon=180.0) > 175)
            True

            ```
    """
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    return _solar_position(time, lat2d, lon2d)[0]

cos_solar_zenith_angle(time, *, lat=None, lon=None, grid=None) #

Per-pixel cosine of the solar zenith angle.

A thin wrapper over solar_zenith_angle returning cos(SZA) directly — the form the readers' and radiance_to_reflectance's cos_sza arguments expect (note solar_zenith_angle itself returns the angle in degrees). Same arguments as solar_zenith_angle.

Parameters:

Name Type Description Default
time datetime

Observation time (a naive datetime is treated as UTC).

required
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None

Returns:

Type Description
ndarray

The cosine of the solar zenith angle, same shape as the coordinates.

Source code in src/pyramids_eo/composites/geometry.py
def cos_solar_zenith_angle(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> np.ndarray:
    """Per-pixel cosine of the solar zenith angle.

    A thin wrapper over `solar_zenith_angle` returning `cos(SZA)` directly — the
    form the readers' and `radiance_to_reflectance`'s `cos_sza` arguments expect
    (note `solar_zenith_angle` itself returns the angle in *degrees*). Same
    arguments as `solar_zenith_angle`.

    Args:
        time: Observation time (a naive datetime is treated as UTC).
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.

    Returns:
        The cosine of the solar zenith angle, same shape as the coordinates.
    """
    return np.cos(np.deg2rad(solar_zenith_angle(time, lat=lat, lon=lon, grid=grid)))

solar_zenith_azimuth(time, *, lat=None, lon=None, grid=None) #

Per-pixel solar (zenith, azimuth) in degrees.

Same coordinate inputs as solar_zenith_angle (a lat/lon pair, or an EPSG:4326 grid). The returned zenith is identical to solar_zenith_angle; the azimuth is the NOAA solar azimuth in degrees clockwise from north ([0, 360): 0 = north, 90 = east, 180 = south, 270 = west) — the same convention as satellite_zenith_azimuth, so the two feed relative_azimuth.

Parameters:

Name Type Description Default
time datetime

Observation time (a naive datetime is treated as UTC).

required
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None

Returns:

Type Description
tuple[ndarray, ndarray]

(zenith, azimuth) arrays in degrees.

Raises:

Type Description
ValueError

Same coordinate-argument errors as solar_zenith_angle.

Examples:

  • At equinox noon on the Greenwich meridian the Sun is due south:
    >>> import datetime as dt
    >>> from pyramids_eo.composites import solar_zenith_azimuth
    >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
    >>> _, az = solar_zenith_azimuth(t, lat=45.0, lon=0.0)
    >>> bool(170.0 < az < 190.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def solar_zenith_azimuth(
    time: _dt.datetime,
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Per-pixel solar `(zenith, azimuth)` in degrees.

    Same coordinate inputs as `solar_zenith_angle` (a `lat`/`lon` pair, or an
    EPSG:4326 `grid`). The returned zenith is identical to `solar_zenith_angle`;
    the azimuth is the NOAA solar azimuth in **degrees clockwise from north**
    (`[0, 360)`: 0 = north, 90 = east, 180 = south, 270 = west) — the same
    convention as `satellite_zenith_azimuth`, so the two feed `relative_azimuth`.

    Args:
        time: Observation time (a naive datetime is treated as UTC).
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.

    Returns:
        `(zenith, azimuth)` arrays in degrees.

    Raises:
        ValueError: Same coordinate-argument errors as `solar_zenith_angle`.

    Examples:
        - At equinox noon on the Greenwich meridian the Sun is due south:
            ```python
            >>> import datetime as dt
            >>> from pyramids_eo.composites import solar_zenith_azimuth
            >>> t = dt.datetime(2024, 3, 20, 12, 0, tzinfo=dt.timezone.utc)
            >>> _, az = solar_zenith_azimuth(t, lat=45.0, lon=0.0)
            >>> bool(170.0 < az < 190.0)
            True

            ```
    """
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    return _solar_position(time, lat2d, lon2d)

satellite_zenith_azimuth(*, lat=None, lon=None, grid=None, sat_lon=0.0, sat_radius_km=_R_GEO_KM) #

Per-pixel (zenith, azimuth) of a geostationary satellite, in degrees.

Closed-form and time-invariant (a geostationary satellite sits at a fixed sub-satellite longitude). The zenith is 0 at the sub-satellite point and rises toward 90 at the limb; the azimuth is in degrees clockwise from north ([0, 360)), the same convention as solar_zenith_azimuth, so the two feed relative_azimuth.

Parameters:

Name Type Description Default
lat Any

Latitude(s) in degrees north, paired with lon.

None
lon Any

Longitude(s) in degrees east, paired with lat.

None
grid Any

A pyramids Dataset grid (EPSG:4326), mutually exclusive with lat / lon.

None
sat_lon float

Sub-satellite longitude in degrees east (default 0.0, Meteosat prime).

0.0
sat_radius_km float

Satellite orbital radius from Earth's centre in km (default 42164, geostationary) — this is a radius, not an altitude.

_R_GEO_KM

Returns:

Type Description
ndarray

(zenith, azimuth) arrays in degrees. The zenith is NaN beyond the

ndarray

geometric horizon (points that cannot see the satellite, e.g. the far

tuple[ndarray, ndarray]

side of the Earth on a full global grid).

Raises:

Type Description
ValueError

When sat_radius_km is not greater than Earth's radius (it is an orbital radius, not an altitude), or on the same coordinate-argument errors as solar_zenith_angle.

Examples:

  • The sub-satellite point sees the satellite at the local zenith (0deg):
    >>> from pyramids_eo.composites import satellite_zenith_azimuth
    >>> vza, _ = satellite_zenith_azimuth(lat=0.0, lon=0.0, sat_lon=0.0)
    >>> bool(vza < 0.01)
    True
    
  • A point due north of the sub-point sees the satellite due south (~180deg):
    >>> from pyramids_eo.composites import satellite_zenith_azimuth
    >>> _, az = satellite_zenith_azimuth(lat=30.0, lon=0.0, sat_lon=0.0)
    >>> bool(175.0 < az < 185.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def satellite_zenith_azimuth(
    *,
    lat: Any = None,
    lon: Any = None,
    grid: Any = None,
    sat_lon: float = 0.0,
    sat_radius_km: float = _R_GEO_KM,
) -> tuple[np.ndarray, np.ndarray]:
    """Per-pixel `(zenith, azimuth)` of a geostationary satellite, in degrees.

    Closed-form and time-invariant (a geostationary satellite sits at a fixed
    sub-satellite longitude). The zenith is `0` at the sub-satellite point and
    rises toward `90` at the limb; the azimuth is in **degrees clockwise from
    north** (`[0, 360)`), the same convention as `solar_zenith_azimuth`, so the
    two feed `relative_azimuth`.

    Args:
        lat: Latitude(s) in degrees north, paired with `lon`.
        lon: Longitude(s) in degrees east, paired with `lat`.
        grid: A pyramids `Dataset` grid (EPSG:4326), mutually exclusive with
            `lat` / `lon`.
        sat_lon: Sub-satellite longitude in degrees east (default 0.0, Meteosat
            prime).
        sat_radius_km: Satellite orbital **radius from Earth's centre** in km
            (default 42164, geostationary) — this is a radius, not an altitude.

    Returns:
        `(zenith, azimuth)` arrays in degrees. The zenith is NaN beyond the
        geometric horizon (points that cannot see the satellite, e.g. the far
        side of the Earth on a full global grid).

    Raises:
        ValueError: When `sat_radius_km` is not greater than Earth's radius (it is
            an orbital radius, not an altitude), or on the same coordinate-argument
            errors as `solar_zenith_angle`.

    Examples:
        - The sub-satellite point sees the satellite at the local zenith (0deg):
            ```python
            >>> from pyramids_eo.composites import satellite_zenith_azimuth
            >>> vza, _ = satellite_zenith_azimuth(lat=0.0, lon=0.0, sat_lon=0.0)
            >>> bool(vza < 0.01)
            True

            ```
        - A point due north of the sub-point sees the satellite due south (~180deg):
            ```python
            >>> from pyramids_eo.composites import satellite_zenith_azimuth
            >>> _, az = satellite_zenith_azimuth(lat=30.0, lon=0.0, sat_lon=0.0)
            >>> bool(175.0 < az < 185.0)
            True

            ```
    """
    if sat_radius_km <= _R_EARTH_KM:
        raise ValueError(
            f"sat_radius_km must exceed Earth's radius ({_R_EARTH_KM} km); got "
            f"{sat_radius_km}. Pass an orbital radius from Earth's centre, not an "
            "altitude (geostationary is ~42164 km)."
        )
    lon2d, lat2d = _resolve_coords(lat, lon, grid)
    la = np.deg2rad(lat2d)
    dlon = np.deg2rad(lon2d - sat_lon)
    cos_psi = np.clip(np.cos(la) * np.cos(dlon), -1.0, 1.0)
    psi = np.arccos(cos_psi)
    distance = np.sqrt(
        _R_EARTH_KM**2 + sat_radius_km**2 - 2.0 * _R_EARTH_KM * sat_radius_km * cos_psi
    )
    zenith = np.degrees(
        np.arcsin(np.clip(sat_radius_km * np.sin(psi) / distance, -1.0, 1.0))
    )
    # Beyond the geometric horizon (cos_psi < R_earth / R_sat) the satellite is
    # below the local horizon and cannot be seen; flag those points not-viewable
    # (NaN) rather than letting the arcsin clamp saturate them at a plausible 90.
    zenith = np.where(cos_psi >= _R_EARTH_KM / sat_radius_km, zenith, np.nan)
    azimuth = np.degrees(np.arctan2(np.sin(-dlon), -np.sin(la) * np.cos(dlon))) % 360.0
    return np.asarray(zenith, dtype=float), np.asarray(azimuth, dtype=float)

relative_azimuth(sun_az, sat_az) #

Sun-satellite azimuth difference, folded into [0, 180] degrees.

The absolute difference of two azimuths (each in [0, 360), clockwise from north) folded to [0, 180] — the relative-azimuth input every atmospheric correction expects. Order-independent.

Parameters:

Name Type Description Default
sun_az Any

Solar azimuth(s) in degrees (e.g. from solar_zenith_azimuth).

required
sat_az Any

Satellite azimuth(s) in degrees (e.g. from satellite_zenith_azimuth).

required

Returns:

Type Description
ndarray

The relative azimuth in [0, 180] degrees, broadcast over the inputs.

Examples:

  • Opposed azimuths (0deg and 180deg) give the maximum, 180deg:
    >>> from pyramids_eo.composites import relative_azimuth
    >>> float(relative_azimuth(10.0, 190.0))
    180.0
    
  • Azimuths 350deg and 10deg are only 20deg apart (wrap-around):
    >>> from pyramids_eo.composites import relative_azimuth
    >>> float(relative_azimuth(350.0, 10.0))
    20.0
    
Source code in src/pyramids_eo/composites/geometry.py
def relative_azimuth(sun_az: Any, sat_az: Any) -> np.ndarray:
    """Sun-satellite azimuth difference, folded into `[0, 180]` degrees.

    The absolute difference of two azimuths (each in `[0, 360)`, clockwise from
    north) folded to `[0, 180]` — the relative-azimuth input every atmospheric
    correction expects. Order-independent.

    Args:
        sun_az: Solar azimuth(s) in degrees (e.g. from `solar_zenith_azimuth`).
        sat_az: Satellite azimuth(s) in degrees (e.g. from
            `satellite_zenith_azimuth`).

    Returns:
        The relative azimuth in `[0, 180]` degrees, broadcast over the inputs.

    Examples:
        - Opposed azimuths (0deg and 180deg) give the maximum, 180deg:
            ```python
            >>> from pyramids_eo.composites import relative_azimuth
            >>> float(relative_azimuth(10.0, 190.0))
            180.0

            ```
        - Azimuths 350deg and 10deg are only 20deg apart (wrap-around):
            ```python
            >>> from pyramids_eo.composites import relative_azimuth
            >>> float(relative_azimuth(350.0, 10.0))
            20.0

            ```
    """
    diff = (
        np.abs(np.asarray(sun_az, dtype=float) - np.asarray(sat_az, dtype=float))
        % 360.0
    )
    return np.asarray(np.where(diff > 180.0, 360.0 - diff, diff), dtype=float)

sunz_correct(band, sza, *, correction_limit=88.0, max_sza=95.0) #

Correct a solar band for the sun-zenith angle (divide by cos(sza), capped).

A plain 1 / cos(sza) diverges at the terminator, so the correction is capped: below correction_limit the factor is 1 / cos(sza); from correction_limit to max_sza it tapers from 1 / cos(correction_limit) down to 0 by an inverted-log2 ramp; beyond max_sza (and where sza is NaN) the factor is 0. The band is multiplied by this factor. This mirrors the reference sunz_corrected modifier (SunZenithCorrector), whose defaults are correction_limit=88, max_sza=95.

Parameters:

Name Type Description Default
band Any

The solar band (reflectance) — array-like or a pyramids Dataset.

required
sza Any

Per-pixel solar zenith angle in degrees (e.g. from solar_zenith_angle), broadcastable against band.

required
correction_limit float

SZA (degrees), in [0, 90), at/beyond which the 1 / cos factor is capped and starts to taper. Also the largest correction applied (1 / cos(correction_limit)).

88.0
max_sza float | None

SZA (degrees) at which the correction reaches 0, or None to hold the factor constant at 1 / cos(correction_limit) beyond the limit (no taper). Must exceed correction_limit.

95.0

Returns:

Type Description
Any

The corrected band (band times the per-pixel factor). A pyramids

Any

Dataset (carrying band's geotransform + CRS) when band is a

Any

Dataset, otherwise an ndarray (a 0-d array for scalar inputs). The

Any

factor is 0 beyond max_sza and where sza is NaN, but a NaN band

Any

value stays NaN (0 * NaN), so off-disk nodata is preserved, not blacked.

Raises:

Type Description
ValueError

When correction_limit is not in [0, 90), or max_sza is not greater than correction_limit.

Examples:

  • Overhead sun is unchanged; a 60deg zenith doubles the signal (1/cos60):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_correct
    >>> sunz_correct(np.array([1.0, 1.0]), np.array([0.0, 60.0])).round(3).tolist()
    [1.0, 2.0]
    
  • The correction stays finite at the terminator (no 1/0 blow-up):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_correct
    >>> bool(np.isfinite(sunz_correct(np.array([1.0]), np.array([90.0]))).all())
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def sunz_correct(
    band: Any,
    sza: Any,
    *,
    correction_limit: float = 88.0,
    max_sza: float | None = 95.0,
) -> Any:
    """Correct a solar band for the sun-zenith angle (divide by `cos(sza)`, capped).

    A plain `1 / cos(sza)` diverges at the terminator, so the correction is capped:
    below `correction_limit` the factor is `1 / cos(sza)`; from `correction_limit`
    to `max_sza` it tapers from `1 / cos(correction_limit)` down to `0` by an
    inverted-`log2` ramp; beyond `max_sza` (and where `sza` is NaN) the factor is
    `0`. The band is multiplied by this factor. This mirrors the reference
    `sunz_corrected` modifier (`SunZenithCorrector`), whose defaults are
    `correction_limit=88`, `max_sza=95`.

    Args:
        band: The solar band (reflectance) — array-like or a pyramids `Dataset`.
        sza: Per-pixel solar zenith angle in **degrees** (e.g. from
            `solar_zenith_angle`), broadcastable against `band`.
        correction_limit: SZA (degrees), in `[0, 90)`, at/beyond which the
            `1 / cos` factor is capped and starts to taper. Also the largest
            correction applied (`1 / cos(correction_limit)`).
        max_sza: SZA (degrees) at which the correction reaches `0`, or `None` to
            hold the factor constant at `1 / cos(correction_limit)` beyond the
            limit (no taper). Must exceed `correction_limit`.

    Returns:
        The corrected band (`band` times the per-pixel factor). A pyramids
        `Dataset` (carrying `band`'s geotransform + CRS) when `band` is a
        `Dataset`, otherwise an ndarray (a 0-d array for scalar inputs). The
        *factor* is `0` beyond `max_sza` and where `sza` is NaN, but a NaN band
        value stays NaN (`0 * NaN`), so off-disk nodata is preserved, not blacked.

    Raises:
        ValueError: When `correction_limit` is not in `[0, 90)`, or `max_sza` is
            not greater than `correction_limit`.

    Examples:
        - Overhead sun is unchanged; a 60deg zenith doubles the signal (`1/cos60`):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_correct
            >>> sunz_correct(np.array([1.0, 1.0]), np.array([0.0, 60.0])).round(3).tolist()
            [1.0, 2.0]

            ```
        - The correction stays finite at the terminator (no `1/0` blow-up):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_correct
            >>> bool(np.isfinite(sunz_correct(np.array([1.0]), np.array([90.0]))).all())
            True

            ```
    """
    if not 0.0 <= correction_limit < 90.0:
        raise ValueError(
            f"correction_limit must be in [0, 90) degrees, got {correction_limit}"
        )
    if max_sza is not None and max_sza <= correction_limit:
        raise ValueError(
            f"max_sza ({max_sza}) must be greater than correction_limit "
            f"({correction_limit})"
        )
    arr = _as_array(band)
    angle = _as_array(sza)
    cos_zen = np.cos(np.deg2rad(angle))
    limit_cos = float(np.cos(np.deg2rad(correction_limit)))

    with np.errstate(divide="ignore", invalid="ignore"):
        corr = 1.0 / cos_zen
    if max_sza is not None:
        ramp = (angle - correction_limit) / (max_sza - correction_limit)
        with np.errstate(invalid="ignore"):
            grad_factor = 1.0 - np.log2(ramp + 1.0)
        grad_factor = np.clip(grad_factor, 0.0, None)
    else:
        grad_factor = np.ones_like(cos_zen)

    corr = np.where(cos_zen > limit_cos, corr, grad_factor / limit_cos)
    corr = np.where(np.isnan(cos_zen), 0.0, corr)
    return _wrap_like(arr * corr, band)

sunz_reduce(band, sza, *, correction_limit=80.0, max_sza=90.0, strength=1.3) #

Taper a solar band's signal toward the terminator so deep shadow reads dark.

Below correction_limit the signal is unchanged; from correction_limit to max_sza it is multiplied by a factor that ramps from 1 down to 0 by an inverted-log2 curve sharpened by a strength sigmoid; at/beyond max_sza (and where sza is NaN) the factor is 0. This mirrors the reference sunz_reduced modifier (SunZenithReducer), whose defaults are correction_limit=80, max_sza=90, strength=1.3.

Parameters:

Name Type Description Default
band Any

The solar band (reflectance) — array-like or a pyramids Dataset.

required
sza Any

Per-pixel solar zenith angle in degrees (e.g. from solar_zenith_angle), broadcastable against band.

required
correction_limit float

SZA (degrees), >= 0, below which the signal is unchanged.

80.0
max_sza float | None

SZA (degrees) at which the signal is fully reduced to 0. Must exceed correction_limit; required (unlike sunz_correct, None is rejected).

90.0
strength float

Sigmoid power sharpening the reduction ramp; 1.0 leaves it as the plain inverted-log2 curve. Must be > 0.

1.3

Returns:

Type Description
Any

The reduced band (band times the per-pixel factor). A pyramids Dataset

Any

(carrying band's geotransform + CRS) when band is a Dataset,

Any

otherwise an ndarray (a 0-d array for scalar inputs). The factor is 0

Any

at/beyond max_sza and where sza is NaN, but a NaN band value stays NaN

Any

(0 * NaN), so off-disk nodata is preserved, not blacked.

Raises:

Type Description
ValueError

When max_sza is None or not greater than correction_limit, correction_limit < 0, or strength <= 0.

Examples:

  • Unchanged below the limit, fully reduced to 0 at max_sza:
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_reduce
    >>> sunz_reduce(np.array([1.0, 1.0]), np.array([70.0, 90.0])).round(3).tolist()
    [1.0, 0.0]
    
  • Inside the band the signal is dimmed (a shadow, not a grey floor):
    >>> import numpy as np
    >>> from pyramids_eo.composites import sunz_reduce
    >>> bool(sunz_reduce(np.array([1.0]), np.array([85.0]))[0] < 1.0)
    True
    
Source code in src/pyramids_eo/composites/geometry.py
def sunz_reduce(
    band: Any,
    sza: Any,
    *,
    correction_limit: float = 80.0,
    max_sza: float | None = 90.0,
    strength: float = 1.3,
) -> Any:
    """Taper a solar band's signal toward the terminator so deep shadow reads dark.

    Below `correction_limit` the signal is unchanged; from `correction_limit` to
    `max_sza` it is multiplied by a factor that ramps from `1` down to `0` by an
    inverted-`log2` curve sharpened by a `strength` sigmoid; at/beyond `max_sza`
    (and where `sza` is NaN) the factor is `0`. This mirrors the reference
    `sunz_reduced` modifier (`SunZenithReducer`), whose defaults are
    `correction_limit=80`, `max_sza=90`, `strength=1.3`.

    Args:
        band: The solar band (reflectance) — array-like or a pyramids `Dataset`.
        sza: Per-pixel solar zenith angle in **degrees** (e.g. from
            `solar_zenith_angle`), broadcastable against `band`.
        correction_limit: SZA (degrees), `>= 0`, below which the signal is
            unchanged.
        max_sza: SZA (degrees) at which the signal is fully reduced to `0`. Must
            exceed `correction_limit`; required (unlike `sunz_correct`, `None` is
            rejected).
        strength: Sigmoid power sharpening the reduction ramp; `1.0` leaves it as
            the plain inverted-`log2` curve. Must be `> 0`.

    Returns:
        The reduced band (`band` times the per-pixel factor). A pyramids `Dataset`
        (carrying `band`'s geotransform + CRS) when `band` is a `Dataset`,
        otherwise an ndarray (a 0-d array for scalar inputs). The *factor* is `0`
        at/beyond `max_sza` and where `sza` is NaN, but a NaN band value stays NaN
        (`0 * NaN`), so off-disk nodata is preserved, not blacked.

    Raises:
        ValueError: When `max_sza` is `None` or not greater than
            `correction_limit`, `correction_limit < 0`, or `strength <= 0`.

    Examples:
        - Unchanged below the limit, fully reduced to `0` at `max_sza`:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_reduce
            >>> sunz_reduce(np.array([1.0, 1.0]), np.array([70.0, 90.0])).round(3).tolist()
            [1.0, 0.0]

            ```
        - Inside the band the signal is dimmed (a shadow, not a grey floor):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import sunz_reduce
            >>> bool(sunz_reduce(np.array([1.0]), np.array([85.0]))[0] < 1.0)
            True

            ```
    """
    if max_sza is None:
        raise ValueError("max_sza is required for sunz_reduce (got None)")
    if correction_limit < 0:
        raise ValueError(f"correction_limit must be >= 0, got {correction_limit}")
    if max_sza <= correction_limit:
        raise ValueError(
            f"max_sza ({max_sza}) must be greater than correction_limit "
            f"({correction_limit})"
        )
    if strength <= 0:
        raise ValueError(f"strength must be > 0, got {strength}")
    arr = _as_array(band)
    angle = _as_array(sza)

    ramp = np.clip((angle - correction_limit) / (max_sza - correction_limit), 0.0, 1.0)
    reduction = 1.0 - np.log2(ramp + 1.0)
    reduction = reduction**strength / (
        reduction**strength + (1.0 - reduction) ** strength
    )
    corr = np.where(angle < correction_limit, 1.0, reduction)
    corr = np.where(np.isnan(angle), 0.0, corr)
    return _wrap_like(arr * corr, band)

pyramids_eo.composites.blend #

Solar-zenith-angle day/night blending.

day_night_blend cross-fades a day image and a night image by the per-pixel solar zenith angle (SZA), producing the smooth twilight transition of the true_color_with_night_ir look. The blend keys off the Sun's geometric position (from solar_zenith_angle), not on how dark a pixel looks — which is why an eclipse shadow is rendered as day, not night.

day_weight(sza, lim_low=78.0, lim_high=88.0) #

Per-pixel day weight in [0, 1] from the solar zenith angle.

The weight is 1 where the Sun is high (sza <= lim_low, full day), 0 where it is low (sza >= lim_high, full night), and a smooth cos-space ramp through the twilight band between them — the DayNightCompositor curve.

Parameters:

Name Type Description Default
sza Any

Solar zenith angle in degrees (scalar or array), e.g. from solar_zenith_angle.

required
lim_low float

SZA (degrees) at/below which it is fully day. Default 78.

78.0
lim_high float

SZA (degrees) at/above which it is fully night. Default 88.

88.0

Returns:

Type Description
ndarray

The day weight, same shape as sza, clipped to [0, 1].

Raises:

Type Description
ValueError

When lim_low >= lim_high.

Examples:

  • Overhead Sun is full day, horizon is full night, midway is ~0.5:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_weight
    >>> day_weight(np.array([0.0, 83.0, 90.0])).round(2).tolist()
    [1.0, 0.5, 0.0]
    
Source code in src/pyramids_eo/composites/blend.py
def day_weight(sza: Any, lim_low: float = 78.0, lim_high: float = 88.0) -> np.ndarray:
    """Per-pixel day weight in `[0, 1]` from the solar zenith angle.

    The weight is 1 where the Sun is high (`sza <= lim_low`, full day), 0 where
    it is low (`sza >= lim_high`, full night), and a smooth cos-space ramp
    through the twilight band between them — the DayNightCompositor curve.

    Args:
        sza: Solar zenith angle in degrees (scalar or array), e.g. from
            `solar_zenith_angle`.
        lim_low: SZA (degrees) at/below which it is fully day. Default 78.
        lim_high: SZA (degrees) at/above which it is fully night. Default 88.

    Returns:
        The day weight, same shape as `sza`, clipped to `[0, 1]`.

    Raises:
        ValueError: When `lim_low >= lim_high`.

    Examples:
        - Overhead Sun is full day, horizon is full night, midway is ~0.5:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_weight
            >>> day_weight(np.array([0.0, 83.0, 90.0])).round(2).tolist()
            [1.0, 0.5, 0.0]

            ```
    """
    if lim_low >= lim_high:
        raise ValueError(
            f"lim_low ({lim_low}) must be < lim_high ({lim_high}) in SZA degrees"
        )
    low = np.cos(np.deg2rad(lim_low))
    high = np.cos(np.deg2rad(lim_high))
    coszen = np.cos(np.deg2rad(np.asarray(sza, dtype=float)))
    weight = (coszen - min(low, high)) / abs(low - high)
    return np.asarray(np.clip(weight, 0.0, 1.0), dtype=float)

day_night_blend(day, night, sza, *, lim_low=78.0, lim_high=88.0, mode='day_night', keep_alpha=False) #

Cross-fade a day and a night image by solar zenith angle.

Computes a per-pixel day weight from sza (see day_weight) and mixes: day * weight + night * (1 - weight). day / night may be (H, W) or (band, H, W) arrays, or pyramids Dataset objects; the weight broadcasts across bands.

Parameters:

Name Type Description Default
day Any

The day image — array-like or a pyramids Dataset.

required
night Any

The night image — same shape/type family as day. Ignored when mode="day_only".

required
sza Any

Per-pixel solar zenith angle in degrees ((H, W)), from solar_zenith_angle.

required
lim_low float

SZA at/below which it is fully day (default 78).

78.0
lim_high float

SZA at/above which it is fully night (default 88).

88.0
mode str

"day_night" (blend, default), "day_only" (day * weight), or "night_only" (night * (1 - weight)).

'day_night'
keep_alpha bool

When True, append a coverage / alpha band — 1.0 where the contributing input(s) are finite, the geometry is defined, and the blended pixel itself is finite; 0.0 otherwise (see :func:pyramids_eo.composites._common._coverage). The band comes from data validity, not brightness, so a dark-but-valid pixel stays covered while a NaN-producing twilight pixel does not. Default False leaves the output unchanged.

False

Returns:

Type Description
Any

The blended image. A pyramids Dataset (carrying day's / night's

Any

geotransform + CRS) when either input is a Dataset, otherwise an

Any

ndarray. With keep_alpha=True the output carries one extra (alpha)

Any

band.

Raises:

Type Description
ValueError

When mode is unknown or lim_low >= lim_high.

Examples:

  • A day (1s) / night (0s) pair collapses to the day weight per pixel:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_night_blend
    >>> day = np.ones((2, 2))
    >>> night = np.zeros((2, 2))
    >>> sza = np.array([[0.0, 83.0], [88.0, 180.0]])
    >>> day_night_blend(day, night, sza).round(2).tolist()
    [[1.0, 0.5], [0.0, 0.0]]
    
  • keep_alpha appends a coverage band, giving a 4-band RGBA result:
    >>> import numpy as np
    >>> from pyramids_eo.composites import day_night_blend
    >>> day = np.ones((3, 1, 2))
    >>> night = np.zeros((3, 1, 2))
    >>> sza = np.array([[0.0, 0.0]])
    >>> day_night_blend(day, night, sza, keep_alpha=True).shape
    (4, 1, 2)
    
Source code in src/pyramids_eo/composites/blend.py
def day_night_blend(
    day: Any,
    night: Any,
    sza: Any,
    *,
    lim_low: float = 78.0,
    lim_high: float = 88.0,
    mode: str = "day_night",
    keep_alpha: bool = False,
) -> Any:
    """Cross-fade a day and a night image by solar zenith angle.

    Computes a per-pixel day weight from `sza` (see `day_weight`) and mixes:
    `day * weight + night * (1 - weight)`.
    `day` / `night` may be `(H, W)` or `(band, H, W)` arrays, or pyramids
    `Dataset` objects; the weight broadcasts across bands.

    Args:
        day: The day image — array-like or a pyramids `Dataset`.
        night: The night image — same shape/type family as `day`. Ignored when
            `mode="day_only"`.
        sza: Per-pixel solar zenith angle in degrees (`(H, W)`), from
            `solar_zenith_angle`.
        lim_low: SZA at/below which it is fully day (default 78).
        lim_high: SZA at/above which it is fully night (default 88).
        mode: `"day_night"` (blend, default), `"day_only"` (`day * weight`), or
            `"night_only"` (`night * (1 - weight)`).
        keep_alpha: When `True`, append a coverage / alpha band — `1.0` where the
            contributing input(s) are finite, the geometry is defined, and the
            blended pixel itself is finite; `0.0` otherwise (see
            :func:`pyramids_eo.composites._common._coverage`). The band comes from
            data validity, not brightness, so a dark-but-valid pixel stays covered
            while a NaN-producing twilight pixel does not. Default `False` leaves
            the output unchanged.

    Returns:
        The blended image. A pyramids `Dataset` (carrying `day`'s / `night`'s
        geotransform + CRS) when either input is a `Dataset`, otherwise an
        ndarray. With `keep_alpha=True` the output carries one extra (alpha)
        band.

    Raises:
        ValueError: When `mode` is unknown or `lim_low >= lim_high`.

    Examples:
        - A day (1s) / night (0s) pair collapses to the day weight per pixel:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_night_blend
            >>> day = np.ones((2, 2))
            >>> night = np.zeros((2, 2))
            >>> sza = np.array([[0.0, 83.0], [88.0, 180.0]])
            >>> day_night_blend(day, night, sza).round(2).tolist()
            [[1.0, 0.5], [0.0, 0.0]]

            ```
        - `keep_alpha` appends a coverage band, giving a 4-band RGBA result:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import day_night_blend
            >>> day = np.ones((3, 1, 2))
            >>> night = np.zeros((3, 1, 2))
            >>> sza = np.array([[0.0, 0.0]])
            >>> day_night_blend(day, night, sza, keep_alpha=True).shape
            (4, 1, 2)

            ```
    """
    if mode not in _MODES:
        raise ValueError(f"mode must be one of {_MODES}; got {mode!r}")

    weight2d = day_weight(_as_array(sza), lim_low=lim_low, lim_high=lim_high)
    day_arr = _as_array(day)
    weight = weight2d
    if weight2d.ndim == 2 and day_arr.ndim == 3:
        weight = weight2d[np.newaxis, ...]

    # np.where zeros each image's contribution where its weight is 0, so a NaN
    # in a fully-weighted-out region (e.g. sun-angle-normalised day reflectance,
    # which is NaN across the night side) does not leak through NaN * 0 = NaN.
    if mode == "day_only":
        out = np.where(weight > 0, day_arr * weight, 0.0)
    elif mode == "night_only":
        night_arr = _as_array(night)
        out = np.where(weight < 1, night_arr * (1.0 - weight), 0.0)
    else:
        night_arr = _as_array(night)
        day_term = np.where(weight > 0, day_arr * weight, 0.0)
        night_term = np.where(weight < 1, night_arr * (1.0 - weight), 0.0)
        out = day_term + night_term
    # A NaN weight means the SZA (day/night geometry) is undefined, so keep the
    # pixel masked as NaN rather than collapsing it to 0 — matching day_weight's
    # NaN propagation (the weight-zeroing above only handles image-side NaN).
    out = np.where(np.isnan(weight), np.nan, out)

    if keep_alpha:
        out = _append_alpha(out, day, night, weight2d, mode)

    return _wrap_like(out, day, night)

pyramids_eo.composites.overlay #

Alpha overlay of one image over another.

alpha_overlay composites an RGBA foreground over an RGB or RGBA background with the standard "over" operator. In the day/night chain the foreground is the night-IR cloud RGBA (transparent where there are no clouds) and the background is the Black Marble city lights, so the lights show through the gaps.

alpha_overlay(foreground, background) #

Composite an RGBA foreground over an RGB(A) background.

Implements the "over" operator. For an opaque (RGB) background the result is fg_rgb * fg_a + bg_rgb * (1 - fg_a) (a 3-band RGB image). For an RGBA background the full premultiplied over is used, yielding a 4-band RGBA image with a_out = fg_a + bg_a * (1 - fg_a).

Parameters:

Name Type Description Default
foreground Any

The RGBA foreground — a (4, H, W) array-like (R, G, B, alpha) or a pyramids Dataset with four bands. Alpha is expected in [0, 1].

required
background Any

The background — a (3, H, W) RGB or (4, H, W) RGBA array-like or Dataset, matching the foreground's (H, W).

required

Returns:

Type Description
Any

The composited image: 3-band RGB for an RGB background, 4-band RGBA for an

Any

RGBA background. A pyramids Dataset (carrying the foreground's or

Any

background's geotransform + CRS) when either input is a Dataset,

Any

otherwise an ndarray.

Raises:

Type Description
ValueError

When foreground is not a (4, H, W) RGBA array, or when background is not a (3|4, H, W) array.

Examples:

  • A half-transparent red foreground over a blue background blends 50/50:
    >>> import numpy as np
    >>> from pyramids_eo.composites import alpha_overlay
    >>> fg = np.array([[[1.0]], [[0.0]], [[0.0]], [[0.5]]])  # red, alpha 0.5
    >>> bg = np.array([[[0.0]], [[0.0]], [[1.0]]])           # blue
    >>> alpha_overlay(fg, bg).round(2).ravel().tolist()
    [0.5, 0.0, 0.5]
    
Source code in src/pyramids_eo/composites/overlay.py
def alpha_overlay(foreground: Any, background: Any) -> Any:
    """Composite an RGBA foreground over an RGB(A) background.

    Implements the "over" operator. For an **opaque (RGB) background** the result
    is `fg_rgb * fg_a + bg_rgb * (1 - fg_a)` (a 3-band RGB image). For an **RGBA
    background** the full premultiplied over is used, yielding a 4-band RGBA image
    with `a_out = fg_a + bg_a * (1 - fg_a)`.

    Args:
        foreground: The RGBA foreground — a `(4, H, W)` array-like (R, G, B,
            alpha) or a pyramids `Dataset` with four bands. Alpha is expected in
            `[0, 1]`.
        background: The background — a `(3, H, W)` RGB or `(4, H, W)` RGBA
            array-like or `Dataset`, matching the foreground's `(H, W)`.

    Returns:
        The composited image: 3-band RGB for an RGB background, 4-band RGBA for an
        RGBA background. A pyramids `Dataset` (carrying the foreground's or
        background's geotransform + CRS) when either input is a `Dataset`,
        otherwise an ndarray.

    Raises:
        ValueError: When `foreground` is not a `(4, H, W)` RGBA array, or when
            `background` is not a `(3|4, H, W)` array.

    Examples:
        - A half-transparent red foreground over a blue background blends 50/50:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import alpha_overlay
            >>> fg = np.array([[[1.0]], [[0.0]], [[0.0]], [[0.5]]])  # red, alpha 0.5
            >>> bg = np.array([[[0.0]], [[0.0]], [[1.0]]])           # blue
            >>> alpha_overlay(fg, bg).round(2).ravel().tolist()
            [0.5, 0.0, 0.5]

            ```
    """
    fg = _as_array(foreground)
    bg = _as_array(background)
    if fg.ndim != 3 or fg.shape[0] != 4:
        raise ValueError(
            f"foreground must be a (4, H, W) RGBA array; got shape {fg.shape}"
        )
    if bg.ndim != 3 or bg.shape[0] not in (3, 4):
        raise ValueError(
            f"background must be a (3, H, W) RGB or (4, H, W) RGBA array; "
            f"got shape {bg.shape}"
        )

    fg_rgb = fg[:3]
    fg_a = fg[3]

    if bg.shape[0] == 4:
        bg_rgb = bg[:3]
        bg_a = bg[3]
        out_a = fg_a + bg_a * (1.0 - fg_a)
        premultiplied = fg_rgb * fg_a + bg_rgb * bg_a * (1.0 - fg_a)
        out_rgb = np.divide(
            premultiplied,
            out_a,
            out=np.zeros_like(premultiplied),
            where=out_a > 0,
        )
        out = np.concatenate([out_rgb, out_a[np.newaxis, ...]], axis=0)
    else:
        out = fg_rgb * fg_a + bg[:3] * (1.0 - fg_a)

    return _wrap_like(out, foreground, background)

pyramids_eo.composites.background #

Static georeferenced background images for compositing.

static_image loads a georeferenced raster (e.g. the NASA Black Marble city lights that back the night-IR clouds), caching it locally when the source is a URL, and optionally warps/crops it to another dataset's grid via pyramids' align.

It takes a plain local or remote path and caches a remote one. A live Black Marble mirror is https://eoimages.gsfc.nasa.gov/images/imagerecords/144000/144898/BlackMarble_2016_3km_geo.tif (the older neo.gsfc.nasa.gov/archive/blackmarble/... URLs are 404).

static_image(source, *, like=None, cache_dir=None, timeout=60.0, max_bytes=_DEFAULT_MAX_BYTES, refresh=False) #

Load a georeferenced image, caching a remote URL and warping to a grid.

Loads a georeferenced background image. source may be a local path (relative or absolute) or an http/https URL; a URL is downloaded once and cached under cache_dir. When like is given, the loaded image is warped and cropped onto that dataset's grid (CRS + rows/columns + cell size) via pyramids' align.

Parameters:

Name Type Description Default
source Any

A local filesystem path or an http/https URL to a georeferenced raster (e.g. the Black Marble GeoTIFF).

required
like Any

A pyramids Dataset whose grid the image is warped/cropped to. When None, the image is returned at its native grid.

None
cache_dir Any

Directory used to cache a downloaded URL. Defaults to ~/.cache/pyramids-eo. Ignored for a local source.

None
timeout float

Per-request download timeout in seconds (default 60).

60.0
max_bytes int

Cap on a URL download in bytes (default ~1 GB) — guards against an oversized/hostile URL filling the cache.

_DEFAULT_MAX_BYTES
refresh bool

When True, re-download a URL even if it is already cached (the cache is otherwise reused whenever the file is present).

False

Returns:

Type Description
Any

A pyramids Dataset — aligned to like's grid when like is given,

Any

otherwise the image at its native grid.

Raises:

Type Description
FileNotFoundError

When a local source does not exist.

EOError

When a URL download exceeds max_bytes.

Source code in src/pyramids_eo/composites/background.py
def static_image(
    source: Any,
    *,
    like: Any = None,
    cache_dir: Any = None,
    timeout: float = 60.0,
    max_bytes: int = _DEFAULT_MAX_BYTES,
    refresh: bool = False,
) -> Any:
    """Load a georeferenced image, caching a remote URL and warping to a grid.

    Loads a georeferenced background image. `source` may be a local path
    (relative or absolute) or an http/https URL; a URL is downloaded once and
    cached under `cache_dir`. When `like` is given, the loaded image is warped
    and cropped onto that dataset's grid (CRS + rows/columns + cell size) via
    pyramids' `align`.

    Args:
        source: A local filesystem path or an http/https URL to a georeferenced
            raster (e.g. the Black Marble GeoTIFF).
        like: A pyramids `Dataset` whose grid the image is warped/cropped to. When
            `None`, the image is returned at its native grid.
        cache_dir: Directory used to cache a downloaded URL. Defaults to
            `~/.cache/pyramids-eo`. Ignored for a local `source`.
        timeout: Per-request download timeout in seconds (default 60).
        max_bytes: Cap on a URL download in bytes (default ~1 GB) — guards against
            an oversized/hostile URL filling the cache.
        refresh: When `True`, re-download a URL even if it is already cached
            (the cache is otherwise reused whenever the file is present).

    Returns:
        A pyramids `Dataset` — aligned to `like`'s grid when `like` is given,
        otherwise the image at its native grid.

    Raises:
        FileNotFoundError: When a local `source` does not exist.
        EOError: When a URL download exceeds `max_bytes`.
    """
    path = _resolve_source(source, cache_dir, timeout, max_bytes, refresh)

    from pyramids.dataset import Dataset

    dataset = Dataset.read_file(str(path))
    if like is not None:
        dataset = dataset.align(like)
    return dataset

pyramids_eo.composites.true_color #

True-colour RGB from calibrated reflectance bands.

SEVIRI carries no native green band, so for it true_color synthesises one from the red, blue, and near-IR ("veggie") reflectances using the CIMSS weighted recipe (green_mode="synthetic", the default), then stacks red / green / blue into an RGB image.

FCI FDHSI does carry a native green band (vis_05, ~0.51 um). For FCI, pass that band as green= and select green_mode="native" to use it directly, or green_mode="ndvi_hybrid" to blend it with the NIR by an NDVI fraction (more NIR over barren surfaces, less over vegetation) — the reference true-colour look.

This is the no-Rayleigh variant (per the pyramids-eo compositing decision): by default it does the band combination only, so the result is slightly flatter over ocean / haze than a Rayleigh-corrected image. Atmospheric / Rayleigh correction stays opt-in rather than automatic — pass a rayleigh= callable and it is applied to each solar band before green synthesis. The package ships a local, dependency-free correction (rayleigh_correct) for that hook, so opting in adds no third-party dependency.

true_color(red, blue, nir, *, green=None, green_mode='synthetic', green_weights=_DEFAULT_GREEN_WEIGHTS, ndvi_strength=3.0, ndvi_limits=(0.15, 0.05), rayleigh=None, gamma=None, clip=False) #

Build a true-colour RGB from red, blue, and near-IR reflectances.

The green channel is built per green_mode:

  • "synthetic" (default) — green = wr*red + wn*nir + wb*blue (the CIMSS recipe), for sensors with no native green band (SEVIRI). Byte-identical to the historical behaviour.
  • "native" — use the green= band directly (FCI vis_05).
  • "ndvi_hybrid" — blend the green= band with the NIR by an NDVI fraction (see :func:_ndvi_hybrid_green).

When rayleigh is given it is applied to each solar band (red, blue, nir, and a native green) before green synthesis; None (default) leaves the bands untouched and adds no dependency. The callable may take just (band), or (band, *, role) where role is the band's part in the composite — one of "red", "green", "blue", "nir" — so it can pick a per-band correction (e.g. a wavelength-dependent Rayleigh) or decline a band by returning it unchanged. The (band, role=...) form is used when the callable accepts a role keyword (probed once); otherwise the (band) form is called.

Parameters:

Name Type Description Default
red Any

Red-band reflectance — array-like or a pyramids Dataset.

required
blue Any

Blue-band reflectance, same grid as red.

required
nir Any

Near-IR ("veggie") reflectance — the synthetic-green source, the NDVI NIR term, and the ndvi_hybrid blend source.

required
green Any

Native green reflectance (FCI vis_05). Required for green_mode "native" / "ndvi_hybrid", ignored for "synthetic".

None
green_mode str

How to build the green channel — "synthetic" (default), "native", or "ndvi_hybrid".

'synthetic'
green_weights tuple[float, float, float]

The (red, nir, blue) weights for the synthetic green (default the CIMSS (0.45, 0.10, 0.45)).

_DEFAULT_GREEN_WEIGHTS
ndvi_strength float

Non-linear NDVI sharpening for "ndvi_hybrid" (default 3.0).

3.0
ndvi_limits tuple[float, float]

The (low, high) NIR fractions for "ndvi_hybrid".

(0.15, 0.05)
rayleigh Callable[..., Any] | None

Optional atmospheric correction applied to each solar band before green synthesis — a callable taking (band) or (band, *, role) (see above), or None.

None
gamma float | None

Optional gamma to apply (value ** (1 / gamma)), or None.

None
clip bool

When True, clip the output to [0, 1].

False

Returns:

Type Description
Any

The (3, H, W) RGB image. A pyramids Dataset (carrying an input

Any

Dataset's geotransform + CRS) when any input is a Dataset, otherwise

Any

an ndarray.

Raises:

Type Description
ValueError

When green_mode is unknown, a native/ndvi_hybrid mode is requested without a green= band, or green_weights is not a 3-tuple.

Examples:

  • Synthetic CIMSS green (SEVIRI-style) from red / blue / NIR reflectance:
    >>> import numpy as np
    >>> from pyramids_eo.composites import true_color
    >>> r, b, n = np.full((1, 1), 0.2), np.full((1, 1), 0.6), np.full((1, 1), 0.9)
    >>> true_color(r, b, n)[1].round(3).tolist()
    [[0.45]]
    
  • Use FCI's native green band directly (green_mode="native"):
    >>> import numpy as np
    >>> from pyramids_eo.composites import true_color
    >>> out = true_color(
    ...     np.full((1, 1), 0.2),
    ...     np.full((1, 1), 0.6),
    ...     np.full((1, 1), 0.9),
    ...     green=np.full((1, 1), 0.44),
    ...     green_mode="native",
    ... )
    >>> out[1].tolist()
    [[0.44]]
    
Source code in src/pyramids_eo/composites/true_color.py
def true_color(
    red: Any,
    blue: Any,
    nir: Any,
    *,
    green: Any = None,
    green_mode: str = "synthetic",
    green_weights: tuple[float, float, float] = _DEFAULT_GREEN_WEIGHTS,
    ndvi_strength: float = 3.0,
    ndvi_limits: tuple[float, float] = (0.15, 0.05),
    rayleigh: Callable[..., Any] | None = None,
    gamma: float | None = None,
    clip: bool = False,
) -> Any:
    """Build a true-colour RGB from red, blue, and near-IR reflectances.

    The green channel is built per `green_mode`:

    * `"synthetic"` (default) — `green = wr*red + wn*nir + wb*blue` (the CIMSS
      recipe), for sensors with no native green band (SEVIRI). Byte-identical to
      the historical behaviour.
    * `"native"` — use the `green=` band directly (FCI `vis_05`).
    * `"ndvi_hybrid"` — blend the `green=` band with the NIR by an NDVI fraction
      (see :func:`_ndvi_hybrid_green`).

    When `rayleigh` is given it is applied to each solar band (red, blue, nir, and
    a native `green`) before green synthesis; `None` (default) leaves the bands
    untouched and adds no dependency. The callable may take just `(band)`, or
    `(band, *, role)` where `role` is the band's part in the composite — one of
    `"red"`, `"green"`, `"blue"`, `"nir"` — so it can pick a per-band correction
    (e.g. a wavelength-dependent Rayleigh) or decline a band by returning it
    unchanged. The `(band, role=...)` form is used when the callable accepts a
    `role` keyword (probed once); otherwise the `(band)` form is called.

    Args:
        red: Red-band reflectance — array-like or a pyramids `Dataset`.
        blue: Blue-band reflectance, same grid as `red`.
        nir: Near-IR ("veggie") reflectance — the synthetic-green source, the
            NDVI NIR term, and the `ndvi_hybrid` blend source.
        green: Native green reflectance (FCI `vis_05`). Required for
            `green_mode` `"native"` / `"ndvi_hybrid"`, ignored for `"synthetic"`.
        green_mode: How to build the green channel — `"synthetic"` (default),
            `"native"`, or `"ndvi_hybrid"`.
        green_weights: The `(red, nir, blue)` weights for the synthetic green
            (default the CIMSS `(0.45, 0.10, 0.45)`).
        ndvi_strength: Non-linear NDVI sharpening for `"ndvi_hybrid"` (default 3.0).
        ndvi_limits: The `(low, high)` NIR fractions for `"ndvi_hybrid"`.
        rayleigh: Optional atmospheric correction applied to each solar band
            before green synthesis — a callable taking `(band)` or `(band, *,
            role)` (see above), or `None`.
        gamma: Optional gamma to apply (`value ** (1 / gamma)`), or `None`.
        clip: When `True`, clip the output to `[0, 1]`.

    Returns:
        The `(3, H, W)` RGB image. A pyramids `Dataset` (carrying an input
        `Dataset`'s geotransform + CRS) when any input is a `Dataset`, otherwise
        an ndarray.

    Raises:
        ValueError: When `green_mode` is unknown, a native/ndvi_hybrid mode is
            requested without a `green=` band, or `green_weights` is not a
            3-tuple.

    Examples:
        - Synthetic CIMSS green (SEVIRI-style) from red / blue / NIR reflectance:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import true_color
            >>> r, b, n = np.full((1, 1), 0.2), np.full((1, 1), 0.6), np.full((1, 1), 0.9)
            >>> true_color(r, b, n)[1].round(3).tolist()
            [[0.45]]

            ```
        - Use FCI's native green band directly (`green_mode="native"`):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import true_color
            >>> out = true_color(
            ...     np.full((1, 1), 0.2),
            ...     np.full((1, 1), 0.6),
            ...     np.full((1, 1), 0.9),
            ...     green=np.full((1, 1), 0.44),
            ...     green_mode="native",
            ... )
            >>> out[1].tolist()
            [[0.44]]

            ```
    """
    if green_mode not in _GREEN_MODES:
        raise ValueError(
            f"green_mode must be one of {_GREEN_MODES}; got {green_mode!r}"
        )

    r = _as_array(red)
    b = _as_array(blue)
    n = _as_array(nir)
    g_native = _as_array(green) if green is not None else None

    if rayleigh is not None:
        rich = _rayleigh_wants_role(rayleigh)
        r = _apply_rayleigh(rayleigh, r, "red", rich)
        b = _apply_rayleigh(rayleigh, b, "blue", rich)
        n = _apply_rayleigh(rayleigh, n, "nir", rich)
        if g_native is not None:
            g_native = _apply_rayleigh(rayleigh, g_native, "green", rich)

    green_ch = _build_green_channel(
        green_mode, r, b, n, g_native, green_weights, ndvi_strength, ndvi_limits
    )

    rgb = np.stack([r, green_ch, b], axis=0)

    if gamma is not None:
        rgb = np.where(rgb > 0, rgb, 0.0) ** (1.0 / gamma)
    if clip:
        rgb = np.clip(rgb, 0.0, 1.0)

    return _wrap_like(rgb, red, blue, nir, green)

pyramids_eo.composites.rayleigh #

Local Rayleigh (molecular-scattering) correction for solar bands.

A self-contained, closed-form single-scattering Rayleigh correction over NumPy — no third-party radiative-transfer dependency. It removes the blue molecular-scattering veil a no-Rayleigh true colour leaves over the disc, using the viewing geometry from geometry.py (solar_zenith_azimuth, satellite_zenith_azimuth, relative_azimuth).

The model is:

  • Rayleigh optical thickness tau_r(lambda) from the Hansen & Travis (1974) closed form, scaled linearly by surface pressure.
  • The Rayleigh phase function P(Theta) = 3/4 (1 + cos^2 Theta) at the Sun-satellite scattering angle.
  • The single-scattering path reflectance rho_r = P(Theta) / (4 (mu_s + mu_v)) * (1 - exp(-tau_r (1/mu_s + 1/mu_v))), which stays bounded toward the terminator / limb.

rho_r is subtracted from the (already reflectance-scaled [0, 1]) band. Because tau_r goes as lambda^-4, blue is corrected several times more than red — the per-band selectivity the composite needs. This is a single-scattering approximation (no multiple scattering, aerosol, or surface coupling), so it is lighter and slightly less accurate than a full radiative-transfer table, but it carries no dependency and reproduces the bulk of the blue-veil removal.

rayleigh_optical_depth(wavelength_um, pressure_hpa=_P0_HPA) #

Rayleigh optical thickness at a wavelength, scaled by surface pressure.

Uses the Hansen & Travis (1974) closed form tau0 = 0.008569 l^-4 (1 + 0.0113 l^-2 + 0.00013 l^-4) (l in micrometres, sea level), scaled linearly by pressure_hpa / 1013.25.

Parameters:

Name Type Description Default
wavelength_um float

Band centre wavelength in micrometres.

required
pressure_hpa float

Surface pressure in hPa (default sea level, 1013.25).

_P0_HPA

Returns:

Type Description
float

The (dimensionless) Rayleigh optical thickness.

Raises:

Type Description
ValueError

When wavelength_um or pressure_hpa is not positive.

Examples:

  • Blue scatters far more than red (the lambda^-4 law):
    >>> from pyramids_eo.composites.rayleigh import rayleigh_optical_depth
    >>> blue = rayleigh_optical_depth(0.444)
    >>> red = rayleigh_optical_depth(0.640)
    >>> bool(blue > 3 * red)
    True
    
Source code in src/pyramids_eo/composites/rayleigh.py
def rayleigh_optical_depth(
    wavelength_um: float, pressure_hpa: float = _P0_HPA
) -> float:
    """Rayleigh optical thickness at a wavelength, scaled by surface pressure.

    Uses the Hansen & Travis (1974) closed form
    `tau0 = 0.008569 l^-4 (1 + 0.0113 l^-2 + 0.00013 l^-4)` (`l` in micrometres,
    sea level), scaled linearly by `pressure_hpa / 1013.25`.

    Args:
        wavelength_um: Band centre wavelength in micrometres.
        pressure_hpa: Surface pressure in hPa (default sea level, 1013.25).

    Returns:
        The (dimensionless) Rayleigh optical thickness.

    Raises:
        ValueError: When `wavelength_um` or `pressure_hpa` is not positive.

    Examples:
        - Blue scatters far more than red (the `lambda^-4` law):
            ```python
            >>> from pyramids_eo.composites.rayleigh import rayleigh_optical_depth
            >>> blue = rayleigh_optical_depth(0.444)
            >>> red = rayleigh_optical_depth(0.640)
            >>> bool(blue > 3 * red)
            True

            ```
    """
    if wavelength_um <= 0:
        raise ValueError(f"wavelength_um must be > 0, got {wavelength_um}")
    if pressure_hpa <= 0:
        raise ValueError(f"pressure_hpa must be > 0, got {pressure_hpa}")
    lam = wavelength_um
    tau0 = 0.008569 * lam**-4 * (1.0 + 0.0113 * lam**-2 + 0.00013 * lam**-4)
    return tau0 * (pressure_hpa / _P0_HPA)

rayleigh_reflectance(wavelength_um, sza, vza, azidiff, *, pressure_hpa=_P0_HPA) #

Single-scattering Rayleigh path reflectance for the viewing geometry.

Parameters:

Name Type Description Default
wavelength_um float

Band centre wavelength in micrometres.

required
sza Any

Solar zenith angle(s) in degrees (e.g. from solar_zenith_azimuth).

required
vza Any

Satellite (view) zenith angle(s) in degrees (from satellite_zenith_azimuth).

required
azidiff Any

Sun-satellite relative azimuth in degrees (from relative_azimuth).

required
pressure_hpa float

Surface pressure in hPa (default sea level).

_P0_HPA

Returns:

Type Description
ndarray

The per-pixel Rayleigh path reflectance in [0, 1] (clamped — the single-

ndarray

scattering form is unbounded toward the limb), 0 on the night side

ndarray

(sza >= 90) or where the view is off-disc (vza >= 90), and NaN where a

ndarray

geometry input is NaN.

Raises:

Type Description
ValueError

When wavelength_um or pressure_hpa is not positive (via :func:rayleigh_optical_depth).

Examples:

  • The path reflectance is a small positive fraction, larger for blue:
    >>> from pyramids_eo.composites.rayleigh import rayleigh_reflectance
    >>> blue = rayleigh_reflectance(0.444, sza=40.0, vza=30.0, azidiff=60.0)
    >>> red = rayleigh_reflectance(0.640, sza=40.0, vza=30.0, azidiff=60.0)
    >>> bool(0.0 < float(blue) < 0.3)
    True
    >>> bool(float(blue) > float(red))
    True
    
  • There is no single-scatter path on the night side (sza >= 90):
    >>> from pyramids_eo.composites.rayleigh import rayleigh_reflectance
    >>> float(rayleigh_reflectance(0.444, sza=120.0, vza=30.0, azidiff=60.0))
    0.0
    
Source code in src/pyramids_eo/composites/rayleigh.py
def rayleigh_reflectance(
    wavelength_um: float,
    sza: Any,
    vza: Any,
    azidiff: Any,
    *,
    pressure_hpa: float = _P0_HPA,
) -> np.ndarray:
    """Single-scattering Rayleigh path reflectance for the viewing geometry.

    Args:
        wavelength_um: Band centre wavelength in micrometres.
        sza: Solar zenith angle(s) in degrees (e.g. from `solar_zenith_azimuth`).
        vza: Satellite (view) zenith angle(s) in degrees (from
            `satellite_zenith_azimuth`).
        azidiff: Sun-satellite relative azimuth in degrees (from
            `relative_azimuth`).
        pressure_hpa: Surface pressure in hPa (default sea level).

    Returns:
        The per-pixel Rayleigh path reflectance in `[0, 1]` (clamped — the single-
        scattering form is unbounded toward the limb), `0` on the night side
        (`sza >= 90`) or where the view is off-disc (`vza >= 90`), and NaN where a
        geometry input is NaN.

    Raises:
        ValueError: When `wavelength_um` or `pressure_hpa` is not positive (via
            :func:`rayleigh_optical_depth`).

    Examples:
        - The path reflectance is a small positive fraction, larger for blue:
            ```python
            >>> from pyramids_eo.composites.rayleigh import rayleigh_reflectance
            >>> blue = rayleigh_reflectance(0.444, sza=40.0, vza=30.0, azidiff=60.0)
            >>> red = rayleigh_reflectance(0.640, sza=40.0, vza=30.0, azidiff=60.0)
            >>> bool(0.0 < float(blue) < 0.3)
            True
            >>> bool(float(blue) > float(red))
            True

            ```
        - There is no single-scatter path on the night side (`sza >= 90`):
            ```python
            >>> from pyramids_eo.composites.rayleigh import rayleigh_reflectance
            >>> float(rayleigh_reflectance(0.444, sza=120.0, vza=30.0, azidiff=60.0))
            0.0

            ```
    """
    tau = rayleigh_optical_depth(wavelength_um, pressure_hpa)
    sza_r = np.deg2rad(_as_array(sza))
    vza_r = np.deg2rad(_as_array(vza))
    raz_r = np.deg2rad(_as_array(azidiff))

    mu_s = np.cos(sza_r)
    mu_v = np.cos(vza_r)
    # Rayleigh phase function at the scattering angle. cos(Theta) is
    # -mu_s*mu_v - sin(sza)*sin(vza)*cos(azidiff); azidiff = 0 (co-azimuth)
    # maximises the phase over azimuth -- and is true back-scatter (cos(Theta) = -1)
    # when sza == vza. cos**2 is even, so only the azimuth *sign* is immaterial --
    # the term's own sign is not.
    cos_scat = -mu_s * mu_v - np.sin(sza_r) * np.sin(vza_r) * np.cos(raz_r)
    phase = 0.75 * (1.0 + cos_scat**2)

    with np.errstate(divide="ignore", invalid="ignore"):
        transmittance = 1.0 - np.exp(-tau * (1.0 / mu_s + 1.0 / mu_v))
        refl = phase / (4.0 * (mu_s + mu_v)) * transmittance
    # Only a sunlit, on-disc pixel (mu_s > 0 and mu_v > 0) has a single-scatter
    # path; elsewhere (night, or an off-disc view) there is none. The single-
    # scattering form is unbounded toward the limb, so clamp to the physical
    # [0, 1]. A NaN geometry stays NaN.
    refl = np.where((mu_s > 0) & (mu_v > 0), refl, 0.0)
    refl = np.clip(refl, 0.0, 1.0)
    invalid = np.isnan(mu_s) | np.isnan(mu_v) | np.isnan(raz_r)
    return np.asarray(np.where(invalid, np.nan, refl), dtype=float)

rayleigh_correct(band, *, wavelength_um, sza, vza, azidiff, pressure_hpa=_P0_HPA) #

Rayleigh-correct a solar band by subtracting the molecular path reflectance.

Computes the single-scattering Rayleigh reflectance (see :func:rayleigh_reflectance) for the band's wavelength and geometry and subtracts it from the band, clipping the result at 0. Because the correction grows as wavelength^-4, blue is corrected far more than red. Designed to be used as the true_color rayleigh= hook (per band):

rayleigh=lambda band, *, role: rayleigh_correct(
    band, wavelength_um=WL[role], sza=sza, vza=vza, azidiff=azidiff)

Parameters:

Name Type Description Default
band Any

The solar band reflectance in [0, 1] — array-like or a pyramids Dataset.

required
wavelength_um float

The band's centre wavelength in micrometres (e.g. from the sensor registry Channel.wavelength_um).

required
sza Any

Solar zenith angle(s) in degrees.

required
vza Any

Satellite (view) zenith angle(s) in degrees.

required
azidiff Any

Sun-satellite relative azimuth in degrees.

required
pressure_hpa float

Surface pressure in hPa (default sea level).

_P0_HPA

Returns:

Type Description
Any

The corrected band. A pyramids Dataset (carrying band's geotransform +

Any

CRS) when band is a Dataset, otherwise an ndarray.

Examples:

  • Correcting reduces a band, and blue drops more than red:
    >>> import numpy as np
    >>> from pyramids_eo.composites.rayleigh import rayleigh_correct
    >>> geom = dict(sza=40.0, vza=30.0, azidiff=60.0)
    >>> blue = rayleigh_correct(np.array([0.6]), wavelength_um=0.444, **geom)
    >>> red = rayleigh_correct(np.array([0.6]), wavelength_um=0.640, **geom)
    >>> bool(blue[0] < red[0] < 0.6)
    True
    
Source code in src/pyramids_eo/composites/rayleigh.py
def rayleigh_correct(
    band: Any,
    *,
    wavelength_um: float,
    sza: Any,
    vza: Any,
    azidiff: Any,
    pressure_hpa: float = _P0_HPA,
) -> Any:
    """Rayleigh-correct a solar band by subtracting the molecular path reflectance.

    Computes the single-scattering Rayleigh reflectance (see
    :func:`rayleigh_reflectance`) for the band's wavelength and geometry and
    subtracts it from the band, clipping the result at `0`. Because the
    correction grows as `wavelength^-4`, blue is corrected far more than red.
    Designed to be used as the `true_color` `rayleigh=` hook (per band):

        rayleigh=lambda band, *, role: rayleigh_correct(
            band, wavelength_um=WL[role], sza=sza, vza=vza, azidiff=azidiff)

    Args:
        band: The solar band reflectance in `[0, 1]` — array-like or a pyramids
            `Dataset`.
        wavelength_um: The band's centre wavelength in micrometres (e.g. from the
            sensor registry `Channel.wavelength_um`).
        sza: Solar zenith angle(s) in degrees.
        vza: Satellite (view) zenith angle(s) in degrees.
        azidiff: Sun-satellite relative azimuth in degrees.
        pressure_hpa: Surface pressure in hPa (default sea level).

    Returns:
        The corrected band. A pyramids `Dataset` (carrying `band`'s geotransform +
        CRS) when `band` is a `Dataset`, otherwise an ndarray.

    Examples:
        - Correcting reduces a band, and blue drops more than red:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites.rayleigh import rayleigh_correct
            >>> geom = dict(sza=40.0, vza=30.0, azidiff=60.0)
            >>> blue = rayleigh_correct(np.array([0.6]), wavelength_um=0.444, **geom)
            >>> red = rayleigh_correct(np.array([0.6]), wavelength_um=0.640, **geom)
            >>> bool(blue[0] < red[0] < 0.6)
            True

            ```
    """
    arr = _as_array(band)
    path = rayleigh_reflectance(
        wavelength_um, sza, vza, azidiff, pressure_hpa=pressure_hpa
    )
    return _wrap_like(np.clip(arr - path, 0.0, None), band)

pyramids_eo.composites.true_color_night #

Assemble the true_color_with_night_ir day/night image.

This wires the compositing primitives into the true_color_with_night_ir chain, entirely in pyramids-eo:

true_color_with_night_ir = day_night_blend(
    day        = true_color,
    night      = alpha_overlay(night_ir, static_image(BlackMarble)),
    sza        = solar_zenith_angle(...),
)
night_ir = stack(ir_38, ir_105, ir_123) -> RGB + alpha

night_ir builds the RGBA night-cloud image (the IR-stack step); true_color_with_night_ir overlays it on the city-lights background and cross-fades against the day image by solar zenith angle.

night_ir(red, green, blue, *, alpha=None) #

Stack three IR bands into an RGBA night-cloud image.

Stack the three IR bands (e.g. ir_38, ir_105, ir_123) as RGB and attach an alpha channel. The alpha controls where the background (city lights) shows through — pass a cloud-derived alpha (opaque over cold cloud tops, transparent over clear sky) to reproduce the reference look; the default is fully opaque (alpha = 1).

Parameters:

Name Type Description Default
red Any

The IR band mapped to red (e.g. ir_38) — array-like or Dataset.

required
green Any

The IR band mapped to green (e.g. ir_105).

required
blue Any

The IR band mapped to blue (e.g. ir_123).

required
alpha Any

Per-pixel alpha in [0, 1], or None for fully opaque.

None

Returns:

Type Description
Any

A (4, H, W) RGBA image — a pyramids Dataset when any input is a

Any

Dataset, otherwise an ndarray.

Source code in src/pyramids_eo/composites/true_color_night.py
def night_ir(red: Any, green: Any, blue: Any, *, alpha: Any = None) -> Any:
    """Stack three IR bands into an RGBA night-cloud image.

    Stack the three IR bands (e.g. `ir_38`, `ir_105`, `ir_123`) as RGB and
    attach an alpha channel. The alpha controls where the
    background (city lights) shows through — pass a cloud-derived alpha
    (opaque over cold cloud tops, transparent over clear sky) to reproduce the
    reference look; the default is fully opaque (alpha = 1).

    Args:
        red: The IR band mapped to red (e.g. `ir_38`) — array-like or `Dataset`.
        green: The IR band mapped to green (e.g. `ir_105`).
        blue: The IR band mapped to blue (e.g. `ir_123`).
        alpha: Per-pixel alpha in `[0, 1]`, or `None` for fully opaque.

    Returns:
        A `(4, H, W)` RGBA image — a pyramids `Dataset` when any input is a
        `Dataset`, otherwise an ndarray.
    """
    r = _as_array(red)
    g = _as_array(green)
    b = _as_array(blue)
    a = np.ones_like(r) if alpha is None else _as_array(alpha)
    rgba = np.stack([r, g, b, a], axis=0)
    return _wrap_like(rgba, red, green, blue)

true_color_with_night_ir(day, night_ir_rgba, background, sza, *, lim_low=78.0, lim_high=88.0, keep_alpha=False) #

Compose the full true_color_with_night_ir day/night image.

Overlays the RGBA night-IR clouds on the city-lights background (alpha_overlay), then cross-fades that night image against the day true-colour image by solar zenith angle (day_night_blend).

Parameters:

Name Type Description Default
day Any

The day image — true-colour RGB (3, H, W) array-like or Dataset.

required
night_ir_rgba Any

The RGBA night-IR clouds from night_ir.

required
background Any

The RGB city-lights background (e.g. Black Marble warped to the grid via static_image).

required
sza Any

Per-pixel solar zenith angle in degrees, from solar_zenith_angle.

required
lim_low float

SZA at/below which it is fully day (default 78).

78.0
lim_high float

SZA at/above which it is fully night (default 88).

88.0
keep_alpha bool

When True, append a coverage / alpha band to the (3, H, W) result, giving (4, H, W). Coverage is derived from the two satellite-derived inputs before the global background is merged in — the day true-colour image (valid on the day side of the disk) and the night_ir_rgba clouds (valid on the night side) — so it marks the whole sensor disk, including dark-but-valid night pixels, and is 0 off-disk. Where the band is 0 the RGB is set to a finite 0 so a premultiplied composite stays NaN-free. Default False returns the 3-band image unchanged.

False

Returns:

Type Description
Any

The composed day/night image — a pyramids Dataset when the inputs carry

Any

one, otherwise an ndarray. (4, H, W) when keep_alpha=True, else

Any

(3, H, W).

Examples:

  • Compose a day/night frame from the primitives:
    >>> import numpy as np
    >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
    >>> day = np.ones((3, 1, 2))
    >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
    >>> bg = np.zeros((3, 1, 2))
    >>> true_color_with_night_ir(day, clouds, bg, np.zeros((1, 2))).shape
    (3, 1, 2)
    
  • Keep a coverage band for edge feathering (4-band RGBA):
    >>> import numpy as np
    >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
    >>> day = np.ones((3, 1, 2))
    >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
    >>> bg = np.zeros((3, 1, 2))
    >>> out = true_color_with_night_ir(
    ...     day, clouds, bg, np.zeros((1, 2)), keep_alpha=True
    ... )
    >>> out.shape
    (4, 1, 2)
    
Source code in src/pyramids_eo/composites/true_color_night.py
def true_color_with_night_ir(
    day: Any,
    night_ir_rgba: Any,
    background: Any,
    sza: Any,
    *,
    lim_low: float = 78.0,
    lim_high: float = 88.0,
    keep_alpha: bool = False,
) -> Any:
    """Compose the full `true_color_with_night_ir` day/night image.

    Overlays the RGBA night-IR clouds on the city-lights `background`
    (`alpha_overlay`), then cross-fades that night image against the `day`
    true-colour image by solar zenith angle (`day_night_blend`).

    Args:
        day: The day image — true-colour RGB `(3, H, W)` array-like or `Dataset`.
        night_ir_rgba: The RGBA night-IR clouds from `night_ir`.
        background: The RGB city-lights background (e.g. Black Marble warped to
            the grid via `static_image`).
        sza: Per-pixel solar zenith angle in degrees, from `solar_zenith_angle`.
        lim_low: SZA at/below which it is fully day (default 78).
        lim_high: SZA at/above which it is fully night (default 88).
        keep_alpha: When `True`, append a coverage / alpha band to the `(3, H, W)`
            result, giving `(4, H, W)`. Coverage is derived from the two
            *satellite-derived* inputs before the global background is merged in —
            the `day` true-colour image (valid on the day side of the disk) and
            the `night_ir_rgba` clouds (valid on the night side) — so it marks the
            whole sensor disk, including dark-but-valid night pixels, and is `0`
            off-disk. Where the band is `0` the RGB is set to a finite `0` so a
            premultiplied composite stays NaN-free. Default `False` returns the
            3-band image unchanged.

    Returns:
        The composed day/night image — a pyramids `Dataset` when the inputs carry
        one, otherwise an ndarray. `(4, H, W)` when `keep_alpha=True`, else
        `(3, H, W)`.

    Examples:
        - Compose a day/night frame from the primitives:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
            >>> day = np.ones((3, 1, 2))
            >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
            >>> bg = np.zeros((3, 1, 2))
            >>> true_color_with_night_ir(day, clouds, bg, np.zeros((1, 2))).shape
            (3, 1, 2)

            ```
        - Keep a coverage band for edge feathering (4-band RGBA):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.composites import night_ir, true_color_with_night_ir
            >>> day = np.ones((3, 1, 2))
            >>> clouds = night_ir(np.ones((1, 2)), np.ones((1, 2)), np.ones((1, 2)))
            >>> bg = np.zeros((3, 1, 2))
            >>> out = true_color_with_night_ir(
            ...     day, clouds, bg, np.zeros((1, 2)), keep_alpha=True
            ... )
            >>> out.shape
            (4, 1, 2)

            ```
    """
    night = alpha_overlay(night_ir_rgba, background)
    blended = day_night_blend(day, night, sza, lim_low=lim_low, lim_high=lim_high)
    if not keep_alpha:
        return blended

    # Coverage from the satellite-derived inputs *before* the global background
    # is merged in: the day true-colour image covers the day side of the disk,
    # the night-IR clouds (RGB, ignoring their own alpha) cover the night side.
    # Their union is the sensor disk. Intersect it with the finite blended pixels
    # so alpha is never 1 over a NaN, and zero the RGB wherever it is not finite
    # so a downstream premultiplied (RGB * alpha) composite cannot leak NaN.
    disk = _coverage(day) | _coverage(_as_array(night_ir_rgba)[:3])
    blended_arr = _as_array(blended)
    rgb = blended_arr if blended_arr.ndim >= 3 else blended_arr[np.newaxis, ...]
    finite_rgb = _coverage(rgb)
    coverage = disk & finite_rgb
    rgb = np.where(finite_rgb[np.newaxis, ...], rgb, 0.0)
    rgba = np.concatenate([rgb, coverage.astype(float)[np.newaxis, ...]], axis=0)
    return _wrap_like(rgba, day, night_ir_rgba, background)

Display and resampling#

stretch (pyramids_eo.enhance) maps a composite's physical values — reflectance in roughly [0, 1], brightness temperature in kelvin — onto a display range and dtype (uint8 by default), via a "linear", "crude", "cira", or "histogram" curve. to_area (pyramids_eo.resample) warps a georeferenced composite onto an exact target grid (a CRS, an extent, and a pixel width/height) in a single GDAL pass — the one step of the chain with no direct pyramids equivalent.

pyramids_eo.enhance #

Map composite physical values to a display range.

pyramids-eo composites return physical values — reflectance in roughly [0, 1], brightness temperature in kelvin. stretch maps those to a display range and dtype (uint8 by default), the step between a raw composite and a displayable frame.

Four curves are provided:

  • "linear" — percentile-clip (the cutoffs) then rescale to [0, 1].
  • "crude" — fixed min/max linear rescale, (x - lo) / (hi - lo).
  • "cira" — a logarithmic, human-vision-tuned stretch; recommended for a true-colour composite (no gamma needed). Note it is not the signature default; pass kind="cira" explicitly.
  • "histogram" — histogram equalisation.

The stretch is computed over the whole array (shared across bands), preserving inter-band ratios — important for a true-colour image. NaN / nodata pixels are excluded from the statistics and preserved (float output) or filled with 0 (integer output). For an RGBA input carrying a coverage / alpha band (e.g. from keep_alpha), pass preserve_alpha=True so the trailing band is passed through untouched instead of being curved like image data. Reflectance is expected in [0, 1]; scale first if it is in percent.

For an integer frame, 0 is used for both a masked pixel and a valid-black pixel, so the coverage / alpha band — not the nodata value — is the reliable mask.

stretch(image, *, kind='linear', min_stretch=None, max_stretch=None, gamma=None, cutoffs=(0.005, 0.005), preserve_alpha=False, dtype='uint8') #

Map a composite's physical values to a display range and dtype.

Parameters:

Name Type Description Default
image Any

The composite — an array ((H, W) or (band, H, W)) or a pyramids Dataset. Reflectance is expected in [0, 1].

required
kind str

The stretch curve — "linear" (percentile-clip then rescale), "crude" (fixed min/max rescale), "cira" (logarithmic; the true-colour default), or "histogram" (equalisation).

'linear'
min_stretch float | None

Fixed lower bound for linear/crude; None derives it.

None
max_stretch float | None

Fixed upper bound for linear/crude; None derives it.

None
gamma float | None

Optional power curve x ** (1 / gamma) applied after the stretch.

None
cutoffs tuple[float, float]

(left, right) percentile fractions clipped by the linear curve (default 0.5% per side). Ignored by the other kinds. Each must be non-negative and the two must sum to less than 1.

(0.005, 0.005)
preserve_alpha bool

When True and image is (band, H, W) with 2+ bands, the trailing band is treated as a coverage / alpha band — passed through untouched (only cast to dtype) rather than curved. Use it when stretching an alpha-carrying frame from keep_alpha (RGBA / LA). Do not set it for a plain RGB image: its last band (blue) would be passed through uncurved.

False
dtype Any

Output dtype. Integer dtypes scale [0, 1] onto [0, max] and fill NaN with 0; float dtypes keep [0, 1] and preserve NaN.

'uint8'

Returns:

Type Description
Any

The stretched image in dtype — a pyramids Dataset (carrying the

Any

input's geotransform + CRS, nodata 0 for integer / NaN for float) when

Any

image is a Dataset, otherwise an ndarray.

Raises:

Type Description
ValueError

When kind is unknown, gamma is not positive, or cutoffs are negative or sum to 1 or more.

Examples:

  • Crude-stretch reflectance onto the 8-bit display range:
    >>> import numpy as np
    >>> from pyramids_eo.enhance import stretch
    >>> stretch(
    ...     np.array([[0.0, 0.5, 1.0]]),
    ...     kind="crude",
    ...     min_stretch=0.0,
    ...     max_stretch=1.0,
    ... ).tolist()
    [[0, 128, 255]]
    
  • The CIRA log stretch keeps NaN and lifts low reflectance (float out):
    >>> import numpy as np
    >>> from pyramids_eo.enhance import stretch
    >>> out = stretch(np.array([[0.02, 0.5]]), kind="cira", dtype="float64")
    >>> bool(out[0, 1] > out[0, 0])
    True
    
Source code in src/pyramids_eo/enhance.py
def stretch(
    image: Any,
    *,
    kind: str = "linear",
    min_stretch: float | None = None,
    max_stretch: float | None = None,
    gamma: float | None = None,
    cutoffs: tuple[float, float] = (0.005, 0.005),
    preserve_alpha: bool = False,
    dtype: Any = "uint8",
) -> Any:
    """Map a composite's physical values to a display range and dtype.

    Args:
        image: The composite — an array (`(H, W)` or `(band, H, W)`) or a pyramids
            `Dataset`. Reflectance is expected in `[0, 1]`.
        kind: The stretch curve — `"linear"` (percentile-clip then rescale),
            `"crude"` (fixed min/max rescale), `"cira"` (logarithmic; the
            true-colour default), or `"histogram"` (equalisation).
        min_stretch: Fixed lower bound for `linear`/`crude`; `None` derives it.
        max_stretch: Fixed upper bound for `linear`/`crude`; `None` derives it.
        gamma: Optional power curve `x ** (1 / gamma)` applied after the stretch.
        cutoffs: `(left, right)` percentile fractions clipped by the `linear`
            curve (default 0.5% per side). Ignored by the other kinds. Each must
            be non-negative and the two must sum to less than 1.
        preserve_alpha: When `True` and `image` is `(band, H, W)` with 2+ bands,
            the trailing band is treated as a coverage / alpha band — passed
            through untouched (only cast to `dtype`) rather than curved. Use it
            when stretching an alpha-carrying frame from `keep_alpha` (RGBA / LA).
            Do not set it for a plain RGB image: its last band (blue) would be
            passed through uncurved.
        dtype: Output dtype. Integer dtypes scale `[0, 1]` onto `[0, max]` and
            fill NaN with 0; float dtypes keep `[0, 1]` and preserve NaN.

    Returns:
        The stretched image in `dtype` — a pyramids `Dataset` (carrying the
        input's geotransform + CRS, nodata 0 for integer / NaN for float) when
        `image` is a `Dataset`, otherwise an ndarray.

    Raises:
        ValueError: When `kind` is unknown, `gamma` is not positive, or `cutoffs`
            are negative or sum to 1 or more.

    Examples:
        - Crude-stretch reflectance onto the 8-bit display range:
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.enhance import stretch
            >>> stretch(
            ...     np.array([[0.0, 0.5, 1.0]]),
            ...     kind="crude",
            ...     min_stretch=0.0,
            ...     max_stretch=1.0,
            ... ).tolist()
            [[0, 128, 255]]

            ```
        - The CIRA log stretch keeps NaN and lifts low reflectance (float out):
            ```python
            >>> import numpy as np
            >>> from pyramids_eo.enhance import stretch
            >>> out = stretch(np.array([[0.02, 0.5]]), kind="cira", dtype="float64")
            >>> bool(out[0, 1] > out[0, 0])
            True

            ```
    """
    if kind not in _KINDS:
        raise ValueError(f"kind must be one of {_KINDS}; got {kind!r}")
    if gamma is not None and gamma <= 0:
        raise ValueError(f"gamma must be > 0, got {gamma}")
    if cutoffs[0] < 0 or cutoffs[1] < 0 or cutoffs[0] + cutoffs[1] >= 1:
        raise ValueError(
            f"cutoffs must be non-negative and sum to < 1; got {cutoffs!r}"
        )

    values, template = _read(image)
    if preserve_alpha and values.ndim >= 3 and values.shape[0] >= 2:
        rgb = _curve(values[:-1], kind, min_stretch, max_stretch, gamma, cutoffs)
        alpha = np.clip(values[-1], 0.0, 1.0)
        norm = np.concatenate([rgb, alpha[np.newaxis, ...]], axis=0)
    else:
        norm = _curve(values, kind, min_stretch, max_stretch, gamma, cutoffs)

    out = _to_dtype(norm, dtype)
    return _wrap(out, template, dtype)

pyramids_eo.resample #

Resample a composite onto an explicit target grid.

to_area places a georeferenced composite onto an exact target grid — a CRS, an extent, and a pixel width/height — with a chosen interpolation method, in a single GDAL warp. This is the one step of the day/night chain with no pyramids equivalent: Dataset.to_crs lets GDAL pick the grid, and Dataset.align needs a pre-built template Dataset already on the grid. A direct warp pins -t_srs / -te / -ts / -r together and lands the exact grid in one pass — the same primitive the Earth Engine reader keeps for the same reason.

to_area(dataset, crs, extent, width, height, *, method='bilinear') #

Warp a composite onto an exact target grid (CRS + extent + size).

Parameters:

Name Type Description Default
dataset Any

The source composite — a pyramids Dataset (needs a .raster handle to warp; an ndarray has no georeferencing to place).

required
crs Any

Target CRS — any string GDAL accepts, including an EPSG code or a PROJ4 string with no EPSG (e.g. a +proj=nsper ... perspective).

required
extent tuple[float, float, float, float]

Output bounds (min_x, min_y, max_x, max_y) in crs units.

required
width int

Output width in pixels.

required
height int

Output height in pixels.

required
method str

Resampling method — one of to_area's supported names ("bilinear" default, "nearest", "cubic", ...).

'bilinear'

Returns:

Type Description
Dataset

A pyramids Dataset on exactly that grid — CRS crs, extent extent,

Dataset

shape (bands, height, width) — with band count, dtype and nodata

Dataset

preserved from dataset.

Raises:

Type Description
ValueError

When dataset has no raster handle, extent is malformed, width/height are not whole positive pixel counts, method is unknown, or crs is a bool.

RuntimeError

When the GDAL warp fails.

Examples:

  • Warp a small WGS84 raster onto an exact 4x4 grid:
    >>> import numpy as np
    >>> from pyramids.dataset import Dataset, GeoReference
    >>> from pyramids_eo.resample import to_area
    >>> src = Dataset.from_array(
    ...     np.ones((2, 2)),
    ...     geo_ref=GeoReference(top_left_corner=(0.0, 2.0), cell_size=1.0, epsg=4326),
    ... )
    >>> out = to_area(src, 4326, (0.0, 0.0, 2.0, 2.0), 4, 4)
    >>> out.read_array().shape
    (4, 4)
    
Source code in src/pyramids_eo/resample.py
def to_area(
    dataset: Any,
    crs: Any,
    extent: tuple[float, float, float, float],
    width: int,
    height: int,
    *,
    method: str = "bilinear",
) -> Dataset:
    """Warp a composite onto an exact target grid (CRS + extent + size).

    Args:
        dataset: The source composite — a pyramids `Dataset` (needs a `.raster`
            handle to warp; an ndarray has no georeferencing to place).
        crs: Target CRS — any string GDAL accepts, including an EPSG code or a
            PROJ4 string with no EPSG (e.g. a `+proj=nsper ...` perspective).
        extent: Output bounds `(min_x, min_y, max_x, max_y)` in `crs` units.
        width: Output width in pixels.
        height: Output height in pixels.
        method: Resampling method — one of `to_area`'s supported names
            (`"bilinear"` default, `"nearest"`, `"cubic"`, ...).

    Returns:
        A pyramids `Dataset` on exactly that grid — CRS `crs`, extent `extent`,
        shape `(bands, height, width)` — with band count, dtype and nodata
        preserved from `dataset`.

    Raises:
        ValueError: When `dataset` has no raster handle, `extent` is malformed,
            `width`/`height` are not whole positive pixel counts, `method` is
            unknown, or `crs` is a bool.
        RuntimeError: When the GDAL warp fails.

    Examples:
        - Warp a small WGS84 raster onto an exact 4x4 grid:
            ```python
            >>> import numpy as np
            >>> from pyramids.dataset import Dataset, GeoReference
            >>> from pyramids_eo.resample import to_area
            >>> src = Dataset.from_array(
            ...     np.ones((2, 2)),
            ...     geo_ref=GeoReference(top_left_corner=(0.0, 2.0), cell_size=1.0, epsg=4326),
            ... )
            >>> out = to_area(src, 4326, (0.0, 0.0, 2.0, 2.0), 4, 4)
            >>> out.read_array().shape
            (4, 4)

            ```
    """
    raster = getattr(dataset, "raster", None)
    if raster is None:
        raise ValueError(
            "to_area needs a georeferenced pyramids Dataset (with a raster "
            "handle); an ndarray has no grid to place."
        )
    if method not in _RESAMPLERS:
        raise ValueError(f"method must be one of {sorted(_RESAMPLERS)}; got {method!r}")
    if len(extent) != 4:
        raise ValueError(f"extent must be (min_x, min_y, max_x, max_y); got {extent!r}")
    min_x, min_y, max_x, max_y = (float(v) for v in extent)
    if not (min_x < max_x and min_y < max_y):
        raise ValueError(
            f"extent must have min_x < max_x and min_y < max_y; got {extent!r}"
        )
    if int(width) != width or int(height) != height:
        raise ValueError(
            f"width and height must be whole numbers of pixels; got {width}x{height}"
        )
    if width <= 0 or height <= 0:
        raise ValueError(f"width and height must be positive; got {width}x{height}")

    # An integer EPSG code must be a string GDAL's SRS parser accepts — including
    # a NumPy integer (e.g. an epsg looked up from an array), which is not a
    # Python `int`. A `bool` is also `Integral` but is never a real code, so
    # reject it rather than mapping `True` to "EPSG:1". `outputBounds` is left in
    # the target CRS (dstSRS), so no separate `-te_srs` is needed.
    if isinstance(crs, bool):
        raise ValueError(
            f"crs must be an EPSG code or CRS string, not a bool; got {crs!r}"
        )
    dst_srs = f"EPSG:{int(crs)}" if isinstance(crs, numbers.Integral) else str(crs)
    warp_kwargs: dict[str, Any] = {
        "format": "MEM",
        "outputBounds": [min_x, min_y, max_x, max_y],
        "dstSRS": dst_srs,
        "width": int(width),
        "height": int(height),
        "resampleAlg": _RESAMPLERS[method],
    }
    nodata = _warp_nodata(getattr(dataset, "no_data_value", None))
    if nodata is not None:
        warp_kwargs["srcNodata"] = nodata
        warp_kwargs["dstNodata"] = nodata

    out = gdal.Warp("", raster, **warp_kwargs)
    if out is None:
        raise RuntimeError(
            f"gdal.Warp failed for to_area: {gdal.GetLastErrorMsg() or 'no detail'}"
        )
    return Dataset(out)