Skip to content

Sentinel#

The reader family for ESA's Sentinel missions, built on GDAL's SENTINEL2 / SAFE drivers: GDAL parses the product structure, pyramids does the raster ops, and this package adds the instrument semantics — which subdataset is which band, how to turn DN into reflectance, how to read the scene-classification mask.

A .SAFE product opens through a bare Dataset.read_file(path), zipped or not — see the Reading EO sources via read_file guide.

A Sentinel product is a catalog of rasters, not a raster, so it gets its own small model:

  • open_product — sniff the GDAL driver behind a path (.SAFE / MTD_*.xml / .zip) and return the right typed SentinelProduct (currently S2Product; Sentinel-1 SAFE is a planned later phase and raises a clear error today).
  • from_sentinel2 — turnkey Sentinel-2 read into a pyramids Dataset: band selection, native-resolution choice, optional crop / reprojection, DN → reflectance tagging, and Level-2A SCL masking.
  • collection_from_sentinel2 — read several bands / products into a DatasetCollection.
  • scl_mask / SclClass — Level-2A cloud / shadow masking via the scene-classification layer.

Product model#

pyramids_eo.sentinel #

Sentinel product readers built on GDAL's SENTINEL2 / SAFE drivers.

The earth-observation reader family for ESA's Sentinel missions, layered on pyramids the same way :mod:pyramids_eo.earthengine layers on the EEDAI driver: GDAL parses the product structure, pyramids does the raster ops, and this package adds the instrument semantics — which subdataset is which band, how to turn DN into reflectance, how to read the scene-classification mask.

Public surface:

  • :func:open_product — open any supported Sentinel product into a typed model.
  • :func:from_sentinel2 — turnkey Sentinel-2 read → a pyramids Dataset.
  • :func:scl_mask / :class:SclClass — Level-2A cloud/shadow masking.

Sentinel-1 (SAFE) is planned as a later phase; :func:open_product raises a clear error for it today.

SentinelProduct #

Bases: ABC

A Sentinel product on disk — a catalog of openable rasters.

Concrete subclasses (:class:~pyramids_eo.sentinel.s2.S2Product, and a future S1Product) add the mission-specific model. This base holds only what every Sentinel product shares.

Attributes:

Name Type Description
path

The path (or connection root) the product was opened from.

driver

The GDAL driver short name ("SENTINEL2" / "SAFE").

metadata dict[str, str]

The container's default-domain metadata (Dataset.metadata).

subdatasets list[Any]

The pyramids SubDataset value objects the container exposes, each openable with .open().

Source code in src/pyramids_eo/sentinel/product.py
class SentinelProduct(abc.ABC):
    """A Sentinel product on disk — a catalog of openable rasters.

    Concrete subclasses (:class:`~pyramids_eo.sentinel.s2.S2Product`, and a
    future ``S1Product``) add the mission-specific model. This base holds only
    what every Sentinel product shares.

    Attributes:
        path: The path (or connection root) the product was opened from.
        driver: The GDAL driver short name (``"SENTINEL2"`` / ``"SAFE"``).
        metadata: The container's default-domain metadata (``Dataset.metadata``).
        subdatasets: The pyramids ``SubDataset`` value objects the container
            exposes, each openable with ``.open()``.
    """

    def __init__(self, path: str, container: Dataset) -> None:
        self.path = path
        self.driver = container.raster.GetDriver().ShortName
        self.metadata: dict[str, str] = dict(container.metadata or {})
        self.subdatasets: list[Any] = list(container.subdatasets)

    @property
    @abc.abstractmethod
    def mission(self) -> str:
        """Mission identifier, e.g. ``"sentinel-2"``."""

    @property
    @abc.abstractmethod
    def product_type(self) -> str:
        """Product type token, e.g. ``"S2MSI2A"`` / ``"GRD"``."""

    def __repr__(self) -> str:  # pragma: no cover - display only
        return (
            f"{type(self).__name__}(driver={self.driver!r}, "
            f"product_type={self.product_type!r}, subdatasets={len(self.subdatasets)})"
        )
mission abstractmethod property #

Mission identifier, e.g. "sentinel-2".

product_type abstractmethod property #

Product type token, e.g. "S2MSI2A" / "GRD".

SclClass #

Bases: IntEnum

Sentinel-2 L2A Scene-Classification codes (GDAL category names).

Each member's value is the integer pixel code the SCL band stores, so a member can be used directly as a class selector or compared with a raw code.

Examples:

  • A member carries the SCL pixel code and its name:
    >>> from pyramids_eo.sentinel.s2.masks import SclClass
    >>> SclClass.CLOUD_HIGH_PROBA.value
    9
    >>> SclClass.WATER.name
    'WATER'
    
  • Build a cloud/shadow mask selection and read back the codes:
    >>> from pyramids_eo.sentinel.s2.masks import SclClass
    >>> clouds = [SclClass.CLOUD_MEDIUM_PROBA, SclClass.CLOUD_HIGH_PROBA]
    >>> [int(c) for c in clouds]
    [8, 9]
    
Source code in src/pyramids_eo/sentinel/s2/masks.py
class SclClass(IntEnum):
    """Sentinel-2 L2A Scene-Classification codes (GDAL category names).

    Each member's value is the integer pixel code the SCL band stores, so a
    member can be used directly as a class selector or compared with a raw code.

    Examples:
        - A member carries the SCL pixel code and its name:
            ```python
            >>> from pyramids_eo.sentinel.s2.masks import SclClass
            >>> SclClass.CLOUD_HIGH_PROBA.value
            9
            >>> SclClass.WATER.name
            'WATER'

            ```
        - Build a cloud/shadow mask selection and read back the codes:
            ```python
            >>> from pyramids_eo.sentinel.s2.masks import SclClass
            >>> clouds = [SclClass.CLOUD_MEDIUM_PROBA, SclClass.CLOUD_HIGH_PROBA]
            >>> [int(c) for c in clouds]
            [8, 9]

            ```
    """

    NODATA = 0
    SATURATED_DEFECTIVE = 1
    DARK_FEATURE_SHADOW = 2
    CLOUD_SHADOW = 3
    VEGETATION = 4
    BARE_SOIL_DESERT = 5
    WATER = 6
    CLOUD_LOW_PROBA = 7
    CLOUD_MEDIUM_PROBA = 8
    CLOUD_HIGH_PROBA = 9
    THIN_CIRRUS = 10
    SNOW_ICE = 11

open_product(path) #

Open a Sentinel product and return its typed model.

Sniffs the GDAL driver behind path and dispatches to the concrete product class. Accepts a .SAFE directory, a product metadata XML, a manifest.safe, a .zip holding a .SAFE (opened in place), or a driver connection string.

Parameters:

Name Type Description Default
path str | Path

The product to open.

required

Returns:

Name Type Description
A SentinelProduct

class:SentinelProduct — currently an

SentinelProduct

class:~pyramids_eo.sentinel.s2.S2Product for Sentinel-2.

Raises:

Type Description
UnsupportedProductError

The path opens, but its driver is not a Sentinel product family this package models.

ProductError

The path cannot be opened as a product.

Examples:

  • Open a Level-2A product and inspect its subdatasets:
    >>> from pyramids_eo.sentinel import open_product  # doctest: +SKIP
    >>> product = open_product("S2A_..._MSIL2A.SAFE")   # doctest: +SKIP
    >>> product.product_type                            # doctest: +SKIP
    'S2MSI2A'
    
Source code in src/pyramids_eo/sentinel/product.py
def open_product(path: str | Path) -> SentinelProduct:
    """Open a Sentinel product and return its typed model.

    Sniffs the GDAL driver behind ``path`` and dispatches to the concrete
    product class. Accepts a ``.SAFE`` directory, a product metadata XML, a
    ``manifest.safe``, a ``.zip`` holding a ``.SAFE`` (opened in place), or a
    driver connection string.

    Args:
        path: The product to open.

    Returns:
        A :class:`SentinelProduct` — currently an
        :class:`~pyramids_eo.sentinel.s2.S2Product` for Sentinel-2.

    Raises:
        UnsupportedProductError: The path opens, but its driver is not a
            Sentinel product family this package models.
        ProductError: The path cannot be opened as a product.

    Examples:
        - Open a Level-2A product and inspect its subdatasets:
            ```python
            >>> from pyramids_eo.sentinel import open_product  # doctest: +SKIP
            >>> product = open_product("S2A_..._MSIL2A.SAFE")   # doctest: +SKIP
            >>> product.product_type                            # doctest: +SKIP
            'S2MSI2A'

            ```
    """
    container_path = _resolve_container_path(path)
    try:
        # A product metadata XML is a 0-band container by design -- that is what
        # we want to open, and what .subdatasets is then read from. pyramids 0.57
        # warns on such an open; silence it here so the warning does not fire on
        # every open_product, and so a consumer running warnings as errors does
        # not see it turn into the ProductError raised below.
        container = Dataset.read_file(container_path, warn_on_container=False)
    except Exception as exc:  # noqa: BLE001 - re-raise as the package's error
        raise ProductError(f"cannot open product {path!r}: {exc}") from exc

    driver = container.raster.GetDriver().ShortName
    family = _DRIVER_FAMILY.get(driver)
    if family == "s2":
        from pyramids_eo.sentinel.s2.product import S2Product

        return S2Product(str(path), container)
    if family == "s1":
        raise UnsupportedProductError(
            f"Sentinel-1 ({driver}) products are not yet modelled "
            "(planned as Phase 2); Sentinel-2 is supported today."
        )
    raise UnsupportedProductError(
        f"{driver!r} is not a Sentinel product driver this package models "
        f"(known: {sorted(_DRIVER_FAMILY)})."
    )

