Skip to content

API reference

geoproducts

The reader base class and stack. The contract is in Concepts.

geoproducts.ProductReader

Bases: ABC

ABC for product readers: each one a lazy geoarray.RasterSource.

Subclasses provide sensor-specific metadata and implement :meth:_read_window; the base class supplies the RasterSource surface (grid, shape, dtype, fill_value, attrs, read_window, load) and georeader's map-coordinate reads (read_from_bounds, read_from_center_coords), all returning a geoarray.GeoArray.

Examples:

Implement a file-backed product reader::

class Reader(ProductReader):
    def __init__(self, path): ...
    def _read_window(self, window: PixelWindow) -> np.ndarray: ...

Load a full scene into a GeoArray::

scene = Reader("scene.dat").load()  # (C, H, W)

Read a tile without changing the reader::

window = PixelWindow(col_off=0, row_off=0, width=256, height=256)
tile = Reader("scene.dat").read_window(window)  # (C, 256, 256)
Source code in packages/geotoolz-products/src/geoproducts/_src/base.py
class ProductReader(ABC):
    """ABC for product readers: each one a lazy `geoarray.RasterSource`.

    Subclasses provide sensor-specific metadata and implement
    :meth:`_read_window`; the base class supplies the `RasterSource`
    surface (``grid``, ``shape``, ``dtype``, ``fill_value``, ``attrs``,
    ``read_window``, ``load``) and georeader's map-coordinate reads
    (``read_from_bounds``, ``read_from_center_coords``), all returning a
    `geoarray.GeoArray`.

    Examples:
        Implement a file-backed product reader::

            class Reader(ProductReader):
                def __init__(self, path): ...
                def _read_window(self, window: PixelWindow) -> np.ndarray: ...

        Load a full scene into a ``GeoArray``::

            scene = Reader("scene.dat").load()  # (C, H, W)

        Read a tile without changing the reader::

            window = PixelWindow(col_off=0, row_off=0, width=256, height=256)
            tile = Reader("scene.dat").read_window(window)  # (C, 256, 256)
    """

    @abstractmethod
    def _read_window(self, window: PixelWindow) -> np.ndarray:
        """Read a sensor-native pixel window into a numpy array.

        Implementations receive windows clipped to the grid when
        ``boundless=False`` and may receive windows partly or wholly
        outside it when ``boundless=True`` (:meth:`_read_boundless`
        handles both).
        """

    @property
    @abstractmethod
    def _crs(self) -> Any:
        """Reader CRS (anything `geoarray.as_crs` accepts)."""

    @property
    @abstractmethod
    def _transform(self) -> Affine:
        """Reader affine transform."""

    @property
    @abstractmethod
    def _shape(self) -> tuple[int, ...]:
        """Reader array shape as ``(..., height, width)``."""

    @property
    @abstractmethod
    def _dtype(self) -> Any:
        """Reader array dtype."""

    @property
    @abstractmethod
    def _bands(self) -> Sequence[str]:
        """Band names in array order."""

    @property
    @abstractmethod
    def _fill_value(self) -> Any:
        """Fill value for nodata and out-of-grid pixels."""

    @property
    @abstractmethod
    def _track(self) -> Track:
        """Track A for clean affine grids, Track B for irregular geolocation."""

    # -- RasterSource metadata ---------------------------------------------

    @cached_property
    def grid(self) -> Grid:
        """The pixel grid: transform, CRS and ``(H, W)``."""
        return Grid.from_affine(self._transform, self._crs, self._shape[-2:])

    @property
    def crs(self) -> pyproj.CRS | None:
        """Reader CRS (``grid.crs``)."""
        return self.grid.crs

    @property
    def transform(self) -> Affine:
        """Affine transform of the grid (``grid.affine``), for Track A readers."""
        return self.grid.affine

    @property
    def res(self) -> tuple[float, float]:
        """Pixel size ``(x, y)`` in CRS units (``grid.res``)."""
        return self.grid.res

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """``(minx, miny, maxx, maxy)`` of the grid (``grid.bounds``)."""
        return self.grid.bounds

    @property
    def shape(self) -> tuple[int, ...]:
        """Array shape as ``(..., height, width)``."""
        return tuple(self._shape)

    @property
    def width(self) -> int:
        """Grid width in pixels."""
        return int(self.shape[-1])

    @property
    def height(self) -> int:
        """Grid height in pixels."""
        return int(self.shape[-2])

    @property
    def dtype(self) -> np.dtype:
        """Numpy dtype read by this reader."""
        return np.dtype(self._dtype)

    @property
    def dims(self) -> tuple[str, ...]:
        """Dimension names, as `geoarray.GeoArray.dims`.

        ``("time", "band", "y", "x")[-ndim:]`` — i.e. ``("y", "x")`` for 2-D,
        ``("band", "y", "x")`` for 3-D and ``("time", "band", "y", "x")``
        for 4-D readers.

        Raises:
            ValueError: If the reader shape is not 2-D, 3-D or 4-D.
        """
        ndim = len(self.shape)
        if ndim not in (2, 3, 4):
            raise ValueError(
                f"ProductReader expects a 2d-4d array shape; got {self.shape}."
            )
        return ("time", "band", "y", "x")[-ndim:]

    @property
    def bands(self) -> tuple[str, ...]:
        """Band names in array order."""
        return tuple(self._bands)

    @property
    def fill_value(self) -> Any:
        """Fill value of nodata and out-of-grid pixels."""
        return self._fill_value

    @property
    def track(self) -> Track:
        """Reader track classification."""
        return self._track

    @property
    def attrs(self) -> FrozenAttrs:
        """Metadata every read carries: ``band_names`` plus :meth:`_band_attrs`."""
        # `band_names` is the canonical key every band resolver reads first
        # (see geoops._src.bands.DEFAULT_BAND_KEYS).
        return FrozenAttrs({"band_names": self.bands, **self._band_attrs()})

    @property
    def coords(self) -> tuple[Any, ...]:
        """The coordinates every read carries: a `SpectralAxis` on ``band``.

        Its names are `bands` and its centre wavelengths the ``wavelengths``
        of :meth:`_band_attrs` (nm, one per band) when the reader declares
        them; ``()`` for a reader without a ``band`` dim or whose band names
        are not one unique name per band.

        Example:
            >>> import numpy as np
            >>> from geoproducts.toy_sensor import Reader
            >>> Reader("scene", data=np.zeros((4, 2, 2))).coords[0].names
            ('blue', 'green', 'red', 'nir')
        """
        dims = self.dims
        if "band" not in dims:
            return ()
        size = self.shape[dims.index("band")]
        names = tuple(str(name) for name in self.bands)
        if len(names) != size or len(set(names)) != size:
            return ()
        wavelengths = self._band_attrs().get("wavelengths")
        if wavelengths is None or len(wavelengths) != size:
            return (SpectralAxis(names),)
        return (SpectralAxis(names, tuple(float(w) for w in wavelengths)),)

    def _band_attrs(self) -> dict[str, Any]:
        """Extra ``attrs`` every read carries (per-band ``units``, ``wavelengths``, …).

        ``band_names`` is always set; readers override this to add more.
        """
        return {}

    # -- RasterSource reads ------------------------------------------------

    def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
        """Read a pixel window as a ``GeoArray`` on the window's grid.

        Args:
            window: The pixels to read; may extend past the grid.
            boundless: ``True`` returns exactly ``window.shape``, filled with
                `fill_value` outside the grid; ``False`` returns only the
                part inside.

        Returns:
            ``(..., h, w)`` carrier whose ``attrs`` are :attr:`attrs`.

        Raises:
            TypeError: ``window`` is not a `geoarray.PixelWindow` (convert a
                rasterio ``Window`` with
                ``PixelWindow(col_off=..., row_off=..., width=..., height=...)``).
            ValueError: ``boundless=False`` and the window misses the grid.
        """
        if not isinstance(window, PixelWindow):
            raise TypeError(
                f"{type(self).__name__}.read_window takes a geoarray.PixelWindow, "
                f"got {type(window).__name__}; build one with PixelWindow("
                "col_off=..., row_off=..., width=..., height=...)"
            )
        if not boundless:
            whole = PixelWindow(
                col_off=0, row_off=0, width=self.width, height=self.height
            )
            inside = window.intersection(whole)
            if inside is None:
                raise ValueError(
                    f"window {window} does not overlap the grid "
                    f"{(self.height, self.width)}"
                )
            window = inside
        values = self._read_window(window)
        return GeoArray(
            values,
            self.grid.crop(window).transform,
            self.grid.crs,
            fill_value=self.fill_value,
            attrs=self.attrs,
            dims=self.dims,
            coords=self.coords,
        )

    def load(self) -> GeoArray:
        """Load the reader's full extent into a ``GeoArray`` of `shape`."""
        return self.read_window(
            PixelWindow(col_off=0, row_off=0, width=self.width, height=self.height)
        )

    def read_from_bounds(
        self,
        bounds: tuple[float, float, float, float],
        *,
        boundless: bool = True,
        crs_bounds: Any = None,
    ) -> GeoArray:
        """Read map-coordinate bounds as a ``GeoArray``.

        georeader's :func:`georeader.read.read_from_bounds` computes the
        window (outward rounding, CRS transform of ``bounds``), so the
        window maths match georeader exactly; the pixels come from
        :meth:`read_window`.
        """
        from geoarray.interop.georeader import from_georeader, source_to_georeader
        from georeader import read

        return from_georeader(
            read.read_from_bounds(
                source_to_georeader(self),
                bounds,
                crs_bounds=crs_bounds,
                boundless=boundless,
            )
        )

    def read_from_center_coords(
        self,
        x: float,
        y: float,
        width: int,
        height: int,
        *,
        boundless: bool = True,
        crs_center_coords: Any = None,
    ) -> GeoArray:
        """Read a ``height x width`` window centered on map coordinates.

        georeader's :func:`georeader.read.read_from_center_coords` places
        the window, so the placement matches georeader exactly; the pixels
        come from :meth:`read_window`.
        """
        from geoarray.interop.georeader import from_georeader, source_to_georeader
        from georeader import read

        return from_georeader(
            read.read_from_center_coords(
                source_to_georeader(self),
                (x, y),
                (height, width),
                crs_center_coords=crs_center_coords,
                boundless=boundless,
            )
        )

    def _read_boundless(
        self, window: PixelWindow, read: Callable[[slice, slice], np.ndarray]
    ) -> np.ndarray:
        """Read ``window`` through ``read``, padding outside the grid with the fill.

        The shared body of a ``_read_window``: allocates the output filled
        with `fill_value`, asks ``read(rows, cols)`` only for the part of
        the window inside the grid (returning ``(..., h, w)``), and pastes
        it in place. Windows partly or wholly outside the grid (boundless
        reads) are handled here once for every reader.

        Args:
            window: Pixel window, possibly extending past the grid.
            read: Reads the in-grid ``rows`` / ``cols`` slices of every band.

        Returns:
            ``(..., window.height, window.width)`` array of ``self.dtype``.
        """
        row0, col0 = window.row_off, window.col_off
        n_rows, n_cols = window.height, window.width
        out = np.full(
            (*self.shape[:-2], n_rows, n_cols), self.fill_value, dtype=self.dtype
        )
        r_start, r_stop = max(row0, 0), min(row0 + n_rows, self.height)
        c_start, c_stop = max(col0, 0), min(col0 + n_cols, self.width)
        if r_start >= r_stop or c_start >= c_stop:
            return out
        out[..., r_start - row0 : r_stop - row0, c_start - col0 : c_stop - col0] = read(
            slice(r_start, r_stop), slice(c_start, c_stop)
        )
        return out

attrs property

Metadata every read carries: band_names plus :meth:_band_attrs.

bands property

Band names in array order.

bounds property

(minx, miny, maxx, maxy) of the grid (grid.bounds).

coords property

The coordinates every read carries: a SpectralAxis on band.

Its names are bands and its centre wavelengths the wavelengths of :meth:_band_attrs (nm, one per band) when the reader declares them; () for a reader without a band dim or whose band names are not one unique name per band.

Example

import numpy as np from geoproducts.toy_sensor import Reader Reader("scene", data=np.zeros((4, 2, 2))).coords[0].names ('blue', 'green', 'red', 'nir')

crs property

Reader CRS (grid.crs).

dims property

Dimension names, as geoarray.GeoArray.dims.

("time", "band", "y", "x")[-ndim:] — i.e. ("y", "x") for 2-D, ("band", "y", "x") for 3-D and ("time", "band", "y", "x") for 4-D readers.

Raises:

Type Description
ValueError

If the reader shape is not 2-D, 3-D or 4-D.

dtype property

Numpy dtype read by this reader.

fill_value property

Fill value of nodata and out-of-grid pixels.

grid cached property

The pixel grid: transform, CRS and (H, W).

height property

Grid height in pixels.

res property

Pixel size (x, y) in CRS units (grid.res).

shape property

Array shape as (..., height, width).

track property

Reader track classification.

transform property

Affine transform of the grid (grid.affine), for Track A readers.

width property

Grid width in pixels.

load()

Load the reader's full extent into a GeoArray of shape.

Source code in packages/geotoolz-products/src/geoproducts/_src/base.py
def load(self) -> GeoArray:
    """Load the reader's full extent into a ``GeoArray`` of `shape`."""
    return self.read_window(
        PixelWindow(col_off=0, row_off=0, width=self.width, height=self.height)
    )

read_from_bounds(bounds, *, boundless=True, crs_bounds=None)

Read map-coordinate bounds as a GeoArray.

georeader's :func:georeader.read.read_from_bounds computes the window (outward rounding, CRS transform of bounds), so the window maths match georeader exactly; the pixels come from :meth:read_window.

Source code in packages/geotoolz-products/src/geoproducts/_src/base.py
def read_from_bounds(
    self,
    bounds: tuple[float, float, float, float],
    *,
    boundless: bool = True,
    crs_bounds: Any = None,
) -> GeoArray:
    """Read map-coordinate bounds as a ``GeoArray``.

    georeader's :func:`georeader.read.read_from_bounds` computes the
    window (outward rounding, CRS transform of ``bounds``), so the
    window maths match georeader exactly; the pixels come from
    :meth:`read_window`.
    """
    from geoarray.interop.georeader import from_georeader, source_to_georeader
    from georeader import read

    return from_georeader(
        read.read_from_bounds(
            source_to_georeader(self),
            bounds,
            crs_bounds=crs_bounds,
            boundless=boundless,
        )
    )

read_from_center_coords(x, y, width, height, *, boundless=True, crs_center_coords=None)

Read a height x width window centered on map coordinates.

georeader's :func:georeader.read.read_from_center_coords places the window, so the placement matches georeader exactly; the pixels come from :meth:read_window.

Source code in packages/geotoolz-products/src/geoproducts/_src/base.py
def read_from_center_coords(
    self,
    x: float,
    y: float,
    width: int,
    height: int,
    *,
    boundless: bool = True,
    crs_center_coords: Any = None,
) -> GeoArray:
    """Read a ``height x width`` window centered on map coordinates.

    georeader's :func:`georeader.read.read_from_center_coords` places
    the window, so the placement matches georeader exactly; the pixels
    come from :meth:`read_window`.
    """
    from geoarray.interop.georeader import from_georeader, source_to_georeader
    from georeader import read

    return from_georeader(
        read.read_from_center_coords(
            source_to_georeader(self),
            (x, y),
            (height, width),
            crs_center_coords=crs_center_coords,
            boundless=boundless,
        )
    )

read_window(window, *, boundless=True)

Read a pixel window as a GeoArray on the window's grid.

Parameters:

Name Type Description Default
window PixelWindow

The pixels to read; may extend past the grid.

required
boundless bool

True returns exactly window.shape, filled with fill_value outside the grid; False returns only the part inside.

True

Returns:

Type Description
``(..., h, w)`` carrier whose ``attrs`` are

attr:attrs.

Raises:

Type Description
TypeError

window is not a geoarray.PixelWindow (convert a rasterio Window with PixelWindow(col_off=..., row_off=..., width=..., height=...)).

ValueError

boundless=False and the window misses the grid.

Source code in packages/geotoolz-products/src/geoproducts/_src/base.py
def read_window(self, window: PixelWindow, *, boundless: bool = True) -> GeoArray:
    """Read a pixel window as a ``GeoArray`` on the window's grid.

    Args:
        window: The pixels to read; may extend past the grid.
        boundless: ``True`` returns exactly ``window.shape``, filled with
            `fill_value` outside the grid; ``False`` returns only the
            part inside.

    Returns:
        ``(..., h, w)`` carrier whose ``attrs`` are :attr:`attrs`.

    Raises:
        TypeError: ``window`` is not a `geoarray.PixelWindow` (convert a
            rasterio ``Window`` with
            ``PixelWindow(col_off=..., row_off=..., width=..., height=...)``).
        ValueError: ``boundless=False`` and the window misses the grid.
    """
    if not isinstance(window, PixelWindow):
        raise TypeError(
            f"{type(self).__name__}.read_window takes a geoarray.PixelWindow, "
            f"got {type(window).__name__}; build one with PixelWindow("
            "col_off=..., row_off=..., width=..., height=...)"
        )
    if not boundless:
        whole = PixelWindow(
            col_off=0, row_off=0, width=self.width, height=self.height
        )
        inside = window.intersection(whole)
        if inside is None:
            raise ValueError(
                f"window {window} does not overlap the grid "
                f"{(self.height, self.width)}"
            )
        window = inside
    values = self._read_window(window)
    return GeoArray(
        values,
        self.grid.crop(window).transform,
        self.grid.crs,
        fill_value=self.fill_value,
        attrs=self.attrs,
        dims=self.dims,
        coords=self.coords,
    )

geoproducts.stack(readers, *, bounds=None, crs_bounds=None, like=0, resampling=None)

Stack readers' bands on the grid of readers[like].

The reference reader is read over bounds (or loaded whole); every other reader is read only where it overlaps that grid and warped onto it. The bands are concatenated in reader order, with their band_names (and units / wavelengths when every reader carries them).

Parameters:

Name Type Description Default
readers Sequence[RasterSource]

Readers to stack: any geoarray.RasterSource — a ProductReader (goes.Reader, goes.L2Reader, …), a geocloud.cog.CogSource or a loaded GeoArray.

required
bounds tuple[float, float, float, float] | None

(minx, miny, maxx, maxy) area to read. Default: the reference reader's whole extent.

None
crs_bounds Any

CRS of bounds, e.g. "EPSG:4326". Default: the reference reader's CRS.

None
like int

Index of the reference reader whose grid the output takes.

0
resampling str | None

A rasterio resampling name for every warp. Default: chosen per reader — "average" from a finer float grid, "bilinear" from a coarser one, "mode" / "nearest" for integer (mask / class) readers.

None

Returns:

Type Description
GeoArray

A (sum of bands, H, W) GeoArray on the reference grid. It

GeoArray

keeps an integer dtype when every reader shares one integer dtype

GeoArray

and fill; otherwise it is float32 with NaN fill, and every

GeoArray

reader's nodata pixels (its own fill, integer or float such as

GeoArray

-9999.0, and non-finite values) become NaN.

Raises:

Type Description
TypeError

A reader is a georeader GeoTensor / GeoData (convert it with geoarray.interop.georeader.from_georeader / source_from_georeader) or not a geoarray.RasterSource.

ValueError

readers is empty or like is out of range.

Examples:

True-colour inputs at 1 km, from three L1b files::

blue, red, veggie = (goes.Reader(p, calibration="reflectance")
                     for p in (c01_path, c02_path, c03_path))
rgb_in = geoproducts.stack([blue, red, veggie], bounds=aoi,
                           crs_bounds="EPSG:4326")  # (3, h, w)
Source code in packages/geotoolz-products/src/geoproducts/_src/stack.py
def stack(
    readers: Sequence[RasterSource],
    *,
    bounds: tuple[float, float, float, float] | None = None,
    crs_bounds: Any = None,
    like: int = 0,
    resampling: str | None = None,
) -> GeoArray:
    """Stack readers' bands on the grid of ``readers[like]``.

    The reference reader is read over ``bounds`` (or loaded whole); every
    other reader is read only where it overlaps that grid and warped onto
    it. The bands are concatenated in reader order, with their
    ``band_names`` (and ``units`` / ``wavelengths`` when every reader
    carries them).

    Args:
        readers: Readers to stack: any `geoarray.RasterSource` — a
            ``ProductReader`` (``goes.Reader``, ``goes.L2Reader``, …), a
            ``geocloud.cog.CogSource`` or a loaded ``GeoArray``.
        bounds: ``(minx, miny, maxx, maxy)`` area to read. Default: the
            reference reader's whole extent.
        crs_bounds: CRS of ``bounds``, e.g. ``"EPSG:4326"``. Default: the
            reference reader's CRS.
        like: Index of the reference reader whose grid the output takes.
        resampling: A rasterio resampling name for every warp. Default:
            chosen per reader — ``"average"`` from a finer float grid,
            ``"bilinear"`` from a coarser one, ``"mode"`` / ``"nearest"``
            for integer (mask / class) readers.

    Returns:
        A ``(sum of bands, H, W)`` ``GeoArray`` on the reference grid. It
        keeps an integer dtype when every reader shares one integer dtype
        and fill; otherwise it is ``float32`` with ``NaN`` fill, and every
        reader's nodata pixels (its own fill, integer or float such as
        ``-9999.0``, and non-finite values) become ``NaN``.

    Raises:
        TypeError: A reader is a georeader ``GeoTensor`` / ``GeoData``
            (convert it with ``geoarray.interop.georeader.from_georeader`` /
            ``source_from_georeader``) or not a `geoarray.RasterSource`.
        ValueError: ``readers`` is empty or ``like`` is out of range.

    Examples:
        True-colour inputs at 1 km, from three L1b files::

            blue, red, veggie = (goes.Reader(p, calibration="reflectance")
                                 for p in (c01_path, c02_path, c03_path))
            rgb_in = geoproducts.stack([blue, red, veggie], bounds=aoi,
                                       crs_bounds="EPSG:4326")  # (3, h, w)
    """
    if not readers:
        raise ValueError("stack needs at least one reader.")
    for reader in readers:
        require_source(reader, "geoproducts.stack")
    if not 0 <= like < len(readers):
        raise ValueError(f"like={like} is out of range for {len(readers)} readers.")
    from geoarray.interop.georeader import (
        from_georeader,
        source_to_georeader,
        to_georeader,
    )
    from georeader import read

    reference = readers[like]
    if bounds is None:
        ref = reference.load()
    else:
        ref = from_georeader(
            read.read_from_bounds(
                source_to_georeader(reference), bounds, crs_bounds=crs_bounds
            )
        )
    ref_res = abs(ref.grid.affine.a)
    ref_engine = to_georeader(ref)
    parts: list[GeoArray] = []
    for i, reader in enumerate(readers):
        if i == like:
            parts.append(ref)
            continue
        method = resampling or _auto_resampling(reader, ref_res)
        warped = read.read_reproject_like(
            source_to_georeader(reader), ref_engine, resampling=Resampling[method]
        )
        parts.append(from_georeader(warped))
    return _concatenate(ref, parts, [r.attrs for r in readers], list(readers))

geoproducts.toy_sensor

The in-memory reference readers: Reader on an affine grid, and SwathReader, the same bands in sensor geometry (a geoarray.GeoSwath).

geoproducts.toy_sensor.Reader

Bases: ProductReader

Toy reference reader implementing the sensor-reader contract.

Parameters:

Name Type Description Default
path str | Path

Scene path recorded for auditability.

required
data ndarray | None

Optional in-memory array in (band, y, x) order.

None
transform Affine | None

Affine transform for the synthetic grid.

None
crs Any

Coordinate reference system.

'EPSG:4326'
fill_value float | None

Fill value used for boundless reads. None (default) picks NaN for floating-point data and 0 for integer / boolean data.

None

Raises:

Type Description
TypeError

data is a georeader GeoTensor (pass np.asarray(gt), or keep its georeferencing with transform= / crs=).

ValueError

If fill_value is not exactly representable in the data dtype (e.g. NaN or 1.5 with integer data, or a value outside the integer range).

Examples:

>>> import numpy as np
>>> from geoproducts.toy_sensor import Reader
>>> reader = Reader("scene", data=np.zeros((4, 8, 8), dtype="float32"))
>>> reader.load().shape  # (C, H, W)
(4, 8, 8)
Source code in packages/geotoolz-products/src/geoproducts/toy_sensor/reader.py
class Reader(ProductReader):
    """Toy reference reader implementing the sensor-reader contract.

    Args:
        path: Scene path recorded for auditability.
        data: Optional in-memory array in ``(band, y, x)`` order.
        transform: Affine transform for the synthetic grid.
        crs: Coordinate reference system.
        fill_value: Fill value used for boundless reads. ``None``
            (default) picks ``NaN`` for floating-point data and ``0`` for
            integer / boolean data.

    Raises:
        TypeError: ``data`` is a georeader ``GeoTensor`` (pass
            ``np.asarray(gt)``, or keep its georeferencing with
            ``transform=`` / ``crs=``).
        ValueError: If ``fill_value`` is not exactly representable
            in the data dtype (e.g. ``NaN`` or ``1.5`` with integer data,
            or a value outside the integer range).

    Examples:
        >>> import numpy as np
        >>> from geoproducts.toy_sensor import Reader
        >>> reader = Reader("scene", data=np.zeros((4, 8, 8), dtype="float32"))
        >>> reader.load().shape  # (C, H, W)
        (4, 8, 8)
    """

    def __init__(
        self,
        path: str | Path,
        *,
        data: np.ndarray | None = None,
        transform: Affine | None = None,
        crs: Any = "EPSG:4326",
        fill_value: float | None = None,
    ) -> None:
        reject_georeader(data, "toy_sensor.Reader(data=...)")
        self.path = Path(path)
        self._data = (
            np.zeros((_DEFAULT_NUM_BANDS, 1, 1), dtype=np.float32)
            if data is None
            else np.asarray(data)
        )
        if self._data.ndim != 3:
            raise ValueError(
                "toy_sensor.Reader expects ``data`` with shape (bands, y, x); "
                f"got ndim={self._data.ndim} (shape={self._data.shape})."
            )
        if self._data.shape[0] != _DEFAULT_NUM_BANDS:
            raise ValueError(
                "toy_sensor.Reader has a fixed 4-band layout "
                "(blue, green, red, nir); "
                f"got {self._data.shape[0]} bands (shape={self._data.shape})."
            )
        self._reader_transform = Affine.identity() if transform is None else transform
        self._reader_crs = crs
        self._reader_fill = resolve_fill_value(
            fill_value, self._data.dtype, owner="toy_sensor.Reader"
        )

    @property
    def _crs(self) -> Any:
        return self._reader_crs

    @property
    def _transform(self) -> Affine:
        return self._reader_transform

    @property
    def _shape(self) -> tuple[int, ...]:
        return self._data.shape

    @property
    def _dtype(self) -> Any:
        return self._data.dtype

    @property
    def _bands(self) -> tuple[str, ...]:
        return (
            constants.BAND_BLUE,
            constants.BAND_GREEN,
            constants.BAND_RED,
            constants.BAND_NIR,
        )

    @property
    def _fill_value(self) -> float | int | bool:
        return self._reader_fill

    def _band_attrs(self) -> dict[str, Any]:
        # centre wavelengths (nm) from the band table, in band order
        return {
            "wavelengths": band_values(constants.BANDS, self._bands, "wavelength_nm")
        }

    @property
    def _track(self) -> Track:
        return "A"

    def _read_window(self, window: PixelWindow) -> np.ndarray:
        return self._read_boundless(
            window, lambda rows, cols: self._data[..., rows, cols]
        )

geoproducts.toy_sensor.SwathReader

The toy sensor's four bands in sensor geometry, read as a GeoSwath.

Parameters:

Name Type Description Default
path str | Path

Scene path recorded for auditability.

required
data Any

(band, row, col) values, 4 bands (blue, green, red, nir).

required
lat Any

(row, col) pixel-centre latitudes, degrees.

required
lon Any

(row, col) pixel-centre longitudes, degrees.

required
fill_value float | None

Nodata marker; None picks NaN for float data and 0 for integer / boolean data.

None

Raises:

Type Description
TypeError

data is a georeader GeoTensor.

ValueError

data is not (4, row, col), or lat / lon are not (row, col).

Example

import numpy as np rows, cols = np.linspace(40, 41, 3), np.linspace(-1, 0, 5) lat, lon = np.meshgrid(rows, cols, indexing="ij") reader = SwathReader("granule", data=np.zeros((4, 3, 5)), lat=lat, lon=lon) swath = reader.load() swath.dims, swath.lat.shape (('band', 'row', 'col'), (3, 5))

Source code in packages/geotoolz-products/src/geoproducts/toy_sensor/swath.py
class SwathReader:
    """The toy sensor's four bands in sensor geometry, read as a `GeoSwath`.

    Args:
        path: Scene path recorded for auditability.
        data: ``(band, row, col)`` values, 4 bands (blue, green, red, nir).
        lat: ``(row, col)`` pixel-centre latitudes, degrees.
        lon: ``(row, col)`` pixel-centre longitudes, degrees.
        fill_value: Nodata marker; ``None`` picks ``NaN`` for float data and
            ``0`` for integer / boolean data.

    Raises:
        TypeError: ``data`` is a georeader ``GeoTensor``.
        ValueError: ``data`` is not ``(4, row, col)``, or ``lat`` / ``lon``
            are not ``(row, col)``.

    Example:
        >>> import numpy as np
        >>> rows, cols = np.linspace(40, 41, 3), np.linspace(-1, 0, 5)
        >>> lat, lon = np.meshgrid(rows, cols, indexing="ij")
        >>> reader = SwathReader("granule", data=np.zeros((4, 3, 5)), lat=lat, lon=lon)
        >>> swath = reader.load()
        >>> swath.dims, swath.lat.shape
        (('band', 'row', 'col'), (3, 5))
    """

    dims = ("band", "row", "col")

    def __init__(
        self,
        path: str | Path,
        *,
        data: Any,
        lat: Any,
        lon: Any,
        fill_value: float | None = None,
    ) -> None:
        reject_georeader(data, "toy_sensor.SwathReader(data=...)")
        self.path = Path(path)
        self._data = np.asarray(data)
        self._lat = np.asarray(lat, dtype=np.float64)
        self._lon = np.asarray(lon, dtype=np.float64)
        if self._data.ndim != 3 or self._data.shape[0] != len(_BANDS):
            raise ValueError(
                "toy_sensor.SwathReader expects data (4, row, col) "
                f"(blue, green, red, nir); got shape {self._data.shape}."
            )
        if (
            self._lat.shape != self._data.shape[1:]
            or self._lon.shape != self._lat.shape
        ):
            raise ValueError(
                f"lat {self._lat.shape} and lon {self._lon.shape} must be "
                f"(row, col) = {self._data.shape[1:]}."
            )
        self._fill = resolve_fill_value(
            fill_value, self._data.dtype, owner="toy_sensor.SwathReader"
        )

    @property
    def bands(self) -> tuple[str, ...]:
        """Band names in array order."""
        return _BANDS

    @property
    def shape(self) -> tuple[int, ...]:
        """``(band, row, col)``."""
        return tuple(self._data.shape)

    @property
    def coords(self) -> tuple[SpectralAxis, ...]:
        """The band names and centre wavelengths (nm)."""
        wavelengths = band_values(constants.BANDS, _BANDS, "wavelength_nm")
        return (SpectralAxis(_BANDS, wavelengths),)

    def load(self) -> GeoSwath:
        """The whole granule."""
        return self._swath(slice(None), slice(None))

    def read_window(self, window: PixelWindow) -> GeoSwath:
        """The rows and columns of ``window``, clipped to the granule.

        Raises:
            ValueError: ``window`` misses the granule.
        """
        rows, cols = self._data.shape[1:]
        whole = PixelWindow(col_off=0, row_off=0, width=cols, height=rows)
        inside = window.intersection(whole)
        if inside is None:
            raise ValueError(f"window {window} misses the granule {(rows, cols)}")
        return self._swath(*inside.to_slices())

    def _swath(self, rows: slice, cols: slice) -> GeoSwath:
        return GeoSwath(
            self._data[:, rows, cols],
            self._lat[rows, cols],
            self._lon[rows, cols],
            dims=self.dims,
            coords=self.coords,
            fill_value=self._fill,
            attrs={"path": str(self.path)},
        )

bands property

Band names in array order.

coords property

The band names and centre wavelengths (nm).

shape property

(band, row, col).

load()

The whole granule.

Source code in packages/geotoolz-products/src/geoproducts/toy_sensor/swath.py
def load(self) -> GeoSwath:
    """The whole granule."""
    return self._swath(slice(None), slice(None))

read_window(window)

The rows and columns of window, clipped to the granule.

Raises:

Type Description
ValueError

window misses the granule.

Source code in packages/geotoolz-products/src/geoproducts/toy_sensor/swath.py
def read_window(self, window: PixelWindow) -> GeoSwath:
    """The rows and columns of ``window``, clipped to the granule.

    Raises:
        ValueError: ``window`` misses the granule.
    """
    rows, cols = self._data.shape[1:]
    whole = PixelWindow(col_off=0, row_off=0, width=cols, height=rows)
    inside = window.intersection(whole)
    if inside is None:
        raise ValueError(f"window {window} misses the granule {(rows, cols)}")
    return self._swath(*inside.to_slices())

geoproducts.toy_sensor.NDVI()

Return a toy-sensor NDVI operator configured with the reference band names.

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/toy_sensor/presets.py
def NDVI() -> Operator:
    """Return a toy-sensor NDVI operator configured with the reference band names.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    indices = require("geoops.indices", "toy_sensor.presets.NDVI", "operators")
    return indices.NDVI(red=constants.BAND_RED, nir=constants.BAND_NIR)

geoproducts.goes

GOES-R ABI L1b and L2 readers, NOAA bucket helpers, recipes and presets (guide).

geoproducts.goes.l1b

GOES-R ABI L1b radiance reader.

One L1b file (OR_ABI-L1b-Rad{F,C,M1,M2}-M6Cnn_Gnn_s..._e..._c....nc) holds one channel of one scan on the geostationary fixed grid. The reader calibrates with the coefficients stored in that same file: kappa0 for reflectance and the planck_* set for brightness temperature.

QualityReader

Bases: ABIFile

The DQF data-quality flags of an ABI file, as unsigned integers.

For L1b files the values follow :data:geoproducts.goes.constants.DQF_FLAGS (0 good, 1 conditionally usable, 2 out of range, 3 no value, 4 focal-plane temperature exceeded); 255 marks pixels with no flag and reads outside the file's extent. L2 products define their own meanings: read them with :meth:flags. Usually reached through Reader.quality / L2Reader.quality.

Parameters:

Name Type Description Default
source Source

Path to an ABI .nc file, or a binary file-like object.

required
variables tuple[str, ...]

Quality variables to read, one band each. Default ("DQF",).

('DQF',)

Raises:

Type Description
ImportError

h5py is not installed (the [goes] extra).

ValueError

source is not an ABI file or lacks a variable.

Source code in packages/geotoolz-products/src/geoproducts/goes/l1b.py
class QualityReader(ABIFile):
    """The ``DQF`` data-quality flags of an ABI file, as unsigned integers.

    For L1b files the values follow :data:`geoproducts.goes.constants.DQF_FLAGS`
    (``0`` good, ``1`` conditionally usable, ``2`` out of range, ``3`` no
    value, ``4`` focal-plane temperature exceeded); ``255`` marks pixels with
    no flag and reads outside the file's extent. L2 products define their
    own meanings: read them with :meth:`flags`. Usually reached through
    ``Reader.quality`` / ``L2Reader.quality``.

    Args:
        source: Path to an ABI ``.nc`` file, or a binary file-like object.
        variables: Quality variables to read, one band each. Default
            ``("DQF",)``.

    Raises:
        ImportError: ``h5py`` is not installed (the ``[goes]`` extra).
        ValueError: ``source`` is not an ABI file or lacks a variable.
    """

    def __init__(
        self, source: Source, *, variables: tuple[str, ...] = ("DQF",)
    ) -> None:
        self._init_file(source, variables)

    @classmethod
    def _sharing(
        cls, reader: ABIFile, variables: tuple[str, ...] = ("DQF",)
    ) -> QualityReader:
        """A quality reader on ``reader``'s file, reusing its parsed grid."""
        out = cls.__new__(cls)
        out._share(reader, variables)
        return out

    def __repr__(self) -> str:
        return f"goes.QualityReader({self._describe()!r}, variables={self.variables})"

    @property
    def _bands(self) -> tuple[str, ...]:
        return self.variables

Reader

Bases: ABIFile

GOES-R ABI L1b radiance reader (one channel, one scan).

The grid is the file's +proj=geos fixed grid; load / read_window / read_from_bounds return a (1, H, W) GeoArray whose band is named after the channel ("C13"). Off-Earth-disk and missing pixels hold the fill: NaN for every calibrated output, the file's own count fill for "counts".

Calibration uses the coefficients carried by the file itself:

  • "counts" — the raw unsigned detector counts (uint16).
  • "radiance" — counts * scale_factor + add_offset in the file's units (W m-2 sr-1 um-1 for C01-C06, mW m-2 sr-1 (cm-1)-1 for C07-C16).
  • "reflectance" — kappa0 * radiance, the ABI reflectance factor (C01-C06 only; not divided by the cosine of the solar zenith).
  • "brightness_temperature" — (fk2 / ln(fk1 / L + 1) - bc1) / bc2 in Kelvin (C07-C16 only).

Parameters:

Name Type Description Default
source Source

An L1b .nc file: a local path, any URI geotoolz-cloud reads (s3://noaa-goes19/...; register anonymous access with geocloud.credentials.set_credentials), read with ranged requests, or an open binary file-like object (not safe to read from several threads).

required
calibration Calibration

Output quantity; see above. Default "radiance".

'radiance'

Raises:

Type Description
ImportError

h5py is not installed (the [goes] extra).

ValueError

source is not an ABI L1b radiance file, or calibration is unknown or does not apply to the channel.

Examples:

Brightness temperature of one CONUS C13 scan::

reader = goes.Reader(path, calibration="brightness_temperature")
reader.channel, reader.shape  # ('C13', (1, 1500, 2500))
window = PixelWindow(col_off=0, row_off=0, width=512, height=512)
bt = reader.read_window(window)  # (1, 512, 512) float32 K
Source code in packages/geotoolz-products/src/geoproducts/goes/l1b.py
class Reader(ABIFile):
    """GOES-R ABI L1b radiance reader (one channel, one scan).

    The grid is the file's ``+proj=geos`` fixed grid; ``load`` /
    ``read_window`` / ``read_from_bounds`` return a ``(1, H, W)``
    ``GeoArray`` whose band is named after the channel (``"C13"``).
    Off-Earth-disk and missing pixels hold the fill: ``NaN`` for every
    calibrated output, the file's own count fill for ``"counts"``.

    Calibration uses the coefficients carried by the file itself:

    - ``"counts"`` — the raw unsigned detector counts (``uint16``).
    - ``"radiance"`` — ``counts * scale_factor + add_offset`` in the
      file's units (``W m-2 sr-1 um-1`` for C01-C06,
      ``mW m-2 sr-1 (cm-1)-1`` for C07-C16).
    - ``"reflectance"`` — ``kappa0 * radiance``, the ABI reflectance
      factor (C01-C06 only; not divided by the cosine of the solar zenith).
    - ``"brightness_temperature"`` — ``(fk2 / ln(fk1 / L + 1) - bc1) / bc2``
      in Kelvin (C07-C16 only).

    Args:
        source: An L1b ``.nc`` file: a local path, any URI geotoolz-cloud
            reads (``s3://noaa-goes19/...``; register anonymous access with
            ``geocloud.credentials.set_credentials``), read with ranged
            requests, or an open binary file-like object (not safe to read
            from several threads).
        calibration: Output quantity; see above. Default ``"radiance"``.

    Raises:
        ImportError: ``h5py`` is not installed (the ``[goes]`` extra).
        ValueError: ``source`` is not an ABI L1b radiance file, or
            ``calibration`` is unknown or does not apply to the channel.

    Examples:
        Brightness temperature of one CONUS C13 scan::

            reader = goes.Reader(path, calibration="brightness_temperature")
            reader.channel, reader.shape  # ('C13', (1, 1500, 2500))
            window = PixelWindow(col_off=0, row_off=0, width=512, height=512)
            bt = reader.read_window(window)  # (1, 512, 512) float32 K
    """

    def __init__(
        self, source: Source, *, calibration: Calibration = "radiance"
    ) -> None:
        if calibration not in get_args(Calibration):
            raise ValueError(
                f"calibration must be one of {get_args(Calibration)}; "
                f"got {calibration!r}."
            )
        try:
            self._init_file(source, ["Rad"])
        except ValueError as exc:
            raise ValueError(
                f"not a GOES-R ABI L1b radiance file ({exc}); L2 products "
                "are read with goes.L2Reader."
            ) from exc
        self.calibration = calibration
        with self._open() as f:
            self._band_id = int(np.asarray(f["band_id"][()]).reshape(-1)[0])
            self._wavelength_um = round(
                float(np.asarray(f["band_wavelength"][()]).reshape(-1)[0]), 6
            )
            self._coefficients = {
                name: abi_scalar(f, name)
                for name in (
                    "kappa0",
                    "planck_fk1",
                    "planck_fk2",
                    "planck_bc1",
                    "planck_bc2",
                )
            }
        c = self._coefficients
        if calibration == "reflectance" and not np.isfinite(c["kappa0"]):
            raise ValueError(
                f"reflectance applies to the reflective channels "
                f"{constants.REFLECTIVE_CHANNELS[0]}-{constants.REFLECTIVE_CHANNELS[-1]};"
                f" {self.channel} has no kappa0."
            )
        planck = [c["planck_fk1"], c["planck_fk2"], c["planck_bc1"], c["planck_bc2"]]
        if calibration == "brightness_temperature" and not np.all(np.isfinite(planck)):
            raise ValueError(
                f"brightness_temperature applies to the emissive channels "
                f"{constants.EMISSIVE_CHANNELS[0]}-{constants.EMISSIVE_CHANNELS[-1]};"
                f" {self.channel} has no Planck coefficients."
            )

    def __repr__(self) -> str:
        return (
            f"goes.Reader({self._describe()!r}, channel={self.channel!r}, "
            f"calibration={self.calibration!r}, shape={self.shape})"
        )

    @property
    def channel(self) -> str:
        """ABI channel name (``"C01"`` … ``"C16"``)."""
        return f"C{self._band_id:02d}"

    @property
    def wavelength_um(self) -> float:
        """Band central wavelength (µm)."""
        return self._wavelength_um

    @property
    def quality(self) -> QualityReader:
        """The file's per-pixel data-quality flags (``DQF``) on the same grid."""
        return QualityReader._sharing(self)

    @property
    def units(self) -> str:
        """Units of the calibrated output."""
        return {
            "counts": "1",
            "radiance": self._vars[0].units,
            "reflectance": "1",
            "brightness_temperature": "K",
        }[self.calibration]

    @property
    def calibration_coefficients(self) -> dict[str, float]:
        """The file's scaling and calibration coefficients (``NaN`` = n/a)."""
        rad = self._vars[0]
        return {
            "scale_factor": rad.scale if rad.scale is not None else float("nan"),
            "add_offset": rad.offset if rad.offset is not None else float("nan"),
            **self._coefficients,
        }

    @property
    def _bands(self) -> tuple[str, ...]:
        return (self.channel,)

    @property
    def _dtype(self) -> Any:
        return np.dtype(np.uint16 if self.calibration == "counts" else np.float32)

    @property
    def _fill_value(self) -> float | int:
        return self._vars[0].fill if self.calibration == "counts" else np.nan

    def _band_attrs(self) -> dict[str, Any]:
        return {
            "units": (self.units,),
            "wavelengths": (self._wavelength_um * 1000.0,),
            "calibration": self.calibration,
        }

    def _decode(self, raw: list[np.ndarray]) -> np.ndarray:
        rad = self._vars[0]
        if self.calibration == "counts":
            return rad.raw(raw[0])[None]
        radiance = rad.decode(raw[0])
        c = self._coefficients
        if self.calibration == "radiance":
            return radiance[None]
        if self.calibration == "reflectance":
            return (radiance * np.float32(c["kappa0"]))[None]
        band = PlanckLinear(
            fk1=c["planck_fk1"],
            fk2=c["planck_fk2"],
            bc1=c["planck_bc1"],
            bc2=c["planck_bc2"],
        )
        bt = brightness_temperature_band(radiance, band)
        return bt.astype(np.float32)[None]

calibration_coefficients property

The file's scaling and calibration coefficients (NaN = n/a).

channel property

ABI channel name ("C01" … "C16").

quality property

The file's per-pixel data-quality flags (DQF) on the same grid.

units property

Units of the calibrated output.

wavelength_um property

Band central wavelength (µm).

geoproducts.goes.l2

GOES-R ABI L2 product reader.

Every ABI L2 product (OR_ABI-L2-<code><sector>-M6..._G.._s..._e..._c....nc) puts its retrievals on the same fixed grid as the L1b radiances, packed with the same CF conventions, so one reader covers them all: the clear sky mask (ACM), cloud-top height (ACHA), land surface temperature (LST), fire detection (FDC), stability indices (DSI), total precipitable water (TPW), cloud and moisture imagery (CMIP, and MCMIP with all 16 channels on one 2 km grid), and the rest.

L2Reader

Bases: ABIFile

GOES-R ABI L2 product reader: chosen variables as bands.

Each band is one 2-D variable of the file. Unpacked integer variables (masks, class codes such as the clear sky mask's BCM / ACM or the fire Mask) are kept as integers with the file's fill; anything packed or floating (cloud-top height, LST, CMI reflectance and brightness temperature, fire power) is decoded to float32 with NaN fill.

Band names are the variable names, except that cloud and moisture imagery is named by channel (CMI_C13 / CMIP's CMI → "C13"), so an MCMIP file feeds the channel-named presets and RGB recipes directly.

Parameters:

Name Type Description Default
source Source

An L2 .nc file: a local path, any URI geotoolz-cloud reads (read with ranged requests), or a binary file-like object.

required
variables str | Sequence[str] | None

Variable name(s) to read. Default: the product's primary variables — BCM + ACM for ACM, Mask for FDC, LST for LST, otherwise every 2-D variable that is not a quality flag (all 16 CMI_Cnn for MCMIP, the five indices for DSI, HT for ACHA, …). available_variables lists them all.

None

Raises:

Type Description
ImportError

h5py is not installed (the [goes] extra).

ValueError

source is not an ABI file, or a variable is missing or not on the fixed grid.

Examples:

Cloud-top height and the clear sky mask of one mesoscale scan::

height = goes.L2Reader(acha_path)            # bands ('HT',), metres
mask = goes.L2Reader(acm_path)               # ('BCM', 'ACM') uint8
mask.flags("ACM")  # {0: 'clear', 1: 'probably_clear', ...}

All 16 channels, already calibrated, on one 2 km grid::

cmi = goes.L2Reader(mcmip_path).load()       # (16, 500, 500) float32
cmi.attrs["band_names"][:3]                  # ('C01', 'C02', 'C03')
Source code in packages/geotoolz-products/src/geoproducts/goes/l2.py
class L2Reader(ABIFile):
    """GOES-R ABI L2 product reader: chosen variables as bands.

    Each band is one 2-D variable of the file. Unpacked integer variables
    (masks, class codes such as the clear sky mask's ``BCM`` / ``ACM`` or
    the fire ``Mask``) are kept as integers with the file's fill; anything
    packed or floating (cloud-top height, LST, CMI reflectance and brightness
    temperature, fire power) is decoded to ``float32`` with ``NaN`` fill.

    Band names are the variable names, except that cloud and moisture
    imagery is named by channel (``CMI_C13`` / CMIP's ``CMI`` → ``"C13"``),
    so an MCMIP file feeds the channel-named presets and RGB recipes
    directly.

    Args:
        source: An L2 ``.nc`` file: a local path, any URI geotoolz-cloud
            reads (read with ranged requests), or a binary file-like object.
        variables: Variable name(s) to read. Default: the product's primary
            variables — ``BCM`` + ``ACM`` for ACM, ``Mask`` for FDC, ``LST``
            for LST, otherwise every 2-D variable that is not a quality
            flag (all 16 ``CMI_Cnn`` for MCMIP, the five indices for DSI,
            ``HT`` for ACHA, …). ``available_variables`` lists them all.

    Raises:
        ImportError: ``h5py`` is not installed (the ``[goes]`` extra).
        ValueError: ``source`` is not an ABI file, or a variable is missing
            or not on the fixed grid.

    Examples:
        Cloud-top height and the clear sky mask of one mesoscale scan::

            height = goes.L2Reader(acha_path)            # bands ('HT',), metres
            mask = goes.L2Reader(acm_path)               # ('BCM', 'ACM') uint8
            mask.flags("ACM")  # {0: 'clear', 1: 'probably_clear', ...}

        All 16 channels, already calibrated, on one 2 km grid::

            cmi = goes.L2Reader(mcmip_path).load()       # (16, 500, 500) float32
            cmi.attrs["band_names"][:3]                  # ('C01', 'C02', 'C03')
    """

    def __init__(
        self, source: Source, *, variables: str | Sequence[str] | None = None
    ) -> None:
        self._init_file(source, [])
        self._product = product_code(self._info.dataset_name)
        with self._open() as f:
            names = self._resolve(f, variables)
            self._load_variables(f, names)
            self._channel_of_cmi = (
                f"C{int(np.asarray(f['band_id'][()]).reshape(-1)[0]):02d}"
                if "CMI" in names and "band_id" in f
                else None
            )
            self._available = grid_variables(f)
            self._wavelengths = self._cmi_wavelengths(f)

    def _resolve(self, f: Any, variables: str | Sequence[str] | None) -> list[str]:
        if isinstance(variables, str):
            return [variables]
        if variables is not None:
            names = list(variables)
            if not names:
                raise ValueError("variables must name at least one variable.")
            return names
        default = constants.L2_DEFAULT_VARIABLES.get(self._product)
        if default is not None:
            return list(default)
        names = [n for n in grid_variables(f) if not n.startswith("DQF")]
        if not names:
            raise ValueError(
                f"{self._describe()} has no 2-D data variables on its grid."
            )
        return names

    def _cmi_wavelengths(self, f: Any) -> tuple[float, ...] | None:
        """Band-centre wavelengths (nm) when every band is CMI imagery."""
        out = []
        for name in self._bands:
            key = f"band_wavelength_{name}" if f"band_wavelength_{name}" in f else None
            if key is None and name == self._channel_of_cmi:
                key = "band_wavelength"
            if key is None or key not in f:
                return None
            um = float(np.asarray(f[key][()]).reshape(-1)[0])
            out.append(round(um, 6) * 1000.0)
        return tuple(out)

    def __repr__(self) -> str:
        return (
            f"goes.L2Reader({self._describe()!r}, product={self.product!r}, "
            f"bands={self.bands}, shape={self.shape})"
        )

    @property
    def product(self) -> str:
        """The L2 product code (``"ACM"``, ``"ACHA"``, ``"MCMIP"``, …)."""
        return self._product

    @property
    def available_variables(self) -> tuple[str, ...]:
        """Every 2-D variable of the file on the fixed grid (data and flags)."""
        return self._available

    @property
    def quality(self) -> QualityReader:
        """The quality flags matching the bands, on the same grid.

        ``CMI_Cnn`` bands map to ``DQF_Cnn``; everything else to the
        product's ``DQF`` (``DQF_Overall`` for the sounding products).
        """
        names: list[str] = []
        for var in self._vars:
            match = _CMI_RE.fullmatch(var.name)
            if match and f"DQF_{match['channel']}" in self._available:
                name = f"DQF_{match['channel']}"
            elif "DQF" in self._available:
                name = "DQF"
            elif "DQF_Overall" in self._available:
                name = "DQF_Overall"
            else:
                raise ValueError(f"{self._describe()} has no quality flags.")
            if name not in names:
                names.append(name)
        return QualityReader._sharing(self, tuple(names))

    @property
    def _bands(self) -> tuple[str, ...]:
        out = []
        for var in self._vars:
            match = _CMI_RE.fullmatch(var.name)
            if match:
                out.append(match["channel"])
            elif var.name == "CMI" and self._channel_of_cmi:
                out.append(self._channel_of_cmi)
            else:
                out.append(var.name)
        return tuple(out)

    def _band_attrs(self) -> dict[str, Any]:
        attrs = {**super()._band_attrs(), "product": self._product}
        if self._wavelengths is not None:
            attrs["wavelengths"] = self._wavelengths
        return attrs

available_variables property

Every 2-D variable of the file on the fixed grid (data and flags).

product property

The L2 product code ("ACM", "ACHA", "MCMIP", …).

quality property

The quality flags matching the bands, on the same grid.

CMI_Cnn bands map to DQF_Cnn; everything else to the product's DQF (DQF_Overall for the sounding products).

product_code(dataset_name)

The L2 product code of a file name: "ACM", "MCMIP", "ACHA2KM".

Returns "" when the name is not an ABI L2 file name.

Source code in packages/geotoolz-products/src/geoproducts/goes/l2.py
def product_code(dataset_name: str) -> str:
    """The L2 product code of a file name: ``"ACM"``, ``"MCMIP"``, ``"ACHA2KM"``.

    Returns ``""`` when the name is not an ABI L2 file name.
    """
    match = _PRODUCT_RE.search(dataset_name)
    return match["code"] if match else ""

geoproducts.goes.aws

Find and fetch ABI files in NOAA's public GOES buckets on AWS.

NOAA's Open Data Dissemination programme mirrors every GOES-R product to public, anonymous S3 buckets (noaa-goes16 … noaa-goes19), keyed by product and scan-start hour::

<product>/<year>/<day-of-year>/<hour>/OR_<product>-M6C<nn>_G<nn>_s<start>_e<end>_c<created>.nc

This module maps ABI file names, satellites and time windows onto those objects. Listing and atomic downloads go unsigned through geocloud.files on the shared obstore pool (no credentials, no AWS SDK; geotoolz-cloud comes with the [goes] extra).

ABIFile dataclass

One ABI object in a NOAA bucket, with its file-name fields parsed.

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
@dataclass(frozen=True)
class ABIFile:
    """One ABI object in a NOAA bucket, with its file-name fields parsed."""

    key: str
    satellite: str
    product: str
    sector: str | None
    mode: int
    channel: str | None
    start: datetime
    end: datetime
    created: datetime
    size: int | None = None

    @property
    def name(self) -> str:
        """The object's file name."""
        return self.key.rsplit("/", 1)[-1]

    @property
    def url(self) -> str:
        """Public HTTPS URL of the object."""
        return url(self.satellite, self.key)

name property

The object's file name.

url property

Public HTTPS URL of the object.

bucket(satellite)

The NOAA bucket of a GOES-R satellite ("G19" / 19 → noaa-goes19).

Raises:

Type Description
ValueError

satellite is not GOES-16 … GOES-19.

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
def bucket(satellite: str | int) -> str:
    """The NOAA bucket of a GOES-R satellite (``"G19"`` / ``19`` → ``noaa-goes19``).

    Raises:
        ValueError: ``satellite`` is not GOES-16 … GOES-19.
    """
    return f"noaa-goes{_satellite_number(satellite)}"

download(file, dest, *, satellite=None, overwrite=False)

Download one ABI object into the directory dest.

The file is streamed to <name>.part and renamed when complete, so an interrupted download never leaves a truncated .nc behind. An existing file is reused unless overwrite is set.

Parameters:

Name Type Description Default
file ABIFile | str

An :class:ABIFile from :func:list_files, or an object key.

required
dest str | Path

Destination directory (created if missing).

required
satellite str | int | None

Required when file is a key whose name does not identify the satellite; otherwise read from the file name.

None
overwrite bool

Re-download even when the file already exists.

False

Returns:

Type Description
Path

Path of the downloaded file.

Raises:

Type Description
ImportError

geotoolz-cloud is not installed ([goes] extra).

FileNotFoundError

No such object.

Exception

The download failed (obstore's error; transient errors are retried first).

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
def download(
    file: ABIFile | str,
    dest: str | Path,
    *,
    satellite: str | int | None = None,
    overwrite: bool = False,
) -> Path:
    """Download one ABI object into the directory ``dest``.

    The file is streamed to ``<name>.part`` and renamed when complete, so
    an interrupted download never leaves a truncated ``.nc`` behind. An
    existing file is reused unless ``overwrite`` is set.

    Args:
        file: An :class:`ABIFile` from :func:`list_files`, or an object key.
        dest: Destination directory (created if missing).
        satellite: Required when ``file`` is a key whose name does not
            identify the satellite; otherwise read from the file name.
        overwrite: Re-download even when the file already exists.

    Returns:
        Path of the downloaded file.

    Raises:
        ImportError: geotoolz-cloud is not installed (``[goes]`` extra).
        FileNotFoundError: No such object.
        Exception: The download failed (obstore's error; transient errors
            are retried first).
    """
    item = parse_key(file) if isinstance(file, str) else file
    target = Path(dest) / item.name
    if target.exists() and not overwrite:
        return target
    return s3.download_object(
        bucket(satellite or item.satellite), item.key, target, extra="goes"
    )

list_files(*, satellite, start, end=None, product='ABI-L1b-RadC', channel=None, sector=None)

List the ABI files whose scan starts in [start, end).

Parameters:

Name Type Description Default
satellite str | int

"G16" … "G19" (or 16 … 19).

required
start datetime

Window start. Naive datetimes are taken as UTC.

required
end datetime | None

Window end (exclusive). Default: start plus one hour.

None
product str

Bucket product prefix, e.g. "ABI-L1b-RadF" (full disk), "ABI-L1b-RadC" (CONUS / PACUS), "ABI-L1b-RadM" (mesoscale), or an L2 product such as "ABI-L2-ACMC" (clear sky mask) or "ABI-L2-MCMIPF" (all 16 channels on one grid). Default "ABI-L1b-RadC".

'ABI-L1b-RadC'
channel int | str | None

Keep one channel (13 or "C13"); L2 files without a channel are then skipped. Default: all.

None
sector str | None

Mesoscale sector, "M1" or "M2". Default: both.

None

Returns:

Type Description
list[ABIFile]

The matching files, sorted by scan start then channel.

Raises:

Type Description
ValueError

end is not after start, or channel / satellite is out of range.

ImportError

geotoolz-cloud is not installed ([goes] extra).

Exception

The bucket listing failed (obstore's error; transient errors are retried first).

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
def list_files(
    *,
    satellite: str | int,
    start: datetime,
    end: datetime | None = None,
    product: str = "ABI-L1b-RadC",
    channel: int | str | None = None,
    sector: str | None = None,
) -> list[ABIFile]:
    """List the ABI files whose scan starts in ``[start, end)``.

    Args:
        satellite: ``"G16"`` … ``"G19"`` (or ``16`` … ``19``).
        start: Window start. Naive datetimes are taken as UTC.
        end: Window end (exclusive). Default: ``start`` plus one hour.
        product: Bucket product prefix, e.g. ``"ABI-L1b-RadF"`` (full disk),
            ``"ABI-L1b-RadC"`` (CONUS / PACUS), ``"ABI-L1b-RadM"``
            (mesoscale), or an L2 product such as ``"ABI-L2-ACMC"`` (clear
            sky mask) or ``"ABI-L2-MCMIPF"`` (all 16 channels on one grid).
            Default ``"ABI-L1b-RadC"``.
        channel: Keep one channel (``13`` or ``"C13"``); L2 files without
            a channel are then skipped. Default: all.
        sector: Mesoscale sector, ``"M1"`` or ``"M2"``. Default: both.

    Returns:
        The matching files, sorted by scan start then channel.

    Raises:
        ValueError: ``end`` is not after ``start``, or ``channel`` /
            ``satellite`` is out of range.
        ImportError: geotoolz-cloud is not installed (``[goes]`` extra).
        Exception: The bucket listing failed (obstore's error; transient
            errors are retried first).
    """
    start = as_utc(start)
    end = start + timedelta(hours=1) if end is None else as_utc(end)
    if end <= start:
        raise ValueError(f"end ({end}) must be after start ({start}).")
    wanted_channel = None if channel is None else _channel_name(channel)
    files: list[ABIFile] = []
    hour = start.replace(minute=0, second=0, microsecond=0)
    while hour < end:
        prefix = f"{product}/{hour:%Y}/{hour:%j}/{hour:%H}/"
        for key, size in s3.list_objects(bucket(satellite), prefix, extra="goes"):
            try:
                item = parse_key(key, size=size)
            except ValueError:
                continue
            if not start <= item.start < end:
                continue
            if wanted_channel is not None and item.channel != wanted_channel:
                continue
            if sector is not None and item.sector != sector:
                continue
            files.append(item)
        hour += timedelta(hours=1)
    return sorted(files, key=lambda item: (item.start, item.channel or "", item.key))

parse_key(key, *, size=None)

Parse an ABI object key (or bare file name).

Raises:

Type Description
ValueError

key does not follow the ABI file-naming convention.

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
def parse_key(key: str, *, size: int | None = None) -> ABIFile:
    """Parse an ABI object key (or bare file name).

    Raises:
        ValueError: ``key`` does not follow the ABI file-naming convention.
    """
    match = _KEY_RE.search(key)
    if match is None:
        raise ValueError(f"not an ABI file name: {key!r}")
    return ABIFile(
        key=key,
        satellite=f"G{match['satellite']}",
        product=match["product"],
        sector=f"M{match['sector']}" if match["sector"] else None,
        mode=int(match["mode"]),
        channel=f"C{match['channel']}" if match["channel"] else None,
        start=_parse_stamp(match["start"]),
        end=_parse_stamp(match["end"]),
        created=_parse_stamp(match["created"]),
        size=size,
    )

url(satellite, key)

Public HTTPS URL of key in satellite's bucket.

Source code in packages/geotoolz-products/src/geoproducts/goes/aws.py
def url(satellite: str | int, key: str) -> str:
    """Public HTTPS URL of ``key`` in ``satellite``'s bucket."""
    return s3.object_url(bucket(satellite), key)

geoproducts.goes.recipes

The standard ABI RGB recipes, as data.

Each operational RGB is three band expressions, each linearly stretched between a fixed vmin and vmax and gamma-corrected. The numbers follow the published quick guides (CIRA / NOAA / CIMSS). Inputs are ABI channel names (band_names of goes.Reader / goes.L2Reader outputs): reflectance factor (0-1) for C01-C06, brightness temperature (K) for C07-C16, i.e. calibration="reflectance" / "brightness_temperature" L1b reads or MCMIP / CMIP imagery.

goes.presets turns a recipe into a geoops.viz.RGBRecipe operator; the recipes themselves need no extra.

Recipe dataclass

One RGB recipe: per-channel expression, stretch and gamma.

Attributes:

Name Type Description
name str

Short identifier.

red str

Red-channel band name or band-math expression.

green str

Green-channel band name or expression.

blue str

Blue-channel band name or expression.

vmin tuple[float, float, float]

Per-channel value mapped to 0 (above vmax inverts).

vmax tuple[float, float, float]

Per-channel value mapped to 1.

gamma tuple[float, float, float]

Per-channel display gamma.

channels tuple[str, ...]

Bands the expressions read.

description str

What the composite shows.

Source code in packages/geotoolz-products/src/geoproducts/_src/presets.py
@dataclass(frozen=True)
class Recipe:
    """One RGB recipe: per-channel expression, stretch and gamma.

    Attributes:
        name: Short identifier.
        red: Red-channel band name or band-math expression.
        green: Green-channel band name or expression.
        blue: Blue-channel band name or expression.
        vmin: Per-channel value mapped to 0 (above ``vmax`` inverts).
        vmax: Per-channel value mapped to 1.
        gamma: Per-channel display gamma.
        channels: Bands the expressions read.
        description: What the composite shows.
    """

    name: str
    red: str
    green: str
    blue: str
    vmin: tuple[float, float, float]
    vmax: tuple[float, float, float]
    gamma: tuple[float, float, float]
    channels: tuple[str, ...]
    description: str

geoproducts.goes.presets

GOES-R ABI-aware geotoolz operator presets.

Presets bind geotoolz operators to ABI channel names ("C01" … "C16", the band_names of :class:geoproducts.goes.Reader and :class:geoproducts.goes.L2Reader outputs) and to the RGB recipes in :mod:geoproducts.goes.recipes. geotoolz is an optional dependency (pip install 'geotoolz-products[operators]'), imported when a preset is called, so the readers install without the operator library.

The multi-channel presets expect the channels on one grid: an MCMIP file (all 16 channels at 2 km), or L1b readers put together with :func:geoproducts.stack.

DayCloudPhase()

CIRA day cloud phase distinction (C13 BT, C02, C05).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def DayCloudPhase() -> Operator:
    """CIRA day cloud phase distinction (C13 BT, C02, C05)."""
    return _rgb_recipe(recipes.DAY_CLOUD_PHASE, "DayCloudPhase")

FireTemperature()

CIRA fire temperature (C07 BT, C06, C05).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def FireTemperature() -> Operator:
    """CIRA fire temperature (C07 BT, C06, C05)."""
    return _rgb_recipe(recipes.FIRE_TEMPERATURE, "FireTemperature")

MaskClouds(*, conservative=False)

Cloud mask from the L2 clear sky mask (ACM), True = cloudy.

Reads the BCM band of a goes.L2Reader ACM read (cloudy or probably cloudy). conservative=True reads the four-level ACM band instead and also flags probably clear pixels, for analyses that need confidently clear sky. Pair with gz.mask.ApplyMask once the mask is on the data's grid (geoproducts.stack resamples it with mode).

Parameters:

Name Type Description Default
conservative bool

Flag probably-clear pixels as well.

False

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def MaskClouds(*, conservative: bool = False) -> Operator:
    """Cloud mask from the L2 clear sky mask (ACM), ``True`` = cloudy.

    Reads the ``BCM`` band of a ``goes.L2Reader`` ACM read (cloudy or
    probably cloudy). ``conservative=True`` reads the four-level ``ACM``
    band instead and also flags *probably clear* pixels, for analyses that
    need confidently clear sky. Pair with ``gz.mask.ApplyMask`` once the
    mask is on the data's grid (``geoproducts.stack`` resamples it with ``mode``).

    Args:
        conservative: Flag probably-clear pixels as well.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    qa = _geotoolz("qa", "MaskClouds")
    if conservative:
        values = [
            constants.ACM_PROBABLY_CLEAR,
            constants.ACM_PROBABLY_CLOUDY,
            constants.ACM_CLOUDY,
        ]
        return qa.MaskClouds(qa_band="ACM", values=values)
    return qa.MaskClouds(qa_band="BCM", values=[constants.BCM_CLOUDY])

NDVI()

NDVI from ABI reflectance: red="C02", nir="C03".

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def NDVI() -> Operator:
    """NDVI from ABI reflectance: ``red="C02"``, ``nir="C03"``.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    return _geotoolz("indices", "NDVI").NDVI(red="C02", nir="C03")

NaturalColor()

CIRA day land cloud "natural colour" (C05, C03, C02). Reads C02/C03/C05.

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def NaturalColor() -> Operator:
    """CIRA day land cloud "natural colour" (C05, C03, C02). Reads C02/C03/C05."""
    return _rgb_recipe(recipes.NATURAL_COLOR, "NaturalColor")

ParallaxCorrect(*, satellite_lon_deg=constants.GOES_EAST_LON_DEG, target_height_m=0.0, method='bilinear')

Geostationary parallax correction from a GOES-R viewpoint.

Binds gz.geom.GeostationaryParallaxCorrect to the GOES geostationary height; the input must already be on an EPSG:4326 grid. Pass reader.satellite_lon_deg (or constants.GOES_WEST_LON_DEG) for a satellite other than GOES-East, and the ACHA cloud-top height (on the same grid) as target_height_m to move clouds to where they are.

Parameters:

Name Type Description Default
satellite_lon_deg float

Sub-satellite longitude. Default GOES-East.

GOES_EAST_LON_DEG
target_height_m Any

Height of the observed feature (metres): a scalar, a same-grid array or a same-grid GeoArray.

0.0
method str

"nearest" or "bilinear".

'bilinear'

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def ParallaxCorrect(
    *,
    satellite_lon_deg: float = constants.GOES_EAST_LON_DEG,
    target_height_m: Any = 0.0,
    method: str = "bilinear",
) -> Operator:
    """Geostationary parallax correction from a GOES-R viewpoint.

    Binds ``gz.geom.GeostationaryParallaxCorrect`` to the GOES geostationary
    height; the input must already be on an EPSG:4326 grid. Pass
    ``reader.satellite_lon_deg`` (or ``constants.GOES_WEST_LON_DEG``) for a
    satellite other than GOES-East, and the ACHA cloud-top height (on the
    same grid) as ``target_height_m`` to move clouds to where they are.

    Args:
        satellite_lon_deg: Sub-satellite longitude. Default GOES-East.
        target_height_m: Height of the observed feature (metres): a scalar,
            a same-grid array or a same-grid GeoArray.
        method: ``"nearest"`` or ``"bilinear"``.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    return parallax_correct(
        "goes.presets.ParallaxCorrect",
        satellite_lon_deg=satellite_lon_deg,
        satellite_height_m=constants.SATELLITE_HEIGHT_M,
        target_height_m=target_height_m,
        method=method,
    )

Recipe(recipe)

A gz.viz.RGBRecipe for one of :data:goes.recipes.RECIPES.

Parameters:

Name Type Description Default
recipe Recipe | str

A :class:~geoproducts.goes.recipes.Recipe, or its name ("true_color", "natural_color", "day_cloud_phase", "fire_temperature").

required

Returns:

Type Description
Operator

An operator mapping a channel-named stack to a (3, H, W)

Operator

float32 RGB in [0, 1].

Raises:

Type Description
KeyError

Unknown recipe name.

ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def Recipe(recipe: recipes.Recipe | str) -> Operator:
    """A ``gz.viz.RGBRecipe`` for one of :data:`goes.recipes.RECIPES`.

    Args:
        recipe: A :class:`~geoproducts.goes.recipes.Recipe`, or its name
            (``"true_color"``, ``"natural_color"``, ``"day_cloud_phase"``,
            ``"fire_temperature"``).

    Returns:
        An operator mapping a channel-named stack to a ``(3, H, W)``
        ``float32`` RGB in ``[0, 1]``.

    Raises:
        KeyError: Unknown recipe name.
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    spec = recipes.RECIPES[recipe] if isinstance(recipe, str) else recipe
    return _rgb_recipe(spec, "Recipe")

SyntheticGreen()

The CIMSS synthetic green band, 0.45 C02 + 0.10 C03 + 0.45 C01.

ABI has no green channel; this linear mix of red, "veggie" near-IR and blue reflectance stands in for it in true-colour imagery. Output is one band, (1, H, W).

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def SyntheticGreen() -> Operator:
    """The CIMSS synthetic green band, ``0.45 C02 + 0.10 C03 + 0.45 C01``.

    ABI has no green channel; this linear mix of red, "veggie" near-IR and
    blue reflectance stands in for it in true-colour imagery. Output is one
    band, ``(1, H, W)``.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    expression = " + ".join(
        f"{weight} * {channel}"
        for channel, weight in constants.SYNTHETIC_GREEN_WEIGHTS.items()
    )
    return _geotoolz("spectral", "SyntheticGreen").BandMath(expression=expression)

TrueColor()

True colour (C02, synthetic green, C01), gamma 2.2. Reads C01-C03.

Source code in packages/geotoolz-products/src/geoproducts/goes/presets.py
def TrueColor() -> Operator:
    """True colour (C02, synthetic green, C01), gamma 2.2. Reads C01-C03."""
    return _rgb_recipe(recipes.TRUE_COLOR, "TrueColor")

geoproducts.goes.constants

GOES-R ABI band table, quality-flag meanings and orbital constants.

geoproducts.himawari

Himawari AHI HSD and L2 readers, NOAA bucket helpers, recipes and presets (guide).

geoproducts.himawari.reader

Himawari AHI L1b reader: one band of one scan from its HSD segments.

An AHI observation area (the full disk, a Japan area, a target area) is split into horizontal segments, one HSD file each (10 for the full disk). :class:Reader places the segments it is given on the area's geostationary grid — missing segments simply read as fill — and decodes only the segments a window touches.

The grid is the CGMS normalised geostationary projection of the header's CFAC / LFAC / COFF / LOFF (evenly spaced +proj=geos metres, sweep=y; see :meth:geoproducts._src.geostationary.FixedGrid.from_cgms).

Reader

Bases: ProductReader

Himawari-8 / -9 AHI L1b reader (one band, one scan, any segments).

load / read_window / read_from_bounds return a (1, H, W) GeoArray on the observation area's grid, the band named "B01" … "B16". Pixels in segments that were not given, outside the scan, flagged as errors or — for calibrated outputs — off the Earth's disk hold the fill: NaN for every calibrated output, 65535 for "counts" (which are otherwise the stored values).

Calibration uses the coefficients in each file (block 5 of the header), segment by segment:

  • "counts" — the stored counts (uint16).
  • "radiance" — counts · gain + offset (W m-2 sr-1 µm-1). Bands 1-6 use the updated visible calibration when the file carries one.
  • "reflectance" — radiance · albedo coefficient, the albedo (reflectance factor; bands 1-6 only).
  • "brightness_temperature" — the effective temperature of the radiance at the band's central wavelength (Planck), corrected by the file's c0 + c1 T + c2 T² (bands 7-16 only).

.bz2 segments are decompressed on read (the most recent one is kept in memory); for many small windows over a large file, decompress once with himawari.aws.download(..., decompress=True) and read the .DAT files, which are memory-mapped.

Parameters:

Name Type Description Default
segments Source | Sequence[Source]

HSD segment files (.DAT or .DAT.bz2) of one band of one scan, in any order — all of them, or only those covering the area of interest.

required
calibration Calibration

Output quantity; see above. Default "radiance".

'radiance'

Raises:

Type Description
ValueError

No segments, segments of different bands / scans / areas, a duplicated segment, or a calibration that does not apply to the band.

Examples:

The full disk of band 13 (10.4 µm), brightness temperature::

paths = sorted(Path("ahi").glob("HS_H09_*_B13_FLDK_R20_S*.DAT.bz2"))
reader = himawari.Reader(paths, calibration="brightness_temperature")
reader.shape  # (1, 5500, 5500) · 2 km
Source code in packages/geotoolz-products/src/geoproducts/himawari/reader.py
class Reader(ProductReader):
    """Himawari-8 / -9 AHI L1b reader (one band, one scan, any segments).

    ``load`` / ``read_window`` / ``read_from_bounds`` return a
    ``(1, H, W)`` ``GeoArray`` on the observation area's grid, the band
    named ``"B01"`` … ``"B16"``. Pixels in segments that were not given,
    outside the scan, flagged as errors or — for calibrated outputs — off
    the Earth's disk hold the fill: ``NaN`` for every calibrated output,
    ``65535`` for ``"counts"`` (which are otherwise the stored values).

    Calibration uses the coefficients in each file (block 5 of the header),
    segment by segment:

    - ``"counts"`` — the stored counts (``uint16``).
    - ``"radiance"`` — ``counts · gain + offset`` (W m-2 sr-1 µm-1). Bands
      1-6 use the updated visible calibration when the file carries one.
    - ``"reflectance"`` — ``radiance · albedo coefficient``, the albedo
      (reflectance factor; bands 1-6 only).
    - ``"brightness_temperature"`` — the effective temperature of the
      radiance at the band's central wavelength (Planck), corrected by the
      file's ``c0 + c1 T + c2 T²`` (bands 7-16 only).

    ``.bz2`` segments are decompressed on read (the most recent one is
    kept in memory); for many small windows over a large file,
    decompress once with ``himawari.aws.download(..., decompress=True)``
    and read the ``.DAT`` files, which are memory-mapped.

    Args:
        segments: HSD segment files (``.DAT`` or ``.DAT.bz2``) of one band
            of one scan, in any order — all of them, or only those covering
            the area of interest.
        calibration: Output quantity; see above. Default ``"radiance"``.

    Raises:
        ValueError: No segments, segments of different bands / scans /
            areas, a duplicated segment, or a ``calibration`` that does
            not apply to the band.

    Examples:
        The full disk of band 13 (10.4 µm), brightness temperature::

            paths = sorted(Path("ahi").glob("HS_H09_*_B13_FLDK_R20_S*.DAT.bz2"))
            reader = himawari.Reader(paths, calibration="brightness_temperature")
            reader.shape  # (1, 5500, 5500) · 2 km
    """

    def __init__(
        self,
        segments: Source | Sequence[Source],
        *,
        calibration: Calibration = "radiance",
    ) -> None:
        if calibration not in get_args(Calibration):
            raise ValueError(
                f"calibration must be one of {get_args(Calibration)}; "
                f"got {calibration!r}."
            )
        paths = [segments] if isinstance(segments, str | os.PathLike) else segments
        if not paths:
            raise ValueError("Reader needs at least one HSD segment file.")
        headers = [read_header(p) for p in paths]
        first = headers[0]
        for path, header in zip(paths, headers, strict=True):
            for name in _SHARED:
                if getattr(header, name) != getattr(first, name):
                    raise ValueError(
                        f"{Path(path).name} differs from the first segment in "
                        f"{name!r}: segments must be one band of one scan."
                    )
        if len({h.start_time.date() for h in headers}) > 1:
            raise ValueError(
                "segments come from different days: segments must be one band "
                "of one scan."
            )
        numbers = [h.segment for h in headers]
        if len(set(numbers)) != len(numbers):
            raise ValueError(f"duplicated segments: {sorted(numbers)}.")
        if calibration == "reflectance" and first.is_emissive:
            raise ValueError(
                f"reflectance applies to bands 1-6; {self._name(first)} is emissive."
            )
        if calibration == "brightness_temperature" and not first.is_emissive:
            raise ValueError(
                f"brightness_temperature applies to bands 7-16; "
                f"{self._name(first)} is reflective."
            )
        if any(h.rotation_urad or h.max_shift_px for h in headers):
            warnings.warn(
                "HSD navigation corrections (block 8) are not applied: the grid "
                "is the nominal projection, off by up to "
                f"{max(h.max_shift_px for h in headers):.2f} px plus a "
                f"{max(abs(h.rotation_urad) for h in headers):.3g} µrad rotation.",
                UserWarning,
                stacklevel=2,
            )
        order = np.argsort(numbers)
        self._paths: tuple[Path, ...] = tuple(Path(paths[i]) for i in order)
        self._headers: tuple[HSDHeader, ...] = tuple(headers[i] for i in order)
        self.calibration = calibration
        h = self._headers[0]
        self._grid = FixedGrid.from_cgms(
            columns=h.columns,
            lines=h.area_lines,
            cfac=h.cfac,
            lfac=h.lfac,
            coff=h.coff,
            loff=h.loff,
            lon_0=h.sub_lon,
            height_m=(h.distance_km - h.equatorial_radius_km) * 1000.0,
            semi_major_m=h.equatorial_radius_km * 1000.0,
            semi_minor_m=h.polar_radius_km * 1000.0,
        )
        self._cache: tuple[int, np.ndarray] | None = None

    @staticmethod
    def _name(header: HSDHeader) -> str:
        return f"B{header.band:02d}"

    def __getstate__(self) -> dict[str, Any]:
        state = dict(self.__dict__)
        state["_cache"] = None  # decompressed segments stay with the process
        return state

    def __repr__(self) -> str:
        return (
            f"himawari.Reader(band={self.band!r}, area={self.area!r}, "
            f"segments={self.segments}, calibration={self.calibration!r}, "
            f"shape={self.shape})"
        )

    # -- metadata ---------------------------------------------------------

    @property
    def header(self) -> HSDHeader:
        """The decoded header of the first segment."""
        return self._headers[0]

    @property
    def band(self) -> str:
        """AHI band name (``"B01"`` … ``"B16"``)."""
        return self._name(self.header)

    @property
    def wavelength_um(self) -> float:
        """Band central wavelength (µm)."""
        return self.header.wavelength_um

    @property
    def satellite(self) -> str:
        """``"Himawari-9"`` / ``"Himawari-8"``."""
        return self.header.satellite

    @property
    def area(self) -> str:
        """Observation area (``"FLDK"``, ``"JP01"``, ``"R301"``, …)."""
        return self.header.area

    @property
    def segments(self) -> tuple[int, ...]:
        """The segment numbers given (1-based)."""
        return tuple(h.segment for h in self._headers)

    @property
    def paths(self) -> tuple[Path, ...]:
        """The segment files, in segment order."""
        return self._paths

    @property
    def start_time(self) -> datetime:
        """Observation start (UTC) of the earliest segment."""
        return min(h.start_time for h in self._headers)

    @property
    def end_time(self) -> datetime:
        """Observation end (UTC) of the latest segment."""
        return max(h.end_time for h in self._headers)

    @property
    def satellite_lon_deg(self) -> float:
        """Sub-satellite longitude of the projection (degrees east)."""
        return self.header.sub_lon

    @property
    def satellite_height_m(self) -> float:
        """Satellite height above the equator (metres)."""
        return self._grid.height_m

    @property
    def units(self) -> str:
        """Units of the calibrated output."""
        return {
            "counts": "1",
            "radiance": "W m-2 sr-1 um-1",
            "reflectance": "1",
            "brightness_temperature": "K",
        }[self.calibration]

    # -- georeferencing ---------------------------------------------------

    @property
    def _crs(self) -> CRS:
        return self._grid.crs

    @property
    def _transform(self) -> Affine:
        return self._grid.transform

    @property
    def _shape(self) -> tuple[int, ...]:
        return (1, self._grid.height, self._grid.width)

    @property
    def _dtype(self) -> Any:
        return np.dtype(np.uint16 if self.calibration == "counts" else np.float32)

    @property
    def _fill_value(self) -> float | int:
        return self.header.error_count if self.calibration == "counts" else np.nan

    @property
    def _bands(self) -> tuple[str, ...]:
        return (self.band,)

    @property
    def _track(self) -> Track:
        return "A"

    def _band_attrs(self) -> dict[str, Any]:
        return {
            "units": (self.units,),
            "wavelengths": (round(self.wavelength_um * 1000.0, 6),),
            "calibration": self.calibration,
        }

    # -- windowed I/O -----------------------------------------------------

    def _segment_counts(self, index: int, rows: slice, cols: slice) -> np.ndarray:
        path, header = self._paths[index], self._headers[index]
        if path.suffix != ".bz2":
            return read_lines(path, header, rows, cols)
        if self._cache is None or self._cache[0] != index:
            whole = read_lines(path, header, slice(0, header.lines), slice(None))
            self._cache = (index, whole)
        return self._cache[1][rows, cols]

    def _read_window(self, window: PixelWindow) -> np.ndarray:
        def read(rows: slice, cols: slice) -> np.ndarray:
            # Each segment is calibrated with its own header's coefficients.
            out = np.full(
                (rows.stop - rows.start, cols.stop - cols.start),
                self._fill_value,
                dtype=self._dtype,
            )
            for i, h in enumerate(self._headers):
                seg_start = h.first_line - 1
                lo = max(rows.start, seg_start)
                hi = min(rows.stop, seg_start + h.lines)
                if lo >= hi:
                    continue
                counts = self._segment_counts(
                    i, slice(lo - seg_start, hi - seg_start), cols
                )
                out[lo - rows.start : hi - rows.start] = self._calibrate(counts, h)
            if self.calibration != "counts":
                out[~self._grid.on_earth(rows, cols)] = np.nan
            return out[None]

        return self._read_boundless(window, read)

    def _calibrate(self, counts: np.ndarray, h: HSDHeader) -> np.ndarray:
        """One segment's counts → the output quantity, with its coefficients."""
        if self.calibration == "counts":
            return counts
        invalid = (counts == h.error_count) | (counts == h.outside_count)
        gain, offset = h.gain, h.offset
        if not h.is_emissive and np.isfinite(h.updated_gain):
            gain, offset = h.updated_gain, h.updated_offset
        radiance = counts.astype(np.float64) * gain + offset
        radiance[invalid] = np.nan
        if self.calibration == "radiance":
            return radiance.astype(np.float32)
        if self.calibration == "reflectance":
            return (radiance * h.albedo_coefficient).astype(np.float32)
        return _brightness_temperature(radiance, h).astype(np.float32)

area property

Observation area ("FLDK", "JP01", "R301", …).

band property

AHI band name ("B01" … "B16").

end_time property

Observation end (UTC) of the latest segment.

header property

The decoded header of the first segment.

paths property

The segment files, in segment order.

satellite property

"Himawari-9" / "Himawari-8".

satellite_height_m property

Satellite height above the equator (metres).

satellite_lon_deg property

Sub-satellite longitude of the projection (degrees east).

segments property

The segment numbers given (1-based).

start_time property

Observation start (UTC) of the earliest segment.

units property

Units of the calibrated output.

wavelength_um property

Band central wavelength (µm).

geoproducts.himawari.l2

NOAA AHI L2 cloud products: cloud mask, cloud height, cloud phase.

NOAA's enterprise algorithms run on Himawari full-disk scans and publish NetCDF-4 files (AHI-<code>_v1r1_h09_s<start>_e<end>_c<created>.nc; CMSK cloud mask, CHGT cloud-top height, CPHS cloud phase). The variables sit on the AHI 2 km full-disk fixed grid, but the files carry per-pixel latitude / longitude rather than a usable grid mapping, so the reader places them on the nominal grid (identical, pixel for pixel, to the L1b 2 km full disk).

L2Reader

Bases: PackedGridReader

NOAA AHI L2 full-disk cloud product reader: chosen variables as bands.

Each band is one 2-D variable of the file on the 2 km full disk. Integer masks (CloudMask, CloudMaskBinary, Dust_Mask, …) stay int8 with the file's fill (-128); anything floating (cloud probability, cloud-top height) is float32 with NaN.

Parameters:

Name Type Description Default
source Source

An L2 .nc file: a local path, any URI geotoolz-cloud reads (read with ranged requests), or a binary file-like object.

required
variables str | Sequence[str] | None

Variable name(s) to read. Default: CloudMaskBinary + CloudMask for CMSK, otherwise every data variable on the grid. available_variables lists them all.

None

Raises:

Type Description
ImportError

h5py is not installed (the [himawari] extra).

ValueError

A variable is missing or not on the 2 km full disk.

Examples:

The binary and four-level cloud masks of one full-disk scan::

mask = himawari.L2Reader(cmsk_path)    # ('CloudMaskBinary', 'CloudMask')
mask.shape                             # (2, 5500, 5500) int8
mask.flags("CloudMask")  # {0: 'clear', 1: 'probably_clear', ...}
Source code in packages/geotoolz-products/src/geoproducts/himawari/l2.py
class L2Reader(PackedGridReader):
    """NOAA AHI L2 full-disk cloud product reader: chosen variables as bands.

    Each band is one 2-D variable of the file on the 2 km full disk.
    Integer masks (``CloudMask``, ``CloudMaskBinary``, ``Dust_Mask``, …)
    stay ``int8`` with the file's fill (``-128``); anything floating
    (cloud probability, cloud-top height) is ``float32`` with ``NaN``.

    Args:
        source: An L2 ``.nc`` file: a local path, any URI geotoolz-cloud
            reads (read with ranged requests), or a binary file-like object.
        variables: Variable name(s) to read. Default: ``CloudMaskBinary`` +
            ``CloudMask`` for ``CMSK``, otherwise every data variable on
            the grid. ``available_variables`` lists them all.

    Raises:
        ImportError: ``h5py`` is not installed (the ``[himawari]`` extra).
        ValueError: A variable is missing or not on the 2 km full disk.

    Examples:
        The binary and four-level cloud masks of one full-disk scan::

            mask = himawari.L2Reader(cmsk_path)    # ('CloudMaskBinary', 'CloudMask')
            mask.shape                             # (2, 5500, 5500) int8
            mask.flags("CloudMask")  # {0: 'clear', 1: 'probably_clear', ...}
    """

    extra = "himawari"
    feature = "geoproducts.himawari.L2Reader"

    def __init__(
        self, source: Source, *, variables: str | Sequence[str] | None = None
    ) -> None:
        self._source = source
        self._grid = full_disk_grid(2.0)
        with self._open() as f:
            self._product = product_code(str(hdf.attr(f, "Metadata_Link", ""))) or str(
                hdf.attr(f, "title", "")
            ).removeprefix("AHI-")
            self._satellite = str(hdf.attr(f, "satellite_name", ""))
            self._start = hdf.time_attr(f, "time_coverage_start")
            self._end = hdf.time_attr(f, "time_coverage_end")
            self._available = tuple(
                n
                for n in hdf.grid_variables(f, self._grid_shape)
                if not n.startswith(_GEOLOCATION) and not n.endswith("AWIPS")
            )
            self._load_variables(f, self._resolve(variables))

    def _resolve(self, variables: str | Sequence[str] | None) -> list[str]:
        if isinstance(variables, str):
            return [variables]
        if variables is not None:
            names = list(variables)
            if not names:
                raise ValueError("variables must name at least one variable.")
            return names
        default = constants.L2_DEFAULT_VARIABLES.get(self._product)
        names = list(default) if default is not None else list(self._available)
        if not names:
            raise ValueError(f"{self._describe()} has no data variables on its grid.")
        return names

    def __repr__(self) -> str:
        return (
            f"himawari.L2Reader({self._describe()!r}, product={self.product!r}, "
            f"variables={self.variables}, shape={self.shape})"
        )

    # -- georeferencing ---------------------------------------------------

    @property
    def _grid_shape(self) -> tuple[int, int]:
        return (self._grid.height, self._grid.width)

    @property
    def _crs(self) -> CRS:
        return self._grid.crs

    @property
    def _transform(self) -> Affine:
        return self._grid.transform

    @property
    def _track(self) -> Track:
        return "A"

    @property
    def _bands(self) -> tuple[str, ...]:
        return self.variables

    # -- file metadata ----------------------------------------------------

    @property
    def product(self) -> str:
        """Product code (``"CMSK"``, ``"CHGT"``, ``"CPHS"``)."""
        return self._product

    @property
    def satellite(self) -> str:
        """``"Himawari-9"`` / ``"Himawari-8"``."""
        return self._satellite

    @property
    def available_variables(self) -> tuple[str, ...]:
        """Every data variable of the file on the grid."""
        return self._available

    @property
    def start_time(self) -> datetime | None:
        """Scan start (UTC)."""
        return self._start

    @property
    def end_time(self) -> datetime | None:
        """Scan end (UTC)."""
        return self._end

    @property
    def satellite_lon_deg(self) -> float:
        """Sub-satellite longitude of the grid (degrees east)."""
        return self._grid.lon_0

available_variables property

Every data variable of the file on the grid.

end_time property

Scan end (UTC).

product property

Product code ("CMSK", "CHGT", "CPHS").

satellite property

"Himawari-9" / "Himawari-8".

satellite_lon_deg property

Sub-satellite longitude of the grid (degrees east).

start_time property

Scan start (UTC).

full_disk_grid(resolution_km=2.0)

The nominal AHI full-disk fixed grid at resolution_km.

Parameters:

Name Type Description Default
resolution_km float

0.5, 1.0 or 2.0.

2.0

Raises:

Type Description
KeyError

Not an AHI resolution.

Examples:

>>> grid = full_disk_grid(2.0)
>>> grid.height, grid.width, round(grid.transform.a)
(5500, 5500, 2000)
Source code in packages/geotoolz-products/src/geoproducts/himawari/l2.py
def full_disk_grid(resolution_km: float = 2.0) -> FixedGrid:
    """The nominal AHI full-disk fixed grid at ``resolution_km``.

    Args:
        resolution_km: ``0.5``, ``1.0`` or ``2.0``.

    Raises:
        KeyError: Not an AHI resolution.

    Examples:
        >>> grid = full_disk_grid(2.0)
        >>> grid.height, grid.width, round(grid.transform.a)
        (5500, 5500, 2000)
    """
    size, factor, offset = constants.FULL_DISK_GRIDS[resolution_km]
    return FixedGrid.from_cgms(
        columns=size,
        lines=size,
        cfac=factor,
        lfac=factor,
        coff=offset,
        loff=offset,
        lon_0=constants.HIMAWARI_LON_DEG,
        height_m=constants.SATELLITE_HEIGHT_M,
        semi_major_m=constants.EARTH_SEMI_MAJOR_M,
        semi_minor_m=constants.EARTH_SEMI_MINOR_M,
    )

product_code(name)

The product code of an AHI L2 file name: "CMSK", "CHGT", ….

Returns "" when the name is not a NOAA AHI L2 file name.

Source code in packages/geotoolz-products/src/geoproducts/himawari/l2.py
def product_code(name: str) -> str:
    """The product code of an AHI L2 file name: ``"CMSK"``, ``"CHGT"``, ….

    Returns ``""`` when the name is not a NOAA AHI L2 file name.
    """
    match = _PRODUCT_RE.search(name)
    return match["code"] if match else ""

geoproducts.himawari.aws

Find and fetch Himawari files in NOAA's public buckets on AWS.

NOAA mirrors the JMA Himawari-8 / -9 data to public, anonymous S3 buckets (noaa-himawari8 for the 2015-2022 archive, noaa-himawari9), keyed by product and 10-minute observation slot::

AHI-L1b-FLDK/<yyyy>/<mm>/<dd>/<hhmm>/HS_H09_<yyyymmdd>_<hhmm>_B13_FLDK_R20_S0510.DAT.bz2
AHI-L1b-Japan/...                    HS_H09_..._B13_JP01_R20_S0101.DAT.bz2
AHI-L1b-Target/...                   HS_H09_..._B13_R301_R20_S0101.DAT.bz2
AHI-L2-FLDK-Clouds/...               AHI-CMSK_v1r1_h09_s<start>_e<end>_c<created>.nc

L1b files are one HSD segment of one band (the full disk in 10 segments; the Japan and target areas in one, scanned four times per slot as JP01 … JP04 / R301 … R304). Listing and atomic downloads go unsigned through geocloud.files on the shared obstore pool (no credentials, no AWS SDK; geotoolz-cloud comes with the [himawari] extra).

L2File dataclass

One NOAA AHI L2 object, with its file-name fields parsed.

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
@dataclass(frozen=True)
class L2File:
    """One NOAA AHI L2 object, with its file-name fields parsed."""

    key: str
    satellite: str
    product: str
    start: datetime
    end: datetime
    created: datetime
    size: int | None = None

    @property
    def name(self) -> str:
        """The object's file name."""
        return self.key.rsplit("/", 1)[-1]

    @property
    def url(self) -> str:
        """Public HTTPS URL of the object."""
        return url(self.satellite, self.key)

name property

The object's file name.

url property

Public HTTPS URL of the object.

Segment dataclass

One L1b HSD segment in a NOAA bucket, with its file-name fields parsed.

Attributes:

Name Type Description
key str

Object key.

satellite str

"H08" / "H09".

slot datetime

Nominal 10-minute observation slot (UTC); the Japan / target sub-scans JP02 … start 2.5, 5 and 7.5 minutes later.

band str

"B01" … "B16".

area str

"FLDK", "JP01" … "JP04", "R301" … "R304".

resolution_km float

0.5, 1.0 or 2.0.

segment int

1-based segment number.

total_segments int

Segments of the area (10 for the full disk).

size int | None

Object size (bytes), when listed.

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
@dataclass(frozen=True)
class Segment:
    """One L1b HSD segment in a NOAA bucket, with its file-name fields parsed.

    Attributes:
        key: Object key.
        satellite: ``"H08"`` / ``"H09"``.
        slot: Nominal 10-minute observation slot (UTC); the Japan / target
            sub-scans ``JP02`` … start 2.5, 5 and 7.5 minutes later.
        band: ``"B01"`` … ``"B16"``.
        area: ``"FLDK"``, ``"JP01"`` … ``"JP04"``, ``"R301"`` … ``"R304"``.
        resolution_km: ``0.5``, ``1.0`` or ``2.0``.
        segment: 1-based segment number.
        total_segments: Segments of the area (10 for the full disk).
        size: Object size (bytes), when listed.
    """

    key: str
    satellite: str
    slot: datetime
    band: str
    area: str
    resolution_km: float
    segment: int
    total_segments: int
    size: int | None = None

    @property
    def name(self) -> str:
        """The object's file name."""
        return self.key.rsplit("/", 1)[-1]

    @property
    def url(self) -> str:
        """Public HTTPS URL of the object."""
        return url(self.satellite, self.key)

name property

The object's file name.

url property

Public HTTPS URL of the object.

bucket(satellite)

The NOAA bucket of a Himawari satellite ("H09" / 9 → noaa-himawari9).

Raises:

Type Description
ValueError

satellite is not Himawari-8 or -9.

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def bucket(satellite: str | int) -> str:
    """The NOAA bucket of a Himawari satellite (``"H09"`` / ``9`` → ``noaa-himawari9``).

    Raises:
        ValueError: ``satellite`` is not Himawari-8 or -9.
    """
    return f"noaa-himawari{_satellite_number(satellite)}"

download(file, dest, *, satellite=None, decompress=False, overwrite=False)

Download one object into the directory dest.

The file is streamed to <name>.part and renamed when complete, so an interrupted download never leaves a truncated file behind. An existing file is reused unless overwrite is set.

Parameters:

Name Type Description Default
file Segment | L2File | str

A :class:Segment / :class:L2File from the listings, or an object key.

required
dest str | Path

Destination directory (created if missing).

required
satellite str | int | None

Required when file is a key whose name does not identify the satellite; otherwise read from the file name.

None
decompress bool

Store .DAT.bz2 segments decompressed as .DAT (about 3-4x larger, but memory-mapped by :class:~geoproducts.himawari.Reader, so windows read without decompressing the segment). A .bz2 already in dest is decompressed without downloading it again, and kept.

False
overwrite bool

Re-download even when the file already exists.

False

Returns:

Type Description
Path

Path of the downloaded (or decompressed) file.

Raises:

Type Description
ImportError

geotoolz-cloud is not installed ([himawari] extra).

FileNotFoundError

No such object.

Exception

The download failed (obstore's error; transient errors are retried first).

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def download(
    file: Segment | L2File | str,
    dest: str | Path,
    *,
    satellite: str | int | None = None,
    decompress: bool = False,
    overwrite: bool = False,
) -> Path:
    """Download one object into the directory ``dest``.

    The file is streamed to ``<name>.part`` and renamed when complete, so
    an interrupted download never leaves a truncated file behind. An
    existing file is reused unless ``overwrite`` is set.

    Args:
        file: A :class:`Segment` / :class:`L2File` from the listings, or an
            object key.
        dest: Destination directory (created if missing).
        satellite: Required when ``file`` is a key whose name does not
            identify the satellite; otherwise read from the file name.
        decompress: Store ``.DAT.bz2`` segments decompressed as ``.DAT``
            (about 3-4x larger, but memory-mapped by
            :class:`~geoproducts.himawari.Reader`, so windows read without
            decompressing the segment). A ``.bz2`` already in ``dest`` is
            decompressed without downloading it again, and kept.
        overwrite: Re-download even when the file already exists.

    Returns:
        Path of the downloaded (or decompressed) file.

    Raises:
        ImportError: geotoolz-cloud is not installed (``[himawari]`` extra).
        FileNotFoundError: No such object.
        Exception: The download failed (obstore's error; transient errors
            are retried first).
    """
    item = parse_key(file) if isinstance(file, str) else file
    name = item.name
    unpack = decompress and name.endswith(".bz2")
    target = Path(dest) / (name.removesuffix(".bz2") if unpack else name)
    if target.exists() and not overwrite:
        return target
    local = Path(dest) / name
    # Decompress a ``.bz2`` already on disk (and keep it); otherwise fetch
    # into a hidden temporary file that is removed once decompressed.
    fetch = not unpack or overwrite or not local.exists()
    compressed = local.with_name(f".{name}.download") if unpack and fetch else local
    if fetch:
        s3.download_object(
            bucket(satellite or item.satellite), item.key, compressed, extra="himawari"
        )
    if not unpack:
        return target
    try:
        with (
            bz2.open(compressed, "rb") as src,
            atomic_path(target) as tmp,
            tmp.open("wb") as out,
        ):
            shutil.copyfileobj(src, out, length=1 << 20)
    finally:
        if fetch:
            compressed.unlink(missing_ok=True)
    return target

list_l2(*, start, end=None, satellite='H09', product='CMSK', group='Clouds')

List NOAA AHI L2 full-disk files whose scan starts in [start, end).

Parameters:

Name Type Description Default
start datetime

Window start. Naive datetimes are taken as UTC.

required
end datetime | None

Window end (exclusive). Default: start plus 10 minutes.

None
satellite str | int

"H09" (default) or "H08".

'H09'
product str

Product code: "CMSK" (cloud mask, default), "CHGT" (cloud-top height), "CPHS" (cloud phase).

'CMSK'
group str

Bucket product group (AHI-L2-FLDK-<group>). Default "Clouds".

'Clouds'

Returns:

Type Description
list[L2File]

The matching files, sorted by scan start.

Raises:

Type Description
ValueError

end is not after start, or satellite is out of range.

ImportError

geotoolz-cloud is not installed ([himawari] extra).

Exception

The bucket listing failed (obstore's error).

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def list_l2(
    *,
    start: datetime,
    end: datetime | None = None,
    satellite: str | int = "H09",
    product: str = "CMSK",
    group: str = "Clouds",
) -> list[L2File]:
    """List NOAA AHI L2 full-disk files whose scan starts in ``[start, end)``.

    Args:
        start: Window start. Naive datetimes are taken as UTC.
        end: Window end (exclusive). Default: ``start`` plus 10 minutes.
        satellite: ``"H09"`` (default) or ``"H08"``.
        product: Product code: ``"CMSK"`` (cloud mask, default), ``"CHGT"``
            (cloud-top height), ``"CPHS"`` (cloud phase).
        group: Bucket product group (``AHI-L2-FLDK-<group>``). Default
            ``"Clouds"``.

    Returns:
        The matching files, sorted by scan start.

    Raises:
        ValueError: ``end`` is not after ``start``, or ``satellite`` is out
            of range.
        ImportError: geotoolz-cloud is not installed (``[himawari]`` extra).
        Exception: The bucket listing failed (obstore's error).
    """
    lo = as_utc(start)
    hi = lo + _SLOT if end is None else as_utc(end)
    out: list[L2File] = []
    for key, size in _list_slots(satellite, f"AHI-L2-FLDK-{group}", lo, hi):
        try:
            item = parse_key(key, size=size)
        except ValueError:
            continue
        if (
            isinstance(item, L2File)
            and item.product == product
            and lo <= item.start < hi
        ):
            out.append(item)
    return sorted(out, key=lambda f: (f.start, f.key))

list_segments(*, start, end=None, satellite='H09', sector='FLDK', band=None, area=None, segments=None)

List the L1b HSD segments of the 10-minute slots overlapping [start, end).

Parameters:

Name Type Description Default
start datetime

Window start, rounded down to its slot (03:07 lists the 03:00 slot). Naive datetimes are taken as UTC.

required
end datetime | None

Window end (exclusive). Default: start plus 10 minutes (one slot).

None
satellite str | int

"H09" (default) or "H08" (or 9 / 8).

'H09'
sector Sector

"FLDK" (full disk, default), "Japan" or "Target".

'FLDK'
band int | str | None

Keep one band (13 or "B13"). Default: all 16.

None
area str | None

Keep one sub-scan ("JP01", "R302", …). Default: all.

None
segments int | list[int] | None

Keep these segment numbers (1-based), e.g. the full-disk segments over an area of interest. Default: all.

None

Returns:

Type Description
list[Segment]

The matching segments, sorted by slot, band, area and segment.

Raises:

Type Description
ValueError

end is not after start, or satellite / sector / band is out of range.

ImportError

geotoolz-cloud is not installed ([himawari] extra).

Exception

The bucket listing failed (obstore's error; transient errors are retried first).

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def list_segments(
    *,
    start: datetime,
    end: datetime | None = None,
    satellite: str | int = "H09",
    sector: Sector = "FLDK",
    band: int | str | None = None,
    area: str | None = None,
    segments: int | list[int] | None = None,
) -> list[Segment]:
    """List the L1b HSD segments of the 10-minute slots overlapping ``[start, end)``.

    Args:
        start: Window start, rounded down to its slot (``03:07`` lists the
            ``03:00`` slot). Naive datetimes are taken as UTC.
        end: Window end (exclusive). Default: ``start`` plus 10 minutes
            (one slot).
        satellite: ``"H09"`` (default) or ``"H08"`` (or ``9`` / ``8``).
        sector: ``"FLDK"`` (full disk, default), ``"Japan"`` or ``"Target"``.
        band: Keep one band (``13`` or ``"B13"``). Default: all 16.
        area: Keep one sub-scan (``"JP01"``, ``"R302"``, …). Default: all.
        segments: Keep these segment numbers (1-based), e.g. the full-disk
            segments over an area of interest. Default: all.

    Returns:
        The matching segments, sorted by slot, band, area and segment.

    Raises:
        ValueError: ``end`` is not after ``start``, or ``satellite`` /
            ``sector`` / ``band`` is out of range.
        ImportError: geotoolz-cloud is not installed (``[himawari]`` extra).
        Exception: The bucket listing failed (obstore's error; transient
            errors are retried first).
    """
    if sector not in get_args(Sector):
        raise ValueError(f"sector must be one of {get_args(Sector)}; got {sector!r}.")
    wanted_band = None if band is None else _band_name(band)
    wanted_segments = {segments} if isinstance(segments, int) else segments
    out: list[Segment] = []
    for key, size in _list_slots(satellite, f"AHI-L1b-{sector}", start, end):
        try:
            item = parse_key(key, size=size)
        except ValueError:
            continue
        if not isinstance(item, Segment):
            continue
        if wanted_band is not None and item.band != wanted_band:
            continue
        if area is not None and item.area != area:
            continue
        if wanted_segments is not None and item.segment not in wanted_segments:
            continue
        out.append(item)
    return sorted(out, key=lambda s: (s.slot, s.band, s.area, s.segment))

parse_key(key, *, size=None)

Parse an L1b segment or L2 object key (or bare file name).

Raises:

Type Description
ValueError

key follows neither naming convention.

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def parse_key(key: str, *, size: int | None = None) -> Segment | L2File:
    """Parse an L1b segment or L2 object key (or bare file name).

    Raises:
        ValueError: ``key`` follows neither naming convention.
    """
    match = _SEGMENT_RE.search(key)
    if match is not None:
        return Segment(
            key=key,
            satellite=f"H{match['satellite']}",
            slot=datetime.strptime(match["slot"], "%Y%m%d_%H%M").replace(tzinfo=UTC),
            band=f"B{match['band']}",
            area=match["area"],
            resolution_km=int(match["resolution"]) / 10.0,
            segment=int(match["segment"]),
            total_segments=int(match["total"]),
            size=size,
        )
    match = _L2_RE.search(key)
    if match is not None:
        return L2File(
            key=key,
            satellite=f"H{match['satellite']}",
            product=match["product"],
            start=_parse_stamp(match["start"]),
            end=_parse_stamp(match["end"]),
            created=_parse_stamp(match["created"]),
            size=size,
        )
    raise ValueError(f"not a Himawari HSD segment or L2 file name: {key!r}")

url(satellite, key)

Public HTTPS URL of key in satellite's bucket.

Source code in packages/geotoolz-products/src/geoproducts/himawari/aws.py
def url(satellite: str | int, key: str) -> str:
    """Public HTTPS URL of ``key`` in ``satellite``'s bucket."""
    return s3.object_url(bucket(satellite), key)

geoproducts.himawari.recipes

The standard RGB recipes on AHI bands, as data.

AHI and ABI share their instrument heritage, so the operational RGBs keep the ABI quick-guide stretches (CIRA / JMA) on the equivalent AHI bands. Inputs are AHI band names (band_names of himawari.Reader outputs): reflectance factor (0-1) for B01-B06, brightness temperature (K) for B07-B16, i.e. calibration="reflectance" / "brightness_temperature" reads put on one grid with :func:geoproducts.stack.

himawari.presets turns a recipe into a geoops.viz.RGBRecipe operator; the recipes themselves need no extra.

Recipe dataclass

One RGB recipe: per-channel expression, stretch and gamma.

Attributes:

Name Type Description
name str

Short identifier.

red str

Red-channel band name or band-math expression.

green str

Green-channel band name or expression.

blue str

Blue-channel band name or expression.

vmin tuple[float, float, float]

Per-channel value mapped to 0 (above vmax inverts).

vmax tuple[float, float, float]

Per-channel value mapped to 1.

gamma tuple[float, float, float]

Per-channel display gamma.

channels tuple[str, ...]

Bands the expressions read.

description str

What the composite shows.

Source code in packages/geotoolz-products/src/geoproducts/_src/presets.py
@dataclass(frozen=True)
class Recipe:
    """One RGB recipe: per-channel expression, stretch and gamma.

    Attributes:
        name: Short identifier.
        red: Red-channel band name or band-math expression.
        green: Green-channel band name or expression.
        blue: Blue-channel band name or expression.
        vmin: Per-channel value mapped to 0 (above ``vmax`` inverts).
        vmax: Per-channel value mapped to 1.
        gamma: Per-channel display gamma.
        channels: Bands the expressions read.
        description: What the composite shows.
    """

    name: str
    red: str
    green: str
    blue: str
    vmin: tuple[float, float, float]
    vmax: tuple[float, float, float]
    gamma: tuple[float, float, float]
    channels: tuple[str, ...]
    description: str

geoproducts.himawari.presets

Himawari AHI-aware geotoolz operator presets.

Presets bind geotoolz operators to AHI band names ("B01" … "B16", the band_names of :class:geoproducts.himawari.Reader outputs and of the L2 cloud-mask variables) and to the RGB recipes in :mod:geoproducts.himawari.recipes. geotoolz is an optional dependency (pip install 'geotoolz-products[operators]'), imported when a preset is called, so the readers install without the operator library.

The multi-band presets expect the bands on one grid: readers put together with :func:geoproducts.stack (B03 is at 0.5 km, B01 / B02 / B04 at 1 km, the rest at 2 km).

DayCloudPhase()

Day cloud phase distinction (B13 BT, B03, B05).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def DayCloudPhase() -> Operator:
    """Day cloud phase distinction (B13 BT, B03, B05)."""
    return rgb_recipe(recipes.DAY_CLOUD_PHASE, "himawari.presets.DayCloudPhase")

FireTemperature()

Fire temperature (B07 BT, B06, B05).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def FireTemperature() -> Operator:
    """Fire temperature (B07 BT, B06, B05)."""
    return rgb_recipe(recipes.FIRE_TEMPERATURE, "himawari.presets.FireTemperature")

HybridGreen(*, nir_fraction=constants.HYBRID_GREEN_NIR_FRACTION)

The hybrid green band, (1 - f) · B02 + f · B04.

AHI's green band (0.51 µm) sits below the vegetation reflectance peak, so vegetation looks too dark in true colour; mixing in a little near-infrared restores it. Output is one band, (1, H, W).

Parameters:

Name Type Description Default
nir_fraction float

Share f of the 0.86 µm band. Default 0.07.

HYBRID_GREEN_NIR_FRACTION

Raises:

Type Description
ValueError

nir_fraction is outside [0, 1].

ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def HybridGreen(
    *, nir_fraction: float = constants.HYBRID_GREEN_NIR_FRACTION
) -> Operator:
    """The hybrid green band, ``(1 - f) · B02 + f · B04``.

    AHI's green band (0.51 µm) sits below the vegetation reflectance peak,
    so vegetation looks too dark in true colour; mixing in a little
    near-infrared restores it. Output is one band, ``(1, H, W)``.

    Args:
        nir_fraction: Share ``f`` of the 0.86 µm band. Default ``0.07``.

    Raises:
        ValueError: ``nir_fraction`` is outside ``[0, 1]``.
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    if not 0.0 <= nir_fraction <= 1.0:
        raise ValueError(f"nir_fraction must be in [0, 1]; got {nir_fraction}.")
    expression = f"{1.0 - nir_fraction:g} * B02 + {nir_fraction:g} * B04"
    return _geotoolz("spectral", "HybridGreen").BandMath(expression=expression)

MaskClouds(*, conservative=False)

Cloud mask from the NOAA L2 cloud mask (CMSK), True = cloudy.

Reads the CloudMaskBinary band of a himawari.L2Reader CMSK read. conservative=True reads the four-level CloudMask band instead and also flags probably clear pixels. Pair with gz.mask.ApplyMask once the mask is on the data's grid.

Parameters:

Name Type Description Default
conservative bool

Flag probably-clear pixels as well.

False

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def MaskClouds(*, conservative: bool = False) -> Operator:
    """Cloud mask from the NOAA L2 cloud mask (``CMSK``), ``True`` = cloudy.

    Reads the ``CloudMaskBinary`` band of a ``himawari.L2Reader`` CMSK read.
    ``conservative=True`` reads the four-level ``CloudMask`` band instead and
    also flags *probably clear* pixels. Pair with ``gz.mask.ApplyMask`` once
    the mask is on the data's grid.

    Args:
        conservative: Flag probably-clear pixels as well.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    qa = _geotoolz("qa", "MaskClouds")
    if conservative:
        values = [
            constants.CLOUD_MASK_PROBABLY_CLEAR,
            constants.CLOUD_MASK_PROBABLY_CLOUDY,
            constants.CLOUD_MASK_CLOUDY,
        ]
        return qa.MaskClouds(qa_band="CloudMask", values=values)
    return qa.MaskClouds(
        qa_band="CloudMaskBinary", values=[constants.CLOUD_MASK_BINARY_CLOUDY]
    )

NDVI()

NDVI from AHI reflectance: red="B03", nir="B04".

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def NDVI() -> Operator:
    """NDVI from AHI reflectance: ``red="B03"``, ``nir="B04"``.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    return _geotoolz("indices", "NDVI").NDVI(red="B03", nir="B04")

NaturalColor()

Day land cloud "natural colour" (B05, B04, B03).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def NaturalColor() -> Operator:
    """Day land cloud "natural colour" (B05, B04, B03)."""
    return rgb_recipe(recipes.NATURAL_COLOR, "himawari.presets.NaturalColor")

ParallaxCorrect(*, satellite_lon_deg=constants.HIMAWARI_LON_DEG, target_height_m=0.0, method='bilinear')

Geostationary parallax correction from the Himawari viewpoint (140.7°E).

Binds gz.geom.GeostationaryParallaxCorrect to the Himawari height; the input must already be on an EPSG:4326 grid. Pass the cloud-top height (on the same grid) as target_height_m to move clouds to where they are.

Parameters:

Name Type Description Default
satellite_lon_deg float

Sub-satellite longitude. Default 140.7°E.

HIMAWARI_LON_DEG
target_height_m Any

Height of the observed feature (metres): a scalar, a same-grid array or a same-grid GeoArray.

0.0
method str

"nearest" or "bilinear".

'bilinear'

Raises:

Type Description
ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def ParallaxCorrect(
    *,
    satellite_lon_deg: float = constants.HIMAWARI_LON_DEG,
    target_height_m: Any = 0.0,
    method: str = "bilinear",
) -> Operator:
    """Geostationary parallax correction from the Himawari viewpoint (140.7°E).

    Binds ``gz.geom.GeostationaryParallaxCorrect`` to the Himawari height;
    the input must already be on an EPSG:4326 grid. Pass the cloud-top
    height (on the same grid) as ``target_height_m`` to move clouds to where
    they are.

    Args:
        satellite_lon_deg: Sub-satellite longitude. Default 140.7°E.
        target_height_m: Height of the observed feature (metres): a scalar,
            a same-grid array or a same-grid GeoArray.
        method: ``"nearest"`` or ``"bilinear"``.

    Raises:
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    return parallax_correct(
        "himawari.presets.ParallaxCorrect",
        satellite_lon_deg=satellite_lon_deg,
        satellite_height_m=constants.SATELLITE_HEIGHT_M,
        target_height_m=target_height_m,
        method=method,
    )

Recipe(recipe)

A gz.viz.RGBRecipe for one of :data:himawari.recipes.RECIPES.

Parameters:

Name Type Description Default
recipe Recipe | str

A :class:~geoproducts.himawari.recipes.Recipe, or its name ("true_color", "natural_color", "day_cloud_phase", "fire_temperature").

required

Returns:

Type Description
Operator

An operator mapping a band-named stack to a (3, H, W)

Operator

float32 RGB in [0, 1].

Raises:

Type Description
KeyError

Unknown recipe name.

ImportError

geotoolz is not installed (the [operators] extra).

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def Recipe(recipe: recipes.Recipe | str) -> Operator:
    """A ``gz.viz.RGBRecipe`` for one of :data:`himawari.recipes.RECIPES`.

    Args:
        recipe: A :class:`~geoproducts.himawari.recipes.Recipe`, or its name
            (``"true_color"``, ``"natural_color"``, ``"day_cloud_phase"``,
            ``"fire_temperature"``).

    Returns:
        An operator mapping a band-named stack to a ``(3, H, W)``
        ``float32`` RGB in ``[0, 1]``.

    Raises:
        KeyError: Unknown recipe name.
        ImportError: geotoolz is not installed (the ``[operators]`` extra).
    """
    spec = recipes.RECIPES[recipe] if isinstance(recipe, str) else recipe
    return rgb_recipe(spec, "himawari.presets.Recipe")

TrueColor()

True colour (B03, hybrid green, B01), gamma 2.2. Reads B01-B04.

Source code in packages/geotoolz-products/src/geoproducts/himawari/presets.py
def TrueColor() -> Operator:
    """True colour (B03, hybrid green, B01), gamma 2.2. Reads B01-B04."""
    return rgb_recipe(recipes.TRUE_COLOR, "himawari.presets.TrueColor")

geoproducts.himawari.constants

Himawari AHI band table, fixed grids, cloud-mask codes and orbit constants.

geoproducts.carbonmapper

The Carbon Mapper plume catalogue and STAC client, typed records and rasters (guide; [carbonmapper] extra).

geoproducts.carbonmapper.config

config.py

Lightweight credentials and configuration handler for the Carbon Mapper Data Platform API.

Credentials can be supplied in three ways (checked in priority order):

  1. Environment variables — set CARBONMAPPER_TOKEN (access token), CARBONMAPPER_EMAIL and CARBONMAPPER_PASSWORD (login credentials).
  2. Config file — a JSON file at one of the well-known paths listed in :data:CONFIG_SEARCH_PATHS, or a custom path passed to :meth:CarbonMapperConfig.load. The canonical location is ~/.geoproducts/auth_carbonmapper.json (one auth_<provider>.json per provider).
  3. Explicit arguments — pass token= directly to API functions in download.py.

If no config file exists when :meth:CarbonMapperConfig.load is called without an explicit path and no env-var credentials are set, a placeholder ~/.geoproducts/auth_carbonmapper.json is auto-created with stub values so users have a clear edit target.

Quick start

from geoproducts.carbonmapper.config import CarbonMapperConfig cfg = CarbonMapperConfig.load() token = cfg.get_token() # resolves from env var or file

— or — log in once and keep the tokens for later sessions:

cfg = CarbonMapperConfig(email="user@example.com", password="s3cret") token = cfg.refresh_access_token() cfg.save() # ~/.geoproducts/auth_carbonmapper.json: email + tokens, no password

References

  • API docs : https://api.carbonmapper.org/api/v1/docs
  • Registration : https://data.carbonmapper.org

CarbonMapperConfig

Simple credentials and configuration container for the Carbon Mapper API.

Attributes

token: A pre-obtained JWT bearer token. If set, it takes precedence over email / password when :meth:get_token is called. email: Registered Carbon Mapper account e-mail address. password: Account password. Held in memory only: :meth:save never writes it, and it is never sent anywhere except the token endpoint. A "password" a user put in the config file by hand is still read. extra: Any additional key/value pairs loaded from or saved to the config file (for forward compatibility).

Examples

Load from environment or disk and retrieve a usable token:

cfg = CarbonMapperConfig.load() token = cfg.get_token() # may return None if no credentials found if token: ... data = get_plumes_annotated(plume_gas="CH4", token=token)

Log in once and keep the tokens (not the password) for later sessions:

cfg = CarbonMapperConfig(email="user@example.com", password="s3cret") cfg.refresh_access_token() cfg.save()

Reset (delete) the stored config file:

CarbonMapperConfig.reset()

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
class CarbonMapperConfig:
    """Simple credentials and configuration container for the Carbon Mapper API.

    Attributes
    ----------
    token:
        A pre-obtained JWT bearer token.  If set, it takes precedence over
        *email* / *password* when :meth:`get_token` is called.
    email:
        Registered Carbon Mapper account e-mail address.
    password:
        Account password.  Held in memory only: :meth:`save` never writes
        it, and it is never sent anywhere except the token endpoint. A
        ``"password"`` a user put in the config file by hand is still read.
    extra:
        Any additional key/value pairs loaded from or saved to the config
        file (for forward compatibility).

    Examples
    --------
    Load from environment or disk and retrieve a usable token:

    >>> cfg = CarbonMapperConfig.load()
    >>> token = cfg.get_token()  # may return None if no credentials found
    >>> if token:
    ...     data = get_plumes_annotated(plume_gas="CH4", token=token)

    Log in once and keep the tokens (not the password) for later sessions:

    >>> cfg = CarbonMapperConfig(email="user@example.com", password="s3cret")
    >>> cfg.refresh_access_token()
    >>> cfg.save()

    Reset (delete) the stored config file:

    >>> CarbonMapperConfig.reset()
    """

    def __init__(
        self,
        *,
        token: str | None = None,
        email: str | None = None,
        password: str | None = None,
        **extra: Any,
    ) -> None:
        self.token = token
        self.email = email
        self.password = password
        self.extra: dict[str, Any] = extra

    # ------------------------------------------------------------------ #
    # Class-level factory / persistence methods                            #
    # ------------------------------------------------------------------ #

    @classmethod
    def from_env(cls) -> CarbonMapperConfig:
        """Build a :class:`CarbonMapperConfig` purely from environment variables.

        Reads :envvar:`CARBONMAPPER_TOKEN`, :envvar:`CARBONMAPPER_EMAIL`,
        and :envvar:`CARBONMAPPER_PASSWORD`.  Fields that are absent from
        the environment are left as ``None``.

        Returns
        -------
        CarbonMapperConfig
            A new config object populated from the environment.

        Examples
        --------
        >>> import os
        >>> os.environ["CARBONMAPPER_TOKEN"] = "eyJ..."
        >>> cfg = CarbonMapperConfig.from_env()
        >>> cfg.token
        'eyJ...'
        """
        return cls(
            token=os.environ.get(_ENV_TOKEN),
            email=os.environ.get(_ENV_EMAIL),
            password=os.environ.get(_ENV_PASSWORD),
        )

    @classmethod
    def from_file(cls, path: Path | str) -> CarbonMapperConfig:
        """Load a :class:`CarbonMapperConfig` from a specific JSON file.

        Parameters
        ----------
        path:
            Path to a JSON config file containing any combination of the
            keys ``"token"``, ``"email"``, ``"password"``, plus any extra
            fields.

        Returns
        -------
        CarbonMapperConfig
            Config populated from the file.

        Raises
        ------
        FileNotFoundError
            If *path* does not exist.
        json.JSONDecodeError
            If the file cannot be parsed as JSON.

        Examples
        --------
        >>> cfg = CarbonMapperConfig.from_file("~/.geoproducts/auth_carbonmapper.json")
        """
        data = read_json_config(Path(path).expanduser().resolve())
        token = data.pop("token", None)
        email = data.pop("email", None) or data.pop("username", None)
        password = data.pop("password", None)
        # Filter stub values — if the user hasn't yet edited a freshly
        # auto-created placeholder, treat the fields as un-set rather
        # than letting ``"SET-EMAIL"`` flow into has_credentials() as
        # if it were a real value.
        if email == _PLACEHOLDER_EMAIL:
            email = None
        if password == _PLACEHOLDER_PASSWORD:
            password = None
        return cls(token=token, email=email, password=password, **data)

    @classmethod
    def load(
        cls,
        path: Path | str | None = None,
        *,
        create_placeholder: bool = True,
    ) -> CarbonMapperConfig:
        """Load config using the standard resolution order.

        Resolution order
        ~~~~~~~~~~~~~~~~
        1. If *path* is given, load that file.
        2. Otherwise search :data:`CONFIG_SEARCH_PATHS` for the first file
           that exists.
        3. Overlay environment variables — env values overwrite file values.
        4. If still nothing is configured (no file found, no env vars set)
           AND ``create_placeholder`` is True, write a stub config to
           :data:`DEFAULT_SAVE_PATH` with ``SET-EMAIL`` / ``SET-PASSWORD``
           placeholders so users have a clear edit target.

        Parameters
        ----------
        path:
            Optional explicit path to a config file.  Skips the search
            when provided.
        create_placeholder:
            When ``True`` (default), auto-create a stub config file at
            :data:`DEFAULT_SAVE_PATH` if no credentials could be
            resolved. Set to ``False`` in tests / non-interactive
            contexts to keep the filesystem untouched.

        Returns
        -------
        CarbonMapperConfig
            The resolved config.  Fields without a value (from file *and*
            env) are ``None``.

        Examples
        --------
        >>> cfg = CarbonMapperConfig.load()
        >>> print(cfg.email)   # None if not configured

        >>> cfg = CarbonMapperConfig.load("~/my_project/.carbonmapper.json")
        """
        cfg: CarbonMapperConfig | None = None
        loaded_from_file = False

        # 1. Explicit path
        if path is not None:
            resolved = Path(path).expanduser().resolve()
            if resolved.exists():
                try:
                    cfg = cls.from_file(resolved)
                    loaded_from_file = True
                    logger.debug("Loaded Carbon Mapper config from %s", resolved)
                except Exception as exc:
                    logger.warning("Failed to load config from %s: %s", resolved, exc)
            else:
                logger.warning("Config path %s does not exist; ignoring.", resolved)

        # 2. Search well-known paths (only without an explicit path: a
        # missing or broken one must not silently pick up another
        # account's credentials).
        if cfg is None and path is None:
            for candidate in CONFIG_SEARCH_PATHS:
                resolved_candidate = candidate.expanduser().resolve()
                if resolved_candidate.exists():
                    try:
                        cfg = cls.from_file(resolved_candidate)
                        loaded_from_file = True
                        logger.debug(
                            "Loaded Carbon Mapper config from %s", resolved_candidate
                        )
                        break
                    except Exception as exc:
                        logger.warning(
                            "Failed to load config from %s: %s",
                            resolved_candidate,
                            exc,
                        )

        if cfg is None:
            cfg = cls()

        # 3. Overlay environment variables (env takes priority over file)
        env_token = os.environ.get(_ENV_TOKEN)
        env_email = os.environ.get(_ENV_EMAIL)
        env_password = os.environ.get(_ENV_PASSWORD)
        if env_token:
            cfg.token = env_token
        if env_email:
            cfg.email = env_email
        if env_password:
            cfg.password = env_password

        # 4. Placeholder — only when caller didn't pass an explicit path,
        #    no config file was found, and env vars didn't supply creds.
        if (
            create_placeholder
            and path is None
            and not loaded_from_file
            and not cfg.has_credentials()
        ):
            _create_placeholder_config()

        return cfg

    # ------------------------------------------------------------------ #
    # Persistence                                                          #
    # ------------------------------------------------------------------ #

    def save(self, path: Path | str | None = None) -> Path:
        """Persist the config — email, tokens, extras — to a JSON file.

        The password is never written: the stored refresh token renews the
        access token (see :meth:`get_token`), and the password, when
        renewal needs it again, comes from ``CARBONMAPPER_PASSWORD`` or the
        constructor.

        Parameters
        ----------
        path:
            Destination file path.  Defaults to
            :data:`DEFAULT_SAVE_PATH`
            (``~/.geoproducts/auth_carbonmapper.json``), a user-level
            location outside the working tree so credentials are never
            accidentally committed.

        Returns
        -------
        Path
            The resolved path of the file that was written.

        Examples
        --------
        >>> cfg = CarbonMapperConfig(email="user@example.com", password="s3cret")
        >>> cfg.refresh_access_token()
        >>> saved_path = cfg.save()
        >>> print(saved_path)
        /home/user/.geoproducts/auth_carbonmapper.json
        """
        if path is not None:
            dest = Path(path).expanduser().resolve()
        else:
            dest = DEFAULT_SAVE_PATH.expanduser().resolve()
        data: dict[str, Any] = {**self.extra}
        if self.token is not None:
            data["token"] = self.token
        if self.email is not None:
            data["email"] = self.email
        # Owner-only (0600) from the first byte, renamed into place: the
        # credentials are never readable by other users, not even briefly,
        # and a crash leaves no torn file.
        write_private_json(dest, data)
        logger.info("Carbon Mapper config saved to %s", dest)
        return dest

    @classmethod
    def reset(cls, path: Path | str | None = None) -> None:
        """Delete the stored config file, if it exists.

        Parameters
        ----------
        path:
            Path to the config file to remove.  Defaults to
            :data:`DEFAULT_SAVE_PATH`
            (``~/.geoproducts/auth_carbonmapper.json``).

        Examples
        --------
        >>> CarbonMapperConfig.reset()  # removes ~/.geoproducts/auth_carbonmapper.json
        """
        dest = (
            Path(path).expanduser().resolve()
            if path is not None
            else DEFAULT_SAVE_PATH.expanduser().resolve()
        )
        if dest.exists():
            dest.unlink()
            logger.info("Carbon Mapper config removed: %s", dest)
        else:
            logger.debug("No config file to remove at %s", dest)

    # ------------------------------------------------------------------ #
    # Token resolution                                                     #
    # ------------------------------------------------------------------ #

    def get_token(self) -> str | None:
        """Return the best available bearer token.

        1. No :attr:`token` → return ``None`` — callers that need one
           call :meth:`refresh_access_token` (or
           :func:`~geoproducts.carbonmapper.download.obtain_token`).
        2. :attr:`token` is not a readable JWT, or expires more than
           :data:`TOKEN_EXPIRY_MARGIN_S` from now → return it as is.
        3. It has expired (or is about to): renew it with the stored
           refresh token (``extra["refresh"]``) when there is one, else
           with :attr:`email` / :attr:`password`, and return the new
           access token.
        4. If neither renewal source exists (or the refresh token is
           rejected and no credentials are set), return the stale token
           — the API's 401 then tells the caller why.

        Returns
        -------
        str or None
            A JWT bearer token string, or ``None`` if none is configured.

        Examples
        --------
        >>> cfg = CarbonMapperConfig.load()
        >>> token = cfg.get_token()
        >>> if token is None:
        ...     token = cfg.refresh_access_token()
        """
        if not self.token:
            return None
        expiry = jwt_expiry(self.token)
        if expiry is None or expiry - time.time() > TOKEN_EXPIRY_MARGIN_S:
            return self.token

        refresh = self.extra.get("refresh")
        if refresh:
            from geoproducts.carbonmapper.download import refresh_token

            try:
                tokens = refresh_token(refresh)
            except Exception as exc:
                logger.warning("Carbon Mapper token refresh failed (%s)", exc)
            else:
                self.token = tokens["access"]
                if tokens.get("refresh"):
                    self.extra["refresh"] = tokens["refresh"]
                logger.info("Carbon Mapper access token refreshed")
                return self.token
        if self.email and self.password:
            return self.refresh_access_token()
        logger.warning(
            "Carbon Mapper access token has expired and no refresh token or "
            "credentials are configured to renew it."
        )
        return self.token

    def refresh_access_token(self) -> str:
        """Obtain a fresh JWT access token using stored email/password.

        Calls :func:`~geoproducts.carbonmapper.download.obtain_token` with the
        stored :attr:`email` and :attr:`password`, updates :attr:`token`
        in-place, and returns the new access token.

        Returns
        -------
        str
            The new JWT access token.

        Raises
        ------
        ValueError
            If *email* or *password* is not set.
        requests.HTTPError
            If the Carbon Mapper API rejects the credentials.

        Examples
        --------
        >>> cfg = CarbonMapperConfig.load()  # ~/.geoproducts/auth_carbonmapper.json
        >>> token = cfg.refresh_access_token()
        """
        if not self.email or not self.password:
            raise ValueError(
                "Cannot refresh token: email and password are required. "
                "Provide them via config file, environment variables, or "
                "constructor arguments."
            )
        from geoproducts.carbonmapper.download import obtain_token

        tokens = obtain_token(self.email, self.password)
        self.token = tokens["access"]
        self.extra["refresh"] = tokens.get("refresh")
        logger.info("Carbon Mapper access token refreshed for %s", self.email)
        return self.token

    def has_credentials(self) -> bool:
        """Return ``True`` if any usable credentials are present.

        A config is considered to have credentials when at least one of the
        following is set: :attr:`token`, or both :attr:`email` *and*
        :attr:`password`.

        Examples
        --------
        >>> cfg = CarbonMapperConfig(email="u@example.com", password="pw")
        >>> cfg.has_credentials()
        True
        >>> CarbonMapperConfig().has_credentials()
        False
        """
        return bool(self.token) or bool(self.email and self.password)

    # ------------------------------------------------------------------ #
    # String representations                                               #
    # ------------------------------------------------------------------ #

    def __repr__(self) -> str:
        return (
            f"CarbonMapperConfig("
            f"email={self.email!r}, "
            f"has_token={self.token is not None}, "
            f"has_password={self.password is not None}"
            f")"
        )

from_env() classmethod

Build a :class:CarbonMapperConfig purely from environment variables.

Reads :envvar:CARBONMAPPER_TOKEN, :envvar:CARBONMAPPER_EMAIL, and :envvar:CARBONMAPPER_PASSWORD. Fields that are absent from the environment are left as None.

Returns

CarbonMapperConfig A new config object populated from the environment.

Examples

import os os.environ["CARBONMAPPER_TOKEN"] = "eyJ..." cfg = CarbonMapperConfig.from_env() cfg.token 'eyJ...'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
@classmethod
def from_env(cls) -> CarbonMapperConfig:
    """Build a :class:`CarbonMapperConfig` purely from environment variables.

    Reads :envvar:`CARBONMAPPER_TOKEN`, :envvar:`CARBONMAPPER_EMAIL`,
    and :envvar:`CARBONMAPPER_PASSWORD`.  Fields that are absent from
    the environment are left as ``None``.

    Returns
    -------
    CarbonMapperConfig
        A new config object populated from the environment.

    Examples
    --------
    >>> import os
    >>> os.environ["CARBONMAPPER_TOKEN"] = "eyJ..."
    >>> cfg = CarbonMapperConfig.from_env()
    >>> cfg.token
    'eyJ...'
    """
    return cls(
        token=os.environ.get(_ENV_TOKEN),
        email=os.environ.get(_ENV_EMAIL),
        password=os.environ.get(_ENV_PASSWORD),
    )

from_file(path) classmethod

Load a :class:CarbonMapperConfig from a specific JSON file.

Parameters

path: Path to a JSON config file containing any combination of the keys "token", "email", "password", plus any extra fields.

Returns

CarbonMapperConfig Config populated from the file.

Raises

FileNotFoundError If path does not exist. json.JSONDecodeError If the file cannot be parsed as JSON.

Examples

cfg = CarbonMapperConfig.from_file("~/.geoproducts/auth_carbonmapper.json")

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
@classmethod
def from_file(cls, path: Path | str) -> CarbonMapperConfig:
    """Load a :class:`CarbonMapperConfig` from a specific JSON file.

    Parameters
    ----------
    path:
        Path to a JSON config file containing any combination of the
        keys ``"token"``, ``"email"``, ``"password"``, plus any extra
        fields.

    Returns
    -------
    CarbonMapperConfig
        Config populated from the file.

    Raises
    ------
    FileNotFoundError
        If *path* does not exist.
    json.JSONDecodeError
        If the file cannot be parsed as JSON.

    Examples
    --------
    >>> cfg = CarbonMapperConfig.from_file("~/.geoproducts/auth_carbonmapper.json")
    """
    data = read_json_config(Path(path).expanduser().resolve())
    token = data.pop("token", None)
    email = data.pop("email", None) or data.pop("username", None)
    password = data.pop("password", None)
    # Filter stub values — if the user hasn't yet edited a freshly
    # auto-created placeholder, treat the fields as un-set rather
    # than letting ``"SET-EMAIL"`` flow into has_credentials() as
    # if it were a real value.
    if email == _PLACEHOLDER_EMAIL:
        email = None
    if password == _PLACEHOLDER_PASSWORD:
        password = None
    return cls(token=token, email=email, password=password, **data)

get_token()

Return the best available bearer token.

  1. No :attr:token → return None — callers that need one call :meth:refresh_access_token (or :func:~geoproducts.carbonmapper.download.obtain_token).
  2. :attr:token is not a readable JWT, or expires more than :data:TOKEN_EXPIRY_MARGIN_S from now → return it as is.
  3. It has expired (or is about to): renew it with the stored refresh token (extra["refresh"]) when there is one, else with :attr:email / :attr:password, and return the new access token.
  4. If neither renewal source exists (or the refresh token is rejected and no credentials are set), return the stale token — the API's 401 then tells the caller why.
Returns

str or None A JWT bearer token string, or None if none is configured.

Examples

cfg = CarbonMapperConfig.load() token = cfg.get_token() if token is None: ... token = cfg.refresh_access_token()

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
def get_token(self) -> str | None:
    """Return the best available bearer token.

    1. No :attr:`token` → return ``None`` — callers that need one
       call :meth:`refresh_access_token` (or
       :func:`~geoproducts.carbonmapper.download.obtain_token`).
    2. :attr:`token` is not a readable JWT, or expires more than
       :data:`TOKEN_EXPIRY_MARGIN_S` from now → return it as is.
    3. It has expired (or is about to): renew it with the stored
       refresh token (``extra["refresh"]``) when there is one, else
       with :attr:`email` / :attr:`password`, and return the new
       access token.
    4. If neither renewal source exists (or the refresh token is
       rejected and no credentials are set), return the stale token
       — the API's 401 then tells the caller why.

    Returns
    -------
    str or None
        A JWT bearer token string, or ``None`` if none is configured.

    Examples
    --------
    >>> cfg = CarbonMapperConfig.load()
    >>> token = cfg.get_token()
    >>> if token is None:
    ...     token = cfg.refresh_access_token()
    """
    if not self.token:
        return None
    expiry = jwt_expiry(self.token)
    if expiry is None or expiry - time.time() > TOKEN_EXPIRY_MARGIN_S:
        return self.token

    refresh = self.extra.get("refresh")
    if refresh:
        from geoproducts.carbonmapper.download import refresh_token

        try:
            tokens = refresh_token(refresh)
        except Exception as exc:
            logger.warning("Carbon Mapper token refresh failed (%s)", exc)
        else:
            self.token = tokens["access"]
            if tokens.get("refresh"):
                self.extra["refresh"] = tokens["refresh"]
            logger.info("Carbon Mapper access token refreshed")
            return self.token
    if self.email and self.password:
        return self.refresh_access_token()
    logger.warning(
        "Carbon Mapper access token has expired and no refresh token or "
        "credentials are configured to renew it."
    )
    return self.token

has_credentials()

Return True if any usable credentials are present.

A config is considered to have credentials when at least one of the following is set: :attr:token, or both :attr:email and :attr:password.

Examples

cfg = CarbonMapperConfig(email="u@example.com", password="pw") cfg.has_credentials() True CarbonMapperConfig().has_credentials() False

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
def has_credentials(self) -> bool:
    """Return ``True`` if any usable credentials are present.

    A config is considered to have credentials when at least one of the
    following is set: :attr:`token`, or both :attr:`email` *and*
    :attr:`password`.

    Examples
    --------
    >>> cfg = CarbonMapperConfig(email="u@example.com", password="pw")
    >>> cfg.has_credentials()
    True
    >>> CarbonMapperConfig().has_credentials()
    False
    """
    return bool(self.token) or bool(self.email and self.password)

load(path=None, *, create_placeholder=True) classmethod

Load config using the standard resolution order.

Resolution order ~~~~~~~~~~~~~~~~ 1. If path is given, load that file. 2. Otherwise search :data:CONFIG_SEARCH_PATHS for the first file that exists. 3. Overlay environment variables — env values overwrite file values. 4. If still nothing is configured (no file found, no env vars set) AND create_placeholder is True, write a stub config to :data:DEFAULT_SAVE_PATH with SET-EMAIL / SET-PASSWORD placeholders so users have a clear edit target.

Parameters

path: Optional explicit path to a config file. Skips the search when provided. create_placeholder: When True (default), auto-create a stub config file at :data:DEFAULT_SAVE_PATH if no credentials could be resolved. Set to False in tests / non-interactive contexts to keep the filesystem untouched.

Returns

CarbonMapperConfig The resolved config. Fields without a value (from file and env) are None.

Examples

cfg = CarbonMapperConfig.load() print(cfg.email) # None if not configured

cfg = CarbonMapperConfig.load("~/my_project/.carbonmapper.json")

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
@classmethod
def load(
    cls,
    path: Path | str | None = None,
    *,
    create_placeholder: bool = True,
) -> CarbonMapperConfig:
    """Load config using the standard resolution order.

    Resolution order
    ~~~~~~~~~~~~~~~~
    1. If *path* is given, load that file.
    2. Otherwise search :data:`CONFIG_SEARCH_PATHS` for the first file
       that exists.
    3. Overlay environment variables — env values overwrite file values.
    4. If still nothing is configured (no file found, no env vars set)
       AND ``create_placeholder`` is True, write a stub config to
       :data:`DEFAULT_SAVE_PATH` with ``SET-EMAIL`` / ``SET-PASSWORD``
       placeholders so users have a clear edit target.

    Parameters
    ----------
    path:
        Optional explicit path to a config file.  Skips the search
        when provided.
    create_placeholder:
        When ``True`` (default), auto-create a stub config file at
        :data:`DEFAULT_SAVE_PATH` if no credentials could be
        resolved. Set to ``False`` in tests / non-interactive
        contexts to keep the filesystem untouched.

    Returns
    -------
    CarbonMapperConfig
        The resolved config.  Fields without a value (from file *and*
        env) are ``None``.

    Examples
    --------
    >>> cfg = CarbonMapperConfig.load()
    >>> print(cfg.email)   # None if not configured

    >>> cfg = CarbonMapperConfig.load("~/my_project/.carbonmapper.json")
    """
    cfg: CarbonMapperConfig | None = None
    loaded_from_file = False

    # 1. Explicit path
    if path is not None:
        resolved = Path(path).expanduser().resolve()
        if resolved.exists():
            try:
                cfg = cls.from_file(resolved)
                loaded_from_file = True
                logger.debug("Loaded Carbon Mapper config from %s", resolved)
            except Exception as exc:
                logger.warning("Failed to load config from %s: %s", resolved, exc)
        else:
            logger.warning("Config path %s does not exist; ignoring.", resolved)

    # 2. Search well-known paths (only without an explicit path: a
    # missing or broken one must not silently pick up another
    # account's credentials).
    if cfg is None and path is None:
        for candidate in CONFIG_SEARCH_PATHS:
            resolved_candidate = candidate.expanduser().resolve()
            if resolved_candidate.exists():
                try:
                    cfg = cls.from_file(resolved_candidate)
                    loaded_from_file = True
                    logger.debug(
                        "Loaded Carbon Mapper config from %s", resolved_candidate
                    )
                    break
                except Exception as exc:
                    logger.warning(
                        "Failed to load config from %s: %s",
                        resolved_candidate,
                        exc,
                    )

    if cfg is None:
        cfg = cls()

    # 3. Overlay environment variables (env takes priority over file)
    env_token = os.environ.get(_ENV_TOKEN)
    env_email = os.environ.get(_ENV_EMAIL)
    env_password = os.environ.get(_ENV_PASSWORD)
    if env_token:
        cfg.token = env_token
    if env_email:
        cfg.email = env_email
    if env_password:
        cfg.password = env_password

    # 4. Placeholder — only when caller didn't pass an explicit path,
    #    no config file was found, and env vars didn't supply creds.
    if (
        create_placeholder
        and path is None
        and not loaded_from_file
        and not cfg.has_credentials()
    ):
        _create_placeholder_config()

    return cfg

refresh_access_token()

Obtain a fresh JWT access token using stored email/password.

Calls :func:~geoproducts.carbonmapper.download.obtain_token with the stored :attr:email and :attr:password, updates :attr:token in-place, and returns the new access token.

Returns

str The new JWT access token.

Raises

ValueError If email or password is not set. requests.HTTPError If the Carbon Mapper API rejects the credentials.

Examples

cfg = CarbonMapperConfig.load() # ~/.geoproducts/auth_carbonmapper.json token = cfg.refresh_access_token()

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
def refresh_access_token(self) -> str:
    """Obtain a fresh JWT access token using stored email/password.

    Calls :func:`~geoproducts.carbonmapper.download.obtain_token` with the
    stored :attr:`email` and :attr:`password`, updates :attr:`token`
    in-place, and returns the new access token.

    Returns
    -------
    str
        The new JWT access token.

    Raises
    ------
    ValueError
        If *email* or *password* is not set.
    requests.HTTPError
        If the Carbon Mapper API rejects the credentials.

    Examples
    --------
    >>> cfg = CarbonMapperConfig.load()  # ~/.geoproducts/auth_carbonmapper.json
    >>> token = cfg.refresh_access_token()
    """
    if not self.email or not self.password:
        raise ValueError(
            "Cannot refresh token: email and password are required. "
            "Provide them via config file, environment variables, or "
            "constructor arguments."
        )
    from geoproducts.carbonmapper.download import obtain_token

    tokens = obtain_token(self.email, self.password)
    self.token = tokens["access"]
    self.extra["refresh"] = tokens.get("refresh")
    logger.info("Carbon Mapper access token refreshed for %s", self.email)
    return self.token

reset(path=None) classmethod

Delete the stored config file, if it exists.

Parameters

path: Path to the config file to remove. Defaults to :data:DEFAULT_SAVE_PATH (~/.geoproducts/auth_carbonmapper.json).

Examples

CarbonMapperConfig.reset() # removes ~/.geoproducts/auth_carbonmapper.json

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
@classmethod
def reset(cls, path: Path | str | None = None) -> None:
    """Delete the stored config file, if it exists.

    Parameters
    ----------
    path:
        Path to the config file to remove.  Defaults to
        :data:`DEFAULT_SAVE_PATH`
        (``~/.geoproducts/auth_carbonmapper.json``).

    Examples
    --------
    >>> CarbonMapperConfig.reset()  # removes ~/.geoproducts/auth_carbonmapper.json
    """
    dest = (
        Path(path).expanduser().resolve()
        if path is not None
        else DEFAULT_SAVE_PATH.expanduser().resolve()
    )
    if dest.exists():
        dest.unlink()
        logger.info("Carbon Mapper config removed: %s", dest)
    else:
        logger.debug("No config file to remove at %s", dest)

save(path=None)

Persist the config — email, tokens, extras — to a JSON file.

The password is never written: the stored refresh token renews the access token (see :meth:get_token), and the password, when renewal needs it again, comes from CARBONMAPPER_PASSWORD or the constructor.

Parameters

path: Destination file path. Defaults to :data:DEFAULT_SAVE_PATH (~/.geoproducts/auth_carbonmapper.json), a user-level location outside the working tree so credentials are never accidentally committed.

Returns

Path The resolved path of the file that was written.

Examples

cfg = CarbonMapperConfig(email="user@example.com", password="s3cret") cfg.refresh_access_token() saved_path = cfg.save() print(saved_path) /home/user/.geoproducts/auth_carbonmapper.json

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/config.py
def save(self, path: Path | str | None = None) -> Path:
    """Persist the config — email, tokens, extras — to a JSON file.

    The password is never written: the stored refresh token renews the
    access token (see :meth:`get_token`), and the password, when
    renewal needs it again, comes from ``CARBONMAPPER_PASSWORD`` or the
    constructor.

    Parameters
    ----------
    path:
        Destination file path.  Defaults to
        :data:`DEFAULT_SAVE_PATH`
        (``~/.geoproducts/auth_carbonmapper.json``), a user-level
        location outside the working tree so credentials are never
        accidentally committed.

    Returns
    -------
    Path
        The resolved path of the file that was written.

    Examples
    --------
    >>> cfg = CarbonMapperConfig(email="user@example.com", password="s3cret")
    >>> cfg.refresh_access_token()
    >>> saved_path = cfg.save()
    >>> print(saved_path)
    /home/user/.geoproducts/auth_carbonmapper.json
    """
    if path is not None:
        dest = Path(path).expanduser().resolve()
    else:
        dest = DEFAULT_SAVE_PATH.expanduser().resolve()
    data: dict[str, Any] = {**self.extra}
    if self.token is not None:
        data["token"] = self.token
    if self.email is not None:
        data["email"] = self.email
    # Owner-only (0600) from the first byte, renamed into place: the
    # credentials are never readable by other users, not even briefly,
    # and a crash leaves no torn file.
    write_private_json(dest, data)
    logger.info("Carbon Mapper config saved to %s", dest)
    return dest

geoproducts.carbonmapper.api_queries

High-level typed queries over the Carbon Mapper REST + STAC APIs.

This module is the typed, cross-resolution layer that sits between the raw HTTP wrappers in :mod:geoproducts.carbonmapper.download and consumers (monitoring pipelines, analyst notebooks, backfills).

Why this exists

:mod:download exposes ~16 low-level endpoint wrappers that return raw JSON / pandas DataFrames. Every consumer otherwise has to:

  1. Pick the right endpoint (/catalog/plume-csv vs /catalog/plumes/annotated vs STAC search — all three have different schemas).
  2. Parse the response into something usable.
  3. Stitch resources together by hand: plume → scene_id via rsplit("-", 1)[0], scene_id → STAC item, plume → source via /catalog/source/plume/name/{plume_id}.

This module lifts those patterns into:

  • One function per logical question (not per HTTP endpoint).
  • Typed return values (:class:CMRawPlume, :class:CMTileItem, :class:CMSource) — never raw dicts.
  • Owned knowledge of the bbox-encoding and source_name query-suffix quirks.

Failure modes

The exception hierarchy is part of the contract:

  • :class:CMPlumeNotFound — get_plume 404.
  • :class:CMSourceNotFound — get_source 404.
  • :class:CMSceneNotPublished — get_tile / get_tile_for_plume 404 (CM publishes L2B selectively). The cross-resolution helper :func:get_tile_for_plume catches this and returns None; the single-resource :func:get_tile re-raises so callers can choose to defer.

Examples

"What does CM know about this plume?":

from geoproducts.carbonmapper.api_queries import get_plume_context plume, tile, source = get_plume_context(token, "tan20251212t185057c20s4001-E") plume.plume_id 'tan20251212t185057c20s4001-E' tile.scene_id if tile else None 'tan20251212t185057c20s4001' source.sector if source else None # may be None if unattributed '1B2'

"All tiles ever observing this chronic emitter":

from geoproducts.carbonmapper.api_queries import list_tiles_for_source tiles = list_tiles_for_source(token, "CH4_1B2_100m_-104.17525_32.49125") {t.platform for t in tiles}

See also

geoproducts.carbonmapper.download : raw HTTP / JSON wrappers. geoproducts.carbonmapper.plume.CMRawPlume : typed plume model. geoproducts.carbonmapper.source.CMSource : typed source model.

CMAPIError

Bases: Exception

Base for everything raised by :mod:api_queries.

Catch this to handle any expected Carbon Mapper API miss in one block. requests.HTTPError for non-404 statuses (e.g. 500, 429) propagates unchanged — those are infra issues, not data issues.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
class CMAPIError(Exception):
    """Base for everything raised by :mod:`api_queries`.

    Catch this to handle any expected Carbon Mapper API miss in one
    block. ``requests.HTTPError`` for non-404 statuses (e.g. 500, 429)
    propagates unchanged — those are infra issues, not data issues.
    """

CMPlumeNotFound

Bases: CMAPIError

Raised by :func:get_plume when the plume is unknown to CM.

The unmodified plume_id is preserved on the instance for logging.

Examples

try: ... get_plume(token, "tan-does-not-exist") # doctest: +SKIP ... except CMPlumeNotFound as exc: ... log.warning("missing plume", plume_id=exc.plume_id)

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
class CMPlumeNotFound(CMAPIError):
    """Raised by :func:`get_plume` when the plume is unknown to CM.

    The unmodified ``plume_id`` is preserved on the instance for
    logging.

    Examples
    --------
    >>> try:
    ...     get_plume(token, "tan-does-not-exist")  # doctest: +SKIP
    ... except CMPlumeNotFound as exc:
    ...     log.warning("missing plume", plume_id=exc.plume_id)
    """

    def __init__(self, plume_id: str):
        super().__init__(f"Plume not found: {plume_id}")
        self.plume_id = plume_id

CMSceneNotPublished

Bases: CMAPIError

Raised when STAC has no L2B item for a given scene_id.

Carbon Mapper publishes L2B selectively: plumes can exist for scenes whose L2B raster has not been (or never will be) released, so callers may want to defer such plumes rather than fail hard.

The :func:get_tile single-resource fetcher raises this so callers can pick a strategy; the cross-resolution :func:get_tile_for_plume catches it and returns None.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
class CMSceneNotPublished(CMAPIError):
    """Raised when STAC has no L2B item for a given ``scene_id``.

    Carbon Mapper publishes L2B selectively: plumes can exist for scenes
    whose L2B raster has not been (or never will be) released, so
    callers may want to defer such plumes rather than fail hard.

    The :func:`get_tile` single-resource fetcher *raises* this so
    callers can pick a strategy; the cross-resolution
    :func:`get_tile_for_plume` *catches* it and returns ``None``.
    """

    def __init__(self, scene_id: str):
        super().__init__(f"L2B scene not published: {scene_id}")
        self.scene_id = scene_id

CMSourceNotFound

Bases: CMAPIError

Raised by :func:get_source when the source name is unknown.

The (cleaned, query-suffix-stripped) source_name is preserved on the instance.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
class CMSourceNotFound(CMAPIError):
    """Raised by :func:`get_source` when the source name is unknown.

    The (cleaned, query-suffix-stripped) ``source_name`` is preserved
    on the instance.
    """

    def __init__(self, source_name: str):
        super().__init__(f"Source not found: {source_name}")
        self.source_name = source_name

CMTileItem dataclass

Lightweight Carbon Mapper L2B STAC item.

Frozen so instances are hashable and safe to use as dict keys when deduplicating scene_ids in cross-resolution queries; the mapping fields take part in equality but not in the hash.

Attributes

scene_id: STAC item id — equivalent to plume_id.rsplit("-", 1)[0] for plumes that came from this scene. collection: STAC collection id, e.g. "l2b-ch4-mfa-v3a". datetime: UTC-aware acquisition time parsed from properties["datetime"]. platform: properties["platform"] — "Tanager1", "EMIT", etc. bbox: (W, S, E, N) in WGS-84 decimal degrees. geometry: Shapely geometry (typically a Polygon) of the scene footprint. asset_urls: Mapping of asset name → href URL, e.g. {"cmf": "https://.../cmf.tif", "rgb": ...}. The L2B CH4 collection consistently exposes cmf, rgb, uncertainty, and artifact-mask. properties: Full properties mapping from the STAC item. raw: Original STAC item dict — useful for fields not yet exposed on the dataclass.

Examples

from geoproducts.carbonmapper.api_queries import CMTileItem tile = CMTileItem.from_stac_item({ ... "id": "tan20251212t185057c20s4001", ... "collection": "l2b-ch4-mfa-v3a", ... "properties": {"datetime": "2025-12-12T18:50:57Z", ... "platform": "Tanager1"}, ... "bbox": [-103.6, 31.4, -103.4, 31.6], ... "geometry": {"type": "Polygon", "coordinates": [ ... [[-103.6, 31.4], [-103.4, 31.4], ... [-103.4, 31.6], [-103.6, 31.6], [-103.6, 31.4]]]}, ... "assets": {"cmf": {"href": "https://cm/.../cmf.tif"}}, ... }) tile.scene_id, tile.platform ('tan20251212t185057c20s4001', 'Tanager1') tile.asset_urls["cmf"] 'https://cm/.../cmf.tif'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
@dataclass(frozen=True)
class CMTileItem:
    """Lightweight Carbon Mapper L2B STAC item.

    Frozen so instances are hashable and safe to use as dict keys when
    deduplicating ``scene_ids`` in cross-resolution queries; the mapping
    fields take part in equality but not in the hash.

    Attributes
    ----------
    scene_id:
        STAC item id — equivalent to ``plume_id.rsplit("-", 1)[0]`` for
        plumes that came from this scene.
    collection:
        STAC collection id, e.g. ``"l2b-ch4-mfa-v3a"``.
    datetime:
        UTC-aware acquisition time parsed from
        ``properties["datetime"]``.
    platform:
        ``properties["platform"]`` — ``"Tanager1"``, ``"EMIT"``, etc.
    bbox:
        ``(W, S, E, N)`` in WGS-84 decimal degrees.
    geometry:
        Shapely geometry (typically a Polygon) of the scene footprint.
    asset_urls:
        Mapping of asset name → href URL, e.g.
        ``{"cmf": "https://.../cmf.tif", "rgb": ...}``. The L2B CH4
        collection consistently exposes ``cmf``, ``rgb``,
        ``uncertainty``, and ``artifact-mask``.
    properties:
        Full ``properties`` mapping from the STAC item.
    raw:
        Original STAC item dict — useful for fields not yet exposed
        on the dataclass.

    Examples
    --------
    >>> from geoproducts.carbonmapper.api_queries import CMTileItem
    >>> tile = CMTileItem.from_stac_item({
    ...     "id": "tan20251212t185057c20s4001",
    ...     "collection": "l2b-ch4-mfa-v3a",
    ...     "properties": {"datetime": "2025-12-12T18:50:57Z",
    ...                    "platform": "Tanager1"},
    ...     "bbox": [-103.6, 31.4, -103.4, 31.6],
    ...     "geometry": {"type": "Polygon", "coordinates": [
    ...         [[-103.6, 31.4], [-103.4, 31.4],
    ...          [-103.4, 31.6], [-103.6, 31.6], [-103.6, 31.4]]]},
    ...     "assets": {"cmf": {"href": "https://cm/.../cmf.tif"}},
    ... })
    >>> tile.scene_id, tile.platform
    ('tan20251212t185057c20s4001', 'Tanager1')
    >>> tile.asset_urls["cmf"]
    'https://cm/.../cmf.tif'
    """

    scene_id: str
    collection: str
    datetime: datetime
    platform: str
    bbox: tuple[float, float, float, float]
    geometry: BaseGeometry
    asset_urls: Mapping[str, str] = field(hash=False)
    properties: Mapping[str, Any] = field(hash=False)
    raw: Mapping[str, Any] = field(hash=False)

    @classmethod
    def from_stac_item(cls, item: Mapping[str, Any]) -> CMTileItem:
        """Build a :class:`CMTileItem` from a raw STAC item dict.

        Tolerates both string and pre-parsed datetime values for
        ``properties["datetime"]``. When it is null (allowed by STAC for
        interval items), falls back to ``start_datetime`` then
        ``end_datetime``.

        Parameters
        ----------
        item:
            STAC item dict (Feature shape) as returned by
            :func:`geoproducts.carbonmapper.download.stac_get_item` or
            :func:`geoproducts.carbonmapper.download.stac_search`.

        Returns
        -------
        CMTileItem

        Raises
        ------
        ValueError
            If ``item["bbox"]`` is missing or not 4-length, or the item
            carries no ``datetime`` / ``start_datetime`` /
            ``end_datetime`` at all.
        """
        props = dict(item.get("properties") or {})
        bbox = tuple(item.get("bbox") or ())
        if len(bbox) != 4:
            raise ValueError(f"STAC item missing 4-tuple bbox: {item.get('id')!r}")

        dt_raw = (
            props.get("datetime")
            or props.get("start_datetime")
            or props.get("end_datetime")
        )
        if isinstance(dt_raw, datetime):
            dt = dt_raw
        elif isinstance(dt_raw, str):
            dt = datetime.fromisoformat(dt_raw.replace("Z", "+00:00"))
        else:
            raise ValueError(
                f"STAC item {item.get('id')!r} has no datetime, "
                "start_datetime or end_datetime."
            )
        # Always UTC-aware: naive values are taken as UTC, offsets converted.
        dt = as_utc(dt)

        geom_dict = item.get("geometry") or {}
        if not geom_dict:
            raise ValueError(f"STAC item missing geometry: {item.get('id')!r}")
        geom = shape(geom_dict)  # type: ignore[arg-type]

        assets = item.get("assets") or {}
        asset_urls = {
            name: asset.get("href", "")
            for name, asset in assets.items()
            if isinstance(asset, Mapping)
        }

        return cls(
            scene_id=str(item.get("id", "")),
            collection=str(item.get("collection", "")),
            datetime=dt,
            platform=str(props.get("platform", "")),
            bbox=(float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3])),
            geometry=geom,
            asset_urls=asset_urls,
            properties=props,
            raw=dict(item),
        )

from_stac_item(item) classmethod

Build a :class:CMTileItem from a raw STAC item dict.

Tolerates both string and pre-parsed datetime values for properties["datetime"]. When it is null (allowed by STAC for interval items), falls back to start_datetime then end_datetime.

Parameters

item: STAC item dict (Feature shape) as returned by :func:geoproducts.carbonmapper.download.stac_get_item or :func:geoproducts.carbonmapper.download.stac_search.

Returns

CMTileItem

Raises

ValueError If item["bbox"] is missing or not 4-length, or the item carries no datetime / start_datetime / end_datetime at all.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
@classmethod
def from_stac_item(cls, item: Mapping[str, Any]) -> CMTileItem:
    """Build a :class:`CMTileItem` from a raw STAC item dict.

    Tolerates both string and pre-parsed datetime values for
    ``properties["datetime"]``. When it is null (allowed by STAC for
    interval items), falls back to ``start_datetime`` then
    ``end_datetime``.

    Parameters
    ----------
    item:
        STAC item dict (Feature shape) as returned by
        :func:`geoproducts.carbonmapper.download.stac_get_item` or
        :func:`geoproducts.carbonmapper.download.stac_search`.

    Returns
    -------
    CMTileItem

    Raises
    ------
    ValueError
        If ``item["bbox"]`` is missing or not 4-length, or the item
        carries no ``datetime`` / ``start_datetime`` /
        ``end_datetime`` at all.
    """
    props = dict(item.get("properties") or {})
    bbox = tuple(item.get("bbox") or ())
    if len(bbox) != 4:
        raise ValueError(f"STAC item missing 4-tuple bbox: {item.get('id')!r}")

    dt_raw = (
        props.get("datetime")
        or props.get("start_datetime")
        or props.get("end_datetime")
    )
    if isinstance(dt_raw, datetime):
        dt = dt_raw
    elif isinstance(dt_raw, str):
        dt = datetime.fromisoformat(dt_raw.replace("Z", "+00:00"))
    else:
        raise ValueError(
            f"STAC item {item.get('id')!r} has no datetime, "
            "start_datetime or end_datetime."
        )
    # Always UTC-aware: naive values are taken as UTC, offsets converted.
    dt = as_utc(dt)

    geom_dict = item.get("geometry") or {}
    if not geom_dict:
        raise ValueError(f"STAC item missing geometry: {item.get('id')!r}")
    geom = shape(geom_dict)  # type: ignore[arg-type]

    assets = item.get("assets") or {}
    asset_urls = {
        name: asset.get("href", "")
        for name, asset in assets.items()
        if isinstance(asset, Mapping)
    }

    return cls(
        scene_id=str(item.get("id", "")),
        collection=str(item.get("collection", "")),
        datetime=dt,
        platform=str(props.get("platform", "")),
        bbox=(float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3])),
        geometry=geom,
        asset_urls=asset_urls,
        properties=props,
        raw=dict(item),
    )

get_image_raster_for_plume(token, plume_id, *, collection=None, prefer_url_pattern_fallback=True, with_rgb=True)

Resolve a plume to its parent :class:CMImageRaster.

  1. Derive the parent scene_id from plume_id.
  2. Unless collection is pinned or the URL-pattern path is disabled, fetch the plume record and resolve its :class:CMCollectionSpec; probe the asset proxy for that gas/version first (same-gas fallbacks only).
  3. Otherwise — or when the plume is unknown (404) — defer to :func:get_image_raster_for_scene (STAC first, then default candidate probing).
Parameters

token, prefer_url_pattern_fallback, with_rgb: Forwarded to :func:get_image_raster_for_scene. collection: Explicit STAC collection. When given, step 2 is skipped and the STAC path uses it verbatim. None (default) resolves the collection from the plume record. plume_id: Colloquial plume id (with the -{part} suffix).

Returns

CMImageRaster | None None when the scene is not published in any probed collection.

Raises

requests.HTTPError For non-404 failures (401, 429 after retries, 5xx) — never reported as "not published".

Examples

tile = get_image_raster_for_plume( # doctest: +SKIP ... token, "tan20260331t181625c77s4001-A", ... ) tile is not None # doctest: +SKIP True

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_image_raster_for_plume(
    token: str,
    plume_id: str,
    *,
    collection: str | None = None,
    prefer_url_pattern_fallback: bool = True,
    with_rgb: bool = True,
) -> CMImageRaster | None:
    """Resolve a plume to its parent :class:`CMImageRaster`.

    1. Derive the parent ``scene_id`` from ``plume_id``.
    2. Unless ``collection`` is pinned or the URL-pattern path is
       disabled, fetch the plume record and resolve its
       :class:`CMCollectionSpec`; probe the asset proxy for that
       gas/version first (same-gas fallbacks only).
    3. Otherwise — or when the plume is unknown (404) — defer to
       :func:`get_image_raster_for_scene` (STAC first, then default
       candidate probing).

    Parameters
    ----------
    token, prefer_url_pattern_fallback, with_rgb:
        Forwarded to :func:`get_image_raster_for_scene`.
    collection:
        Explicit STAC collection. When given, step 2 is skipped and the
        STAC path uses it verbatim. ``None`` (default) resolves the
        collection from the plume record.
    plume_id:
        Colloquial plume id (with the ``-{part}`` suffix).

    Returns
    -------
    CMImageRaster | None
        ``None`` when the scene is not published in any probed
        collection.

    Raises
    ------
    requests.HTTPError
        For non-404 failures (401, 429 after retries, 5xx) — never
        reported as "not published".

    Examples
    --------
    >>> tile = get_image_raster_for_plume(  # doctest: +SKIP
    ...     token, "tan20260331t181625c77s4001-A",
    ... )
    >>> tile is not None  # doctest: +SKIP
    True
    """
    scene_id = _scene_id_from_plume(plume_id)

    # Preferred path: one catalog fetch resolves the CMCollectionSpec
    # (gas / cmf_type / version) from the plume's own record; its L2B
    # collection is probed first, with same-gas backups for re-versioned
    # plumes, so this never goes stale when Carbon Mapper bumps
    # versions. Only a 404 (unknown plume) or an unparseable record
    # falls back to the STAC-first path — throttling and auth errors
    # propagate instead of costing a dozen extra calls.
    spec: CMCollectionSpec | None = None
    if collection is None and prefer_url_pattern_fallback:
        spec = _spec_for_plume(token, plume_id)

    if spec is not None:
        from geoproducts.carbonmapper.rasters import CMImageRaster

        try:
            return CMImageRaster.from_scene_id(
                scene_id,
                token=token,
                spec=spec,
                with_rgb=with_rgb,
            )
        except CMSceneNotPublished:
            return None

    return get_image_raster_for_scene(
        token,
        scene_id,
        collection=collection,
        prefer_url_pattern_fallback=prefer_url_pattern_fallback,
        with_rgb=with_rgb,
    )

get_image_raster_for_scene(token, scene_id, *, collection=None, prefer_url_pattern_fallback=True, with_rgb=True)

Resolve a scene_id to a :class:CMImageRaster with rgb sibling.

Single entry point for "give me the L2B parent tile as a usable raster object" — handles both STAC-resident scenes (v3a) and URL-pattern-only scenes (v3c, the live 2026 L2B version) transparently:

  1. Try STAC item lookup (cheap when it works — one HTTP call for the CH4 item, one for the RGB sibling). Builds via :meth:CMImageRaster.from_cm_tile_item + :meth:with_rgb.
  2. If STAC returns 404 AND prefer_url_pattern_fallback is True (default), fall back to :meth:CMImageRaster.from_scene_id which probes the verified L2B asset-proxy URL pattern.
  3. Return None only if both paths fail.
Parameters

token: Bearer token. scene_id: L2B scene id (e.g. "tan20260331t181625c77s4001"). collection: STAC collection probed first. None (default) means :data:DEFAULT_L2B_COLLECTION (l2b-ch4-mfa-v3a) for STAC and the default CH4 candidates for the URL-pattern fallback. A pinned collection is the only one either path probes, so a non-default gas or version never resolves to another collection's scene. prefer_url_pattern_fallback: When True (default), fall back to URL-pattern derivation on STAC 404. Set to False to keep the v3a-only behaviour of :func:get_tile_for_plume. with_rgb: When True (default), attach the RGB sibling raster.

Returns

CMImageRaster | None None when STAC has no item AND either the fallback is disabled or the URL-pattern probes also 404.

Examples

tile = get_image_raster_for_scene( # doctest: +SKIP ... token, "tan20260331t181625c77s4001", ... ) tile.cmf # doctest: +SKIP

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_image_raster_for_scene(
    token: str,
    scene_id: str,
    *,
    collection: str | None = None,
    prefer_url_pattern_fallback: bool = True,
    with_rgb: bool = True,
) -> CMImageRaster | None:
    """Resolve a ``scene_id`` to a :class:`CMImageRaster` with rgb sibling.

    Single entry point for "give me the L2B parent tile as a usable
    raster object" — handles both STAC-resident scenes (v3a) and
    URL-pattern-only scenes (v3c, the live 2026 L2B version)
    transparently:

    1. Try STAC item lookup (cheap when it works — one HTTP call for
       the CH4 item, one for the RGB sibling). Builds via
       :meth:`CMImageRaster.from_cm_tile_item` + :meth:`with_rgb`.
    2. If STAC returns 404 AND ``prefer_url_pattern_fallback`` is
       ``True`` (default), fall back to
       :meth:`CMImageRaster.from_scene_id` which probes the verified
       L2B asset-proxy URL pattern.
    3. Return ``None`` only if both paths fail.

    Parameters
    ----------
    token:
        Bearer token.
    scene_id:
        L2B scene id (e.g. ``"tan20260331t181625c77s4001"``).
    collection:
        STAC collection probed first. ``None`` (default) means
        :data:`DEFAULT_L2B_COLLECTION` (``l2b-ch4-mfa-v3a``) for STAC and
        the default CH4 candidates for the URL-pattern fallback. A
        pinned collection is the only one either path probes, so a
        non-default gas or version never resolves to another
        collection's scene.
    prefer_url_pattern_fallback:
        When ``True`` (default), fall back to URL-pattern derivation
        on STAC 404. Set to ``False`` to keep the v3a-only behaviour
        of :func:`get_tile_for_plume`.
    with_rgb:
        When ``True`` (default), attach the RGB sibling raster.

    Returns
    -------
    CMImageRaster | None
        ``None`` when STAC has no item AND either the fallback is
        disabled or the URL-pattern probes also 404.

    Examples
    --------
    >>> tile = get_image_raster_for_scene(  # doctest: +SKIP
    ...     token, "tan20260331t181625c77s4001",
    ... )
    >>> tile.cmf  # doctest: +SKIP
    <RasterioReader …/l2b-ch4-mfa-v3c/2026/03/31/…/cmf.tif>
    """
    # Lazy import to avoid the rasters → api_queries circular import.
    from geoproducts.carbonmapper.rasters import CMImageRaster

    stac_collection = collection or DEFAULT_L2B_COLLECTION

    # ── 1. STAC path (cheap when it works) ──────────────────────────
    try:
        ch4_item = get_tile(token, scene_id, collection=stac_collection)
        ir = CMImageRaster.from_cm_tile_item(ch4_item, token=token)
        if with_rgb:
            try:
                # The RGB sibling shares the retrieval's version
                # (`l2b-ch4-mfa-v3e` → `l2b-rgb-v3e`).
                rgb_item = get_tile(
                    token,
                    scene_id,
                    collection=_rgb_collection_for(stac_collection),
                )
                ir = ir.with_rgb(rgb_item)
            except CMSceneNotPublished:
                # CH4 item exists but RGB sibling doesn't — keep the
                # CH4-only raster rather than failing the whole call.
                pass
        return ir
    except CMSceneNotPublished:
        if not prefer_url_pattern_fallback:
            return None
    # Fall through to URL-pattern path.

    # ── 2. URL-pattern fallback (for v3c/v3d scenes not in STAC) ────
    # A pinned collection is still probed (so an unpublished scene stays
    # ``None``), but it is the only candidate.
    pinned: dict[str, Any] = {}
    if collection is not None:
        pinned = {
            "l2b_collection_candidates": (collection,),
            "rgb_collection_candidates": (_rgb_collection_for(collection),),
        }
    try:
        return CMImageRaster.from_scene_id(
            scene_id,
            token=token,
            with_rgb=with_rgb,
            **pinned,
        )
    except CMSceneNotPublished:
        return None

get_plume(token, plume_id)

Fetch a single plume by its CM plume_id.

Wraps GET /catalog/plume/{id} and parses the result through :class:CMRawPlume.

Parameters

token: Carbon Mapper Bearer token. Required for non-public fields. plume_id: Either the colloquial name (e.g. "tan20251212t185057c20s4001-E") or the UUID form.

Returns

CMRawPlume

Raises

CMPlumeNotFound When the API returns 404. requests.HTTPError For non-404 errors (5xx, 429, etc.).

Examples

plume = get_plume(token, "tan20251212t185057c20s4001-E") # doctest: +SKIP plume.plume_id, plume.gas ('tan20251212t185057c20s4001-E', 'CH4')

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_plume(token: str, plume_id: str) -> CMRawPlume:
    """Fetch a single plume by its CM ``plume_id``.

    Wraps ``GET /catalog/plume/{id}`` and parses the result through
    :class:`CMRawPlume`.

    Parameters
    ----------
    token:
        Carbon Mapper Bearer token. Required for non-public fields.
    plume_id:
        Either the colloquial name (e.g.
        ``"tan20251212t185057c20s4001-E"``) or the UUID form.

    Returns
    -------
    CMRawPlume

    Raises
    ------
    CMPlumeNotFound
        When the API returns 404.
    requests.HTTPError
        For non-404 errors (5xx, 429, etc.).

    Examples
    --------
    >>> plume = get_plume(token, "tan20251212t185057c20s4001-E")  # doctest: +SKIP
    >>> plume.plume_id, plume.gas
    ('tan20251212t185057c20s4001-E', 'CH4')
    """
    try:
        raw = _dl.get_plume_by_id(plume_id, token=token)
    except requests.HTTPError as exc:
        if _is_404(exc):
            raise CMPlumeNotFound(plume_id) from exc
        raise
    return CMRawPlume(**raw)

get_plume_context(token, plume_id)

Single-call fetch of a plume plus its parent tile and source.

The most common notebook / ETL question is "give me everything CM knows about this plume". This helper batches the three independent REST/STAC calls behind a single name and surfaces the contracts as a typed tuple.

Failure modes are asymmetric:

  • The plume itself must exist — CMPlumeNotFound propagates.
  • Tile resolution returns None when the scene has not been published to L2B (CMSceneNotPublished caught internally).
  • Source resolution returns None when CM has not attributed the plume (404 caught internally).
Parameters

token: Bearer token. plume_id: Colloquial plume id.

Returns

(CMRawPlume, CMTileItem | None, CMSource | None)

Raises

CMPlumeNotFound When the plume itself is unknown.

Examples

Notebook exploration:

plume, tile, source = get_plume_context( # doctest: +SKIP ... token, "tan20251212t185057c20s4001-E", ... ) print(f"emission: {plume.emission_auto:.0f} kg/h") # doctest: +SKIP emission: 1240 kg/h if source: # doctest: +SKIP ... print(f"source {source.source_name} sector {source.sector}")

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_plume_context(
    token: str,
    plume_id: str,
) -> tuple[CMRawPlume, CMTileItem | None, CMSource | None]:
    """Single-call fetch of a plume plus its parent tile and source.

    The most common notebook / ETL question is *"give me everything CM
    knows about this plume"*. This helper batches the three independent
    REST/STAC calls behind a single name and surfaces the contracts as
    a typed tuple.

    Failure modes are asymmetric:

    - The plume itself **must** exist — ``CMPlumeNotFound`` propagates.
    - Tile resolution returns ``None`` when the scene has not been
      published to L2B (``CMSceneNotPublished`` caught internally).
    - Source resolution returns ``None`` when CM has not attributed
      the plume (404 caught internally).

    Parameters
    ----------
    token:
        Bearer token.
    plume_id:
        Colloquial plume id.

    Returns
    -------
    (CMRawPlume, CMTileItem | None, CMSource | None)

    Raises
    ------
    CMPlumeNotFound
        When the plume itself is unknown.

    Examples
    --------
    Notebook exploration:

    >>> plume, tile, source = get_plume_context(  # doctest: +SKIP
    ...     token, "tan20251212t185057c20s4001-E",
    ... )
    >>> print(f"emission: {plume.emission_auto:.0f} kg/h")  # doctest: +SKIP
    emission: 1240 kg/h
    >>> if source:                                          # doctest: +SKIP
    ...     print(f"source {source.source_name} sector {source.sector}")
    """
    plume = get_plume(token, plume_id)
    tile = get_tile_for_plume(token, plume_id, spec=plume.collection_spec)
    source = get_source_for_plume(token, plume_id)
    return plume, tile, source

get_source(token, source_name)

Fetch a single Carbon Mapper source by its canonical name.

Strips the source-name query-string suffix (?plume_gas=...) automatically — pass either the dirty or clean form.

Parameters

token: Bearer token. source_name: Canonical or query-suffixed source name, e.g. "CH4_1B2_100m_-104.17525_32.49125" or "CH4_1B2_100m_-104.17525_32.49125?plume_gas=CH4".

Returns

CMSource

Raises

CMSourceNotFound When the API returns 404.

Examples

src = get_source(token, "CH4_1B2_100m_-104.17525_32.49125") # doctest: +SKIP src.sector, src.plume_count ('1B2', 12)

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_source(token: str, source_name: str) -> CMSource:
    """Fetch a single Carbon Mapper source by its canonical name.

    Strips the source-name query-string suffix (``?plume_gas=...``)
    automatically — pass either the dirty or
    clean form.

    Parameters
    ----------
    token:
        Bearer token.
    source_name:
        Canonical or query-suffixed source name, e.g.
        ``"CH4_1B2_100m_-104.17525_32.49125"`` or
        ``"CH4_1B2_100m_-104.17525_32.49125?plume_gas=CH4"``.

    Returns
    -------
    CMSource

    Raises
    ------
    CMSourceNotFound
        When the API returns 404.

    Examples
    --------
    >>> src = get_source(token, "CH4_1B2_100m_-104.17525_32.49125")  # doctest: +SKIP
    >>> src.sector, src.plume_count
    ('1B2', 12)
    """
    cleaned = _strip_query_suffix(source_name)
    try:
        raw = _dl.get_source_by_name(cleaned, token=token)
    except requests.HTTPError as exc:
        if _is_404(exc):
            raise CMSourceNotFound(cleaned) from exc
        raise
    raw = _flatten_source_detail(raw, cleaned)
    # The single-source endpoint can return either a Feature or properties
    # directly; coerce to a Feature shape so CMSource.from_geojson_feature
    # handles both.
    if "properties" not in raw and "source_name" in raw:
        feature = {
            "properties": dict(raw),
            "geometry": {
                "type": "Point",
                "coordinates": [raw.get("lon"), raw.get("lat")],
            },
        }
    else:
        feature = dict(raw)

    # The /catalog/source/{name} endpoint sometimes returns top-level
    # geometry with null coords and stashes the real centroid under
    # properties.point — fall back to that when the outer geometry is
    # unusable.
    geom = feature.get("geometry") or {}
    coords = geom.get("coordinates") or [None, None]
    if not coords or coords[0] is None or coords[1] is None:
        props = feature.get("properties") or {}
        point = props.get("point") or {}
        pcoords = point.get("coordinates") if isinstance(point, dict) else None
        if pcoords and pcoords[0] is not None and pcoords[1] is not None:
            feature = dict(feature)
            feature["geometry"] = {"type": "Point", "coordinates": list(pcoords)}

    return CMSource.from_geojson_feature(feature)

get_source_for_plume(token, plume_id)

Resolve a plume to its attributed Carbon Mapper source.

Wraps /catalog/source/plume/name/{plume_id} — the by-name endpoint, which returns the cleaned source_name (preferred over the UUID-keyed sibling for colloquial plume_id strings).

Returns None when CM has not attributed the plume to a source (HTTP 404). Other HTTP errors propagate.

Parameters

token: Bearer token. plume_id: Colloquial plume id.

Returns

CMSource | None

Examples

plume_id = "tan20251212t185057c20s4001-E" src = get_source_for_plume(token, plume_id) # doctest: +SKIP src.source_name if src else "unattributed" # doctest: +SKIP 'CH4_1B2_100m_-104.0_32.0'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_source_for_plume(
    token: str,
    plume_id: str,
) -> CMSource | None:
    """Resolve a plume to its attributed Carbon Mapper source.

    Wraps ``/catalog/source/plume/name/{plume_id}`` — the *by-name*
    endpoint, which returns the cleaned ``source_name`` (preferred over
    the UUID-keyed sibling for colloquial ``plume_id`` strings).

    Returns ``None`` when CM has not attributed the plume to a source
    (HTTP 404). Other HTTP errors propagate.

    Parameters
    ----------
    token:
        Bearer token.
    plume_id:
        Colloquial plume id.

    Returns
    -------
    CMSource | None

    Examples
    --------
    >>> plume_id = "tan20251212t185057c20s4001-E"
    >>> src = get_source_for_plume(token, plume_id)  # doctest: +SKIP
    >>> src.source_name if src else "unattributed"  # doctest: +SKIP
    'CH4_1B2_100m_-104.0_32.0'
    """
    try:
        raw = _dl.get_source_for_plume_name(plume_id, token=token)
    except requests.HTTPError as exc:
        if _is_404(exc):
            return None
        raise
    if not raw:
        return None
    raw = _flatten_source_detail(raw, None)
    if "geometry" not in raw and "properties" not in raw:
        feature = {
            "properties": dict(raw),
            "geometry": {
                "type": "Point",
                "coordinates": [raw.get("lon"), raw.get("lat")],
            },
        }
    else:
        feature = dict(raw)

    # The endpoint occasionally returns a plume-shaped payload (no
    # source_name, null top-level geometry) when CM has not yet
    # attributed the plume — treat as unattributed.
    props = feature.get("properties") or {}
    if not props.get("source_name") and not feature.get("source_name"):
        return None

    # Fall back to properties.point when the outer geometry is null
    # (same quirk as get_source).
    geom = feature.get("geometry") or {}
    coords = geom.get("coordinates") or [None, None]
    if not coords or coords[0] is None or coords[1] is None:
        point = props.get("point") or {}
        pcoords = point.get("coordinates") if isinstance(point, dict) else None
        if pcoords and pcoords[0] is not None and pcoords[1] is not None:
            feature["geometry"] = {"type": "Point", "coordinates": list(pcoords)}

    return CMSource.from_geojson_feature(feature)

get_tile(token, scene_id, *, collection=DEFAULT_L2B_COLLECTION)

Fetch a single L2B STAC item by scene_id.

Wraps GET /stac/collections/{collection}/items/{scene_id}.

Parameters

token: Bearer token (STAC item endpoints accept anonymous reads for published items, but auth surfaces additional fields). scene_id: The L2B scene_id, equal to plume_id.rsplit("-", 1)[0] for any plume that came from this scene. collection: STAC collection — defaults to :data:DEFAULT_L2B_COLLECTION (CH4 matched-filter v3a). Override for CO2 or earlier versions.

Returns

CMTileItem

Raises

CMSceneNotPublished When the L2B item has not been published yet (HTTP 404). Re-raised — not caught — so callers can choose to defer.

Examples

tile = get_tile(token, "tan20251212t185057c20s4001") # doctest: +SKIP tile.platform, list(tile.asset_urls) ('Tanager1', ['cmf', 'rgb', 'uncertainty', 'artifact-mask'])

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_tile(
    token: str,
    scene_id: str,
    *,
    collection: str = DEFAULT_L2B_COLLECTION,
) -> CMTileItem:
    """Fetch a single L2B STAC item by ``scene_id``.

    Wraps ``GET /stac/collections/{collection}/items/{scene_id}``.

    Parameters
    ----------
    token:
        Bearer token (STAC item endpoints accept anonymous reads for
        published items, but auth surfaces additional fields).
    scene_id:
        The L2B scene_id, equal to ``plume_id.rsplit("-", 1)[0]`` for
        any plume that came from this scene.
    collection:
        STAC collection — defaults to :data:`DEFAULT_L2B_COLLECTION`
        (CH4 matched-filter v3a). Override for CO2 or earlier versions.

    Returns
    -------
    CMTileItem

    Raises
    ------
    CMSceneNotPublished
        When the L2B item has not been published yet (HTTP 404).
        Re-raised — not caught — so callers can choose to defer.

    Examples
    --------
    >>> tile = get_tile(token, "tan20251212t185057c20s4001")  # doctest: +SKIP
    >>> tile.platform, list(tile.asset_urls)
    ('Tanager1', ['cmf', 'rgb', 'uncertainty', 'artifact-mask'])
    """
    try:
        raw = _dl.stac_get_item(collection, scene_id, token=token)
    except requests.HTTPError as exc:
        if _is_404(exc):
            raise CMSceneNotPublished(scene_id) from exc
        raise
    return CMTileItem.from_stac_item(raw)

get_tile_for_plume(token, plume_id, *, collection=None, spec=None)

Resolve a plume to its parent L2B STAC item.

  1. Derive the parent scene_id via plume_id.rsplit("-", 1)[0].
  2. Pick the STAC collections to try: collection verbatim when given; else the candidates of the plume's :class:CMCollectionSpec (spec if passed, otherwise resolved from the plume record — one extra catalog call); else, for an unknown plume, the default CH4 candidates.
  3. Return the first collection's item for the scene.

Unlike :func:get_tile, this helper catches :class:CMSceneNotPublished and returns None — appropriate for consumers that want to defer rather than error.

Parameters

token: Bearer token. plume_id: Colloquial plume id (with the -{part} suffix). collection: Explicit STAC collection. None (default) resolves it from the plume's own version and gas (same-gas candidates only). spec: Pre-resolved collection spec (e.g. CMRawPlume.collection_spec) — skips the record fetch.

Returns

CMTileItem | None None when the L2B scene has not been published yet.

Raises

requests.HTTPError For non-404 failures of the record or STAC lookups (401, 429 after retries, 5xx).

Examples

plume_id = "tan20251212t185057c20s4001-E" tile = get_tile_for_plume(token, plume_id) # doctest: +SKIP tile.scene_id if tile else "deferred" # doctest: +SKIP 'tan20251212t185057c20s4001'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def get_tile_for_plume(
    token: str,
    plume_id: str,
    *,
    collection: str | None = None,
    spec: CMCollectionSpec | None = None,
) -> CMTileItem | None:
    """Resolve a plume to its parent L2B STAC item.

    1. Derive the parent ``scene_id`` via ``plume_id.rsplit("-", 1)[0]``.
    2. Pick the STAC collections to try: ``collection`` verbatim when
       given; else the candidates of the plume's
       :class:`CMCollectionSpec` (``spec`` if passed, otherwise
       resolved from the plume record — one extra catalog call); else,
       for an unknown plume, the default CH4 candidates.
    3. Return the first collection's item for the scene.

    Unlike :func:`get_tile`, this helper **catches**
    :class:`CMSceneNotPublished` and returns ``None`` — appropriate for
    consumers that want to defer rather than error.

    Parameters
    ----------
    token:
        Bearer token.
    plume_id:
        Colloquial plume id (with the ``-{part}`` suffix).
    collection:
        Explicit STAC collection. ``None`` (default) resolves it from
        the plume's own version and gas (same-gas candidates only).
    spec:
        Pre-resolved collection spec (e.g. ``CMRawPlume.collection_spec``)
        — skips the record fetch.

    Returns
    -------
    CMTileItem | None
        ``None`` when the L2B scene has not been published yet.

    Raises
    ------
    requests.HTTPError
        For non-404 failures of the record or STAC lookups (401, 429
        after retries, 5xx).

    Examples
    --------
    >>> plume_id = "tan20251212t185057c20s4001-E"
    >>> tile = get_tile_for_plume(token, plume_id)  # doctest: +SKIP
    >>> tile.scene_id if tile else "deferred"  # doctest: +SKIP
    'tan20251212t185057c20s4001'
    """
    scene_id = _scene_id_from_plume(plume_id)
    if collection is not None:
        candidates: tuple[str, ...] = (collection,)
    else:
        if spec is None:
            spec = _spec_for_plume(token, plume_id)
        candidates = _stac_l2b_candidates(spec)
    return _first_published_tile(token, scene_id, candidates)

list_plumes(token, *, bbox=None, sectors=None, instruments=None, datetime_min=None, datetime_max=None, published_at_min=None, published_at_max=None, gas=Gas.CH4, limit=1000)

Materialised list of plumes matching filters.

  1. Request /catalog/plumes/annotated pages of at most 1 000 rows (the server cap) at increasing offsets.
  2. Stop at limit rows, on an empty or short page, or once the offset reaches the response's total_count.
  3. Convert each row into a :class:CMRawPlume.

The bbox is encoded as repeated keys (REST style — see :func:geoproducts.carbonmapper.download._rest_bbox_params).

Parameters

token: Bearer token. bbox: (W, S, E, N) WGS-84 spatial filter. sectors: IPCC sector codes — e.g. ["1B2", "6A"]. instruments: Instrument short codes — e.g. ["emi", "tan"] or :class:Instrument members like [Instrument.EMIT, Instrument.TANAGER]. datetime_min, datetime_max: Optional UTC bounds — combined into an RFC 3339 interval. Filters on observation time (scene_timestamp). published_at_min, published_at_max: Optional UTC bounds on publication date (published_at). Carbon Mapper frequently publishes plumes weeks-to-months after acquisition, so this is the axis to poll for newly published data — e.g. published_at_min=last_poll_time. gas: :data:Gas.CH4 (default), :data:Gas.CO2, or None for both gases. Plain strings ("CH4" / "CO2") work too. limit: Max rows returned in total. Pages of up to 1 000 rows (the server cap) are fetched until limit is reached or the results run out.

Returns

list[CMRawPlume]

Examples

Permian methane plumes for Q1 2025 from EMIT and Tanager:

from datetime import datetime, timezone plumes = list_plumes( # doctest: +SKIP ... token, ... bbox=(-104.5, 31.0, -101.5, 33.5), ... instruments=["emi", "tan"], ... datetime_min=datetime(2025, 1, 1, tzinfo=timezone.utc), ... datetime_max=datetime(2025, 4, 1, tzinfo=timezone.utc), ... limit=500, ... ) sum(p.emission_auto or 0 for p in plumes) # doctest: +SKIP 412350.0

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_plumes(
    token: str,
    *,
    bbox: BBox | None = None,
    sectors: list[str] | None = None,
    instruments: list[str] | None = None,
    datetime_min: datetime | None = None,
    datetime_max: datetime | None = None,
    published_at_min: datetime | None = None,
    published_at_max: datetime | None = None,
    gas: Gas | Literal["CH4", "CO2"] | None = Gas.CH4,
    limit: int = 1_000,
) -> list[CMRawPlume]:
    """Materialised list of plumes matching filters.

    1. Request ``/catalog/plumes/annotated`` pages of at most 1 000 rows
       (the server cap) at increasing offsets.
    2. Stop at ``limit`` rows, on an empty or short page, or once the
       offset reaches the response's ``total_count``.
    3. Convert each row into a :class:`CMRawPlume`.

    The bbox is encoded as repeated keys (REST style — see
    :func:`geoproducts.carbonmapper.download._rest_bbox_params`).

    Parameters
    ----------
    token:
        Bearer token.
    bbox:
        ``(W, S, E, N)`` WGS-84 spatial filter.
    sectors:
        IPCC sector codes — e.g. ``["1B2", "6A"]``.
    instruments:
        Instrument short codes — e.g. ``["emi", "tan"]`` or
        :class:`Instrument` members like ``[Instrument.EMIT, Instrument.TANAGER]``.
    datetime_min, datetime_max:
        Optional UTC bounds — combined into an RFC 3339 interval.
        Filters on **observation time** (``scene_timestamp``).
    published_at_min, published_at_max:
        Optional UTC bounds on **publication date** (``published_at``).
        Carbon Mapper frequently publishes plumes weeks-to-months
        after acquisition, so this is the axis to poll for newly
        published data — e.g. ``published_at_min=last_poll_time``.
    gas:
        :data:`Gas.CH4` (default), :data:`Gas.CO2`, or ``None`` for
        both gases. Plain strings (``"CH4"`` / ``"CO2"``) work too.
    limit:
        Max rows returned in total. Pages of up to 1 000 rows (the
        server cap) are fetched until ``limit`` is reached or the
        results run out.

    Returns
    -------
    list[CMRawPlume]

    Examples
    --------
    Permian methane plumes for Q1 2025 from EMIT and Tanager:

    >>> from datetime import datetime, timezone
    >>> plumes = list_plumes(  # doctest: +SKIP
    ...     token,
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     instruments=["emi", "tan"],
    ...     datetime_min=datetime(2025, 1, 1, tzinfo=timezone.utc),
    ...     datetime_max=datetime(2025, 4, 1, tzinfo=timezone.utc),
    ...     limit=500,
    ... )
    >>> sum(p.emission_auto or 0 for p in plumes)  # doctest: +SKIP
    412350.0
    """
    dt_range = time_interval(datetime_min, datetime_max)
    pub_range = time_interval(published_at_min, published_at_max)
    rows: list[Mapping[str, Any]] = []
    while len(rows) < limit:
        page_size = min(_ANNOTATED_PAGE_SIZE, limit - len(rows))
        result = _dl.get_plumes_annotated(
            plume_gas=None if gas is None else str(gas),
            bbox=bbox,
            datetime_range=dt_range,
            published_at_range=pub_range,
            sectors=sectors,
            instruments=instruments,
            limit=page_size,
            offset=len(rows),
            token=token,
        )
        page = result.get("items", []) if isinstance(result, Mapping) else []
        rows.extend(page)
        total = result.get("total_count") if isinstance(result, Mapping) else None
        if len(page) < page_size or (total is not None and len(rows) >= total):
            break
    return [CMRawPlume(**row) for row in rows[:limit]]

list_plumes_for_source(token, source_name, *, limit=10000)

All plumes attributed to a Carbon Mapper source.

Wraps /catalog/source/{source_name} and reads the embedded plumes records (full annotated-shape dicts; verified complete against the source's plume_count in the 2026-07 audit). The /catalog/source-plumes-csv/{source_name} route (JSON, despite its name) is kept only as a fallback for API deployments that don't embed plumes.

Strips the ?... query suffix from source_name automatically.

Parameters

token: Bearer token. source_name: Canonical or query-suffixed source name. limit: Cap the returned list. Defaults to 10 000 — CM sources rarely exceed a few hundred plumes, so this is just a safety cap.

Returns

list[CMRawPlume]

Raises

CMSourceNotFound When the API returns 404 for source_name. (Source names are re-clustered over time — resolve fresh names via :func:list_sources / :func:get_source_for_plume rather than persisting them.)

Examples

plumes = list_plumes_for_source( # doctest: +SKIP ... token, "CH4_1B2_100m_-104.17525_32.49125", ... ) len(plumes), plumes[0].plume_id[:3] # doctest: +SKIP (47, 'tan')

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_plumes_for_source(
    token: str,
    source_name: str,
    *,
    limit: int = 10_000,
) -> list[CMRawPlume]:
    """All plumes attributed to a Carbon Mapper source.

    Wraps ``/catalog/source/{source_name}`` and reads the **embedded**
    ``plumes`` records (full annotated-shape dicts; verified complete
    against the source's ``plume_count`` in the 2026-07 audit). The
    ``/catalog/source-plumes-csv/{source_name}`` route (JSON, despite
    its name) is kept only as a fallback for API deployments that don't
    embed ``plumes``.

    Strips the ``?...`` query suffix from ``source_name`` automatically.

    Parameters
    ----------
    token:
        Bearer token.
    source_name:
        Canonical or query-suffixed source name.
    limit:
        Cap the returned list. Defaults to 10 000 — CM sources rarely
        exceed a few hundred plumes, so this is just a safety cap.

    Returns
    -------
    list[CMRawPlume]

    Raises
    ------
    CMSourceNotFound
        When the API returns 404 for ``source_name``. (Source names
        are re-clustered over time — resolve fresh names via
        :func:`list_sources` / :func:`get_source_for_plume` rather
        than persisting them.)

    Examples
    --------
    >>> plumes = list_plumes_for_source(  # doctest: +SKIP
    ...     token, "CH4_1B2_100m_-104.17525_32.49125",
    ... )
    >>> len(plumes), plumes[0].plume_id[:3]  # doctest: +SKIP
    (47, 'tan')
    """
    cleaned = _strip_query_suffix(source_name)
    try:
        raw = _dl.get_source_by_name(cleaned, token=token)
    except requests.HTTPError as exc:
        if _is_404(exc):
            raise CMSourceNotFound(cleaned) from exc
        raise

    records = raw.get("plumes")
    if records is None:
        # Older API shape without embedded plumes — the source-plumes
        # route returns the same records as JSON.
        records = _dl.get_source_plumes(cleaned, token=token).get("plumes") or []

    if limit and len(records) > limit:
        records = records[:limit]
    return [CMRawPlume(**rec) for rec in records]

list_plumes_for_tile(token, scene_id, *, gas=None)

All plumes attributed to a given L2B scene.

  1. Parse the acquisition date from the scene name and restrict the annotated-plumes query to that day (± 1 day of slack).
  2. Page through every matching plume (:func:list_plumes).
  3. Keep the plumes whose plume_id starts with "{scene_id}-" (Carbon Mapper convention: plume_id = "{scene_id}-{part}").
Parameters

token: Bearer token. scene_id: L2B scene id, e.g. "tan20251212t185057c20s4001". gas: None (default) for both gases, or :data:Gas.CH4 / :data:Gas.CO2 to restrict.

Returns

list[CMRawPlume]

Note

Scene names that don't carry a parseable date fall back to an unfiltered (but still fully paginated) listing — slow, but complete.

Examples

plumes = list_plumes_for_tile( # doctest: +SKIP ... token, "tan20251212t185057c20s4001", ... ) [p.plume_id[-1] for p in plumes] # doctest: +SKIP ['A', 'B', 'C', 'E']

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_plumes_for_tile(
    token: str,
    scene_id: str,
    *,
    gas: Gas | Literal["CH4", "CO2"] | None = None,
) -> list[CMRawPlume]:
    """All plumes attributed to a given L2B scene.

    1. Parse the acquisition date from the scene name and restrict the
       annotated-plumes query to that day (± 1 day of slack).
    2. Page through every matching plume (:func:`list_plumes`).
    3. Keep the plumes whose ``plume_id`` starts with ``"{scene_id}-"``
       (Carbon Mapper convention: ``plume_id = "{scene_id}-{part}"``).

    Parameters
    ----------
    token:
        Bearer token.
    scene_id:
        L2B scene id, e.g. ``"tan20251212t185057c20s4001"``.
    gas:
        ``None`` (default) for both gases, or :data:`Gas.CH4` /
        :data:`Gas.CO2` to restrict.

    Returns
    -------
    list[CMRawPlume]

    Note
    ----
    Scene names that don't carry a parseable date fall back to an
    unfiltered (but still fully paginated) listing — slow, but complete.

    Examples
    --------
    >>> plumes = list_plumes_for_tile(  # doctest: +SKIP
    ...     token, "tan20251212t185057c20s4001",
    ... )
    >>> [p.plume_id[-1] for p in plumes]  # doctest: +SKIP
    ['A', 'B', 'C', 'E']
    """
    dt_min = dt_max = None
    try:
        yyyy, mm, dd = parse_item_date(scene_id)
        day = datetime(int(yyyy), int(mm), int(dd), tzinfo=UTC)
        dt_min, dt_max = day - timedelta(days=1), day + timedelta(days=2)
    except ValueError:
        _log.warning(
            "scene_id %r carries no date; listing plumes unfiltered",
            scene_id,
        )
    plumes = list_plumes(
        token,
        datetime_min=dt_min,
        datetime_max=dt_max,
        gas=gas,
        limit=1_000_000,
    )
    prefix = f"{scene_id}-"
    return [p for p in plumes if p.plume_id.startswith(prefix)]

list_sources(token, *, bbox=None, sectors=None, gas=Gas.CH4)

List Carbon Mapper sources matching filters.

Wraps the source listing endpoint (REST Catalog). Each item is parsed via :meth:CMSource.from_geojson_feature, which strips the source-name query-suffix.

Parameters

token: Bearer token. bbox: (W, S, E, N) WGS-84 spatial filter (REST repeated-keys encoding). sectors: IPCC sector codes. gas: :data:Gas.CH4 (default), :data:Gas.CO2, or None for both gases.

Returns

list[CMSource]

Examples

Top oil & gas sources in the Permian:

sources = list_sources( # doctest: +SKIP ... token, ... bbox=(-104.5, 31.0, -101.5, 33.5), ... sectors=["1B2"], ... ) sorted(sources, key=lambda s: -(s.emission_auto or 0))[:3] # doctest: +SKIP [, , ]

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_sources(
    token: str,
    *,
    bbox: BBox | None = None,
    sectors: list[str] | None = None,
    gas: Gas | Literal["CH4", "CO2"] | None = Gas.CH4,
) -> list[CMSource]:
    """List Carbon Mapper sources matching filters.

    Wraps the source listing endpoint (REST Catalog). Each item is
    parsed via :meth:`CMSource.from_geojson_feature`, which strips the
    source-name query-suffix.

    Parameters
    ----------
    token:
        Bearer token.
    bbox:
        ``(W, S, E, N)`` WGS-84 spatial filter (REST repeated-keys
        encoding).
    sectors:
        IPCC sector codes.
    gas:
        :data:`Gas.CH4` (default), :data:`Gas.CO2`, or ``None`` for
        both gases.

    Returns
    -------
    list[CMSource]

    Examples
    --------
    Top oil & gas sources in the Permian:

    >>> sources = list_sources(  # doctest: +SKIP
    ...     token,
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     sectors=["1B2"],
    ... )
    >>> sorted(sources, key=lambda s: -(s.emission_auto or 0))[:3]  # doctest: +SKIP
    [<CMSource ...>, <CMSource ...>, <CMSource ...>]
    """
    # The source listing lives at `/catalog/sources.geojson` and returns a
    # GeoJSON FeatureCollection. Query it with REST repeated-keys bbox.
    params: list[tuple[str, str]] = []
    if gas is not None:
        params.append(("plume_gas", str(gas)))
    for key, values in _dl._rest_bbox_params(bbox).items():
        params.extend((key, v) for v in values)
    if sectors:
        for s in sectors:
            params.append(("sectors", s))
    resp = _dl._request(
        "GET",
        f"{_dl.CATALOG_URL}/sources.geojson",
        params=params,
        headers=_dl._headers(token),
        timeout=60,
    )
    resp.raise_for_status()
    fc = resp.json()
    features = fc.get("features", []) if isinstance(fc, Mapping) else []
    return [CMSource.from_geojson_feature(f) for f in features]

list_tiles(token, *, bbox=None, datetime_min=None, datetime_max=None, collection=None, limit=1000)

Materialised list of L2B STAC items matching filters.

Wraps /stac/search (comma-joined STAC bbox encoding). A scene registered under several collection versions is returned once, from the newest version.

Parameters

token: Bearer token. bbox: (W, S, E, N) WGS-84 spatial filter. datetime_min, datetime_max: Optional UTC bounds. collection: One STAC collection id or several. None (default) searches every known CH4 L2B version (:data:~geoproducts.carbonmapper.rasters.DEFAULT_L2B_CH4_COLLECTION_CANDIDATES) — STAC registers current versions as of 2026-09. limit: Max items in this call.

Returns

list[CMTileItem]

Examples

tiles = list_tiles( # doctest: +SKIP ... token, bbox=(-104.5, 31.0, -101.5, 33.5), limit=10, ... ) {t.platform for t in tiles} # doctest: +SKIP

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_tiles(
    token: str,
    *,
    bbox: BBox | None = None,
    datetime_min: datetime | None = None,
    datetime_max: datetime | None = None,
    collection: str | Sequence[str] | None = None,
    limit: int = 1_000,
) -> list[CMTileItem]:
    """Materialised list of L2B STAC items matching filters.

    Wraps ``/stac/search`` (comma-joined STAC bbox encoding). A scene
    registered under several collection versions is returned once, from
    the newest version.

    Parameters
    ----------
    token:
        Bearer token.
    bbox:
        ``(W, S, E, N)`` WGS-84 spatial filter.
    datetime_min, datetime_max:
        Optional UTC bounds.
    collection:
        One STAC collection id or several. ``None`` (default) searches
        every known CH4 L2B version
        (:data:`~geoproducts.carbonmapper.rasters.DEFAULT_L2B_CH4_COLLECTION_CANDIDATES`)
        — STAC registers current versions as of 2026-09.
    limit:
        Max items in this call.

    Returns
    -------
    list[CMTileItem]

    Examples
    --------
    >>> tiles = list_tiles(  # doctest: +SKIP
    ...     token, bbox=(-104.5, 31.0, -101.5, 33.5), limit=10,
    ... )
    >>> {t.platform for t in tiles}  # doctest: +SKIP
    {'Tanager1', 'EMIT'}
    """
    if collection is None:
        from geoproducts.carbonmapper.rasters import (
            DEFAULT_L2B_CH4_COLLECTION_CANDIDATES,
        )

        collections = list(DEFAULT_L2B_CH4_COLLECTION_CANDIDATES)
    elif isinstance(collection, str):
        collections = [collection]
    else:
        collections = list(collection)
    dt_range = time_interval(datetime_min, datetime_max)
    result = _dl.stac_search(
        collections=collections,
        bbox=bbox,
        datetime_range=dt_range,
        limit=limit,
        token=token,
    )
    features = result.get("features", []) if isinstance(result, Mapping) else []
    return _dedupe_newest([CMTileItem.from_stac_item(f) for f in features])

list_tiles_for_source(token, source_name, *, collection=None)

All distinct parent L2B tiles touched by a source's plumes.

Implementation:

  1. :func:list_plumes_for_source — every plume attributed to the source.
  2. Map each distinct scene_id to the L2B collection(s) of its plume's own gas and version (collection overrides this).
  3. stac_search(collections=..., ids=[...]) per collection group, at most 100 ids per request — resolve to STAC items, one per scene.

Useful for tile-level backfill: given a chronic emitter, fetch every L2B scene that ever observed it, regardless of whether plumes were detected on a given pass.

Parameters

token: Bearer token. source_name: Canonical or query-suffixed source name. collection: Explicit STAC collection for every scene. None (default) uses each plume's own gas/version collection(s).

Returns

list[CMTileItem] Empty list if the source has no plumes. Scenes whose L2B item isn't in STAC under the plume's version are omitted — use :func:get_image_raster_for_plume to probe older versions.

Examples

tiles = list_tiles_for_source( # doctest: +SKIP ... token, "CH4_1B2_100m_-104.17525_32.49125", ... ) sorted({t.platform for t in tiles}) # doctest: +SKIP ['EMIT', 'Tanager1']

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/api_queries.py
def list_tiles_for_source(
    token: str,
    source_name: str,
    *,
    collection: str | None = None,
) -> list[CMTileItem]:
    """All distinct parent L2B tiles touched by a source's plumes.

    Implementation:

    1. :func:`list_plumes_for_source` — every plume attributed to the
       source.
    2. Map each distinct scene_id to the L2B collection(s) of its
       plume's own gas and version (``collection`` overrides this).
    3. ``stac_search(collections=..., ids=[...])`` per collection group,
       at most 100 ids per request — resolve to STAC items, one per
       scene.

    Useful for tile-level backfill: given a chronic emitter, fetch
    every L2B scene that ever observed it, regardless of whether
    plumes were detected on a given pass.

    Parameters
    ----------
    token:
        Bearer token.
    source_name:
        Canonical or query-suffixed source name.
    collection:
        Explicit STAC collection for every scene. ``None`` (default)
        uses each plume's own gas/version collection(s).

    Returns
    -------
    list[CMTileItem]
        Empty list if the source has no plumes. Scenes whose L2B item
        isn't in STAC under the plume's version are omitted — use
        :func:`get_image_raster_for_plume` to probe older versions.

    Examples
    --------
    >>> tiles = list_tiles_for_source(  # doctest: +SKIP
    ...     token, "CH4_1B2_100m_-104.17525_32.49125",
    ... )
    >>> sorted({t.platform for t in tiles})  # doctest: +SKIP
    ['EMIT', 'Tanager1']
    """
    plumes = list_plumes_for_source(token, source_name)
    by_collections: dict[tuple[str, ...], set[str]] = {}
    for p in plumes:
        if collection is not None:
            colls: tuple[str, ...] = (collection,)
        else:
            spec = p.collection_spec
            colls = (
                tuple(
                    c
                    for c in _stac_l2b_candidates(spec)
                    if c.endswith(f"-{spec.version}")
                )
                if spec is not None
                else (DEFAULT_L2B_COLLECTION,)
            )
        by_collections.setdefault(colls, set()).add(_scene_id_from_plume(p.plume_id))

    tiles: dict[str, CMTileItem] = {}
    for colls, scene_set in by_collections.items():
        scene_ids = sorted(scene_set)
        for i in range(0, len(scene_ids), _STAC_IDS_PER_REQUEST):
            chunk = scene_ids[i : i + _STAC_IDS_PER_REQUEST]
            result = _dl.stac_search(
                collections=list(colls),
                ids=chunk,
                limit=len(chunk) * len(colls),
                token=token,
            )
            features = result.get("features", []) if isinstance(result, Mapping) else []
            for f in features:
                item = CMTileItem.from_stac_item(f)
                tiles.setdefault(item.scene_id, item)
    return [tiles[k] for k in sorted(tiles)]

geoproducts.carbonmapper.download

download.py

Carbon Mapper Data Platform API client.

Provides typed wrappers around three Carbon Mapper APIs:

1. **REST Catalog API**  — plumes, sources, scenes, plume CSV, assets
2. **STAC API**          — spatiotemporal search across collections
3. **Asset Download**    — GeoTIFF retrievals, RGB imagery, plume PNGs

Authentication

Most read endpoints work without a token, but some (scenes, related plumes, STAC tokens) require a Bearer token. Use :func:obtain_token or :meth:~geoproducts.carbonmapper.config.CarbonMapperConfig.refresh_access_token to obtain one from credentials in ~/.geoproducts/auth_carbonmapper.json.

References

  • API Docs : https://api.carbonmapper.org/api/v1/docs
  • STAC Root : https://api.carbonmapper.org/api/v1/stac/
  • Registration : https://data.carbonmapper.org

download_asset(asset_key, dest, token=None)

Download a raster asset (GeoTIFF or PNG) by its storage key.

Parameters

asset_key: The path portion after /catalog/asset/. For example::

    l2b-ch4-mf-v1/2016/10/08/ang20161008t211637/ang20161008t211637_l2b-ch4-mf-v1_cmf.tif

Asset keys are available in STAC item ``assets[name]["href"]``
entries and can be derived from the plume ``plume_tif`` /
``con_tif`` / ``rgb_tif`` URLs.

dest: Local file path where the asset will be written. Parent directories are created automatically. token: Optional Bearer token for authenticated access.

Returns

Path The resolved path of the downloaded file.

Examples

download_asset( ... "l2b-ch4-mf-v1/2016/10/08/ang20161008t211637/" ... "ang20161008t211637_l2b-ch4-mf-v1_cmf.tif", ... dest="./retrieval.tif", ... )

.. note:: For plume dicts returned by :func:get_plumes_annotated, prefer :func:download_plume_assets which handles all assets at once.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def download_asset(asset_key: str, dest: Path | str, token: str | None = None) -> Path:
    """
    Download a raster asset (GeoTIFF or PNG) by its storage key.

    Parameters
    ----------
    asset_key:
        The path portion after ``/catalog/asset/``.  For example::

            l2b-ch4-mf-v1/2016/10/08/ang20161008t211637/ang20161008t211637_l2b-ch4-mf-v1_cmf.tif

        Asset keys are available in STAC item ``assets[name]["href"]``
        entries and can be derived from the plume ``plume_tif`` /
        ``con_tif`` / ``rgb_tif`` URLs.
    dest:
        Local file path where the asset will be written.  Parent
        directories are created automatically.
    token:
        Optional Bearer token for authenticated access.

    Returns
    -------
    Path
        The resolved path of the downloaded file.

    Examples
    --------
    >>> download_asset(
    ...     "l2b-ch4-mf-v1/2016/10/08/ang20161008t211637/"
    ...     "ang20161008t211637_l2b-ch4-mf-v1_cmf.tif",
    ...     dest="./retrieval.tif",
    ... )

    .. note::
        For plume dicts returned by :func:`get_plumes_annotated`, prefer
        :func:`download_plume_assets` which handles all assets at once.
    """
    dest = Path(dest)
    url = f"{CATALOG_URL}/asset/{asset_key}"
    resp = _request("GET", url, headers=_headers(token), timeout=120, stream=True)
    resp.raise_for_status()
    dest.parent.mkdir(parents=True, exist_ok=True)
    _stream_to_file(resp, dest)
    logger.info("Downloaded %s → %s (%d bytes)", asset_key, dest, dest.stat().st_size)
    return dest

download_plume_assets(plume, dest_dir)

Download all available raster assets for a single plume.

Given a plume dict returned by :func:get_plumes_annotated, download every non-null asset URL into dest_dir and return a mapping of asset type to local file path.

Parameters

plume: A single plume dict as returned in get_plumes_annotated()["items"]. The function inspects the "plume_png", "plume_tif", "con_tif", "rgb_png", "rgb_tif", and "plume_rgb_png" keys for download URLs. dest_dir: Directory into which assets are downloaded. Created automatically if it does not already exist.

Returns

dict[str, Path] Mapping of asset type → local :class:~pathlib.Path for each successfully downloaded asset. Assets that are missing (null) or whose download fails are omitted. Example::

    {
        "plume_png": Path("./plumes/emi20240420t101448p07050-A_plume.png"),
        "plume_tif": Path("./plumes/emi20240420t101448p07050-A_plume.tif"),
        "con_tif": Path("./plumes/emi20240420t101448p07050-A_con.tif"),
        "rgb_png": Path("./plumes/emi20240420t101448p07050-A_rgb.png"),
    }
Examples

.. code-block:: python

result = get_plumes_annotated(plume_gas="CH4", limit=1, qualities=["good"])
plume = result["items"][0]
downloaded = download_plume_assets(plume, "./plume_data/")
for asset_type, path in downloaded.items():
    print(asset_type, "→", path)
Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def download_plume_assets(plume: dict, dest_dir: Path | str) -> dict[str, Path]:
    """
    Download all available raster assets for a single plume.

    Given a plume dict returned by :func:`get_plumes_annotated`, download
    every non-null asset URL into *dest_dir* and return a mapping of asset
    type to local file path.

    Parameters
    ----------
    plume:
        A single plume dict as returned in
        ``get_plumes_annotated()["items"]``.  The function inspects the
        ``"plume_png"``, ``"plume_tif"``, ``"con_tif"``, ``"rgb_png"``,
        ``"rgb_tif"``, and ``"plume_rgb_png"`` keys for download URLs.
    dest_dir:
        Directory into which assets are downloaded.  Created automatically
        if it does not already exist.

    Returns
    -------
    dict[str, Path]
        Mapping of asset type → local :class:`~pathlib.Path` for each
        successfully downloaded asset.  Assets that are missing (``null``)
        or whose download fails are omitted.  Example::

            {
                "plume_png": Path("./plumes/emi20240420t101448p07050-A_plume.png"),
                "plume_tif": Path("./plumes/emi20240420t101448p07050-A_plume.tif"),
                "con_tif": Path("./plumes/emi20240420t101448p07050-A_con.tif"),
                "rgb_png": Path("./plumes/emi20240420t101448p07050-A_rgb.png"),
            }

    Examples
    --------
    .. code-block:: python

        result = get_plumes_annotated(plume_gas="CH4", limit=1, qualities=["good"])
        plume = result["items"][0]
        downloaded = download_plume_assets(plume, "./plume_data/")
        for asset_type, path in downloaded.items():
            print(asset_type, "→", path)
    """
    dest_dir = Path(dest_dir)
    dest_dir.mkdir(parents=True, exist_ok=True)
    plume_name = plume.get("plume_id", "unknown")
    downloaded: dict[str, Path] = {}

    asset_keys = [
        "plume_png",
        "plume_tif",
        "con_tif",
        "rgb_png",
        "rgb_tif",
        "plume_rgb_png",
    ]
    for key in asset_keys:
        url = plume.get(key)
        if not url:
            continue
        suffix = ".tif" if key.endswith("tif") else ".png"
        short = key.replace("_tif", "").replace("_png", "")
        local = dest_dir / f"{plume_name}_{short}{suffix}"
        try:
            resp = _request("GET", url, timeout=120, stream=True)
            resp.raise_for_status()
            _stream_to_file(resp, local)
            downloaded[key] = local
            logger.info("  %s → %s", key, local)
        except requests.RequestException as exc:
            logger.warning("  %s download failed: %s", key, exc)
    return downloaded

export_plumes_to_geojson(plumes, output)

Convert a list of plume dicts into a GeoJSON FeatureCollection and write to output.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def export_plumes_to_geojson(plumes: list[dict], output: Path | str) -> Path:
    """
    Convert a list of plume dicts into a GeoJSON FeatureCollection and
    write to *output*.
    """
    output = Path(output)
    features = []
    for p in plumes:
        geom = p.get("geometry_json")
        props = {k: v for k, v in p.items() if k != "geometry_json"}
        features.append({"type": "Feature", "geometry": geom, "properties": props})
    fc = {"type": "FeatureCollection", "features": features}
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(fc, indent=2))
    logger.info("Wrote %d features → %s", len(features), output)
    return output

get_plume_by_id(plume_id, token=None)

Get a single plume by its UUID or colloquial name.

Parameters

plume_id: The unique plume identifier. Either the UUID form ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") or the colloquial name derived from the scene (e.g. "emi20240420t101448p07050-A"). token: Optional Bearer token for authenticated requests.

Returns

dict A single plume dict with the same schema as each element of get_plumes_annotated()["items"].

Examples

plume = get_plume_by_id("emi20240420t101448p07050-A") print(plume["emission_auto"], "kg/hr")

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_plume_by_id(plume_id: str, token: str | None = None) -> dict:
    """
    Get a single plume by its UUID or colloquial name.

    Parameters
    ----------
    plume_id:
        The unique plume identifier.  Either the UUID form
        (``"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"``) or the colloquial
        name derived from the scene (e.g. ``"emi20240420t101448p07050-A"``).
    token:
        Optional Bearer token for authenticated requests.

    Returns
    -------
    dict
        A single plume dict with the same schema as each element of
        ``get_plumes_annotated()["items"]``.

    Examples
    --------
    >>> plume = get_plume_by_id("emi20240420t101448p07050-A")
    >>> print(plume["emission_auto"], "kg/hr")
    """
    return cast(dict, _get(f"{CATALOG_URL}/plume/{plume_id}", token=token))

get_plumes_annotated(*, plume_gas=None, bbox=None, datetime_range=None, published_at_range=None, created_at_range=None, modified_at_range=None, sectors=None, instruments=None, emission_min=None, emission_max=None, qualities=None, has_phme=None, source_name=None, limit=25, offset=0, sort='desc', token=None)

Fetch annotated plumes with emissions, wind, and image URLs.

This is the primary public endpoint — no auth required for published data, though authenticated requests may see additional fields.

Parameters

plume_gas: Gas species to filter by. "CH4" (methane) or "CO2" (carbon dioxide). Omit to return both gases. bbox: Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84 decimal degrees. Example: (-104.5, 31.0, -101.5, 33.5) for the Permian Basin. datetime_range: RFC 3339 time interval string, e.g. "2024-01-01T00:00:00Z/2024-06-01T00:00:00Z". Either bound may be replaced with ".." to indicate open-ended. Filters on observation time (scene_timestamp) — for "what was published this period?" use published_at_range instead: Carbon Mapper frequently publishes plumes weeks-to-months after acquisition. published_at_range: RFC 3339 interval (same format as datetime_range) filtering on publication date (published_at) — the axis ingest pipelines polling for newly published plumes need. Sent as the API's published_at_datetime param. created_at_range: RFC 3339 interval filtering on catalog-record creation date (created_at). modified_at_range: RFC 3339 interval filtering on catalog-record modification date (modified_at). sectors: One or more IPCC sector codes to filter by. Common values: "1B2" (Oil & Gas), "6A" (Solid Waste), "1B1a" (Coal Mining), "4B" (Livestock), "other". instruments: Instrument identifiers to restrict results to. Recognised values: "emi" (EMIT on the ISS), "tan" (Tanager-1 satellite), "ang" (AVIRIS-NG airborne), "GAO" (Global Airborne Observatory), "av3" (AVIRIS-3 airborne). emission_min: Lower bound on emission_auto in kg/hr (inclusive). emission_max: Upper bound on emission_auto in kg/hr (inclusive). qualities: Plume quality flags to include. One or more of "good", "questionable", "bad". has_phme: When True, return only plumes flagged as a Potentially Harmful Methane Event (PHME). When False, exclude them. None (default) applies no PHME filter. source_name: Return only plumes associated with a specific emission source, e.g. "CH4_6A_100m_-74.00656_40.71283". limit: Maximum number of plumes to return in a single response. The server caps this at 1 000 per request. Use offset or :func:paginate_plumes for larger result sets. offset: Zero-based index of the first result to return. Use with limit for manual pagination. sort: Result ordering direction. "desc" (default) returns the most recently detected plumes first; "asc" returns oldest first. token: Bearer token for authenticated requests (see :func:obtain_token). Not required for publicly available data.

Returns

dict A mapping with the following top-level keys:

- ``"items"`` — list of plume dicts.  Each dict contains:

  - ``"plume_id"``                    — unique identifier string.
  - ``"gas"``                          — ``"CH4"`` or ``"CO2"``.
  - ``"geometry_json"``               — GeoJSON geometry (Point or Polygon).
  - ``"emission_auto"``               — estimated emission rate in **kg/hr**.
  - ``"emission_uncertainty_auto"``   — 1-σ uncertainty in kg/hr.
  - ``"wind_speed_avg_auto"``         — average wind speed in m/s.
  - ``"wind_direction_avg_auto"``     — meteorological wind direction
    in degrees.
  - ``"plume_png"``, ``"plume_tif"``, ``"con_tif"``, ``"rgb_png"``,
    ``"rgb_tif"``, ``"plume_rgb_png"`` — pre-signed download URLs for
    raster assets (may be ``null`` if unavailable).
  - ``"sector"``                      — IPCC sector code.
  - ``"plume_quality"``               — quality flag.
  - ``"instrument"``                  — sensor identifier.
  - ``"platform"``                    — e.g. ``"ISS"``, ``"satellite"``.
  - ``"scene_timestamp"``             — ISO 8601 acquisition time (UTC).

- ``"total_count"`` — total number of matching plumes (across all pages).
- ``"bbox_count"``  — number of matching plumes inside the requested bbox.
Examples

Fetch the 10 most recent good-quality CH4 plumes in the Permian Basin:

result = get_plumes_annotated( ... plume_gas="CH4", ... bbox=(-104.5, 31.0, -101.5, 33.5), ... qualities=["good"], ... limit=10, ... ) print(result["total_count"]) for p in result["items"]: ... print(p["plume_id"], p["emission_auto"], "kg/hr")

Filter by sector and emission threshold (Oil & Gas, ≥ 500 kg/hr):

result = get_plumes_annotated( ... plume_gas="CH4", ... sectors=["1B2"], ... emission_min=500, ... limit=25, ... )

Authenticated request for additional fields:

tokens = obtain_token("user@example.com", "s3cret") result = get_plumes_annotated( ... plume_gas="CH4", ... limit=5, ... token=tokens["access"], ... )

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_plumes_annotated(
    *,
    plume_gas: str | None = None,
    bbox: tuple[float, float, float, float] | None = None,
    datetime_range: str | None = None,
    published_at_range: str | None = None,
    created_at_range: str | None = None,
    modified_at_range: str | None = None,
    sectors: list[str] | None = None,
    instruments: list[str] | None = None,
    emission_min: int | None = None,
    emission_max: int | None = None,
    qualities: list[str] | None = None,
    has_phme: bool | None = None,
    source_name: str | None = None,
    limit: int = 25,
    offset: int = 0,
    sort: str = "desc",
    token: str | None = None,
) -> dict:
    """
    Fetch annotated plumes with emissions, wind, and image URLs.

    This is the primary public endpoint — no auth required for published
    data, though authenticated requests may see additional fields.

    Parameters
    ----------
    plume_gas:
        Gas species to filter by.  ``"CH4"`` (methane) or ``"CO2"``
        (carbon dioxide).  Omit to return both gases.
    bbox:
        Bounding-box spatial filter as
        ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84 decimal
        degrees.  Example: ``(-104.5, 31.0, -101.5, 33.5)`` for the
        Permian Basin.
    datetime_range:
        RFC 3339 time interval string, e.g.
        ``"2024-01-01T00:00:00Z/2024-06-01T00:00:00Z"``.  Either bound
        may be replaced with ``".."`` to indicate open-ended.  Filters
        on **observation time** (``scene_timestamp``) — for "what was
        *published* this period?" use *published_at_range* instead:
        Carbon Mapper frequently publishes plumes weeks-to-months
        after acquisition.
    published_at_range:
        RFC 3339 interval (same format as *datetime_range*) filtering
        on **publication date** (``published_at``) — the axis ingest
        pipelines polling for newly published plumes need.  Sent as
        the API's ``published_at_datetime`` param.
    created_at_range:
        RFC 3339 interval filtering on catalog-record **creation
        date** (``created_at``).
    modified_at_range:
        RFC 3339 interval filtering on catalog-record **modification
        date** (``modified_at``).
    sectors:
        One or more IPCC sector codes to filter by.  Common values:
        ``"1B2"`` (Oil & Gas), ``"6A"`` (Solid Waste), ``"1B1a"``
        (Coal Mining), ``"4B"`` (Livestock), ``"other"``.
    instruments:
        Instrument identifiers to restrict results to.  Recognised values:
        ``"emi"`` (EMIT on the ISS), ``"tan"`` (Tanager-1 satellite),
        ``"ang"`` (AVIRIS-NG airborne), ``"GAO"`` (Global Airborne
        Observatory), ``"av3"`` (AVIRIS-3 airborne).
    emission_min:
        Lower bound on ``emission_auto`` in **kg/hr** (inclusive).
    emission_max:
        Upper bound on ``emission_auto`` in **kg/hr** (inclusive).
    qualities:
        Plume quality flags to include.  One or more of ``"good"``,
        ``"questionable"``, ``"bad"``.
    has_phme:
        When ``True``, return only plumes flagged as a Potentially Harmful
        Methane Event (PHME).  When ``False``, exclude them.  ``None``
        (default) applies no PHME filter.
    source_name:
        Return only plumes associated with a specific emission source, e.g.
        ``"CH4_6A_100m_-74.00656_40.71283"``.
    limit:
        Maximum number of plumes to return in a single response.  The
        server caps this at **1 000** per request.  Use *offset* or
        :func:`paginate_plumes` for larger result sets.
    offset:
        Zero-based index of the first result to return.  Use with *limit*
        for manual pagination.
    sort:
        Result ordering direction.  ``"desc"`` (default) returns the most
        recently detected plumes first; ``"asc"`` returns oldest first.
    token:
        Bearer token for authenticated requests (see :func:`obtain_token`).
        Not required for publicly available data.

    Returns
    -------
    dict
        A mapping with the following top-level keys:

        - ``"items"`` — list of plume dicts.  Each dict contains:

          - ``"plume_id"``                    — unique identifier string.
          - ``"gas"``                          — ``"CH4"`` or ``"CO2"``.
          - ``"geometry_json"``               — GeoJSON geometry (Point or Polygon).
          - ``"emission_auto"``               — estimated emission rate in **kg/hr**.
          - ``"emission_uncertainty_auto"``   — 1-σ uncertainty in kg/hr.
          - ``"wind_speed_avg_auto"``         — average wind speed in m/s.
          - ``"wind_direction_avg_auto"``     — meteorological wind direction
            in degrees.
          - ``"plume_png"``, ``"plume_tif"``, ``"con_tif"``, ``"rgb_png"``,
            ``"rgb_tif"``, ``"plume_rgb_png"`` — pre-signed download URLs for
            raster assets (may be ``null`` if unavailable).
          - ``"sector"``                      — IPCC sector code.
          - ``"plume_quality"``               — quality flag.
          - ``"instrument"``                  — sensor identifier.
          - ``"platform"``                    — e.g. ``"ISS"``, ``"satellite"``.
          - ``"scene_timestamp"``             — ISO 8601 acquisition time (UTC).

        - ``"total_count"`` — total number of matching plumes (across all pages).
        - ``"bbox_count"``  — number of matching plumes inside the requested bbox.

    Examples
    --------
    Fetch the 10 most recent good-quality CH4 plumes in the Permian Basin:

    >>> result = get_plumes_annotated(
    ...     plume_gas="CH4",
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     qualities=["good"],
    ...     limit=10,
    ... )
    >>> print(result["total_count"])
    >>> for p in result["items"]:
    ...     print(p["plume_id"], p["emission_auto"], "kg/hr")

    Filter by sector and emission threshold (Oil & Gas, ≥ 500 kg/hr):

    >>> result = get_plumes_annotated(
    ...     plume_gas="CH4",
    ...     sectors=["1B2"],
    ...     emission_min=500,
    ...     limit=25,
    ... )

    Authenticated request for additional fields:

    >>> tokens = obtain_token("user@example.com", "s3cret")
    >>> result = get_plumes_annotated(
    ...     plume_gas="CH4",
    ...     limit=5,
    ...     token=tokens["access"],
    ... )
    """
    params: dict[str, Any] = {"limit": limit, "offset": offset, "sort": sort}
    if plume_gas:
        params["plume_gas"] = plume_gas
    params.update(_rest_bbox_params(bbox))
    if datetime_range:
        params["datetime"] = datetime_range
    if published_at_range:
        params["published_at_datetime"] = published_at_range
    if created_at_range:
        params["created_at"] = created_at_range
    if modified_at_range:
        params["modified_at"] = modified_at_range
    if sectors:
        params["sectors"] = sectors
    if instruments:
        params["instruments"] = instruments
    if emission_min is not None:
        params["emission_min"] = emission_min
    if emission_max is not None:
        params["emission_max"] = emission_max
    if qualities:
        params["qualities"] = qualities
    if has_phme is not None:
        params["has_phme"] = str(has_phme).lower()
    if source_name:
        params["source_name"] = source_name
    return cast(
        dict, _get(f"{CATALOG_URL}/plumes/annotated", params=params, token=token)
    )

get_plumes_csv(*, plume_gas=None, bbox=None, datetime_range=None, published_at_range=None, created_at_range=None, modified_at_range=None, sectors=None, instruments=None, limit=50000, offset=0, token=None)

Download plume data as CSV text.

Returns the same plumes as :func:get_plumes_annotated but serialised as a comma-separated text string suitable for writing directly to a .csv file or loading into :func:pandas.read_csv.

Parameters

plume_gas: Gas species filter — "CH4" or "CO2". bbox: Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84. datetime_range: RFC 3339 time interval, e.g. "2024-01-01T00:00:00Z/2024-06-01T00:00:00Z". Filters on observation time (scene_timestamp). published_at_range: RFC 3339 interval filtering on publication date — sent as the API's published_at_datetime param. See :func:get_plumes_annotated. created_at_range: RFC 3339 interval on record creation date (created_at). modified_at_range: RFC 3339 interval on record modification date (modified_at). sectors: IPCC sector codes to include, e.g. ["1B2", "6A"]. instruments: Instrument identifiers, e.g. ["emi", "tan"]. limit: Maximum rows per request. The server caps at 10 000 when asset-URL columns (plume_tif, rgb_png, etc.) are included, or 50 000 when they are excluded. offset: Zero-based row offset for pagination. token: Optional Bearer token for authenticated requests.

Returns

str Raw CSV text with a header row followed by one row per plume. Columns include: plume_id, lat (→ plume_latitude), lon (→ plume_longitude), datetime, sector, gas, emission_auto, emission_uncertainty_auto, wind fields, and asset URLs. Pass raw column names directly to CMRawPlume — e.g. CMRawPlume(**row) from a pandas.read_csv iteration.

Examples

Save a bulk CSV for the Permian Basin to disk:

csv_text = get_plumes_csv( ... plume_gas="CH4", ... bbox=(-104.5, 31.0, -101.5, 33.5), ... limit=10_000, ... ) from pathlib import Path Path("permian_ch4.csv").write_text(csv_text)

Load into pandas:

import io, pandas as pd df = pd.read_csv(io.StringIO(csv_text))

.. note:: When file-URL columns are included the server caps limit at 10 000. For larger exports paginate with offset or filter with bbox / datetime_range.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_plumes_csv(
    *,
    plume_gas: str | None = None,
    bbox: tuple[float, float, float, float] | None = None,
    datetime_range: str | None = None,
    published_at_range: str | None = None,
    created_at_range: str | None = None,
    modified_at_range: str | None = None,
    sectors: list[str] | None = None,
    instruments: list[str] | None = None,
    limit: int = 50_000,
    offset: int = 0,
    token: str | None = None,
) -> str:
    """
    Download plume data as CSV text.

    Returns the same plumes as :func:`get_plumes_annotated` but serialised
    as a comma-separated text string suitable for writing directly to a
    ``.csv`` file or loading into :func:`pandas.read_csv`.

    Parameters
    ----------
    plume_gas:
        Gas species filter — ``"CH4"`` or ``"CO2"``.
    bbox:
        Bounding-box spatial filter as
        ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84.
    datetime_range:
        RFC 3339 time interval, e.g.
        ``"2024-01-01T00:00:00Z/2024-06-01T00:00:00Z"``.  Filters on
        **observation time** (``scene_timestamp``).
    published_at_range:
        RFC 3339 interval filtering on **publication date** — sent as
        the API's ``published_at_datetime`` param.  See
        :func:`get_plumes_annotated`.
    created_at_range:
        RFC 3339 interval on record **creation date** (``created_at``).
    modified_at_range:
        RFC 3339 interval on record **modification date**
        (``modified_at``).
    sectors:
        IPCC sector codes to include, e.g. ``["1B2", "6A"]``.
    instruments:
        Instrument identifiers, e.g. ``["emi", "tan"]``.
    limit:
        Maximum rows per request.  The server caps at **10 000** when
        asset-URL columns (``plume_tif``, ``rgb_png``, etc.) are included,
        or **50 000** when they are excluded.
    offset:
        Zero-based row offset for pagination.
    token:
        Optional Bearer token for authenticated requests.

    Returns
    -------
    str
        Raw CSV text with a header row followed by one row per plume.
        Columns include: ``plume_id``, ``lat`` (→ ``plume_latitude``),
        ``lon`` (→ ``plume_longitude``), ``datetime``,
        ``sector``, ``gas``, ``emission_auto``,
        ``emission_uncertainty_auto``, wind fields, and asset URLs.
        Pass raw column names directly to ``CMRawPlume`` — e.g.
        ``CMRawPlume(**row)`` from a ``pandas.read_csv`` iteration.

    Examples
    --------
    Save a bulk CSV for the Permian Basin to disk:

    >>> csv_text = get_plumes_csv(
    ...     plume_gas="CH4",
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     limit=10_000,
    ... )
    >>> from pathlib import Path
    >>> Path("permian_ch4.csv").write_text(csv_text)

    Load into pandas:

    >>> import io, pandas as pd
    >>> df = pd.read_csv(io.StringIO(csv_text))

    .. note::
        When file-URL columns are included the server caps *limit* at
        10 000.  For larger exports paginate with *offset* or filter with
        *bbox* / *datetime_range*.
    """
    params: dict[str, Any] = {"limit": limit, "offset": offset}
    if plume_gas:
        params["plume_gas"] = plume_gas
    params.update(_rest_bbox_params(bbox))
    if datetime_range:
        params["datetime"] = datetime_range
    if published_at_range:
        params["published_at_datetime"] = published_at_range
    if created_at_range:
        params["created_at"] = created_at_range
    if modified_at_range:
        params["modified_at"] = modified_at_range
    if sectors:
        params["sectors"] = sectors
    if instruments:
        params["instruments"] = instruments
    return cast(str, _get(f"{CATALOG_URL}/plume-csv", params=params, token=token))

get_scenes(*, instrument=None, plume_gas=None, has_plume_emissions=None, cloud_cover_pct_max=None, limit=25, offset=0, token=None)

List observation scenes (satellite or aircraft flight strips).

A scene is a single sensor overpass or flight strip captured by one of Carbon Mapper's instruments. Scenes describe the spatial footprint and metadata for the raw L2 observations from which plumes are derived.

.. note:: This endpoint requires authentication (see :func:obtain_token).

Parameters

instrument: Sensor identifier to filter by. One of "emi" (EMIT/ISS), "tan" (Tanager-1), "ang" (AVIRIS-NG), "GAO" (Global Airborne Observatory), or "av3" (AVIRIS-3). plume_gas: Gas species of interest — "CH4" or "CO2". has_plume_emissions: When True, return only scenes that contain at least one detected plume with quantified emissions. cloud_cover_pct_max: Maximum allowable cloud cover percentage (0 – 100). limit: Maximum number of scenes to return per page. offset: Zero-based pagination offset. token: Bearer token (required — see :func:obtain_token).

Returns

dict A mapping with "items" (list of scene dicts) and "total_count". Each scene dict includes scene ID, instrument, platform, acquisition datetime, spatial extent (GeoJSON), and cloud-cover percentage.

Examples

tokens = obtain_token("user@example.com", "s3cret") scenes = get_scenes( ... instrument="emi", ... has_plume_emissions=True, ... limit=5, ... token=tokens["access"], ... ) for s in scenes["items"]: ... print(s.get("scene_id"), s.get("datetime"))

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_scenes(
    *,
    instrument: str | None = None,
    plume_gas: str | None = None,
    has_plume_emissions: bool | None = None,
    cloud_cover_pct_max: float | None = None,
    limit: int = 25,
    offset: int = 0,
    token: str | None = None,
) -> dict:
    """
    List observation scenes (satellite or aircraft flight strips).

    A *scene* is a single sensor overpass or flight strip captured by one
    of Carbon Mapper's instruments.  Scenes describe the spatial footprint
    and metadata for the raw L2 observations from which plumes are derived.

    .. note::
        This endpoint requires authentication (see :func:`obtain_token`).

    Parameters
    ----------
    instrument:
        Sensor identifier to filter by.  One of ``"emi"`` (EMIT/ISS),
        ``"tan"`` (Tanager-1), ``"ang"`` (AVIRIS-NG), ``"GAO"``
        (Global Airborne Observatory), or ``"av3"`` (AVIRIS-3).
    plume_gas:
        Gas species of interest — ``"CH4"`` or ``"CO2"``.
    has_plume_emissions:
        When ``True``, return only scenes that contain at least one
        detected plume with quantified emissions.
    cloud_cover_pct_max:
        Maximum allowable cloud cover percentage (0 – 100).
    limit:
        Maximum number of scenes to return per page.
    offset:
        Zero-based pagination offset.
    token:
        Bearer token (required — see :func:`obtain_token`).

    Returns
    -------
    dict
        A mapping with ``"items"`` (list of scene dicts) and
        ``"total_count"``.  Each scene dict includes scene ID, instrument,
        platform, acquisition datetime, spatial extent (GeoJSON), and
        cloud-cover percentage.

    Examples
    --------
    >>> tokens = obtain_token("user@example.com", "s3cret")
    >>> scenes = get_scenes(
    ...     instrument="emi",
    ...     has_plume_emissions=True,
    ...     limit=5,
    ...     token=tokens["access"],
    ... )
    >>> for s in scenes["items"]:
    ...     print(s.get("scene_id"), s.get("datetime"))
    """
    params: dict[str, Any] = {"limit": limit, "offset": offset}
    if instrument:
        params["instrument"] = instrument
    if plume_gas:
        params["plume_gas"] = plume_gas
    if has_plume_emissions is not None:
        params["has_plume_emissions"] = str(has_plume_emissions).lower()
    if cloud_cover_pct_max is not None:
        params["cloud_cover_pct_max"] = cloud_cover_pct_max
    return cast(dict, _get(f"{CATALOG_URL}/scenes", params=params, token=token))

get_source_by_name(source_name, *, token=None)

Get a single Carbon Mapper source by its deterministic name.

A source is a DBSCAN cluster of plumes detected at the same geographic location. Source names follow the pattern {gas}_{sector}_{footprint_m}m_{lon}_{lat}, e.g. "CH4_1B2_100m_-104.17525_32.49125".

Wraps GET /catalog/source/{source_name}.

Parameters

source_name: Canonical source name. Strip any ?... query-string suffix first — see :func:geoproducts.carbonmapper.source._strip_query_suffix. token: Optional Bearer token.

Returns

dict Source record as a GeoJSON Feature (or, for some endpoints, a flat dict). The high-level :func:geoproducts.carbonmapper.api_queries.get_source normalises both shapes into a typed :class:CMSource.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_source_by_name(source_name: str, *, token: str | None = None) -> dict:
    """Get a single Carbon Mapper source by its deterministic name.

    A *source* is a DBSCAN cluster of plumes detected at the same
    geographic location. Source names follow the pattern
    ``{gas}_{sector}_{footprint_m}m_{lon}_{lat}``, e.g.
    ``"CH4_1B2_100m_-104.17525_32.49125"``.

    Wraps ``GET /catalog/source/{source_name}``.

    Parameters
    ----------
    source_name:
        Canonical source name. **Strip any ``?...`` query-string
        suffix first** — see
        :func:`geoproducts.carbonmapper.source._strip_query_suffix`.
    token:
        Optional Bearer token.

    Returns
    -------
    dict
        Source record as a GeoJSON Feature (or, for some endpoints,
        a flat dict). The high-level
        :func:`geoproducts.carbonmapper.api_queries.get_source` normalises
        both shapes into a typed :class:`CMSource`.
    """
    return cast(dict, _get(f"{CATALOG_URL}/source/{source_name}", token=token))

get_source_for_plume_name(plume_id, *, token=None)

Look up the Carbon Mapper source attributed to a plume.

Uses the by-name endpoint (GET /catalog/source/plume/name/{plume_id}), which returns the cleaned source_name — preferred over the UUID-keyed sibling /catalog/source/plume/{plume_uuid} when working with the colloquial plume_id strings (e.g. "emi20240420t101448p07050-A").

Parameters

plume_id: Colloquial plume identifier — "{instrument}{datetime}-{part}". token: Optional Bearer token.

Returns

dict Source record (GeoJSON Feature or flat dict). Returns 404 when CM has not yet attributed the plume to a source. The high-level :func:geoproducts.carbonmapper.api_queries.get_source_for_plume translates 404 into None.

Examples

raw = get_source_for_plume_name("tan20251212t185057c20s4001-E") raw.get("source_name") 'CH4_1B2_100m_-104.0_32.0'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_source_for_plume_name(
    plume_id: str,
    *,
    token: str | None = None,
) -> dict:
    """Look up the Carbon Mapper source attributed to a plume.

    Uses the *by-name* endpoint
    (``GET /catalog/source/plume/name/{plume_id}``), which returns the
    cleaned ``source_name`` — preferred over the UUID-keyed sibling
    ``/catalog/source/plume/{plume_uuid}`` when working with the
    colloquial plume_id strings (e.g. ``"emi20240420t101448p07050-A"``).

    Parameters
    ----------
    plume_id:
        Colloquial plume identifier — ``"{instrument}{datetime}-{part}"``.
    token:
        Optional Bearer token.

    Returns
    -------
    dict
        Source record (GeoJSON Feature or flat dict). Returns ``404``
        when CM has not yet attributed the plume to a source. The
        high-level :func:`geoproducts.carbonmapper.api_queries.get_source_for_plume`
        translates ``404`` into ``None``.

    Examples
    --------
    >>> raw = get_source_for_plume_name("tan20251212t185057c20s4001-E")
    >>> raw.get("source_name")
    'CH4_1B2_100m_-104.0_32.0'
    """
    return cast(dict, _get(f"{CATALOG_URL}/source/plume/name/{plume_id}", token=token))

get_source_plumes(source_name, *, token=None)

Fetch a Carbon Mapper source with its attributed plumes.

Wraps GET /catalog/source-plumes-csv/{source_name}. Despite the route's name it returns JSON: a PlumeSource object whose plumes array holds annotated plume records, each of which can be passed to :class:geoproducts.carbonmapper.plume.CMRawPlume.

Parameters

source_name: Canonical source name. Strip any ?... suffix first. token: Optional Bearer token.

Returns

dict The PlumeSource payload (plumes, scenes, point, source_name, observation_dates, ...).

Examples

payload = get_source_plumes( # doctest: +SKIP ... "CH4_1B2_100m_-104.17525_32.49125" ... ) len(payload["plumes"]) # doctest: +SKIP 47

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_source_plumes(
    source_name: str,
    *,
    token: str | None = None,
) -> dict:
    """Fetch a Carbon Mapper source with its attributed plumes.

    Wraps ``GET /catalog/source-plumes-csv/{source_name}``. Despite the
    route's name it returns JSON: a ``PlumeSource`` object whose
    ``plumes`` array holds annotated plume records, each of which can be
    passed to :class:`geoproducts.carbonmapper.plume.CMRawPlume`.

    Parameters
    ----------
    source_name:
        Canonical source name. Strip any ``?...`` suffix first.
    token:
        Optional Bearer token.

    Returns
    -------
    dict
        The ``PlumeSource`` payload (``plumes``, ``scenes``, ``point``,
        ``source_name``, ``observation_dates``, ...).

    Examples
    --------
    >>> payload = get_source_plumes(  # doctest: +SKIP
    ...     "CH4_1B2_100m_-104.17525_32.49125"
    ... )
    >>> len(payload["plumes"])  # doctest: +SKIP
    47
    """
    return cast(
        dict, _get(f"{CATALOG_URL}/source-plumes-csv/{source_name}", token=token)
    )

get_sources(*, source_gas=None, bbox=None, sectors=None, token=None)

Fetch emission sources (clusters of plumes at a location).

An emission source groups all plumes detected at the same geographic location into a persistent point source record. Each source includes aggregated statistics across all associated plumes.

Parameters:

Name Type Description Default
source_gas str | None

Gas species to filter by — "CH4" or "CO2".

None
bbox tuple[float, float, float, float] | None

Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84.

None
sectors list[str] | None

IPCC sector codes to include, e.g. ["1B2"] for Oil & Gas.

None
token str | None

Optional Bearer token for authenticated requests.

None

Returns:

Type Description
dict

The /catalog/sources.geojson GeoJSON FeatureCollection. Each

dict

feature carries the source centroid and properties such as

dict

source_name, sector, plume_count, persistence and

``emission_auto``.

func:~geoproducts.carbonmapper.list_sources

dict

parses the features into CMSource records.

Examples:

>>> sources = get_sources(source_gas="CH4", sectors=["1B2"])
>>> features = sources["features"]
>>> names = [f["properties"]["source_name"] for f in features]
Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def get_sources(
    *,
    source_gas: str | None = None,
    bbox: tuple[float, float, float, float] | None = None,
    sectors: list[str] | None = None,
    token: str | None = None,
) -> dict:
    """Fetch emission sources (clusters of plumes at a location).

    An *emission source* groups all plumes detected at the same geographic
    location into a persistent point source record.  Each source includes
    aggregated statistics across all associated plumes.

    Args:
        source_gas: Gas species to filter by — ``"CH4"`` or ``"CO2"``.
        bbox: Bounding-box spatial filter as
            ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84.
        sectors: IPCC sector codes to include, e.g. ``["1B2"]`` for Oil & Gas.
        token: Optional Bearer token for authenticated requests.

    Returns:
        The ``/catalog/sources.geojson`` GeoJSON FeatureCollection. Each
        feature carries the source centroid and properties such as
        ``source_name``, ``sector``, ``plume_count``, persistence and
        ``emission_auto``. :func:`~geoproducts.carbonmapper.list_sources`
        parses the features into ``CMSource`` records.

    Examples:
        >>> sources = get_sources(source_gas="CH4", sectors=["1B2"])  # doctest: +SKIP
        >>> features = sources["features"]  # doctest: +SKIP
        >>> names = [f["properties"]["source_name"] for f in features]  # doctest: +SKIP
    """
    params: dict[str, Any] = {}
    if source_gas:
        params["plume_gas"] = source_gas
    params.update(_rest_bbox_params(bbox))
    if sectors:
        params["sectors"] = sectors
    return cast(
        dict, _get(f"{CATALOG_URL}/sources.geojson", params=params, token=token)
    )

obtain_token(email, password)

Exchange credentials for a JWT access/refresh token pair.

Parameters

email: Registered Carbon Mapper account e-mail address. password: Account password.

Returns

dict A mapping with at least two keys:

- ``"access"``  — short-lived JWT bearer token (use in API calls).
- ``"refresh"`` — long-lived refresh token (use with :func:`refresh_token`).
Examples

tokens = obtain_token("user@example.com", "s3cret") access_token = tokens["access"] data = get_plumes_annotated(plume_gas="CH4", limit=5, token=access_token)

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def obtain_token(email: str, password: str) -> dict:
    """
    Exchange credentials for a JWT access/refresh token pair.

    Parameters
    ----------
    email:
        Registered Carbon Mapper account e-mail address.
    password:
        Account password.

    Returns
    -------
    dict
        A mapping with at least two keys:

        - ``"access"``  — short-lived JWT bearer token (use in API calls).
        - ``"refresh"`` — long-lived refresh token (use with :func:`refresh_token`).

    Examples
    --------
    >>> tokens = obtain_token("user@example.com", "s3cret")
    >>> access_token = tokens["access"]
    >>> data = get_plumes_annotated(plume_gas="CH4", limit=5, token=access_token)
    """
    return _post(f"{BASE_URL}/token/pair", {"email": email, "password": password})

paginate_plumes(*, plume_gas='CH4', bbox=None, datetime_range=None, max_plumes=100, page_size=50, token=None, **filters)

Auto-paginate through the annotated plumes endpoint.

  1. Request a page of min(page_size, remaining) rows at the current offset via :func:get_plumes_annotated.
  2. Stop when the page is empty, short (fewer rows than asked for — the server has no more), or the offset has reached the response's total_count (when the server reports one).
  3. Otherwise advance the offset and repeat until max_plumes rows have been collected.
Parameters

plume_gas: Gas species — "CH4" (default) or "CO2". bbox: Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84. datetime_range: RFC 3339 time interval, e.g. "2024-01-01T00:00:00Z/2024-06-01T00:00:00Z". max_plumes: Maximum total number of plume dicts to return (across all pages). page_size: Number of plumes to request per API call. Must not exceed 1 000. token: Optional Bearer token for authenticated requests. **filters: Any other :func:get_plumes_annotated filter, forwarded unchanged to every page — e.g. published_at_range, sectors, instruments, qualities, source_name.

Returns

list[dict] A flat list of plume dicts (same schema as get_plumes_annotated()["items"]), up to max_plumes entries.

Examples

Collect up to 500 recent CH4 plumes in the Permian Basin:

plumes = paginate_plumes( ... plume_gas="CH4", ... bbox=(-104.5, 31.0, -101.5, 33.5), ... max_plumes=500, ... page_size=100, ... ) print(f"Collected {len(plumes)} plumes")

Export to GeoJSON:

from pathlib import Path export_plumes_to_geojson(plumes, Path("permian_ch4.geojson"))

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def paginate_plumes(
    *,
    plume_gas: str | None = "CH4",
    bbox: tuple[float, float, float, float] | None = None,
    datetime_range: str | None = None,
    max_plumes: int = 100,
    page_size: int = 50,
    token: str | None = None,
    **filters: Any,
) -> list[dict]:
    """
    Auto-paginate through the annotated plumes endpoint.

    1. Request a page of ``min(page_size, remaining)`` rows at the
       current offset via :func:`get_plumes_annotated`.
    2. Stop when the page is empty, **short** (fewer rows than asked
       for — the server has no more), or the offset has reached the
       response's ``total_count`` (when the server reports one).
    3. Otherwise advance the offset and repeat until *max_plumes* rows
       have been collected.

    Parameters
    ----------
    plume_gas:
        Gas species — ``"CH4"`` (default) or ``"CO2"``.
    bbox:
        Bounding-box spatial filter as
        ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84.
    datetime_range:
        RFC 3339 time interval, e.g.
        ``"2024-01-01T00:00:00Z/2024-06-01T00:00:00Z"``.
    max_plumes:
        Maximum total number of plume dicts to return (across all pages).
    page_size:
        Number of plumes to request per API call.  Must not exceed 1 000.
    token:
        Optional Bearer token for authenticated requests.
    **filters:
        Any other :func:`get_plumes_annotated` filter, forwarded
        unchanged to every page — e.g. ``published_at_range``,
        ``sectors``, ``instruments``, ``qualities``, ``source_name``.

    Returns
    -------
    list[dict]
        A flat list of plume dicts (same schema as
        ``get_plumes_annotated()["items"]``), up to *max_plumes* entries.

    Examples
    --------
    Collect up to 500 recent CH4 plumes in the Permian Basin:

    >>> plumes = paginate_plumes(
    ...     plume_gas="CH4",
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     max_plumes=500,
    ...     page_size=100,
    ... )
    >>> print(f"Collected {len(plumes)} plumes")

    Export to GeoJSON:

    >>> from pathlib import Path
    >>> export_plumes_to_geojson(plumes, Path("permian_ch4.geojson"))
    """
    all_items: list[dict] = []
    offset = 0
    while len(all_items) < max_plumes:
        batch_size = min(page_size, max_plumes - len(all_items))
        result = get_plumes_annotated(
            plume_gas=plume_gas,
            bbox=bbox,
            datetime_range=datetime_range,
            limit=batch_size,
            offset=offset,
            token=token,
            **filters,
        )
        items = result.get("items", [])
        if not items:
            break
        all_items.extend(items)
        offset += len(items)
        if len(items) < batch_size:
            break
        total = result.get("total_count")
        if total is not None and offset >= total:
            break
    return all_items[:max_plumes]

refresh_token(refresh)

Refresh an expired access token using a refresh token.

Parameters

refresh: The "refresh" value previously returned by :func:obtain_token.

Returns

dict A mapping with a new "access" token (and optionally a new "refresh" token if the server rotates them).

Examples

tokens = obtain_token("user@example.com", "s3cret") new_tokens = refresh_token(tokens["refresh"]) access_token = new_tokens["access"]

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def refresh_token(refresh: str) -> dict:
    """
    Refresh an expired access token using a refresh token.

    Parameters
    ----------
    refresh:
        The ``"refresh"`` value previously returned by :func:`obtain_token`.

    Returns
    -------
    dict
        A mapping with a new ``"access"`` token (and optionally a new
        ``"refresh"`` token if the server rotates them).

    Examples
    --------
    >>> tokens = obtain_token("user@example.com", "s3cret")
    >>> new_tokens = refresh_token(tokens["refresh"])
    >>> access_token = new_tokens["access"]
    """
    return _post(f"{BASE_URL}/token/refresh", {"refresh": refresh})

stac_get_catalog()

Get the STAC root catalog with links to all collections.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_get_catalog() -> dict:
    """Get the STAC root catalog with links to all collections."""
    return cast(dict, _get(f"{STAC_URL}/"))

stac_get_collection(collection_id)

Get metadata for a single collection.

Key collections
  • l2b-ch4-mfa-v3 — CH4 matched-filter atmospheric retrievals (GeoTIFF)
  • l2b-co2-mfal-v3a — CO2 retrievals (log-normal variant)
  • l2b-rgb-v3a — simultaneous RGB surface imagery (GeoTIFF)
  • l2c-ch4-v0 — CH4 plume detections
  • l2c-co2-v0 — CO2 plume detections
  • l3a-ime-ch4-mfa-v3a — preliminary plume IME estimates
  • l4a-combined-ch4-v3a — final combined CH4 plume emissions
  • l4a-co2-mfal-v3a — final CO2 plume emissions
Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_get_collection(collection_id: str) -> dict:
    """
    Get metadata for a single collection.

    Key collections
    ---------------
    - ``l2b-ch4-mfa-v3``       — CH4 matched-filter atmospheric retrievals (GeoTIFF)
    - ``l2b-co2-mfal-v3a``     — CO2 retrievals (log-normal variant)
    - ``l2b-rgb-v3a``          — simultaneous RGB surface imagery (GeoTIFF)
    - ``l2c-ch4-v0``           — CH4 plume detections
    - ``l2c-co2-v0``           — CO2 plume detections
    - ``l3a-ime-ch4-mfa-v3a``  — preliminary plume IME estimates
    - ``l4a-combined-ch4-v3a`` — final combined CH4 plume emissions
    - ``l4a-co2-mfal-v3a``     — final CO2 plume emissions
    """
    return cast(dict, _get(f"{STAC_URL}/collections/{collection_id}"))

stac_get_item(collection_id, item_id, *, token=None)

Get a single STAC item by collection ID and item ID.

Wraps GET /stac/collections/{collection_id}/items/{item_id}. The item ID for a Carbon Mapper L2B raster matches the scene_id — i.e. plume_id.rsplit("-", 1)[0].

Parameters

collection_id: STAC collection identifier, e.g. "l2b-ch4-mfa-v3a" for the L2B CH4 matched-filter rasters. item_id: Item identifier (= scene_id for L2B rasters). token: Optional Bearer token. STAC item endpoints generally accept unauthenticated requests for published items.

Returns

dict STAC Item GeoJSON (a single Feature with "id", "bbox", "geometry", "properties", "assets").

Raises

requests.HTTPError 404 when the scene has not been published to L2B yet — the higher-level :func:geoproducts.carbonmapper.api_queries.get_tile translates this into CMSceneNotPublished.

Examples

item = stac_get_item( ... "l2b-ch4-mfa-v3a", ... "tan20251212t185057c20s4001", ... ) sorted(item["assets"]) ['artifact-mask', 'cmf', 'rgb', 'uncertainty']

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_get_item(
    collection_id: str,
    item_id: str,
    *,
    token: str | None = None,
) -> dict:
    """Get a single STAC item by collection ID and item ID.

    Wraps ``GET /stac/collections/{collection_id}/items/{item_id}``. The
    item ID for a Carbon Mapper L2B raster matches the *scene_id* — i.e.
    ``plume_id.rsplit("-", 1)[0]``.

    Parameters
    ----------
    collection_id:
        STAC collection identifier, e.g. ``"l2b-ch4-mfa-v3a"`` for the
        L2B CH4 matched-filter rasters.
    item_id:
        Item identifier (= scene_id for L2B rasters).
    token:
        Optional Bearer token. STAC item endpoints generally accept
        unauthenticated requests for published items.

    Returns
    -------
    dict
        STAC Item GeoJSON (a single Feature with ``"id"``, ``"bbox"``,
        ``"geometry"``, ``"properties"``, ``"assets"``).

    Raises
    ------
    requests.HTTPError
        ``404`` when the scene has not been published to L2B yet — the
        higher-level :func:`geoproducts.carbonmapper.api_queries.get_tile`
        translates this into ``CMSceneNotPublished``.

    Examples
    --------
    >>> item = stac_get_item(
    ...     "l2b-ch4-mfa-v3a",
    ...     "tan20251212t185057c20s4001",
    ... )
    >>> sorted(item["assets"])
    ['artifact-mask', 'cmf', 'rgb', 'uncertainty']
    """
    return cast(
        dict,
        _get(
            f"{STAC_URL}/collections/{collection_id}/items/{item_id}",
            token=token,
        ),
    )

stac_get_items(collection_id, *, limit=10, bbox=None, datetime_range=None, token=None)

Get items from a STAC collection (OGC API Features compliant).

Parameters

collection_id: Identifier of the STAC collection to query, e.g. "l4a-combined-ch4-v3a" or "l2b-rgb-v3a". limit: Maximum number of items to return. bbox: Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84. datetime_range: RFC 3339 time interval string. token: Optional Bearer token for authenticated requests.

Returns

dict A GeoJSON FeatureCollection. Each Feature has "assets" containing download links for GeoTIFFs, PNGs, and other raster products, with "href" and media-type annotations.

Examples

items = stac_get_items("l4a-combined-ch4-v3a", limit=5) for feat in items["features"]: ... print(feat["id"], feat.get("properties", {}).get("datetime"))

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_get_items(
    collection_id: str,
    *,
    limit: int = 10,
    bbox: tuple[float, float, float, float] | None = None,
    datetime_range: str | None = None,
    token: str | None = None,
) -> dict:
    """
    Get items from a STAC collection (OGC API Features compliant).

    Parameters
    ----------
    collection_id:
        Identifier of the STAC collection to query, e.g.
        ``"l4a-combined-ch4-v3a"`` or ``"l2b-rgb-v3a"``.
    limit:
        Maximum number of items to return.
    bbox:
        Bounding-box spatial filter as
        ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84.
    datetime_range:
        RFC 3339 time interval string.
    token:
        Optional Bearer token for authenticated requests.

    Returns
    -------
    dict
        A GeoJSON FeatureCollection.  Each Feature has ``"assets"``
        containing download links for GeoTIFFs, PNGs, and other raster
        products, with ``"href"`` and media-type annotations.

    Examples
    --------
    >>> items = stac_get_items("l4a-combined-ch4-v3a", limit=5)
    >>> for feat in items["features"]:
    ...     print(feat["id"], feat.get("properties", {}).get("datetime"))
    """
    params: dict[str, Any] = {"limit": limit}
    params.update(_stac_bbox_param(bbox))
    if datetime_range:
        params["datetime"] = datetime_range
    return cast(
        dict,
        _get(
            f"{STAC_URL}/collections/{collection_id}/items", params=params, token=token
        ),
    )

stac_list_collections()

List all STAC collections with their metadata.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_list_collections() -> list[dict]:
    """List all STAC collections with their metadata."""
    resp = _get(f"{STAC_URL}/collections")
    if isinstance(resp, dict):
        return cast("list[dict]", resp.get("collections", resp))
    return cast("list[dict]", resp)

Cross-collection STAC item search.

Searches across one or more STAC collections using spatial and temporal filters and returns matching items as a GeoJSON FeatureCollection.

Parameters

collections: List of STAC collection IDs to search. If None, all collections are searched. Example: ["l2b-ch4-mfa-v3", "l4a-combined-ch4-v3a"]. bbox: Bounding-box spatial filter as (west_lon, south_lat, east_lon, north_lat) in WGS 84. datetime_range: RFC 3339 time interval string, e.g. "2024-01-01T00:00:00Z/2024-06-01T00:00:00Z". limit: Maximum number of items to return. token: Optional Bearer token for authenticated requests.

Returns

dict A GeoJSON FeatureCollection mapping. Key fields:

- ``"type"``     — ``"FeatureCollection"``.
- ``"features"`` — list of STAC item GeoJSON Features.  Each
  Feature has:

  - ``"id"``         — item ID.
  - ``"geometry"``   — GeoJSON geometry of the scene footprint.
  - ``"properties"`` — item metadata (datetime, collection, etc.).
  - ``"assets"``     — dict of named assets, each with an
    ``"href"`` download URL and media type.

- ``"context"``  — pagination info (``matched``, ``returned``).
Examples

Search CH4 retrievals in the Permian Basin:

result = stac_search( ... collections=["l2b-ch4-mfa-v3"], ... bbox=(-104.5, 31.0, -101.5, 33.5), ... datetime_range="2024-01-01T00:00:00Z/2024-06-01T00:00:00Z", ... limit=5, ... ) for feat in result["features"]: ... print(feat["id"], list(feat["assets"].keys()))

Search across multiple collections simultaneously:

result = stac_search( ... collections=["l4a-combined-ch4-v3a", "l2b-rgb-v3a"], ... bbox=(-104.5, 31.0, -101.5, 33.5), ... limit=3, ... )

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/download.py
def stac_search(
    *,
    collections: list[str] | None = None,
    bbox: tuple[float, float, float, float] | None = None,
    datetime_range: str | None = None,
    ids: list[str] | None = None,
    limit: int = 10,
    token: str | None = None,
) -> dict:
    """
    Cross-collection STAC item search.

    Searches across one or more STAC collections using spatial and
    temporal filters and returns matching items as a GeoJSON
    FeatureCollection.

    Parameters
    ----------
    collections:
        List of STAC collection IDs to search.  If ``None``, all
        collections are searched.  Example:
        ``["l2b-ch4-mfa-v3", "l4a-combined-ch4-v3a"]``.
    bbox:
        Bounding-box spatial filter as
        ``(west_lon, south_lat, east_lon, north_lat)`` in WGS 84.
    datetime_range:
        RFC 3339 time interval string, e.g.
        ``"2024-01-01T00:00:00Z/2024-06-01T00:00:00Z"``.
    limit:
        Maximum number of items to return.
    token:
        Optional Bearer token for authenticated requests.

    Returns
    -------
    dict
        A GeoJSON FeatureCollection mapping.  Key fields:

        - ``"type"``     — ``"FeatureCollection"``.
        - ``"features"`` — list of STAC item GeoJSON Features.  Each
          Feature has:

          - ``"id"``         — item ID.
          - ``"geometry"``   — GeoJSON geometry of the scene footprint.
          - ``"properties"`` — item metadata (datetime, collection, etc.).
          - ``"assets"``     — dict of named assets, each with an
            ``"href"`` download URL and media type.

        - ``"context"``  — pagination info (``matched``, ``returned``).

    Examples
    --------
    Search CH4 retrievals in the Permian Basin:

    >>> result = stac_search(
    ...     collections=["l2b-ch4-mfa-v3"],
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     datetime_range="2024-01-01T00:00:00Z/2024-06-01T00:00:00Z",
    ...     limit=5,
    ... )
    >>> for feat in result["features"]:
    ...     print(feat["id"], list(feat["assets"].keys()))

    Search across multiple collections simultaneously:

    >>> result = stac_search(
    ...     collections=["l4a-combined-ch4-v3a", "l2b-rgb-v3a"],
    ...     bbox=(-104.5, 31.0, -101.5, 33.5),
    ...     limit=3,
    ... )
    """
    params: dict[str, Any] = {"limit": limit}
    if collections:
        params["collections"] = ",".join(collections)
    if ids:
        params["ids"] = ",".join(ids)
    params.update(_stac_bbox_param(bbox))
    if datetime_range:
        params["datetime"] = datetime_range
    return cast(dict, _get(f"{STAC_URL}/search", params=params, token=token))

geoproducts.carbonmapper.plume

plume.py

Unified Pydantic model for Carbon Mapper plume records.

Handles payloads from both Carbon Mapper API formats:

  • CSV bulk export (/api/v1/catalog/plume-csv) — provides plume_latitude, plume_longitude, datetime, plume_bounds.
  • Annotated plume JSON (/api/v1/catalog/plumes/annotated) — provides geometry_json, scene_timestamp, validated, has_phme.

All fields except plume_id are optional so that the model can be constructed from either format without validation errors.

CH4 and CO2. The model is gas-agnostic (CMRawPlume.gas returns whatever the API gave us) and the query helpers in :mod:api_queries accept either gas (or None for both). CO2 splits its cmf_type across collection families — see :class:~geoproducts.carbonmapper.products.CMCollectionSpec.

Version timeline. Carbon Mapper bumps emission_version per processing-software release. v3a was the first STAC-exposed version family; newer versions (v3c onwards) were reachable only via direct asset URLs from /catalog/plume/{id} until 2026, and STAC now registers every version through v3e. The :attr:CMRawPlume.version property exposes the version; :class:~geoproducts.carbonmapper.image.CMPlumeImage resolves the assets from the plume record for any version.

This module is the API-side typed view of a Carbon Mapper plume record; downstream consumers may persist it into their own tables.

CMRawPlume

Bases: BaseModel

Unified Carbon Mapper plume model.

Accepts payloads from both the CSV bulk-export endpoint and the annotated plume JSON endpoint. Only plume_id is required — all other fields default to None so either format can be parsed without errors.

Geometry is built automatically from whichever source is available:

  1. geometry_json (GeoJSON dict) — Point geometries are buffered by 0.001° to produce a small polygon.
  2. plume_bounds (bounding box) — converted to a shapely.box.

Note that geometry here is not the retrieved plume mask polygon — it's just the API's reported point/bounds. For the authoritative plume polygon, use :attr:~geoproducts.carbonmapper.image.CMPlumeImage.outline (or the band-4 alpha mask of the L3A plume_tif).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
class CMRawPlume(BaseModel):
    """Unified Carbon Mapper plume model.

    Accepts payloads from both the CSV bulk-export endpoint and the
    annotated plume JSON endpoint. Only ``plume_id`` is required — all
    other fields default to ``None`` so either format can be parsed
    without errors.

    Geometry is built automatically from whichever source is available:

    1. ``geometry_json`` (GeoJSON dict) — Point geometries are buffered
       by 0.001° to produce a small polygon.
    2. ``plume_bounds`` (bounding box) — converted to a ``shapely.box``.

    Note that ``geometry`` here is **not** the retrieved plume mask
    polygon — it's just the API's reported point/bounds. For the
    authoritative plume polygon, use
    :attr:`~geoproducts.carbonmapper.image.CMPlumeImage.outline`
    (or the band-4 alpha mask of the L3A ``plume_tif``).
    """

    model_config = ConfigDict(
        arbitrary_types_allowed=True,
        populate_by_name=True,
        str_strip_whitespace=True,
        validate_assignment=True,
    )

    # Field descriptions below follow the upstream Carbon Mapper API docs.

    # --- Core identifiers ---
    plume_id: str = Field(
        description=(
            "Unique plume identifier in the format "
            "``{platform}{YYYYMMDD}{HHMMSS}-{part}``. The first three "
            "characters represent the platform (e.g. ``gao`` for Global "
            "Airborne Observatory) followed by the acquisition date and "
            "time in ISO 8601 UTC format. The ``-{part}`` suffix (e.g. "
            "``-A``) retains key information from the original radiance "
            "filename and indicates the order of multiple plumes "
            "detected in the same image."
        ),
    )
    gas: str | None = Field(
        default="CH4",
        description="The gas molecule detected during imaging operations.",
    )

    # --- Coordinates (CSV: required; JSON: derived from geometry_json) ---
    plume_latitude: float | None = Field(
        default=None,
        alias="plume_latitude",
        description="Latitude estimate of plume origin (decimal degrees, EPSG:4326).",
    )
    plume_longitude: float | None = Field(
        default=None,
        alias="plume_longitude",
        description="Longitude estimate of plume origin (decimal degrees, EPSG:4326).",
    )

    # --- Timestamps ---
    # CSV format uses "datetime"; annotated format uses "scene_timestamp"
    datetime_str: str | None = Field(
        default=None,
        alias="datetime",
        description=(
            "Acquisition time (UTC ISO 8601). "
            "Set on CSV-format payloads; the "
            "annotated-JSON endpoint uses ``scene_timestamp`` instead."
        ),
    )
    scene_timestamp: str | None = Field(
        default=None,
        description=(
            "Acquisition time (UTC ISO 8601) — annotated-JSON variant of "
            "``datetime``. Either field may be populated, never both."
        ),
    )
    scene_uuid: str | None = Field(
        default=None,
        alias="scene_id",
        description=(
            "Internal Carbon Mapper scene UUID — what the API returns "
            "in the ``scene_id`` JSON field. **Not** the parseable scene "
            "name (e.g. ``tan20251212t185057c20s4001``); for that, use "
            "the :attr:`scene_id` property which derives from "
            "``plume_id.rsplit('-', 1)[0]`` and matches the STAC item id "
            "in the ``l2b-ch4-mfa-v3a`` collection."
        ),
    )
    published_at_str: str | None = Field(
        default=None,
        alias="published_at",
        description="Date and time the observation was published (UTC).",
    )
    modified_str: str | None = Field(
        default=None,
        alias="modified",
        description="Date and time the observation was last modified (UTC).",
    )

    # --- Emissions ---
    emission_auto: float | None = Field(
        default=None,
        description=(
            "Quantified emission rate of the plume [kg/hr], estimated "
            "using the Integrated Methane Enhancement (IME) method "
            "(Duren et al. 2019, *California's Methane Super-Emitters*, "
            "Nature)."
        ),
    )
    emission_uncertainty_auto: float | None = Field(
        default=None,
        description=(
            "Uncertainty in the emission rate [± kg/hr range], derived "
            "from uncertainty in IME and wind speed."
        ),
    )

    # --- Wind ---
    wind_speed_avg_auto: float | None = Field(
        default=None,
        description="Mean wind speed at the plume site [m/s].",
    )
    wind_speed_std_auto: float | None = Field(
        default=None,
        description="Standard deviation of wind speed [m/s].",
    )
    wind_direction_avg_auto: float | None = Field(
        default=None,
        description="Wind direction at the plume site [degrees].",
    )
    wind_direction_std_auto: float | None = Field(
        default=None,
        description="Standard deviation of wind direction [degrees].",
    )
    wind_source_auto: str | None = Field(
        default=None,
        description=(
            "Wind reanalysis source (e.g. ``HRRR``, ``ECMWF_IFS``, "
            "``ERA5``). Indicates which forecast/reanalysis product fed "
            "the IME quantification."
        ),
    )

    # --- Instrument / platform ---
    instrument: str | None = Field(
        default=None,
        description=(
            "Three-character sensor abbreviation: ``ang`` (AVIRIS-NG), "
            "``av3`` (AVIRIS-3), ``emi`` (EMIT), ``tan`` (Tanager-1), "
            "``gao`` (GAO)."
        ),
    )
    platform: str | None = Field(
        default=None,
        description="Unique name of the platform the instrument is attached to.",
    )
    provider: str | None = Field(
        default=None,
        description="Short description of the data provider's name.",
    )

    # --- Classification / metadata ---
    ipcc_sector: str | None = Field(
        default=None,
        alias="ipcc_sector",
        description=(
            "IPCC emissions sector (e.g. ``1B2`` for Oil & Gas) when "
            "Carbon Mapper attributes one. Reference: "
            "https://www.ipcc-nggip.iges.or.jp/public/gl/guidelin/ch1ri.pdf"
        ),
    )
    sector: str | None = Field(
        default=None,
        description=(
            "Carbon Mapper free-text sector category. Often a "
            "human-readable wrapper around ``ipcc_sector`` (e.g. "
            '``"Oil & Gas (1B2)"``).'
        ),
    )
    emission_cmf_type: str | None = Field(
        default=None,
        alias="emission_cmf_type",
        description=(
            "Statistical column-wise atmospheric retrieval algorithm "
            "used to threshold methane / carbon dioxide plumes from "
            "background concentrations (e.g. ``mfa``)."
        ),
    )
    mission_phase: str | None = Field(
        default=None,
        description=(
            "Operational mission phase, such as ``first_light`` or ``production``."
        ),
    )
    emission_version: str | None = Field(
        default=None,
        description=(
            "Version label for the algorithm + calibration applied to "
            "produce this emission record. Pairs with reprocessing "
            "campaigns."
        ),
    )
    processing_software: str | None = Field(
        default=None,
        description=(
            "Software version used by the provider to process the raw "
            "satellite data (e.g. ``cmpro: 3.41.4``)."
        ),
    )
    gsd: float | None = Field(
        default=None,
        description=(
            "Native ground sample distance — the distance on the ground "
            "represented by the center-to-center spacing of pixels in "
            "the sensor's raw radiance data [meters]."
        ),
    )
    sensitivity_mode: str | None = Field(
        default=None,
        description=(
            "The sensor's configured detection threshold and "
            "radiometric settings, which affect signal-to-noise ratio "
            "(SNR), exposure time, and spectral fidelity."
        ),
    )
    off_nadir: float | None = Field(
        default=None,
        description=(
            "Angle between the satellite's sensor line of sight and the "
            "point directly below the satellite (nadir) [degrees]. "
            "Carbon Mapper publishes this on the plume; the equivalent "
            "STAC property at the L2B scene level is ``view:off_nadir``."
        ),
    )

    # --- Quality & validation (annotated JSON) ---
    plume_quality: str | None = Field(
        default=None,
        description=(
            "CM-side quality flag for the plume retrieval. Presence "
            "implies the record was reviewed by Carbon Mapper's "
            "pipeline."
        ),
    )
    validated: bool | None = Field(
        default=None,
        description="CM-side validation flag (annotated JSON only).",
    )
    validator_user: str | None = Field(
        default=None,
        description="Validator user id from the CM annotated payload.",
    )
    has_phme: bool | None = Field(
        default=None,
        description=(
            "Whether the plume is flagged as a Potentially Harmful Methane "
            "Event (PHME). Annotated JSON only."
        ),
    )
    detection_institution: str | None = Field(
        default=None,
        description="Detection institution string from the CM annotated payload.",
    )

    # --- Source linkage (annotated JSON) ---
    source_id: str | None = Field(
        default=None,
        description=(
            "Carbon Mapper-assigned emission-source id. Joins to the CM "
            "API's source endpoint."
        ),
    )
    source_name: str | None = Field(
        default=None,
        description=(
            "Carbon Mapper source-name string (e.g. "
            "``CH4_1B2_100m_-104.17525_32.49125``)."
        ),
    )

    # --- Assets ---
    plume_tif: str | None = Field(
        default=None,
        description=(
            "HTTPS link to a GeoTIFF of the delineated plume (L3A "
            "alpha-banded mask). "
            "Band 4 of this file is the plume mask — the authoritative "
            "source for the retrieved plume shape (see "
            ":attr:`~geoproducts.carbonmapper.image.CMPlumeImage.outline`)."
        ),
    )
    plume_png: str | None = Field(
        default=None,
        description="HTTPS link to a PNG visualisation of the delineated plume.",
    )
    con_tif: str | None = Field(
        default=None,
        description=(
            "HTTPS link to a GeoTIFF pixel map of unsmoothed "
            "concentration values [ppm·m]. The L2B-tile-level "
            "equivalent is the ``cmf`` asset on the parent STAC item."
        ),
    )
    rgb_tif: str | None = Field(
        default=None,
        description=(
            "HTTPS link to a 3-band, natural-colour, full-strip "
            "surface-reflectance GeoTIFF. The L2B-tile-level sibling "
            "lives in the ``l2b-rgb-v3a`` STAC collection."
        ),
    )
    rgb_png: str | None = Field(
        default=None,
        description=(
            "HTTPS link to a natural-colour, full-strip surface-reflectance PNG."
        ),
    )
    plume_rgb_png: str | None = Field(
        default=None,
        description="HTTPS link to a PNG of the plume overlaid on RGB.",
    )

    # --- Geometry sources ---
    geometry_json: dict | None = Field(
        default=None,
        description=(
            "Raw GeoJSON geometry dict from the CM payload — typically "
            "a Point or coarse Polygon. **Not** the retrieved plume "
            "polygon; for that, use ``CMPlumeImage.outline`` or the "
            "``plume_tif`` mask."
        ),
    )
    plume_bounds_raw: str | list[float] | tuple[float, float, float, float] | None = (
        Field(
            default=None,
            alias="plume_bounds",
            description="Geographic bounds encompassing the plume image (W, S, E, N).",
        )
    )

    # --- Derived ---
    geometry: BaseGeometry | None = Field(
        default=None,
        description=(
            "Shapely geometry built from ``geometry_json`` (preferred) "
            "or ``plume_bounds`` at validation time. **Not** the "
            "retrieved plume mask — same caveat as ``geometry_json``."
        ),
    )

    # ------------------------------------------------------------------ #
    # Field validators                                                     #
    # ------------------------------------------------------------------ #

    @model_validator(mode="before")
    @classmethod
    def _nan_cells_to_none(cls, data: Any) -> Any:
        """Map float ``NaN`` (an empty pandas CSV cell) to ``None``.

        Runs before field validation, so every optional field — strings
        and URLs included, not just the numeric ones — treats an empty
        bulk-export cell as missing instead of rejecting the row.
        """
        if isinstance(data, Mapping):
            return {
                k: None if isinstance(v, float) and math.isnan(v) else v
                for k, v in data.items()
            }
        return data

    @field_validator(
        "plume_latitude",
        "plume_longitude",
        "gsd",
        "off_nadir",
        "emission_auto",
        "emission_uncertainty_auto",
        "wind_speed_avg_auto",
        "wind_speed_std_auto",
        "wind_direction_avg_auto",
        "wind_direction_std_auto",
        mode="before",
    )
    @classmethod
    def _coerce_float(cls, v: Any) -> float | None:
        return _to_float(v)

    @field_validator("validated", "has_phme", mode="before")
    @classmethod
    def _coerce_bool(cls, v: Any) -> bool | None:
        if v is None:
            return None
        if isinstance(v, bool):
            return v
        if isinstance(v, str):
            return v.lower() in ("true", "1", "yes")
        # An empty CSV cell arrives from pandas as NaN, which is truthy.
        if isinstance(v, float) and math.isnan(v):
            return None
        return bool(v)

    # ------------------------------------------------------------------ #
    # Model validator                                                      #
    # ------------------------------------------------------------------ #

    @model_validator(mode="after")
    def _build_geometry(self) -> CMRawPlume:
        """Build shapely geometry from ``geometry_json`` or ``plume_bounds``."""
        geom: BaseGeometry | None = None

        # Priority 1: GeoJSON
        if self.geometry_json:
            try:
                geom = shape(self.geometry_json)
            except Exception:
                geom = None
            geom_type = self.geometry_json.get("type", "")
            if geom_type == "Point" and geom is not None:
                # Buffer by ~111 m to get a small polygon
                geom = geom.buffer(0.001)
            # Fill lat/lon from Point coordinates if not set
            if (
                self.plume_latitude is None or self.plume_longitude is None
            ) and geom_type == "Point":
                coords = self.geometry_json.get("coordinates")
                if coords and len(coords) >= 2:
                    object.__setattr__(self, "plume_longitude", float(coords[0]))
                    object.__setattr__(self, "plume_latitude", float(coords[1]))

        # Priority 2: Bounding box
        if geom is None:
            b = _parse_bounds(self.plume_bounds_raw)
            if b is not None:
                try:
                    geom = box(*b)
                except Exception:
                    geom = None

        object.__setattr__(self, "geometry", geom)
        return self

    # ------------------------------------------------------------------ #
    # Properties                                                           #
    # ------------------------------------------------------------------ #

    @property
    def observation_datetime(self) -> datetime | None:
        """Parse observation time from ``datetime_str`` or ``scene_timestamp``."""
        return _parse_iso_datetime(self.datetime_str) or _parse_iso_datetime(
            self.scene_timestamp
        )

    @property
    def published_at(self) -> datetime | None:
        return _parse_iso_datetime(self.published_at_str)

    @property
    def modified_at(self) -> datetime | None:
        return _parse_iso_datetime(self.modified_str)

    @property
    def lat(self) -> float | None:
        return self.plume_latitude

    @property
    def lon(self) -> float | None:
        return self.plume_longitude

    @property
    def geometry_wkt(self) -> str | None:
        return self.geometry.wkt if self.geometry is not None else None

    @property
    def wind_u(self) -> float | None:
        """Eastward wind component (m/s), meteorological convention."""
        u, _ = decompose_wind(self.wind_speed_avg_auto, self.wind_direction_avg_auto)
        return u

    @property
    def wind_v(self) -> float | None:
        """Northward wind component (m/s), meteorological convention."""
        _, v = decompose_wind(self.wind_speed_avg_auto, self.wind_direction_avg_auto)
        return v

    @property
    def instrument_name(self) -> str | None:
        """Human-readable instrument name from :data:`CARBONMAPPER_INSTRUMENTS`.

        The lookup is case-insensitive — upstream payloads occasionally
        report ``"GAO"`` while ``plume_id`` prefixes are lowercase, so
        the table key is normalised at lookup time rather than relying
        on every caller to lowercase first.
        """
        if self.instrument is None:
            return None
        return CARBONMAPPER_INSTRUMENTS.get(
            self.instrument.lower(),
            self.instrument,
        )

    @property
    def scene_id(self) -> str:
        """Parent L2B scene id, derived from ``plume_id``.

        Equivalent to ``plume_id.rsplit('-', 1)[0]`` — same string used
        as the STAC item id in the ``l2b-ch4-mfa-v3a`` collection. Use
        this to bridge from a plume to its parent scene without an HTTP
        round-trip:

        >>> raw.scene_id                       # doctest: +SKIP
        'tan20251212t185057c20s4001'
        >>> tile = api_queries.get_tile(token, raw.scene_id)  # doctest: +SKIP

        Distinct from :attr:`scene_uuid`, which is the API's internal
        UUID for the scene.
        """
        return self.plume_id.rsplit("-", 1)[0]

    @property
    def version(self) -> str | None:
        """Processing version (``"v3a"`` / ``"v3b"`` / ``"v3c"`` / ...).

        Re-exposes :attr:`emission_version` under a shorter name.
        Returns ``None`` if the upstream payload didn't include
        ``emission_version`` (older CSV exports).
        """
        return self.emission_version

    @property
    def collection_spec(self) -> CMCollectionSpec | None:
        """This plume's resolved collection spec, or ``None``.

        Resolves the ``(gas, cmf_type, version)`` triple naming the
        collections this plume's assets live in — from the
        :attr:`plume_tif` URL when present, else from the
        ``gas`` / ``emission_cmf_type`` / ``emission_version`` fields.
        Composes every product-family collection id without version
        guessing (see
        :class:`~geoproducts.carbonmapper.products.CMCollectionSpec`).

        Returns ``None`` when neither source is available (e.g. sparse
        CSV exports without asset URLs).
        """
        from geoproducts.carbonmapper.products import CMCollectionSpec

        record = {
            "plume_id": self.plume_id,
            "plume_tif": self.plume_tif,
            "con_tif": self.con_tif,
            "gas": self.gas,
            "cmf_type": self.emission_cmf_type,
            "emission_version": self.emission_version,
        }
        try:
            return CMCollectionSpec.from_plume_record(record)
        except ValueError:
            return None

    # ------------------------------------------------------------------ #
    # Serialisation                                                        #
    # ------------------------------------------------------------------ #

    def to_source_dict(self) -> dict[str, Any]:
        """Serialise to a dict suitable for round-tripping through :meth:`from_raw`."""
        d: dict[str, Any] = {"plume_id": self.plume_id, "gas": self.gas}

        # Coordinates
        if self.plume_latitude is not None:
            d["plume_latitude"] = self.plume_latitude
        if self.plume_longitude is not None:
            d["plume_longitude"] = self.plume_longitude

        # Timestamps
        if self.datetime_str is not None:
            d["datetime"] = self.datetime_str
        if self.scene_timestamp is not None:
            d["scene_timestamp"] = self.scene_timestamp
        # Round-trip the API's `scene_id` (UUID) under its on-the-wire
        # name; the parseable form is derived via the property.
        if self.scene_uuid is not None:
            d["scene_id"] = self.scene_uuid
        if self.published_at_str is not None:
            d["published_at"] = self.published_at_str
        if self.modified_str is not None:
            d["modified"] = self.modified_str

        # Emissions
        d["emission_auto"] = self.emission_auto
        d["emission_uncertainty_auto"] = self.emission_uncertainty_auto

        # Wind
        d["wind_speed_avg_auto"] = self.wind_speed_avg_auto
        d["wind_speed_std_auto"] = self.wind_speed_std_auto
        d["wind_direction_avg_auto"] = self.wind_direction_avg_auto
        d["wind_direction_std_auto"] = self.wind_direction_std_auto
        d["wind_source_auto"] = self.wind_source_auto

        # Instrument / platform
        d["instrument"] = self.instrument
        d["platform"] = self.platform
        d["provider"] = self.provider

        # Classification
        if self.ipcc_sector is not None:
            d["ipcc_sector"] = self.ipcc_sector
        if self.sector is not None:
            d["sector"] = self.sector
        d["emission_cmf_type"] = self.emission_cmf_type
        d["mission_phase"] = self.mission_phase
        d["emission_version"] = self.emission_version
        d["processing_software"] = self.processing_software
        d["gsd"] = self.gsd
        d["sensitivity_mode"] = self.sensitivity_mode
        d["off_nadir"] = self.off_nadir

        # Quality / validation
        if self.plume_quality is not None:
            d["plume_quality"] = self.plume_quality
        if self.validated is not None:
            d["validated"] = self.validated
        if self.validator_user is not None:
            d["validator_user"] = self.validator_user
        if self.has_phme is not None:
            d["has_phme"] = self.has_phme
        if self.detection_institution is not None:
            d["detection_institution"] = self.detection_institution

        # Source linkage
        if self.source_id is not None:
            d["source_id"] = self.source_id
        if self.source_name is not None:
            d["source_name"] = self.source_name

        # Assets
        d["plume_tif"] = self.plume_tif
        d["plume_png"] = self.plume_png
        d["con_tif"] = self.con_tif
        d["rgb_tif"] = self.rgb_tif
        d["rgb_png"] = self.rgb_png
        if self.plume_rgb_png is not None:
            d["plume_rgb_png"] = self.plume_rgb_png

        # Geometry sources
        if self.geometry_json is not None:
            d["geometry_json"] = self.geometry_json
        if self.plume_bounds_raw is not None:
            d["plume_bounds"] = self.plume_bounds_raw

        return d

    # ------------------------------------------------------------------ #
    # Factory classmethods                                                 #
    # ------------------------------------------------------------------ #

    @classmethod
    def from_raw(cls, raw: str | dict[str, Any]) -> CMRawPlume:
        """Create from a JSON string or dict (CSV row or annotated-plume payload)."""
        if isinstance(raw, str):
            raw = json.loads(raw)
        return cls(**raw)

    # ------------------------------------------------------------------ #
    # Representation                                                       #
    # ------------------------------------------------------------------ #

    def _short_wkt_preview(self, max_len: int = 160) -> str | None:
        if not self.geometry:
            return None
        txt = self.geometry.wkt.replace("\n", " ").strip()
        return txt if len(txt) <= max_len else txt[: max_len - 3] + "..."

    def __str__(self) -> str:
        geom = self.geometry
        geom_type = getattr(geom, "geom_type", None)
        area = round(geom.area, 6) if geom is not None else None
        dt = (
            self.observation_datetime.isoformat() if self.observation_datetime else None
        )
        return (
            f"{self.__class__.__name__}\n"
            f"  plume_id: {self.plume_id}\n"
            f"  observation_datetime (UTC): {dt}\n"
            f"  lat: {self.lat}\n"
            f"  lon: {self.lon}\n"
            f"  instrument: {self.instrument}\n"
            f"  platform: {self.platform}\n"
            f"  geometry_type: {geom_type}\n"
            f"  geometry_area_deg2: {area}\n"
            f"  emission_auto: {self.emission_auto}\n"
            f"  emission_uncertainty_auto: {self.emission_uncertainty_auto}\n"
            f"  wind_speed_avg_auto: {self.wind_speed_avg_auto}\n"
            f"  wind_direction_avg_auto: {self.wind_direction_avg_auto}\n"
            f"  gas: {self.gas}\n"
            f"  validated: {self.validated}\n"
        )

    def __repr__(self) -> str:
        geom = self.geometry
        geom_type = getattr(geom, "geom_type", None)
        area = geom.area if geom is not None else None
        return (
            f"{self.__class__.__name__}(\n"
            f"  plume_id={self.plume_id!r},\n"
            f"  lat={self.lat},\n"
            f"  lon={self.lon},\n"
            f"  gas={self.gas!r},\n"
            f"  instrument={self.instrument!r},\n"
            f"  platform={self.platform!r},\n"
            f"  emission_auto={self.emission_auto},\n"
            f"  emission_uncertainty_auto={self.emission_uncertainty_auto},\n"
            f"  wind_speed_avg_auto={self.wind_speed_avg_auto},\n"
            f"  wind_direction_avg_auto={self.wind_direction_avg_auto},\n"
            f"  validated={self.validated},\n"
            f"  geometry_type={geom_type},\n"
            f"  geometry_area_deg2={area},\n"
            f"  geometry_wkt_preview={self._short_wkt_preview()!r}\n"
            f")"
        )

collection_spec property

This plume's resolved collection spec, or None.

Resolves the (gas, cmf_type, version) triple naming the collections this plume's assets live in — from the :attr:plume_tif URL when present, else from the gas / emission_cmf_type / emission_version fields. Composes every product-family collection id without version guessing (see :class:~geoproducts.carbonmapper.products.CMCollectionSpec).

Returns None when neither source is available (e.g. sparse CSV exports without asset URLs).

instrument_name property

Human-readable instrument name from :data:CARBONMAPPER_INSTRUMENTS.

The lookup is case-insensitive — upstream payloads occasionally report "GAO" while plume_id prefixes are lowercase, so the table key is normalised at lookup time rather than relying on every caller to lowercase first.

observation_datetime property

Parse observation time from datetime_str or scene_timestamp.

scene_id property

Parent L2B scene id, derived from plume_id.

Equivalent to plume_id.rsplit('-', 1)[0] — same string used as the STAC item id in the l2b-ch4-mfa-v3a collection. Use this to bridge from a plume to its parent scene without an HTTP round-trip:

raw.scene_id # doctest: +SKIP 'tan20251212t185057c20s4001' tile = api_queries.get_tile(token, raw.scene_id) # doctest: +SKIP

Distinct from :attr:scene_uuid, which is the API's internal UUID for the scene.

version property

Processing version ("v3a" / "v3b" / "v3c" / ...).

Re-exposes :attr:emission_version under a shorter name. Returns None if the upstream payload didn't include emission_version (older CSV exports).

wind_u property

Eastward wind component (m/s), meteorological convention.

wind_v property

Northward wind component (m/s), meteorological convention.

from_raw(raw) classmethod

Create from a JSON string or dict (CSV row or annotated-plume payload).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
@classmethod
def from_raw(cls, raw: str | dict[str, Any]) -> CMRawPlume:
    """Create from a JSON string or dict (CSV row or annotated-plume payload)."""
    if isinstance(raw, str):
        raw = json.loads(raw)
    return cls(**raw)

to_source_dict()

Serialise to a dict suitable for round-tripping through :meth:from_raw.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
def to_source_dict(self) -> dict[str, Any]:
    """Serialise to a dict suitable for round-tripping through :meth:`from_raw`."""
    d: dict[str, Any] = {"plume_id": self.plume_id, "gas": self.gas}

    # Coordinates
    if self.plume_latitude is not None:
        d["plume_latitude"] = self.plume_latitude
    if self.plume_longitude is not None:
        d["plume_longitude"] = self.plume_longitude

    # Timestamps
    if self.datetime_str is not None:
        d["datetime"] = self.datetime_str
    if self.scene_timestamp is not None:
        d["scene_timestamp"] = self.scene_timestamp
    # Round-trip the API's `scene_id` (UUID) under its on-the-wire
    # name; the parseable form is derived via the property.
    if self.scene_uuid is not None:
        d["scene_id"] = self.scene_uuid
    if self.published_at_str is not None:
        d["published_at"] = self.published_at_str
    if self.modified_str is not None:
        d["modified"] = self.modified_str

    # Emissions
    d["emission_auto"] = self.emission_auto
    d["emission_uncertainty_auto"] = self.emission_uncertainty_auto

    # Wind
    d["wind_speed_avg_auto"] = self.wind_speed_avg_auto
    d["wind_speed_std_auto"] = self.wind_speed_std_auto
    d["wind_direction_avg_auto"] = self.wind_direction_avg_auto
    d["wind_direction_std_auto"] = self.wind_direction_std_auto
    d["wind_source_auto"] = self.wind_source_auto

    # Instrument / platform
    d["instrument"] = self.instrument
    d["platform"] = self.platform
    d["provider"] = self.provider

    # Classification
    if self.ipcc_sector is not None:
        d["ipcc_sector"] = self.ipcc_sector
    if self.sector is not None:
        d["sector"] = self.sector
    d["emission_cmf_type"] = self.emission_cmf_type
    d["mission_phase"] = self.mission_phase
    d["emission_version"] = self.emission_version
    d["processing_software"] = self.processing_software
    d["gsd"] = self.gsd
    d["sensitivity_mode"] = self.sensitivity_mode
    d["off_nadir"] = self.off_nadir

    # Quality / validation
    if self.plume_quality is not None:
        d["plume_quality"] = self.plume_quality
    if self.validated is not None:
        d["validated"] = self.validated
    if self.validator_user is not None:
        d["validator_user"] = self.validator_user
    if self.has_phme is not None:
        d["has_phme"] = self.has_phme
    if self.detection_institution is not None:
        d["detection_institution"] = self.detection_institution

    # Source linkage
    if self.source_id is not None:
        d["source_id"] = self.source_id
    if self.source_name is not None:
        d["source_name"] = self.source_name

    # Assets
    d["plume_tif"] = self.plume_tif
    d["plume_png"] = self.plume_png
    d["con_tif"] = self.con_tif
    d["rgb_tif"] = self.rgb_tif
    d["rgb_png"] = self.rgb_png
    if self.plume_rgb_png is not None:
        d["plume_rgb_png"] = self.plume_rgb_png

    # Geometry sources
    if self.geometry_json is not None:
        d["geometry_json"] = self.geometry_json
    if self.plume_bounds_raw is not None:
        d["plume_bounds"] = self.plume_bounds_raw

    return d

Collection

Bases: StrEnum

Active CH4 Carbon Mapper collection identifiers.

Values are the canonical collection IDs used in /stac/collections/<id> paths and embedded in the asset URLs returned by /catalog/plume/{id}.

Two version families named here:

  • *_V3A — plumes from 2023-10 to 2025-12.
  • *_V3C — newer data (post 2026-01); REST-only until 2026, and registered in /stac/collections since.

Collection.L3A_VIS_V3A.value 'l3a-vis-ch4-mfa-v3a' Collection.L3A_VIS_V3A.version 'v3a'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
class Collection(StrEnum):
    """Active CH4 Carbon Mapper collection identifiers.

    Values are the canonical collection IDs used in
    ``/stac/collections/<id>`` paths and embedded in the asset URLs
    returned by ``/catalog/plume/{id}``.

    Two version families named here:

    - ``*_V3A`` — plumes from 2023-10 to 2025-12.
    - ``*_V3C`` — newer data (post 2026-01); REST-only until 2026, and
      registered in ``/stac/collections`` since.

    >>> Collection.L3A_VIS_V3A.value
    'l3a-vis-ch4-mfa-v3a'
    >>> Collection.L3A_VIS_V3A.version
    'v3a'
    """

    #: L3A vis — per-plume mask + concentrations + outline + RGB
    L3A_VIS_V3A = "l3a-vis-ch4-mfa-v3a"
    #: L3A IME — IME-clipped concentration + mask + outline
    L3A_IME_V3A = "l3a-ime-ch4-mfa-v3a"
    #: L2B scene — cmf / uncertainty / artifact-mask / unortho variants
    L2B_V3A = "l2b-ch4-mfa-v3a"
    #: L2B RGB sibling — true-colour rasters aligned to L2B_V3A scenes
    L2B_RGB_V3A = "l2b-rgb-v3a"
    #: L3A vis v3c — REST-only until 2026; STAC registers it since
    L3A_VIS_V3C = "l3a-vis-ch4-mfa-v3c"
    #: L3A IME v3c — REST-only until 2026; STAC registers it since
    L3A_IME_V3C = "l3a-ime-ch4-mfa-v3c"

    @property
    def version(self) -> str:
        """Processing version segment (``"v3a"`` / ``"v3c"``)."""
        return self.value.rsplit("-", 1)[1]

version property

Processing version segment ("v3a" / "v3c").

Gas

Bases: StrEnum

Gas species in the Carbon Mapper catalog.

Used as the closed-set type for gas parameters on the typed query helpers in :mod:api_queries. CMRawPlume.gas stays a plain str so the model is forgiving of unexpected upstream values.

Gas.CH4 str(Gas.CH4) 'CH4' Gas("CH4") is Gas.CH4 True

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
class Gas(StrEnum):
    """Gas species in the Carbon Mapper catalog.

    Used as the closed-set type for ``gas`` parameters on the typed
    query helpers in :mod:`api_queries`. ``CMRawPlume.gas`` stays a
    plain ``str`` so the model is forgiving of unexpected upstream
    values.

    >>> Gas.CH4
    <Gas.CH4: 'CH4'>
    >>> str(Gas.CH4)
    'CH4'
    >>> Gas("CH4") is Gas.CH4
    True
    """

    CH4 = "CH4"
    CO2 = "CO2"

Instrument

Bases: StrEnum

Carbon Mapper instrument short codes.

Carbon Mapper is case-sensitive on these codes upstream: tan / emi / ang / av3 are lowercase; GAO is uppercase. Filter values must match (e.g. instrument=gao silently returns no results — use GAO). The :meth:_missing_ hook normalises any case to the canonical upstream form when constructing the enum from a free-form string:

Instrument("tan") is Instrument.TANAGER True Instrument("TAN") is Instrument.TANAGER # case-insensitive lookup True Instrument("gao") is Instrument.GAO # also normalises GAO True str(Instrument.GAO) # serialises to upstream form 'GAO'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
class Instrument(StrEnum):
    """Carbon Mapper instrument short codes.

    Carbon Mapper is **case-sensitive** on these codes upstream:
    ``tan`` / ``emi`` / ``ang`` / ``av3`` are lowercase; ``GAO`` is
    uppercase. Filter values must match (e.g. ``instrument=gao``
    silently returns no results — use ``GAO``). The :meth:`_missing_`
    hook normalises any case to the canonical upstream form when
    constructing the enum from a free-form string:

    >>> Instrument("tan") is Instrument.TANAGER
    True
    >>> Instrument("TAN") is Instrument.TANAGER  # case-insensitive lookup
    True
    >>> Instrument("gao") is Instrument.GAO       # also normalises GAO
    True
    >>> str(Instrument.GAO)                       # serialises to upstream form
    'GAO'
    """

    TANAGER = "tan"
    EMIT = "emi"
    AVIRIS_NG = "ang"
    AVIRIS_3 = "av3"
    GAO = "GAO"  # upstream uses uppercase for this one

    @classmethod
    def _missing_(cls, value: object) -> Instrument | None:
        """Case-insensitive fallback so upstream variants (``"GAO"`` vs
        ``"gao"``) all resolve to the canonical member."""
        if isinstance(value, str):
            lowered = value.lower()
            for member in cls:
                if member.value.lower() == lowered:
                    return member
        return None

decompose_wind(speed, direction_deg)

Convert wind speed + meteorological direction to (u, v) components.

Meteorological convention: 0° = wind from North, 90° = wind from East. Returns the eastward (u) and northward (v) wind vector components.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/plume.py
def decompose_wind(
    speed: float | None,
    direction_deg: float | None,
) -> tuple[float | None, float | None]:
    """Convert wind speed + meteorological direction to (u, v) components.

    Meteorological convention: 0° = wind *from* North, 90° = wind *from* East.
    Returns the eastward (u) and northward (v) wind vector components.
    """
    if speed is None or direction_deg is None:
        return None, None
    direction_rad = math.radians(direction_deg)
    wind_u = -speed * math.sin(direction_rad)
    wind_v = -speed * math.cos(direction_rad)
    return wind_u, wind_v

geoproducts.carbonmapper.source

Typed model for a Carbon Mapper source (DBSCAN cluster of plumes).

A Carbon Mapper source groups all plumes detected at the same geographic location into a persistent point-source record. Sources are addressed by a deterministic name of the form {gas}_{sector}_{footprint_m}m_{lon}_{lat} — e.g. "CH4_1B2_100m_-104.17525_32.49125".

This module is the API-side typed view of a Carbon Mapper source. Downstream consumers may persist it into their own tables, but this package deliberately does not assume any particular DB schema.

Notable quirks handled here

  • /catalog/sources.geojson features sometimes return source_name with a stray query-string fragment appended ("...?plume_gas=CH4&bbox=..."). :func:_strip_query_suffix removes it; :meth:CMSource.from_geojson_feature calls it always so callers never see the dirty form.
  • The endpoints return either a GeoJSON Feature (with properties / geometry) or a flat dict; the higher-level :mod:geoproducts.carbonmapper.api_queries normalises these before invoking :meth:from_geojson_feature.

CMSource dataclass

Typed view of a Carbon Mapper source (cluster of plumes).

Frozen — instances are immutable and hashable. The raw dict captures the full upstream properties payload so consumers can reach for fields not yet exposed on the dataclass without round- tripping through the API.

Attributes

source_name: Canonical name (no ?... suffix). Stable across CM API revisions for the same physical site. gas: Gas species — typically "CH4" or "CO2". sector: IPCC sector code, e.g. "1B2" (Oil & Gas), "6A" (Solid Waste), "1B1a" (Coal Mining). point: Centroid as a Shapely :class:shapely.geometry.Point in WGS-84. plume_count: Number of plumes Carbon Mapper has attributed to this source. persistence: Carbon Mapper's persistence metric (overpasses-with-detection / total-overpasses), in [0, 1]. emission_auto: Persistence-weighted average emission rate in kg/h. None when CM has not produced an aggregate estimate. emission_uncertainty_auto: Companion uncertainty for emission_auto, in kg/h. first_observation, last_observation: Earliest and latest detection datetimes (UTC-aware). raw: Original properties mapping from the API response.

Examples

Parse from a /catalog/sources.geojson feature:

feature = { ... "properties": { ... "source_name": "CH4_1B2_100m_-104.17525_32.49125?plume_gas=CH4", ... "sector": "1B2", "gas": "CH4", ... "plume_count": 12, "persistence": 0.42, ... "emission_auto": 250.0, ... }, ... "geometry": {"type": "Point", ... "coordinates": [-104.17525, 32.49125]}, ... } src = CMSource.from_geojson_feature(feature) src.source_name # query suffix stripped 'CH4_1B2_100m_-104.17525_32.49125' src.point.x, src.point.y (-104.17525, 32.49125) src.plume_count, src.sector (12, '1B2')

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/source.py
@dataclass(frozen=True)
class CMSource:
    """Typed view of a Carbon Mapper source (cluster of plumes).

    Frozen — instances are immutable and hashable. The ``raw`` dict
    captures the full upstream properties payload so consumers can
    reach for fields not yet exposed on the dataclass without round-
    tripping through the API.

    Attributes
    ----------
    source_name:
        Canonical name (no ``?...`` suffix). Stable across CM API
        revisions for the same physical site.
    gas:
        Gas species — typically ``"CH4"`` or ``"CO2"``.
    sector:
        IPCC sector code, e.g. ``"1B2"`` (Oil & Gas), ``"6A"`` (Solid
        Waste), ``"1B1a"`` (Coal Mining).
    point:
        Centroid as a Shapely :class:`shapely.geometry.Point` in WGS-84.
    plume_count:
        Number of plumes Carbon Mapper has attributed to this source.
    persistence:
        Carbon Mapper's persistence metric (overpasses-with-detection /
        total-overpasses), in ``[0, 1]``.
    emission_auto:
        Persistence-weighted average emission rate in ``kg/h``. ``None``
        when CM has not produced an aggregate estimate.
    emission_uncertainty_auto:
        Companion uncertainty for ``emission_auto``, in ``kg/h``.
    first_observation, last_observation:
        Earliest and latest detection datetimes (UTC-aware).
    raw:
        Original ``properties`` mapping from the API response.

    Examples
    --------
    Parse from a ``/catalog/sources.geojson`` feature:

    >>> feature = {
    ...     "properties": {
    ...         "source_name": "CH4_1B2_100m_-104.17525_32.49125?plume_gas=CH4",
    ...         "sector": "1B2", "gas": "CH4",
    ...         "plume_count": 12, "persistence": 0.42,
    ...         "emission_auto": 250.0,
    ...     },
    ...     "geometry": {"type": "Point",
    ...                  "coordinates": [-104.17525, 32.49125]},
    ... }
    >>> src = CMSource.from_geojson_feature(feature)
    >>> src.source_name              # query suffix stripped
    'CH4_1B2_100m_-104.17525_32.49125'
    >>> src.point.x, src.point.y
    (-104.17525, 32.49125)
    >>> src.plume_count, src.sector
    (12, '1B2')
    """

    source_name: str
    gas: str
    sector: str
    point: Point
    plume_count: int
    persistence: float
    emission_auto: float | None = None
    emission_uncertainty_auto: float | None = None
    first_observation: datetime | None = None
    last_observation: datetime | None = None
    # Excluded from the hash (a dict isn't hashable); still compared.
    raw: dict = field(default_factory=dict, hash=False)

    @classmethod
    def from_geojson_feature(cls, feature: dict) -> CMSource:
        """Parse a ``/catalog/sources.geojson`` feature into a CMSource.

        Always strips the ``source_name`` query-string suffix
        (``?plume_gas=...``) — this is the canonical strip site, so
        downstream code can treat ``CMSource.source_name`` as clean.

        Parameters
        ----------
        feature:
            GeoJSON Feature dict with at least ``"geometry"`` (Point)
            and ``"properties"`` (with ``source_name`` and friends).

        Returns
        -------
        CMSource
            Typed source record with the suffix stripped.

        Raises
        ------
        ValueError
            If ``feature["geometry"]`` does not carry a Point coordinate
            pair.

        Examples
        --------
        >>> feature = {
        ...     "properties": {"source_name": "x?bbox=1", "sector": "1B2",
        ...                    "gas": "CH4", "plume_count": 1,
        ...                    "persistence": 0.5},
        ...     "geometry": {"type": "Point", "coordinates": [-100.0, 30.0]},
        ... }
        >>> CMSource.from_geojson_feature(feature).source_name
        'x'
        """
        props = dict(feature.get("properties") or {})
        geom = feature.get("geometry") or {}
        coords = geom.get("coordinates") or (None, None)
        lon, lat = (
            [*coords, None, None][:2] if isinstance(coords, list) else (None, None)
        )

        if lon is None or lat is None:
            raise ValueError(f"feature is missing Point coordinates: {feature!r}")

        return cls(
            source_name=_strip_query_suffix(str(props.get("source_name", ""))),
            gas=str(props.get("gas", "") or ""),
            sector=str(props.get("sector", "") or ""),
            point=Point(float(lon), float(lat)),
            plume_count=int(props.get("plume_count") or 0),
            persistence=float(props.get("persistence") or 0.0),
            emission_auto=_to_float(props.get("emission_auto")),
            emission_uncertainty_auto=_to_float(props.get("emission_uncertainty_auto")),
            # `sources.geojson` publishes the bounds as `timestamp_min` /
            # `timestamp_max`; the older names are kept as fallbacks.
            first_observation=_parse_iso_datetime(
                props.get("timestamp_min") or props.get("first_observation")
            ),
            last_observation=_parse_iso_datetime(
                props.get("timestamp_max") or props.get("last_observation")
            ),
            raw=props,
        )

from_geojson_feature(feature) classmethod

Parse a /catalog/sources.geojson feature into a CMSource.

Always strips the source_name query-string suffix (?plume_gas=...) — this is the canonical strip site, so downstream code can treat CMSource.source_name as clean.

Parameters

feature: GeoJSON Feature dict with at least "geometry" (Point) and "properties" (with source_name and friends).

Returns

CMSource Typed source record with the suffix stripped.

Raises

ValueError If feature["geometry"] does not carry a Point coordinate pair.

Examples

feature = { ... "properties": {"source_name": "x?bbox=1", "sector": "1B2", ... "gas": "CH4", "plume_count": 1, ... "persistence": 0.5}, ... "geometry": {"type": "Point", "coordinates": [-100.0, 30.0]}, ... } CMSource.from_geojson_feature(feature).source_name 'x'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/source.py
@classmethod
def from_geojson_feature(cls, feature: dict) -> CMSource:
    """Parse a ``/catalog/sources.geojson`` feature into a CMSource.

    Always strips the ``source_name`` query-string suffix
    (``?plume_gas=...``) — this is the canonical strip site, so
    downstream code can treat ``CMSource.source_name`` as clean.

    Parameters
    ----------
    feature:
        GeoJSON Feature dict with at least ``"geometry"`` (Point)
        and ``"properties"`` (with ``source_name`` and friends).

    Returns
    -------
    CMSource
        Typed source record with the suffix stripped.

    Raises
    ------
    ValueError
        If ``feature["geometry"]`` does not carry a Point coordinate
        pair.

    Examples
    --------
    >>> feature = {
    ...     "properties": {"source_name": "x?bbox=1", "sector": "1B2",
    ...                    "gas": "CH4", "plume_count": 1,
    ...                    "persistence": 0.5},
    ...     "geometry": {"type": "Point", "coordinates": [-100.0, 30.0]},
    ... }
    >>> CMSource.from_geojson_feature(feature).source_name
    'x'
    """
    props = dict(feature.get("properties") or {})
    geom = feature.get("geometry") or {}
    coords = geom.get("coordinates") or (None, None)
    lon, lat = (
        [*coords, None, None][:2] if isinstance(coords, list) else (None, None)
    )

    if lon is None or lat is None:
        raise ValueError(f"feature is missing Point coordinates: {feature!r}")

    return cls(
        source_name=_strip_query_suffix(str(props.get("source_name", ""))),
        gas=str(props.get("gas", "") or ""),
        sector=str(props.get("sector", "") or ""),
        point=Point(float(lon), float(lat)),
        plume_count=int(props.get("plume_count") or 0),
        persistence=float(props.get("persistence") or 0.0),
        emission_auto=_to_float(props.get("emission_auto")),
        emission_uncertainty_auto=_to_float(props.get("emission_uncertainty_auto")),
        # `sources.geojson` publishes the bounds as `timestamp_min` /
        # `timestamp_max`; the older names are kept as fallbacks.
        first_observation=_parse_iso_datetime(
            props.get("timestamp_min") or props.get("first_observation")
        ),
        last_observation=_parse_iso_datetime(
            props.get("timestamp_max") or props.get("last_observation")
        ),
        raw=props,
    )

geoproducts.carbonmapper.products

Explicit Carbon Mapper product registry.

Every product Carbon Mapper publishes is modelled here as a first-class, frozen descriptor object — its asset key (the filename tail in the asset-proxy URL), the collection family it lives in, and how to open it. Consumers select the products they want explicitly instead of the reader assuming a bundle::

from geoproducts.carbonmapper import products as P

img = CMPlumeImage.from_plume_id(
    plume_id,
    token=token,
    products=(P.PLUME_TIF, P.PLUME_OUTLINE, P.RGB_TIF),
)

Collection identity is factored into :class:CMCollectionSpec — the (gas, cmf_type, version) triple that composes every collection id (l3a-vis-ch4-mfa-v3d etc.). The spec is resolved from the plume record itself (the collection segment of its plume_tif URL, or the gas / cmf_type / emission_version fields), never guessed from a hardcoded version list. A live-API audit (2026-07) verified:

  • the asset-proxy URL pattern {base}/{coll}/{Y}/{M}/{D}/{item}/{item}_{coll}_{key} for both L3A (item = plume_id) and L2B (item = scene name) products;
  • independent versioning across levels — an L3A plume and its L2B parent are re-versioned separately. They usually pair same-version (a v3e L3A plume's parent serves at l2b-ch4-mfa-v3e), but not always: plume tan20260331t181625c77s4001-D is a v3d L3A whose parent still serves at l2b-ch4-mfa-v3c. So compose the parent id from the record's own version and probe it, with older versions as backup — never assume the pairing in either direction;
  • the full asset sets per family (tables below), including the PNG quicklooks the reader previously ignored.

A 2026-09 re-check added two facts:

  • CO2 splits its cmf_type across families. The vis and L2B collections are co2-mfa (l3a-vis-co2-mfa-v3e, l2b-co2-mfa-v3e) while the IME collection is co2-mfal (l3a-ime-co2-mfal-v3e — the record's con_tif and its cmf_type / emission_cmf_type fields name it). Earlier eras published CO2 L2B as l2b-co2-mfal-v3{b,c,d}, so CO2 L2B lookups probe both cmf types. :class:CMCollectionSpec carries the IME cmf_type separately (ime_cmf_type) and resolves it from the record rather than composing it.
  • /stac/collections now registers every version through -v3e and serves items for current scenes (l2b-ch4-mfa-v3e and l2b-co2-mfa-v3e items for August-2026 scenes). The asset-proxy URL derivation below remains the primary path because it needs no catalog round-trip.

CMCollectionSpec dataclass

The (gas, cmf_type, version) triple naming a processing run.

Composes every collection id the reader touches, so that resolving the version once (from the plume record) pins all four product families consistently — the 2026-07 audit verified pairing is same-version across L3A vis / L3A ime / L2B / L2B-RGB.

cmf_type names the vis and L2B collections. ime_cmf_type names the IME collection when it differs — CO2 publishes vis/L2B as mfa but IME as mfal. None means "same as cmf_type" (every CH4 run).

spec = CMCollectionSpec(version="v3d") spec.collection_id(CMProductFamily.L3A_VIS) 'l3a-vis-ch4-mfa-v3d' spec.collection_id(CMProductFamily.L2B) 'l2b-ch4-mfa-v3d' spec.collection_id(CMProductFamily.L2B_RGB) 'l2b-rgb-v3d' co2 = CMCollectionSpec("v3e", "co2", "mfa", ime_cmf_type="mfal") co2.collection_id(CMProductFamily.L3A_IME) 'l3a-ime-co2-mfal-v3e'

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
@dataclass(frozen=True)
class CMCollectionSpec:
    """The ``(gas, cmf_type, version)`` triple naming a processing run.

    Composes every collection id the reader touches, so that resolving
    the version **once** (from the plume record) pins all four product
    families consistently — the 2026-07 audit verified pairing is
    same-version across L3A vis / L3A ime / L2B / L2B-RGB.

    ``cmf_type`` names the vis and L2B collections. ``ime_cmf_type``
    names the IME collection when it differs — CO2 publishes vis/L2B
    as ``mfa`` but IME as ``mfal``. ``None`` means "same as
    ``cmf_type``" (every CH4 run).

    >>> spec = CMCollectionSpec(version="v3d")
    >>> spec.collection_id(CMProductFamily.L3A_VIS)
    'l3a-vis-ch4-mfa-v3d'
    >>> spec.collection_id(CMProductFamily.L2B)
    'l2b-ch4-mfa-v3d'
    >>> spec.collection_id(CMProductFamily.L2B_RGB)
    'l2b-rgb-v3d'
    >>> co2 = CMCollectionSpec("v3e", "co2", "mfa", ime_cmf_type="mfal")
    >>> co2.collection_id(CMProductFamily.L3A_IME)
    'l3a-ime-co2-mfal-v3e'
    """

    version: str
    gas: str = "ch4"
    cmf_type: str = "mfa"
    ime_cmf_type: str | None = None

    def __repr__(self) -> str:
        extra = (
            f", ime_cmf_type={self.ime_cmf_type!r}"
            if self.ime_cmf_type is not None
            else ""
        )
        return (
            f"CMCollectionSpec(version={self.version!r}, gas={self.gas!r}, "
            f"cmf_type={self.cmf_type!r}{extra})"
        )

    def collection_id(self, family: CMProductFamily) -> str:
        """Collection id for one product family under this spec."""
        cmf_type = self.cmf_type
        if family is CMProductFamily.L3A_IME and self.ime_cmf_type:
            cmf_type = self.ime_cmf_type
        return _FAMILY_PATTERNS[family].format(
            gas=self.gas,
            cmf_type=cmf_type,
            version=self.version,
        )

    @classmethod
    def from_collection_id(cls, collection_id: str) -> CMCollectionSpec:
        """Parse a collection id (any family) into its spec.

        >>> CMCollectionSpec.from_collection_id("l3a-vis-ch4-mfa-v3d")
        CMCollectionSpec(version='v3d', gas='ch4', cmf_type='mfa')
        >>> CMCollectionSpec.from_collection_id("l3a-vis-ch4-mf-v1")
        CMCollectionSpec(version='v1', gas='ch4', cmf_type='mf')
        >>> CMCollectionSpec.from_collection_id("l2b-rgb-v3a")
        CMCollectionSpec(version='v3a', gas='ch4', cmf_type='mfa')

        A CO2 IME id names only the IME cmf_type; the vis / L2B one
        keeps the CO2 default (``mfa``):

        >>> CMCollectionSpec.from_collection_id("l3a-ime-co2-mfal-v3e")
        CMCollectionSpec(version='v3e', gas='co2', cmf_type='mfa', ime_cmf_type='mfal')

        Raises:
            ValueError: If ``collection_id`` doesn't match any known
                family pattern.
        """
        m = _COLLECTION_ID_RE.match(collection_id)
        if m is None:
            raise ValueError(
                f"Unrecognised Carbon Mapper collection id "
                f"{collection_id!r} — expected one of the "
                f"{[f.value for f in CMProductFamily]} families."
            )
        gas = m.group("gas") or "ch4"
        cmf_type = m.group("cmf_type") or "mfa"
        is_ime = m.group("family") == CMProductFamily.L3A_IME.value
        if is_ime and gas == "co2" and cmf_type != "mfa":
            # CO2 splits its cmf_type: IME is `mfal`, vis / L2B are `mfa`.
            return cls(
                version=m.group("version"),
                gas=gas,
                cmf_type="mfa",
                ime_cmf_type=cmf_type,
            )
        return cls(version=m.group("version"), gas=gas, cmf_type=cmf_type)

    @classmethod
    def from_plume_record(cls, record: Mapping[str, Any]) -> CMCollectionSpec:
        """Resolve the spec from a ``/catalog/plume/{id}`` record.

        1. Parse the vis collection from the record's ``plume_tif`` URL
           — authoritative for ``version`` / ``gas`` / ``cmf_type``.
        2. Parse the IME collection from the record's ``con_tif`` URL —
           authoritative for the IME cmf_type (CO2: ``mfal``).
        3. Fill whatever is still missing from the ``gas`` /
           ``cmf_type`` (or ``emission_cmf_type``) / ``emission_version``
           fields. The record's cmf_type field names the **IME**
           collection: for CO2 it reads ``mfal`` while the vis and L2B
           collections are ``mfa``, so a fields-only spec sets
           ``cmf_type`` from the field and leaves the vis id unverified.

        Raises:
            ValueError: If none of the three sources yields a version,
                gas and cmf_type.
        """
        vis = _spec_from_asset_url(record.get("plume_tif"), CMProductFamily.L3A_VIS)
        ime = _spec_from_asset_url(record.get("con_tif"), CMProductFamily.L3A_IME)
        field_gas = record.get("gas")
        field_cmf = record.get("cmf_type") or record.get("emission_cmf_type")
        field_version = record.get("emission_version")

        url_spec = vis or ime
        version = url_spec.version if url_spec else field_version
        gas = url_spec.gas if url_spec else field_gas
        cmf_type = vis.cmf_type if vis else (ime.cmf_type if ime else field_cmf)
        ime_cmf_type = (
            (ime.ime_cmf_type or ime.cmf_type)
            if ime
            else (field_cmf if vis and field_cmf else None)
        )
        if not (version and gas and cmf_type):
            raise ValueError(
                f"Cannot resolve a CMCollectionSpec for plume "
                f"{record.get('plume_id')!r}: no parseable 'plume_tif' / "
                "'con_tif' URL and no gas/cmf_type/emission_version fields."
            )
        cmf_type = str(cmf_type)
        if ime_cmf_type is not None and str(ime_cmf_type) == cmf_type:
            ime_cmf_type = None
        return cls(
            version=str(version),
            gas=str(gas).lower(),
            cmf_type=cmf_type,
            ime_cmf_type=None if ime_cmf_type is None else str(ime_cmf_type),
        )

collection_id(family)

Collection id for one product family under this spec.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def collection_id(self, family: CMProductFamily) -> str:
    """Collection id for one product family under this spec."""
    cmf_type = self.cmf_type
    if family is CMProductFamily.L3A_IME and self.ime_cmf_type:
        cmf_type = self.ime_cmf_type
    return _FAMILY_PATTERNS[family].format(
        gas=self.gas,
        cmf_type=cmf_type,
        version=self.version,
    )

from_collection_id(collection_id) classmethod

Parse a collection id (any family) into its spec.

CMCollectionSpec.from_collection_id("l3a-vis-ch4-mfa-v3d") CMCollectionSpec(version='v3d', gas='ch4', cmf_type='mfa') CMCollectionSpec.from_collection_id("l3a-vis-ch4-mf-v1") CMCollectionSpec(version='v1', gas='ch4', cmf_type='mf') CMCollectionSpec.from_collection_id("l2b-rgb-v3a") CMCollectionSpec(version='v3a', gas='ch4', cmf_type='mfa')

A CO2 IME id names only the IME cmf_type; the vis / L2B one keeps the CO2 default (mfa):

CMCollectionSpec.from_collection_id("l3a-ime-co2-mfal-v3e") CMCollectionSpec(version='v3e', gas='co2', cmf_type='mfa', ime_cmf_type='mfal')

Raises:

Type Description
ValueError

If collection_id doesn't match any known family pattern.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
@classmethod
def from_collection_id(cls, collection_id: str) -> CMCollectionSpec:
    """Parse a collection id (any family) into its spec.

    >>> CMCollectionSpec.from_collection_id("l3a-vis-ch4-mfa-v3d")
    CMCollectionSpec(version='v3d', gas='ch4', cmf_type='mfa')
    >>> CMCollectionSpec.from_collection_id("l3a-vis-ch4-mf-v1")
    CMCollectionSpec(version='v1', gas='ch4', cmf_type='mf')
    >>> CMCollectionSpec.from_collection_id("l2b-rgb-v3a")
    CMCollectionSpec(version='v3a', gas='ch4', cmf_type='mfa')

    A CO2 IME id names only the IME cmf_type; the vis / L2B one
    keeps the CO2 default (``mfa``):

    >>> CMCollectionSpec.from_collection_id("l3a-ime-co2-mfal-v3e")
    CMCollectionSpec(version='v3e', gas='co2', cmf_type='mfa', ime_cmf_type='mfal')

    Raises:
        ValueError: If ``collection_id`` doesn't match any known
            family pattern.
    """
    m = _COLLECTION_ID_RE.match(collection_id)
    if m is None:
        raise ValueError(
            f"Unrecognised Carbon Mapper collection id "
            f"{collection_id!r} — expected one of the "
            f"{[f.value for f in CMProductFamily]} families."
        )
    gas = m.group("gas") or "ch4"
    cmf_type = m.group("cmf_type") or "mfa"
    is_ime = m.group("family") == CMProductFamily.L3A_IME.value
    if is_ime and gas == "co2" and cmf_type != "mfa":
        # CO2 splits its cmf_type: IME is `mfal`, vis / L2B are `mfa`.
        return cls(
            version=m.group("version"),
            gas=gas,
            cmf_type="mfa",
            ime_cmf_type=cmf_type,
        )
    return cls(version=m.group("version"), gas=gas, cmf_type=cmf_type)

from_plume_record(record) classmethod

Resolve the spec from a /catalog/plume/{id} record.

  1. Parse the vis collection from the record's plume_tif URL — authoritative for version / gas / cmf_type.
  2. Parse the IME collection from the record's con_tif URL — authoritative for the IME cmf_type (CO2: mfal).
  3. Fill whatever is still missing from the gas / cmf_type (or emission_cmf_type) / emission_version fields. The record's cmf_type field names the IME collection: for CO2 it reads mfal while the vis and L2B collections are mfa, so a fields-only spec sets cmf_type from the field and leaves the vis id unverified.

Raises:

Type Description
ValueError

If none of the three sources yields a version, gas and cmf_type.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
@classmethod
def from_plume_record(cls, record: Mapping[str, Any]) -> CMCollectionSpec:
    """Resolve the spec from a ``/catalog/plume/{id}`` record.

    1. Parse the vis collection from the record's ``plume_tif`` URL
       — authoritative for ``version`` / ``gas`` / ``cmf_type``.
    2. Parse the IME collection from the record's ``con_tif`` URL —
       authoritative for the IME cmf_type (CO2: ``mfal``).
    3. Fill whatever is still missing from the ``gas`` /
       ``cmf_type`` (or ``emission_cmf_type``) / ``emission_version``
       fields. The record's cmf_type field names the **IME**
       collection: for CO2 it reads ``mfal`` while the vis and L2B
       collections are ``mfa``, so a fields-only spec sets
       ``cmf_type`` from the field and leaves the vis id unverified.

    Raises:
        ValueError: If none of the three sources yields a version,
            gas and cmf_type.
    """
    vis = _spec_from_asset_url(record.get("plume_tif"), CMProductFamily.L3A_VIS)
    ime = _spec_from_asset_url(record.get("con_tif"), CMProductFamily.L3A_IME)
    field_gas = record.get("gas")
    field_cmf = record.get("cmf_type") or record.get("emission_cmf_type")
    field_version = record.get("emission_version")

    url_spec = vis or ime
    version = url_spec.version if url_spec else field_version
    gas = url_spec.gas if url_spec else field_gas
    cmf_type = vis.cmf_type if vis else (ime.cmf_type if ime else field_cmf)
    ime_cmf_type = (
        (ime.ime_cmf_type or ime.cmf_type)
        if ime
        else (field_cmf if vis and field_cmf else None)
    )
    if not (version and gas and cmf_type):
        raise ValueError(
            f"Cannot resolve a CMCollectionSpec for plume "
            f"{record.get('plume_id')!r}: no parseable 'plume_tif' / "
            "'con_tif' URL and no gas/cmf_type/emission_version fields."
        )
    cmf_type = str(cmf_type)
    if ime_cmf_type is not None and str(ime_cmf_type) == cmf_type:
        ime_cmf_type = None
    return cls(
        version=str(version),
        gas=str(gas).lower(),
        cmf_type=cmf_type,
        ime_cmf_type=None if ime_cmf_type is None else str(ime_cmf_type),
    )

CMProduct dataclass

One Carbon Mapper product: an asset key within a family.

Identity is (family, key) — e.g. rgb.tif exists both as an L3A per-plume crop and as the L2B whole-scene sibling; they are two distinct products.

Attributes:

Name Type Description
key str

Asset filename tail ("plume-concentrations.tif", "cmf.tif", ...). Carries its extension.

family CMProductFamily

The :class:CMProductFamily whose collections serve it.

description str

One-line human description (audit-grounded).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
@dataclass(frozen=True)
class CMProduct:
    """One Carbon Mapper product: an asset key within a family.

    Identity is ``(family, key)`` — e.g. ``rgb.tif`` exists both as an
    L3A per-plume crop and as the L2B whole-scene sibling; they are two
    distinct products.

    Attributes:
        key: Asset filename tail (``"plume-concentrations.tif"``,
            ``"cmf.tif"``, ...). Carries its extension.
        family: The :class:`CMProductFamily` whose collections serve it.
        description: One-line human description (audit-grounded).
    """

    key: str
    family: CMProductFamily
    description: str = field(default="", compare=False)

    @property
    def name(self) -> str:
        """Python-identifier form of :attr:`key` (no extension,
        ``-`` → ``_``): ``"ime-cmf-mask.tif"`` → ``"ime_cmf_mask"``."""
        return self.band.replace("-", "_")

    @property
    def band(self) -> str:
        """:attr:`key` without its extension — the historical band name
        used as ``CMImageRaster.asset_paths`` key (``"cmf-unortho"``,
        ``"artifact-mask"``, ...)."""
        return self.key.rsplit(".", 1)[0]

    def asset_url(
        self,
        spec: CMCollectionSpec | None,
        item_id: str,
        *,
        date: tuple[str, str, str] | None = None,
        collection_id: str | None = None,
        base: str = CM_API_ASSET_BASE,
    ) -> str:
        """Compose this product's asset-proxy URL.

        Args:
            spec: Collection spec resolving the family to a collection
                id. May be ``None`` when ``collection_id`` is given.
            item_id: ``plume_id`` for L3A products, scene name for L2B.
            date: ``(YYYY, MM, DD)`` override; parsed from ``item_id``
                when omitted.
            collection_id: Explicit collection id override — use when
                the exact id is known from an existing asset URL
                (avoids recomposition drift, and is the only option
                for legacy families like ``l3a-ch4-mf-v1`` that predate
                the vis/ime split).
            base: URL base — swap for the signed-CDN host or a local
                mirror if needed.

        Raises:
            ValueError: If neither ``spec`` nor ``collection_id`` is
                given, or the date can't be parsed from ``item_id``.
        """
        if collection_id is not None:
            coll = collection_id
        elif spec is not None:
            coll = spec.collection_id(self.family)
        else:
            raise ValueError(
                f"asset_url for {self.key!r} needs a spec or an explicit collection_id."
            )
        yyyy, mm, dd = date if date is not None else parse_item_date(item_id)
        return f"{base}/{coll}/{yyyy}/{mm}/{dd}/{item_id}/{item_id}_{coll}_{self.key}"

    def open(
        self,
        path_or_url: str,
        *,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> Any:
        """Open the product from a URL or local path. Kind-specific."""
        raise NotImplementedError

band property

:attr:key without its extension — the historical band name used as CMImageRaster.asset_paths key ("cmf-unortho", "artifact-mask", ...).

name property

Python-identifier form of :attr:key (no extension, - → _): "ime-cmf-mask.tif" → "ime_cmf_mask".

asset_url(spec, item_id, *, date=None, collection_id=None, base=CM_API_ASSET_BASE)

Compose this product's asset-proxy URL.

Parameters:

Name Type Description Default
spec CMCollectionSpec | None

Collection spec resolving the family to a collection id. May be None when collection_id is given.

required
item_id str

plume_id for L3A products, scene name for L2B.

required
date tuple[str, str, str] | None

(YYYY, MM, DD) override; parsed from item_id when omitted.

None
collection_id str | None

Explicit collection id override — use when the exact id is known from an existing asset URL (avoids recomposition drift, and is the only option for legacy families like l3a-ch4-mf-v1 that predate the vis/ime split).

None
base str

URL base — swap for the signed-CDN host or a local mirror if needed.

CM_API_ASSET_BASE

Raises:

Type Description
ValueError

If neither spec nor collection_id is given, or the date can't be parsed from item_id.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def asset_url(
    self,
    spec: CMCollectionSpec | None,
    item_id: str,
    *,
    date: tuple[str, str, str] | None = None,
    collection_id: str | None = None,
    base: str = CM_API_ASSET_BASE,
) -> str:
    """Compose this product's asset-proxy URL.

    Args:
        spec: Collection spec resolving the family to a collection
            id. May be ``None`` when ``collection_id`` is given.
        item_id: ``plume_id`` for L3A products, scene name for L2B.
        date: ``(YYYY, MM, DD)`` override; parsed from ``item_id``
            when omitted.
        collection_id: Explicit collection id override — use when
            the exact id is known from an existing asset URL
            (avoids recomposition drift, and is the only option
            for legacy families like ``l3a-ch4-mf-v1`` that predate
            the vis/ime split).
        base: URL base — swap for the signed-CDN host or a local
            mirror if needed.

    Raises:
        ValueError: If neither ``spec`` nor ``collection_id`` is
            given, or the date can't be parsed from ``item_id``.
    """
    if collection_id is not None:
        coll = collection_id
    elif spec is not None:
        coll = spec.collection_id(self.family)
    else:
        raise ValueError(
            f"asset_url for {self.key!r} needs a spec or an explicit collection_id."
        )
    yyyy, mm, dd = date if date is not None else parse_item_date(item_id)
    return f"{base}/{coll}/{yyyy}/{mm}/{dd}/{item_id}/{item_id}_{coll}_{self.key}"

open(path_or_url, *, token=None, overview_level=None, http_timeout=30.0)

Open the product from a URL or local path. Kind-specific.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def open(
    self,
    path_or_url: str,
    *,
    token: str | None = None,
    overview_level: int | None = None,
    http_timeout: float = 30.0,
) -> Any:
    """Open the product from a URL or local path. Kind-specific."""
    raise NotImplementedError

CMProductFamily

Bases: StrEnum

Which collection family a product's assets live in.

The family decides how the collection id is composed from a :class:CMCollectionSpec and which item id keys the URL (plume_id for L3A products, scene name for L2B products).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMProductFamily(StrEnum):
    """Which collection family a product's assets live in.

    The family decides how the collection id is composed from a
    :class:`CMCollectionSpec` and which item id keys the URL (plume_id
    for L3A products, scene name for L2B products).
    """

    L3A_VIS = "l3a-vis"  #: per-plume visualisation products
    L3A_IME = "l3a-ime"  #: per-plume IME (emission-integral) products
    L2B = "l2b"  #: per-scene retrieval products (gas-typed)
    L2B_RGB = "l2b-rgb"  #: per-scene true-colour sibling (not gas-typed)

CMProductNotSelected

Bases: KeyError

A product was requested from a bundle that didn't select it.

Raised instead of silently returning None so callers notice when they access a product they did not ask for at construction.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMProductNotSelected(KeyError):
    """A product was requested from a bundle that didn't select it.

    Raised instead of silently returning ``None`` so callers notice
    when they access a product they did not ask for at construction.
    """

    def __init__(self, product: CMProduct, selected: tuple[CMProduct, ...]):
        super().__init__(
            f"Product {product.key!r} ({product.family.value}) was not "
            f"selected on this bundle. Selected products: "
            f"{sorted(p.key for p in selected)}. Pass it in `products=` "
            "at construction to use it."
        )
        self.product = product

CMQuicklookProduct dataclass

Bases: CMProduct

A non-georeferenced PNG quicklook → raw bytes.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMQuicklookProduct(CMProduct):
    """A non-georeferenced PNG quicklook → raw ``bytes``."""

    def open(
        self,
        path_or_url: str,
        *,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> bytes:
        del overview_level
        sp = str(path_or_url)
        if sp.startswith(("http://", "https://")):
            headers = bearer_headers_for(sp, token)
            r = _request("GET", sp, headers=headers, timeout=http_timeout)
            r.raise_for_status()
            return r.content
        return Path(sp).read_bytes()

CMRasterProduct dataclass

Bases: CMProduct

A georeferenced raster product (GeoTIFF) → a lazy geoarray.RasterSource.

georeader's RasterioReader reads it (the internal engine), wrapped with geoarray.interop.georeader.source_from_georeader, so reads return a geoarray.GeoArray.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMRasterProduct(CMProduct):
    """A georeferenced raster product (GeoTIFF) → a lazy `geoarray.RasterSource`.

    georeader's ``RasterioReader`` reads it (the internal engine), wrapped
    with ``geoarray.interop.georeader.source_from_georeader``, so reads
    return a `geoarray.GeoArray`.
    """

    def open(
        self,
        path_or_url: str,
        *,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> RasterSource:
        del http_timeout  # GDAL applies its own HTTP timeouts
        return _open_raster(path_or_url, token=token, overview_level=overview_level)

CMTextProduct dataclass

Bases: CMProduct

A plain-text sidecar (uas.txt) → str.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMTextProduct(CMProduct):
    """A plain-text sidecar (``uas.txt``) → ``str``."""

    def open(
        self,
        path_or_url: str,
        *,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> str:
        del overview_level
        sp = str(path_or_url)
        if sp.startswith(("http://", "https://")):
            headers = bearer_headers_for(sp, token)
            r = _request("GET", sp, headers=headers, timeout=http_timeout)
            r.raise_for_status()
            return r.text
        return Path(sp).read_text()

CMVectorProduct dataclass

Bases: CMProduct

A GeoJSON vector product → shapely geometry (EPSG:4326).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
class CMVectorProduct(CMProduct):
    """A GeoJSON vector product → shapely geometry (EPSG:4326)."""

    def open(
        self,
        path_or_url: str,
        *,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> BaseGeometry | None:
        del overview_level
        data = _fetch_json_or_file(path_or_url, token=token, http_timeout=http_timeout)
        from geoproducts.carbonmapper.image import (
            _parse_geojson_to_geometry,
        )

        return _parse_geojson_to_geometry(data)

bearer_headers_for(url, token)

The Authorization header for one request, or {}.

The token is attached only for https:// URLs on Carbon Mapper's API host, never for other hosts (signed-CDN URLs need no token).

Parameters:

Name Type Description Default
url str

The URL about to be requested.

required
token str | None

Carbon Mapper Bearer token, or None.

required

Returns:

Type Description
``{"Authorization"

"Bearer …"}`` or an empty dict.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def bearer_headers_for(url: str, token: str | None) -> dict[str, str]:
    """The ``Authorization`` header for one request, or ``{}``.

    The token is attached only for ``https://`` URLs on Carbon Mapper's
    API host, never for other hosts (signed-CDN URLs need no token).

    Args:
        url: The URL about to be requested.
        token: Carbon Mapper Bearer token, or ``None``.

    Returns:
        ``{"Authorization": "Bearer …"}`` or an empty dict.
    """
    return _bearer_headers_for(url, token, host=_BEARER_HOST)

parse_item_date(item_id)

Extract (YYYY, MM, DD) from a scene name or plume_id.

Both follow <3-char-instrument><YYYYMMDD>t<HHMMSS>... — the date sits at positions [3:11]. Note the record's scene_id field is a UUID and will NOT parse; use the scene name derived from plume_id.rsplit("-", 1)[0].

parse_item_date("tan20260623t124240c80s4001") ('2026', '06', '23')

Raises:

Type Description
ValueError

If positions [3:11] aren't an 8-digit date.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def parse_item_date(item_id: str) -> tuple[str, str, str]:
    """Extract ``(YYYY, MM, DD)`` from a scene name or plume_id.

    Both follow ``<3-char-instrument><YYYYMMDD>t<HHMMSS>...`` — the
    date sits at positions ``[3:11]``. Note the *record's* ``scene_id``
    field is a UUID and will NOT parse; use the scene name derived from
    ``plume_id.rsplit("-", 1)[0]``.

    >>> parse_item_date("tan20260623t124240c80s4001")
    ('2026', '06', '23')

    Raises:
        ValueError: If positions ``[3:11]`` aren't an 8-digit date.
    """
    if len(item_id) < 11 or not item_id[3:11].isdigit():
        raise ValueError(
            f"item id {item_id!r} does not carry an 8-digit date at "
            "positions [3:11] — is this a UUID scene_id? Use the scene "
            "name (plume_id.rsplit('-', 1)[0]) instead."
        )
    d = item_id[3:11]
    return d[:4], d[4:6], d[6:8]

product_for_key(key, *, family=None)

Look up a registry product by asset key (and family for the ambiguous rgb.tif).

product_for_key("plume-outline.geojson").name 'plume_outline' product_for_key("rgb.tif", family=CMProductFamily.L2B_RGB) is SCENE_RGB True

Raises:

Type Description
KeyError

If no product matches (or several do and family wasn't given).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def product_for_key(key: str, *, family: CMProductFamily | None = None) -> CMProduct:
    """Look up a registry product by asset key (and family for the
    ambiguous ``rgb.tif``).

    >>> product_for_key("plume-outline.geojson").name
    'plume_outline'
    >>> product_for_key("rgb.tif", family=CMProductFamily.L2B_RGB) is SCENE_RGB
    True

    Raises:
        KeyError: If no product matches (or several do and ``family``
            wasn't given).
    """
    matches = [
        p
        for p in ALL_PRODUCTS
        if p.key == key and (family is None or p.family == family)
    ]
    if len(matches) == 1:
        return matches[0]
    if not matches:
        raise KeyError(f"No Carbon Mapper product with key {key!r}")
    raise KeyError(
        f"Ambiguous product key {key!r} — matches families "
        f"{[p.family.value for p in matches]}; pass family=."
    )

rio_env_options_for(path, token)

GDAL env options that authenticate one remote raster read.

Returns None (use georeader's defaults) for local paths, when no token is given, or for hosts other than Carbon Mapper's API (see :func:bearer_headers_for). Otherwise returns the defaults plus a GDAL_HTTP_HEADERS Bearer header, which RasterioReader applies only inside its own rasterio.Env — the token is never exported process-wide.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/products.py
def rio_env_options_for(path: str, token: str | None) -> dict[str, Any] | None:
    """GDAL env options that authenticate one remote raster read.

    Returns ``None`` (use georeader's defaults) for local paths, when no
    token is given, or for hosts other than Carbon Mapper's API (see
    :func:`bearer_headers_for`). Otherwise returns the defaults plus a
    ``GDAL_HTTP_HEADERS`` Bearer header, which ``RasterioReader``
    applies only inside its own ``rasterio.Env`` — the token is never
    exported process-wide.
    """
    if not bearer_headers_for(path, token):
        return None
    from georeader.rasterio_reader import RIO_ENV_OPTIONS_DEFAULT

    return {
        **RIO_ENV_OPTIONS_DEFAULT,
        "GDAL_HTTP_HEADERS": f"Authorization: Bearer {token}",
    }

geoproducts.carbonmapper.image

Per-plume image bundle wrapper for Carbon Mapper L3A products.

One :class:CMPlumeImage is the cropped raster suite for one plume — binary mask, full column-density crop, IME-clipped retrieval, RGB context, and the canonical outline polygon. This is the per-plume counterpart to :class:~geoproducts.carbonmapper.rasters.CMImageRaster (which wraps L2B scenes).

Which products the bundle carries is an explicit caller choice — the products= parameter takes descriptors from :mod:~geoproducts.carbonmapper.products (defaulting to the 7 GeoTIFF/GeoJSON assets). Collection versioning is resolved per plume from the record's own plume_tif URL via :class:~geoproducts.carbonmapper.products.CMCollectionSpec — nothing is guessed from hardcoded version lists, so the wrapper works for any gas / cmf_type / version CM publishes (v3a, v3c, v3d, …).

Why URL derivation instead of STAC: until 2026 the STAC registry stopped at -v3a and newer collections were reachable only via direct asset URLs. STAC now registers current versions too (re-checked 2026-09), but deriving from the plume record still needs no extra catalog round-trip and works for every version. :meth:CMPlumeImage.from_plume_id derives all asset URLs from the REST catalog response (which has signed CDN URLs for any version) and rewrites them to the Bearer-aware api gateway form so the URLs don't expire.

Outline GeoJSON is the canonical source for the plume polygon; if the fetch fails (network / 404 / malformed body), we fall back to vectorising the band-4 alpha of plume.tif and log a warning so callers notice when they're not on the canonical path.

CMPlumeImage dataclass

Per-plume L3A bundle — outline polygon + L2B tile bridge.

The two things consumers actually want from a plume:

  1. Polygon geometry for the plume — :attr:outline returns a shapely MultiPolygon in EPSG:4326. The plume REST response's geometry_json is only a centroid Point; the canonical polygon lives on this L3A asset bundle.
  2. The L2B parent tile for full-resolution rasters — :attr:tile resolves the parent :class:CMImageRaster transparently for v3a (via STAC) and every current-era version (via URL-pattern fallback). The :meth:tile_cmf / :meth:tile_rgb / :meth:tile_uncertainty methods crop the L2B band by the outline polygon at full native resolution — this is the analysis-grade workflow.

The L3A pre-cropped thumbnails (:attr:mask, :attr:concentrations, :attr:ime_concentrations, :attr:ime_mask, :attr:rgb) are kept as a convenience for fast preview UIs. They are typically 41 × 48 px for plume-concentrations.tif and as small as 11 × 11 px for ime-cmf-concentrations.tif — well below analysis quality. For any quantitative work, prefer the tile_* methods.

Lazy: instantiating the dataclass does NOT issue HTTP / blob reads. Each property opens its asset on first access and caches the result.

Recommended workflow::

img = CMPlumeImage.from_plume_id(plume_id, token=token)
outline = img.outline                        # MultiPolygon in EPSG:4326
crop    = img.tile_cmf(pad_px=64)            # GeoArray (1, h, w), full L2B res
rgb     = img.tile_rgb(pad_px=64)            # 3-band context image

Attributes:

Name Type Description
plume_id str

Carbon Mapper plume_id (e.g. "tan20251212t185057c20s4001-E").

urls Mapping[str, str]

Mapping of asset name → URL (Bearer-aware api gateway form preferred; signed CDN URLs work but expire). Up to 7 keys expected: plume.tif, plume-concentrations.tif, plume-outline.geojson, rgb.tif, ime-cmf-concentrations.tif, ime-cmf-mask.tif, ime-cmf-outline.geojson. Missing keys → corresponding property returns None.

token str | None

Bearer token. Required for :attr:tile (the L2B asset proxy is always Bearer-gated). May be None for L3A-only usage if :attr:urls already point at signed CDN URLs or local files.

overview_level int | None

None for full resolution, integer for COG overviews.

http_timeout float

Per-request timeout (seconds) for the outline GeoJSON fetch. Defaults to 30s.

products tuple[CMProduct, ...]

The explicit product selection this bundle exposes (descriptors from :mod:~geoproducts.carbonmapper.products). Accessing a product outside the selection raises :class:~geoproducts.carbonmapper.products.CMProductNotSelected. Defaults to :data:~geoproducts.carbonmapper.products.DEFAULT_PLUME_PRODUCTS.

spec CMCollectionSpec | None

The plume's resolved :class:~geoproducts.carbonmapper.products.CMCollectionSpec. Set by the from_* constructors; enables :attr:tile to resolve the L2B parent at the same version with zero probing. None for hand-built bundles (tile then falls back to the probing resolver).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
@dataclass(repr=False)
class CMPlumeImage:
    """Per-plume L3A bundle — **outline polygon + L2B tile bridge**.

    The two things consumers actually want from a plume:

    1. **Polygon geometry** for the plume — :attr:`outline` returns a
       shapely ``MultiPolygon`` in EPSG:4326. The plume REST response's
       ``geometry_json`` is only a centroid Point; the canonical
       polygon lives on this L3A asset bundle.
    2. **The L2B parent tile** for full-resolution rasters —
       :attr:`tile` resolves the parent :class:`CMImageRaster`
       transparently for v3a (via STAC) and every current-era version
       (via URL-pattern fallback). The :meth:`tile_cmf` / :meth:`tile_rgb` /
       :meth:`tile_uncertainty` methods crop the L2B band by the
       outline polygon at full native resolution — this is the
       analysis-grade workflow.

    The L3A pre-cropped thumbnails (:attr:`mask`,
    :attr:`concentrations`, :attr:`ime_concentrations`,
    :attr:`ime_mask`, :attr:`rgb`) are kept as a convenience for fast
    preview UIs. They are typically **41 × 48 px** for
    ``plume-concentrations.tif`` and as small as **11 × 11 px** for
    ``ime-cmf-concentrations.tif`` — well below analysis quality. For
    any quantitative work, prefer the ``tile_*`` methods.

    Lazy: instantiating the dataclass does NOT issue HTTP / blob reads.
    Each property opens its asset on first access and caches the
    result.

    Recommended workflow::

        img = CMPlumeImage.from_plume_id(plume_id, token=token)
        outline = img.outline                        # MultiPolygon in EPSG:4326
        crop    = img.tile_cmf(pad_px=64)            # GeoArray (1, h, w), full L2B res
        rgb     = img.tile_rgb(pad_px=64)            # 3-band context image

    Attributes:
        plume_id: Carbon Mapper plume_id (e.g.
            ``"tan20251212t185057c20s4001-E"``).
        urls: Mapping of asset name → URL (Bearer-aware api gateway
            form preferred; signed CDN URLs work but expire). Up to 7
            keys expected: ``plume.tif``, ``plume-concentrations.tif``,
            ``plume-outline.geojson``, ``rgb.tif``,
            ``ime-cmf-concentrations.tif``, ``ime-cmf-mask.tif``,
            ``ime-cmf-outline.geojson``. Missing keys → corresponding
            property returns ``None``.
        token: Bearer token. Required for :attr:`tile` (the L2B asset
            proxy is always Bearer-gated). May be ``None`` for L3A-only
            usage if :attr:`urls` already point at signed CDN URLs or
            local files.
        overview_level: ``None`` for full resolution, integer for COG
            overviews.
        http_timeout: Per-request timeout (seconds) for the outline
            GeoJSON fetch. Defaults to 30s.
        products: The explicit product selection this bundle exposes
            (descriptors from
            :mod:`~geoproducts.carbonmapper.products`). Accessing
            a product outside the selection raises
            :class:`~geoproducts.carbonmapper.products.CMProductNotSelected`.
            Defaults to
            :data:`~geoproducts.carbonmapper.products.DEFAULT_PLUME_PRODUCTS`.
        spec: The plume's resolved
            :class:`~geoproducts.carbonmapper.products.CMCollectionSpec`.
            Set by the ``from_*`` constructors; enables :attr:`tile` to
            resolve the L2B parent at the **same version** with zero
            probing. ``None`` for hand-built bundles (``tile`` then
            falls back to the probing resolver).
    """

    plume_id: str
    urls: Mapping[str, str]
    token: str | None = None
    overview_level: int | None = None
    http_timeout: float = 30.0
    products: tuple[CMProduct, ...] = DEFAULT_PLUME_PRODUCTS
    spec: CMCollectionSpec | None = None

    def __post_init__(self) -> None:
        self._product_cache: dict[str, Any] = {}

    # ---- Generic product access ----------------------------------------

    def product(self, product: CMProduct) -> Any:
        """Open one selected product (cached per product key).

        Returns the product-kind-specific object — a lazy
        `geoarray.RasterSource` for raster products, a shapely geometry
        for vector products, ``bytes`` for PNG quicklooks. Returns
        ``None`` when the product was selected but its URL was not
        available from the source (e.g. :meth:`from_stac_item` with a
        missing sibling item).

        Raises:
            CMProductNotSelected: If ``product`` is not in
                :attr:`products` — select it at construction to use it.
        """
        if product not in self.products:
            raise CMProductNotSelected(product, tuple(self.products))
        if product.key in self._product_cache:
            return self._product_cache[product.key]
        url = self.urls.get(product.key)
        value = None
        if url is not None:
            value = product.open(
                str(url),
                token=self.token,
                overview_level=self.overview_level,
                http_timeout=self.http_timeout,
            )
        self._product_cache[product.key] = value
        return value

    # ---- Constructors --------------------------------------------------

    @classmethod
    def from_plume_id(
        cls,
        plume_id: str,
        *,
        token: str,
        products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> CMPlumeImage:
        """Build by fetching ``/catalog/plume/{id}`` then deriving asset URLs.

        One round-trip. Works for any collection version (v3a onwards,
        including versions cut after this docstring was written) — the
        version is resolved from the record itself via
        :class:`CMCollectionSpec`, never guessed.

        Args:
            plume_id: Colloquial plume id.
            token: Bearer token.
            products: Explicit product selection (see
                :mod:`~geoproducts.carbonmapper.products`).
            overview_level: See the class attribute.
            http_timeout: See the class attribute.

        Raises:
            requests.HTTPError: On REST failure (404 etc.; 429 is
                retried first).
            ValueError: If the response lacks the ``plume_tif`` URL the
                derivation needs.
        """
        from geoproducts.carbonmapper import download as _dl

        record = _dl.get_plume_by_id(plume_id, token=token)
        # The endpoint accepts a UUID too; the colloquial id (which the
        # tile bridge needs to derive the scene name) is on the record.
        return cls(
            plume_id=str(record.get("plume_id") or plume_id),
            urls=_derive_asset_urls(record, products),
            token=token,
            overview_level=overview_level,
            http_timeout=http_timeout,
            products=tuple(products),
            spec=_spec_or_none(record),
        )

    @classmethod
    def from_cmrawplume(
        cls,
        raw: CMRawPlume,
        *,
        token: str,
        products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> CMPlumeImage:
        """Build from an already-fetched typed plume.

        Useful when the caller is iterating over a list returned by
        ``api_queries.list_plumes(...)`` and wants the image bundle
        per plume without re-fetching the catalog dict. Derives URLs
        from the asset URLs the typed model already carries.
        """
        if not raw.plume_tif:
            raise ValueError(
                f"CMRawPlume {raw.plume_id!r} has no plume_tif URL — "
                f"can't derive asset URLs."
            )
        seed = {
            "plume_tif": raw.plume_tif,
            "con_tif": raw.con_tif,
            "plume_id": raw.plume_id,
            "gas": raw.gas,
            "cmf_type": raw.emission_cmf_type,
            "emission_version": raw.emission_version,
        }
        return cls(
            plume_id=raw.plume_id,
            urls=_derive_asset_urls(seed, products),
            token=token,
            overview_level=overview_level,
            http_timeout=http_timeout,
            products=tuple(products),
            spec=_spec_or_none(seed),
        )

    @classmethod
    def from_stac_item(
        cls,
        item: Mapping[str, Any],
        *,
        ime_item: Mapping[str, Any] | None = None,
        products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
        token: str | None = None,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> CMPlumeImage:
        """Build from STAC items (vis + optional ime sibling).

        Use when the caller is driving STAC search directly. STAC
        registers every version through v3e (re-checked 2026-09), but
        :meth:`from_plume_id` needs no search and works for any version.
        Pass both the vis and ime items if you have them (recommended);
        the ime sibling provides the ``ime-*`` product URLs. Asset keys
        are accepted with or without their file extension.

        Raises:
            ValueError: If ``ime_item``'s ``id`` is absent or differs from
                ``item``'s (the two must describe the same plume).
        """
        plume_id = str(item.get("id", ""))
        if ime_item is not None and str(ime_item.get("id", "")) != plume_id:
            raise ValueError(
                f"ime_item id {ime_item.get('id')!r} does not match the vis "
                f"item id {plume_id!r}"
            )
        urls: dict[str, str] = {}
        for product in products:
            source = item if product.family == CMProductFamily.L3A_VIS else ime_item
            if source is None:
                continue
            # STAC items key assets with the extension (`plume.tif`);
            # accept the extension-less form too.
            assets = source.get("assets") or {}
            asset = assets.get(product.key) or assets.get(product.band) or {}
            href = asset.get("href") if isinstance(asset, Mapping) else None
            if href:
                urls[product.key] = href
        spec: CMCollectionSpec | None = None
        collection = item.get("collection")
        if collection:
            try:
                spec = CMCollectionSpec.from_collection_id(str(collection))
            except ValueError:
                spec = None
        return cls(
            plume_id=plume_id,
            urls=urls,
            token=token,
            overview_level=overview_level,
            http_timeout=http_timeout,
            products=tuple(products),
            spec=spec,
        )

    # ---- Lazy raster properties (delegate to the product registry) ----

    @property
    def mask(self) -> RasterSource | None:
        """L3A pre-cropped RGBA GeoTIFF — band 4 alpha is the binary mask.

        **Thumbnail-grade.** Typically a small per-plume window
        (~30–50 px per side). For analysis-grade rasters at full L2B
        native resolution, prefer :meth:`tile_cmf` cropped by
        :attr:`outline`.

        A lazy `geoarray.RasterSource`. Returns ``None`` if
        ``plume.tif`` URL is absent; raises
        :class:`CMProductNotSelected` if ``PLUME_TIF`` wasn't selected.
        """
        return self.product(PLUME_TIF)

    @property
    def concentrations(self) -> RasterSource | None:
        """L3A pre-cropped CH4 column density thumbnail (ppm·m).

        **Thumbnail-grade — typically ~41 × 48 px.** Covers the full
        per-plume window incl. noise floor outside the mask. Use
        :attr:`ime_concentrations` for the IME-clipped variant.

        For analysis-grade resolution, prefer :meth:`tile_cmf` —
        crops the L2B parent at native pixel grid (~150 × 150 px
        with default padding).
        """
        return self.product(PLUME_CONCENTRATIONS)

    @property
    def ime_concentrations(self) -> RasterSource | None:
        """L3A IME-clipped CH4 column density (ppm·m).

        **Thumbnail-grade — typically ~11 × 11 px.** Only
        mask-significant pixels (others NoData). This is the raster
        Carbon Mapper uses to compute the plume's ``emission_auto``
        integral — so it's the right thing if you want to reproduce
        the upstream emission calculation, but **the wrong thing if
        you want a recognisable plume image** (pixelates into
        circle-like blobs at this resolution).

        For an analysis-grade plume image at L2B native resolution,
        use :meth:`tile_cmf` cropped by :attr:`outline` instead.

        Returns ``None`` if the IME sibling URL wasn't provided
        (e.g. :meth:`from_stac_item` without ``ime_item``).
        """
        return self.product(IME_CONCENTRATIONS)

    @property
    def rgb(self) -> RasterSource | None:
        """L3A pre-cropped 3-band uint8 true-colour GeoTIFF.

        **Thumbnail-grade** per-plume crop. For full-resolution true
        colour at L2B native pixel size (analysis-grade context for
        overlays), use :meth:`tile_rgb`.
        """
        return self.product(RGB_TIF)

    @property
    def ime_mask(self) -> RasterSource | None:
        """L3A binary mask of pixels that contributed to ``emission_auto``.

        From ``ime-cmf-mask.tif`` — a tighter subset of
        :attr:`mask`'s band-4 alpha. **Thumbnail-grade** (same ~11 × 11
        px window as :attr:`ime_concentrations`). Use this when you
        specifically need the IME-significant pixel set (e.g. for
        re-quantification with a different wind product) rather than
        the broader plume polygon.
        """
        return self.product(IME_MASK)

    @cached_property
    def outline(self) -> BaseGeometry | None:
        """Plume polygon in EPSG:4326 (broader — the full plume mask).

        Canonical source: ``plume-outline.geojson`` from the asset
        bundle. If that fetch fails (network / 404 / malformed), falls
        back to vectorising the band-4 alpha of :attr:`mask` and logs
        a warning so callers notice when they're not on the canonical
        path.

        Returns ``None`` if neither source is reachable. For the
        tighter IME-significant polygon used in the
        ``emission_auto`` integral, use :attr:`ime_outline`.
        """
        try:
            geom = self.product(PLUME_OUTLINE)
            if geom is not None:
                return geom
        except CMProductNotSelected:
            raise
        except Exception as exc:
            if _is_transient(exc):
                # Don't cache a fallback polygon for a throttled / failed
                # request — let the next access retry the canonical path.
                raise
            _log.warning(
                "outline GeoJSON fetch failed for plume %s (%s); "
                "falling back to band-4 alpha vectorize",
                self.plume_id,
                exc,
            )
        return self._polygon_from_alpha()

    @cached_property
    def ime_outline(self) -> BaseGeometry | None:
        """IME-significance polygon in EPSG:4326 (tighter than :attr:`outline`).

        Tracks the ``ime-cmf-outline.geojson`` asset — the polygon
        Carbon Mapper actually integrated over for ``emission_auto``.
        Excludes pixels below the IME detection threshold (which
        :attr:`outline` includes via the broader plume mask).

        Returns ``None`` if the IME outline isn't reachable (older
        plumes, network failure, etc.); does **not** vectorize-fallback
        because :attr:`ime_mask` and :attr:`outline` are both
        readily available substitutes.
        """
        try:
            return self.product(IME_OUTLINE)
        except CMProductNotSelected:
            raise
        except Exception as exc:
            if _is_transient(exc):
                raise
            _log.warning(
                "ime-cmf-outline.geojson fetch failed for plume %s (%s)",
                self.plume_id,
                exc,
            )
            return None

    # ---- Tile bridge --------------------------------------------------

    @cached_property
    def scene_id(self) -> str:
        """Parent L2B ``scene_id``, derived from ``plume_id`` (no HTTP).

        Carbon Mapper convention: ``plume_id == "{scene_id}-{part}"``.
        Splitting on the last ``-`` recovers the parent scene id used
        by STAC item lookup and the asset-proxy URL pattern.

        >>> img = CMPlumeImage(plume_id="tan20260331t181625c77s4001-A", urls={})
        >>> img.scene_id
        'tan20260331t181625c77s4001'
        """
        return self.plume_id.rsplit("-", 1)[0]

    @cached_property
    def tile(self) -> CMImageRaster:
        """Parent L2B :class:`CMImageRaster` for this plume (lazy).

        When :attr:`spec` is known (any ``from_*`` constructor), the
        L2B parent is resolved by probing the plume's **own collection
        version first** (usually one probe — same-version pairing),
        with the default candidates as backup for the re-versioned
        case (a v3d L3A plume whose L2B parent still serves at v3c).
        No STAC lookup, no extra catalog calls, and never stale.
        Without a spec (hand-built bundles), falls back to
        :func:`~geoproducts.carbonmapper.api_queries.get_image_raster_for_plume`
        (STAC first, then candidate probing). Result is cached, so
        subsequent crops reuse the same raster handle.

        Requires :attr:`token` (set at construction). The L3A asset
        URLs on :attr:`urls` are usable without a token only when
        they're signed CDN URLs (which expire); the L2B asset proxy
        always needs Bearer auth.

        Raises:
            ValueError: If :attr:`token` is ``None``.
            RuntimeError: If the spec-less fallback could not resolve
                the L2B parent through either STAC or candidate
                probing.

        >>> img = CMPlumeImage.from_plume_id(  # doctest: +SKIP
        ...     "tan20260331t181625c77s4001-A", token=tok,
        ... )
        >>> img.tile.cmf  # doctest: +SKIP
        source_from_georeader(<RasterioReader …/l2b-ch4-mfa-v3c/2026/03/31/…/cmf.tif>)
        """
        if self.token is None:
            msg = (
                f"CMPlumeImage(plume_id={self.plume_id!r}) has no token — "
                "cannot fetch the L2B tile. Pass token= at construction "
                "or use from_plume_id/from_cmrawplume which take it."
            )
            raise ValueError(msg)

        # Lazy import to avoid pulling the L2B raster machinery (and
        # api_queries) into the L3A-only import path.
        from geoproducts.carbonmapper.rasters import CMImageRaster

        if self.spec is not None:
            return CMImageRaster.from_scene_id(
                self.scene_id,
                token=self.token,
                spec=self.spec,
                overview_level=self.overview_level,
                http_timeout=self.http_timeout,
            )

        from geoproducts.carbonmapper.api_queries import (
            get_image_raster_for_plume,
        )

        ir = get_image_raster_for_plume(self.token, self.plume_id)
        if ir is None:
            msg = (
                f"L2B parent tile for plume {self.plume_id!r} is not "
                "reachable. Neither STAC nor the URL-pattern fallback "
                "resolved it. Either the scene hasn't been published or "
                "it uses a collection variant not in the candidate list."
            )
            raise RuntimeError(msg)
        return ir

    def tile_cmf(self, *, pad_px: int = 64) -> GeoArray:
        """L2B CH4 retrieval cropped to :attr:`outline`, full L2B resolution.

        This is the headline workflow: the analysis-grade
        ``cmf`` raster, tightly cropped to the plume polygon, at the
        L2B's native pixel grid — **not** the pre-cropped L3A
        thumbnail (``plume-concentrations.tif`` is typically
        ~41×48 px, ``ime-cmf-concentrations.tif`` only ~11×11 px).

        Args:
            pad_px: Pixels of context to add on every side around the
                outline bounding rectangle. Default ``64`` shows the
                plume embedded in its surroundings — set to ``0`` for
                a tight crop, larger for more context.

        Returns:
            `geoarray.GeoArray` — eagerly loaded, ready to plot.

        Raises:
            ValueError: If :attr:`outline` is ``None`` (canonical fetch
                failed AND band-4 vectorize fallback failed — rare).
            ValueError, RuntimeError: If :attr:`tile` couldn't be
                resolved (see :attr:`tile`).

        >>> crop = img.tile_cmf(pad_px=64)  # doctest: +SKIP
        >>> crop.shape  # doctest: +SKIP
        (1, 168, 152)
        """
        return self._crop_tile_band("cmf", pad_px=pad_px)

    def tile_rgb(self, *, pad_px: int = 64) -> GeoArray:
        """L2B true-colour RGB sibling cropped to :attr:`outline`.

        See :meth:`tile_cmf` for the cropping semantics. Returns the
        3-band RGB raster at L2B native resolution — the "proper image"
        backdrop for a plume polygon overlay.

        Raises:
            KeyError: If the tile has no RGB sibling URL (rare —
                ``with_rgb=True`` is the default on the tile resolver).
        """
        return self._crop_tile_band("rgb", pad_px=pad_px)

    def tile_uncertainty(self, *, pad_px: int = 64) -> GeoArray:
        """L2B per-pixel uncertainty cropped to :attr:`outline`.

        Companion to :meth:`tile_cmf` — the uncertainty raster shares
        the cmf's pixel grid. See :meth:`tile_cmf` for the cropping
        semantics.
        """
        return self._crop_tile_band("uncertainty", pad_px=pad_px)

    def _crop_tile_band(self, band: str, *, pad_px: int) -> GeoArray:
        """Shared crop pipeline for the ``tile_*`` methods.

        Cropping rule: take the plume polygon's bounding rectangle in
        the L2B's CRS, add ``pad_px`` pixels on each side, read that
        window. Same algorithm as ``CMImageRaster.read_polygon`` but
        with explicit padding for a single band.
        """
        outline = self.outline
        if outline is None:
            msg = (
                f"CMPlumeImage(plume_id={self.plume_id!r}).outline is None "
                "— canonical plume-outline.geojson fetch failed AND the "
                "band-4 alpha vectorize fallback returned no geometry. "
                "Cannot crop the tile."
            )
            raise ValueError(msg)

        tile = self.tile
        reader = getattr(tile, band.replace("-", "_"), None)
        if reader is None:
            msg = (
                f"L2B tile for plume {self.plume_id!r} has no {band!r} "
                f"asset. Available: {sorted(tile.asset_paths)}."
            )
            raise KeyError(msg)

        from geoarray.interop.georeader import from_georeader, source_to_georeader
        from georeader import read

        # `boundless=False` returns None on zero-overlap windows. The
        # outline is derived from this plume, which came from this
        # tile, so non-overlap implies a data bug — surface it loudly.
        result = read.read_from_polygon(
            source_to_georeader(reader),
            polygon=outline,
            crs_polygon="EPSG:4326",
            pad_add=(pad_px, pad_px),
            boundless=False,
            trigger_load=True,
        )
        if result is None:
            msg = (
                f"Outline of plume {self.plume_id!r} doesn't overlap its "
                f"parent tile (scene_id={self.scene_id!r}, band={band!r}). "
                "This indicates upstream data inconsistency."
            )
            raise RuntimeError(msg)
        # `trigger_load=True` materialises the read (a georeader
        # GeoTensor); a lazy window reader would be loaded here.
        if hasattr(result, "load") and not isinstance(result, np.ndarray):
            result = result.load()
        return from_georeader(result)

    # ---- Auxiliary -----------------------------------------------------

    def load_alpha_mask(self) -> GeoArray | None:
        """Load just band 4 of :attr:`mask` as a boolean ``(H, W)`` GeoArray."""
        reader = self.mask
        if reader is None:
            return None
        geo = reader.load()
        arr = np.asarray(geo)
        if arr.ndim != 3 or arr.shape[0] < 4:
            return None
        return GeoArray(
            arr[3] > 0, geo.transform, geo.crs, fill_value=False, dims=("y", "x")
        )

    # ---- Internals -----------------------------------------------------

    def _polygon_from_alpha(self) -> BaseGeometry | None:
        """Vectorise band-4 alpha of :attr:`mask` to an EPSG:4326 polygon.

        Fallback path — used only when the canonical
        ``plume-outline.geojson`` is unreachable.
        """
        reader = self.mask
        if reader is None:
            return None
        geo = reader.load()
        arr = np.asarray(geo)
        if arr.ndim != 3 or arr.shape[0] < 4:
            return None
        alpha = arr[3]
        mask = (alpha > 0).astype("uint8")
        if not mask.any():
            return None

        # Lazy import to keep rasterio out of the import path when only
        # the GeoJSON-canonical outline is used.
        import rasterio.features

        polys = [
            shape(geom)
            for geom, val in rasterio.features.shapes(
                mask,
                mask=mask.astype(bool),
                transform=geo.grid.affine,
            )
            if val == 1
        ]
        if not polys:
            return None
        merged = unary_union(polys)
        from georeader import window_utils

        return window_utils.polygon_to_crs(
            merged,
            crs_polygon=geo.crs.to_wkt() if geo.crs is not None else None,
            dst_crs="EPSG:4326",
        )

    # ---- Repr ---------------------------------------------------------

    def __repr__(self) -> str:
        selected = [p.key for p in self.products]
        present = [k for k in selected if k in self.urls]
        missing = [k for k in selected if k not in self.urls]
        ov = self.overview_level if self.overview_level is not None else "full"
        lines = [
            "CMPlumeImage",
            f"  plume_id:       {self.plume_id}",
            f"  assets present: {present or '<none>'}",
        ]
        if missing:
            lines.append(f"  assets missing: {missing}")
        if self.spec is not None:
            lines.append(f"  spec:           {self.spec}")
        lines.append(f"  overview_level: {ov}")
        return "\n".join(lines)

    __str__ = __repr__

concentrations property

L3A pre-cropped CH4 column density thumbnail (ppm·m).

Thumbnail-grade — typically ~41 × 48 px. Covers the full per-plume window incl. noise floor outside the mask. Use :attr:ime_concentrations for the IME-clipped variant.

For analysis-grade resolution, prefer :meth:tile_cmf — crops the L2B parent at native pixel grid (~150 × 150 px with default padding).

ime_concentrations property

L3A IME-clipped CH4 column density (ppm·m).

Thumbnail-grade — typically ~11 × 11 px. Only mask-significant pixels (others NoData). This is the raster Carbon Mapper uses to compute the plume's emission_auto integral — so it's the right thing if you want to reproduce the upstream emission calculation, but the wrong thing if you want a recognisable plume image (pixelates into circle-like blobs at this resolution).

For an analysis-grade plume image at L2B native resolution, use :meth:tile_cmf cropped by :attr:outline instead.

Returns None if the IME sibling URL wasn't provided (e.g. :meth:from_stac_item without ime_item).

ime_mask property

L3A binary mask of pixels that contributed to emission_auto.

From ime-cmf-mask.tif — a tighter subset of :attr:mask's band-4 alpha. Thumbnail-grade (same ~11 × 11 px window as :attr:ime_concentrations). Use this when you specifically need the IME-significant pixel set (e.g. for re-quantification with a different wind product) rather than the broader plume polygon.

ime_outline cached property

IME-significance polygon in EPSG:4326 (tighter than :attr:outline).

Tracks the ime-cmf-outline.geojson asset — the polygon Carbon Mapper actually integrated over for emission_auto. Excludes pixels below the IME detection threshold (which :attr:outline includes via the broader plume mask).

Returns None if the IME outline isn't reachable (older plumes, network failure, etc.); does not vectorize-fallback because :attr:ime_mask and :attr:outline are both readily available substitutes.

mask property

L3A pre-cropped RGBA GeoTIFF — band 4 alpha is the binary mask.

Thumbnail-grade. Typically a small per-plume window (~30–50 px per side). For analysis-grade rasters at full L2B native resolution, prefer :meth:tile_cmf cropped by :attr:outline.

A lazy geoarray.RasterSource. Returns None if plume.tif URL is absent; raises :class:CMProductNotSelected if PLUME_TIF wasn't selected.

outline cached property

Plume polygon in EPSG:4326 (broader — the full plume mask).

Canonical source: plume-outline.geojson from the asset bundle. If that fetch fails (network / 404 / malformed), falls back to vectorising the band-4 alpha of :attr:mask and logs a warning so callers notice when they're not on the canonical path.

Returns None if neither source is reachable. For the tighter IME-significant polygon used in the emission_auto integral, use :attr:ime_outline.

rgb property

L3A pre-cropped 3-band uint8 true-colour GeoTIFF.

Thumbnail-grade per-plume crop. For full-resolution true colour at L2B native pixel size (analysis-grade context for overlays), use :meth:tile_rgb.

scene_id cached property

Parent L2B scene_id, derived from plume_id (no HTTP).

Carbon Mapper convention: plume_id == "{scene_id}-{part}". Splitting on the last - recovers the parent scene id used by STAC item lookup and the asset-proxy URL pattern.

img = CMPlumeImage(plume_id="tan20260331t181625c77s4001-A", urls={}) img.scene_id 'tan20260331t181625c77s4001'

tile cached property

Parent L2B :class:CMImageRaster for this plume (lazy).

When :attr:spec is known (any from_* constructor), the L2B parent is resolved by probing the plume's own collection version first (usually one probe — same-version pairing), with the default candidates as backup for the re-versioned case (a v3d L3A plume whose L2B parent still serves at v3c). No STAC lookup, no extra catalog calls, and never stale. Without a spec (hand-built bundles), falls back to :func:~geoproducts.carbonmapper.api_queries.get_image_raster_for_plume (STAC first, then candidate probing). Result is cached, so subsequent crops reuse the same raster handle.

Requires :attr:token (set at construction). The L3A asset URLs on :attr:urls are usable without a token only when they're signed CDN URLs (which expire); the L2B asset proxy always needs Bearer auth.

Raises:

Type Description
ValueError

If :attr:token is None.

RuntimeError

If the spec-less fallback could not resolve the L2B parent through either STAC or candidate probing.

img = CMPlumeImage.from_plume_id( # doctest: +SKIP ... "tan20260331t181625c77s4001-A", token=tok, ... ) img.tile.cmf # doctest: +SKIP source_from_georeader()

from_cmrawplume(raw, *, token, products=DEFAULT_PLUME_PRODUCTS, overview_level=None, http_timeout=30.0) classmethod

Build from an already-fetched typed plume.

Useful when the caller is iterating over a list returned by api_queries.list_plumes(...) and wants the image bundle per plume without re-fetching the catalog dict. Derives URLs from the asset URLs the typed model already carries.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
@classmethod
def from_cmrawplume(
    cls,
    raw: CMRawPlume,
    *,
    token: str,
    products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
    overview_level: int | None = None,
    http_timeout: float = 30.0,
) -> CMPlumeImage:
    """Build from an already-fetched typed plume.

    Useful when the caller is iterating over a list returned by
    ``api_queries.list_plumes(...)`` and wants the image bundle
    per plume without re-fetching the catalog dict. Derives URLs
    from the asset URLs the typed model already carries.
    """
    if not raw.plume_tif:
        raise ValueError(
            f"CMRawPlume {raw.plume_id!r} has no plume_tif URL — "
            f"can't derive asset URLs."
        )
    seed = {
        "plume_tif": raw.plume_tif,
        "con_tif": raw.con_tif,
        "plume_id": raw.plume_id,
        "gas": raw.gas,
        "cmf_type": raw.emission_cmf_type,
        "emission_version": raw.emission_version,
    }
    return cls(
        plume_id=raw.plume_id,
        urls=_derive_asset_urls(seed, products),
        token=token,
        overview_level=overview_level,
        http_timeout=http_timeout,
        products=tuple(products),
        spec=_spec_or_none(seed),
    )

from_plume_id(plume_id, *, token, products=DEFAULT_PLUME_PRODUCTS, overview_level=None, http_timeout=30.0) classmethod

Build by fetching /catalog/plume/{id} then deriving asset URLs.

One round-trip. Works for any collection version (v3a onwards, including versions cut after this docstring was written) — the version is resolved from the record itself via :class:CMCollectionSpec, never guessed.

Parameters:

Name Type Description Default
plume_id str

Colloquial plume id.

required
token str

Bearer token.

required
products Sequence[CMProduct]

Explicit product selection (see :mod:~geoproducts.carbonmapper.products).

DEFAULT_PLUME_PRODUCTS
overview_level int | None

See the class attribute.

None
http_timeout float

See the class attribute.

30.0

Raises:

Type Description
HTTPError

On REST failure (404 etc.; 429 is retried first).

ValueError

If the response lacks the plume_tif URL the derivation needs.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
@classmethod
def from_plume_id(
    cls,
    plume_id: str,
    *,
    token: str,
    products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
    overview_level: int | None = None,
    http_timeout: float = 30.0,
) -> CMPlumeImage:
    """Build by fetching ``/catalog/plume/{id}`` then deriving asset URLs.

    One round-trip. Works for any collection version (v3a onwards,
    including versions cut after this docstring was written) — the
    version is resolved from the record itself via
    :class:`CMCollectionSpec`, never guessed.

    Args:
        plume_id: Colloquial plume id.
        token: Bearer token.
        products: Explicit product selection (see
            :mod:`~geoproducts.carbonmapper.products`).
        overview_level: See the class attribute.
        http_timeout: See the class attribute.

    Raises:
        requests.HTTPError: On REST failure (404 etc.; 429 is
            retried first).
        ValueError: If the response lacks the ``plume_tif`` URL the
            derivation needs.
    """
    from geoproducts.carbonmapper import download as _dl

    record = _dl.get_plume_by_id(plume_id, token=token)
    # The endpoint accepts a UUID too; the colloquial id (which the
    # tile bridge needs to derive the scene name) is on the record.
    return cls(
        plume_id=str(record.get("plume_id") or plume_id),
        urls=_derive_asset_urls(record, products),
        token=token,
        overview_level=overview_level,
        http_timeout=http_timeout,
        products=tuple(products),
        spec=_spec_or_none(record),
    )

from_stac_item(item, *, ime_item=None, products=DEFAULT_PLUME_PRODUCTS, token=None, overview_level=None, http_timeout=30.0) classmethod

Build from STAC items (vis + optional ime sibling).

Use when the caller is driving STAC search directly. STAC registers every version through v3e (re-checked 2026-09), but :meth:from_plume_id needs no search and works for any version. Pass both the vis and ime items if you have them (recommended); the ime sibling provides the ime-* product URLs. Asset keys are accepted with or without their file extension.

Raises:

Type Description
ValueError

If ime_item's id is absent or differs from item's (the two must describe the same plume).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
@classmethod
def from_stac_item(
    cls,
    item: Mapping[str, Any],
    *,
    ime_item: Mapping[str, Any] | None = None,
    products: Sequence[CMProduct] = DEFAULT_PLUME_PRODUCTS,
    token: str | None = None,
    overview_level: int | None = None,
    http_timeout: float = 30.0,
) -> CMPlumeImage:
    """Build from STAC items (vis + optional ime sibling).

    Use when the caller is driving STAC search directly. STAC
    registers every version through v3e (re-checked 2026-09), but
    :meth:`from_plume_id` needs no search and works for any version.
    Pass both the vis and ime items if you have them (recommended);
    the ime sibling provides the ``ime-*`` product URLs. Asset keys
    are accepted with or without their file extension.

    Raises:
        ValueError: If ``ime_item``'s ``id`` is absent or differs from
            ``item``'s (the two must describe the same plume).
    """
    plume_id = str(item.get("id", ""))
    if ime_item is not None and str(ime_item.get("id", "")) != plume_id:
        raise ValueError(
            f"ime_item id {ime_item.get('id')!r} does not match the vis "
            f"item id {plume_id!r}"
        )
    urls: dict[str, str] = {}
    for product in products:
        source = item if product.family == CMProductFamily.L3A_VIS else ime_item
        if source is None:
            continue
        # STAC items key assets with the extension (`plume.tif`);
        # accept the extension-less form too.
        assets = source.get("assets") or {}
        asset = assets.get(product.key) or assets.get(product.band) or {}
        href = asset.get("href") if isinstance(asset, Mapping) else None
        if href:
            urls[product.key] = href
    spec: CMCollectionSpec | None = None
    collection = item.get("collection")
    if collection:
        try:
            spec = CMCollectionSpec.from_collection_id(str(collection))
        except ValueError:
            spec = None
    return cls(
        plume_id=plume_id,
        urls=urls,
        token=token,
        overview_level=overview_level,
        http_timeout=http_timeout,
        products=tuple(products),
        spec=spec,
    )

load_alpha_mask()

Load just band 4 of :attr:mask as a boolean (H, W) GeoArray.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
def load_alpha_mask(self) -> GeoArray | None:
    """Load just band 4 of :attr:`mask` as a boolean ``(H, W)`` GeoArray."""
    reader = self.mask
    if reader is None:
        return None
    geo = reader.load()
    arr = np.asarray(geo)
    if arr.ndim != 3 or arr.shape[0] < 4:
        return None
    return GeoArray(
        arr[3] > 0, geo.transform, geo.crs, fill_value=False, dims=("y", "x")
    )

product(product)

Open one selected product (cached per product key).

Returns the product-kind-specific object — a lazy geoarray.RasterSource for raster products, a shapely geometry for vector products, bytes for PNG quicklooks. Returns None when the product was selected but its URL was not available from the source (e.g. :meth:from_stac_item with a missing sibling item).

Raises:

Type Description
CMProductNotSelected

If product is not in :attr:products — select it at construction to use it.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
def product(self, product: CMProduct) -> Any:
    """Open one selected product (cached per product key).

    Returns the product-kind-specific object — a lazy
    `geoarray.RasterSource` for raster products, a shapely geometry
    for vector products, ``bytes`` for PNG quicklooks. Returns
    ``None`` when the product was selected but its URL was not
    available from the source (e.g. :meth:`from_stac_item` with a
    missing sibling item).

    Raises:
        CMProductNotSelected: If ``product`` is not in
            :attr:`products` — select it at construction to use it.
    """
    if product not in self.products:
        raise CMProductNotSelected(product, tuple(self.products))
    if product.key in self._product_cache:
        return self._product_cache[product.key]
    url = self.urls.get(product.key)
    value = None
    if url is not None:
        value = product.open(
            str(url),
            token=self.token,
            overview_level=self.overview_level,
            http_timeout=self.http_timeout,
        )
    self._product_cache[product.key] = value
    return value

tile_cmf(*, pad_px=64)

L2B CH4 retrieval cropped to :attr:outline, full L2B resolution.

This is the headline workflow: the analysis-grade cmf raster, tightly cropped to the plume polygon, at the L2B's native pixel grid — not the pre-cropped L3A thumbnail (plume-concentrations.tif is typically ~41×48 px, ime-cmf-concentrations.tif only ~11×11 px).

Parameters:

Name Type Description Default
pad_px int

Pixels of context to add on every side around the outline bounding rectangle. Default 64 shows the plume embedded in its surroundings — set to 0 for a tight crop, larger for more context.

64

Returns:

Type Description
GeoArray

geoarray.GeoArray — eagerly loaded, ready to plot.

Raises:

Type Description
ValueError

If :attr:outline is None (canonical fetch failed AND band-4 vectorize fallback failed — rare).

(ValueError, RuntimeError)

If :attr:tile couldn't be resolved (see :attr:tile).

crop = img.tile_cmf(pad_px=64) # doctest: +SKIP crop.shape # doctest: +SKIP (1, 168, 152)

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
def tile_cmf(self, *, pad_px: int = 64) -> GeoArray:
    """L2B CH4 retrieval cropped to :attr:`outline`, full L2B resolution.

    This is the headline workflow: the analysis-grade
    ``cmf`` raster, tightly cropped to the plume polygon, at the
    L2B's native pixel grid — **not** the pre-cropped L3A
    thumbnail (``plume-concentrations.tif`` is typically
    ~41×48 px, ``ime-cmf-concentrations.tif`` only ~11×11 px).

    Args:
        pad_px: Pixels of context to add on every side around the
            outline bounding rectangle. Default ``64`` shows the
            plume embedded in its surroundings — set to ``0`` for
            a tight crop, larger for more context.

    Returns:
        `geoarray.GeoArray` — eagerly loaded, ready to plot.

    Raises:
        ValueError: If :attr:`outline` is ``None`` (canonical fetch
            failed AND band-4 vectorize fallback failed — rare).
        ValueError, RuntimeError: If :attr:`tile` couldn't be
            resolved (see :attr:`tile`).

    >>> crop = img.tile_cmf(pad_px=64)  # doctest: +SKIP
    >>> crop.shape  # doctest: +SKIP
    (1, 168, 152)
    """
    return self._crop_tile_band("cmf", pad_px=pad_px)

tile_rgb(*, pad_px=64)

L2B true-colour RGB sibling cropped to :attr:outline.

See :meth:tile_cmf for the cropping semantics. Returns the 3-band RGB raster at L2B native resolution — the "proper image" backdrop for a plume polygon overlay.

Raises:

Type Description
KeyError

If the tile has no RGB sibling URL (rare — with_rgb=True is the default on the tile resolver).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
def tile_rgb(self, *, pad_px: int = 64) -> GeoArray:
    """L2B true-colour RGB sibling cropped to :attr:`outline`.

    See :meth:`tile_cmf` for the cropping semantics. Returns the
    3-band RGB raster at L2B native resolution — the "proper image"
    backdrop for a plume polygon overlay.

    Raises:
        KeyError: If the tile has no RGB sibling URL (rare —
            ``with_rgb=True`` is the default on the tile resolver).
    """
    return self._crop_tile_band("rgb", pad_px=pad_px)

tile_uncertainty(*, pad_px=64)

L2B per-pixel uncertainty cropped to :attr:outline.

Companion to :meth:tile_cmf — the uncertainty raster shares the cmf's pixel grid. See :meth:tile_cmf for the cropping semantics.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/image.py
def tile_uncertainty(self, *, pad_px: int = 64) -> GeoArray:
    """L2B per-pixel uncertainty cropped to :attr:`outline`.

    Companion to :meth:`tile_cmf` — the uncertainty raster shares
    the cmf's pixel grid. See :meth:`tile_cmf` for the cropping
    semantics.
    """
    return self._crop_tile_band("uncertainty", pad_px=pad_px)

geoproducts.carbonmapper.rasters

Carbon Mapper L2B scene raster wrapper.

:class:CMImageRaster exposes every loadable L2B scene asset (cmf / cmf-unortho / uncertainty / uncertainty-unortho / artifact-mask / rgb / uas) as lazy geoarray.RasterSource properties whose reads return a geoarray.GeoArray (or plain text for the uas.txt sidecar). georeader's RasterioReader and georeader.read do the I/O and the window maths internally; no georeader object leaves this module.

Per-plume L3A products (mask, concentrations, IME-clipped concentrations, RGB, outline) live in :mod:~geoproducts.carbonmapper.image — :class:~geoproducts.carbonmapper.image.CMPlumeImage is the counterpart to this class for plume-level data.

Intentionally NOT wrapped:

  • PNG assets (rgb_png etc.) — un-georeferenced, not COGs.
  • Per-plume con_tif from the catalog REST surface — duplicates the column-density crop already provided by CMPlumeImage.

Pure raster wrappers: no persistence, no uploads.

CMImageRaster dataclass

L2B scene exposed as lazy geoarray.RasterSource rasters.

Lazy: instantiating the dataclass does NOT issue HTTP / blob reads; access .cmf / .rgb / etc. or call :meth:read_window / :meth:read_polygon to trigger I/O.

Attributes:

Name Type Description
scene_id str

CM L2B item id (e.g. "tan20251212t185057c20s4001").

asset_paths Mapping[str, PathLike]

Mapping of band name → URL (https://) or local / blob path. Optional bands (artifact-mask, rgb, the *-unortho variants) may be missing from the mapping or from the server — either way the accessor returns None.

overview_level int | None

None for full resolution; integer for COG overviews (faster previews).

token str | None

Bearer token for asset-proxy URLs. Applied per read (scoped GDAL env), never exported process-wide. None falls back to whatever GDAL_HTTP_HEADERS the caller set.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
@dataclass(repr=False)
class CMImageRaster:
    """L2B scene exposed as lazy `geoarray.RasterSource` rasters.

    Lazy: instantiating the dataclass does NOT issue HTTP / blob reads;
    access ``.cmf`` / ``.rgb`` / etc. or call :meth:`read_window` /
    :meth:`read_polygon` to trigger I/O.

    Attributes:
        scene_id: CM L2B item id (e.g. ``"tan20251212t185057c20s4001"``).
        asset_paths: Mapping of band name → URL (``https://``) or
            local / blob path. Optional bands (``artifact-mask``,
            ``rgb``, the ``*-unortho`` variants) may be missing from the
            mapping **or** from the server — either way the accessor
            returns ``None``.
        overview_level: ``None`` for full resolution; integer for COG
            overviews (faster previews).
        token: Bearer token for asset-proxy URLs. Applied per read
            (scoped GDAL env), never exported process-wide. ``None``
            falls back to whatever ``GDAL_HTTP_HEADERS`` the caller set.
    """

    scene_id: str
    asset_paths: Mapping[str, PathLike]
    overview_level: int | None = None
    token: str | None = None

    # ---- Constructors --------------------------------------------------

    @classmethod
    def from_cm_tile_item(
        cls,
        item: CMTileItem,
        *,
        token: str | None = None,
    ) -> CMImageRaster:
        """Build from the lightweight STAC item.

        STAC asset keys carry file extensions (``cmf.tif``,
        ``uncertainty.tif``, ``artifact-mask.tif``, ``uas.txt``,
        ``*-unortho.tif`` variants). This method strips the
        appropriate extension and retains every key listed in
        :data:`CM_L2B_BANDS` plus ``uas`` (the text sidecar).
        """
        paths: dict[str, PathLike] = {}
        for key, url in item.asset_urls.items():
            if not url:
                continue
            stripped = key[:-4] if key.endswith((".tif", ".txt")) else key
            if stripped in _CM_L2B_KEYS_ALL:
                paths[stripped] = url
        return cls(scene_id=item.scene_id, asset_paths=paths, token=token)

    def with_rgb(self, rgb_item: CMTileItem) -> CMImageRaster:
        """Return a copy with ``rgb`` merged in from a sibling STAC item.

        The CH4 (``l2b-ch4-mfa-v3a``) and RGB (``l2b-rgb-v3a``) L2B
        collections share ``scene_id`` and pixel grid, but each STAC
        item only exposes its own assets. Fetch both with
        :func:`api_queries.get_tile` (passing ``collection=...``) and
        compose them via this method:

        >>> ir = CMImageRaster.from_cm_tile_item(ch4_item)
        >>> ir = ir.with_rgb(rgb_item)
        >>> ir.rgb is not None
        True

        Raises:
            ValueError: If ``rgb_item.scene_id`` doesn't match
                ``self.scene_id`` (mismatched scenes don't share a grid
                — usually a programming error).
        """
        if rgb_item.scene_id != self.scene_id:
            raise ValueError(
                f"scene_id mismatch: {self.scene_id!r} vs {rgb_item.scene_id!r}"
            )
        # Pick the rgb GeoTIFF (with or without `.tif` extension);
        # ignore everything else on the rgb item.
        new_paths = dict(self.asset_paths)
        for key, url in rgb_item.asset_urls.items():
            if not url:
                continue
            stripped = key[:-4] if key.endswith(".tif") else key
            if stripped == "rgb":
                new_paths["rgb"] = url
                break
        return CMImageRaster(
            scene_id=self.scene_id,
            asset_paths=new_paths,
            overview_level=self.overview_level,
            token=self.token,
        )

    @classmethod
    def from_scene_id(
        cls,
        scene_id: str,
        *,
        token: str,
        spec: CMCollectionSpec | None = None,
        collection: str | None = None,
        rgb_collection: str | None = None,
        products: Sequence[CMProduct] = DEFAULT_SCENE_PRODUCTS,
        l2b_collection_candidates: Sequence[str] | None = None,
        rgb_collection_candidates: Sequence[str] | None = None,
        with_rgb: bool = True,
        overview_level: int | None = None,
        http_timeout: float = 30.0,
    ) -> CMImageRaster:
        """Build by deriving L2B asset URLs from the scene_id (URL-pattern).

        Bypasses STAC entirely — derives every asset URL by templating
        against the verified asset-proxy pattern (see
        :func:`_l2b_asset_url`). Required for 2026 scenes (v3c/v3d)
        which are **not** in ``/stac/collections``.

        Collection resolution, in order of preference:

        1. ``collection`` / ``rgb_collection`` — explicit ids,
           probe-free (you pinned them, they're used verbatim).
        2. ``spec`` — a :class:`CMCollectionSpec` resolved from the
           plume record (``CMCollectionSpec.from_plume_record``). The
           spec's composed collection id is probed **first**. Usually
           one probe suffices (same-version pairing), but the L3A side
           can be re-versioned ahead of the L2B parent (observed: a v3d
           L3A plume whose L2B still serves at v3c), so
           :func:`l2b_collection_candidates_for_spec` backs it up with
           older versions (then newer ones) **of the same gas** — a CO2
           plume never resolves to a CH4 scene. Because the spec always
           contributes the record's own version, this path never goes
           stale when Carbon Mapper bumps versions.
        3. Candidate probing (legacy) — for scene-name-only lookups
           with no record available. Probes
           ``l2b_collection_candidates`` (default: the CH4 candidates)
           in order; first 200/206 wins.

        Parameters
        ----------
        scene_id:
            L2B scene name, equal to ``plume_id.rsplit("-", 1)[0]`` for
            any plume that came from this scene. Must follow the
            ``<inst><YYYYMMDD>t<HHMMSS>...`` convention so the date
            can be parsed. (The catalog record's ``scene_id`` field is
            a **UUID** and will not work here.)
        token:
            Bearer token. Required — the asset-proxy URLs return 401
            without it.
        spec:
            Collection spec (gas / cmf_type / version) to compose both
            collection ids from. Its own ids are probed first; explicit
            candidate lists (if given) follow, else the gas-matched
            spec-derived candidates.
        collection:
            Explicit L2B CH4-family collection id (e.g.
            ``"l2b-ch4-mfa-v3d"``). Used verbatim with no probing and
            takes precedence over ``spec`` for the CH4 side (``spec``
            then still orders the RGB candidates if ``rgb_collection``
            is not pinned).
        rgb_collection:
            Explicit RGB sibling collection id (e.g. ``"l2b-rgb-v3d"``).
            Used verbatim with no probing; takes precedence over
            ``spec`` for the RGB side.
        products:
            Which per-scene products to derive URLs for — descriptors
            from :mod:`~geoproducts.carbonmapper.products`
            (:data:`DEFAULT_SCENE_PRODUCTS` = the 5 rasters + ``uas``).
            The RGB sibling is controlled by ``with_rgb``, not this
            list (it lives in a different collection).
        l2b_collection_candidates:
            L2B collection IDs to probe, in order, when ``collection``
            is not given. ``None`` (default) means the spec-derived
            candidates when ``spec`` is given, else
            :data:`DEFAULT_L2B_CH4_COLLECTION_CANDIDATES`.
        rgb_collection_candidates:
            L2B RGB sibling collection IDs probed identically (on
            ``rgb.tif``). ``None`` (default) means the spec-derived
            candidates when ``spec`` is given, else
            :data:`DEFAULT_L2B_RGB_COLLECTION_CANDIDATES`.
        with_rgb:
            When ``True`` (default), attach the ``rgb`` sibling URL
            (probing the RGB candidates only when its collection isn't
            pinned by ``spec`` / ``rgb_collection``). When ``False``,
            ``self.rgb`` will be ``None``.
        overview_level:
            ``None`` for full resolution; integer for a COG overview.
        http_timeout:
            Per-probe range-GET timeout (seconds).

        Returns
        -------
        CMImageRaster
            With ``asset_paths`` populated for the selected products
            and, when ``with_rgb=True``, the ``rgb`` sibling URL.

        Raises
        ------
        CMSceneNotPublished
            When probing was needed and every candidate L2B collection
            404'd for ``scene_id`` — the scene either hasn't been
            processed yet or only exists in an unlisted collection
            variant. Catch in ETL paths that want to defer rather
            than error. (Not raised on the explicit ``collection``
            path, which builds URLs without probing — missing scenes
            surface as read errors on first access.)
        ValueError
            When ``scene_id`` doesn't carry an 8-digit date at
            positions ``[3:11]``, or a non-L2B product was requested.

        Examples
        --------
        >>> tile = CMImageRaster.from_scene_id(  # doctest: +SKIP
        ...     "tan20260623t124240c80s4001", token=tok,
        ...     spec=CMCollectionSpec(version="v3d"),
        ... )
        >>> tile.cmf  # doctest: +SKIP
        source_from_georeader(<RasterioReader …/l2b-ch4-mfa-v3d/2026/06/23/…>)
        """
        # The spec's composed ids probe FIRST (the record's own version
        # — usually the right one) with same-gas backups; an explicit
        # `collection` / `rgb_collection` is used verbatim.
        l2b_collection_candidates = _probe_order(
            spec,
            CMProductFamily.L2B,
            l2b_collection_candidates,
        )
        rgb_collection_candidates = _probe_order(
            spec,
            CMProductFamily.L2B_RGB,
            rgb_collection_candidates,
        )
        l2b_coll = collection
        rgb_coll = rgb_collection

        if l2b_coll is None:
            l2b_coll = _probe_l2b_collection(
                scene_id,
                l2b_collection_candidates,
                probe_asset="cmf.tif",
                token=token,
                http_timeout=http_timeout,
            )
            if l2b_coll is None:
                raise CMSceneNotPublished(scene_id)

        # Build one asset URL per selected product. Keys are the
        # extension-less band names — they must match the lazy-property
        # names exactly (`_open` strips nothing).
        asset_paths: dict[str, PathLike] = {}
        for product in products:
            if product.family is not CMProductFamily.L2B:
                raise ValueError(
                    f"Product {product.key!r} ({product.family.value}) "
                    "is not an L2B per-scene product. Use CMPlumeImage "
                    "for L3A per-plume products. The whole-scene RGB "
                    "sibling lives in a separate collection and is not "
                    "selected via products= — pass with_rgb=True (the "
                    "default) to attach it."
                )
            asset_paths[product.band] = _l2b_asset_url(
                l2b_coll,
                scene_id,
                product.key,
            )

        if with_rgb:
            if rgb_coll is None:
                rgb_coll = _probe_l2b_collection(
                    scene_id,
                    rgb_collection_candidates,
                    probe_asset="rgb.tif",
                    token=token,
                    http_timeout=http_timeout,
                )
            if rgb_coll is not None:
                asset_paths["rgb"] = _l2b_asset_url(rgb_coll, scene_id, "rgb.tif")

        return cls(
            scene_id=scene_id,
            asset_paths=asset_paths,
            overview_level=overview_level,
            token=token,
        )

    @classmethod
    def from_local(cls, scene_dir: PathLike) -> CMImageRaster:
        """Build from a downloaded scene directory.

        Picks up every L2B asset present (``cmf.tif`` / ``rgb.tif`` /
        ``uncertainty.tif`` / ``artifact-mask.tif`` and the
        un-orthorectified variants), plus the ``uas.txt`` sidecar.
        Missing files become absent keys in ``asset_paths``.
        """
        d = Path(scene_dir)
        paths: dict[str, PathLike] = {}
        for band in CM_L2B_BANDS:
            p = d / f"{band}.tif"
            if p.exists():
                paths[band] = str(p)
        uas_path = d / "uas.txt"
        if uas_path.exists():
            paths["uas"] = str(uas_path)
        return cls(scene_id=d.name, asset_paths=paths)

    # ---- Lazy band readers --------------------------------------------

    @cached_property
    def cmf(self) -> RasterSource:
        """CH4 matched-filter retrieval, orthorectified (ppm·m).
        Always present on L2B-CH4 items."""
        return self._open("cmf")

    @cached_property
    def cmf_unortho(self) -> RasterSource | None:
        """CH4 retrieval in raw sensor frame (pre-orthorectification).
        ``None`` for older collection variants (e.g. ``mfm-v1``) that
        don't ship the unortho sibling."""
        return self._open_optional("cmf-unortho")

    @cached_property
    def rgb(self) -> RasterSource | None:
        """3-band uint8 RGB. ``None`` for L2B-CH4 collections (RGB lives
        in a separate STAC collection — fetch and pass via
        ``asset_paths`` or compose via :meth:`with_rgb`)."""
        return self._open_optional("rgb")

    @cached_property
    def uncertainty(self) -> RasterSource:
        """Companion uncertainty raster aligned with ``cmf``."""
        return self._open("uncertainty")

    @cached_property
    def uncertainty_unortho(self) -> RasterSource | None:
        """Per-pixel uncertainty in raw sensor frame. ``None`` for
        older collection variants without the unortho sibling."""
        return self._open_optional("uncertainty-unortho")

    @cached_property
    def artifact_mask(self) -> RasterSource | None:
        """Artefact mask (covers ~25% of scene). Flags un-orthorectified
        strip pixels and geometric anomalies — **not** a cloud mask.
        ``None`` if absent — which is common: Carbon Mapper publishes it
        per scene, and no v3e scene checked in 2026-09 carried one."""
        return self._open_optional("artifact-mask")

    @cached_property
    def uas(self) -> str | None:
        """UAS sensor-metadata sidecar — raw text from ``uas.txt``.

        Lazy-fetched on first access (one HTTP GET if the path is a
        URL, or a file read for local paths) and cached as a string.
        Callers parse the structure as needed; we don't impose a
        schema. Returns ``None`` if no ``uas`` URL/path was supplied.

        Auth: :attr:`token` when set; otherwise the ``Authorization``
        line of a process-wide ``GDAL_HTTP_HEADERS`` (which may hold
        several CRLF- or newline-separated headers), so the legacy
        env-var setup keeps working for text and raster assets alike.
        """
        path = self.asset_paths.get("uas")
        if path is None:
            return None
        sp = str(path)
        if sp.startswith(("http://", "https://")):
            headers: dict[str, str] = {}
            if self.token:
                headers = bearer_headers_for(sp, self.token)
            else:
                for line in os.environ.get("GDAL_HTTP_HEADERS", "").splitlines():
                    name, _, value = line.partition(":")
                    if name.strip().lower() == "authorization" and value.strip():
                        headers["Authorization"] = value.strip()
                        break
            r = _request("GET", sp, headers=headers, timeout=30)
            r.raise_for_status()
            return r.text
        with open(sp) as fh:
            return fh.read()

    # ---- Geometric metadata (pulled from cmf as the canonical band) ---

    @property
    def grid(self) -> Grid:
        """The ``cmf`` pixel grid (transform, CRS, ``(H, W)``)."""
        return self.cmf.grid

    @property
    def crs(self) -> str:
        """The ``cmf`` CRS as a string (``"EPSG:…"`` when it has a code)."""
        crs = self.grid.crs
        return "" if crs is None else crs.to_string()

    @property
    def transform(self) -> Affine:
        """The ``cmf`` affine transform."""
        return self.grid.affine

    @property
    def bounds(self) -> BBox:
        """``(minx, miny, maxx, maxy)`` of the ``cmf`` grid, in :attr:`crs`."""
        return self.grid.bounds

    @property
    def shape(self) -> tuple[int, int]:
        """``(H, W)`` of the ``cmf`` grid."""
        return self.grid.shape

    # ---- Read helpers (georeader.read is the engine) -------------------

    def read_polygon(
        self,
        polygon: BaseGeometry,
        *,
        crs_polygon: str = "EPSG:4326",
        bands: Iterable[str] = CM_L2B_BANDS,
    ) -> dict[str, RasterSource | None]:
        """Read a polygon clip from the requested bands.

        Args:
            polygon: Clip geometry.
            crs_polygon: CRS of ``polygon``. Defaults to ``"EPSG:4326"``.
            bands: Subset of band names. Bands whose asset is missing
                (absent from :attr:`asset_paths`, or an optional band
                the server doesn't have) or whose window has zero
                overlap return ``None``.

        Returns:
            ``{"cmf": <RasterSource>, "rgb": <RasterSource>, ...}`` — lazy
            windowed sources (`geoarray.RasterSource`); ``.load()``
            materialises one as a `geoarray.GeoArray`.
        """
        from geoarray.interop.georeader import (
            source_from_georeader,
            source_to_georeader,
        )
        from georeader import read

        out: dict[str, RasterSource | None] = {}
        for band in bands:
            if self.asset_paths.get(band) is None:
                out[band] = None
                continue
            # `uas` is a text sidecar, not a raster — skip the band
            # reader path. Callers reading text sidecars use the
            # `.uas` property directly.
            if band == "uas":
                continue
            reader = self._reader(band)
            if reader is None:
                out[band] = None
                continue
            # `boundless=False` makes `read_from_polygon` return `None`
            # for windows that don't intersect the raster (e.g. an
            # artifact-mask whose un-orthorectified strip falls outside
            # the requested AOI), instead of allocating a fill-valued
            # tensor the size of the requested window. Real CRS / I/O
            # errors are left to propagate — the prior bare
            # `except Exception` swallowed those silently.
            #
            # With ``return_only_data=False`` the result is a windowed
            # (lazy) georeader reader, wrapped back as a RasterSource.
            result = read.read_from_polygon(
                source_to_georeader(reader),
                polygon=polygon,
                crs_polygon=crs_polygon,
                boundless=False,
            )
            out[band] = source_from_georeader(result) if result is not None else None
        return out

    def read_window(
        self,
        bounds_4326: BBox,
        *,
        bands: Iterable[str] = CM_L2B_BANDS,
    ) -> dict[str, RasterSource | None]:
        """Read a WGS-84 bbox window from the requested bands (lazy).

        Raises:
            ValueError: If ``bounds_4326`` is malformed or crosses the
                antimeridian (``W > E``) — split such windows in two.
        """
        validate_lonlat_bbox(bounds_4326)
        return self.read_polygon(box(*bounds_4326), bands=bands)

    def read_window_to_crs(
        self,
        bounds_4326: BBox,
        crs_dst: str,
        *,
        bands: Iterable[str] = CM_L2B_BANDS,
    ) -> dict[str, GeoArray | None]:
        """Read a window then reproject each band to ``crs_dst``.

        Reprojection materialises the data — values are
        `geoarray.GeoArray`, not lazy sources.
        """
        from geoarray.interop.georeader import from_georeader, source_to_georeader
        from georeader import read

        crops = self.read_window(bounds_4326, bands=bands)
        return {
            band: (
                from_georeader(read.read_to_crs(source_to_georeader(geo), crs_dst))
                if geo is not None
                else None
            )
            for band, geo in crops.items()
        }

    # ---- Internals -----------------------------------------------------

    def _open(self, band: str) -> RasterSource:
        path = self.asset_paths.get(band)
        if path is None:
            raise KeyError(f"Asset {band!r} not present on {self.scene_id}")
        return _open_raster(path, token=self.token, overview_level=self.overview_level)

    def _open_optional(self, band: str) -> RasterSource | None:
        """Open an optional band; ``None`` when it has no path **or** the
        server says it doesn't exist (403/404). Auth, throttling and
        server errors still raise."""
        if self.asset_paths.get(band) is None:
            return None
        try:
            return self._open(band)
        except RasterioIOError as exc:
            if not _is_absent_asset_error(exc):
                raise
            _log.info("Optional L2B asset %r absent for %s", band, self.scene_id)
            return None

    def _reader(self, band: str) -> RasterSource | None:
        """Reader for ``band`` through its cached accessor (so optional
        bands resolve to ``None`` and each band is opened once); bands
        without an accessor are opened directly."""
        attr = band.replace("-", "_")
        if attr in type(self).__dict__:
            return getattr(self, attr)
        return self._open(band)

    # ---- Repr ---------------------------------------------------------

    def __repr__(self) -> str:
        present = [b for b in CM_L2B_BANDS if b in self.asset_paths]
        missing = [b for b in CM_L2B_BANDS if b not in self.asset_paths]
        extra = sorted(set(self.asset_paths) - set(CM_L2B_BANDS))
        ov = self.overview_level if self.overview_level is not None else "full"
        lines = [
            "CMImageRaster",
            f"  scene_id:       {self.scene_id}",
            f"  bands present:  {present or '<none>'}",
        ]
        if missing:
            lines.append(f"  bands missing:  {missing}")
        if extra:
            lines.append(f"  extra keys:     {extra}")
        lines.append(f"  overview_level: {ov}")
        return "\n".join(lines)

    __str__ = __repr__

artifact_mask cached property

Artefact mask (covers ~25% of scene). Flags un-orthorectified strip pixels and geometric anomalies — not a cloud mask. None if absent — which is common: Carbon Mapper publishes it per scene, and no v3e scene checked in 2026-09 carried one.

bounds property

(minx, miny, maxx, maxy) of the cmf grid, in :attr:crs.

cmf cached property

CH4 matched-filter retrieval, orthorectified (ppm·m). Always present on L2B-CH4 items.

cmf_unortho cached property

CH4 retrieval in raw sensor frame (pre-orthorectification). None for older collection variants (e.g. mfm-v1) that don't ship the unortho sibling.

crs property

The cmf CRS as a string ("EPSG:…" when it has a code).

grid property

The cmf pixel grid (transform, CRS, (H, W)).

rgb cached property

3-band uint8 RGB. None for L2B-CH4 collections (RGB lives in a separate STAC collection — fetch and pass via asset_paths or compose via :meth:with_rgb).

shape property

(H, W) of the cmf grid.

transform property

The cmf affine transform.

uas cached property

UAS sensor-metadata sidecar — raw text from uas.txt.

Lazy-fetched on first access (one HTTP GET if the path is a URL, or a file read for local paths) and cached as a string. Callers parse the structure as needed; we don't impose a schema. Returns None if no uas URL/path was supplied.

Auth: :attr:token when set; otherwise the Authorization line of a process-wide GDAL_HTTP_HEADERS (which may hold several CRLF- or newline-separated headers), so the legacy env-var setup keeps working for text and raster assets alike.

uncertainty cached property

Companion uncertainty raster aligned with cmf.

uncertainty_unortho cached property

Per-pixel uncertainty in raw sensor frame. None for older collection variants without the unortho sibling.

from_cm_tile_item(item, *, token=None) classmethod

Build from the lightweight STAC item.

STAC asset keys carry file extensions (cmf.tif, uncertainty.tif, artifact-mask.tif, uas.txt, *-unortho.tif variants). This method strips the appropriate extension and retains every key listed in :data:CM_L2B_BANDS plus uas (the text sidecar).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
@classmethod
def from_cm_tile_item(
    cls,
    item: CMTileItem,
    *,
    token: str | None = None,
) -> CMImageRaster:
    """Build from the lightweight STAC item.

    STAC asset keys carry file extensions (``cmf.tif``,
    ``uncertainty.tif``, ``artifact-mask.tif``, ``uas.txt``,
    ``*-unortho.tif`` variants). This method strips the
    appropriate extension and retains every key listed in
    :data:`CM_L2B_BANDS` plus ``uas`` (the text sidecar).
    """
    paths: dict[str, PathLike] = {}
    for key, url in item.asset_urls.items():
        if not url:
            continue
        stripped = key[:-4] if key.endswith((".tif", ".txt")) else key
        if stripped in _CM_L2B_KEYS_ALL:
            paths[stripped] = url
    return cls(scene_id=item.scene_id, asset_paths=paths, token=token)

from_local(scene_dir) classmethod

Build from a downloaded scene directory.

Picks up every L2B asset present (cmf.tif / rgb.tif / uncertainty.tif / artifact-mask.tif and the un-orthorectified variants), plus the uas.txt sidecar. Missing files become absent keys in asset_paths.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
@classmethod
def from_local(cls, scene_dir: PathLike) -> CMImageRaster:
    """Build from a downloaded scene directory.

    Picks up every L2B asset present (``cmf.tif`` / ``rgb.tif`` /
    ``uncertainty.tif`` / ``artifact-mask.tif`` and the
    un-orthorectified variants), plus the ``uas.txt`` sidecar.
    Missing files become absent keys in ``asset_paths``.
    """
    d = Path(scene_dir)
    paths: dict[str, PathLike] = {}
    for band in CM_L2B_BANDS:
        p = d / f"{band}.tif"
        if p.exists():
            paths[band] = str(p)
    uas_path = d / "uas.txt"
    if uas_path.exists():
        paths["uas"] = str(uas_path)
    return cls(scene_id=d.name, asset_paths=paths)

from_scene_id(scene_id, *, token, spec=None, collection=None, rgb_collection=None, products=DEFAULT_SCENE_PRODUCTS, l2b_collection_candidates=None, rgb_collection_candidates=None, with_rgb=True, overview_level=None, http_timeout=30.0) classmethod

Build by deriving L2B asset URLs from the scene_id (URL-pattern).

Bypasses STAC entirely — derives every asset URL by templating against the verified asset-proxy pattern (see :func:_l2b_asset_url). Required for 2026 scenes (v3c/v3d) which are not in /stac/collections.

Collection resolution, in order of preference:

  1. collection / rgb_collection — explicit ids, probe-free (you pinned them, they're used verbatim).
  2. spec — a :class:CMCollectionSpec resolved from the plume record (CMCollectionSpec.from_plume_record). The spec's composed collection id is probed first. Usually one probe suffices (same-version pairing), but the L3A side can be re-versioned ahead of the L2B parent (observed: a v3d L3A plume whose L2B still serves at v3c), so :func:l2b_collection_candidates_for_spec backs it up with older versions (then newer ones) of the same gas — a CO2 plume never resolves to a CH4 scene. Because the spec always contributes the record's own version, this path never goes stale when Carbon Mapper bumps versions.
  3. Candidate probing (legacy) — for scene-name-only lookups with no record available. Probes l2b_collection_candidates (default: the CH4 candidates) in order; first 200/206 wins.
Parameters

scene_id: L2B scene name, equal to plume_id.rsplit("-", 1)[0] for any plume that came from this scene. Must follow the <inst><YYYYMMDD>t<HHMMSS>... convention so the date can be parsed. (The catalog record's scene_id field is a UUID and will not work here.) token: Bearer token. Required — the asset-proxy URLs return 401 without it. spec: Collection spec (gas / cmf_type / version) to compose both collection ids from. Its own ids are probed first; explicit candidate lists (if given) follow, else the gas-matched spec-derived candidates. collection: Explicit L2B CH4-family collection id (e.g. "l2b-ch4-mfa-v3d"). Used verbatim with no probing and takes precedence over spec for the CH4 side (spec then still orders the RGB candidates if rgb_collection is not pinned). rgb_collection: Explicit RGB sibling collection id (e.g. "l2b-rgb-v3d"). Used verbatim with no probing; takes precedence over spec for the RGB side. products: Which per-scene products to derive URLs for — descriptors from :mod:~geoproducts.carbonmapper.products (:data:DEFAULT_SCENE_PRODUCTS = the 5 rasters + uas). The RGB sibling is controlled by with_rgb, not this list (it lives in a different collection). l2b_collection_candidates: L2B collection IDs to probe, in order, when collection is not given. None (default) means the spec-derived candidates when spec is given, else :data:DEFAULT_L2B_CH4_COLLECTION_CANDIDATES. rgb_collection_candidates: L2B RGB sibling collection IDs probed identically (on rgb.tif). None (default) means the spec-derived candidates when spec is given, else :data:DEFAULT_L2B_RGB_COLLECTION_CANDIDATES. with_rgb: When True (default), attach the rgb sibling URL (probing the RGB candidates only when its collection isn't pinned by spec / rgb_collection). When False, self.rgb will be None. overview_level: None for full resolution; integer for a COG overview. http_timeout: Per-probe range-GET timeout (seconds).

Returns

CMImageRaster With asset_paths populated for the selected products and, when with_rgb=True, the rgb sibling URL.

Raises

CMSceneNotPublished When probing was needed and every candidate L2B collection 404'd for scene_id — the scene either hasn't been processed yet or only exists in an unlisted collection variant. Catch in ETL paths that want to defer rather than error. (Not raised on the explicit collection path, which builds URLs without probing — missing scenes surface as read errors on first access.) ValueError When scene_id doesn't carry an 8-digit date at positions [3:11], or a non-L2B product was requested.

Examples

tile = CMImageRaster.from_scene_id( # doctest: +SKIP ... "tan20260623t124240c80s4001", token=tok, ... spec=CMCollectionSpec(version="v3d"), ... ) tile.cmf # doctest: +SKIP source_from_georeader()

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
@classmethod
def from_scene_id(
    cls,
    scene_id: str,
    *,
    token: str,
    spec: CMCollectionSpec | None = None,
    collection: str | None = None,
    rgb_collection: str | None = None,
    products: Sequence[CMProduct] = DEFAULT_SCENE_PRODUCTS,
    l2b_collection_candidates: Sequence[str] | None = None,
    rgb_collection_candidates: Sequence[str] | None = None,
    with_rgb: bool = True,
    overview_level: int | None = None,
    http_timeout: float = 30.0,
) -> CMImageRaster:
    """Build by deriving L2B asset URLs from the scene_id (URL-pattern).

    Bypasses STAC entirely — derives every asset URL by templating
    against the verified asset-proxy pattern (see
    :func:`_l2b_asset_url`). Required for 2026 scenes (v3c/v3d)
    which are **not** in ``/stac/collections``.

    Collection resolution, in order of preference:

    1. ``collection`` / ``rgb_collection`` — explicit ids,
       probe-free (you pinned them, they're used verbatim).
    2. ``spec`` — a :class:`CMCollectionSpec` resolved from the
       plume record (``CMCollectionSpec.from_plume_record``). The
       spec's composed collection id is probed **first**. Usually
       one probe suffices (same-version pairing), but the L3A side
       can be re-versioned ahead of the L2B parent (observed: a v3d
       L3A plume whose L2B still serves at v3c), so
       :func:`l2b_collection_candidates_for_spec` backs it up with
       older versions (then newer ones) **of the same gas** — a CO2
       plume never resolves to a CH4 scene. Because the spec always
       contributes the record's own version, this path never goes
       stale when Carbon Mapper bumps versions.
    3. Candidate probing (legacy) — for scene-name-only lookups
       with no record available. Probes
       ``l2b_collection_candidates`` (default: the CH4 candidates)
       in order; first 200/206 wins.

    Parameters
    ----------
    scene_id:
        L2B scene name, equal to ``plume_id.rsplit("-", 1)[0]`` for
        any plume that came from this scene. Must follow the
        ``<inst><YYYYMMDD>t<HHMMSS>...`` convention so the date
        can be parsed. (The catalog record's ``scene_id`` field is
        a **UUID** and will not work here.)
    token:
        Bearer token. Required — the asset-proxy URLs return 401
        without it.
    spec:
        Collection spec (gas / cmf_type / version) to compose both
        collection ids from. Its own ids are probed first; explicit
        candidate lists (if given) follow, else the gas-matched
        spec-derived candidates.
    collection:
        Explicit L2B CH4-family collection id (e.g.
        ``"l2b-ch4-mfa-v3d"``). Used verbatim with no probing and
        takes precedence over ``spec`` for the CH4 side (``spec``
        then still orders the RGB candidates if ``rgb_collection``
        is not pinned).
    rgb_collection:
        Explicit RGB sibling collection id (e.g. ``"l2b-rgb-v3d"``).
        Used verbatim with no probing; takes precedence over
        ``spec`` for the RGB side.
    products:
        Which per-scene products to derive URLs for — descriptors
        from :mod:`~geoproducts.carbonmapper.products`
        (:data:`DEFAULT_SCENE_PRODUCTS` = the 5 rasters + ``uas``).
        The RGB sibling is controlled by ``with_rgb``, not this
        list (it lives in a different collection).
    l2b_collection_candidates:
        L2B collection IDs to probe, in order, when ``collection``
        is not given. ``None`` (default) means the spec-derived
        candidates when ``spec`` is given, else
        :data:`DEFAULT_L2B_CH4_COLLECTION_CANDIDATES`.
    rgb_collection_candidates:
        L2B RGB sibling collection IDs probed identically (on
        ``rgb.tif``). ``None`` (default) means the spec-derived
        candidates when ``spec`` is given, else
        :data:`DEFAULT_L2B_RGB_COLLECTION_CANDIDATES`.
    with_rgb:
        When ``True`` (default), attach the ``rgb`` sibling URL
        (probing the RGB candidates only when its collection isn't
        pinned by ``spec`` / ``rgb_collection``). When ``False``,
        ``self.rgb`` will be ``None``.
    overview_level:
        ``None`` for full resolution; integer for a COG overview.
    http_timeout:
        Per-probe range-GET timeout (seconds).

    Returns
    -------
    CMImageRaster
        With ``asset_paths`` populated for the selected products
        and, when ``with_rgb=True``, the ``rgb`` sibling URL.

    Raises
    ------
    CMSceneNotPublished
        When probing was needed and every candidate L2B collection
        404'd for ``scene_id`` — the scene either hasn't been
        processed yet or only exists in an unlisted collection
        variant. Catch in ETL paths that want to defer rather
        than error. (Not raised on the explicit ``collection``
        path, which builds URLs without probing — missing scenes
        surface as read errors on first access.)
    ValueError
        When ``scene_id`` doesn't carry an 8-digit date at
        positions ``[3:11]``, or a non-L2B product was requested.

    Examples
    --------
    >>> tile = CMImageRaster.from_scene_id(  # doctest: +SKIP
    ...     "tan20260623t124240c80s4001", token=tok,
    ...     spec=CMCollectionSpec(version="v3d"),
    ... )
    >>> tile.cmf  # doctest: +SKIP
    source_from_georeader(<RasterioReader …/l2b-ch4-mfa-v3d/2026/06/23/…>)
    """
    # The spec's composed ids probe FIRST (the record's own version
    # — usually the right one) with same-gas backups; an explicit
    # `collection` / `rgb_collection` is used verbatim.
    l2b_collection_candidates = _probe_order(
        spec,
        CMProductFamily.L2B,
        l2b_collection_candidates,
    )
    rgb_collection_candidates = _probe_order(
        spec,
        CMProductFamily.L2B_RGB,
        rgb_collection_candidates,
    )
    l2b_coll = collection
    rgb_coll = rgb_collection

    if l2b_coll is None:
        l2b_coll = _probe_l2b_collection(
            scene_id,
            l2b_collection_candidates,
            probe_asset="cmf.tif",
            token=token,
            http_timeout=http_timeout,
        )
        if l2b_coll is None:
            raise CMSceneNotPublished(scene_id)

    # Build one asset URL per selected product. Keys are the
    # extension-less band names — they must match the lazy-property
    # names exactly (`_open` strips nothing).
    asset_paths: dict[str, PathLike] = {}
    for product in products:
        if product.family is not CMProductFamily.L2B:
            raise ValueError(
                f"Product {product.key!r} ({product.family.value}) "
                "is not an L2B per-scene product. Use CMPlumeImage "
                "for L3A per-plume products. The whole-scene RGB "
                "sibling lives in a separate collection and is not "
                "selected via products= — pass with_rgb=True (the "
                "default) to attach it."
            )
        asset_paths[product.band] = _l2b_asset_url(
            l2b_coll,
            scene_id,
            product.key,
        )

    if with_rgb:
        if rgb_coll is None:
            rgb_coll = _probe_l2b_collection(
                scene_id,
                rgb_collection_candidates,
                probe_asset="rgb.tif",
                token=token,
                http_timeout=http_timeout,
            )
        if rgb_coll is not None:
            asset_paths["rgb"] = _l2b_asset_url(rgb_coll, scene_id, "rgb.tif")

    return cls(
        scene_id=scene_id,
        asset_paths=asset_paths,
        overview_level=overview_level,
        token=token,
    )

read_polygon(polygon, *, crs_polygon='EPSG:4326', bands=CM_L2B_BANDS)

Read a polygon clip from the requested bands.

Parameters:

Name Type Description Default
polygon BaseGeometry

Clip geometry.

required
crs_polygon str

CRS of polygon. Defaults to "EPSG:4326".

'EPSG:4326'
bands Iterable[str]

Subset of band names. Bands whose asset is missing (absent from :attr:asset_paths, or an optional band the server doesn't have) or whose window has zero overlap return None.

CM_L2B_BANDS

Returns:

Type Description
``{"cmf"

, "rgb": , ...}`` — lazy

dict[str, RasterSource | None]

windowed sources (geoarray.RasterSource); .load()

dict[str, RasterSource | None]

materialises one as a geoarray.GeoArray.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def read_polygon(
    self,
    polygon: BaseGeometry,
    *,
    crs_polygon: str = "EPSG:4326",
    bands: Iterable[str] = CM_L2B_BANDS,
) -> dict[str, RasterSource | None]:
    """Read a polygon clip from the requested bands.

    Args:
        polygon: Clip geometry.
        crs_polygon: CRS of ``polygon``. Defaults to ``"EPSG:4326"``.
        bands: Subset of band names. Bands whose asset is missing
            (absent from :attr:`asset_paths`, or an optional band
            the server doesn't have) or whose window has zero
            overlap return ``None``.

    Returns:
        ``{"cmf": <RasterSource>, "rgb": <RasterSource>, ...}`` — lazy
        windowed sources (`geoarray.RasterSource`); ``.load()``
        materialises one as a `geoarray.GeoArray`.
    """
    from geoarray.interop.georeader import (
        source_from_georeader,
        source_to_georeader,
    )
    from georeader import read

    out: dict[str, RasterSource | None] = {}
    for band in bands:
        if self.asset_paths.get(band) is None:
            out[band] = None
            continue
        # `uas` is a text sidecar, not a raster — skip the band
        # reader path. Callers reading text sidecars use the
        # `.uas` property directly.
        if band == "uas":
            continue
        reader = self._reader(band)
        if reader is None:
            out[band] = None
            continue
        # `boundless=False` makes `read_from_polygon` return `None`
        # for windows that don't intersect the raster (e.g. an
        # artifact-mask whose un-orthorectified strip falls outside
        # the requested AOI), instead of allocating a fill-valued
        # tensor the size of the requested window. Real CRS / I/O
        # errors are left to propagate — the prior bare
        # `except Exception` swallowed those silently.
        #
        # With ``return_only_data=False`` the result is a windowed
        # (lazy) georeader reader, wrapped back as a RasterSource.
        result = read.read_from_polygon(
            source_to_georeader(reader),
            polygon=polygon,
            crs_polygon=crs_polygon,
            boundless=False,
        )
        out[band] = source_from_georeader(result) if result is not None else None
    return out

read_window(bounds_4326, *, bands=CM_L2B_BANDS)

Read a WGS-84 bbox window from the requested bands (lazy).

Raises:

Type Description
ValueError

If bounds_4326 is malformed or crosses the antimeridian (W > E) — split such windows in two.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def read_window(
    self,
    bounds_4326: BBox,
    *,
    bands: Iterable[str] = CM_L2B_BANDS,
) -> dict[str, RasterSource | None]:
    """Read a WGS-84 bbox window from the requested bands (lazy).

    Raises:
        ValueError: If ``bounds_4326`` is malformed or crosses the
            antimeridian (``W > E``) — split such windows in two.
    """
    validate_lonlat_bbox(bounds_4326)
    return self.read_polygon(box(*bounds_4326), bands=bands)

read_window_to_crs(bounds_4326, crs_dst, *, bands=CM_L2B_BANDS)

Read a window then reproject each band to crs_dst.

Reprojection materialises the data — values are geoarray.GeoArray, not lazy sources.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def read_window_to_crs(
    self,
    bounds_4326: BBox,
    crs_dst: str,
    *,
    bands: Iterable[str] = CM_L2B_BANDS,
) -> dict[str, GeoArray | None]:
    """Read a window then reproject each band to ``crs_dst``.

    Reprojection materialises the data — values are
    `geoarray.GeoArray`, not lazy sources.
    """
    from geoarray.interop.georeader import from_georeader, source_to_georeader
    from georeader import read

    crops = self.read_window(bounds_4326, bands=bands)
    return {
        band: (
            from_georeader(read.read_to_crs(source_to_georeader(geo), crs_dst))
            if geo is not None
            else None
        )
        for band, geo in crops.items()
    }

with_rgb(rgb_item)

Return a copy with rgb merged in from a sibling STAC item.

The CH4 (l2b-ch4-mfa-v3a) and RGB (l2b-rgb-v3a) L2B collections share scene_id and pixel grid, but each STAC item only exposes its own assets. Fetch both with :func:api_queries.get_tile (passing collection=...) and compose them via this method:

ir = CMImageRaster.from_cm_tile_item(ch4_item) ir = ir.with_rgb(rgb_item) ir.rgb is not None True

Raises:

Type Description
ValueError

If rgb_item.scene_id doesn't match self.scene_id (mismatched scenes don't share a grid — usually a programming error).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def with_rgb(self, rgb_item: CMTileItem) -> CMImageRaster:
    """Return a copy with ``rgb`` merged in from a sibling STAC item.

    The CH4 (``l2b-ch4-mfa-v3a``) and RGB (``l2b-rgb-v3a``) L2B
    collections share ``scene_id`` and pixel grid, but each STAC
    item only exposes its own assets. Fetch both with
    :func:`api_queries.get_tile` (passing ``collection=...``) and
    compose them via this method:

    >>> ir = CMImageRaster.from_cm_tile_item(ch4_item)
    >>> ir = ir.with_rgb(rgb_item)
    >>> ir.rgb is not None
    True

    Raises:
        ValueError: If ``rgb_item.scene_id`` doesn't match
            ``self.scene_id`` (mismatched scenes don't share a grid
            — usually a programming error).
    """
    if rgb_item.scene_id != self.scene_id:
        raise ValueError(
            f"scene_id mismatch: {self.scene_id!r} vs {rgb_item.scene_id!r}"
        )
    # Pick the rgb GeoTIFF (with or without `.tif` extension);
    # ignore everything else on the rgb item.
    new_paths = dict(self.asset_paths)
    for key, url in rgb_item.asset_urls.items():
        if not url:
            continue
        stripped = key[:-4] if key.endswith(".tif") else key
        if stripped == "rgb":
            new_paths["rgb"] = url
            break
    return CMImageRaster(
        scene_id=self.scene_id,
        asset_paths=new_paths,
        overview_level=self.overview_level,
        token=self.token,
    )

l2b_collection_candidates_for_spec(spec)

L2B collection ids to probe for a plume, in probe order.

Candidates never leave the spec's gas: a CO2 plume never resolves to a CH4 scene raster. Within each version (ordered by :func:_lag_ordered_versions) the spec's own cmf_type is tried first, then the other variants known for that gas.

l2b_collection_candidates_for_spec(CMCollectionSpec("v3d")) ('l2b-ch4-mfa-v3d', 'l2b-ch4-mfa-v3c', 'l2b-ch4-mfa-v3a', 'l2b-ch4-mfa-v3e') l2b_collection_candidates_for_spec( ... CMCollectionSpec("v3e", "co2", "mfa", ime_cmf_type="mfal"))[:3] ('l2b-co2-mfa-v3e', 'l2b-co2-mfal-v3e', 'l2b-co2-mfa-v3d')

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def l2b_collection_candidates_for_spec(spec: CMCollectionSpec) -> tuple[str, ...]:
    """L2B collection ids to probe for a plume, in probe order.

    Candidates never leave the spec's gas: a CO2 plume never resolves
    to a CH4 scene raster. Within each version (ordered by
    :func:`_lag_ordered_versions`) the spec's own cmf_type is tried
    first, then the other variants known for that gas.

    >>> l2b_collection_candidates_for_spec(CMCollectionSpec("v3d"))
    ('l2b-ch4-mfa-v3d', 'l2b-ch4-mfa-v3c', 'l2b-ch4-mfa-v3a', 'l2b-ch4-mfa-v3e')
    >>> l2b_collection_candidates_for_spec(
    ...     CMCollectionSpec("v3e", "co2", "mfa", ime_cmf_type="mfal"))[:3]
    ('l2b-co2-mfa-v3e', 'l2b-co2-mfal-v3e', 'l2b-co2-mfa-v3d')
    """
    cmf_types = list(
        dict.fromkeys(
            [spec.cmf_type]
            + ([spec.ime_cmf_type] if spec.ime_cmf_type else [])
            + list(_L2B_CMF_TYPES.get(spec.gas, ()))
        )
    )
    return tuple(
        f"l2b-{spec.gas}-{cmf}-{version}"
        for version in _lag_ordered_versions(spec.version)
        for cmf in cmf_types
    )

rgb_collection_candidates_for_spec(spec)

L2B RGB sibling collection ids to probe, in the same version order as :func:l2b_collection_candidates_for_spec (RGB is not gas-typed).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/rasters.py
def rgb_collection_candidates_for_spec(spec: CMCollectionSpec) -> tuple[str, ...]:
    """L2B RGB sibling collection ids to probe, in the same version order
    as :func:`l2b_collection_candidates_for_spec` (RGB is not gas-typed)."""
    return tuple(f"l2b-rgb-{v}" for v in _lag_ordered_versions(spec.version))

geoproducts.carbonmapper.sources_raster

Rasterize Carbon Mapper sources (point clusters) onto a target grid.

Carbon Mapper sources are point geometries (DBSCAN-clustered plume locations). For training labels, QA overlays, and source-prior features it is useful to project them onto the same grid as an L2B scene as a binary mask. This module provides:

  • :func:rasterize_sources — one-shot function: list of points → geoarray.GeoArray mask.
  • :class:CMSourceRaster — lazy wrapper that mirrors :class:~geoproducts.carbonmapper.rasters.CMImageRaster shape (read_polygon / read_window / read_window_to_crs) so callers can compose the source mask with the L2B rasters.

Both delegate the actual burn-in to georeader (the internal engine: :func:georeader.rasterize.rasterize_geopandas_like / :func:~georeader.rasterize.rasterize_from_geopandas) and return a geoarray.GeoArray — no custom rasterio.features call lives in this module.

The Carbon Mapper API does not publish a sources raster — these helpers build it client-side from :func:list_sources (or any iterable of :class:~geoproducts.carbonmapper.source.CMSource).

CMSourceRaster dataclass

Lazy binary-mask raster of Carbon Mapper sources on a target grid.

Mirrors the read-helper surface of :class:~geoproducts.carbonmapper.rasters.CMImageRaster so callers can compose source masks with L2B reads.

Attributes

sources: Source points to rasterize. transform, shape, crs: Target grid spec. Use :meth:from_cmtileitem or :meth:from_source to inherit the spec from an existing raster. buffer_m: Per-point disk radius in metres. 0 → single pixel.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
@dataclass(repr=False)
class CMSourceRaster:
    """Lazy binary-mask raster of Carbon Mapper sources on a target grid.

    Mirrors the read-helper surface of
    :class:`~geoproducts.carbonmapper.rasters.CMImageRaster` so
    callers can compose source masks with L2B reads.

    Attributes
    ----------
    sources:
        Source points to rasterize.
    transform, shape, crs:
        Target grid spec. Use :meth:`from_cmtileitem` or
        :meth:`from_source` to inherit the spec from an existing
        raster.
    buffer_m:
        Per-point disk radius in metres. ``0`` → single pixel.
    """

    sources: Sequence[SourceLike]
    transform: rasterio.Affine
    shape: tuple[int, int]
    crs: rasterio.crs.CRS
    buffer_m: float = 0.0

    # ---- Constructors ----

    @classmethod
    def from_source(
        cls,
        sources: Sequence[SourceLike],
        template: RasterSource,
        *,
        buffer_m: float = 0.0,
    ) -> CMSourceRaster:
        """Build a source raster on the grid of an existing raster.

        Args:
            sources: Source points to rasterize.
            template: Any `geoarray.RasterSource` (a reader, a lazy CM
                band such as ``CMImageRaster.cmf``, a GeoArray).
            buffer_m: Per-point disk radius in metres.

        Raises:
            TypeError: ``template`` is a georeader ``GeoTensor`` /
                ``GeoData`` (convert it with ``from_georeader`` /
                ``source_from_georeader``).
        """
        grid = require_source(template, "CMSourceRaster.from_source").grid
        return cls(
            sources=sources,
            transform=grid.affine,
            shape=grid.shape,
            crs=rasterio.crs.CRS.from_user_input(grid.crs),
            buffer_m=buffer_m,
        )

    @classmethod
    def from_cmtileitem(
        cls,
        sources: Sequence[SourceLike],
        tile: CMTileItem,
        *,
        buffer_m: float = 0.0,
        token: str | None = None,
    ) -> CMSourceRaster:
        """Build a source raster aligned to an L2B :class:`CMTileItem`.

        Resolves the tile's ``cmf`` GeoTIFF header to inherit
        ``(transform, shape, crs)``. Issues one HEAD/GET-range read.
        STAC items key the asset with its extension (``cmf.tif``); the
        extension-less form is accepted too. Pass ``token`` for an href
        on Carbon Mapper's Bearer-gated asset proxy; it is sent only
        inside this read's ``rasterio.Env``.
        """
        assets = tile.asset_urls
        cmf_url = assets.get("cmf.tif") or assets.get("cmf") or assets.get("ch4-mfa")
        if not cmf_url:
            raise ValueError(
                f"CMTileItem {tile.scene_id!r} has no 'cmf' asset to align to."
            )
        env_options = rio_env_options_for(str(cmf_url), token) or {}
        with rasterio.Env(**env_options), rasterio.open(cmf_url) as ds:
            return cls(
                sources=sources,
                transform=ds.transform,
                shape=(ds.height, ds.width),
                crs=ds.crs,
                buffer_m=buffer_m,
            )

    # ---- Eager render ----

    @property
    def grid(self) -> Grid:
        """The target pixel grid."""
        return Grid.from_affine(self.transform, self.crs, self.shape)

    def load(self) -> GeoArray:
        """Rasterize all sources onto the full grid: ``(H, W)`` ``uint8``."""
        return rasterize_sources(
            self.sources,
            transform=self.transform,
            shape=self.shape,
            crs=self.crs,
            buffer_m=self.buffer_m,
        )

    # ---- Read helpers (mirror CMImageRaster) ----

    def read_polygon(
        self,
        polygon: BaseGeometry,
        *,
        crs_polygon: str = "EPSG:4326",
    ) -> GeoArray:
        """Read a polygon clip of the source mask."""
        full = self.load()
        return from_georeader(
            read.read_from_polygon(
                source_to_georeader(full),
                polygon=polygon,
                crs_polygon=crs_polygon,
            )
        )

    def read_window(self, bounds_4326: BBox) -> GeoArray:
        """Read a WGS-84 bbox window of the source mask.

        Raises:
            ValueError: If the bbox is malformed or crosses the
                antimeridian (``W > E``) — split such windows in two.
        """
        validate_lonlat_bbox(bounds_4326)
        return self.read_polygon(box(*bounds_4326))

    def read_window_to_crs(
        self,
        bounds_4326: BBox,
        crs_dst: str,
    ) -> GeoArray:
        """Read a window then reproject the mask to ``crs_dst``."""
        crop = self.read_window(bounds_4326)
        return from_georeader(read.read_to_crs(source_to_georeader(crop), crs_dst))

    # ---- Repr ----

    def __repr__(self) -> str:
        return (
            f"{type(self).__name__}(n_sources={len(self.sources)}, "
            f"shape={self.shape}, buffer_m={self.buffer_m}, crs={self.crs})"
        )

grid property

The target pixel grid.

from_cmtileitem(sources, tile, *, buffer_m=0.0, token=None) classmethod

Build a source raster aligned to an L2B :class:CMTileItem.

Resolves the tile's cmf GeoTIFF header to inherit (transform, shape, crs). Issues one HEAD/GET-range read. STAC items key the asset with its extension (cmf.tif); the extension-less form is accepted too. Pass token for an href on Carbon Mapper's Bearer-gated asset proxy; it is sent only inside this read's rasterio.Env.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
@classmethod
def from_cmtileitem(
    cls,
    sources: Sequence[SourceLike],
    tile: CMTileItem,
    *,
    buffer_m: float = 0.0,
    token: str | None = None,
) -> CMSourceRaster:
    """Build a source raster aligned to an L2B :class:`CMTileItem`.

    Resolves the tile's ``cmf`` GeoTIFF header to inherit
    ``(transform, shape, crs)``. Issues one HEAD/GET-range read.
    STAC items key the asset with its extension (``cmf.tif``); the
    extension-less form is accepted too. Pass ``token`` for an href
    on Carbon Mapper's Bearer-gated asset proxy; it is sent only
    inside this read's ``rasterio.Env``.
    """
    assets = tile.asset_urls
    cmf_url = assets.get("cmf.tif") or assets.get("cmf") or assets.get("ch4-mfa")
    if not cmf_url:
        raise ValueError(
            f"CMTileItem {tile.scene_id!r} has no 'cmf' asset to align to."
        )
    env_options = rio_env_options_for(str(cmf_url), token) or {}
    with rasterio.Env(**env_options), rasterio.open(cmf_url) as ds:
        return cls(
            sources=sources,
            transform=ds.transform,
            shape=(ds.height, ds.width),
            crs=ds.crs,
            buffer_m=buffer_m,
        )

from_source(sources, template, *, buffer_m=0.0) classmethod

Build a source raster on the grid of an existing raster.

Parameters:

Name Type Description Default
sources Sequence[SourceLike]

Source points to rasterize.

required
template RasterSource

Any geoarray.RasterSource (a reader, a lazy CM band such as CMImageRaster.cmf, a GeoArray).

required
buffer_m float

Per-point disk radius in metres.

0.0

Raises:

Type Description
TypeError

template is a georeader GeoTensor / GeoData (convert it with from_georeader / source_from_georeader).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
@classmethod
def from_source(
    cls,
    sources: Sequence[SourceLike],
    template: RasterSource,
    *,
    buffer_m: float = 0.0,
) -> CMSourceRaster:
    """Build a source raster on the grid of an existing raster.

    Args:
        sources: Source points to rasterize.
        template: Any `geoarray.RasterSource` (a reader, a lazy CM
            band such as ``CMImageRaster.cmf``, a GeoArray).
        buffer_m: Per-point disk radius in metres.

    Raises:
        TypeError: ``template`` is a georeader ``GeoTensor`` /
            ``GeoData`` (convert it with ``from_georeader`` /
            ``source_from_georeader``).
    """
    grid = require_source(template, "CMSourceRaster.from_source").grid
    return cls(
        sources=sources,
        transform=grid.affine,
        shape=grid.shape,
        crs=rasterio.crs.CRS.from_user_input(grid.crs),
        buffer_m=buffer_m,
    )

load()

Rasterize all sources onto the full grid: (H, W) uint8.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def load(self) -> GeoArray:
    """Rasterize all sources onto the full grid: ``(H, W)`` ``uint8``."""
    return rasterize_sources(
        self.sources,
        transform=self.transform,
        shape=self.shape,
        crs=self.crs,
        buffer_m=self.buffer_m,
    )

read_polygon(polygon, *, crs_polygon='EPSG:4326')

Read a polygon clip of the source mask.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def read_polygon(
    self,
    polygon: BaseGeometry,
    *,
    crs_polygon: str = "EPSG:4326",
) -> GeoArray:
    """Read a polygon clip of the source mask."""
    full = self.load()
    return from_georeader(
        read.read_from_polygon(
            source_to_georeader(full),
            polygon=polygon,
            crs_polygon=crs_polygon,
        )
    )

read_window(bounds_4326)

Read a WGS-84 bbox window of the source mask.

Raises:

Type Description
ValueError

If the bbox is malformed or crosses the antimeridian (W > E) — split such windows in two.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def read_window(self, bounds_4326: BBox) -> GeoArray:
    """Read a WGS-84 bbox window of the source mask.

    Raises:
        ValueError: If the bbox is malformed or crosses the
            antimeridian (``W > E``) — split such windows in two.
    """
    validate_lonlat_bbox(bounds_4326)
    return self.read_polygon(box(*bounds_4326))

read_window_to_crs(bounds_4326, crs_dst)

Read a window then reproject the mask to crs_dst.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def read_window_to_crs(
    self,
    bounds_4326: BBox,
    crs_dst: str,
) -> GeoArray:
    """Read a window then reproject the mask to ``crs_dst``."""
    crop = self.read_window(bounds_4326)
    return from_georeader(read.read_to_crs(source_to_georeader(crop), crs_dst))

rasterize_sources(sources, *, transform, shape, crs, buffer_m=0.0)

Rasterize source points onto a target grid as a binary mask.

Each source contributes a value of 1 at its pixel; if buffer_m > 0 a disk of that radius (in metres) is stamped instead. Sources falling outside the grid are silently dropped.

Delegates to :func:georeader.rasterize.rasterize_from_geopandas.

Parameters

sources: Iterable of :class:CMSource, Shapely :class:Point, or (lon, lat) tuples — all interpreted as WGS-84 lon/lat. transform: Affine transform of the target grid. shape: (height, width) of the target grid. crs: CRS of the target grid. Must be projected when buffer_m > 0. buffer_m: Buffer radius in metres applied around each source point. 0 (default) → all_touched single-pixel stamp per source.

Returns

GeoArray 2D uint8 mask of shape with values in {0, 1} (fill 0).

Raises

ValueError If buffer_m > 0 and crs is geographic, or if shape is not 2D.

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def rasterize_sources(
    sources: Iterable[SourceLike],
    *,
    transform: rasterio.Affine,
    shape: tuple[int, int],
    crs: str | rasterio.crs.CRS,
    buffer_m: float = 0.0,
) -> GeoArray:
    """Rasterize source points onto a target grid as a binary mask.

    Each source contributes a value of ``1`` at its pixel; if
    ``buffer_m > 0`` a disk of that radius (in metres) is stamped
    instead. Sources falling outside the grid are silently dropped.

    Delegates to
    :func:`georeader.rasterize.rasterize_from_geopandas`.

    Parameters
    ----------
    sources:
        Iterable of :class:`CMSource`, Shapely :class:`Point`, or
        ``(lon, lat)`` tuples — all interpreted as WGS-84 lon/lat.
    transform:
        Affine transform of the target grid.
    shape:
        ``(height, width)`` of the target grid.
    crs:
        CRS of the target grid. Must be projected when
        ``buffer_m > 0``.
    buffer_m:
        Buffer radius in metres applied around each source point.
        ``0`` (default) → ``all_touched`` single-pixel stamp per source.

    Returns
    -------
    GeoArray
        2D ``uint8`` mask of ``shape`` with values in ``{0, 1}`` (fill ``0``).

    Raises
    ------
    ValueError
        If ``buffer_m > 0`` and ``crs`` is geographic, or if ``shape``
        is not 2D.
    """
    if len(shape) != 2:
        raise ValueError(f"Expected (H, W) shape, got {shape}")
    crs_obj = rasterio.crs.CRS.from_user_input(crs)

    gdf = _sources_gdf(sources)
    if len(gdf) == 0:
        return GeoArray(
            np.zeros(shape, dtype=np.uint8),
            transform,
            crs_obj,
            fill_value=0,
            dims=("y", "x"),
        )

    if buffer_m > 0:
        gdf = _apply_buffer(gdf, crs_obj, buffer_m)
        all_touched = False
    else:
        gdf = gdf.to_crs(crs_obj)
        all_touched = True  # stamp the pixel containing each point

    height, width = shape
    window_out = rasterio.windows.Window(
        col_off=0, row_off=0, width=width, height=height
    )
    return from_georeader(
        rasterize_from_geopandas(
            gdf,
            column="value",
            transform=transform,
            window_out=window_out,
            crs_out=crs_obj,
            fill=0,
            all_touched=all_touched,
        )
    )

rasterize_sources_like(sources, data_like, *, buffer_m=0.0)

Rasterize sources onto the grid of an existing raster.

Thin wrapper around :func:georeader.rasterize.rasterize_geopandas_like.

Parameters:

Name Type Description Default
sources Iterable[SourceLike]

Source points (see :func:rasterize_sources).

required
data_like RasterSource

The raster whose grid the mask takes: any geoarray.RasterSource (a reader, a lazy CM band, a GeoArray).

required
buffer_m float

Disk radius in metres around each point (0: one pixel).

0.0

Returns:

Type Description
GeoArray

(H, W) uint8 mask on data_like.grid, values in {0, 1}.

Raises:

Type Description
TypeError

data_like is a georeader GeoTensor / GeoData (convert it with from_georeader / source_from_georeader).

Source code in packages/geotoolz-products/src/geoproducts/carbonmapper/sources_raster.py
def rasterize_sources_like(
    sources: Iterable[SourceLike],
    data_like: RasterSource,
    *,
    buffer_m: float = 0.0,
) -> GeoArray:
    """Rasterize sources onto the grid of an existing raster.

    Thin wrapper around
    :func:`georeader.rasterize.rasterize_geopandas_like`.

    Args:
        sources: Source points (see :func:`rasterize_sources`).
        data_like: The raster whose grid the mask takes: any
            `geoarray.RasterSource` (a reader, a lazy CM band, a GeoArray).
        buffer_m: Disk radius in metres around each point (``0``: one pixel).

    Returns:
        ``(H, W)`` ``uint8`` mask on ``data_like.grid``, values in ``{0, 1}``.

    Raises:
        TypeError: ``data_like`` is a georeader ``GeoTensor`` / ``GeoData``
            (convert it with ``from_georeader`` / ``source_from_georeader``).
    """
    require_source(data_like, "rasterize_sources_like")
    grid = data_like.grid
    crs_obj = rasterio.crs.CRS.from_user_input(grid.crs)
    gdf = _sources_gdf(sources)
    if len(gdf) == 0:
        return GeoArray(
            np.zeros(grid.shape, dtype=np.uint8),
            grid.transform,
            grid.crs,
            fill_value=0,
            dims=("y", "x"),
        )

    if buffer_m > 0:
        gdf = _apply_buffer(gdf, crs_obj, buffer_m)
        all_touched = False
    else:
        gdf = gdf.to_crs(crs_obj)
        all_touched = True

    return from_georeader(
        rasterize_geopandas_like(
            gdf,
            data_like=source_to_georeader(data_like),
            column="value",
            fill=0,
            all_touched=all_touched,
        )
    )

until their docstrings render cleanly; see their source for the arguments.