collection_from_sentinel2(paths, *, root_dir, **kwargs) #

Read a time series of Sentinel-2 products into a DatasetCollection.

Each product in paths is read with :func:from_sentinel2 (passing **kwargs through) and written as a GeoTIFF under root_dir; the written files are then assembled into a DatasetCollection.

The collection is file-backed on purpose, for the two things that still need it on pyramids-core >= 0.73.0: DatasetCollection.to_zarr and to_kerchunk require a file-backed collection outright, and out-of-core scale depends on it — the in-memory cube reads each scene's array eagerly (only the time stack is lazy), whereas a file-backed collection reads tile-by-tile, so a series larger than RAM stays readable. Time-axis reductions no longer need it: since pyramids-core 0.73.0 they also run on a resident datasets= collection, which is what :func:collection_from_earthengine returns.

Parameters:

Name Type Description Default
paths Sequence[str | Path]

The Sentinel-2 products (any form :func:from_sentinel2 accepts).

required
root_dir str | Path

Directory the per-scene GeoTIFFs are written to (created if absent).

required
**kwargs Any

Forwarded to :func:from_sentinel2 (bands / resolution / epsg / reflectance / mask_scl / …), applied to every scene.

{}

Returns:

Type Description
Any

A pyramids.dataset.DatasetCollection over the written scenes.

Raises:

Type Description
ProductError

paths is empty.

Source code in src/pyramids_eo/sentinel/s2/reader.py
def collection_from_sentinel2(
    paths: Sequence[str | Path],
    *,
    root_dir: str | Path,
    **kwargs: Any,
) -> Any:
    """Read a time series of Sentinel-2 products into a ``DatasetCollection``.

    Each product in ``paths`` is read with :func:`from_sentinel2` (passing
    ``**kwargs`` through) and written as a GeoTIFF under ``root_dir``; the
    written files are then assembled into a ``DatasetCollection``.

    The collection is **file-backed on purpose**, for the two things that still
    need it on ``pyramids-core`` >= 0.73.0: ``DatasetCollection.to_zarr`` and
    ``to_kerchunk`` require a file-backed collection outright, and out-of-core scale
    depends on it — the in-memory cube reads each scene's array eagerly (only the
    time stack is lazy), whereas a file-backed collection reads tile-by-tile, so a
    series larger than RAM stays readable. Time-axis **reductions** no longer need
    it: since ``pyramids-core`` 0.73.0 they also run on a resident ``datasets=``
    collection, which is what :func:`collection_from_earthengine` returns.

    Args:
        paths: The Sentinel-2 products (any form :func:`from_sentinel2` accepts).
        root_dir: Directory the per-scene GeoTIFFs are written to (created if
            absent).
        **kwargs: Forwarded to :func:`from_sentinel2` (``bands`` / ``resolution``
            / ``epsg`` / ``reflectance`` / ``mask_scl`` / …), applied to every
            scene.

    Returns:
        A ``pyramids.dataset.DatasetCollection`` over the written scenes.

    Raises:
        ProductError: ``paths`` is empty.
    """
    from pyramids.dataset import DatasetCollection

    products = list(paths)
    if not products:
        raise ProductError("collection_from_sentinel2: no product paths given")
    if "path_out" in kwargs:
        raise ProductError(
            "collection_from_sentinel2 manages per-scene output itself; pass "
            "root_dir=, not path_out= (it is set per scene)."
        )

    root = Path(root_dir)
    root.mkdir(parents=True, exist_ok=True)
    written: list[Path] = []
    for index, product_path in enumerate(products):
        out = root / f"{_scene_stem(product_path, index)}.tif"
        from_sentinel2(product_path, path_out=out, **kwargs)
        written.append(out)
    return DatasetCollection.from_files(written)

from_sentinel2(path, *, bands=None, resolution=None, epsg=None, bbox=None, crs=None, reflectance=True, mask_scl=None, resample='nearest', path_out=None) #

Read a Sentinel-2 product into a pyramids Dataset.

Parameters:

Name Type Description Default
path str | Path | S2Product

A product path (.SAFE / MTD_*.xml / .zip) or an already-open :class:S2Product.

required
bands list[str] | None

Band names to read (e.g. ["B04", "B08"]; B4 == B04). None reads every spectral band at the chosen resolution.

None
resolution int | None

Native resolution in metres (10 / 20 / 60). None picks the finest resolution whose subdataset carries all requested bands.

None
epsg int | None

UTM EPSG code, required only for a multi-zone product.

None
bbox BBox | None

Optional crop window (minx, miny, maxx, maxy) in the product's native CRS (cropping happens before any crs reprojection).

None
crs str | int | None

Optional target CRS (an EPSG integer or a WKT string) to reproject to.

None
reflectance bool

When True (default), tag the spectral bands so read_array() yields reflectance (DN + offset) / quantification (the baseline-≥04.00 offset is 0 on older products). The stored values stay DN; read_array(unpack=False) returns them unconverted.

True
mask_scl list[Any] | None

L2A only — classes to mask out (see :class:~pyramids_eo.sentinel.s2.masks.SclClass); masked pixels become no-data.

None
path_out str | Path | None

When given, also write the result there (COG by extension).

None

Returns:

Type Description
Any

A pyramids Dataset of the requested bands.

Note

No-data is declared in the DN domain (the GDAL convention). Because reflectance is applied as lazy scale / offset tags, the default read_array() returns DN * scale + offset for every pixel — so a DN no-data (and any SCL-masked pixel) reads back as the scaled sentinel, not the declared no_data_value. On a baseline-≥04.00 product (offset ≈ −1000) a DN-0 no-data reads as ≈ −0.1, not 0. Test for no-data against a read_array(unpack=False) read, not against a reflectance one.

Raises:

Type Description
ProductError

The product is missing a requested band / resolution, or a multi-zone product is read without epsg.

Examples:

  • Read the red and NIR bands as reflectance:
    >>> from pyramids_eo.sentinel import from_sentinel2  # doctest: +SKIP
    >>> ds = from_sentinel2("S2A_..._MSIL2A.SAFE",       # doctest: +SKIP
    ...                     bands=["B04", "B08"])        # doctest: +SKIP
    >>> reflectance = ds.read_array()                    # doctest: +SKIP
    
Source code in src/pyramids_eo/sentinel/s2/reader.py
def from_sentinel2(  # NOSONAR(S107) - flat keyword reader API mirroring from_earthengine
    path: str | Path | S2Product,
    *,
    bands: list[str] | None = None,
    resolution: int | None = None,
    epsg: int | None = None,
    bbox: BBox | None = None,
    crs: str | int | None = None,
    reflectance: bool = True,
    mask_scl: list[Any] | None = None,
    resample: str = "nearest",
    path_out: str | Path | None = None,
) -> Any:
    """Read a Sentinel-2 product into a pyramids ``Dataset``.

    Args:
        path: A product path (``.SAFE`` / ``MTD_*.xml`` / ``.zip``) or an
            already-open :class:`S2Product`.
        bands: Band names to read (e.g. ``["B04", "B08"]``; ``B4`` == ``B04``).
            ``None`` reads every spectral band at the chosen resolution.
        resolution: Native resolution in metres (10 / 20 / 60). ``None`` picks
            the finest resolution whose subdataset carries all requested bands.
        epsg: UTM EPSG code, required only for a multi-zone product.
        bbox: Optional crop window ``(minx, miny, maxx, maxy)`` in the product's
            native CRS (cropping happens before any ``crs`` reprojection).
        crs: Optional target CRS (an EPSG integer or a WKT string) to reproject to.
        reflectance: When ``True`` (default), tag the spectral bands so
            ``read_array()`` yields reflectance ``(DN + offset) / quantification``
            (the baseline-≥04.00 offset is 0 on older products). The stored values
            stay DN; ``read_array(unpack=False)`` returns them unconverted.
        mask_scl: L2A only — classes to mask out (see
            :class:`~pyramids_eo.sentinel.s2.masks.SclClass`); masked pixels
            become no-data.
        path_out: When given, also write the result there (COG by extension).

    Returns:
        A pyramids ``Dataset`` of the requested bands.

    Note:
        No-data is declared in the **DN domain** (the GDAL convention). Because
        reflectance is applied as lazy ``scale`` / ``offset`` tags, the default
        ``read_array()`` returns ``DN * scale + offset`` for *every* pixel — so a
        DN no-data (and any SCL-masked pixel) reads back as the *scaled*
        sentinel, not the declared ``no_data_value``. On a baseline-≥04.00
        product (offset ≈ −1000) a DN-0 no-data reads as ≈ −0.1, not 0. Test for
        no-data against a ``read_array(unpack=False)`` read, not against a
        reflectance one.

    Raises:
        ProductError: The product is missing a requested band / resolution, or
            a multi-zone product is read without ``epsg``.

    Examples:
        - Read the red and NIR bands as reflectance:
            ```python
            >>> from pyramids_eo.sentinel import from_sentinel2  # doctest: +SKIP
            >>> ds = from_sentinel2("S2A_..._MSIL2A.SAFE",       # doctest: +SKIP
            ...                     bands=["B04", "B08"])        # doctest: +SKIP
            >>> reflectance = ds.read_array()                    # doctest: +SKIP

            ```
    """
    product = path if isinstance(path, S2Product) else open_product(path)
    if not isinstance(
        product, S2Product
    ):  # pragma: no cover - open_product guarantees it
        raise ProductError(f"{path!r} is not a Sentinel-2 product")

    epsg = _resolve_epsg(product, epsg)
    wanted = _resolve_bands(product, bands, resolution, epsg)
    dataset, target_res, offsets = _read(product, wanted, resolution, epsg, resample)
    _set_nodata(dataset, product)

    # Do every DN-domain transform first (mask, crop, reproject), then tag
    # reflectance LAST. The mask's rebuild and pyramids `crop` both reset
    # per-band scale/offset (only `to_crs` / `to_file` preserve them), so tags
    # applied earlier would be silently dropped — tagging last guarantees the
    # returned dataset carries the calibration. `offsets` is captured from the
    # original read and passed through, so tagging after a crop stays correct.
    if mask_scl:
        dataset = _apply_scl_mask(dataset, product, target_res, epsg, mask_scl)
    if bbox is not None:
        dataset = _crop_to_bbox(dataset, bbox)
    if crs is not None:
        dataset = dataset.to_crs(crs)
    if reflectance:
        dataset = _scaling.tag_reflectance(
            dataset,
            product,
            offsets=offsets,
            spectral=[is_spectral_band(b) for b in wanted],
        )
    if path_out is not None:
        dataset.to_file(str(path_out))
    return dataset

scl_mask(dataset, classes, *, scl=None) #

Mask dataset pixels whose SCL class is in classes.

Masked pixels are set to the dataset's no-data value across every band. The SCL source is either an explicit scl (a single-band pyramids Dataset or a 2-D NumPy array on the same grid), or — when scl is None — an SCL band found within dataset itself.

Parameters:

Name Type Description Default
dataset Any

The pyramids Dataset to mask.

required
classes Sequence[SclClass | str | int]

Classes to mask out (see :func:_resolve_classes), e.g. [SclClass.CLOUD_HIGH_PROBA, SclClass.CLOUD_SHADOW].

required
scl Any

Optional explicit SCL source aligned to dataset's grid. When None, an SCL band inside dataset is used.

None

Returns:

Type Description
Any

A new pyramids Dataset with the masked pixels set to no-data; band

Any

names, no-data value, and scale/offset tags are preserved.

Raises:

Type Description
ProductError

No SCL source is available, or its shape does not match dataset.

Source code in src/pyramids_eo/sentinel/s2/masks.py
def scl_mask(
    dataset: Any,
    classes: Sequence[SclClass | str | int],
    *,
    scl: Any = None,
) -> Any:
    """Mask ``dataset`` pixels whose SCL class is in ``classes``.

    Masked pixels are set to the dataset's no-data value across every band. The
    SCL source is either an explicit ``scl`` (a single-band pyramids ``Dataset``
    or a 2-D NumPy array on the same grid), or — when ``scl`` is ``None`` — an
    ``SCL`` band found within ``dataset`` itself.

    Args:
        dataset: The pyramids ``Dataset`` to mask.
        classes: Classes to mask out (see :func:`_resolve_classes`), e.g.
            ``[SclClass.CLOUD_HIGH_PROBA, SclClass.CLOUD_SHADOW]``.
        scl: Optional explicit SCL source aligned to ``dataset``'s grid. When
            ``None``, an ``SCL`` band inside ``dataset`` is used.

    Returns:
        A new pyramids ``Dataset`` with the masked pixels set to no-data; band
        names, no-data value, and scale/offset tags are preserved.

    Raises:
        ProductError: No SCL source is available, or its shape does not match
            ``dataset``.
    """
    from pyramids.dataset import Dataset, GeoReference

    codes = _resolve_classes(classes)
    scl_array = _scl_array(dataset, scl)

    # read_array returns (rows, cols) for one band and (bands, rows, cols) for
    # many; normalise a single band to (1, rows, cols) so the mask indexing and
    # the shape check below are uniform. (np.atleast_3d would wrongly append the
    # band axis, giving (rows, cols, 1).)
    # Read the store, not physical units: this masks in the DN domain -- it
    # writes the raw no-data into the array, casts back to the source dtype and
    # carries the scale/offset onto the result. pyramids >=0.62 unpacks by
    # default, so a caller masking an already-tagged dataset would otherwise get
    # reflectance here and have the calibration applied a second time.
    data = np.asarray(dataset.read_array(unpack=False))
    if data.ndim == 2:
        data = data[np.newaxis, ...]
    if scl_array.shape != data.shape[-2:]:
        raise ProductError(
            f"SCL grid {scl_array.shape} does not match data grid {data.shape[-2:]}"
        )

    nodata = _nodata_of(dataset)
    mask = np.isin(scl_array, list(codes))
    masked = data.astype("float64", copy=True)
    masked[:, mask] = nodata

    # Pass no_data_value at creation so pyramids does not apply (and warn about)
    # its default -9999 sentinel, which is out of range for the uint16 dtype.
    out = Dataset.from_array(
        arr=masked.astype(data.dtype, copy=False),
        geo_ref=GeoReference(geo=dataset.raster.GetGeoTransform(), epsg=dataset.epsg),
        no_data_value=nodata,
    )
    _carry_band_state(dataset, out)
    return out

pyramids_eo.sentinel.product #

Product model: a Sentinel product is a catalog of rasters, not a raster.

Opening a Sentinel .SAFE (or its metadata XML / .zip) with GDAL yields a 0-band dataset whose payload is a set of subdatasets — one per resolution × UTM zone for Sentinel-2, one per swath × polarisation × calibration for Sentinel-1. Dataset models a raster; it cannot model that catalog. So the product is its own small class family:

  • :class:SentinelProduct — the abstract container (path, driver, mission, product type, raw metadata, the subdataset list).
  • :func:open_product — sniffs the GDAL driver behind a path and returns the right concrete product (currently :class:~pyramids_eo.sentinel.s2.S2Product).

Nothing here subclasses Dataset: the readers return plain pyramids Dataset objects, and the product only describes what can be read (see the pyramids-eo/earthengine precedent — no engine objects leak into public types).

SentinelProduct #

Bases: ABC

A Sentinel product on disk — a catalog of openable rasters.

Concrete subclasses (:class:~pyramids_eo.sentinel.s2.S2Product, and a future S1Product) add the mission-specific model. This base holds only what every Sentinel product shares.

Attributes:

Name Type Description
path

The path (or connection root) the product was opened from.

driver

The GDAL driver short name ("SENTINEL2" / "SAFE").

metadata dict[str, str]

The container's default-domain metadata (Dataset.metadata).

subdatasets list[Any]

The pyramids SubDataset value objects the container exposes, each openable with .open().

Source code in src/pyramids_eo/sentinel/product.py
class SentinelProduct(abc.ABC):
    """A Sentinel product on disk — a catalog of openable rasters.

    Concrete subclasses (:class:`~pyramids_eo.sentinel.s2.S2Product`, and a
    future ``S1Product``) add the mission-specific model. This base holds only
    what every Sentinel product shares.

    Attributes:
        path: The path (or connection root) the product was opened from.
        driver: The GDAL driver short name (``"SENTINEL2"`` / ``"SAFE"``).
        metadata: The container's default-domain metadata (``Dataset.metadata``).
        subdatasets: The pyramids ``SubDataset`` value objects the container
            exposes, each openable with ``.open()``.
    """

    def __init__(self, path: str, container: Dataset) -> None:
        self.path = path
        self.driver = container.raster.GetDriver().ShortName
        self.metadata: dict[str, str] = dict(container.metadata or {})
        self.subdatasets: list[Any] = list(container.subdatasets)

    @property
    @abc.abstractmethod
    def mission(self) -> str:
        """Mission identifier, e.g. ``"sentinel-2"``."""

    @property
    @abc.abstractmethod
    def product_type(self) -> str:
        """Product type token, e.g. ``"S2MSI2A"`` / ``"GRD"``."""

    def __repr__(self) -> str:  # pragma: no cover - display only
        return (
            f"{type(self).__name__}(driver={self.driver!r}, "
            f"product_type={self.product_type!r}, subdatasets={len(self.subdatasets)})"
        )
mission abstractmethod property #

Mission identifier, e.g. "sentinel-2".

product_type abstractmethod property #

Product type token, e.g. "S2MSI2A" / "GRD".

open_connection(connection) #

Open a GDAL driver connection string as a pyramids Dataset.

A SubDataset.name from a zipped product — SENTINEL2_L2A:/vsizip/…:60m:EPSG_32632 — used to trip pyramids' archive auto-detection, which saw the embedded .zip and re-wrapped the whole string in a second /vsizip/. pyramids 0.57 fixed that (it no longer re-wraps an already-resolved /vsi path), so every connection now goes through Dataset.read_file — which also applies the cloud credentials and open options that a bare gdal.Open skipped for remote products.

Parameters:

Name Type Description Default
connection str

A GDAL connection string / path.

required

Returns:

Type Description
Dataset

The opened :class:~pyramids.dataset.Dataset.

Raises:

Type Description
ProductError

GDAL cannot open the connection.

Source code in src/pyramids_eo/sentinel/product.py
def open_connection(connection: str) -> Dataset:
    """Open a GDAL driver connection string as a pyramids ``Dataset``.

    A ``SubDataset.name`` from a zipped product —
    ``SENTINEL2_L2A:/vsizip/…:60m:EPSG_32632`` — used to trip pyramids' archive
    auto-detection, which saw the embedded ``.zip`` and re-wrapped the whole
    string in a second ``/vsizip/``. pyramids 0.57 fixed that (it no longer
    re-wraps an already-resolved ``/vsi`` path), so every connection now goes
    through ``Dataset.read_file`` — which also applies the cloud credentials and
    open options that a bare ``gdal.Open`` skipped for remote products.

    Args:
        connection: A GDAL connection string / path.

    Returns:
        The opened :class:`~pyramids.dataset.Dataset`.

    Raises:
        ProductError: GDAL cannot open the connection.
    """
    try:
        return Dataset.read_file(connection)
    except Exception as exc:  # noqa: BLE001 - re-raise as the package's error
        raise ProductError(f"GDAL could not open {connection!r}: {exc}") from exc

open_product(path) #

Open a Sentinel product and return its typed model.

Sniffs the GDAL driver behind path and dispatches to the concrete product class. Accepts a .SAFE directory, a product metadata XML, a manifest.safe, a .zip holding a .SAFE (opened in place), or a driver connection string.

Parameters:

Name Type Description Default
path str | Path

The product to open.

required

Returns:

Name Type Description
A SentinelProduct

class:SentinelProduct — currently an

SentinelProduct

class:~pyramids_eo.sentinel.s2.S2Product for Sentinel-2.

Raises:

Type Description
UnsupportedProductError

The path opens, but its driver is not a Sentinel product family this package models.

ProductError

The path cannot be opened as a product.

Examples:

  • Open a Level-2A product and inspect its subdatasets:
    >>> from pyramids_eo.sentinel import open_product  # doctest: +SKIP
    >>> product = open_product("S2A_..._MSIL2A.SAFE")   # doctest: +SKIP
    >>> product.product_type                            # doctest: +SKIP
    'S2MSI2A'
    
Source code in src/pyramids_eo/sentinel/product.py
def open_product(path: str | Path) -> SentinelProduct:
    """Open a Sentinel product and return its typed model.

    Sniffs the GDAL driver behind ``path`` and dispatches to the concrete
    product class. Accepts a ``.SAFE`` directory, a product metadata XML, a
    ``manifest.safe``, a ``.zip`` holding a ``.SAFE`` (opened in place), or a
    driver connection string.

    Args:
        path: The product to open.

    Returns:
        A :class:`SentinelProduct` — currently an
        :class:`~pyramids_eo.sentinel.s2.S2Product` for Sentinel-2.

    Raises:
        UnsupportedProductError: The path opens, but its driver is not a
            Sentinel product family this package models.
        ProductError: The path cannot be opened as a product.

    Examples:
        - Open a Level-2A product and inspect its subdatasets:
            ```python
            >>> from pyramids_eo.sentinel import open_product  # doctest: +SKIP
            >>> product = open_product("S2A_..._MSIL2A.SAFE")   # doctest: +SKIP
            >>> product.product_type                            # doctest: +SKIP
            'S2MSI2A'

            ```
    """
    container_path = _resolve_container_path(path)
    try:
        # A product metadata XML is a 0-band container by design -- that is what
        # we want to open, and what .subdatasets is then read from. pyramids 0.57
        # warns on such an open; silence it here so the warning does not fire on
        # every open_product, and so a consumer running warnings as errors does
        # not see it turn into the ProductError raised below.
        container = Dataset.read_file(container_path, warn_on_container=False)
    except Exception as exc:  # noqa: BLE001 - re-raise as the package's error
        raise ProductError(f"cannot open product {path!r}: {exc}") from exc

    driver = container.raster.GetDriver().ShortName
    family = _DRIVER_FAMILY.get(driver)
    if family == "s2":
        from pyramids_eo.sentinel.s2.product import S2Product

        return S2Product(str(path), container)
    if family == "s1":
        raise UnsupportedProductError(
            f"Sentinel-1 ({driver}) products are not yet modelled "
            "(planned as Phase 2); Sentinel-2 is supported today."
        )
    raise UnsupportedProductError(
        f"{driver!r} is not a Sentinel product driver this package models "
        f"(known: {sorted(_DRIVER_FAMILY)})."
    )

Sentinel-2#

pyramids_eo.sentinel.s2.reader #

Turnkey Sentinel-2 reader → a pyramids Dataset.

:func:from_sentinel2 mirrors the shape of :func:pyramids_eo.from_earthengine: one flat-keyword call that opens a Sentinel-2 product, picks the requested bands at a resolution, optionally converts DN → reflectance (as lazy scale/offset tags), masks cloud/shadow via the Scene-Classification band, and crops / reprojects — returning a plain pyramids Dataset with no Sentinel objects leaking out.

Built entirely on pyramids 0.64+ APIs: Dataset.subdatasets / open_subdataset for the catalog, Dataset.bands.select for band subsetting (1-based, or by name), Dataset.read_array() for the lazy reflectance read the scale/offset tags drive, and crop / to_crs for the spatial ops.

from_sentinel2(path, *, bands=None, resolution=None, epsg=None, bbox=None, crs=None, reflectance=True, mask_scl=None, resample='nearest', path_out=None) #

Read a Sentinel-2 product into a pyramids Dataset.

Parameters:

Name Type Description Default
path str | Path | S2Product

A product path (.SAFE / MTD_*.xml / .zip) or an already-open :class:S2Product.

required
bands list[str] | None

Band names to read (e.g. ["B04", "B08"]; B4 == B04). None reads every spectral band at the chosen resolution.

None
resolution int | None

Native resolution in metres (10 / 20 / 60). None picks the finest resolution whose subdataset carries all requested bands.

None
epsg int | None

UTM EPSG code, required only for a multi-zone product.

None
bbox BBox | None

Optional crop window (minx, miny, maxx, maxy) in the product's native CRS (cropping happens before any crs reprojection).

None
crs str | int | None

Optional target CRS (an EPSG integer or a WKT string) to reproject to.

None
reflectance bool

When True (default), tag the spectral bands so read_array() yields reflectance (DN + offset) / quantification (the baseline-≥04.00 offset is 0 on older products). The stored values stay DN; read_array(unpack=False) returns them unconverted.

True
mask_scl list[Any] | None

L2A only — classes to mask out (see :class:~pyramids_eo.sentinel.s2.masks.SclClass); masked pixels become no-data.

None
path_out str | Path | None

When given, also write the result there (COG by extension).

None

Returns:

Type Description
Any

A pyramids Dataset of the requested bands.

Note

No-data is declared in the DN domain (the GDAL convention). Because reflectance is applied as lazy scale / offset tags, the default read_array() returns DN * scale + offset for every pixel — so a DN no-data (and any SCL-masked pixel) reads back as the scaled sentinel, not the declared no_data_value. On a baseline-≥04.00 product (offset ≈ −1000) a DN-0 no-data reads as ≈ −0.1, not 0. Test for no-data against a read_array(unpack=False) read, not against a reflectance one.

Raises:

Type Description
ProductError

The product is missing a requested band / resolution, or a multi-zone product is read without epsg.

Examples:

  • Read the red and NIR bands as reflectance:
    >>> from pyramids_eo.sentinel import from_sentinel2  # doctest: +SKIP
    >>> ds = from_sentinel2("S2A_..._MSIL2A.SAFE",       # doctest: +SKIP
    ...                     bands=["B04", "B08"])        # doctest: +SKIP
    >>> reflectance = ds.read_array()                    # doctest: +SKIP
    
Source code in src/pyramids_eo/sentinel/s2/reader.py
def from_sentinel2(  # NOSONAR(S107) - flat keyword reader API mirroring from_earthengine
    path: str | Path | S2Product,
    *,
    bands: list[str] | None = None,
    resolution: int | None = None,
    epsg: int | None = None,
    bbox: BBox | None = None,
    crs: str | int | None = None,
    reflectance: bool = True,
    mask_scl: list[Any] | None = None,
    resample: str = "nearest",
    path_out: str | Path | None = None,
) -> Any:
    """Read a Sentinel-2 product into a pyramids ``Dataset``.

    Args:
        path: A product path (``.SAFE`` / ``MTD_*.xml`` / ``.zip``) or an
            already-open :class:`S2Product`.
        bands: Band names to read (e.g. ``["B04", "B08"]``; ``B4`` == ``B04``).
            ``None`` reads every spectral band at the chosen resolution.
        resolution: Native resolution in metres (10 / 20 / 60). ``None`` picks
            the finest resolution whose subdataset carries all requested bands.
        epsg: UTM EPSG code, required only for a multi-zone product.
        bbox: Optional crop window ``(minx, miny, maxx, maxy)`` in the product's
            native CRS (cropping happens before any ``crs`` reprojection).
        crs: Optional target CRS (an EPSG integer or a WKT string) to reproject to.
        reflectance: When ``True`` (default), tag the spectral bands so
            ``read_array()`` yields reflectance ``(DN + offset) / quantification``
            (the baseline-≥04.00 offset is 0 on older products). The stored values
            stay DN; ``read_array(unpack=False)`` returns them unconverted.
        mask_scl: L2A only — classes to mask out (see
            :class:`~pyramids_eo.sentinel.s2.masks.SclClass`); masked pixels
            become no-data.
        path_out: When given, also write the result there (COG by extension).

    Returns:
        A pyramids ``Dataset`` of the requested bands.

    Note:
        No-data is declared in the **DN domain** (the GDAL convention). Because
        reflectance is applied as lazy ``scale`` / ``offset`` tags, the default
        ``read_array()`` returns ``DN * scale + offset`` for *every* pixel — so a
        DN no-data (and any SCL-masked pixel) reads back as the *scaled*
        sentinel, not the declared ``no_data_value``. On a baseline-≥04.00
        product (offset ≈ −1000) a DN-0 no-data reads as ≈ −0.1, not 0. Test for
        no-data against a ``read_array(unpack=False)`` read, not against a
        reflectance one.

    Raises:
        ProductError: The product is missing a requested band / resolution, or
            a multi-zone product is read without ``epsg``.

    Examples:
        - Read the red and NIR bands as reflectance:
            ```python
            >>> from pyramids_eo.sentinel import from_sentinel2  # doctest: +SKIP
            >>> ds = from_sentinel2("S2A_..._MSIL2A.SAFE",       # doctest: +SKIP
            ...                     bands=["B04", "B08"])        # doctest: +SKIP
            >>> reflectance = ds.read_array()                    # doctest: +SKIP

            ```
    """
    product = path if isinstance(path, S2Product) else open_product(path)
    if not isinstance(
        product, S2Product
    ):  # pragma: no cover - open_product guarantees it
        raise ProductError(f"{path!r} is not a Sentinel-2 product")

    epsg = _resolve_epsg(product, epsg)
    wanted = _resolve_bands(product, bands, resolution, epsg)
    dataset, target_res, offsets = _read(product, wanted, resolution, epsg, resample)
    _set_nodata(dataset, product)

    # Do every DN-domain transform first (mask, crop, reproject), then tag
    # reflectance LAST. The mask's rebuild and pyramids `crop` both reset
    # per-band scale/offset (only `to_crs` / `to_file` preserve them), so tags
    # applied earlier would be silently dropped — tagging last guarantees the
    # returned dataset carries the calibration. `offsets` is captured from the
    # original read and passed through, so tagging after a crop stays correct.
    if mask_scl:
        dataset = _apply_scl_mask(dataset, product, target_res, epsg, mask_scl)
    if bbox is not None:
        dataset = _crop_to_bbox(dataset, bbox)
    if crs is not None:
        dataset = dataset.to_crs(crs)
    if reflectance:
        dataset = _scaling.tag_reflectance(
            dataset,
            product,
            offsets=offsets,
            spectral=[is_spectral_band(b) for b in wanted],
        )
    if path_out is not None:
        dataset.to_file(str(path_out))
    return dataset

collection_from_sentinel2(paths, *, root_dir, **kwargs) #

Read a time series of Sentinel-2 products into a DatasetCollection.

Each product in paths is read with :func:from_sentinel2 (passing **kwargs through) and written as a GeoTIFF under root_dir; the written files are then assembled into a DatasetCollection.

The collection is file-backed on purpose, for the two things that still need it on pyramids-core >= 0.73.0: DatasetCollection.to_zarr and to_kerchunk require a file-backed collection outright, and out-of-core scale depends on it — the in-memory cube reads each scene's array eagerly (only the time stack is lazy), whereas a file-backed collection reads tile-by-tile, so a series larger than RAM stays readable. Time-axis reductions no longer need it: since pyramids-core 0.73.0 they also run on a resident datasets= collection, which is what :func:collection_from_earthengine returns.

Parameters:

Name Type Description Default
paths Sequence[str | Path]

The Sentinel-2 products (any form :func:from_sentinel2 accepts).

required
root_dir str | Path

Directory the per-scene GeoTIFFs are written to (created if absent).

required
**kwargs Any

Forwarded to :func:from_sentinel2 (bands / resolution / epsg / reflectance / mask_scl / …), applied to every scene.

{}

Returns:

Type Description
Any

A pyramids.dataset.DatasetCollection over the written scenes.

Raises:

Type Description
ProductError

paths is empty.

Source code in src/pyramids_eo/sentinel/s2/reader.py
def collection_from_sentinel2(
    paths: Sequence[str | Path],
    *,
    root_dir: str | Path,
    **kwargs: Any,
) -> Any:
    """Read a time series of Sentinel-2 products into a ``DatasetCollection``.

    Each product in ``paths`` is read with :func:`from_sentinel2` (passing
    ``**kwargs`` through) and written as a GeoTIFF under ``root_dir``; the
    written files are then assembled into a ``DatasetCollection``.

    The collection is **file-backed on purpose**, for the two things that still
    need it on ``pyramids-core`` >= 0.73.0: ``DatasetCollection.to_zarr`` and
    ``to_kerchunk`` require a file-backed collection outright, and out-of-core scale
    depends on it — the in-memory cube reads each scene's array eagerly (only the
    time stack is lazy), whereas a file-backed collection reads tile-by-tile, so a
    series larger than RAM stays readable. Time-axis **reductions** no longer need
    it: since ``pyramids-core`` 0.73.0 they also run on a resident ``datasets=``
    collection, which is what :func:`collection_from_earthengine` returns.

    Args:
        paths: The Sentinel-2 products (any form :func:`from_sentinel2` accepts).
        root_dir: Directory the per-scene GeoTIFFs are written to (created if
            absent).
        **kwargs: Forwarded to :func:`from_sentinel2` (``bands`` / ``resolution``
            / ``epsg`` / ``reflectance`` / ``mask_scl`` / …), applied to every
            scene.

    Returns:
        A ``pyramids.dataset.DatasetCollection`` over the written scenes.

    Raises:
        ProductError: ``paths`` is empty.
    """
    from pyramids.dataset import DatasetCollection

    products = list(paths)
    if not products:
        raise ProductError("collection_from_sentinel2: no product paths given")
    if "path_out" in kwargs:
        raise ProductError(
            "collection_from_sentinel2 manages per-scene output itself; pass "
            "root_dir=, not path_out= (it is set per scene)."
        )

    root = Path(root_dir)
    root.mkdir(parents=True, exist_ok=True)
    written: list[Path] = []
    for index, product_path in enumerate(products):
        out = root / f"{_scene_stem(product_path, index)}.tif"
        from_sentinel2(product_path, path_out=out, **kwargs)
        written.append(out)
    return DatasetCollection.from_files(written)

pyramids_eo.sentinel.s2.product #

Sentinel-2 product model — parses one MSI product into a typed catalog.

The GDAL SENTINEL2 driver exposes a product as subdatasets, one per resolution × UTM zone (10 m / 20 m / 60 m) plus preview / true-colour views. :class:S2Product reads that layout plus the product metadata block into a queryable model: which bands live at which resolution, the processing baseline and quantification value needed to turn DN into reflectance, cloud cover, and the footprint.

It holds no pixels — :meth:S2Product.subdataset_for hands back a pyramids SubDataset you open on demand, and the reader (:func:pyramids_eo.sentinel.s2.reader.from_sentinel2) drives it.

S2Level #

Bases: StrEnum

Sentinel-2 processing level.

Source code in src/pyramids_eo/sentinel/s2/product.py
class S2Level(StrEnum):
    """Sentinel-2 processing level."""

    L1B = "L1B"
    L1C = "L1C"
    L2A = "L2A"

S2Subdataset #

One resolution × UTM-zone image subdataset of an S2 product.

A thin typed wrapper over the pyramids SubDataset value object, adding the parsed resolution / EPSG / band list. Open it with :meth:open.

Attributes:

Name Type Description
resolution_m

Native ground sampling distance in metres (10 / 20 / 60).

epsg

UTM EPSG code of the subdataset.

bands

Band names the subdataset carries, in driver order (spectral B* plus any derived layers such as AOT / SCL).

Source code in src/pyramids_eo/sentinel/s2/product.py
class S2Subdataset:
    """One resolution × UTM-zone image subdataset of an S2 product.

    A thin typed wrapper over the pyramids ``SubDataset`` value object, adding
    the parsed resolution / EPSG / band list. Open it with :meth:`open`.

    Attributes:
        resolution_m: Native ground sampling distance in metres (10 / 20 / 60).
        epsg: UTM EPSG code of the subdataset.
        bands: Band names the subdataset carries, in driver order (spectral
            ``B*`` plus any derived layers such as ``AOT`` / ``SCL``).
    """

    def __init__(
        self, subdataset: Any, resolution_m: int, epsg: int | None, bands: list[str]
    ) -> None:
        self._sd = subdataset
        self.resolution_m = resolution_m
        self.epsg = epsg
        self.bands = bands

    @property
    def connection(self) -> str:
        """The GDAL connection string for this subdataset."""
        return str(self._sd.name)

    def open(self) -> Any:
        """Open the subdataset as a pyramids ``Dataset``."""
        return open_connection(self._sd.name)

    def __repr__(self) -> str:  # pragma: no cover - display only
        return f"S2Subdataset({self.resolution_m}m, EPSG:{self.epsg}, {len(self.bands)} bands)"
connection property #

The GDAL connection string for this subdataset.

open() #

Open the subdataset as a pyramids Dataset.

Source code in src/pyramids_eo/sentinel/s2/product.py
def open(self) -> Any:
    """Open the subdataset as a pyramids ``Dataset``."""
    return open_connection(self._sd.name)

S2Product #

Bases: SentinelProduct

A parsed Sentinel-2 MSI product (L1C / L2A; L1B partially).

Built by :func:pyramids_eo.sentinel.open_product. Exposes the product's structure and the metadata a reader needs to calibrate it.

Attributes:

Name Type Description
level

The :class:S2Level.

baseline

Processing baseline string (e.g. "05.09"); "" if absent. Baselines >= 04.00 carry a radiometric offset.

quantification

DN → reflectance divisor (L2A_BOA / L1C_TOA quantification value).

cloud_cover

Scene cloud-cover percentage, or None.

footprint

Product footprint as a WKT polygon string, or "".

resolutions list[int]

Sorted native resolutions present (metres).

epsg_codes list[int]

Sorted UTM EPSG codes present.

Source code in src/pyramids_eo/sentinel/s2/product.py
class S2Product(SentinelProduct):
    """A parsed Sentinel-2 MSI product (L1C / L2A; L1B partially).

    Built by :func:`pyramids_eo.sentinel.open_product`. Exposes the product's
    structure and the metadata a reader needs to calibrate it.

    Attributes:
        level: The :class:`S2Level`.
        baseline: Processing baseline string (e.g. ``"05.09"``); ``""`` if
            absent. Baselines ``>= 04.00`` carry a radiometric offset.
        quantification: DN → reflectance divisor (``L2A_BOA`` / ``L1C_TOA``
            quantification value).
        cloud_cover: Scene cloud-cover percentage, or ``None``.
        footprint: Product footprint as a WKT polygon string, or ``""``.
        resolutions: Sorted native resolutions present (metres).
        epsg_codes: Sorted UTM EPSG codes present.
    """

    def __init__(self, path: str, container: Any) -> None:
        super().__init__(path, container)
        self._image_subdatasets: list[S2Subdataset] = []
        self._preview: list[Any] = []
        self._parse_subdatasets()
        if not self._image_subdatasets:
            raise ProductError(
                f"no Sentinel-2 image subdatasets found in {path!r}; "
                "is this a valid MSI product?"
            )
        self.level = self._resolve_level()
        self.baseline = self.metadata.get("PROCESSING_BASELINE", "")
        self.quantification = self._resolve_quantification()
        self.cloud_cover = _as_float(self.metadata.get("CLOUD_COVERAGE_ASSESSMENT"))
        self.footprint = self.metadata.get("FOOTPRINT", "")

    # -- construction ------------------------------------------------------

    def _parse_subdatasets(self) -> None:
        """Split the raw subdatasets into image vs preview, parsing each."""
        for sd in self.subdatasets:
            conn = _connection.parse_s2(sd.name)
            token = conn.resolution.upper()
            if token in _NON_SPECTRAL:
                self._preview.append(sd)
                continue
            resolution_m = _resolution_metres(conn.resolution)
            if resolution_m is None:
                self._preview.append(sd)
                continue
            self._image_subdatasets.append(
                S2Subdataset(sd, resolution_m, conn.epsg, _bands_of(sd.description))
            )

    def _resolve_level(self) -> S2Level:
        """Derive the processing level from the subdataset connection prefix."""
        level_token = _connection.parse_s2(self.subdatasets[0].name).level
        try:
            return S2Level(level_token)
        except ValueError as exc:
            raise ProductError(f"unknown Sentinel-2 level {level_token!r}") from exc

    def _resolve_quantification(self) -> float:
        """Pick the level-appropriate quantification value from metadata."""
        keys = ("L2A_BOA_QUANTIFICATION_VALUE", "L1C_TOA_QUANTIFICATION_VALUE")
        for key in keys:
            value = _as_float(self.metadata.get(key))
            if value:
                return value
        return _DEFAULT_QUANTIFICATION

    # -- public surface ----------------------------------------------------

    @property
    def mission(self) -> str:
        """Mission identifier."""
        return "sentinel-2"

    @property
    def product_type(self) -> str:
        """Product type token (e.g. ``"S2MSI2A"``), or a fallback from the level.

        The fallback drops the ``L`` from the level (``L2A`` -> ``S2MSI2A``) to
        match ESA's canonical token, rather than emitting ``S2MSIL2A``.
        """
        return self.metadata.get("PRODUCT_TYPE", f"S2MSI{self.level.value[1:]}")

    @property
    def resolutions(self) -> list[int]:
        """Sorted native resolutions present in the product (metres)."""
        return sorted({sd.resolution_m for sd in self._image_subdatasets})

    @property
    def epsg_codes(self) -> list[int]:
        """Sorted UTM EPSG codes present in the product."""
        return sorted(
            {sd.epsg for sd in self._image_subdatasets if sd.epsg is not None}
        )

    @property
    def image_subdatasets(self) -> list[S2Subdataset]:
        """The spectral / derived image subdatasets (excludes preview / TCI)."""
        return list(self._image_subdatasets)

    def resolution_of(self, band: str) -> int:
        """Return the finest native resolution (m) that carries ``band``.

        Args:
            band: Band name, e.g. ``"B04"`` (matched case-insensitively; a bare
                ``"B4"`` also matches ``"B04"``).

        Returns:
            The finest resolution in metres offering the band.

        Raises:
            ProductError: The band is not present in the product.
        """
        candidates = [
            sd.resolution_m
            for sd in self._image_subdatasets
            if _has_band(sd.bands, band)
        ]
        if not candidates:
            raise ProductError(
                f"band {band!r} not in product; available: {sorted(self.available_bands)}"
            )
        return min(candidates)

    @property
    def available_bands(self) -> set[str]:
        """Every band name present across the product's image subdatasets."""
        return {b for sd in self._image_subdatasets for b in sd.bands}

    def subdataset_for(
        self, resolution_m: int, epsg: int | None = None
    ) -> S2Subdataset:
        """Return the image subdataset at ``resolution_m`` (and ``epsg``).

        Args:
            resolution_m: Native resolution in metres (10 / 20 / 60).
            epsg: UTM EPSG code to disambiguate a multi-zone product. ``None``
                is allowed only when the product has a single zone.

        Returns:
            The matching :class:`S2Subdataset`.

        Raises:
            ProductError: No unique subdataset matches.
        """
        matches = [
            sd
            for sd in self._image_subdatasets
            if sd.resolution_m == resolution_m and (epsg is None or sd.epsg == epsg)
        ]
        if not matches:
            raise ProductError(
                f"no {resolution_m}m subdataset"
                + (f" for EPSG:{epsg}" if epsg else "")
                + f"; resolutions present: {self.resolutions}"
            )
        if len(matches) > 1:
            raise ProductError(
                f"{resolution_m}m is ambiguous across EPSG {self.epsg_codes}; "
                "pass epsg=."
            )
        return matches[0]
mission property #

Mission identifier.

product_type property #

Product type token (e.g. "S2MSI2A"), or a fallback from the level.

The fallback drops the L from the level (L2A -> S2MSI2A) to match ESA's canonical token, rather than emitting S2MSIL2A.

resolutions property #

Sorted native resolutions present in the product (metres).

epsg_codes property #

Sorted UTM EPSG codes present in the product.

image_subdatasets property #

The spectral / derived image subdatasets (excludes preview / TCI).

available_bands property #

Every band name present across the product's image subdatasets.

resolution_of(band) #

Return the finest native resolution (m) that carries band.

Parameters:

Name Type Description Default
band str

Band name, e.g. "B04" (matched case-insensitively; a bare "B4" also matches "B04").

required

Returns:

Type Description
int

The finest resolution in metres offering the band.

Raises:

Type Description
ProductError

The band is not present in the product.

Source code in src/pyramids_eo/sentinel/s2/product.py
def resolution_of(self, band: str) -> int:
    """Return the finest native resolution (m) that carries ``band``.

    Args:
        band: Band name, e.g. ``"B04"`` (matched case-insensitively; a bare
            ``"B4"`` also matches ``"B04"``).

    Returns:
        The finest resolution in metres offering the band.

    Raises:
        ProductError: The band is not present in the product.
    """
    candidates = [
        sd.resolution_m
        for sd in self._image_subdatasets
        if _has_band(sd.bands, band)
    ]
    if not candidates:
        raise ProductError(
            f"band {band!r} not in product; available: {sorted(self.available_bands)}"
        )
    return min(candidates)
subdataset_for(resolution_m, epsg=None) #

Return the image subdataset at resolution_m (and epsg).

Parameters:

Name Type Description Default
resolution_m int

Native resolution in metres (10 / 20 / 60).

required
epsg int | None

UTM EPSG code to disambiguate a multi-zone product. None is allowed only when the product has a single zone.

None

Returns:

Type Description
S2Subdataset

The matching :class:S2Subdataset.

Raises:

Type Description
ProductError

No unique subdataset matches.

Source code in src/pyramids_eo/sentinel/s2/product.py
def subdataset_for(
    self, resolution_m: int, epsg: int | None = None
) -> S2Subdataset:
    """Return the image subdataset at ``resolution_m`` (and ``epsg``).

    Args:
        resolution_m: Native resolution in metres (10 / 20 / 60).
        epsg: UTM EPSG code to disambiguate a multi-zone product. ``None``
            is allowed only when the product has a single zone.

    Returns:
        The matching :class:`S2Subdataset`.

    Raises:
        ProductError: No unique subdataset matches.
    """
    matches = [
        sd
        for sd in self._image_subdatasets
        if sd.resolution_m == resolution_m and (epsg is None or sd.epsg == epsg)
    ]
    if not matches:
        raise ProductError(
            f"no {resolution_m}m subdataset"
            + (f" for EPSG:{epsg}" if epsg else "")
            + f"; resolutions present: {self.resolutions}"
        )
    if len(matches) > 1:
        raise ProductError(
            f"{resolution_m}m is ambiguous across EPSG {self.epsg_codes}; "
            "pass epsg=."
        )
    return matches[0]

is_spectral_band(name) #

True for a spectral MSI band (B01…B12, B8A); False for auxiliary layers (AOT / CLD / SCL / SNW / WVP / TCI).

A spectral band is B followed by a digit (so B8A counts, BAND does not).

Parameters:

Name Type Description Default
name str

A band name, e.g. "B04" or "SCL".

required

Returns:

Type Description
bool

True when name is a spectral band, else False.

Examples:

  • Numbered bands and the B8A red-edge band are spectral:
    >>> from pyramids_eo.sentinel.s2.product import is_spectral_band
    >>> is_spectral_band("B04")
    True
    >>> is_spectral_band("B8A")
    True
    
  • Auxiliary layers are not spectral:
    >>> from pyramids_eo.sentinel.s2.product import is_spectral_band
    >>> [is_spectral_band(b) for b in ("SCL", "AOT", "WVP")]
    [False, False, False]
    
Source code in src/pyramids_eo/sentinel/s2/product.py
def is_spectral_band(name: str) -> bool:
    """True for a spectral MSI band (``B01``…``B12``, ``B8A``); False for
    auxiliary layers (``AOT`` / ``CLD`` / ``SCL`` / ``SNW`` / ``WVP`` / ``TCI``).

    A spectral band is ``B`` followed by a digit (so ``B8A`` counts, ``BAND``
    does not).

    Args:
        name: A band name, e.g. ``"B04"`` or ``"SCL"``.

    Returns:
        ``True`` when ``name`` is a spectral band, else ``False``.

    Examples:
        - Numbered bands and the ``B8A`` red-edge band are spectral:
            ```python
            >>> from pyramids_eo.sentinel.s2.product import is_spectral_band
            >>> is_spectral_band("B04")
            True
            >>> is_spectral_band("B8A")
            True

            ```
        - Auxiliary layers are not spectral:
            ```python
            >>> from pyramids_eo.sentinel.s2.product import is_spectral_band
            >>> [is_spectral_band(b) for b in ("SCL", "AOT", "WVP")]
            [False, False, False]

            ```
    """
    text = name.strip().upper()
    return text.startswith("B") and len(text) > 1 and text[1].isdigit()

pyramids_eo.sentinel.s2.masks #

Scene-Classification (SCL) masking for Sentinel-2 Level-2A.

L2A carries a Scene Classification band whose integer codes label each pixel (cloud, shadow, water, vegetation, …). The GDAL SENTINEL2 driver attaches the class names as band category names; :class:SclClass mirrors them as a typed enum so a mask reads [SclClass.CLOUD_HIGH_PROBA, SclClass.CLOUD_SHADOW] rather than [9, 3].

:func:scl_mask sets the masked-out pixels to the dataset's no-data value. Because category names survive reprojection since pyramids #1024, masking may run before or after a warp — order is a convenience, not a correctness rule.

SclClass #

Bases: IntEnum

Sentinel-2 L2A Scene-Classification codes (GDAL category names).

Each member's value is the integer pixel code the SCL band stores, so a member can be used directly as a class selector or compared with a raw code.

Examples:

  • A member carries the SCL pixel code and its name:
    >>> from pyramids_eo.sentinel.s2.masks import SclClass
    >>> SclClass.CLOUD_HIGH_PROBA.value
    9
    >>> SclClass.WATER.name
    'WATER'
    
  • Build a cloud/shadow mask selection and read back the codes:
    >>> from pyramids_eo.sentinel.s2.masks import SclClass
    >>> clouds = [SclClass.CLOUD_MEDIUM_PROBA, SclClass.CLOUD_HIGH_PROBA]
    >>> [int(c) for c in clouds]
    [8, 9]
    
Source code in src/pyramids_eo/sentinel/s2/masks.py
class SclClass(IntEnum):
    """Sentinel-2 L2A Scene-Classification codes (GDAL category names).

    Each member's value is the integer pixel code the SCL band stores, so a
    member can be used directly as a class selector or compared with a raw code.

    Examples:
        - A member carries the SCL pixel code and its name:
            ```python
            >>> from pyramids_eo.sentinel.s2.masks import SclClass
            >>> SclClass.CLOUD_HIGH_PROBA.value
            9
            >>> SclClass.WATER.name
            'WATER'

            ```
        - Build a cloud/shadow mask selection and read back the codes:
            ```python
            >>> from pyramids_eo.sentinel.s2.masks import SclClass
            >>> clouds = [SclClass.CLOUD_MEDIUM_PROBA, SclClass.CLOUD_HIGH_PROBA]
            >>> [int(c) for c in clouds]
            [8, 9]

            ```
    """

    NODATA = 0
    SATURATED_DEFECTIVE = 1
    DARK_FEATURE_SHADOW = 2
    CLOUD_SHADOW = 3
    VEGETATION = 4
    BARE_SOIL_DESERT = 5
    WATER = 6
    CLOUD_LOW_PROBA = 7
    CLOUD_MEDIUM_PROBA = 8
    CLOUD_HIGH_PROBA = 9
    THIN_CIRRUS = 10
    SNOW_ICE = 11

scl_mask(dataset, classes, *, scl=None) #

Mask dataset pixels whose SCL class is in classes.

Masked pixels are set to the dataset's no-data value across every band. The SCL source is either an explicit scl (a single-band pyramids Dataset or a 2-D NumPy array on the same grid), or — when scl is None — an SCL band found within dataset itself.

Parameters:

Name Type Description Default
dataset Any

The pyramids Dataset to mask.

required
classes Sequence[SclClass | str | int]

Classes to mask out (see :func:_resolve_classes), e.g. [SclClass.CLOUD_HIGH_PROBA, SclClass.CLOUD_SHADOW].

required
scl Any

Optional explicit SCL source aligned to dataset's grid. When None, an SCL band inside dataset is used.

None

Returns:

Type Description
Any

A new pyramids Dataset with the masked pixels set to no-data; band

Any

names, no-data value, and scale/offset tags are preserved.

Raises:

Type Description
ProductError

No SCL source is available, or its shape does not match dataset.

Source code in src/pyramids_eo/sentinel/s2/masks.py
def scl_mask(
    dataset: Any,
    classes: Sequence[SclClass | str | int],
    *,
    scl: Any = None,
) -> Any:
    """Mask ``dataset`` pixels whose SCL class is in ``classes``.

    Masked pixels are set to the dataset's no-data value across every band. The
    SCL source is either an explicit ``scl`` (a single-band pyramids ``Dataset``
    or a 2-D NumPy array on the same grid), or — when ``scl`` is ``None`` — an
    ``SCL`` band found within ``dataset`` itself.

    Args:
        dataset: The pyramids ``Dataset`` to mask.
        classes: Classes to mask out (see :func:`_resolve_classes`), e.g.
            ``[SclClass.CLOUD_HIGH_PROBA, SclClass.CLOUD_SHADOW]``.
        scl: Optional explicit SCL source aligned to ``dataset``'s grid. When
            ``None``, an ``SCL`` band inside ``dataset`` is used.

    Returns:
        A new pyramids ``Dataset`` with the masked pixels set to no-data; band
        names, no-data value, and scale/offset tags are preserved.

    Raises:
        ProductError: No SCL source is available, or its shape does not match
            ``dataset``.
    """
    from pyramids.dataset import Dataset, GeoReference

    codes = _resolve_classes(classes)
    scl_array = _scl_array(dataset, scl)

    # read_array returns (rows, cols) for one band and (bands, rows, cols) for
    # many; normalise a single band to (1, rows, cols) so the mask indexing and
    # the shape check below are uniform. (np.atleast_3d would wrongly append the
    # band axis, giving (rows, cols, 1).)
    # Read the store, not physical units: this masks in the DN domain -- it
    # writes the raw no-data into the array, casts back to the source dtype and
    # carries the scale/offset onto the result. pyramids >=0.62 unpacks by
    # default, so a caller masking an already-tagged dataset would otherwise get
    # reflectance here and have the calibration applied a second time.
    data = np.asarray(dataset.read_array(unpack=False))
    if data.ndim == 2:
        data = data[np.newaxis, ...]
    if scl_array.shape != data.shape[-2:]:
        raise ProductError(
            f"SCL grid {scl_array.shape} does not match data grid {data.shape[-2:]}"
        )

    nodata = _nodata_of(dataset)
    mask = np.isin(scl_array, list(codes))
    masked = data.astype("float64", copy=True)
    masked[:, mask] = nodata

    # Pass no_data_value at creation so pyramids does not apply (and warn about)
    # its default -9999 sentinel, which is out of range for the uint16 dtype.
    out = Dataset.from_array(
        arr=masked.astype(data.dtype, copy=False),
        geo_ref=GeoReference(geo=dataset.raster.GetGeoTransform(), epsg=dataset.epsg),
        no_data_value=nodata,
    )
    _carry_band_state(dataset, out)
    return out

pyramids_eo.sentinel.s2.scaling #

DN → reflectance as lazy scale/offset tags, not an eager float array.

Sentinel-2 stores reflectance as scaled integers: reflectance = (DN + offset) / quantification, where quantification is the product's L2A_BOA / L1C_TOA quantification value and offset is the per-band radiometric offset that processing baselines >= 04.00 introduced (BOA_ADD_OFFSET / RADIO_ADD_OFFSET; 0 before that).

The GDAL SENTINEL2 driver surfaces the offset in per-band metadata (Dataset.band_metadata[i]), which is where :func:_band_offset reads it — verified end-to-end against a real baseline-05.09 product (offset -1000 flows into read_array(); see test_baseline_509_*), not just the offset parser.

Rather than materialise a float array, :func:tag_reflectance records the conversion on the dataset's GDAL scale/offset so it is applied lazily by Dataset.read_array(). The tags ride through to_crs and to_file, but this reader's own _crop_to_bbox and the SCL mask both rebuild the raster through from_array, which drops them — so the reader applies :func:tag_reflectance as the last step, after any crop / reproject / mask. In GDAL's real = DN * scale + offset terms:

scale  = 1 / quantification
offset = band_offset / quantification

Only spectral B* bands are tagged; classification / auxiliary bands (SCL / CLD / AOT / …) keep scale=1, offset=0 — they are not reflectance.

tag_reflectance(dataset, product, *, offsets=None, spectral=None) #

Tag dataset's spectral bands so a scaled read yields reflectance.

Sets per-band GDAL scale/offset on dataset in place and returns it. Spectral bands get scale = 1/quantification and offset = band_offset/quantification; every other band is left at scale=1, offset=0. The reflectance is then obtained lazily with dataset.read_array(); read_array(unpack=False) still returns DN.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset of Sentinel-2 bands (must be writable — e.g. the result of Dataset.bands.select or a MEM copy).

required
product S2Product

The :class:S2Product supplying the quantification value.

required
offsets list[float] | None

Optional per-band radiometric offsets, in band order. Passed by the reader (captured from the original read) so tagging does not depend on the driver's BOA_ADD_OFFSET metadata, which a crop / stack rebuild drops. None reads the offsets from each band's metadata.

None
spectral list[bool] | None

Optional per-band True/False (spectral vs auxiliary), in band order. Passed by the reader (computed from the requested band names) so tagging survives a crop — which strips the band metadata tag_reflectance would otherwise classify from. None classifies each band from its BANDNAME / display name.

None

Returns:

Type Description
Any

The same dataset, tagged.

Note

The tags do not touch the no_data_value, which stays in the DN domain. A scaled read therefore returns DN * scale + offset for the no-data pixels too — compare against the raw no-data value, not a scaled one (see :func:~pyramids_eo.sentinel.from_sentinel2).

Raises:

Type Description
ProductError

The product's quantification value is zero / unusable.

Source code in src/pyramids_eo/sentinel/s2/scaling.py
def tag_reflectance(
    dataset: Any,
    product: S2Product,
    *,
    offsets: list[float] | None = None,
    spectral: list[bool] | None = None,
) -> Any:
    """Tag ``dataset``'s spectral bands so a scaled read yields reflectance.

    Sets per-band GDAL scale/offset on ``dataset`` in place and returns it.
    Spectral bands get ``scale = 1/quantification`` and
    ``offset = band_offset/quantification``; every other band is left at
    ``scale=1, offset=0``. The reflectance is then obtained lazily with
    ``dataset.read_array()``; ``read_array(unpack=False)`` still returns DN.

    Args:
        dataset: A pyramids ``Dataset`` of Sentinel-2 bands (must be writable —
            e.g. the result of ``Dataset.bands.select`` or a MEM copy).
        product: The :class:`S2Product` supplying the quantification value.
        offsets: Optional per-band radiometric offsets, in band order. Passed by
            the reader (captured from the original read) so tagging does not
            depend on the driver's ``BOA_ADD_OFFSET`` metadata, which a crop /
            stack rebuild drops. ``None`` reads the offsets from each band's
            metadata.
        spectral: Optional per-band ``True``/``False`` (spectral vs auxiliary),
            in band order. Passed by the reader (computed from the requested
            band names) so tagging survives a ``crop`` — which strips the band
            metadata ``tag_reflectance`` would otherwise classify from. ``None``
            classifies each band from its ``BANDNAME`` / display name.

    Returns:
        The same ``dataset``, tagged.

    Note:
        The tags do not touch the ``no_data_value``, which stays in the DN
        domain. A scaled read therefore returns ``DN * scale + offset`` for the
        no-data pixels too — compare against the raw no-data value, not a scaled
        one (see :func:`~pyramids_eo.sentinel.from_sentinel2`).

    Raises:
        ProductError: The product's quantification value is zero / unusable.
    """
    quant = product.quantification
    if not quant:
        from pyramids_eo.errors import ProductError

        raise ProductError("product has no usable quantification value")

    band_names = dataset.band_names
    band_meta = dataset.band_metadata
    scales: list[float] = []
    tagged_offsets: list[float] = []
    for i, name in enumerate(band_names):
        meta_i = band_meta[i] if i < len(band_meta) else {}
        # Prefer the explicit spectral flag (survives crop's metadata reset);
        # else classify from the driver's BANDNAME, falling back to the name.
        if spectral is not None:
            is_spec = spectral[i]
        else:
            is_spec = is_spectral_band(meta_i.get("BANDNAME") or name)
        if is_spec:
            band_offset = offsets[i] if offsets is not None else _band_offset(meta_i)
            scales.append(1.0 / quant)
            tagged_offsets.append(band_offset / quant)
        else:
            scales.append(1.0)
            tagged_offsets.append(0.0)

    dataset.scale = scales
    dataset.offset = tagged_offsets
    _stamp_baseline(dataset, product)
    return dataset