Skip to content

Sensors — Readers#

Instrument readers that decode L1 formats into calibrated, geolocated pyramids Datasets. For real MTG-FCI L1C FDHSI granules use read_fci_l1c: it decodes the packed radiance from the nested data/<channel>/measured groups, reads the per-granule calibration coefficients, and stitches the chunks by their geostationary geotransform Y origin (validated on real MTI1/Meteosat-12 granules — see issue #40). Read several channels in one call with channels=[...], which returns a dict[str, Dataset] and reads each chunk's structure and coefficients once for the whole set (e.g. the red/blue/near-IR bands of a true-colour composite); available_channels(chunks) lists which channels the chunk set carries (it also accepts a single chunk path). open_fci_l1c_chunk is the lower-level radiance opener for use with the generic read_fci (which also accepts channels=[...]).

For MSG-SEVIRI Level-1.5 native (.nat) granules use read_seviri: it decodes a VIS/IR channel's 10-bit packed counts, applies the granule's per-channel Cal_Slope / Cal_Offset and the registry calibration, and returns the scene north-up on the 3 km geostationary grid (validated on a real Meteosat-10 granule — see issue #40). parse_seviri_native is the underlying .nat decoder, and a custom parse callable can still be injected.

For Himawari-8/9 AHI Himawari Standard Data (.DAT) granules use read_ahi: it walks the 11 self-describing HSD header blocks, decodes the band's 16-bit counts, applies the granule's own count-to-radiance slope / intercept, masks the error (65535) and outside-scan (65534) sentinel counts, and returns the band north-up on its geostationary grid. Calibration prefers the coefficients the granule carries over the registry's nominal table: a solar band (1-6) uses the granule's c' as its band solar irradiance, and a thermal band (7-16) inverts Planck's law with the granule's own c / h / k and applies its quadratic Tb = c0 + c1*Te + c2*Te^2 correction — which the registry's linear alpha / beta form cannot express.

A granule names its own band, so band is optional and merely asserts the expectation. A full disk ships as 10 segment files; pass the segment paths of one band together and they are stitched by their block #7 first-line numbers, with a gap or a duplicate reported rather than silently left blank. A contiguous subset is accepted too and returns only the lines it covers, georeferenced where they belong in the disk — so a partial download reads as the band of the disk it actually covers; completeness is not required, only contiguity. A single segment reads on its own the same way. .DAT.bz2 granules are decompressed transparently.

The segments must come from one acquisition. Line numbers alone do not establish that, because every timeline numbers its segments identically — two scenes ten minutes apart would otherwise stitch into a seamless-looking image of two different moments. read_ahi therefore checks the satellite, the observation timeline and area, the declared segment count, and the projection block, and refuses a mixed set.

Note it does not require the segments to share an observation start time. AHI scans the disk progressively, so each segment carries its own: on a real band-13 full disk, segments 1 and 10 start 526.0 s apart. The start times are only required to fall within an hour of each other, which separates the same timeline on different days without rejecting a legitimate scan.

from pyramids_eo.sensors.readers import read_ahi

# one segment, calibrated to brightness temperature
bt = read_ahi("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")

# a stitched full disk from its 10 segments
import glob
disk = read_ahi(sorted(glob.glob("HS_H08_20150415_0230_B13_FLDK_R20_S*.DAT")))

parse_ahi_hsd is the underlying decoder, returning uncalibrated radiance, and parse_hsd_header exposes the granule's grid, projection and calibration without reading its pixels.

Because HSD carries no per-granule solar irradiance for the reflective bands in a form the registry can hold, ahi.yaml deliberately omits solar_irradiance: a solar calibration attempted without a granule raises CalibrationError rather than quietly using a value from elsewhere. See the table's own header for the provenance of every constant in it.

One unit detail matters if you supply your own thermal coefficients or hand read_ahi a Dataset you built yourself. HSD is micrometre-based throughout: block #5 field 4 holds 10.4 for band 13 (not 1.04e-05), and the slope and intercept of the same block give radiance per micrometre, W / (m2 sr um). The registry's inverse Planck instead takes it per wavenumber, mW / (m2 sr (cm-1)-1). read_ahi rebases between the two itself — by L * wavelength_um**2 * 1e-1 — on every path that reaches the registry, so a Dataset source and an explicit coeffs= both calibrate correctly.

The two bases differ by a factor of 1.5 (3.9 µm) to 17.7 (13.3 µm), which is the dangerous part: skipping the rebasing yields a plausible temperature rather than an obviously broken one — a 280 K scene reads as about 189 K. So a Dataset holding radiance in some other unit will not be rescued here, and the error will not announce itself: pass the granule, or convert before you call.

(If you are reading the specification alongside this: every text extraction of the PDF loses its micro sign, so the wavelength and radiance units appear there as [m] and W / (m2 sr m). Table 1 listing the bands as 0.47 to 13.3 is what settles that they are micrometres.)

Sentinel-3: swath readers#

For Sentinel-3 .SEN3 granules use read_olci (OLCI L1B EFR / ERR) and read_slstr (SLSTR L1 RBT). Both decode through pyramids' bundled GDAL NetCDF driver — there is no netCDF4 dependency and nothing from the satpy stack — and available_olci_channels(granule) lists the OLCI bands a granule carries.

These two differ from the geostationary readers above in three ways worth knowing:

  • They are swath instruments. A pushbroom sensor sweeps a curved strip of ground, so no affine geotransform can describe where the pixels are; the product instead ships a longitude and a latitude for every pixel. The results therefore carry a GDAL GEOLOCATION metadata domain pointing at those arrays, a placeholder pixel/line geotransform, and no CRS.

    Sentinel-3 stores those arrays CF-packed as int32 micro-degrees, and GDAL's geolocation transformer reads geolocation arrays raw, without applying scale_factor. The readers therefore point the domain at a small generated VRT that applies the packing, so the warp below receives real degrees rather than micro-degrees. The VRT is XML only — no geolocation array is read or copied until a warp pulls from it.

Nothing is resampled — a caller who wants a map grid warps on demand:

```python
from osgeo import gdal
from pyramids_eo.sensors.readers import read_olci

swath = read_olci("S3A_OL_1_EFR.SEN3", channel="Oa08")
swath.geotransform          # the placeholder grid, not a geographic one
gdal.Warp("oa08.tif", swath.raster, geoloc=True)   # user-driven reprojection
```
  • They decode only. Radiometric calibration choices are out of scope for these readers (issue #136), so read_olci returns radiance and does not convert to reflectance; a caller converting it should use the granule's own per-detector solar_flux from instrument_data.nc. The SLSTR RBT product is already geophysical, so S7–S9 / F1–F2 arrive as brightness temperature in kelvin with no Planck conversion applied.

  • SLSTR is dual-view and multi-grid. It images each scene twice, so view="nadir" / "n" or "oblique" / "o" selects one. view defaults to None, which is not a synonym for nadir: a channel name may spell the view itself ("S8_BT_io"), and a spelled view wins — nadir is the fallback only when neither the channel nor view= names one. Its channels sit on different resolutions — S1–S6 on the 500 m a grid (with S4–S6 also on the alternative 500 m b), S7–S9 on the 1 km i grid, and of the fire channels F1 on f or i while F2 is i-only — they are asymmetric, and there is no F2_BT_f*.nc, so an f-less granule still reads F1 from i. grid= restricts a read to one grid and never falls back to another, so an explicit grid= can't quietly hand back a different resolution. available_slstr_channels(granule) reports what a granule carries on the grids of one view per call — view="nadir" unless you ask for "oblique" — which is how to discover a non-nominal layout. Because the grids differ in shape, channels=[...] returns a dict[str, Dataset] of differently-sized arrays rather than a stack.

  • OLCI comes as EFR or ERR. The two share every filename and variable name and differ only in pixel size (300 m against ~1200 m), so read_olci detects the product type from the granule name — falling back to xfdumanifest.xml — and reports resolution_m accordingly. A granule that identifies itself as neither carries no resolution_m at all, rather than a figure that could be wrong by a factor of four. (Nothing in this package reads that key today — harmonise takes an explicit reference grid — so it is provenance for a caller, not an input to the stack.)

A reader keyword passed through read_file as a KEY=VALUE list arrives as a string, because Dataset.read_file normalises open_options to GDAL's form. The drivers therefore translate the string spellings of a boolean (false/true, yes/no, on/off, 1/0, case-insensitively) and reject a string they do not recognise, instead of treating the truthy "false" as switching the option on. A value that is not a string reaches the reader untouched, so the dict form with a real False is the unambiguous way to write it. Note that a channel set is a direct-call feature: read_file requires one Dataset back, so use read_olci(..., channels=[...]) when you want several at once.

Himawari AHI (HSD) remains unimplemented: its byte-level layout comes from JMA's Himawari Standard Data User's Guide, which is needed before a correct decoder can be written (see issue #136).

pyramids_eo.sensors.readers #

Instrument readers — the package entry points.

Each reader takes a file path / chunk set / Dataset and returns a pyramids Dataset / DatasetCollection (or curvilinear equivalent).

  • read_fci — MTG-FCI L1C (FDHSI): stitch a channel (or several — channels=[...] returns a dict) across its chunk set and calibrate to reflectance / brightness temperature.
  • read_fci_l1c — decode + stitch + calibrate one channel or several (channels=[...] returns a dict, opening each chunk once) across real MTG-FCI L1C FDHSI chunk files (packed radiance in nested groups, per-granule coefficients, geostationary grid).
  • available_channels — list the VIS/IR channels present in FCI L1C FDHSI chunk(s).
  • open_fci_l1c_chunk — lower-level open_chunk reading the FCI L1C FDHSI nested data/<channel>/measured/effective_radiance radiance for use with read_fci.
  • read_ahi — Himawari-8/9 AHI Himawari Standard Data (.DAT): decode one band from a granule (or stitch its segment set) and calibrate to reflectance / brightness temperature on the geostationary grid, using the granule's own coefficients.
  • parse_ahi_hsd — decode one HSD granule to a geolocated radiance Dataset (the uncalibrated layer under read_ahi).
  • parse_hsd_header / HsdHeader — decode the HSD header blocks from granule bytes the caller supplies, for the grid, projection and calibration without interpreting the pixels. It takes bytes rather than a path, so reading a granule's header alone means reading the file yourself; read_ahi does that internally when it sizes a stitch.
  • band_name / band_from_filename — AHI band keys (3 -> "B03"), and the band an HSD file name declares.
  • read_seviri — MSG-SEVIRI Level-1.5 native (.nat): decode + calibrate + geolocate a VIS/IR channel (via parse_seviri_native, or an injected parser).
  • parse_seviri_native — decode one VIS/IR channel of an MSG Level-1.5 native .nat granule to a geolocated radiance Dataset (the default read_seviri parser).
  • read_olci — Sentinel-3 OLCI L1B (EFR / ERR): decode one radiance band (or several — channels=[...] returns a dict) from a .SEN3 granule onto its native swath grid, geolocated by a GDAL GEOLOCATION domain.
  • available_olci_channels — list the OLCI radiance bands a .SEN3 granule carries.
  • product_type — tell an OLCI granule's EFR / ERR product apart (None when the granule names neither, or both), which is what fixes its ground resolution.
  • read_slstr — Sentinel-3 SLSTR L1 RBT: decode one channel (or several) for a chosen view (nadir / oblique) and grid, likewise swath-geolocated.
  • available_slstr_channels — list the channels, and grids per channel, an SLSTR granule can actually be read for in one view.
  • harmonise — align multi-resolution bands onto one common target grid.

The Sentinel-3 readers decode to arrays plus CF metadata only — radiometric calibration choices stay with the caller (issue #136). Being swath instruments, their results carry a GDAL GEOLOCATION domain over the granule's per-pixel longitude / latitude arrays rather than an affine geotransform, and they resample nothing.

HsdHeader dataclass #

The HSD header fields a read needs, decoded from one granule.

Attributes:

Name Type Description
satellite str

Satellite name from block #1, as the granule spells it -- "Himawari-8" or "Himawari-9". This is a different vocabulary from the file name's H08 / H09 token, which :func:band_from_filename parses instead.

band_number int

AHI band number, 1-16 (block #5).

columns int

Pixels per line in this granule / segment (block #2).

lines int

Lines in this granule / segment (block #2).

bits_per_pixel int

Stored bit depth, always 16 for HSD (block #2).

valid_bits int

Valid bits per pixel for the band — 11, 12 or 14 depending on the band (block #5). Decoded and exposed, but deliberately not applied: the reader does not clip or mask counts that exceed 2**valid_bits. The two sentinel counts already identify every pixel the granule declares invalid, so a count above the valid range is a product defect rather than a flag, and silently discarding it would hide that defect instead of surfacing it. A caller that wants to treat the range as hard can read this field and mask.

compression int

Data-block compression flag — 0 none, 1 gzip, 2 bzip2.

sub_lon float

Sub-satellite longitude, degrees east (block #3).

cfac int

Column scaling factor of the normalised projection (block #3).

lfac int

Line scaling factor of the normalised projection (block #3).

coff float

Column offset — the sub-satellite column, 1-based (block #3).

loff float

Line offset — the sub-satellite line, 1-based (block #3).

rs_km float

Distance from the Earth's centre to the satellite (block #3).

req_km float

Ellipsoid equatorial radius, WGS84 (block #3).

rpol_km float

Ellipsoid polar radius, WGS84 (block #3).

slope float

Count-to-radiance slope actually in force (block #5); the calibrated (updated) value for a solar band when the granule carries one. Only its magnitude is screened — a negative gain decodes and is passed through (see :data:_MIN_SLOPE).

intercept float

Count-to-radiance intercept in force (block #5).

error_count int

Count value marking an error pixel (block #5, 65535).

outside_count int

Count value marking a pixel outside the scan area (block #5, 65534).

central_wavelength_um float

Band central wavelength in micrometres (block #5 field 4). HSD is micrometre-based throughout: the field carries 10.4 for band 13, not 1.04e-05, and the slope / intercept of the same block give radiance per micrometre. Every text extraction of the specification PDF loses its micro sign -- the whole document decodes to ASCII but for one multiplication sign -- so the unit renders as [m] there; Table 1 listing the bands as 0.47 to 13.3 is what settles it. The name carries the unit so the reading cannot drift again.

albedo_coefficient float | None

Solar bands only — c' of albedo = c' * radiance, so 1 / c' is the band solar irradiance; None for a thermal band.

planck_c0 float | None

Thermal bands only — constant term of the effective-to- brightness-temperature correction; None for a solar band.

planck_c1 float | None

Thermal bands only — linear term, else None.

planck_c2 float | None

Thermal bands only — quadratic term, else None.

light_speed float | None

Thermal bands only — speed of light the granule was calibrated with (m/s), else None.

planck_constant float | None

Thermal bands only — Planck constant (J s), else None.

boltzmann_constant float | None

Thermal bands only — Boltzmann constant (J/K), else None.

total_segments int

Number of segments the full image is split into (#7).

segment_number int

This granule's segment sequence number (block #7).

first_line int

1-based line of this segment within the full image (#7).

observation_area str

Observation-area token from block #1 ("FLDK" for a full disk), the same vocabulary as the file name's cccc field.

observation_timeline int

Observation timeline as hhmm (block #1).

observation_start_mjd float

Observation start time in Modified Julian Date (block #1). Per segment, not per image: AHI scans the disk progressively, so every segment of one acquisition carries its own. Measured on a real band-13 full disk, segments 1 and 10 start 526.0 s apart. It therefore does NOT identify an acquisition: observation_timeline with observation_area does so within one day -- that pair recurs daily -- and this field is only used to bound how far apart one acquisition's segments may start, which is what tells consecutive days apart (see :data:_MAX_ACQUISITION_SPAN_DAYS).

total_header_length int

Header length the granule declares (block #1), used to check the header walk rather than trusted blindly.

total_data_length int

Pixel-payload length the granule declares (block #1).

Examples:

  • A decoded band-13 full-disk header reports its band, its radiometric kind, and the satellite height the projection is built from:
    >>> from pyramids_eo.sensors.readers.ahi import HsdHeader
    >>> header = HsdHeader(
    ...     satellite="Himawari-8", band_number=13, columns=5500, lines=5500,
    ...     bits_per_pixel=16, valid_bits=14, compression=0, sub_lon=140.7,
    ...     cfac=20466275, lfac=20466275, coff=2750.5, loff=2750.5,
    ...     rs_km=42164.0, req_km=6378.1370, rpol_km=6356.7523,
    ...     slope=0.5, intercept=-10.0, error_count=65535, outside_count=65534,
    ...     central_wavelength_um=10.4, albedo_coefficient=None,
    ...     planck_c0=0.0, planck_c1=1.0, planck_c2=0.0,
    ...     light_speed=299792458.0, planck_constant=6.62606957e-34,
    ...     boltzmann_constant=1.3806488e-23,
    ...     total_segments=10, segment_number=1, first_line=1,
    ...     observation_area="FLDK", observation_timeline=230,
    ...     observation_start_mjd=57127.1041666667,
    ...     total_header_length=1598, total_data_length=60500000,
    ... )
    >>> header.band
    'B13'
    >>> header.kind
    'thermal'
    >>> round(header.satellite_height_m)
    35785863
    
Source code in src/pyramids_eo/sensors/readers/ahi.py
@dataclass(frozen=True)
class HsdHeader:
    """The HSD header fields a read needs, decoded from one granule.

    Attributes:
        satellite: Satellite name from block #1, as the granule spells it --
            ``"Himawari-8"`` or ``"Himawari-9"``. This is a different vocabulary
            from the file name's ``H08`` / ``H09`` token, which
            :func:`band_from_filename` parses instead.
        band_number: AHI band number, 1-16 (block #5).
        columns: Pixels per line in this granule / segment (block #2).
        lines: Lines in this granule / segment (block #2).
        bits_per_pixel: Stored bit depth, always 16 for HSD (block #2).
        valid_bits: Valid bits per pixel for the band — 11, 12 or 14 depending on
            the band (block #5). Decoded and exposed, but deliberately **not**
            applied: the reader does not clip or mask counts that exceed
            ``2**valid_bits``. The two sentinel counts already identify every
            pixel the granule declares invalid, so a count above the valid range
            is a product defect rather than a flag, and silently discarding it
            would hide that defect instead of surfacing it. A caller that wants
            to treat the range as hard can read this field and mask.
        compression: Data-block compression flag — 0 none, 1 gzip, 2 bzip2.
        sub_lon: Sub-satellite longitude, degrees east (block #3).
        cfac: Column scaling factor of the normalised projection (block #3).
        lfac: Line scaling factor of the normalised projection (block #3).
        coff: Column offset — the sub-satellite column, 1-based (block #3).
        loff: Line offset — the sub-satellite line, 1-based (block #3).
        rs_km: Distance from the Earth's centre to the satellite (block #3).
        req_km: Ellipsoid equatorial radius, WGS84 (block #3).
        rpol_km: Ellipsoid polar radius, WGS84 (block #3).
        slope: Count-to-radiance slope actually in force (block #5); the
            calibrated (updated) value for a solar band when the granule
            carries one. Only its magnitude is screened — a negative gain
            decodes and is passed through (see :data:`_MIN_SLOPE`).
        intercept: Count-to-radiance intercept in force (block #5).
        error_count: Count value marking an error pixel (block #5, 65535).
        outside_count: Count value marking a pixel outside the scan area
            (block #5, 65534).
        central_wavelength_um: Band central wavelength in **micrometres**
            (block #5 field 4). HSD is micrometre-based throughout: the field
            carries 10.4 for band 13, not 1.04e-05, and the slope / intercept
            of the same block give radiance per micrometre. Every text
            extraction of the specification PDF loses its micro sign -- the
            whole document decodes to ASCII but for one multiplication sign --
            so the unit renders as ``[m]`` there; Table 1 listing the bands as
            0.47 to 13.3 is what settles it. The name carries the unit so the
            reading cannot drift again.
        albedo_coefficient: Solar bands only — ``c'`` of ``albedo = c' * radiance``,
            so ``1 / c'`` is the band solar irradiance; `None` for a thermal band.
        planck_c0: Thermal bands only — constant term of the effective-to-
            brightness-temperature correction; `None` for a solar band.
        planck_c1: Thermal bands only — linear term, else `None`.
        planck_c2: Thermal bands only — quadratic term, else `None`.
        light_speed: Thermal bands only — speed of light the granule was
            calibrated with (m/s), else `None`.
        planck_constant: Thermal bands only — Planck constant (J s), else `None`.
        boltzmann_constant: Thermal bands only — Boltzmann constant (J/K), else
            `None`.
        total_segments: Number of segments the full image is split into (#7).
        segment_number: This granule's segment sequence number (block #7).
        first_line: 1-based line of this segment within the full image (#7).
        observation_area: Observation-area token from block #1 (``"FLDK"`` for a
            full disk), the same vocabulary as the file name's ``cccc`` field.
        observation_timeline: Observation timeline as ``hhmm`` (block #1).
        observation_start_mjd: Observation start time in Modified Julian Date
            (block #1). **Per segment, not per image**: AHI scans the disk
            progressively, so every segment of one acquisition carries its own.
            Measured on a real band-13 full disk, segments 1 and 10 start 526.0 s
            apart. It therefore does NOT identify an acquisition:
            `observation_timeline` with `observation_area` does so **within one
            day** -- that pair recurs daily -- and this field is only used to
            bound how far apart one acquisition's segments may start, which is
            what tells consecutive days apart (see
            :data:`_MAX_ACQUISITION_SPAN_DAYS`).
        total_header_length: Header length the granule declares (block #1), used
            to check the header walk rather than trusted blindly.
        total_data_length: Pixel-payload length the granule declares (block #1).

    Examples:
        - A decoded band-13 full-disk header reports its band, its radiometric
          kind, and the satellite height the projection is built from:
            ```python
            >>> from pyramids_eo.sensors.readers.ahi import HsdHeader
            >>> header = HsdHeader(
            ...     satellite="Himawari-8", band_number=13, columns=5500, lines=5500,
            ...     bits_per_pixel=16, valid_bits=14, compression=0, sub_lon=140.7,
            ...     cfac=20466275, lfac=20466275, coff=2750.5, loff=2750.5,
            ...     rs_km=42164.0, req_km=6378.1370, rpol_km=6356.7523,
            ...     slope=0.5, intercept=-10.0, error_count=65535, outside_count=65534,
            ...     central_wavelength_um=10.4, albedo_coefficient=None,
            ...     planck_c0=0.0, planck_c1=1.0, planck_c2=0.0,
            ...     light_speed=299792458.0, planck_constant=6.62606957e-34,
            ...     boltzmann_constant=1.3806488e-23,
            ...     total_segments=10, segment_number=1, first_line=1,
            ...     observation_area="FLDK", observation_timeline=230,
            ...     observation_start_mjd=57127.1041666667,
            ...     total_header_length=1598, total_data_length=60500000,
            ... )
            >>> header.band
            'B13'
            >>> header.kind
            'thermal'
            >>> round(header.satellite_height_m)
            35785863

            ```
    """

    satellite: str
    band_number: int
    columns: int
    lines: int
    bits_per_pixel: int
    valid_bits: int
    compression: int
    sub_lon: float
    cfac: int
    lfac: int
    coff: float
    loff: float
    rs_km: float
    req_km: float
    rpol_km: float
    slope: float
    intercept: float
    error_count: int
    outside_count: int
    central_wavelength_um: float
    albedo_coefficient: float | None
    planck_c0: float | None
    planck_c1: float | None
    planck_c2: float | None
    light_speed: float | None
    planck_constant: float | None
    boltzmann_constant: float | None
    total_segments: int
    segment_number: int
    first_line: int
    observation_area: str
    observation_timeline: int
    observation_start_mjd: float
    total_header_length: int
    total_data_length: int

    @property
    def band(self) -> str:
        """Return the registry band key for this granule.

        Returns:
            The zero-padded ``"B<nn>"`` key for :attr:`band_number`, which is
            both the bundled registry's channel key and the band field of the
            HSD file name (e.g. ``"B13"``).
        """
        return band_name(self.band_number)

    @property
    def kind(self) -> str:
        """Return the band's radiometric kind.

        Returns:
            ``"solar"`` for bands 1-6 and ``"thermal"`` for bands 7-16 - the
            same split the specification uses to decide which variant of
            calibration block #5 a granule carries.

        Examples:
            - The split falls between bands 6 and 7, which is where the
              specification switches block #5 from its visible / near-infrared
              variant to its infrared one:
                ```python
                >>> import dataclasses
                >>> from pyramids_eo.sensors.readers.ahi import HsdHeader
                >>> header = HsdHeader(
                ...     satellite="Himawari-8", band_number=13, columns=5500, lines=5500,
                ...     bits_per_pixel=16, valid_bits=14, compression=0, sub_lon=140.7,
                ...     cfac=20466275, lfac=20466275, coff=2750.5, loff=2750.5,
                ...     rs_km=42164.0, req_km=6378.1370, rpol_km=6356.7523,
                ...     slope=0.5, intercept=-10.0, error_count=65535, outside_count=65534,
                ...     central_wavelength_um=10.4, albedo_coefficient=None,
                ...     planck_c0=0.0, planck_c1=1.0, planck_c2=0.0,
                ...     light_speed=299792458.0, planck_constant=6.62606957e-34,
                ...     boltzmann_constant=1.3806488e-23,
                ...     total_segments=10, segment_number=1, first_line=1,
                ...     observation_area="FLDK", observation_timeline=230,
                ...     observation_start_mjd=57127.1041666667,
                ...     total_header_length=1598, total_data_length=60500000,
                ... )
                >>> [dataclasses.replace(header, band_number=n).kind for n in (1, 6, 7, 16)]
                ['solar', 'solar', 'thermal', 'thermal']

                ```
        """
        return "solar" if self.band_number <= _SOLAR_BAND_MAX else "thermal"

    @property
    def satellite_height_m(self) -> float:
        """Return the satellite height above the ellipsoid, in metres.

        The projection block gives the distance from the Earth's *centre*; the
        geostationary CRS wants the perspective-point height above the equator,
        which is that distance less the equatorial radius.

        Returns:
            The perspective-point height in metres, derived from the granule's
            own ``Rs`` and ``req`` rather than from a hard-coded constant.
        """
        return (self.rs_km - self.req_km) * 1000.0
band property #

Return the registry band key for this granule.

Returns:

Type Description
str

The zero-padded "B<nn>" key for :attr:band_number, which is

str

both the bundled registry's channel key and the band field of the

str

HSD file name (e.g. "B13").

kind property #

Return the band's radiometric kind.

Returns:

Type Description
str

"solar" for bands 1-6 and "thermal" for bands 7-16 - the

str

same split the specification uses to decide which variant of

str

calibration block #5 a granule carries.

Examples:

  • The split falls between bands 6 and 7, which is where the specification switches block #5 from its visible / near-infrared variant to its infrared one:
    >>> import dataclasses
    >>> from pyramids_eo.sensors.readers.ahi import HsdHeader
    >>> header = HsdHeader(
    ...     satellite="Himawari-8", band_number=13, columns=5500, lines=5500,
    ...     bits_per_pixel=16, valid_bits=14, compression=0, sub_lon=140.7,
    ...     cfac=20466275, lfac=20466275, coff=2750.5, loff=2750.5,
    ...     rs_km=42164.0, req_km=6378.1370, rpol_km=6356.7523,
    ...     slope=0.5, intercept=-10.0, error_count=65535, outside_count=65534,
    ...     central_wavelength_um=10.4, albedo_coefficient=None,
    ...     planck_c0=0.0, planck_c1=1.0, planck_c2=0.0,
    ...     light_speed=299792458.0, planck_constant=6.62606957e-34,
    ...     boltzmann_constant=1.3806488e-23,
    ...     total_segments=10, segment_number=1, first_line=1,
    ...     observation_area="FLDK", observation_timeline=230,
    ...     observation_start_mjd=57127.1041666667,
    ...     total_header_length=1598, total_data_length=60500000,
    ... )
    >>> [dataclasses.replace(header, band_number=n).kind for n in (1, 6, 7, 16)]
    ['solar', 'solar', 'thermal', 'thermal']
    
satellite_height_m property #

Return the satellite height above the ellipsoid, in metres.

The projection block gives the distance from the Earth's centre; the geostationary CRS wants the perspective-point height above the equator, which is that distance less the equatorial radius.

Returns:

Type Description
float

The perspective-point height in metres, derived from the granule's

float

own Rs and req rather than from a hard-coded constant.

band_from_filename(path) #

Return the band key named by an HSD file name, when it follows Table 4.

Parameters:

Name Type Description Default
path Any

Path to an HSD granule.

required

Returns:

Type Description
str | None

The "B<nn>" band key the file name declares, or None when the name

str | None

does not follow the HSD convention.

Examples:

  • A conventional name yields its band; anything else yields None:
    >>> from pyramids_eo.sensors.readers.ahi import band_from_filename
    >>> band_from_filename("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
    'B13'
    >>> band_from_filename("scene.dat") is None
    True
    
Source code in src/pyramids_eo/sensors/readers/ahi.py
def band_from_filename(path: Any) -> str | None:
    """Return the band key named by an HSD file name, when it follows Table 4.

    Args:
        path: Path to an HSD granule.

    Returns:
        The ``"B<nn>"`` band key the file name declares, or `None` when the name
        does not follow the HSD convention.

    Examples:
        - A conventional name yields its band; anything else yields `None`:
            ```python
            >>> from pyramids_eo.sensors.readers.ahi import band_from_filename
            >>> band_from_filename("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
            'B13'
            >>> band_from_filename("scene.dat") is None
            True

            ```
    """
    match = _FILENAME_RE.match(str(path).replace("\\", "/").rsplit("/", 1)[-1])
    return None if match is None else band_name(int(match.group("band")))

band_name(number) #

Return the registry channel key for an AHI band number.

Parameters:

Name Type Description Default
number int

Band number, 1-16.

required

Returns:

Type Description
str

The zero-padded "B<nn>" key used by the bundled registry table and by

str

the HSD file name (e.g. 3 -> "B03").

Examples:

  • Band numbers are zero-padded to two digits:
    >>> from pyramids_eo.sensors.readers.ahi import band_name
    >>> band_name(3), band_name(13)
    ('B03', 'B13')
    
Source code in src/pyramids_eo/sensors/readers/ahi.py
def band_name(number: int) -> str:
    """Return the registry channel key for an AHI band number.

    Args:
        number: Band number, 1-16.

    Returns:
        The zero-padded ``"B<nn>"`` key used by the bundled registry table and by
        the HSD file name (e.g. ``3 -> "B03"``).

    Examples:
        - Band numbers are zero-padded to two digits:
            ```python
            >>> from pyramids_eo.sensors.readers.ahi import band_name
            >>> band_name(3), band_name(13)
            ('B03', 'B13')

            ```
    """
    return f"B{int(number):02d}"

parse_ahi_hsd(path) #

Decode one HSD granule to a geolocated radiance Dataset.

Reads the header, decodes the band's 16-bit counts, applies the granule's own count-to-radiance slope / intercept, masks the error and outside-scan sentinel counts to NaN, and registers the geostationary grid. A segment is georeferenced at its true place in the full image, so one segment reads on its own without being mistaken for the whole disk.

Parameters:

Name Type Description Default
path Any

Path to a Himawari Standard Data .DAT (or .DAT.bz2) granule.

required

Returns:

Type Description
Any

A pyramids Dataset of spectral radiance on HSD's own

Any

per-micrometre-of-wavelength basis (W m-2 sr-1 um-1), on the

Any

geostationary grid, with the geostationary CRS and NaN nodata.

Raises:

Type Description
ReaderError

When the file is not a readable HSD granule (see :func:parse_hsd_header and :func:_counts).

Source code in src/pyramids_eo/sensors/readers/ahi.py
def parse_ahi_hsd(path: Any) -> Any:
    """Decode one HSD granule to a geolocated radiance `Dataset`.

    Reads the header, decodes the band's 16-bit counts, applies the granule's
    own count-to-radiance slope / intercept, masks the error and outside-scan
    sentinel counts to NaN, and registers the geostationary grid. A segment is
    georeferenced at its true place in the full image, so one segment reads on
    its own without being mistaken for the whole disk.

    Args:
        path: Path to a Himawari Standard Data ``.DAT`` (or ``.DAT.bz2``) granule.

    Returns:
        A pyramids `Dataset` of spectral radiance on HSD's own
        per-micrometre-of-wavelength basis (``W m-2 sr-1 um-1``), on the
        geostationary grid, with the geostationary CRS and NaN nodata.

    Raises:
        ReaderError: When the file is not a readable HSD granule (see
            :func:`parse_hsd_header` and :func:`_counts`).
    """
    buffer = _read_bytes(path)
    order = _byte_order(buffer)
    blocks = walk_header_blocks(buffer, order)
    header = _parse_header(buffer, order, blocks)
    radiance = _radiance(_counts(buffer, header, blocks, order), header)
    return _dataset(radiance, header, header.first_line)

parse_hsd_header(buffer) #

Decode the HSD header blocks a read depends on.

Parameters:

Name Type Description Default
buffer bytes

The granule bytes (already decompressed).

required

Returns:

Type Description
HsdHeader

The decoded :class:HsdHeader.

Raises:

Type Description
ReaderError

When the granule is not recognisable HSD, a block is truncated or mislabelled, block #1 contradicts the header walk, the band number is out of range, the grid is empty, a solar band's albedo coefficient is non-finite, or the count-to-radiance slope is unusable — non-finite, or of a magnitude below :data:_MIN_SLOPE. Its sign is not constrained.

Source code in src/pyramids_eo/sensors/readers/ahi.py
def parse_hsd_header(buffer: bytes) -> HsdHeader:
    """Decode the HSD header blocks a read depends on.

    Args:
        buffer: The granule bytes (already decompressed).

    Returns:
        The decoded :class:`HsdHeader`.

    Raises:
        ReaderError: When the granule is not recognisable HSD, a block is
            truncated or mislabelled, block #1 contradicts the header walk, the
            band number is out of range, the grid is empty, a solar band's
            albedo coefficient is non-finite, or the count-to-radiance slope is
            unusable — non-finite, or of a magnitude below :data:`_MIN_SLOPE`.
            Its *sign* is not constrained.
    """
    order = _byte_order(buffer)
    return _parse_header(buffer, order, walk_header_blocks(buffer, order))

read_ahi(source, band=None, *, sensor='ahi', calibrate=True, sun_earth_distance=1.0, cos_sza=None, coeffs=None) #

Read one AHI band from Himawari Standard Data into a Dataset.

Decodes the band's counts to radiance with the granule's own calibration, then — when calibrate is set — converts to a physical quantity: reflectance for a solar band (1-6) and brightness temperature for a thermal one (7-16). Both conversions prefer the coefficients the granule carries over the registry's nominal table, so the result is granule-accurate.

Pass the segment paths of one band together to read a stitched full disk; pass one path to read that segment alone, georeferenced where it belongs in the disk. A contiguous subset of the segments is also accepted and returns just those lines, so a partial download reads as the band of the disk it actually covers rather than being padded out or refused. The segments must come from one acquisition — same band, satellite, observation timeline and area — since line numbers alone repeat across timelines. Their observation start times differ, one per segment, because the disk is scanned progressively; the timeline and area are what identify the acquisition, and because that pair recurs daily the start times are bounded to within an hour of each other rather than compared for equality.

Parameters:

Name Type Description Default
source Any

Path to an HSD .DAT / .DAT.bz2 granule, an iterable of segment paths from one acquisition of one band, or a pyramids Dataset already holding the band radiance.

required
band Any

The band to read (13, "B13", "band13"). Optional: a granule names its own band, so this only has to be given to assert the expectation, and a mismatch is an error. Required when source is a Dataset, which carries no band metadata.

None
sensor str

Registry sensor name (default "ahi").

'ahi'
calibrate bool

When True (default), calibrate to reflectance / brightness temperature; when False, return the raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-band reflectance. The default 1.0 leaves reflectance up to ~3.4% off (d ranges ~0.983-1.017 AU over the year); pass the granule's d for absolute accuracy.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None
coeffs dict[str, Any] | None

Per-granule calibration coefficients preferred over both the granule's own values and the registry (see :func:~pyramids_eo.sensors.readers._common.calibrate_channel), or None.

None

Returns:

Type Description
Any

A pyramids Dataset of the calibrated (or raw) band. Read from a granule

Any

it carries the granule's own geostationary grid — the geostationary CRS,

Any

a metre geotransform and NaN nodata. Read from a Dataset source it

Any

keeps that dataset's geotransform, CRS and EPSG instead, since no HSD

Any

header is available to rebuild a grid from; only the values change.

Raises:

Type Description
ReaderError

When source is None, band is unknown or disagrees with the granule, a Dataset source is given without band, or the granule cannot be decoded.

CalibrationError

When a band lacks the constants its kind needs.

UnknownSensorError

When the sensor / band is not in the registry.

Source code in src/pyramids_eo/sensors/readers/ahi.py
def read_ahi(
    source: Any,
    band: Any = None,
    *,
    sensor: str = "ahi",
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
    coeffs: dict[str, Any] | None = None,
) -> Any:
    """Read one AHI band from Himawari Standard Data into a `Dataset`.

    Decodes the band's counts to radiance with the granule's own calibration,
    then — when `calibrate` is set — converts to a physical quantity: reflectance
    for a solar band (1-6) and brightness temperature for a thermal one (7-16).
    Both conversions prefer the coefficients the granule carries over the
    registry's nominal table, so the result is granule-accurate.

    Pass the segment paths of one band together to read a stitched full disk;
    pass one path to read that segment alone, georeferenced where it belongs in
    the disk. A contiguous subset of the segments is also accepted and returns
    just those lines, so a partial download reads as the band of the disk it
    actually covers rather than being padded out or refused. The segments must
    come from one acquisition — same band, satellite, observation timeline and
    area — since line numbers alone repeat across timelines. Their observation
    *start times* differ, one per segment, because the disk is scanned
    progressively; the timeline and area are what identify the acquisition, and
    because that pair recurs daily the start times are bounded to within an hour
    of each other rather than compared for equality.

    Args:
        source: Path to an HSD ``.DAT`` / ``.DAT.bz2`` granule, an iterable of
            segment paths from one acquisition of one band, or a pyramids
            `Dataset` already holding the band radiance.
        band: The band to read (``13``, ``"B13"``, ``"band13"``). Optional: a
            granule names its own band, so this only has to be given to assert
            the expectation, and a mismatch is an error. Required when `source`
            is a `Dataset`, which carries no band metadata.
        sensor: Registry sensor name (default ``"ahi"``).
        calibrate: When `True` (default), calibrate to reflectance / brightness
            temperature; when `False`, return the raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-band reflectance.
            The default ``1.0`` leaves reflectance up to ~3.4% off (``d`` ranges
            ~0.983-1.017 AU over the year); pass the granule's ``d`` for absolute
            accuracy.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.
        coeffs: Per-granule calibration coefficients preferred over both the
            granule's own values and the registry (see
            :func:`~pyramids_eo.sensors.readers._common.calibrate_channel`), or
            `None`.

    Returns:
        A pyramids `Dataset` of the calibrated (or raw) band. Read from a granule
        it carries the granule's own geostationary grid — the geostationary CRS,
        a metre geotransform and NaN nodata. Read from a `Dataset` source it
        keeps **that** dataset's geotransform, CRS and EPSG instead, since no HSD
        header is available to rebuild a grid from; only the values change.

    Raises:
        ReaderError: When `source` is `None`, `band` is unknown or disagrees with
            the granule, a `Dataset` source is given without `band`, or the
            granule cannot be decoded.
        CalibrationError: When a band lacks the constants its kind needs.
        UnknownSensorError: When the sensor / band is not in the registry.
    """
    if source is None:
        raise ReaderError("read_ahi: source is required")
    requested = None if band is None else _canonical_band(band)

    if hasattr(source, "read_array"):
        if requested is None:
            raise ReaderError(
                "read_ahi: band is required when source is already a Dataset "
                "(it carries no HSD header to name the band)"
            )
        return _wrap_like(
            source,
            _calibrate_array(
                source.read_array(),
                requested,
                sensor=sensor,
                calibrate=calibrate,
                sun_earth_distance=sun_earth_distance,
                cos_sza=cos_sza,
                coeffs=coeffs,
                header=None,
            ),
        )

    paths = _resolve_paths(source)

    if len(paths) == 1:
        buffer = _read_bytes(paths[0])
        order = _byte_order(buffer)
        blocks = walk_header_blocks(buffer, order)
        header = _parse_header(buffer, order, blocks)
        # Checked against the header just parsed rather than with a second
        # header-only read, and before the pixels are touched either way.
        _assert_requested_band(header, requested)
        array = _radiance(_counts(buffer, header, blocks, order), header)
        first_line = header.first_line
    else:
        # `_stitch` parses every header before it decodes anything, so it makes
        # the same check there and no granule is read twice.
        array, header = _stitch(paths, requested=requested)
        first_line = header.first_line

    # Calibrate the values before registering them, so a full disk is wrapped
    # once rather than built as radiance and immediately rebuilt as brightness
    # temperature.
    return _dataset(
        _calibrate_array(
            array,
            header.band,
            sensor=sensor,
            calibrate=calibrate,
            sun_earth_distance=sun_earth_distance,
            cos_sza=cos_sza,
            coeffs=coeffs,
            header=header,
        ),
        header,
        first_line,
    )

open_fci_l1c_chunk(path, channel, *, radiance_group=_FCI_RADIANCE_GROUP) #

Open one real FCI L1C FDHSI chunk from its nested group layout.

Unlike _default_open_chunk (which assumes a flat variable named like the channel), this reads the radiance from the nested group path a real FCI L1C FDHSI chunk uses — by default data/<channel>/measured/effective_radiance — through pyramids' group-qualified NetCDF.get_variable, which navigates the /-separated group path. Pass it to read_fci as open_chunk for real granules:

from pyramids_eo.sensors.readers import open_fci_l1c_chunk, read_fci

scene = read_fci(chunk_paths, "ir_105", open_chunk=open_fci_l1c_chunk)
Warning

The nested group path matches the documented FDHSI layout, but has not been validated byte-for-byte against a real EUMETSAT granule, and this opener does not (yet) extract the per-granule calibration coefficients from the chunk's group attributes — supply them via read_fci(..., coeffs=...) or rely on the registry fallback. See issue

40.#

Parameters:

Name Type Description Default
path Any

Path to a single FCI L1C FDHSI chunk NetCDF file.

required
channel str

Channel identifier (e.g. "ir_105"), substituted into radiance_group.

required
radiance_group str

Group-qualified variable-name template with a single {channel} placeholder. Defaults to data/{channel}/measured/effective_radiance. read_fci calls the opener positionally, so to thread a non-default template through read_fci wrap it with functools.partial(open_fci_l1c_chunk, radiance_group=...).

_FCI_RADIANCE_GROUP

Returns:

Type Description
Any

A pyramids NetCDF variable view of the channel's raw effective radiance

Any

(a Dataset-like object exposing read_array / geotransform / epsg /

Any

columns / rows, as read_fci consumes it).

Source code in src/pyramids_eo/sensors/readers/fci.py
def open_fci_l1c_chunk(
    path: Any,
    channel: str,
    *,
    radiance_group: str = _FCI_RADIANCE_GROUP,
) -> Any:
    """Open one real FCI L1C FDHSI chunk from its nested group layout.

    Unlike `_default_open_chunk` (which assumes a flat variable named like the
    channel), this reads the radiance from the nested group path a real FCI L1C
    FDHSI chunk uses — by default `data/<channel>/measured/effective_radiance` —
    through pyramids' group-qualified `NetCDF.get_variable`, which navigates the
    `/`-separated group path. Pass it to `read_fci` as `open_chunk` for real
    granules:

    ```python
    from pyramids_eo.sensors.readers import open_fci_l1c_chunk, read_fci

    scene = read_fci(chunk_paths, "ir_105", open_chunk=open_fci_l1c_chunk)
    ```

    Warning:
        The nested group path matches the documented FDHSI layout, but has not
        been validated byte-for-byte against a real EUMETSAT granule, and this
        opener does not (yet) extract the per-granule calibration coefficients
        from the chunk's group attributes — supply them via
        `read_fci(..., coeffs=...)` or rely on the registry fallback. See issue
        #40.

    Args:
        path: Path to a single FCI L1C FDHSI chunk NetCDF file.
        channel: Channel identifier (e.g. `"ir_105"`), substituted into
            `radiance_group`.
        radiance_group: Group-qualified variable-name template with a single
            `{channel}` placeholder. Defaults to
            `data/{channel}/measured/effective_radiance`. `read_fci` calls the
            opener positionally, so to thread a non-default template through
            `read_fci` wrap it with
            `functools.partial(open_fci_l1c_chunk, radiance_group=...)`.

    Returns:
        A pyramids `NetCDF` variable view of the channel's raw effective radiance
        (a `Dataset`-like object exposing `read_array` / `geotransform` / `epsg` /
        `columns` / `rows`, as `read_fci` consumes it).
    """
    from pyramids.netcdf import NetCDF

    try:
        variable = radiance_group.format(channel=channel)
    except (KeyError, IndexError, ValueError, AttributeError, TypeError) as exc:
        raise ReaderError(
            f"invalid radiance_group template {radiance_group!r}: it must be a "
            f"format string with a single '{{channel}}' field ({exc!r})"
        ) from exc
    # Group navigation via get_variable needs the file opened as multidimensional;
    # pass it explicitly rather than relying on read_file's default.
    return NetCDF.read_file(str(path), open_as_multi_dimensional=True).get_variable(
        variable
    )

read_fci(chunks, channel=None, *, channels=None, sensor='fci', calibrate=True, sun_earth_distance=1.0, cos_sza=None, coeffs=None, open_chunk=None) #

Read one or several FCI channels across a chunk set into Datasets.

For each requested channel, orders the chunks north -> south by their top-left latitude (so the caller may pass them in any order), stitches the radiance row-wise, calibrates it to reflectance (solar) or brightness temperature (thermal), and returns a geolocated pyramids Dataset carrying the northernmost chunk's CRS + geotransform. The chunks must share a CRS, cell size and column count and be vertically contiguous (validated per channel, since channels differ in resolution).

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]); read_fci(chunks, "ir_105") is unchanged.

Parameters:

Name Type Description Default
chunks Any

An ordered iterable of chunks, each either a pyramids Dataset already holding the channel radiance, or a value accepted by open_chunk (by default a NetCDF path).

required
channel str | None

A single channel identifier (e.g. "ir_105", "vis_06") for a Dataset result; mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channel identifiers for a dict[str, Dataset] result; mutually exclusive with channel. (Each channel is opened via open_chunk, whose contract is per-channel; the grid is validated and ordered per channel because channels differ in resolution.)

None
sensor str

Registry sensor name (default "fci").

'fci'
calibrate bool

When True (default), calibrate to a physical quantity; when False, return the stitched raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None
coeffs dict[str, Any] | None

Per-granule calibration coefficients preferred over the registry fallback (see calibrate_channel), or None to use the registry. They override a single channel's calibration, so they are only accepted with channel= — passing coeffs together with channels=[...] is an error (each channel would need its own).

None
open_chunk Any

Callable (chunk, channel) -> Dataset used for chunks that are not already Datasets. Defaults to a NetCDF reader (see the module warning about the FCI layout).

None

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] keyed by

Any

channel (for channels) of the calibrated (or raw) channel(s) on the

Any

stitched grid.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, or when chunks is empty.

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When the sensor / channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/fci.py
def read_fci(
    chunks: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    sensor: str = "fci",
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
    coeffs: dict[str, Any] | None = None,
    open_chunk: Any = None,
) -> Any:
    """Read one or several FCI channels across a chunk set into `Dataset`s.

    For each requested channel, orders the chunks north -> south by their top-left
    latitude (so the caller may pass them in any order), stitches the radiance
    row-wise, calibrates it to reflectance (solar) or brightness temperature
    (thermal), and returns a geolocated pyramids `Dataset` carrying the
    northernmost chunk's CRS + geotransform. The chunks must share a CRS, cell
    size and column count and be vertically contiguous (validated per channel,
    since channels differ in resolution).

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`); `read_fci(chunks, "ir_105")` is unchanged.

    Args:
        chunks: An ordered iterable of chunks, each either a pyramids `Dataset`
            already holding the channel radiance, or a value accepted by
            `open_chunk` (by default a NetCDF path).
        channel: A single channel identifier (e.g. `"ir_105"`, `"vis_06"`) for a
            `Dataset` result; mutually exclusive with `channels`.
        channels: A sequence of channel identifiers for a `dict[str, Dataset]`
            result; mutually exclusive with `channel`. (Each channel is opened via
            `open_chunk`, whose contract is per-channel; the grid is validated and
            ordered per channel because channels differ in resolution.)
        sensor: Registry sensor name (default `"fci"`).
        calibrate: When `True` (default), calibrate to a physical quantity; when
            `False`, return the stitched raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.
        coeffs: Per-granule calibration coefficients preferred over the registry
            fallback (see `calibrate_channel`), or `None` to use the registry. They
            override a **single** channel's calibration, so they are only accepted
            with `channel=` — passing `coeffs` together with `channels=[...]` is an
            error (each channel would need its own).
        open_chunk: Callable `(chunk, channel) -> Dataset` used for chunks that
            are not already Datasets. Defaults to a NetCDF reader (see the module
            warning about the FCI layout).

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` keyed by
        channel (for `channels`) of the calibrated (or raw) channel(s) on the
        stitched grid.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given, or
            when `chunks` is empty.
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When the sensor / channel is not in the registry.
    """
    requested, single = resolve_channels(channel, channels, "read_fci")
    chunk_list = list(chunks)
    if not chunk_list:
        raise ReaderError("read_fci: no chunks given")
    # A pre-opened Dataset holds exactly one channel's radiance, so it cannot serve
    # a multi-channel request — every channel would alias the same array. Reject it
    # rather than return a physically meaningless dict.
    if not single and any(hasattr(chunk, "read_array") for chunk in chunk_list):
        raise ReaderError(
            "read_fci: channels=[...] needs path-like chunks read per channel via "
            "open_chunk; a pre-opened Dataset already holds a single channel"
        )
    # `coeffs` overrides one channel's calibration; sharing it across a channel set
    # would mis-calibrate the others. Require the single-channel form for an override.
    if not single and coeffs is not None:
        raise ReaderError(
            "read_fci: `coeffs` overrides a single channel's calibration; pass it "
            "with `channel=`, not `channels=[...]` (each channel calibrates on its own)"
        )
    opener = open_chunk or _default_open_chunk

    from pyramids.base.crs import crs_spec
    from pyramids.dataset import Dataset, GeoReference

    results = {}
    for name in requested:
        datasets = [
            chunk if hasattr(chunk, "read_array") else opener(chunk, name)
            for chunk in chunk_list
        ]
        _validate_chunk_grid(datasets)
        # Order the chunks north -> south by their top-left latitude/y so the
        # stitch and geolocation are correct regardless of the order the chunks
        # were passed in (FCI files are commonly numbered south -> north).
        ordered = sorted(datasets, key=lambda ds: ds.geotransform[3], reverse=True)
        radiance = np.concatenate(
            [np.asarray(ds.read_array(), dtype=float) for ds in ordered], axis=0
        )
        data = (
            calibrate_channel(
                radiance, name, sensor, sun_earth_distance, cos_sza, coeffs=coeffs
            )
            if calibrate
            else radiance
        )
        north = ordered[0]
        # Calibration can produce NaN (terminator reflectance / non-positive
        # radiance), so declare NaN as nodata rather than the default -9999.
        results[name] = Dataset.from_array(
            data,
            geo_ref=GeoReference(
                geo=north.geotransform, epsg=crs_spec(north.epsg, north.crs)
            ),
            no_data_value=np.nan,
        )
    return results[requested[0]] if single else results

available_channels(chunks) #

List the VIS/IR channels present across FCI L1C FDHSI chunk file(s).

Opens each chunk's multidimensional dataset and reports the data/<channel> groups that carry an effective_radiance array, so a caller can discover the channel names instead of hard-coding them. The union across chunks is returned (a trailer chunk contributes none), sorted.

Parameters:

Name Type Description Default
chunks Any

A single chunk path, or an iterable of chunk paths. (For convenience this discovery helper also accepts a lone path, whereas read_fci_l1c / read_fci take an iterable of chunk paths.)

required

Returns:

Type Description
list[str]

The sorted channel identifiers available in the chunk(s).

Source code in src/pyramids_eo/sensors/readers/fci_l1c.py
def available_channels(chunks: Any) -> list[str]:
    """List the VIS/IR channels present across FCI L1C FDHSI chunk file(s).

    Opens each chunk's multidimensional dataset and reports the `data/<channel>`
    groups that carry an `effective_radiance` array, so a caller can discover the
    channel names instead of hard-coding them. The union across chunks is returned
    (a trailer chunk contributes none), sorted.

    Args:
        chunks: A single chunk path, or an iterable of chunk paths. (For
            convenience this discovery helper also accepts a lone path, whereas
            `read_fci_l1c` / `read_fci` take an iterable of chunk paths.)

    Returns:
        The sorted channel identifiers available in the chunk(s).
    """
    paths = [chunks] if isinstance(chunks, (str, bytes, os.PathLike)) else list(chunks)
    found: set[str] = set()
    for path in paths:
        found |= _channels_in_chunk(path)
    return sorted(found)

read_fci_l1c(paths, channel=None, *, channels=None, calibrate=True, sun_earth_distance=1.0, cos_sza=None) #

Read one or several channels across a set of real FCI L1C FDHSI chunks.

Decodes each chunk once for the whole requested channel set (read_fci_l1c_chunks opens the chunk's structure a single time), drops chunks without a channel's radiance (e.g. CHK-TRAIL), then for each channel orders the chunks north -> south by their geotransform Y origin, checks they are vertically contiguous (and share a grid), stitches the radiance, and calibrates it with the per-granule coefficients (reflectance for a solar channel, brightness temperature for a thermal one). Each result is a geolocated pyramids Dataset on the granule's geostationary grid (metre geotransform reconstructed from the angular grid and the CRS satellite height, with its x axis reconciled to the CRS so a warp is not mirrored east-west — issue #56).

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]); read_fci_l1c(paths, "ir_105") is unchanged.

Parameters:

Name Type Description Default
paths Any

Iterable of FCI L1C FDHSI chunk file paths (any order; trailer / non-imagery chunks are skipped).

required
channel str | None

A single channel identifier (e.g. "ir_105", "vis_06") for a Dataset result; mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channel identifiers for a dict[str, Dataset] result (each chunk opened once for the whole set); mutually exclusive with channel.

None
calibrate bool

When True (default), calibrate to reflectance / brightness temperature; when False, return the stitched raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance. The default 1.0 leaves reflectance up to ~3.4% off (d ranges ~0.983-1.017 AU over the year); pass the granule's d for absolute accuracy.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] keyed by

Any

channel (for channels) of the calibrated (or raw) channel(s) on the

Any

stitched geostationary grid, with NaN nodata and the geostationary CRS.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, when no chunk carries a requested channel, or the chunks are inconsistent (mixed CRS / cell size / column count, or not vertically contiguous — see _validate_chunks).

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When a channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/fci_l1c.py
def read_fci_l1c(
    paths: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
) -> Any:
    """Read one or several channels across a set of real FCI L1C FDHSI chunks.

    Decodes each chunk once for the whole requested channel set
    (`read_fci_l1c_chunks` opens the chunk's structure a single time), drops chunks
    without a channel's radiance (e.g. `CHK-TRAIL`), then for each channel orders
    the chunks north -> south by their geotransform Y origin, checks they are
    vertically contiguous (and share a grid), stitches the radiance, and calibrates
    it with the **per-granule** coefficients (reflectance for a solar channel,
    brightness temperature for a thermal one). Each result is a geolocated pyramids
    `Dataset` on the granule's geostationary grid (metre geotransform reconstructed
    from the angular grid and the CRS satellite height, with its x axis reconciled
    to the CRS so a warp is not mirrored east-west — issue #56).

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`); `read_fci_l1c(paths, "ir_105")` is unchanged.

    Args:
        paths: Iterable of FCI L1C FDHSI chunk file paths (any order; trailer /
            non-imagery chunks are skipped).
        channel: A single channel identifier (e.g. `"ir_105"`, `"vis_06"`) for a
            `Dataset` result; mutually exclusive with `channels`.
        channels: A sequence of channel identifiers for a `dict[str, Dataset]`
            result (each chunk opened once for the whole set); mutually exclusive
            with `channel`.
        calibrate: When `True` (default), calibrate to reflectance / brightness
            temperature; when `False`, return the stitched raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
            The default `1.0` leaves reflectance up to ~3.4% off (`d` ranges
            ~0.983-1.017 AU over the year); pass the granule's `d` for absolute
            accuracy.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` keyed by
        channel (for `channels`) of the calibrated (or raw) channel(s) on the
        stitched geostationary grid, with NaN nodata and the geostationary CRS.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given, when
            no chunk carries a requested channel, or the chunks are inconsistent
            (mixed CRS / cell size / column count, or not vertically contiguous —
            see `_validate_chunks`).
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When a channel is not in the registry.
    """
    requested, single = resolve_channels(channel, channels, "read_fci_l1c")

    per_channel: dict[str, list] = {name: [] for name in requested}
    for path in paths:
        for name, record in read_fci_l1c_chunks(path, requested).items():
            if record is not None:
                per_channel[name].append(record)

    results = {
        name: _assemble_channel(
            per_channel[name],
            name,
            calibrate=calibrate,
            sun_earth_distance=sun_earth_distance,
            cos_sza=cos_sza,
        )
        for name in requested
    }
    return results[requested[0]] if single else results

available_olci_channels(source) #

List the OLCI radiance bands a granule actually carries.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required

Returns:

Type Description
list[str]

The canonical channel names present, sorted (["Oa01", "Oa02", ...]).

Raises:

Type Description
ReaderError

When source is not a granule directory or a file in one.

Source code in src/pyramids_eo/sensors/readers/olci.py
def available_olci_channels(source: Any) -> list[str]:
    """List the OLCI radiance bands a granule actually carries.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.

    Returns:
        The canonical channel names present, sorted (`["Oa01", "Oa02", ...]`).

    Raises:
        ReaderError: When `source` is not a granule directory or a file in one.
    """
    granule = resolve_granule(source, "available_olci_channels")
    found = []
    for number in range(1, _BAND_COUNT + 1):
        channel = f"Oa{number:02d}"
        if (granule / _band_filename(channel)).is_file():
            found.append(channel)
    return found

product_type(granule) #

Detect whether a granule is the full- or reduced-resolution OLCI product.

EFR and ERR granules hold the same OaNN_radiance.nc filenames and the same variable names, so the product type -- and therefore the ground resolution, 300 m against ~1200 m -- is only knowable from the granule's own naming or its manifest. Both are checked -- the name first, then xfdumanifest.xml -- and None means neither identified the product, in which case the reader reports no resolution rather than asserting a wrong one.

An ambiguous source is treated exactly like a silent one: a text carrying both tokens yields None rather than the first match, because an ERR granule routinely references the EFR product it was derived from, so preferring either one would be a guess (see _product_tokens).

Parameters:

Name Type Description Default
granule Path

The .SEN3 granule directory.

required

Returns:

Type Description
str | None

"EFR", "ERR", or None -- when the granule does not identify itself,

str | None

and equally when it names both products.

Examples:

  • A standard product name identifies itself, so no file access is needed:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("S3A_OL_1_EFR____20230101T101530.SEN3"))
    'EFR'
    >>> product_type(Path("S3B_OL_1_ERR____20230101T101530.SEN3"))
    'ERR'
    
  • A granule that names neither, and carries no manifest saying so, yields None -- which is what makes the reader omit resolution_m rather than guess it:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("mystery.SEN3")) is None
    True
    
  • A name claiming both products is ambiguous, so it too yields None rather than the first token found:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("S3A_OL_1_ERR____from_OL_1_EFR_source.SEN3")) is None
    True
    
Source code in src/pyramids_eo/sensors/readers/olci.py
def product_type(granule: Path) -> str | None:
    """Detect whether a granule is the full- or reduced-resolution OLCI product.

    EFR and ERR granules hold the **same** `OaNN_radiance.nc` filenames and the
    same variable names, so the product type -- and therefore the ground
    resolution, 300 m against ~1200 m -- is only knowable from the granule's own
    naming or its manifest. Both are checked -- the name first, then
    `xfdumanifest.xml` -- and `None` means neither identified the product, in
    which case the reader reports no resolution rather than asserting a wrong one.

    An **ambiguous** source is treated exactly like a silent one: a text carrying
    both tokens yields `None` rather than the first match, because an ERR granule
    routinely references the EFR product it was derived from, so preferring either
    one would be a guess (see `_product_tokens`).

    Args:
        granule: The `.SEN3` granule directory.

    Returns:
        `"EFR"`, `"ERR"`, or `None` -- when the granule does not identify itself,
        and equally when it names both products.

    Examples:
        - A standard product name identifies itself, so no file access is needed:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("S3A_OL_1_EFR____20230101T101530.SEN3"))
            'EFR'
            >>> product_type(Path("S3B_OL_1_ERR____20230101T101530.SEN3"))
            'ERR'

            ```
        - A granule that names neither, and carries no manifest saying so, yields
          `None` -- which is what makes the reader omit `resolution_m` rather than
          guess it:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("mystery.SEN3")) is None
            True

            ```
        - A name claiming both products is ambiguous, so it too yields `None`
          rather than the first token found:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("S3A_OL_1_ERR____from_OL_1_EFR_source.SEN3")) is None
            True

            ```
    """
    found = _product_tokens(granule.name.upper(), "_OL_1_")
    if found is not None:
        return found
    manifest = granule / "xfdumanifest.xml"
    if manifest.is_file():
        try:
            text = manifest.read_text(encoding="utf-8", errors="replace").upper()
        except OSError:
            return None
        return _product_tokens(text, "OL_1_")
    return None

read_olci(source, channel=None, *, channels=None, geolocation=True) #

Read one or several OLCI L1B radiance bands from a .SEN3 granule.

Decodes each requested band's packed OaNN_radiance variable (raw * scale_factor + add_offset, with the _FillValue and anything outside the variable's validity limits masked to NaN) and returns it as a swath Dataset carrying the granule's per-pixel geolocation as a GDAL GEOLOCATION domain. The limits come from the valid_min / valid_max scalars the OLCI L1 specification carries -- not from a combined valid_range, which appears nowhere in it -- and are compared against the raw, still-packed values.

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset] keyed by canonical channel name).

This reader decodes only -- it does not convert radiance to reflectance (issue #136 scopes radiometric calibration choices out). The granule's instrument_data.nc carries the per-detector solar_flux a caller needs for that conversion.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or any file inside it.

required
channel str | None

A single band ("Oa08"); mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of bands for a dict result; mutually exclusive with channel.

None
geolocation bool

When True (default), attach each result's per-pixel GEOLOCATION domain from geo_coordinates.nc.

True

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] (for

Any

channels), each on the granule's native swath grid with NaN nodata.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, channels is empty or has duplicates, a band name is not an OLCI band, or the granule lacks a requested band. A channel set whose bands come back on different shapes also raises: the one geolocation domain is shared across the set, which is only sound because the bands of a granule share a grid, so a granule that breaks that is reported rather than geolocated against the wrong grid. With geolocation=True, also when geo_coordinates.nc or its variables are missing, its grid's shape differs from the bands', or it carries an unusable scale_factor / add_offset.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning per affected band and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/olci.py
def read_olci(
    source: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    geolocation: bool = True,
) -> Any:
    """Read one or several OLCI L1B radiance bands from a `.SEN3` granule.

    Decodes each requested band's packed `OaNN_radiance` variable (`raw *
    scale_factor + add_offset`, with the `_FillValue` and anything outside the
    variable's validity limits masked to NaN) and returns it as a swath `Dataset`
    carrying the granule's per-pixel geolocation as a GDAL `GEOLOCATION` domain.
    The limits come from the `valid_min` / `valid_max` scalars the OLCI L1
    specification carries -- not from a combined `valid_range`, which appears
    nowhere in it -- and are compared against the raw, still-packed values.

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]` keyed by canonical channel name).

    This reader **decodes only** -- it does not convert radiance to reflectance
    (issue #136 scopes radiometric calibration choices out). The granule's
    `instrument_data.nc` carries the per-detector `solar_flux` a caller needs for
    that conversion.

    Args:
        source: The `.SEN3` granule directory, or any file inside it.
        channel: A single band (`"Oa08"`); mutually exclusive with `channels`.
        channels: A sequence of bands for a `dict` result; mutually exclusive
            with `channel`.
        geolocation: When `True` (default), attach each result's per-pixel
            `GEOLOCATION` domain from `geo_coordinates.nc`.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` (for
        `channels`), each on the granule's native swath grid with NaN nodata.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given,
            `channels` is empty or has duplicates, a band name is not an OLCI
            band, or the granule lacks a requested band. A channel set whose bands
            come back on **different** shapes also raises: the one geolocation
            domain is shared across the set, which is only sound because the bands
            of a granule share a grid, so a granule that breaks that is reported
            rather than geolocated against the wrong grid. With
            `geolocation=True`, also when `geo_coordinates.nc` or its variables are
            missing, its grid's shape differs from the bands', or it carries an
            unusable `scale_factor` / `add_offset`.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` per affected band and the result's nodata is
        incomplete rather than the read failing (see `invalid_mask`).
    """
    requested, single = resolve_channels(channel, channels, "read_olci")
    # Canonicalise before the duplicate check: `resolve_channels` compares the raw
    # strings, so aliases of one band ("Oa08" and "oa8") slip through it and would
    # otherwise collapse into a single dict entry, silently dropping a requested band.
    canonical = [_canonical_channel(name, "read_olci") for name in requested]
    if len(set(canonical)) != len(canonical):
        duplicates = sorted({c for c in canonical if canonical.count(c) > 1})
        raise ReaderError(
            f"read_olci: `channels` names the same band more than once (after "
            f"normalising spellings): {duplicates}"
        )
    # Resolve the granule and its geolocation domain ONCE for the whole set,
    # matching read_fci_l1c's documented read-each-chunk-once pattern rather than
    # re-running them per channel.
    reader = "read_olci"
    granule = resolve_granule(source, reader)
    # Detect the product type once for the whole set rather than per band: it may
    # read xfdumanifest.xml, which a 21-band read would otherwise re-parse 21 times.
    product = product_type(granule)
    decoded = {name: _read_band(granule, name, reader) for name in canonical}
    shapes = {name: values.shape for name, (values, _) in decoded.items()}
    if len(set(shapes.values())) > 1:
        raise ReaderError(
            f"read_olci: the requested bands are not on one grid: {shapes}; OLCI "
            f"bands of a granule share a grid, so this granule looks inconsistent"
        )
    first = next(iter(decoded.values()))[0]
    domain = _resolve_domain(granule, reader, first.shape) if geolocation else {}
    results = {
        name: _wrap_band(granule, name, values, variable_meta, domain, product)
        for name, (values, variable_meta) in decoded.items()
    }
    return results[canonical[0]] if single else results

parse_seviri_native(path, channel, *, subsatellite_longitude=0.0) #

Decode one VIS/IR channel of an MSG Level-1.5 native (.nat) granule.

Reads the segment table and the fixed-layout 15Header (reference grid, grid step and the per-granule calibration), then unpacks the channel's 10-bit counts from every image line record, applies the granule Cal_Slope / Cal_Offset to get radiance, masks the zero-count (off-earth) corners to NaN, and orients the scene north-up / west-left. Only the image lines actually present are read, so a header-preserved subset (whose header still declares the full disk) decodes correctly rather than reading past end-of-file.

Parameters:

Name Type Description Default
path Any

Path to an MSG SEVIRI Level-1.5 native .nat file.

required
channel str

A VIS/IR channel identifier (e.g. "IR_108", "VIS006"); HRV is not supported.

required
subsatellite_longitude float

Sub-satellite longitude (degrees east) for the geostationary CRS. Defaults to 0.0, the nominal prime service (MSG15); pass the service longitude for IODC (41.5) or rapid-scan (9.5) granules, whose .nat header the reader does not parse for it.

0.0

Returns:

Type Description
Any

A pyramids Dataset holding the channel radiance on the geostationary

Any

grid, with the geostationary CRS, a metre geotransform, and NaN nodata.

Raises:

Type Description
ReaderError

When the channel is unknown / HRV, the file is not a recognised MSG Level-1.5 native granule (no segment table, or the 15Header layout / calibration fails its sanity checks), the file carries no complete line record, or the decoded line records are not contiguous (an unexpected channel selection or layout).

Source code in src/pyramids_eo/sensors/readers/seviri.py
def parse_seviri_native(
    path: Any, channel: str, *, subsatellite_longitude: float = 0.0
) -> Any:
    """Decode one VIS/IR channel of an MSG Level-1.5 native (`.nat`) granule.

    Reads the segment table and the fixed-layout ``15Header`` (reference grid,
    grid step and the per-granule calibration), then unpacks the channel's 10-bit
    counts from every image line record, applies the granule ``Cal_Slope`` /
    ``Cal_Offset`` to get radiance, masks the zero-count (off-earth) corners to
    NaN, and orients the scene north-up / west-left. Only the image lines
    actually present are read, so a header-preserved subset (whose header still
    declares the full disk) decodes correctly rather than reading past end-of-file.

    Args:
        path: Path to an MSG SEVIRI Level-1.5 native `.nat` file.
        channel: A VIS/IR channel identifier (e.g. `"IR_108"`, `"VIS006"`); HRV
            is not supported.
        subsatellite_longitude: Sub-satellite longitude (degrees east) for the
            geostationary CRS. Defaults to `0.0`, the nominal prime service
            (`MSG15`); pass the service longitude for IODC (41.5) or rapid-scan
            (9.5) granules, whose `.nat` header the reader does not parse for it.

    Returns:
        A pyramids `Dataset` holding the channel radiance on the geostationary
        grid, with the geostationary CRS, a metre geotransform, and NaN nodata.

    Raises:
        ReaderError: When the channel is unknown / HRV, the file is not a
            recognised MSG Level-1.5 native granule (no segment table, or the
            ``15Header`` layout / calibration fails its sanity checks), the file
            carries no complete line record, or the decoded line records are not
            contiguous (an unexpected channel selection or layout).
    """
    if channel == "HRV":
        raise ReaderError("read_seviri: HRV is not supported (different geometry)")
    try:
        position = _VISIR_CHANNELS.index(channel)
    except ValueError as exc:
        raise ReaderError(
            f"read_seviri: unknown SEVIRI VIS/IR channel {channel!r}"
        ) from exc

    try:
        handle = open(path, "rb")
    except OSError as exc:
        raise ReaderError(f"read_seviri: cannot open {path} ({exc})") from exc
    with handle:
        segments = _segments(handle.read(_PRODUCT_HEADER_SCAN_BYTES))
        try:
            header_length, header_offset = segments["15Header"]
            data_length, data_offset = segments["15Data"]
        except KeyError as exc:
            raise ReaderError(
                "read_seviri: no 15Header/15Data segment table "
                f"(not an MSG Level-1.5 native file?) — {path}"
            ) from exc
        handle.seek(header_offset)
        header = handle.read(header_length)
        if len(header) < _CALIBRATION_OFFSET + 12 * 16:
            raise ReaderError(
                "read_seviri: 15Header is truncated "
                "(not a supported MSG Level-1.5 native file)"
            )
        file_size = os.fstat(handle.fileno()).st_size

    lines_declared, columns = struct.unpack_from(">ii", header, _REF_GRID_OFFSET)
    line_step_km, column_step_km = struct.unpack_from(">ff", header, _GRID_STEP_OFFSET)
    # The reference grid and grid step sit immediately before the calibration
    # block: sane values here confirm the fixed 15Header layout was found. The
    # line and column steps must match (the VIS/IR grid is isotropic 3 km).
    if not (
        lines_declared == columns
        and 1000 <= columns <= 12000
        and 2.9 < column_step_km < 3.1
        and np.isclose(line_step_km, column_step_km)
        and columns % 4 == 0
    ):
        raise ReaderError(
            "read_seviri: unexpected 15Header layout (reference grid / grid step "
            "sanity check failed) — not a supported MSG Level-1.5 native file"
        )
    pixel_m = column_step_km * 1000.0

    slope, offset = struct.unpack_from(
        ">dd", header, _CALIBRATION_OFFSET + position * 16
    )
    if slope <= 0:
        raise ReaderError(
            "read_seviri: non-physical calibration slope (unexpected header layout)"
        )

    if data_length % lines_declared:
        raise ReaderError(
            "read_seviri: 15Data length is not a whole number of line records"
        )
    stride = data_length // lines_declared
    packed_bytes = columns * 10 // 8
    # The 11 VIS/IR channels precede HRV in every record; assume the standard
    # all-channel product so channel `position` maps straight to block `position`.
    # The contiguity check below rejects a file where that assumption does not hold.
    block_start = position * (_LINE_SIDE_INFO_BYTES + packed_bytes)
    data_start = block_start + _LINE_SIDE_INFO_BYTES
    if data_start + packed_bytes > stride:
        raise ReaderError("read_seviri: channel block exceeds the line-record stride")

    # The declared 15Data holds exactly `lines_declared` records; a full product
    # has a 15Trailer segment after it, so cap the count at the declared line
    # count. Without this cap the trailer bytes get read as extra "line records",
    # break the +1 contiguity of `line_numbers`, and reject a valid full disk.
    # The file-size term still handles a header-preserved subset (fewer records).
    available = min((file_size - data_offset) // stride, lines_declared)
    if available < 1:
        raise ReaderError("read_seviri: file carries no complete image line record")

    counts = np.empty((available, columns), dtype=np.uint16)
    line_numbers = np.empty(available, dtype=np.int64)
    with (
        open(path, "rb") as handle,
        mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mapped,
    ):
        for index in range(available):
            record = data_offset + index * stride
            line_numbers[index] = struct.unpack_from(
                ">i", mapped, record + block_start + _LINE_NUMBER_OFFSET
            )[0]
            start = record + data_start
            counts[index] = _unpack_10bit(mapped[start : start + packed_bytes], columns)

    if not np.all(np.diff(line_numbers) == 1):
        raise ReaderError(
            "read_seviri: image line records are not contiguous "
            "(unexpected channel selection or record layout)"
        )

    radiance = counts.astype(float) * slope + offset
    radiance[counts == 0] = np.nan  # zero counts mark the off-earth space corners
    # The grid origin is South-East: line numbers increase northward and the
    # stored columns run east -> west (the first column is East). Reverse both
    # axes for a north-up, west-left raster. Copy the flipped view to a
    # C-contiguous array so no downstream consumer trips on the negative strides.
    radiance = np.ascontiguousarray(radiance[::-1, ::-1])

    # CGMS/EUMETSAT navigation places the sub-satellite point at the CENTRE of the
    # reference pixel N/2 (0-based, both axes; e.g. pixel 1856 of the 3712 grid) —
    # the COFF = LOFF convention, which reproduces the published MSG full-disk area
    # extent (west edge -(N/2 + 0.5) * px). All columns are present (full width) so
    # the SSP column is N/2; only a subset of lines may be present, so the SSP row
    # is N/2 measured from the northmost present line (row 0 after the north-up
    # flip). Register the metre geotransform so that reference pixel's centre is
    # (x=0, y=0).
    reference = columns / 2.0  # == lines_declared / 2.0 for the square VIS/IR grid
    ssp_row = int(line_numbers[-1]) - reference
    x_west_edge = -(reference + 0.5) * pixel_m
    y_north_edge = (ssp_row + 0.5) * pixel_m
    geo = (x_west_edge, pixel_m, 0.0, y_north_edge, 0.0, -pixel_m)

    from pyramids.dataset import Dataset, GeoReference

    dataset = Dataset.from_array(
        radiance, geo_ref=GeoReference(geo=geo, epsg=None), no_data_value=np.nan
    )
    dataset.crs = _geostationary_wkt(subsatellite_longitude)
    return dataset

read_seviri(source, channel, *, sensor='seviri', calibrate=True, sun_earth_distance=1.0, cos_sza=None, coeffs=None, parse=None, subsatellite_longitude=0.0) #

Read one SEVIRI channel into a calibrated, geolocated Dataset.

Decodes the channel radiance (from a .nat granule via parse, or straight from a Dataset source), then calibrates it to reflectance (solar) or brightness temperature (thermal) via the registry and returns a pyramids Dataset carrying the source's CRS + geotransform.

Parameters:

Name Type Description Default
source Any

A path to an MSG Level-1.5 native .nat file (decoded by parse), or a pyramids Dataset already holding the channel radiance.

required
channel str

Channel identifier (e.g. "IR_108", "VIS006").

required
sensor str

Registry sensor name (default "seviri").

'seviri'
calibrate bool

When True (default), calibrate to a physical quantity; when False, return the raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance. The default 1.0 leaves reflectance up to ~3.4% off (d ranges ~0.983-1.017 AU over the year); pass the granule's d for absolute accuracy.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None
coeffs dict[str, Any] | None

Per-granule calibration coefficients preferred over the registry fallback (see calibrate_channel), or None to use the registry.

None
parse Any

Callable (source, channel) -> Dataset used when source is not already a Dataset. Defaults to the native .nat parser (parse_seviri_native).

None
subsatellite_longitude float

Sub-satellite longitude (degrees east) passed to the default native parser for the geostationary CRS (default 0.0, the prime service); ignored when a custom parse is supplied.

0.0

Returns:

Type Description
Any

A pyramids Dataset of the calibrated (or raw) channel.

Raises:

Type Description
ReaderError

When source is None, or the native parse fails.

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When the sensor / channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/seviri.py
def read_seviri(
    source: Any,
    channel: str,
    *,
    sensor: str = "seviri",
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
    coeffs: dict[str, Any] | None = None,
    parse: Any = None,
    subsatellite_longitude: float = 0.0,
) -> Any:
    """Read one SEVIRI channel into a calibrated, geolocated `Dataset`.

    Decodes the channel radiance (from a `.nat` granule via `parse`, or straight
    from a `Dataset` source), then calibrates it to reflectance (solar) or
    brightness temperature (thermal) via the registry and returns a pyramids
    `Dataset` carrying the source's CRS + geotransform.

    Args:
        source: A path to an MSG Level-1.5 native `.nat` file (decoded by
            `parse`), or a pyramids `Dataset` already holding the channel radiance.
        channel: Channel identifier (e.g. `"IR_108"`, `"VIS006"`).
        sensor: Registry sensor name (default `"seviri"`).
        calibrate: When `True` (default), calibrate to a physical quantity; when
            `False`, return the raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
            The default `1.0` leaves reflectance up to ~3.4% off (`d` ranges
            ~0.983-1.017 AU over the year); pass the granule's `d` for absolute
            accuracy.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.
        coeffs: Per-granule calibration coefficients preferred over the registry
            fallback (see `calibrate_channel`), or `None` to use the registry.
        parse: Callable `(source, channel) -> Dataset` used when `source` is not
            already a `Dataset`. Defaults to the native `.nat` parser
            (`parse_seviri_native`).
        subsatellite_longitude: Sub-satellite longitude (degrees east) passed to
            the default native parser for the geostationary CRS (default `0.0`,
            the prime service); ignored when a custom `parse` is supplied.

    Returns:
        A pyramids `Dataset` of the calibrated (or raw) channel.

    Raises:
        ReaderError: When `source` is `None`, or the native parse fails.
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When the sensor / channel is not in the registry.
    """
    if source is None:
        raise ReaderError("read_seviri: source is required")

    if hasattr(source, "read_array"):
        dataset = source
    elif parse is not None:
        dataset = parse(source, channel)
    else:
        dataset = parse_seviri_native(
            source, channel, subsatellite_longitude=subsatellite_longitude
        )
    radiance = np.asarray(dataset.read_array(), dtype=float)
    data = (
        calibrate_channel(
            radiance, channel, sensor, sun_earth_distance, cos_sza, coeffs=coeffs
        )
        if calibrate
        else radiance
    )

    from pyramids.dataset import Dataset, GeoReference

    # Calibration can produce NaN (terminator reflectance / non-positive
    # radiance), so declare NaN as nodata rather than the default -9999.
    epsg = dataset.epsg if dataset.epsg else None
    result = Dataset.from_array(
        data,
        geo_ref=GeoReference(geo=dataset.geotransform, epsg=epsg),
        no_data_value=np.nan,
    )
    if epsg is None:
        # A non-EPSG CRS (e.g. the geostationary grid) must be carried explicitly.
        result.crs = dataset.crs
    return result

available_slstr_channels(source, *, view='nadir') #

Report which channels a granule carries in one view, and on which grids.

This is how a caller discovers a product's real layout rather than assuming it -- including that F2 lives on the 1 km i grid while F1 is on f, and which of S4-S6 are duplicated onto the alternative 500 m b grid.

A grid is listed only when the granule holds both the measurement file and the geodetic_<grid><view>.nc the measurement needs, so what this reports is what read_slstr can actually return -- a measurement whose annotation file is missing would raise there, and listing it would promise a read that fails. A granule stripped of its geodetic files therefore reports {} even though the measurement files are all present.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required
view str

"nadir" (default) or "oblique".

'nadir'

Returns:

Type Description
dict[str, list[str]]

A {channel: [grid letters]} mapping listing only the channels the granule

dict[str, list[str]]

holds a measurement and a matching geodetic file for, in the product's

dict[str, list[str]]

own channel order -- S1..S9 then F1, F2 -- which is not the

dict[str, list[str]]

alphabetical order the error messages use. Each channel's grid letters are

dict[str, list[str]]

likewise in the order read_slstr would try them.

Raises:

Type Description
ReaderError

When source is not a granule, or view is not an SLSTR view.

Source code in src/pyramids_eo/sensors/readers/slstr.py
def available_slstr_channels(
    source: Any, *, view: str = "nadir"
) -> dict[str, list[str]]:
    """Report which channels a granule carries in one view, and on which grids.

    This is how a caller discovers a product's real layout rather than assuming
    it -- including that `F2` lives on the 1 km `i` grid while `F1` is on `f`, and
    which of `S4`-`S6` are duplicated onto the alternative 500 m `b` grid.

    A grid is listed only when the granule holds **both** the measurement file and
    the `geodetic_<grid><view>.nc` the measurement needs, so what this reports is
    what `read_slstr` can actually return -- a measurement whose annotation file is
    missing would raise there, and listing it would promise a read that fails. A
    granule stripped of its geodetic files therefore reports `{}` even though the
    measurement files are all present.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.
        view: `"nadir"` (default) or `"oblique"`.

    Returns:
        A `{channel: [grid letters]}` mapping listing only the channels the granule
        holds a measurement **and** a matching geodetic file for, in the product's
        own channel order -- `S1`..`S9` then `F1`, `F2` -- which is not the
        alphabetical order the error messages use. Each channel's grid letters are
        likewise in the order `read_slstr` would try them.

    Raises:
        ReaderError: When `source` is not a granule, or `view` is not an SLSTR
            view.
    """
    reader = "available_slstr_channels"
    suffix = _resolve_view(view, reader)
    granule = resolve_granule(source, reader)
    found: dict[str, list[str]] = {}
    for channel, (grids, quantity) in _CHANNEL_GRIDS.items():
        present = [
            letter
            for letter in grids
            if (granule / f"{channel}_{quantity}_{letter}{suffix}.nc").is_file()
            and (granule / f"geodetic_{letter}{suffix}.nc").is_file()
        ]
        if present:
            found[channel] = present
    return found

read_slstr(source, channel=None, *, channels=None, view=None, grid=None, geolocation=True) #

Read one or several SLSTR L1 RBT channels from a .SEN3 granule.

Decodes each requested channel's packed variable (raw * scale_factor + add_offset, with the _FillValue and anything outside the variable's validity limits masked to NaN) and returns it as a swath Dataset carrying the matching grid's per-pixel geolocation as a GDAL GEOLOCATION domain. The limits come from the valid_min / valid_max scalars the SLSTR L1 specification carries -- not from a combined valid_range, which appears nowhere in it -- and are compared against the raw, still-packed values.

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]). Channels on different grids have different array shapes, which is why a channel set returns a dict rather than a stack.

Either may also be given in the product's own variable spelling ("S5_radiance_bn"), and the grid and view it carries then select the file: they are honoured, not merely tolerated. So a channel set may mix views and grids per channel -- channels=["S5_radiance_an", "S8_BT_io"] reads one nadir and one oblique -- while view= / grid= supply whatever a bare spelling leaves open. A spelling that contradicts an explicit view= / grid= is an error rather than one of the two being silently ignored.

This reader decodes only -- issue #136 scopes radiometric calibration choices out. The RBT product is already geophysical, so S7-S9 / F1-F2 arrive as brightness temperature in kelvin with no conversion applied.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or any file inside it.

required
channel str | None

A single channel ("S5", or "S5_radiance_bn"); mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channels for a dict result; mutually exclusive with channel. The dict is keyed by canonical channel name, so two spellings of one channel -- even on different grids, as ["S5_radiance_an", "S5_radiance_bn"] -- are rejected as a duplicate rather than collapsing into one entry.

None
view str | None

"nadir" or "oblique" -- SLSTR images each scene twice. None (default) takes each channel's view from its own spelling, falling back to nadir for a bare one.

None
grid str | None

An explicit grid letter ("a", "b", "i", "f") restricting every channel to that one grid. None (default) uses a spelled grid where one is given and otherwise tries the channel's documented grids in order. A restricted read never falls back to another resolution: a channel the granule does not carry on that grid raises instead.

None
geolocation bool

When True (default), attach each result's GEOLOCATION domain.

True

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] (for

Any

channels), each on its native swath grid with NaN nodata.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, channels is empty or names a channel twice, a channel or the view is not an SLSTR one, a spelled channel names a quantity that channel does not ship or a grid / view contradicting an explicit grid= / view=, grid is not one of the four SLSTR grid letters, or the granule lacks a requested channel on the grid(s) tried. With geolocation=True, also when a channel's geodetic annotation is missing, is on a grid whose shape differs from the band, or carries an unusable scale_factor / add_offset.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning per affected channel and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/slstr.py
def read_slstr(
    source: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    view: str | None = None,
    grid: str | None = None,
    geolocation: bool = True,
) -> Any:
    """Read one or several SLSTR L1 RBT channels from a `.SEN3` granule.

    Decodes each requested channel's packed variable (`raw * scale_factor +
    add_offset`, with the `_FillValue` and anything outside the variable's
    validity limits masked to NaN) and returns it as a swath `Dataset` carrying
    the matching grid's per-pixel geolocation as a GDAL `GEOLOCATION` domain. The
    limits come from the `valid_min` / `valid_max` scalars the SLSTR L1
    specification carries -- not from a combined `valid_range`, which appears
    nowhere in it -- and are compared against the raw, still-packed values.

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`). Channels on different grids have **different array
    shapes**, which is why a channel set returns a dict rather than a stack.

    Either may also be given in the product's own variable spelling
    (`"S5_radiance_bn"`), and the grid and view it carries then **select the
    file**: they are honoured, not merely tolerated. So a channel set may mix views
    and grids per channel -- `channels=["S5_radiance_an", "S8_BT_io"]` reads one
    nadir and one oblique -- while `view=` / `grid=` supply whatever a bare
    spelling leaves open. A spelling that contradicts an explicit `view=` / `grid=`
    is an error rather than one of the two being silently ignored.

    This reader **decodes only** -- issue #136 scopes radiometric calibration
    choices out. The RBT product is already geophysical, so `S7`-`S9` / `F1`-`F2`
    arrive as brightness temperature in kelvin with no conversion applied.

    Args:
        source: The `.SEN3` granule directory, or any file inside it.
        channel: A single channel (`"S5"`, or `"S5_radiance_bn"`); mutually
            exclusive with `channels`.
        channels: A sequence of channels for a `dict` result; mutually exclusive
            with `channel`. The dict is keyed by **canonical** channel name, so two
            spellings of one channel -- even on different grids, as
            `["S5_radiance_an", "S5_radiance_bn"]` -- are rejected as a duplicate
            rather than collapsing into one entry.
        view: `"nadir"` or `"oblique"` -- SLSTR images each scene twice. `None`
            (default) takes each channel's view from its own spelling, falling back
            to nadir for a bare one.
        grid: An explicit grid letter (`"a"`, `"b"`, `"i"`, `"f"`) restricting
            every channel to that one grid. `None` (default) uses a spelled grid
            where one is given and otherwise tries the channel's documented grids
            in order. A restricted read never falls back to another resolution: a
            channel the granule does not carry on that grid raises instead.
        geolocation: When `True` (default), attach each result's `GEOLOCATION`
            domain.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` (for
        `channels`), each on its native swath grid with NaN nodata.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given,
            `channels` is empty or names a channel twice, a channel or the view
            is not an SLSTR one, a spelled channel names a quantity that channel
            does not ship or a grid / view contradicting an explicit `grid=` /
            `view=`, `grid` is not one of the four SLSTR grid letters, or the
            granule lacks a requested channel on the grid(s) tried. With
            `geolocation=True`, also when a channel's geodetic annotation is
            missing, is on a grid whose shape differs from the band, or carries an
            unusable `scale_factor` / `add_offset`.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` per affected channel and the result's nodata
        is incomplete rather than the read failing (see `invalid_mask`).
    """
    requested, single = resolve_channels(channel, channels, "read_slstr")
    # Canonicalise before the duplicate check: `resolve_channels` compares the raw
    # strings, so aliases of one channel ("S5" and "s5") slip through it and would
    # otherwise collapse into a single dict entry, silently dropping a request.
    canonical = [_canonical_channel(name, "read_slstr") for name in requested]
    if len(set(canonical)) != len(canonical):
        duplicates = sorted({c for c in canonical if canonical.count(c) > 1})
        raise ReaderError(
            f"read_slstr: `channels` names the same channel more than once (after "
            f"normalising spellings): {duplicates}"
        )
    # Pass the caller's ORIGINAL spelling through, not the canonical name: a
    # spelled grid and view select a specific file, and canonicalising first would
    # strip them and read a different one.
    # Resolve the granule once for the whole set rather than per channel, matching
    # read_fci_l1c's and read_olci's read-once pattern.
    granule = resolve_granule(source, "read_slstr")
    results = {
        name: read_slstr_band(
            granule, spelling, view=view, grid=grid, geolocation=geolocation
        )
        for name, spelling in zip(canonical, requested)
    }
    return results[canonical[0]] if single else results

pyramids_eo.sensors.readers.fci_l1c #

Real MTG-FCI L1C FDHSI granule reader.

read_fci_l1c decodes and stitches one channel — or several in a single pass (channels=[...] returns a dict, reading each chunk's structure and coefficients once for the whole set) — across the real FCI L1C FDHSI chunk files of a repeat cycle, and available_channels lists which channels a chunk carries. Unlike the generic read_fci (which stitches already-opened radiance Datasets), this reads the actual granule layout:

  • the packed uint16 radiance from the nested group data/<channel>/measured/effective_radiance, unpacked to physical radiance via the variable's scale_factor / add_offset and masked by its valid_range / _FillValue;
  • the per-granule calibration coefficients carried as sibling variables in the same group (radiance_to_bt_conversion_coefficient_a / _b / _wavenumber for thermal channels, channel_effective_solar_irradiance for solar ones), preferred over the nominal registry table;
  • the chunks are ordered and stitched by their geostationary geotransform Y origin (FCI's start_position_row runs opposite to the geospatial Y, so it is read as metadata but is not the stitch key); a chunk that carries no radiance for the channel — e.g. the CHK-TRAIL trailer — is skipped.

The granule stores the grid in geostationary angular (radian) coordinates with a metre geostationary CRS; the metre geotransform is reconstructed as angular_geotransform * satellite_height (from the CRS +h). This addresses the axis-unit mismatch behind pyramids #706 by keeping the CRS explicit rather than letting it be misread as lon/lat. FCI's x is a scanning azimuth angle whose sign runs opposite to PROJ's geostationary x (which increases eastward), so the scaled x pixel width comes out negative with its origin on the eastern limb; the reader reconciles it to the CRS — re-anchoring the origin on the western limb with a positive x width, the array left untouched — so a warped scene is not mirrored east-west (issue #56).

Validated against real MTI1/Meteosat-12 FDHSI chunks (see issue #40): ir_105 stitches to brightness temperature in the expected range on the geostationary grid. The reader uses GDAL (already vendored by pyramids) to read the nested groups and scalar variables — no extra dependency.

read_fci_l1c(paths, channel=None, *, channels=None, calibrate=True, sun_earth_distance=1.0, cos_sza=None) #

Read one or several channels across a set of real FCI L1C FDHSI chunks.

Decodes each chunk once for the whole requested channel set (read_fci_l1c_chunks opens the chunk's structure a single time), drops chunks without a channel's radiance (e.g. CHK-TRAIL), then for each channel orders the chunks north -> south by their geotransform Y origin, checks they are vertically contiguous (and share a grid), stitches the radiance, and calibrates it with the per-granule coefficients (reflectance for a solar channel, brightness temperature for a thermal one). Each result is a geolocated pyramids Dataset on the granule's geostationary grid (metre geotransform reconstructed from the angular grid and the CRS satellite height, with its x axis reconciled to the CRS so a warp is not mirrored east-west — issue #56).

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]); read_fci_l1c(paths, "ir_105") is unchanged.

Parameters:

Name Type Description Default
paths Any

Iterable of FCI L1C FDHSI chunk file paths (any order; trailer / non-imagery chunks are skipped).

required
channel str | None

A single channel identifier (e.g. "ir_105", "vis_06") for a Dataset result; mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channel identifiers for a dict[str, Dataset] result (each chunk opened once for the whole set); mutually exclusive with channel.

None
calibrate bool

When True (default), calibrate to reflectance / brightness temperature; when False, return the stitched raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance. The default 1.0 leaves reflectance up to ~3.4% off (d ranges ~0.983-1.017 AU over the year); pass the granule's d for absolute accuracy.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] keyed by

Any

channel (for channels) of the calibrated (or raw) channel(s) on the

Any

stitched geostationary grid, with NaN nodata and the geostationary CRS.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, when no chunk carries a requested channel, or the chunks are inconsistent (mixed CRS / cell size / column count, or not vertically contiguous — see _validate_chunks).

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When a channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/fci_l1c.py
def read_fci_l1c(
    paths: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
) -> Any:
    """Read one or several channels across a set of real FCI L1C FDHSI chunks.

    Decodes each chunk once for the whole requested channel set
    (`read_fci_l1c_chunks` opens the chunk's structure a single time), drops chunks
    without a channel's radiance (e.g. `CHK-TRAIL`), then for each channel orders
    the chunks north -> south by their geotransform Y origin, checks they are
    vertically contiguous (and share a grid), stitches the radiance, and calibrates
    it with the **per-granule** coefficients (reflectance for a solar channel,
    brightness temperature for a thermal one). Each result is a geolocated pyramids
    `Dataset` on the granule's geostationary grid (metre geotransform reconstructed
    from the angular grid and the CRS satellite height, with its x axis reconciled
    to the CRS so a warp is not mirrored east-west — issue #56).

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`); `read_fci_l1c(paths, "ir_105")` is unchanged.

    Args:
        paths: Iterable of FCI L1C FDHSI chunk file paths (any order; trailer /
            non-imagery chunks are skipped).
        channel: A single channel identifier (e.g. `"ir_105"`, `"vis_06"`) for a
            `Dataset` result; mutually exclusive with `channels`.
        channels: A sequence of channel identifiers for a `dict[str, Dataset]`
            result (each chunk opened once for the whole set); mutually exclusive
            with `channel`.
        calibrate: When `True` (default), calibrate to reflectance / brightness
            temperature; when `False`, return the stitched raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
            The default `1.0` leaves reflectance up to ~3.4% off (`d` ranges
            ~0.983-1.017 AU over the year); pass the granule's `d` for absolute
            accuracy.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` keyed by
        channel (for `channels`) of the calibrated (or raw) channel(s) on the
        stitched geostationary grid, with NaN nodata and the geostationary CRS.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given, when
            no chunk carries a requested channel, or the chunks are inconsistent
            (mixed CRS / cell size / column count, or not vertically contiguous —
            see `_validate_chunks`).
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When a channel is not in the registry.
    """
    requested, single = resolve_channels(channel, channels, "read_fci_l1c")

    per_channel: dict[str, list] = {name: [] for name in requested}
    for path in paths:
        for name, record in read_fci_l1c_chunks(path, requested).items():
            if record is not None:
                per_channel[name].append(record)

    results = {
        name: _assemble_channel(
            per_channel[name],
            name,
            calibrate=calibrate,
            sun_earth_distance=sun_earth_distance,
            cos_sza=cos_sza,
        )
        for name in requested
    }
    return results[requested[0]] if single else results

available_channels(chunks) #

List the VIS/IR channels present across FCI L1C FDHSI chunk file(s).

Opens each chunk's multidimensional dataset and reports the data/<channel> groups that carry an effective_radiance array, so a caller can discover the channel names instead of hard-coding them. The union across chunks is returned (a trailer chunk contributes none), sorted.

Parameters:

Name Type Description Default
chunks Any

A single chunk path, or an iterable of chunk paths. (For convenience this discovery helper also accepts a lone path, whereas read_fci_l1c / read_fci take an iterable of chunk paths.)

required

Returns:

Type Description
list[str]

The sorted channel identifiers available in the chunk(s).

Source code in src/pyramids_eo/sensors/readers/fci_l1c.py
def available_channels(chunks: Any) -> list[str]:
    """List the VIS/IR channels present across FCI L1C FDHSI chunk file(s).

    Opens each chunk's multidimensional dataset and reports the `data/<channel>`
    groups that carry an `effective_radiance` array, so a caller can discover the
    channel names instead of hard-coding them. The union across chunks is returned
    (a trailer chunk contributes none), sorted.

    Args:
        chunks: A single chunk path, or an iterable of chunk paths. (For
            convenience this discovery helper also accepts a lone path, whereas
            `read_fci_l1c` / `read_fci` take an iterable of chunk paths.)

    Returns:
        The sorted channel identifiers available in the chunk(s).
    """
    paths = [chunks] if isinstance(chunks, (str, bytes, os.PathLike)) else list(chunks)
    found: set[str] = set()
    for path in paths:
        found |= _channels_in_chunk(path)
    return sorted(found)

pyramids_eo.sensors.readers.fci #

MTG-FCI L1C (FDHSI) reader.

read_fci stitches a channel across the ~40 NetCDF chunks of one FCI repeat cycle, calibrates the raw radiance to reflectance / brightness temperature via the sensor registry, and returns a geolocated pyramids Dataset ready for to_crs / warped_view.

Warning

The zero-config default (_default_open_chunk) assumes each chunk exposes the requested channel's radiance as a NetCDF variable named like the channel. Real FCI L1C FDHSI stores radiance in nested groups (data/<channel>/measured/effective_radiance) with the calibration coefficients in group attributes — for those granules pass open_fci_l1c_chunk (which reads that nested layout) as open_chunk, plus the coefficients via coeffs. The stitch + calibrate + geolocate logic is unit-tested on synthetic chunks, and open_fci_l1c_chunk is unit-tested for its group-path resolution, but the exact FCI variable layout and the per-granule coefficient attributes still need validation against a real granule (see issue #40).

open_fci_l1c_chunk(path, channel, *, radiance_group=_FCI_RADIANCE_GROUP) #

Open one real FCI L1C FDHSI chunk from its nested group layout.

Unlike _default_open_chunk (which assumes a flat variable named like the channel), this reads the radiance from the nested group path a real FCI L1C FDHSI chunk uses — by default data/<channel>/measured/effective_radiance — through pyramids' group-qualified NetCDF.get_variable, which navigates the /-separated group path. Pass it to read_fci as open_chunk for real granules:

from pyramids_eo.sensors.readers import open_fci_l1c_chunk, read_fci

scene = read_fci(chunk_paths, "ir_105", open_chunk=open_fci_l1c_chunk)
Warning

The nested group path matches the documented FDHSI layout, but has not been validated byte-for-byte against a real EUMETSAT granule, and this opener does not (yet) extract the per-granule calibration coefficients from the chunk's group attributes — supply them via read_fci(..., coeffs=...) or rely on the registry fallback. See issue

40.#

Parameters:

Name Type Description Default
path Any

Path to a single FCI L1C FDHSI chunk NetCDF file.

required
channel str

Channel identifier (e.g. "ir_105"), substituted into radiance_group.

required
radiance_group str

Group-qualified variable-name template with a single {channel} placeholder. Defaults to data/{channel}/measured/effective_radiance. read_fci calls the opener positionally, so to thread a non-default template through read_fci wrap it with functools.partial(open_fci_l1c_chunk, radiance_group=...).

_FCI_RADIANCE_GROUP

Returns:

Type Description
Any

A pyramids NetCDF variable view of the channel's raw effective radiance

Any

(a Dataset-like object exposing read_array / geotransform / epsg /

Any

columns / rows, as read_fci consumes it).

Source code in src/pyramids_eo/sensors/readers/fci.py
def open_fci_l1c_chunk(
    path: Any,
    channel: str,
    *,
    radiance_group: str = _FCI_RADIANCE_GROUP,
) -> Any:
    """Open one real FCI L1C FDHSI chunk from its nested group layout.

    Unlike `_default_open_chunk` (which assumes a flat variable named like the
    channel), this reads the radiance from the nested group path a real FCI L1C
    FDHSI chunk uses — by default `data/<channel>/measured/effective_radiance` —
    through pyramids' group-qualified `NetCDF.get_variable`, which navigates the
    `/`-separated group path. Pass it to `read_fci` as `open_chunk` for real
    granules:

    ```python
    from pyramids_eo.sensors.readers import open_fci_l1c_chunk, read_fci

    scene = read_fci(chunk_paths, "ir_105", open_chunk=open_fci_l1c_chunk)
    ```

    Warning:
        The nested group path matches the documented FDHSI layout, but has not
        been validated byte-for-byte against a real EUMETSAT granule, and this
        opener does not (yet) extract the per-granule calibration coefficients
        from the chunk's group attributes — supply them via
        `read_fci(..., coeffs=...)` or rely on the registry fallback. See issue
        #40.

    Args:
        path: Path to a single FCI L1C FDHSI chunk NetCDF file.
        channel: Channel identifier (e.g. `"ir_105"`), substituted into
            `radiance_group`.
        radiance_group: Group-qualified variable-name template with a single
            `{channel}` placeholder. Defaults to
            `data/{channel}/measured/effective_radiance`. `read_fci` calls the
            opener positionally, so to thread a non-default template through
            `read_fci` wrap it with
            `functools.partial(open_fci_l1c_chunk, radiance_group=...)`.

    Returns:
        A pyramids `NetCDF` variable view of the channel's raw effective radiance
        (a `Dataset`-like object exposing `read_array` / `geotransform` / `epsg` /
        `columns` / `rows`, as `read_fci` consumes it).
    """
    from pyramids.netcdf import NetCDF

    try:
        variable = radiance_group.format(channel=channel)
    except (KeyError, IndexError, ValueError, AttributeError, TypeError) as exc:
        raise ReaderError(
            f"invalid radiance_group template {radiance_group!r}: it must be a "
            f"format string with a single '{{channel}}' field ({exc!r})"
        ) from exc
    # Group navigation via get_variable needs the file opened as multidimensional;
    # pass it explicitly rather than relying on read_file's default.
    return NetCDF.read_file(str(path), open_as_multi_dimensional=True).get_variable(
        variable
    )

read_fci(chunks, channel=None, *, channels=None, sensor='fci', calibrate=True, sun_earth_distance=1.0, cos_sza=None, coeffs=None, open_chunk=None) #

Read one or several FCI channels across a chunk set into Datasets.

For each requested channel, orders the chunks north -> south by their top-left latitude (so the caller may pass them in any order), stitches the radiance row-wise, calibrates it to reflectance (solar) or brightness temperature (thermal), and returns a geolocated pyramids Dataset carrying the northernmost chunk's CRS + geotransform. The chunks must share a CRS, cell size and column count and be vertically contiguous (validated per channel, since channels differ in resolution).

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]); read_fci(chunks, "ir_105") is unchanged.

Parameters:

Name Type Description Default
chunks Any

An ordered iterable of chunks, each either a pyramids Dataset already holding the channel radiance, or a value accepted by open_chunk (by default a NetCDF path).

required
channel str | None

A single channel identifier (e.g. "ir_105", "vis_06") for a Dataset result; mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channel identifiers for a dict[str, Dataset] result; mutually exclusive with channel. (Each channel is opened via open_chunk, whose contract is per-channel; the grid is validated and ordered per channel because channels differ in resolution.)

None
sensor str

Registry sensor name (default "fci").

'fci'
calibrate bool

When True (default), calibrate to a physical quantity; when False, return the stitched raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None
coeffs dict[str, Any] | None

Per-granule calibration coefficients preferred over the registry fallback (see calibrate_channel), or None to use the registry. They override a single channel's calibration, so they are only accepted with channel= — passing coeffs together with channels=[...] is an error (each channel would need its own).

None
open_chunk Any

Callable (chunk, channel) -> Dataset used for chunks that are not already Datasets. Defaults to a NetCDF reader (see the module warning about the FCI layout).

None

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] keyed by

Any

channel (for channels) of the calibrated (or raw) channel(s) on the

Any

stitched grid.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, or when chunks is empty.

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When the sensor / channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/fci.py
def read_fci(
    chunks: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    sensor: str = "fci",
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
    coeffs: dict[str, Any] | None = None,
    open_chunk: Any = None,
) -> Any:
    """Read one or several FCI channels across a chunk set into `Dataset`s.

    For each requested channel, orders the chunks north -> south by their top-left
    latitude (so the caller may pass them in any order), stitches the radiance
    row-wise, calibrates it to reflectance (solar) or brightness temperature
    (thermal), and returns a geolocated pyramids `Dataset` carrying the
    northernmost chunk's CRS + geotransform. The chunks must share a CRS, cell
    size and column count and be vertically contiguous (validated per channel,
    since channels differ in resolution).

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`); `read_fci(chunks, "ir_105")` is unchanged.

    Args:
        chunks: An ordered iterable of chunks, each either a pyramids `Dataset`
            already holding the channel radiance, or a value accepted by
            `open_chunk` (by default a NetCDF path).
        channel: A single channel identifier (e.g. `"ir_105"`, `"vis_06"`) for a
            `Dataset` result; mutually exclusive with `channels`.
        channels: A sequence of channel identifiers for a `dict[str, Dataset]`
            result; mutually exclusive with `channel`. (Each channel is opened via
            `open_chunk`, whose contract is per-channel; the grid is validated and
            ordered per channel because channels differ in resolution.)
        sensor: Registry sensor name (default `"fci"`).
        calibrate: When `True` (default), calibrate to a physical quantity; when
            `False`, return the stitched raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.
        coeffs: Per-granule calibration coefficients preferred over the registry
            fallback (see `calibrate_channel`), or `None` to use the registry. They
            override a **single** channel's calibration, so they are only accepted
            with `channel=` — passing `coeffs` together with `channels=[...]` is an
            error (each channel would need its own).
        open_chunk: Callable `(chunk, channel) -> Dataset` used for chunks that
            are not already Datasets. Defaults to a NetCDF reader (see the module
            warning about the FCI layout).

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` keyed by
        channel (for `channels`) of the calibrated (or raw) channel(s) on the
        stitched grid.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given, or
            when `chunks` is empty.
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When the sensor / channel is not in the registry.
    """
    requested, single = resolve_channels(channel, channels, "read_fci")
    chunk_list = list(chunks)
    if not chunk_list:
        raise ReaderError("read_fci: no chunks given")
    # A pre-opened Dataset holds exactly one channel's radiance, so it cannot serve
    # a multi-channel request — every channel would alias the same array. Reject it
    # rather than return a physically meaningless dict.
    if not single and any(hasattr(chunk, "read_array") for chunk in chunk_list):
        raise ReaderError(
            "read_fci: channels=[...] needs path-like chunks read per channel via "
            "open_chunk; a pre-opened Dataset already holds a single channel"
        )
    # `coeffs` overrides one channel's calibration; sharing it across a channel set
    # would mis-calibrate the others. Require the single-channel form for an override.
    if not single and coeffs is not None:
        raise ReaderError(
            "read_fci: `coeffs` overrides a single channel's calibration; pass it "
            "with `channel=`, not `channels=[...]` (each channel calibrates on its own)"
        )
    opener = open_chunk or _default_open_chunk

    from pyramids.base.crs import crs_spec
    from pyramids.dataset import Dataset, GeoReference

    results = {}
    for name in requested:
        datasets = [
            chunk if hasattr(chunk, "read_array") else opener(chunk, name)
            for chunk in chunk_list
        ]
        _validate_chunk_grid(datasets)
        # Order the chunks north -> south by their top-left latitude/y so the
        # stitch and geolocation are correct regardless of the order the chunks
        # were passed in (FCI files are commonly numbered south -> north).
        ordered = sorted(datasets, key=lambda ds: ds.geotransform[3], reverse=True)
        radiance = np.concatenate(
            [np.asarray(ds.read_array(), dtype=float) for ds in ordered], axis=0
        )
        data = (
            calibrate_channel(
                radiance, name, sensor, sun_earth_distance, cos_sza, coeffs=coeffs
            )
            if calibrate
            else radiance
        )
        north = ordered[0]
        # Calibration can produce NaN (terminator reflectance / non-positive
        # radiance), so declare NaN as nodata rather than the default -9999.
        results[name] = Dataset.from_array(
            data,
            geo_ref=GeoReference(
                geo=north.geotransform, epsg=crs_spec(north.epsg, north.crs)
            ),
            no_data_value=np.nan,
        )
    return results[requested[0]] if single else results

pyramids_eo.sensors.readers.seviri #

MSG-SEVIRI Level-1.5 native (.nat) reader.

read_seviri decodes one SEVIRI VIS/IR channel from a real MSG Level-1.5 native (.nat) granule and returns a calibrated, geolocated pyramids Dataset (reflectance for a solar channel, brightness temperature for a thermal one).

The .nat format is a packed binary: an ASCII Main/Secondary Product Header carrying the segment table, a fixed-layout binary 15Header (the Level-1.5 prologue, with the per-granule calibration and the reference grid), then the 15Data image records — one record per scan line, holding a 65-byte side-info header plus 10-bit packed counts for each selected channel in turn (the 11 VIS/IR channels first, then HRV). parse_seviri_native reads the segment table and the 15Header, then for the requested channel unpacks the counts, applies the granule's Cal_Slope / Cal_Offset to get radiance, masks the off-earth (zero-count) corners, and orients the scene north-up / west-left (the grid origin is South-East). read_seviri then calibrates that radiance via the sensor registry.

Validated against a real Meteosat-10 (MSG3) full-disk granule (see issue #40): IR_108 decodes to brightness temperature in the expected range on the 3 km geostationary grid. HRV (a different, higher-resolution geometry) is out of scope.

parse_seviri_native(path, channel, *, subsatellite_longitude=0.0) #

Decode one VIS/IR channel of an MSG Level-1.5 native (.nat) granule.

Reads the segment table and the fixed-layout 15Header (reference grid, grid step and the per-granule calibration), then unpacks the channel's 10-bit counts from every image line record, applies the granule Cal_Slope / Cal_Offset to get radiance, masks the zero-count (off-earth) corners to NaN, and orients the scene north-up / west-left. Only the image lines actually present are read, so a header-preserved subset (whose header still declares the full disk) decodes correctly rather than reading past end-of-file.

Parameters:

Name Type Description Default
path Any

Path to an MSG SEVIRI Level-1.5 native .nat file.

required
channel str

A VIS/IR channel identifier (e.g. "IR_108", "VIS006"); HRV is not supported.

required
subsatellite_longitude float

Sub-satellite longitude (degrees east) for the geostationary CRS. Defaults to 0.0, the nominal prime service (MSG15); pass the service longitude for IODC (41.5) or rapid-scan (9.5) granules, whose .nat header the reader does not parse for it.

0.0

Returns:

Type Description
Any

A pyramids Dataset holding the channel radiance on the geostationary

Any

grid, with the geostationary CRS, a metre geotransform, and NaN nodata.

Raises:

Type Description
ReaderError

When the channel is unknown / HRV, the file is not a recognised MSG Level-1.5 native granule (no segment table, or the 15Header layout / calibration fails its sanity checks), the file carries no complete line record, or the decoded line records are not contiguous (an unexpected channel selection or layout).

Source code in src/pyramids_eo/sensors/readers/seviri.py
def parse_seviri_native(
    path: Any, channel: str, *, subsatellite_longitude: float = 0.0
) -> Any:
    """Decode one VIS/IR channel of an MSG Level-1.5 native (`.nat`) granule.

    Reads the segment table and the fixed-layout ``15Header`` (reference grid,
    grid step and the per-granule calibration), then unpacks the channel's 10-bit
    counts from every image line record, applies the granule ``Cal_Slope`` /
    ``Cal_Offset`` to get radiance, masks the zero-count (off-earth) corners to
    NaN, and orients the scene north-up / west-left. Only the image lines
    actually present are read, so a header-preserved subset (whose header still
    declares the full disk) decodes correctly rather than reading past end-of-file.

    Args:
        path: Path to an MSG SEVIRI Level-1.5 native `.nat` file.
        channel: A VIS/IR channel identifier (e.g. `"IR_108"`, `"VIS006"`); HRV
            is not supported.
        subsatellite_longitude: Sub-satellite longitude (degrees east) for the
            geostationary CRS. Defaults to `0.0`, the nominal prime service
            (`MSG15`); pass the service longitude for IODC (41.5) or rapid-scan
            (9.5) granules, whose `.nat` header the reader does not parse for it.

    Returns:
        A pyramids `Dataset` holding the channel radiance on the geostationary
        grid, with the geostationary CRS, a metre geotransform, and NaN nodata.

    Raises:
        ReaderError: When the channel is unknown / HRV, the file is not a
            recognised MSG Level-1.5 native granule (no segment table, or the
            ``15Header`` layout / calibration fails its sanity checks), the file
            carries no complete line record, or the decoded line records are not
            contiguous (an unexpected channel selection or layout).
    """
    if channel == "HRV":
        raise ReaderError("read_seviri: HRV is not supported (different geometry)")
    try:
        position = _VISIR_CHANNELS.index(channel)
    except ValueError as exc:
        raise ReaderError(
            f"read_seviri: unknown SEVIRI VIS/IR channel {channel!r}"
        ) from exc

    try:
        handle = open(path, "rb")
    except OSError as exc:
        raise ReaderError(f"read_seviri: cannot open {path} ({exc})") from exc
    with handle:
        segments = _segments(handle.read(_PRODUCT_HEADER_SCAN_BYTES))
        try:
            header_length, header_offset = segments["15Header"]
            data_length, data_offset = segments["15Data"]
        except KeyError as exc:
            raise ReaderError(
                "read_seviri: no 15Header/15Data segment table "
                f"(not an MSG Level-1.5 native file?) — {path}"
            ) from exc
        handle.seek(header_offset)
        header = handle.read(header_length)
        if len(header) < _CALIBRATION_OFFSET + 12 * 16:
            raise ReaderError(
                "read_seviri: 15Header is truncated "
                "(not a supported MSG Level-1.5 native file)"
            )
        file_size = os.fstat(handle.fileno()).st_size

    lines_declared, columns = struct.unpack_from(">ii", header, _REF_GRID_OFFSET)
    line_step_km, column_step_km = struct.unpack_from(">ff", header, _GRID_STEP_OFFSET)
    # The reference grid and grid step sit immediately before the calibration
    # block: sane values here confirm the fixed 15Header layout was found. The
    # line and column steps must match (the VIS/IR grid is isotropic 3 km).
    if not (
        lines_declared == columns
        and 1000 <= columns <= 12000
        and 2.9 < column_step_km < 3.1
        and np.isclose(line_step_km, column_step_km)
        and columns % 4 == 0
    ):
        raise ReaderError(
            "read_seviri: unexpected 15Header layout (reference grid / grid step "
            "sanity check failed) — not a supported MSG Level-1.5 native file"
        )
    pixel_m = column_step_km * 1000.0

    slope, offset = struct.unpack_from(
        ">dd", header, _CALIBRATION_OFFSET + position * 16
    )
    if slope <= 0:
        raise ReaderError(
            "read_seviri: non-physical calibration slope (unexpected header layout)"
        )

    if data_length % lines_declared:
        raise ReaderError(
            "read_seviri: 15Data length is not a whole number of line records"
        )
    stride = data_length // lines_declared
    packed_bytes = columns * 10 // 8
    # The 11 VIS/IR channels precede HRV in every record; assume the standard
    # all-channel product so channel `position` maps straight to block `position`.
    # The contiguity check below rejects a file where that assumption does not hold.
    block_start = position * (_LINE_SIDE_INFO_BYTES + packed_bytes)
    data_start = block_start + _LINE_SIDE_INFO_BYTES
    if data_start + packed_bytes > stride:
        raise ReaderError("read_seviri: channel block exceeds the line-record stride")

    # The declared 15Data holds exactly `lines_declared` records; a full product
    # has a 15Trailer segment after it, so cap the count at the declared line
    # count. Without this cap the trailer bytes get read as extra "line records",
    # break the +1 contiguity of `line_numbers`, and reject a valid full disk.
    # The file-size term still handles a header-preserved subset (fewer records).
    available = min((file_size - data_offset) // stride, lines_declared)
    if available < 1:
        raise ReaderError("read_seviri: file carries no complete image line record")

    counts = np.empty((available, columns), dtype=np.uint16)
    line_numbers = np.empty(available, dtype=np.int64)
    with (
        open(path, "rb") as handle,
        mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mapped,
    ):
        for index in range(available):
            record = data_offset + index * stride
            line_numbers[index] = struct.unpack_from(
                ">i", mapped, record + block_start + _LINE_NUMBER_OFFSET
            )[0]
            start = record + data_start
            counts[index] = _unpack_10bit(mapped[start : start + packed_bytes], columns)

    if not np.all(np.diff(line_numbers) == 1):
        raise ReaderError(
            "read_seviri: image line records are not contiguous "
            "(unexpected channel selection or record layout)"
        )

    radiance = counts.astype(float) * slope + offset
    radiance[counts == 0] = np.nan  # zero counts mark the off-earth space corners
    # The grid origin is South-East: line numbers increase northward and the
    # stored columns run east -> west (the first column is East). Reverse both
    # axes for a north-up, west-left raster. Copy the flipped view to a
    # C-contiguous array so no downstream consumer trips on the negative strides.
    radiance = np.ascontiguousarray(radiance[::-1, ::-1])

    # CGMS/EUMETSAT navigation places the sub-satellite point at the CENTRE of the
    # reference pixel N/2 (0-based, both axes; e.g. pixel 1856 of the 3712 grid) —
    # the COFF = LOFF convention, which reproduces the published MSG full-disk area
    # extent (west edge -(N/2 + 0.5) * px). All columns are present (full width) so
    # the SSP column is N/2; only a subset of lines may be present, so the SSP row
    # is N/2 measured from the northmost present line (row 0 after the north-up
    # flip). Register the metre geotransform so that reference pixel's centre is
    # (x=0, y=0).
    reference = columns / 2.0  # == lines_declared / 2.0 for the square VIS/IR grid
    ssp_row = int(line_numbers[-1]) - reference
    x_west_edge = -(reference + 0.5) * pixel_m
    y_north_edge = (ssp_row + 0.5) * pixel_m
    geo = (x_west_edge, pixel_m, 0.0, y_north_edge, 0.0, -pixel_m)

    from pyramids.dataset import Dataset, GeoReference

    dataset = Dataset.from_array(
        radiance, geo_ref=GeoReference(geo=geo, epsg=None), no_data_value=np.nan
    )
    dataset.crs = _geostationary_wkt(subsatellite_longitude)
    return dataset

read_seviri(source, channel, *, sensor='seviri', calibrate=True, sun_earth_distance=1.0, cos_sza=None, coeffs=None, parse=None, subsatellite_longitude=0.0) #

Read one SEVIRI channel into a calibrated, geolocated Dataset.

Decodes the channel radiance (from a .nat granule via parse, or straight from a Dataset source), then calibrates it to reflectance (solar) or brightness temperature (thermal) via the registry and returns a pyramids Dataset carrying the source's CRS + geotransform.

Parameters:

Name Type Description Default
source Any

A path to an MSG Level-1.5 native .nat file (decoded by parse), or a pyramids Dataset already holding the channel radiance.

required
channel str

Channel identifier (e.g. "IR_108", "VIS006").

required
sensor str

Registry sensor name (default "seviri").

'seviri'
calibrate bool

When True (default), calibrate to a physical quantity; when False, return the raw radiance.

True
sun_earth_distance float

Sun-earth distance (AU) for solar-channel reflectance. The default 1.0 leaves reflectance up to ~3.4% off (d ranges ~0.983-1.017 AU over the year); pass the granule's d for absolute accuracy.

1.0
cos_sza Any

Cosine of the solar zenith angle for the reflectance sun-angle correction, or None.

None
coeffs dict[str, Any] | None

Per-granule calibration coefficients preferred over the registry fallback (see calibrate_channel), or None to use the registry.

None
parse Any

Callable (source, channel) -> Dataset used when source is not already a Dataset. Defaults to the native .nat parser (parse_seviri_native).

None
subsatellite_longitude float

Sub-satellite longitude (degrees east) passed to the default native parser for the geostationary CRS (default 0.0, the prime service); ignored when a custom parse is supplied.

0.0

Returns:

Type Description
Any

A pyramids Dataset of the calibrated (or raw) channel.

Raises:

Type Description
ReaderError

When source is None, or the native parse fails.

CalibrationError

When a channel lacks the constants its kind needs.

UnknownSensorError

When the sensor / channel is not in the registry.

Source code in src/pyramids_eo/sensors/readers/seviri.py
def read_seviri(
    source: Any,
    channel: str,
    *,
    sensor: str = "seviri",
    calibrate: bool = True,
    sun_earth_distance: float = 1.0,
    cos_sza: Any = None,
    coeffs: dict[str, Any] | None = None,
    parse: Any = None,
    subsatellite_longitude: float = 0.0,
) -> Any:
    """Read one SEVIRI channel into a calibrated, geolocated `Dataset`.

    Decodes the channel radiance (from a `.nat` granule via `parse`, or straight
    from a `Dataset` source), then calibrates it to reflectance (solar) or
    brightness temperature (thermal) via the registry and returns a pyramids
    `Dataset` carrying the source's CRS + geotransform.

    Args:
        source: A path to an MSG Level-1.5 native `.nat` file (decoded by
            `parse`), or a pyramids `Dataset` already holding the channel radiance.
        channel: Channel identifier (e.g. `"IR_108"`, `"VIS006"`).
        sensor: Registry sensor name (default `"seviri"`).
        calibrate: When `True` (default), calibrate to a physical quantity; when
            `False`, return the raw radiance.
        sun_earth_distance: Sun-earth distance (AU) for solar-channel reflectance.
            The default `1.0` leaves reflectance up to ~3.4% off (`d` ranges
            ~0.983-1.017 AU over the year); pass the granule's `d` for absolute
            accuracy.
        cos_sza: Cosine of the solar zenith angle for the reflectance sun-angle
            correction, or `None`.
        coeffs: Per-granule calibration coefficients preferred over the registry
            fallback (see `calibrate_channel`), or `None` to use the registry.
        parse: Callable `(source, channel) -> Dataset` used when `source` is not
            already a `Dataset`. Defaults to the native `.nat` parser
            (`parse_seviri_native`).
        subsatellite_longitude: Sub-satellite longitude (degrees east) passed to
            the default native parser for the geostationary CRS (default `0.0`,
            the prime service); ignored when a custom `parse` is supplied.

    Returns:
        A pyramids `Dataset` of the calibrated (or raw) channel.

    Raises:
        ReaderError: When `source` is `None`, or the native parse fails.
        CalibrationError: When a channel lacks the constants its kind needs.
        UnknownSensorError: When the sensor / channel is not in the registry.
    """
    if source is None:
        raise ReaderError("read_seviri: source is required")

    if hasattr(source, "read_array"):
        dataset = source
    elif parse is not None:
        dataset = parse(source, channel)
    else:
        dataset = parse_seviri_native(
            source, channel, subsatellite_longitude=subsatellite_longitude
        )
    radiance = np.asarray(dataset.read_array(), dtype=float)
    data = (
        calibrate_channel(
            radiance, channel, sensor, sun_earth_distance, cos_sza, coeffs=coeffs
        )
        if calibrate
        else radiance
    )

    from pyramids.dataset import Dataset, GeoReference

    # Calibration can produce NaN (terminator reflectance / non-positive
    # radiance), so declare NaN as nodata rather than the default -9999.
    epsg = dataset.epsg if dataset.epsg else None
    result = Dataset.from_array(
        data,
        geo_ref=GeoReference(geo=dataset.geotransform, epsg=epsg),
        no_data_value=np.nan,
    )
    if epsg is None:
        # A non-EPSG CRS (e.g. the geostationary grid) must be carried explicitly.
        result.crs = dataset.crs
    return result

pyramids_eo.sensors.readers.olci #

Sentinel-3 OLCI Level-1B (EFR / ERR) reader -- native, satpy-free.

read_olci(granule, channel="Oa08") decodes one OLCI radiance band (or several via channels=[...]) out of a .SEN3 granule into a pyramids Dataset, through pyramids' bundled GDAL NetCDF driver. No netCDF4, and nothing from the satpy stack.

OLCI is a pushbroom swath instrument, so the result carries its geolocation as a GDAL GEOLOCATION domain pointing at the granule's per-pixel geo_coordinates.nc longitude / latitude arrays -- not an affine geotransform, which cannot describe a swath. The reader resamples nothing; a caller who wants a map grid warps the result themselves (gdal.Warp(..., geoloc=True)).

Per issue #136 this decodes to arrays plus standard CF metadata only: radiometric calibration choices (radiance -> reflectance) stay with the callers and the composites tier, and the granule's own instrument_data.nc carries the solar_flux needed for that conversion.

available_olci_channels(source) #

List the OLCI radiance bands a granule actually carries.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required

Returns:

Type Description
list[str]

The canonical channel names present, sorted (["Oa01", "Oa02", ...]).

Raises:

Type Description
ReaderError

When source is not a granule directory or a file in one.

Source code in src/pyramids_eo/sensors/readers/olci.py
def available_olci_channels(source: Any) -> list[str]:
    """List the OLCI radiance bands a granule actually carries.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.

    Returns:
        The canonical channel names present, sorted (`["Oa01", "Oa02", ...]`).

    Raises:
        ReaderError: When `source` is not a granule directory or a file in one.
    """
    granule = resolve_granule(source, "available_olci_channels")
    found = []
    for number in range(1, _BAND_COUNT + 1):
        channel = f"Oa{number:02d}"
        if (granule / _band_filename(channel)).is_file():
            found.append(channel)
    return found

product_type(granule) #

Detect whether a granule is the full- or reduced-resolution OLCI product.

EFR and ERR granules hold the same OaNN_radiance.nc filenames and the same variable names, so the product type -- and therefore the ground resolution, 300 m against ~1200 m -- is only knowable from the granule's own naming or its manifest. Both are checked -- the name first, then xfdumanifest.xml -- and None means neither identified the product, in which case the reader reports no resolution rather than asserting a wrong one.

An ambiguous source is treated exactly like a silent one: a text carrying both tokens yields None rather than the first match, because an ERR granule routinely references the EFR product it was derived from, so preferring either one would be a guess (see _product_tokens).

Parameters:

Name Type Description Default
granule Path

The .SEN3 granule directory.

required

Returns:

Type Description
str | None

"EFR", "ERR", or None -- when the granule does not identify itself,

str | None

and equally when it names both products.

Examples:

  • A standard product name identifies itself, so no file access is needed:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("S3A_OL_1_EFR____20230101T101530.SEN3"))
    'EFR'
    >>> product_type(Path("S3B_OL_1_ERR____20230101T101530.SEN3"))
    'ERR'
    
  • A granule that names neither, and carries no manifest saying so, yields None -- which is what makes the reader omit resolution_m rather than guess it:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("mystery.SEN3")) is None
    True
    
  • A name claiming both products is ambiguous, so it too yields None rather than the first token found:
    >>> from pathlib import Path
    >>> from pyramids_eo.sensors.readers.olci import product_type
    >>> product_type(Path("S3A_OL_1_ERR____from_OL_1_EFR_source.SEN3")) is None
    True
    
Source code in src/pyramids_eo/sensors/readers/olci.py
def product_type(granule: Path) -> str | None:
    """Detect whether a granule is the full- or reduced-resolution OLCI product.

    EFR and ERR granules hold the **same** `OaNN_radiance.nc` filenames and the
    same variable names, so the product type -- and therefore the ground
    resolution, 300 m against ~1200 m -- is only knowable from the granule's own
    naming or its manifest. Both are checked -- the name first, then
    `xfdumanifest.xml` -- and `None` means neither identified the product, in
    which case the reader reports no resolution rather than asserting a wrong one.

    An **ambiguous** source is treated exactly like a silent one: a text carrying
    both tokens yields `None` rather than the first match, because an ERR granule
    routinely references the EFR product it was derived from, so preferring either
    one would be a guess (see `_product_tokens`).

    Args:
        granule: The `.SEN3` granule directory.

    Returns:
        `"EFR"`, `"ERR"`, or `None` -- when the granule does not identify itself,
        and equally when it names both products.

    Examples:
        - A standard product name identifies itself, so no file access is needed:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("S3A_OL_1_EFR____20230101T101530.SEN3"))
            'EFR'
            >>> product_type(Path("S3B_OL_1_ERR____20230101T101530.SEN3"))
            'ERR'

            ```
        - A granule that names neither, and carries no manifest saying so, yields
          `None` -- which is what makes the reader omit `resolution_m` rather than
          guess it:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("mystery.SEN3")) is None
            True

            ```
        - A name claiming both products is ambiguous, so it too yields `None`
          rather than the first token found:
            ```python
            >>> from pathlib import Path
            >>> from pyramids_eo.sensors.readers.olci import product_type
            >>> product_type(Path("S3A_OL_1_ERR____from_OL_1_EFR_source.SEN3")) is None
            True

            ```
    """
    found = _product_tokens(granule.name.upper(), "_OL_1_")
    if found is not None:
        return found
    manifest = granule / "xfdumanifest.xml"
    if manifest.is_file():
        try:
            text = manifest.read_text(encoding="utf-8", errors="replace").upper()
        except OSError:
            return None
        return _product_tokens(text, "OL_1_")
    return None

read_olci_band(source, channel, *, geolocation=True) #

Decode a single OLCI radiance band from a .SEN3 granule.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required
channel Any

The band to read ("Oa08", "oa8", "Oa08_radiance").

required
geolocation bool

When True (default), attach the granule's per-pixel GEOLOCATION domain. False returns the array on its placeholder pixel grid only -- useful when the geolocation file is absent or the caller only wants the counts.

True

Returns:

Type Description
Any

A pyramids Dataset of the unpacked radiance, NaN where the granule

Any

flags a fill / out-of-range pixel, with CF metadata and (by default) the

Any

swath GEOLOCATION domain.

Raises:

Type Description
ReaderError

When the channel name is not an OLCI band, the granule has no such band file, or the variable cannot be decoded. With geolocation=True it also raises when geo_coordinates.nc or its longitude / latitude variables are missing, when that grid's shape does not match the band (an oversized annotation grid would otherwise place every pixel wrongly, silently), or when its scale_factor / add_offset is non-finite or the scale is zero.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/olci.py
def read_olci_band(source: Any, channel: Any, *, geolocation: bool = True) -> Any:
    """Decode a single OLCI radiance band from a `.SEN3` granule.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.
        channel: The band to read (`"Oa08"`, `"oa8"`, `"Oa08_radiance"`).
        geolocation: When `True` (default), attach the granule's per-pixel
            `GEOLOCATION` domain. `False` returns the array on its placeholder
            pixel grid only -- useful when the geolocation file is absent or the
            caller only wants the counts.

    Returns:
        A pyramids `Dataset` of the unpacked radiance, NaN where the granule
        flags a fill / out-of-range pixel, with CF metadata and (by default) the
        swath `GEOLOCATION` domain.

    Raises:
        ReaderError: When the channel name is not an OLCI band, the granule has
            no such band file, or the variable cannot be decoded. With
            `geolocation=True` it also raises when `geo_coordinates.nc` or its
            longitude / latitude variables are missing, when that grid's shape
            does not match the band (an oversized annotation grid would otherwise
            place every pixel wrongly, silently), or when its `scale_factor` /
            `add_offset` is non-finite or the scale is zero.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` and the result's nodata is incomplete rather
        than the read failing (see `invalid_mask`).
    """
    reader = "read_olci"
    name = _canonical_channel(channel, reader)
    granule = resolve_granule(source, reader)
    # Decode first: the geolocation grid is validated against the band's shape, so
    # the shape has to be known before the domain can be built.
    data, variable_meta = _read_band(granule, name, reader)
    domain = _resolve_domain(granule, reader, data.shape) if geolocation else {}
    return _wrap_band(granule, name, data, variable_meta, domain, product_type(granule))

read_olci(source, channel=None, *, channels=None, geolocation=True) #

Read one or several OLCI L1B radiance bands from a .SEN3 granule.

Decodes each requested band's packed OaNN_radiance variable (raw * scale_factor + add_offset, with the _FillValue and anything outside the variable's validity limits masked to NaN) and returns it as a swath Dataset carrying the granule's per-pixel geolocation as a GDAL GEOLOCATION domain. The limits come from the valid_min / valid_max scalars the OLCI L1 specification carries -- not from a combined valid_range, which appears nowhere in it -- and are compared against the raw, still-packed values.

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset] keyed by canonical channel name).

This reader decodes only -- it does not convert radiance to reflectance (issue #136 scopes radiometric calibration choices out). The granule's instrument_data.nc carries the per-detector solar_flux a caller needs for that conversion.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or any file inside it.

required
channel str | None

A single band ("Oa08"); mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of bands for a dict result; mutually exclusive with channel.

None
geolocation bool

When True (default), attach each result's per-pixel GEOLOCATION domain from geo_coordinates.nc.

True

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] (for

Any

channels), each on the granule's native swath grid with NaN nodata.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, channels is empty or has duplicates, a band name is not an OLCI band, or the granule lacks a requested band. A channel set whose bands come back on different shapes also raises: the one geolocation domain is shared across the set, which is only sound because the bands of a granule share a grid, so a granule that breaks that is reported rather than geolocated against the wrong grid. With geolocation=True, also when geo_coordinates.nc or its variables are missing, its grid's shape differs from the bands', or it carries an unusable scale_factor / add_offset.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning per affected band and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/olci.py
def read_olci(
    source: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    geolocation: bool = True,
) -> Any:
    """Read one or several OLCI L1B radiance bands from a `.SEN3` granule.

    Decodes each requested band's packed `OaNN_radiance` variable (`raw *
    scale_factor + add_offset`, with the `_FillValue` and anything outside the
    variable's validity limits masked to NaN) and returns it as a swath `Dataset`
    carrying the granule's per-pixel geolocation as a GDAL `GEOLOCATION` domain.
    The limits come from the `valid_min` / `valid_max` scalars the OLCI L1
    specification carries -- not from a combined `valid_range`, which appears
    nowhere in it -- and are compared against the raw, still-packed values.

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]` keyed by canonical channel name).

    This reader **decodes only** -- it does not convert radiance to reflectance
    (issue #136 scopes radiometric calibration choices out). The granule's
    `instrument_data.nc` carries the per-detector `solar_flux` a caller needs for
    that conversion.

    Args:
        source: The `.SEN3` granule directory, or any file inside it.
        channel: A single band (`"Oa08"`); mutually exclusive with `channels`.
        channels: A sequence of bands for a `dict` result; mutually exclusive
            with `channel`.
        geolocation: When `True` (default), attach each result's per-pixel
            `GEOLOCATION` domain from `geo_coordinates.nc`.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` (for
        `channels`), each on the granule's native swath grid with NaN nodata.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given,
            `channels` is empty or has duplicates, a band name is not an OLCI
            band, or the granule lacks a requested band. A channel set whose bands
            come back on **different** shapes also raises: the one geolocation
            domain is shared across the set, which is only sound because the bands
            of a granule share a grid, so a granule that breaks that is reported
            rather than geolocated against the wrong grid. With
            `geolocation=True`, also when `geo_coordinates.nc` or its variables are
            missing, its grid's shape differs from the bands', or it carries an
            unusable `scale_factor` / `add_offset`.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` per affected band and the result's nodata is
        incomplete rather than the read failing (see `invalid_mask`).
    """
    requested, single = resolve_channels(channel, channels, "read_olci")
    # Canonicalise before the duplicate check: `resolve_channels` compares the raw
    # strings, so aliases of one band ("Oa08" and "oa8") slip through it and would
    # otherwise collapse into a single dict entry, silently dropping a requested band.
    canonical = [_canonical_channel(name, "read_olci") for name in requested]
    if len(set(canonical)) != len(canonical):
        duplicates = sorted({c for c in canonical if canonical.count(c) > 1})
        raise ReaderError(
            f"read_olci: `channels` names the same band more than once (after "
            f"normalising spellings): {duplicates}"
        )
    # Resolve the granule and its geolocation domain ONCE for the whole set,
    # matching read_fci_l1c's documented read-each-chunk-once pattern rather than
    # re-running them per channel.
    reader = "read_olci"
    granule = resolve_granule(source, reader)
    # Detect the product type once for the whole set rather than per band: it may
    # read xfdumanifest.xml, which a 21-band read would otherwise re-parse 21 times.
    product = product_type(granule)
    decoded = {name: _read_band(granule, name, reader) for name in canonical}
    shapes = {name: values.shape for name, (values, _) in decoded.items()}
    if len(set(shapes.values())) > 1:
        raise ReaderError(
            f"read_olci: the requested bands are not on one grid: {shapes}; OLCI "
            f"bands of a granule share a grid, so this granule looks inconsistent"
        )
    first = next(iter(decoded.values()))[0]
    domain = _resolve_domain(granule, reader, first.shape) if geolocation else {}
    results = {
        name: _wrap_band(granule, name, values, variable_meta, domain, product)
        for name, (values, variable_meta) in decoded.items()
    }
    return results[canonical[0]] if single else results

pyramids_eo.sensors.readers.slstr #

Sentinel-3 SLSTR Level-1 RBT reader -- native, satpy-free.

read_slstr(granule, channel="S5") decodes one SLSTR channel (or several via channels=[...]) out of a .SEN3 granule into a pyramids Dataset, through pyramids' bundled GDAL NetCDF driver. No netCDF4, and nothing from the satpy stack.

SLSTR is dual-view and multi-grid, which drives this reader's two extra arguments:

  • view -- the instrument images each scene twice, "nadir" (straight down) and "oblique" (slanted, ~55 deg forward). Each view is a separate grid.
  • grid -- channels live on different resolutions: the solar channels S1-S6 on the 500 m a grid (with S4-S6 duplicated onto the alternative 500 m b), the thermal S7-S9 on the 1 km i grid, and of the fire channels F1 on the 1 km f grid but F2 on i -- they are asymmetric, and there is no F2_BT_f*.nc. read_slstr tries each channel's documented grids in order (F1 falls back to i for products predating the f baseline), and grid= restricts the read to one grid. available_slstr_channels reports what a particular granule actually carries.

Because the grids differ in shape, a multi-channel read returns a dict rather than a stack -- channels=["S5", "S8"] yields arrays of different sizes.

Like OLCI, SLSTR is a swath instrument, so a result carries its geolocation as a GDAL GEOLOCATION domain over the matching geodetic_* annotation file rather than an affine geotransform, and this reader resamples nothing.

Per issue #136 this decodes to arrays plus standard CF metadata only. Note the RBT product is already geophysical: S1-S6 are radiances and S7-S9 / F1-F2 are brightness temperatures in kelvin as shipped, so no Planck conversion is applied (or needed) here.

available_slstr_channels(source, *, view='nadir') #

Report which channels a granule carries in one view, and on which grids.

This is how a caller discovers a product's real layout rather than assuming it -- including that F2 lives on the 1 km i grid while F1 is on f, and which of S4-S6 are duplicated onto the alternative 500 m b grid.

A grid is listed only when the granule holds both the measurement file and the geodetic_<grid><view>.nc the measurement needs, so what this reports is what read_slstr can actually return -- a measurement whose annotation file is missing would raise there, and listing it would promise a read that fails. A granule stripped of its geodetic files therefore reports {} even though the measurement files are all present.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required
view str

"nadir" (default) or "oblique".

'nadir'

Returns:

Type Description
dict[str, list[str]]

A {channel: [grid letters]} mapping listing only the channels the granule

dict[str, list[str]]

holds a measurement and a matching geodetic file for, in the product's

dict[str, list[str]]

own channel order -- S1..S9 then F1, F2 -- which is not the

dict[str, list[str]]

alphabetical order the error messages use. Each channel's grid letters are

dict[str, list[str]]

likewise in the order read_slstr would try them.

Raises:

Type Description
ReaderError

When source is not a granule, or view is not an SLSTR view.

Source code in src/pyramids_eo/sensors/readers/slstr.py
def available_slstr_channels(
    source: Any, *, view: str = "nadir"
) -> dict[str, list[str]]:
    """Report which channels a granule carries in one view, and on which grids.

    This is how a caller discovers a product's real layout rather than assuming
    it -- including that `F2` lives on the 1 km `i` grid while `F1` is on `f`, and
    which of `S4`-`S6` are duplicated onto the alternative 500 m `b` grid.

    A grid is listed only when the granule holds **both** the measurement file and
    the `geodetic_<grid><view>.nc` the measurement needs, so what this reports is
    what `read_slstr` can actually return -- a measurement whose annotation file is
    missing would raise there, and listing it would promise a read that fails. A
    granule stripped of its geodetic files therefore reports `{}` even though the
    measurement files are all present.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.
        view: `"nadir"` (default) or `"oblique"`.

    Returns:
        A `{channel: [grid letters]}` mapping listing only the channels the granule
        holds a measurement **and** a matching geodetic file for, in the product's
        own channel order -- `S1`..`S9` then `F1`, `F2` -- which is not the
        alphabetical order the error messages use. Each channel's grid letters are
        likewise in the order `read_slstr` would try them.

    Raises:
        ReaderError: When `source` is not a granule, or `view` is not an SLSTR
            view.
    """
    reader = "available_slstr_channels"
    suffix = _resolve_view(view, reader)
    granule = resolve_granule(source, reader)
    found: dict[str, list[str]] = {}
    for channel, (grids, quantity) in _CHANNEL_GRIDS.items():
        present = [
            letter
            for letter in grids
            if (granule / f"{channel}_{quantity}_{letter}{suffix}.nc").is_file()
            and (granule / f"geodetic_{letter}{suffix}.nc").is_file()
        ]
        if present:
            found[channel] = present
    return found

read_slstr_band(source, channel, *, view=None, grid=None, geolocation=True) #

Decode a single SLSTR channel from a .SEN3 granule.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or a file inside it.

required
channel Any

The channel to read ("S5", "s5", "F1"), or the product's own variable spelling ("S5_radiance_bn"), whose grid and view then select the file -- passing a conflicting grid= / view= is an error rather than one of the two being silently ignored.

required
view str | None

"nadir" or "oblique". None (default) takes the view from a spelled channel, falling back to nadir.

None
grid str | None

An explicit grid letter ("a", "b", "i", "f") restricting the read to that one grid. None (default) tries the channel's documented grids in order. The restriction is honoured even when only one candidate file exists, so a read never silently returns a different resolution than the one asked for.

None
geolocation bool

When True (default), attach the GEOLOCATION domain from the geodetic_* file matching the grid read.

True

Returns:

Type Description
Any

A pyramids Dataset of the channel -- radiance for S1-S6, brightness

Any

temperature in kelvin for S7-S9 / F1-F2 -- NaN where the granule

Any

flags a fill / out-of-range pixel, with CF metadata and (by default) the

Any

swath GEOLOCATION domain.

Raises:

Type Description
ReaderError

When the channel, view or grid is not an SLSTR one, when a spelled channel names a quantity that channel does not ship ("S9_radiance_an"), when a spelled channel's grid / view contradicts an explicit grid= / view=, or when the granule has no measurement for that channel, view and grid. With geolocation=True it also raises when the matching geodetic file or its longitude / latitude variables are missing, when that annotation grid's shape does not match the band (an oversized one would otherwise place every pixel wrongly, silently), or when its scale_factor / add_offset is non-finite or the scale is zero.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/slstr.py
def read_slstr_band(
    source: Any,
    channel: Any,
    *,
    view: str | None = None,
    grid: str | None = None,
    geolocation: bool = True,
) -> Any:
    """Decode a single SLSTR channel from a `.SEN3` granule.

    Args:
        source: The `.SEN3` granule directory, or a file inside it.
        channel: The channel to read (`"S5"`, `"s5"`, `"F1"`), or the product's
            own variable spelling (`"S5_radiance_bn"`), whose grid and view then
            select the file -- passing a conflicting `grid=` / `view=` is an error
            rather than one of the two being silently ignored.
        view: `"nadir"` or `"oblique"`. `None` (default) takes the view from a
            spelled channel, falling back to nadir.
        grid: An explicit grid letter (`"a"`, `"b"`, `"i"`, `"f"`) restricting the
            read to that one grid. `None` (default) tries the channel's documented
            grids in order. The restriction is honoured even when only one
            candidate file exists, so a read never silently returns a different
            resolution than the one asked for.
        geolocation: When `True` (default), attach the `GEOLOCATION` domain from
            the `geodetic_*` file matching the grid read.

    Returns:
        A pyramids `Dataset` of the channel -- radiance for `S1`-`S6`, brightness
        temperature in kelvin for `S7`-`S9` / `F1`-`F2` -- NaN where the granule
        flags a fill / out-of-range pixel, with CF metadata and (by default) the
        swath `GEOLOCATION` domain.

    Raises:
        ReaderError: When the channel, view or `grid` is not an SLSTR one, when a
            spelled channel names a quantity that channel does not ship
            (`"S9_radiance_an"`), when a spelled channel's grid / view contradicts
            an explicit `grid=` / `view=`, or when the granule has no measurement
            for that channel, view and grid. With `geolocation=True` it also raises
            when the matching geodetic file or its longitude / latitude variables
            are missing, when that annotation grid's shape does not match the band
            (an oversized one would otherwise place every pixel wrongly, silently),
            or when its `scale_factor` / `add_offset` is non-finite or the scale is
            zero.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` and the result's nodata is incomplete rather
        than the read failing (see `invalid_mask`).
    """
    reader = "read_slstr"
    name, letter, suffix = _resolve_channel_target(channel, view, grid, reader)
    granule = resolve_granule(source, reader)
    band_path, found_grid = _discover_band_file(granule, name, suffix, reader, letter)

    data, variable_meta = read_packed_variable(band_path, band_path.stem, reader=reader)
    domain = (
        _geodetic_domain(granule, found_grid, suffix, reader, data.shape)
        if geolocation
        else {}
    )
    dataset = wrap_swath(data, domain)
    dataset.band_names = [name]
    dataset.raster.SetMetadata(
        _channel_metadata(
            name,
            granule,
            found_grid,
            suffix,
            variable_meta,
            geolocated=bool(domain),
        )
    )
    return dataset

read_slstr(source, channel=None, *, channels=None, view=None, grid=None, geolocation=True) #

Read one or several SLSTR L1 RBT channels from a .SEN3 granule.

Decodes each requested channel's packed variable (raw * scale_factor + add_offset, with the _FillValue and anything outside the variable's validity limits masked to NaN) and returns it as a swath Dataset carrying the matching grid's per-pixel geolocation as a GDAL GEOLOCATION domain. The limits come from the valid_min / valid_max scalars the SLSTR L1 specification carries -- not from a combined valid_range, which appears nowhere in it -- and are compared against the raw, still-packed values.

Pass exactly one of channel (returns a Dataset) or channels (returns a dict[str, Dataset]). Channels on different grids have different array shapes, which is why a channel set returns a dict rather than a stack.

Either may also be given in the product's own variable spelling ("S5_radiance_bn"), and the grid and view it carries then select the file: they are honoured, not merely tolerated. So a channel set may mix views and grids per channel -- channels=["S5_radiance_an", "S8_BT_io"] reads one nadir and one oblique -- while view= / grid= supply whatever a bare spelling leaves open. A spelling that contradicts an explicit view= / grid= is an error rather than one of the two being silently ignored.

This reader decodes only -- issue #136 scopes radiometric calibration choices out. The RBT product is already geophysical, so S7-S9 / F1-F2 arrive as brightness temperature in kelvin with no conversion applied.

Parameters:

Name Type Description Default
source Any

The .SEN3 granule directory, or any file inside it.

required
channel str | None

A single channel ("S5", or "S5_radiance_bn"); mutually exclusive with channels.

None
channels Sequence[str] | None

A sequence of channels for a dict result; mutually exclusive with channel. The dict is keyed by canonical channel name, so two spellings of one channel -- even on different grids, as ["S5_radiance_an", "S5_radiance_bn"] -- are rejected as a duplicate rather than collapsing into one entry.

None
view str | None

"nadir" or "oblique" -- SLSTR images each scene twice. None (default) takes each channel's view from its own spelling, falling back to nadir for a bare one.

None
grid str | None

An explicit grid letter ("a", "b", "i", "f") restricting every channel to that one grid. None (default) uses a spelled grid where one is given and otherwise tries the channel's documented grids in order. A restricted read never falls back to another resolution: a channel the granule does not carry on that grid raises instead.

None
geolocation bool

When True (default), attach each result's GEOLOCATION domain.

True

Returns:

Type Description
Any

A pyramids Dataset (for channel) or a dict[str, Dataset] (for

Any

channels), each on its native swath grid with NaN nodata.

Raises:

Type Description
ReaderError

When neither / both of channel / channels are given, channels is empty or names a channel twice, a channel or the view is not an SLSTR one, a spelled channel names a quantity that channel does not ship or a grid / view contradicting an explicit grid= / view=, grid is not one of the four SLSTR grid letters, or the granule lacks a requested channel on the grid(s) tried. With geolocation=True, also when a channel's geodetic annotation is missing, is on a grid whose shape differs from the band, or carries an unusable scale_factor / add_offset.

Note

A _FillValue that is not a finite number cannot mask anything, so the decode emits a UserWarning per affected channel and the result's nodata is incomplete rather than the read failing (see invalid_mask).

Source code in src/pyramids_eo/sensors/readers/slstr.py
def read_slstr(
    source: Any,
    channel: str | None = None,
    *,
    channels: Sequence[str] | None = None,
    view: str | None = None,
    grid: str | None = None,
    geolocation: bool = True,
) -> Any:
    """Read one or several SLSTR L1 RBT channels from a `.SEN3` granule.

    Decodes each requested channel's packed variable (`raw * scale_factor +
    add_offset`, with the `_FillValue` and anything outside the variable's
    validity limits masked to NaN) and returns it as a swath `Dataset` carrying
    the matching grid's per-pixel geolocation as a GDAL `GEOLOCATION` domain. The
    limits come from the `valid_min` / `valid_max` scalars the SLSTR L1
    specification carries -- not from a combined `valid_range`, which appears
    nowhere in it -- and are compared against the raw, still-packed values.

    Pass exactly one of `channel` (returns a `Dataset`) or `channels` (returns a
    `dict[str, Dataset]`). Channels on different grids have **different array
    shapes**, which is why a channel set returns a dict rather than a stack.

    Either may also be given in the product's own variable spelling
    (`"S5_radiance_bn"`), and the grid and view it carries then **select the
    file**: they are honoured, not merely tolerated. So a channel set may mix views
    and grids per channel -- `channels=["S5_radiance_an", "S8_BT_io"]` reads one
    nadir and one oblique -- while `view=` / `grid=` supply whatever a bare
    spelling leaves open. A spelling that contradicts an explicit `view=` / `grid=`
    is an error rather than one of the two being silently ignored.

    This reader **decodes only** -- issue #136 scopes radiometric calibration
    choices out. The RBT product is already geophysical, so `S7`-`S9` / `F1`-`F2`
    arrive as brightness temperature in kelvin with no conversion applied.

    Args:
        source: The `.SEN3` granule directory, or any file inside it.
        channel: A single channel (`"S5"`, or `"S5_radiance_bn"`); mutually
            exclusive with `channels`.
        channels: A sequence of channels for a `dict` result; mutually exclusive
            with `channel`. The dict is keyed by **canonical** channel name, so two
            spellings of one channel -- even on different grids, as
            `["S5_radiance_an", "S5_radiance_bn"]` -- are rejected as a duplicate
            rather than collapsing into one entry.
        view: `"nadir"` or `"oblique"` -- SLSTR images each scene twice. `None`
            (default) takes each channel's view from its own spelling, falling back
            to nadir for a bare one.
        grid: An explicit grid letter (`"a"`, `"b"`, `"i"`, `"f"`) restricting
            every channel to that one grid. `None` (default) uses a spelled grid
            where one is given and otherwise tries the channel's documented grids
            in order. A restricted read never falls back to another resolution: a
            channel the granule does not carry on that grid raises instead.
        geolocation: When `True` (default), attach each result's `GEOLOCATION`
            domain.

    Returns:
        A pyramids `Dataset` (for `channel`) or a `dict[str, Dataset]` (for
        `channels`), each on its native swath grid with NaN nodata.

    Raises:
        ReaderError: When neither / both of `channel` / `channels` are given,
            `channels` is empty or names a channel twice, a channel or the view
            is not an SLSTR one, a spelled channel names a quantity that channel
            does not ship or a grid / view contradicting an explicit `grid=` /
            `view=`, `grid` is not one of the four SLSTR grid letters, or the
            granule lacks a requested channel on the grid(s) tried. With
            `geolocation=True`, also when a channel's geodetic annotation is
            missing, is on a grid whose shape differs from the band, or carries an
            unusable `scale_factor` / `add_offset`.

    Note:
        A `_FillValue` that is not a finite number cannot mask anything, so the
        decode emits a `UserWarning` per affected channel and the result's nodata
        is incomplete rather than the read failing (see `invalid_mask`).
    """
    requested, single = resolve_channels(channel, channels, "read_slstr")
    # Canonicalise before the duplicate check: `resolve_channels` compares the raw
    # strings, so aliases of one channel ("S5" and "s5") slip through it and would
    # otherwise collapse into a single dict entry, silently dropping a request.
    canonical = [_canonical_channel(name, "read_slstr") for name in requested]
    if len(set(canonical)) != len(canonical):
        duplicates = sorted({c for c in canonical if canonical.count(c) > 1})
        raise ReaderError(
            f"read_slstr: `channels` names the same channel more than once (after "
            f"normalising spellings): {duplicates}"
        )
    # Pass the caller's ORIGINAL spelling through, not the canonical name: a
    # spelled grid and view select a specific file, and canonicalising first would
    # strip them and read a different one.
    # Resolve the granule once for the whole set rather than per channel, matching
    # read_fci_l1c's and read_olci's read-once pattern.
    granule = resolve_granule(source, "read_slstr")
    results = {
        name: read_slstr_band(
            granule, spelling, view=view, grid=grid, geolocation=geolocation
        )
        for name, spelling in zip(canonical, requested)
    }
    return results[canonical[0]] if single else results

pyramids_eo.sensors.readers.harmonise #

Harmonise multi-resolution L1 bands onto a common grid.

FCI / SEVIRI channels arrive at different native resolutions (FCI: 0.5 / 1 / 2 km). harmonise warps/crops each band onto one target grid by delegating to pyramids' align (which copies the reference's CRS, rows/columns, and cell size and resamples the band onto it). No new reprojection code; the reference grid decides the output.

harmonise(bands, reference, *, method=None) #

Align a set of bands onto a reference grid.

Parameters:

Name Type Description Default
bands Any

The bands to harmonise — a mapping {name: Dataset} or an iterable of pyramids Datasets. Each is resampled onto reference's grid (CRS + rows/columns + cell size).

required
reference Any

A pyramids Dataset whose grid every band is aligned to.

required
method str | None

Resampling method. None (default) / "nearest" uses Dataset.align (nearest-neighbour onto the exact reference grid); any other value (e.g. "bilinear", "cubic") uses warped_view onto the reference's CRS + cell size + bbox — preferable for continuous reflectance / brightness-temperature bands.

None

Returns:

Type Description
Any

The aligned bands in the same container shape as the input: a dict

Any

{name: Dataset} for a mapping, else a list[Dataset].

Raises:

Type Description
ReaderError

When reference is None, or when bands is empty.

Source code in src/pyramids_eo/sensors/readers/harmonise.py
def harmonise(bands: Any, reference: Any, *, method: str | None = None) -> Any:
    """Align a set of bands onto a reference grid.

    Args:
        bands: The bands to harmonise — a mapping `{name: Dataset}` or an
            iterable of pyramids `Dataset`s. Each is resampled onto `reference`'s
            grid (CRS + rows/columns + cell size).
        reference: A pyramids `Dataset` whose grid every band is aligned to.
        method: Resampling method. `None` (default) / `"nearest"` uses
            `Dataset.align` (nearest-neighbour onto the exact reference grid); any
            other value (e.g. `"bilinear"`, `"cubic"`) uses `warped_view` onto the
            reference's CRS + cell size + bbox — preferable for continuous
            reflectance / brightness-temperature bands.

    Returns:
        The aligned bands in the same container shape as the input: a `dict`
        `{name: Dataset}` for a mapping, else a `list[Dataset]`.

    Raises:
        ReaderError: When `reference` is `None`, or when `bands` is empty.
    """
    if reference is None:
        raise ReaderError("harmonise: a reference grid is required")

    if isinstance(bands, dict):
        if not bands:
            raise ReaderError("harmonise: no bands given")
        return {
            name: _resample_to(band, reference, method) for name, band in bands.items()
        }

    band_list = list(bands)
    if not band_list:
        raise ReaderError("harmonise: no bands given")
    return [_resample_to(band, reference, method) for band in band_list]

Raster-driver plugins#

The EO readers are also registered as pyramids.raster_drivers plugins (the hook pyramids-core 0.70 added), so pyramids.dataset.Dataset.read_file(<source>) can route a source straight into pyramids-eo — no import of this package needed at the call site. Installing pyramids-eo is the whole integration. The Reading EO sources via read_file guide covers the dispatch rules, the open_options contract, and per-source recipes in full; the essentials:

driver name source reader
earthengine ee://<asset-id> from_earthengine
seviri a .nat granule read_seviri
ahi an HSD granule named HS_….DAT (optionally .bz2) read_ahi
s2 a .SAFE product (or .SAFE.zip) from_sentinel2
fci an FCI L1C granule: a chunk directory, a glob, or an fci:// path read_fci_l1c
olci a Sentinel-3 OLCI .SEN3 granule directory, or an olci:// path read_olci
slstr a Sentinel-3 SLSTR .SEN3 granule directory, or a slstr:// path read_slstr
from pyramids.dataset import Dataset

# auto-routed: GDAL cannot open these, so read_file falls through to the plugin
nat = Dataset.read_file("MSG_SEVIRI.nat", open_options={"channel": "IR_108"})
ee = Dataset.read_file("ee://USGS/SRTMGL1_003", open_options={"bbox": (0, 0, 1, 1)})
fci = Dataset.read_file("/data/fci_granule", open_options={"channel": "ir_105"})
fci2 = Dataset.read_file("fci:///data/fci_granule", open_options={"channel": "ir_105"})

# Himawari AHI: claimed by the HSD file-name convention, not by the generic .dat suffix,
# and the granule names its own band so open_options may be omitted entirely
ahi = Dataset.read_file("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")

# Sentinel-3: OLCI and SLSTR share the .SEN3 suffix, so the granule's contents decide
# which driver claims it (an olci:// / slstr:// prefix, or driver=, names one explicitly)
olci = Dataset.read_file("S3A_OL_1_EFR.SEN3", open_options={"channel": "Oa08"})
slstr = Dataset.read_file(
    "S3A_SL_1_RBT.SEN3", open_options={"channel": "S8", "view": "oblique"}
)

# Sentinel-2: a product directory auto-routes (GDAL cannot open one), and a zipped
# product auto-routes too because the driver pre-empts GDAL for `.zip`
s2 = Dataset.read_file("S2A_MSIL2A.SAFE", open_options={"bands": ["B04", "B03", "B02"]})
s2z = Dataset.read_file("S2A_MSIL2A.SAFE.zip", open_options={"bands": ["B04"]})

read_file forwards only open_options to a driver, so reader keywords (channel, bbox, bands, credentials, …) are passed there; options needing a non-string type (e.g. S2 resolution=10) must be given in dict form, not a KEY=VALUE list. A bare read_file("…SAFE") on a product directory reads the product: GDAL cannot open one, so the driver claims it on the fallback. A zipped product reads bare too: the driver declares preempts = (".zip",), so it is tried before GDAL would return a container. Narrow a zipped read with bands / resolution — a whole product is ~10 GiB. Which driver claims a .SAFE is decided by its contents, not its name: ESA shares the suffix with Sentinel-1, and those products stay with GDAL.

pyramids_eo.drivers #

Raster-reader drivers for the pyramids.raster_drivers plugin hook.

pyramids-core 0.70 added a pyramids.raster_drivers entry-point group: a third-party package registers a driver class there, and Dataset.read_file(<source>) routes a source GDAL cannot open into that driver with no import coupling. This subpackage registers pyramids-eo's readers:

  • :class:~pyramids_eo.drivers.earthengine.EarthEngineDriver — ee://<asset-id> sources.
  • :class:~pyramids_eo.drivers.seviri.SeviriDriver — SEVIRI native .nat granules.
  • :class:~pyramids_eo.drivers.ahi.AhiDriver — Himawari AHI Himawari Standard Data (.DAT) granules. It is one of two drivers here that declare a suffix and then deliberately narrow it in can_open — Sentinel-2 is the other, inspecting a product's contents to tell the mission apart: .dat is too generic, so it matches the HSD file-name convention instead (see its docstring).
  • :class:~pyramids_eo.drivers.sentinel2.Sentinel2Driver — Sentinel-2 .SAFE products.
  • :class:~pyramids_eo.drivers.fci.FciDriver — MTG-FCI L1C FDHSI granules (a chunk set named by a directory or glob).
  • :class:~pyramids_eo.drivers.olci.OlciDriver — Sentinel-3 OLCI L1B .SEN3 granules.
  • :class:~pyramids_eo.drivers.slstr.SlstrDriver — Sentinel-3 SLSTR L1 RBT .SEN3 granules.

OLCI and SLSTR products share the .SEN3 directory suffix, so both drivers claim it and their can_open predicates disambiguate on content — an OLCI granule holds Oa*_radiance.nc band files, an SLSTR one holds S*_radiance_*.nc / *_BT_*.nc. An olci:// or slstr:// prefix (or driver=) names one explicitly. Deciding on content has two consequences worth stating, since neither is obvious from the claim set:

  • A .SEN3 holding both kinds of file is claimed by both drivers, and select_driver takes the first claimant in registration order, which is alphabetical — so olci wins. The outcome is stable rather than arbitrary, and a scheme prefix or driver= overrides it.
  • An empty or incomplete .SEN3 is claimed by neither, so read_file surfaces GDAL's own "not recognized" error instead of the readers' more useful "the product looks incomplete or is not the expected Sentinel-3 level/type". Calling read_olci / read_slstr directly, or passing driver=, reaches that better message.

A boolean reader keyword passed through read_file arrives as a string, because Dataset.read_file normalises open_options to GDAL's KEY=VALUE form. The drivers translate those spellings (see :func:~pyramids_eo.drivers._base.coerce_booleans) rather than letting the truthy string "false" switch an option on.

The entry points in pyproject.toml are the whole integration; installing the package is enough for read_file to find these. Each driver is a thin wrapper over an existing reader (from_earthengine / read_seviri / read_ahi / from_sentinel2 / read_fci_l1c / read_olci / read_slstr), which stays the ergonomic public API.

Only a driver's read is reachable this way: Dataset.read_file never dispatches read_collection, so :meth:~pyramids_eo.drivers.earthengine.EarthEngineDriver.read_collection is declared and implemented but unreachable through the facade — a temporal stack goes through collection_from_earthengine.

A single read_file source string can name a set of files — a directory, a glob, or an fci:// path — which is how a multi-chunk FCI granule is addressed (see :func:~pyramids_eo.drivers._base.expand_sources). Sentinel-2 reaches this layer on the bare path in both its forms: a product directory through the post-GDAL can_open fallback (GDAL cannot open one), and a zipped product through pre-emption — :class:~pyramids_eo.drivers.sentinel2. Sentinel2Driver declares preempts = (".zip",), the opt-in pyramids-core 0.71 added (serapeum-org/pyramids-core#1344), because GDAL would otherwise open the archive and return a bare container. Because ESA shares .SAFE across missions, can_open identifies the mission from the product's contents rather than its name, so a Sentinel-1 product — zipped or not — is left to GDAL instead of failing in the Sentinel-2 reader.

AhiDriver #

Read one Himawari-8/9 AHI band from a Himawari Standard Data granule.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

(".dat",) — declared so the driver is discoverable for HSD granules. No preempts is declared alongside it, so the suffix never wins a read ahead of GDAL; can_open narrows the claim to the HSD name convention (see the module docstring).

schemes tuple[str, ...]

Empty — an HSD granule is a local file.

capabilities

read only (one granule is one band at one timestep).

extra str | None

None — the counts are decoded in-process with struct / numpy and the grid is registered through pyramids' bundled GDAL, so there is no optional backend to gate on.

Examples:

  • The driver identifies itself to describe_drivers and reads a single granule:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver.name
    'ahi'
    >>> AhiDriver.suffixes
    ('.dat',)
    >>> sorted(AhiDriver.capabilities)
    ['read']
    
  • It claims a granule by its HSD name, so an unrelated .dat is left to GDAL:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver.can_open("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
    True
    >>> AhiDriver.can_open("measurements.dat")
    False
    
Source code in src/pyramids_eo/drivers/ahi.py
class AhiDriver:
    """Read one Himawari-8/9 AHI band from a Himawari Standard Data granule.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: ``(".dat",)`` — declared so the driver is discoverable for HSD granules. No
            ``preempts`` is declared alongside it, so the suffix never wins a read ahead of GDAL;
            ``can_open`` narrows the claim to the HSD name convention (see the module docstring).
        schemes: Empty — an HSD granule is a local file.
        capabilities: ``read`` only (one granule is one band at one timestep).
        extra: ``None`` — the counts are decoded in-process with ``struct`` / ``numpy`` and the
            grid is registered through pyramids' bundled GDAL, so there is no optional backend
            to gate on.

    Examples:
        - The driver identifies itself to ``describe_drivers`` and reads a single granule:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver.name
            'ahi'
            >>> AhiDriver.suffixes
            ('.dat',)
            >>> sorted(AhiDriver.capabilities)
            ['read']

            ```
        - It claims a granule by its HSD name, so an unrelated ``.dat`` is left to GDAL:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver.can_open("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
            True
            >>> AhiDriver.can_open("measurements.dat")
            False

            ```
    """

    name = "ahi"
    long_name = "Himawari-8/9 AHI Himawari Standard Data (.DAT)"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = (".dat",)
    schemes: tuple[str, ...] = ()
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` names a Himawari Standard Data granule.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified).

        Returns:
            True when the base name follows the HSD convention
            ``HS_aaa_yyyymmdd_hhnn_Bbb_cccc_Rjj_Skkll.DAT`` (optionally ``.bz2``), else False.
            Anything that is not a ``str`` is False, including a `pathlib.Path` — ``read_file``
            stringifies the source before it scans, so a path only ever arrives here already
            stringified. Cheap: no import, no network, no file access, and safe for a path that
            does not exist — matching the name rather than the generic ``.dat`` suffix keeps the
            driver from claiming unrelated files.

        Examples:
            - An HSD granule is claimed; a bare ``.dat`` or another suffix is not:
                ```python
                >>> from pyramids_eo.drivers.ahi import AhiDriver
                >>> AhiDriver.can_open("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
                True
                >>> AhiDriver.can_open("/data/HS_H09_20240101_0000_B03_FLDK_R05_S0110.DAT.bz2")
                True
                >>> AhiDriver.can_open("scene.dat")
                False
                >>> AhiDriver.can_open("scene.tif")
                False

                ```
        """
        if not isinstance(source, str):
            return False
        base = source.replace("\\", "/").rsplit("/", 1)[-1]
        return _HSD_NAME_RE.match(base) is not None

    def read(
        self,
        source: Any,
        *,
        bands: Any = None,
        options: Any = None,
        **_ignored: Any,
    ) -> Dataset:
        """Read one AHI band into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: Path to an HSD ``.DAT`` / ``.DAT.bz2`` granule.
            bands: Optionally the band to read, as a one-element list (e.g. ``["B13"]``); an
                alternative to ``options={"band": …}``. A granule names its own band, so this
                only asserts the expectation. An AHI read is a single band, so more than one is
                rejected rather than silently truncated.
            options: Extra :func:`~pyramids_eo.sensors.readers.read_ahi` keywords — ``band``,
                ``calibrate``, ``sun_earth_distance``, ``coeffs``, ``cos_sza`` — as a dict or
                ``KEY=VALUE`` list. ``read_file`` normalises options to the ``KEY=VALUE`` form,
                so ``calibrate`` and ``sun_earth_distance`` are coerced from their string
                spellings (see :func:`~pyramids_eo.drivers._base.coerce_booleans`); without
                that, the truthy string ``"false"`` would switch calibration *on*.

                ``coeffs`` and ``cos_sza`` are **not** coerced, because neither has a
                ``KEY=VALUE`` spelling: one is a mapping and the other an array. Pass them in
                dict form — ``open_options={"coeffs": {...}}`` — exactly as Sentinel-2's
                ``resolution=10`` must be; through a ``KEY=VALUE`` list they would arrive as
                strings and ``read_ahi`` would reject them. An option this reader does not
                take is forwarded and surfaces as a ``TypeError`` from ``read_ahi``, not a
                ``ValueError`` from here.
            **_ignored: The generic driver-read parameters an AHI read does not use — ``bbox``,
                ``crs``, ``auth`` and any future one — are accepted and ignored: a granule is
                read whole, carries its own geostationary CRS, and needs no credentials.

        Returns:
            The calibrated, geolocated band.

        Raises:
            ValueError: ``bands`` is a bare ``str`` / ``bytes`` rather than a one-element list;
                more than one band was given; ``options`` is a bare string or carries an item
                that is not ``"KEY=VALUE"``; or a boolean / numeric option could not be read
                from its ``KEY=VALUE`` string spelling (``calibrate``, ``sun_earth_distance``).
            ReaderError: The granule carries a band other than the one requested, or cannot be
                decoded (raised by ``read_ahi``, not here).

        Examples:
            - An AHI read is one band, so several are refused rather than silently
              truncated. The check happens before the granule is opened, so no file is
              needed to see it:
                ```python
                >>> from pyramids_eo.drivers.ahi import AhiDriver
                >>> AhiDriver().read(  # doctest: +ELLIPSIS
                ...     "scene.DAT", bands=["B13", "B14"]
                ... )
                Traceback (most recent call last):
                    ...
                ValueError: an AHI read is one band, but 2 bands were given ...

                ```
            - A bare string would be read one character at a time, so it is refused with
              the spelling that works:
                ```python
                >>> from pyramids_eo.drivers.ahi import AhiDriver
                >>> AhiDriver().read("scene.DAT", bands="B13")
                Traceback (most recent call last):
                    ...
                ValueError: bands must be a list of band names, not a bare str ('B13'); pass bands=['B13'].

                ```
            - ``read_file`` normalises options to ``KEY=VALUE`` strings, so a boolean that
              cannot be read from its spelling is reported instead of being taken as truthy:
                ```python
                >>> from pyramids_eo.drivers.ahi import AhiDriver
                >>> AhiDriver().read(  # doctest: +ELLIPSIS
                ...     "scene.DAT", options=["calibrate=maybe"]
                ... )
                Traceback (most recent call last):
                    ...
                ValueError: ahi: open option 'calibrate' must be a boolean; got 'maybe'. ...

                ```
        """
        from pyramids_eo.sensors.readers import read_ahi

        settings = options_as_dict(options)
        coerce_booleans(settings, ("calibrate",), driver="ahi")
        coerce_floats(settings, ("sun_earth_distance",), driver="ahi")
        band = settings.pop("band", None)
        # A list given as `options={"band": [...]}` used to bypass every check
        # below, so three bands or a bare-string-in-a-list went straight through
        # to the reader. Route both spellings through the same validation.
        if band is not None and not isinstance(band, (str, bytes, int)):
            bands, band = band, None
        if band is None and bands is not None and not isinstance(bands, (str, bytes)):
            bands = list(bands)  # materialise a generator/iterator so len() is safe
        if band is None and bands:
            if isinstance(bands, (str, bytes)):
                raise ValueError(
                    f"bands must be a list of band names, not a bare "
                    f"{type(bands).__name__} ({bands!r}); pass bands=['B13']."
                )
            if len(bands) != 1:
                raise ValueError(
                    f"an AHI read is one band, but {len(bands)} bands were given "
                    f"({bands}); pass a single band or options={{'band': 'B13'}}."
                )
            band = bands[0]
        return read_ahi(source, band, **settings)
can_open(source) classmethod #

Return whether source names a Himawari Standard Data granule.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified).

required

Returns:

Type Description
bool

True when the base name follows the HSD convention

bool

HS_aaa_yyyymmdd_hhnn_Bbb_cccc_Rjj_Skkll.DAT (optionally .bz2), else False.

bool

Anything that is not a str is False, including a pathlib.Path — read_file

bool

stringifies the source before it scans, so a path only ever arrives here already

bool

stringified. Cheap: no import, no network, no file access, and safe for a path that

bool

does not exist — matching the name rather than the generic .dat suffix keeps the

bool

driver from claiming unrelated files.

Examples:

  • An HSD granule is claimed; a bare .dat or another suffix is not:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver.can_open("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
    True
    >>> AhiDriver.can_open("/data/HS_H09_20240101_0000_B03_FLDK_R05_S0110.DAT.bz2")
    True
    >>> AhiDriver.can_open("scene.dat")
    False
    >>> AhiDriver.can_open("scene.tif")
    False
    
Source code in src/pyramids_eo/drivers/ahi.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` names a Himawari Standard Data granule.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified).

    Returns:
        True when the base name follows the HSD convention
        ``HS_aaa_yyyymmdd_hhnn_Bbb_cccc_Rjj_Skkll.DAT`` (optionally ``.bz2``), else False.
        Anything that is not a ``str`` is False, including a `pathlib.Path` — ``read_file``
        stringifies the source before it scans, so a path only ever arrives here already
        stringified. Cheap: no import, no network, no file access, and safe for a path that
        does not exist — matching the name rather than the generic ``.dat`` suffix keeps the
        driver from claiming unrelated files.

    Examples:
        - An HSD granule is claimed; a bare ``.dat`` or another suffix is not:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver.can_open("HS_H08_20150415_0230_B13_FLDK_R20_S0101.DAT")
            True
            >>> AhiDriver.can_open("/data/HS_H09_20240101_0000_B03_FLDK_R05_S0110.DAT.bz2")
            True
            >>> AhiDriver.can_open("scene.dat")
            False
            >>> AhiDriver.can_open("scene.tif")
            False

            ```
    """
    if not isinstance(source, str):
        return False
    base = source.replace("\\", "/").rsplit("/", 1)[-1]
    return _HSD_NAME_RE.match(base) is not None
read(source, *, bands=None, options=None, **_ignored) #

Read one AHI band into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

Path to an HSD .DAT / .DAT.bz2 granule.

required
bands Any

Optionally the band to read, as a one-element list (e.g. ["B13"]); an alternative to options={"band": …}. A granule names its own band, so this only asserts the expectation. An AHI read is a single band, so more than one is rejected rather than silently truncated.

None
options Any

Extra :func:~pyramids_eo.sensors.readers.read_ahi keywords — band, calibrate, sun_earth_distance, coeffs, cos_sza — as a dict or KEY=VALUE list. read_file normalises options to the KEY=VALUE form, so calibrate and sun_earth_distance are coerced from their string spellings (see :func:~pyramids_eo.drivers._base.coerce_booleans); without that, the truthy string "false" would switch calibration on.

coeffs and cos_sza are not coerced, because neither has a KEY=VALUE spelling: one is a mapping and the other an array. Pass them in dict form — open_options={"coeffs": {...}} — exactly as Sentinel-2's resolution=10 must be; through a KEY=VALUE list they would arrive as strings and read_ahi would reject them. An option this reader does not take is forwarded and surfaces as a TypeError from read_ahi, not a ValueError from here.

None
**_ignored Any

The generic driver-read parameters an AHI read does not use — bbox, crs, auth and any future one — are accepted and ignored: a granule is read whole, carries its own geostationary CRS, and needs no credentials.

{}

Returns:

Type Description
Dataset

The calibrated, geolocated band.

Raises:

Type Description
ValueError

bands is a bare str / bytes rather than a one-element list; more than one band was given; options is a bare string or carries an item that is not "KEY=VALUE"; or a boolean / numeric option could not be read from its KEY=VALUE string spelling (calibrate, sun_earth_distance).

ReaderError

The granule carries a band other than the one requested, or cannot be decoded (raised by read_ahi, not here).

Examples:

  • An AHI read is one band, so several are refused rather than silently truncated. The check happens before the granule is opened, so no file is needed to see it:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver().read(  # doctest: +ELLIPSIS
    ...     "scene.DAT", bands=["B13", "B14"]
    ... )
    Traceback (most recent call last):
        ...
    ValueError: an AHI read is one band, but 2 bands were given ...
    
  • A bare string would be read one character at a time, so it is refused with the spelling that works:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver().read("scene.DAT", bands="B13")
    Traceback (most recent call last):
        ...
    ValueError: bands must be a list of band names, not a bare str ('B13'); pass bands=['B13'].
    
  • read_file normalises options to KEY=VALUE strings, so a boolean that cannot be read from its spelling is reported instead of being taken as truthy:
    >>> from pyramids_eo.drivers.ahi import AhiDriver
    >>> AhiDriver().read(  # doctest: +ELLIPSIS
    ...     "scene.DAT", options=["calibrate=maybe"]
    ... )
    Traceback (most recent call last):
        ...
    ValueError: ahi: open option 'calibrate' must be a boolean; got 'maybe'. ...
    
Source code in src/pyramids_eo/drivers/ahi.py
def read(
    self,
    source: Any,
    *,
    bands: Any = None,
    options: Any = None,
    **_ignored: Any,
) -> Dataset:
    """Read one AHI band into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: Path to an HSD ``.DAT`` / ``.DAT.bz2`` granule.
        bands: Optionally the band to read, as a one-element list (e.g. ``["B13"]``); an
            alternative to ``options={"band": …}``. A granule names its own band, so this
            only asserts the expectation. An AHI read is a single band, so more than one is
            rejected rather than silently truncated.
        options: Extra :func:`~pyramids_eo.sensors.readers.read_ahi` keywords — ``band``,
            ``calibrate``, ``sun_earth_distance``, ``coeffs``, ``cos_sza`` — as a dict or
            ``KEY=VALUE`` list. ``read_file`` normalises options to the ``KEY=VALUE`` form,
            so ``calibrate`` and ``sun_earth_distance`` are coerced from their string
            spellings (see :func:`~pyramids_eo.drivers._base.coerce_booleans`); without
            that, the truthy string ``"false"`` would switch calibration *on*.

            ``coeffs`` and ``cos_sza`` are **not** coerced, because neither has a
            ``KEY=VALUE`` spelling: one is a mapping and the other an array. Pass them in
            dict form — ``open_options={"coeffs": {...}}`` — exactly as Sentinel-2's
            ``resolution=10`` must be; through a ``KEY=VALUE`` list they would arrive as
            strings and ``read_ahi`` would reject them. An option this reader does not
            take is forwarded and surfaces as a ``TypeError`` from ``read_ahi``, not a
            ``ValueError`` from here.
        **_ignored: The generic driver-read parameters an AHI read does not use — ``bbox``,
            ``crs``, ``auth`` and any future one — are accepted and ignored: a granule is
            read whole, carries its own geostationary CRS, and needs no credentials.

    Returns:
        The calibrated, geolocated band.

    Raises:
        ValueError: ``bands`` is a bare ``str`` / ``bytes`` rather than a one-element list;
            more than one band was given; ``options`` is a bare string or carries an item
            that is not ``"KEY=VALUE"``; or a boolean / numeric option could not be read
            from its ``KEY=VALUE`` string spelling (``calibrate``, ``sun_earth_distance``).
        ReaderError: The granule carries a band other than the one requested, or cannot be
            decoded (raised by ``read_ahi``, not here).

    Examples:
        - An AHI read is one band, so several are refused rather than silently
          truncated. The check happens before the granule is opened, so no file is
          needed to see it:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver().read(  # doctest: +ELLIPSIS
            ...     "scene.DAT", bands=["B13", "B14"]
            ... )
            Traceback (most recent call last):
                ...
            ValueError: an AHI read is one band, but 2 bands were given ...

            ```
        - A bare string would be read one character at a time, so it is refused with
          the spelling that works:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver().read("scene.DAT", bands="B13")
            Traceback (most recent call last):
                ...
            ValueError: bands must be a list of band names, not a bare str ('B13'); pass bands=['B13'].

            ```
        - ``read_file`` normalises options to ``KEY=VALUE`` strings, so a boolean that
          cannot be read from its spelling is reported instead of being taken as truthy:
            ```python
            >>> from pyramids_eo.drivers.ahi import AhiDriver
            >>> AhiDriver().read(  # doctest: +ELLIPSIS
            ...     "scene.DAT", options=["calibrate=maybe"]
            ... )
            Traceback (most recent call last):
                ...
            ValueError: ahi: open option 'calibrate' must be a boolean; got 'maybe'. ...

            ```
    """
    from pyramids_eo.sensors.readers import read_ahi

    settings = options_as_dict(options)
    coerce_booleans(settings, ("calibrate",), driver="ahi")
    coerce_floats(settings, ("sun_earth_distance",), driver="ahi")
    band = settings.pop("band", None)
    # A list given as `options={"band": [...]}` used to bypass every check
    # below, so three bands or a bare-string-in-a-list went straight through
    # to the reader. Route both spellings through the same validation.
    if band is not None and not isinstance(band, (str, bytes, int)):
        bands, band = band, None
    if band is None and bands is not None and not isinstance(bands, (str, bytes)):
        bands = list(bands)  # materialise a generator/iterator so len() is safe
    if band is None and bands:
        if isinstance(bands, (str, bytes)):
            raise ValueError(
                f"bands must be a list of band names, not a bare "
                f"{type(bands).__name__} ({bands!r}); pass bands=['B13']."
            )
        if len(bands) != 1:
            raise ValueError(
                f"an AHI read is one band, but {len(bands)} bands were given "
                f"({bands}); pass a single band or options={{'band': 'B13'}}."
            )
        band = bands[0]
    return read_ahi(source, band, **settings)

EarthEngineDriver #

Read an Earth Engine Image or ImageCollection via an ee:// source.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

Empty — an Earth Engine asset has no file.

schemes tuple[str, ...]

("ee",) — the driver claims ee://… sources.

capabilities

read (single image), read_collection (temporal stack), and needs_auth (an Earth Engine read needs credentials).

extra str | None

None — EE is reached through pyramids' bundled GDAL EEDAI driver, so there is no separate optional backend to gate discovery on.

Source code in src/pyramids_eo/drivers/earthengine.py
class EarthEngineDriver:
    """Read an Earth Engine ``Image`` or ``ImageCollection`` via an ``ee://`` source.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: Empty — an Earth Engine asset has no file.
        schemes: ``("ee",)`` — the driver claims ``ee://…`` sources.
        capabilities: ``read`` (single image), ``read_collection`` (temporal stack), and
            ``needs_auth`` (an Earth Engine read needs credentials).
        extra: ``None`` — EE is reached through pyramids' bundled GDAL EEDAI driver, so there is
            no separate optional backend to gate discovery on.
    """

    name = "earthengine"
    long_name = "Google Earth Engine"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = ()
    schemes: tuple[str, ...] = ("ee",)
    capabilities = frozenset({"read", "read_collection", "needs_auth"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` is an ``ee://`` Earth Engine asset id.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified).

        Returns:
            True for a string beginning ``ee://`` (case-insensitive), else False. Cheap: no
            import, no network.

        Examples:
            - An ``ee://`` source is claimed; a plain path or a bare asset id is not:
                ```python
                >>> from pyramids_eo.drivers.earthengine import EarthEngineDriver
                >>> EarthEngineDriver.can_open("ee://COPERNICUS/S2_SR_HARMONIZED")
                True
                >>> EarthEngineDriver.can_open("scene.tif")
                False
                >>> EarthEngineDriver.can_open("COPERNICUS/S2_SR_HARMONIZED")
                False

                ```
        """
        return isinstance(source, str) and source.lower().startswith(_SCHEME)

    def read(
        self,
        source: Any,
        *,
        bbox: Any = None,
        bands: Any = None,
        crs: Any = None,
        options: Any = None,
        auth: Any = None,
    ) -> Dataset:
        """Read a single Earth Engine image into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: An ``ee://<asset-id>`` string.
            bbox: Optional AOI ``(min_x, min_y, max_x, max_y)`` for the output window.
            bands: Optional band subset.
            crs: Optional target CRS for the output window.
            options: Extra :func:`~pyramids_eo.from_earthengine` keywords (e.g. ``reducer``,
                ``start``, ``end``, ``tile_size``, ``path``) as a dict or ``KEY=VALUE`` list.
                Because ``Dataset.read_file`` forwards only ``options`` to a driver, the window,
                band, and credential inputs may also be given here as ``bbox``/``crs``/``window``,
                ``bands``, and ``credentials`` (or ``auth``) keys; a *non-``None``* explicit
                keyword below wins over the same key in ``options`` (an explicit ``None`` is
                indistinguishable from "not given" and so does not override), and each is consumed
                so it cannot collide. A ``window`` key in ``options`` is used as-is and takes
                precedence over any ``bbox``/``crs``.
            auth: Credentials for the Earth Engine read, passed as ``credentials=``.

        Returns:
            The windowed image.
        """
        from pyramids_eo import Window, from_earthengine

        settings = options_as_dict(options)
        # Pop every reserved key unconditionally so a leftover can never collide with the matching
        # from_earthengine keyword below; then let an explicit read keyword win over the option.
        opt_bbox = settings.pop("bbox", None)
        opt_crs = settings.pop("crs", None)
        opt_bands = settings.pop("bands", None)
        opt_window = settings.pop("window", None)
        opt_cred = settings.pop("credentials", None)
        opt_auth = settings.pop("auth", None)
        bbox = bbox if bbox is not None else opt_bbox
        crs = crs if crs is not None else opt_crs
        bands = bands if bands is not None else opt_bands
        if auth is None:
            auth = opt_cred if opt_cred is not None else opt_auth
        window = opt_window
        if window is None:
            window = (
                Window(bbox=bbox, crs=crs)
                if bbox is not None or crs is not None
                else Window()
            )
        return from_earthengine(
            _strip_scheme(str(source)),
            window=window,
            bands=bands,
            credentials=auth,
            **settings,
        )

    def read_collection(
        self, source: Any, *, time: Any = None, **kwargs: Any
    ) -> DatasetCollection:
        """Read an Earth Engine ``ImageCollection`` into a temporal ``DatasetCollection``.

        pyramids 0.70's :meth:`Dataset.read_file` dispatches only :meth:`read` (single image) —
        it has no collection path — so this method is reached by a direct call, and is here for
        that use and for forward-compatibility if pyramids adds collection dispatch.

        Args:
            source: An ``ee://<asset-id>`` string.
            time: Optional ``(start, end)`` date pair; an alternative to passing ``start`` and
                ``end`` in ``kwargs``. Must be a two-element sequence.
            **kwargs: :func:`~pyramids_eo.collection_from_earthengine` keywords — ``start``,
                ``end`` (both required), ``window``, ``bands``, and ``credentials`` (or ``auth``).
                An explicit ``start``/``end`` keyword takes precedence over the matching element
                of ``time``, and an explicit ``credentials`` takes precedence over ``auth``.

        Returns:
            One aligned timestep per scene.

        Raises:
            ValueError: ``time`` is not a two-element pair, or the resolved ``start``/``end`` are
                not both given and non-``None``.
        """
        from pyramids_eo import collection_from_earthengine

        settings = dict(kwargs)
        if time is not None:
            if not isinstance(time, (tuple, list)) or len(time) != 2:
                raise ValueError(
                    f"time must be a (start, end) pair, got {time!r}; pass a two-element "
                    "sequence or start=… and end=… instead."
                )
            start, end = time
            settings.setdefault(
                "start", start
            )  # an explicit start= keyword wins over time
            settings.setdefault("end", end)
        auth = settings.pop("auth", None)
        if auth is not None:
            settings.setdefault(
                "credentials", auth
            )  # an explicit credentials= wins over auth
        if settings.get("start") is None or settings.get("end") is None:
            raise ValueError(
                "an Earth Engine collection read needs a date range: pass time=(start, end) "
                "or start=… and end=… (both non-None)."
            )
        return collection_from_earthengine(_strip_scheme(str(source)), **settings)
can_open(source) classmethod #

Return whether source is an ee:// Earth Engine asset id.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified).

required

Returns:

Type Description
bool

True for a string beginning ee:// (case-insensitive), else False. Cheap: no

bool

import, no network.

Examples:

  • An ee:// source is claimed; a plain path or a bare asset id is not:
    >>> from pyramids_eo.drivers.earthengine import EarthEngineDriver
    >>> EarthEngineDriver.can_open("ee://COPERNICUS/S2_SR_HARMONIZED")
    True
    >>> EarthEngineDriver.can_open("scene.tif")
    False
    >>> EarthEngineDriver.can_open("COPERNICUS/S2_SR_HARMONIZED")
    False
    
Source code in src/pyramids_eo/drivers/earthengine.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` is an ``ee://`` Earth Engine asset id.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified).

    Returns:
        True for a string beginning ``ee://`` (case-insensitive), else False. Cheap: no
        import, no network.

    Examples:
        - An ``ee://`` source is claimed; a plain path or a bare asset id is not:
            ```python
            >>> from pyramids_eo.drivers.earthengine import EarthEngineDriver
            >>> EarthEngineDriver.can_open("ee://COPERNICUS/S2_SR_HARMONIZED")
            True
            >>> EarthEngineDriver.can_open("scene.tif")
            False
            >>> EarthEngineDriver.can_open("COPERNICUS/S2_SR_HARMONIZED")
            False

            ```
    """
    return isinstance(source, str) and source.lower().startswith(_SCHEME)
read(source, *, bbox=None, bands=None, crs=None, options=None, auth=None) #

Read a single Earth Engine image into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

An ee://<asset-id> string.

required
bbox Any

Optional AOI (min_x, min_y, max_x, max_y) for the output window.

None
bands Any

Optional band subset.

None
crs Any

Optional target CRS for the output window.

None
options Any

Extra :func:~pyramids_eo.from_earthengine keywords (e.g. reducer, start, end, tile_size, path) as a dict or KEY=VALUE list. Because Dataset.read_file forwards only options to a driver, the window, band, and credential inputs may also be given here as bbox/crs/window, bands, and credentials (or auth) keys; a non-None explicit keyword below wins over the same key in options (an explicit None is indistinguishable from "not given" and so does not override), and each is consumed so it cannot collide. A window key in options is used as-is and takes precedence over any bbox/crs.

None
auth Any

Credentials for the Earth Engine read, passed as credentials=.

None

Returns:

Type Description
Dataset

The windowed image.

Source code in src/pyramids_eo/drivers/earthengine.py
def read(
    self,
    source: Any,
    *,
    bbox: Any = None,
    bands: Any = None,
    crs: Any = None,
    options: Any = None,
    auth: Any = None,
) -> Dataset:
    """Read a single Earth Engine image into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: An ``ee://<asset-id>`` string.
        bbox: Optional AOI ``(min_x, min_y, max_x, max_y)`` for the output window.
        bands: Optional band subset.
        crs: Optional target CRS for the output window.
        options: Extra :func:`~pyramids_eo.from_earthengine` keywords (e.g. ``reducer``,
            ``start``, ``end``, ``tile_size``, ``path``) as a dict or ``KEY=VALUE`` list.
            Because ``Dataset.read_file`` forwards only ``options`` to a driver, the window,
            band, and credential inputs may also be given here as ``bbox``/``crs``/``window``,
            ``bands``, and ``credentials`` (or ``auth``) keys; a *non-``None``* explicit
            keyword below wins over the same key in ``options`` (an explicit ``None`` is
            indistinguishable from "not given" and so does not override), and each is consumed
            so it cannot collide. A ``window`` key in ``options`` is used as-is and takes
            precedence over any ``bbox``/``crs``.
        auth: Credentials for the Earth Engine read, passed as ``credentials=``.

    Returns:
        The windowed image.
    """
    from pyramids_eo import Window, from_earthengine

    settings = options_as_dict(options)
    # Pop every reserved key unconditionally so a leftover can never collide with the matching
    # from_earthengine keyword below; then let an explicit read keyword win over the option.
    opt_bbox = settings.pop("bbox", None)
    opt_crs = settings.pop("crs", None)
    opt_bands = settings.pop("bands", None)
    opt_window = settings.pop("window", None)
    opt_cred = settings.pop("credentials", None)
    opt_auth = settings.pop("auth", None)
    bbox = bbox if bbox is not None else opt_bbox
    crs = crs if crs is not None else opt_crs
    bands = bands if bands is not None else opt_bands
    if auth is None:
        auth = opt_cred if opt_cred is not None else opt_auth
    window = opt_window
    if window is None:
        window = (
            Window(bbox=bbox, crs=crs)
            if bbox is not None or crs is not None
            else Window()
        )
    return from_earthengine(
        _strip_scheme(str(source)),
        window=window,
        bands=bands,
        credentials=auth,
        **settings,
    )
read_collection(source, *, time=None, **kwargs) #

Read an Earth Engine ImageCollection into a temporal DatasetCollection.

pyramids 0.70's :meth:Dataset.read_file dispatches only :meth:read (single image) — it has no collection path — so this method is reached by a direct call, and is here for that use and for forward-compatibility if pyramids adds collection dispatch.

Parameters:

Name Type Description Default
source Any

An ee://<asset-id> string.

required
time Any

Optional (start, end) date pair; an alternative to passing start and end in kwargs. Must be a two-element sequence.

None
**kwargs Any

:func:~pyramids_eo.collection_from_earthengine keywords — start, end (both required), window, bands, and credentials (or auth). An explicit start/end keyword takes precedence over the matching element of time, and an explicit credentials takes precedence over auth.

{}

Returns:

Type Description
DatasetCollection

One aligned timestep per scene.

Raises:

Type Description
ValueError

time is not a two-element pair, or the resolved start/end are not both given and non-None.

Source code in src/pyramids_eo/drivers/earthengine.py
def read_collection(
    self, source: Any, *, time: Any = None, **kwargs: Any
) -> DatasetCollection:
    """Read an Earth Engine ``ImageCollection`` into a temporal ``DatasetCollection``.

    pyramids 0.70's :meth:`Dataset.read_file` dispatches only :meth:`read` (single image) —
    it has no collection path — so this method is reached by a direct call, and is here for
    that use and for forward-compatibility if pyramids adds collection dispatch.

    Args:
        source: An ``ee://<asset-id>`` string.
        time: Optional ``(start, end)`` date pair; an alternative to passing ``start`` and
            ``end`` in ``kwargs``. Must be a two-element sequence.
        **kwargs: :func:`~pyramids_eo.collection_from_earthengine` keywords — ``start``,
            ``end`` (both required), ``window``, ``bands``, and ``credentials`` (or ``auth``).
            An explicit ``start``/``end`` keyword takes precedence over the matching element
            of ``time``, and an explicit ``credentials`` takes precedence over ``auth``.

    Returns:
        One aligned timestep per scene.

    Raises:
        ValueError: ``time`` is not a two-element pair, or the resolved ``start``/``end`` are
            not both given and non-``None``.
    """
    from pyramids_eo import collection_from_earthengine

    settings = dict(kwargs)
    if time is not None:
        if not isinstance(time, (tuple, list)) or len(time) != 2:
            raise ValueError(
                f"time must be a (start, end) pair, got {time!r}; pass a two-element "
                "sequence or start=… and end=… instead."
            )
        start, end = time
        settings.setdefault(
            "start", start
        )  # an explicit start= keyword wins over time
        settings.setdefault("end", end)
    auth = settings.pop("auth", None)
    if auth is not None:
        settings.setdefault(
            "credentials", auth
        )  # an explicit credentials= wins over auth
    if settings.get("start") is None or settings.get("end") is None:
        raise ValueError(
            "an Earth Engine collection read needs a date range: pass time=(start, end) "
            "or start=… and end=… (both non-None)."
        )
    return collection_from_earthengine(_strip_scheme(str(source)), **settings)

FciDriver #

Read one or more MTG-FCI L1C FDHSI channels from a granule's chunk set.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

Empty — a granule is a directory or glob of chunks, not a single-file suffix.

schemes tuple[str, ...]

("fci",) — an fci:// path names a granule explicitly (and is the routable declaration the contract requires, since a granule has no file suffix). can_open also claims a bare granule directory.

capabilities

read only (one granule is one timestep).

extra str | None

None — the reader is pure pyramids-eo over pyramids' bundled GDAL, with no optional backend to gate on.

Source code in src/pyramids_eo/drivers/fci.py
class FciDriver:
    """Read one or more MTG-FCI L1C FDHSI channels from a granule's chunk set.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: Empty — a granule is a directory or glob of chunks, not a single-file suffix.
        schemes: ``("fci",)`` — an ``fci://`` path names a granule explicitly (and is the routable
            declaration the contract requires, since a granule has no file suffix). ``can_open``
            also claims a bare granule directory.
        capabilities: ``read`` only (one granule is one timestep).
        extra: ``None`` — the reader is pure pyramids-eo over pyramids' bundled GDAL, with no
            optional backend to gate on.
    """

    name = "fci"
    long_name = "MTG-FCI L1C FDHSI granule"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = ()
    schemes: tuple[str, ...] = ("fci",)
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` names a real FCI L1C FDHSI chunk set.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified) — an ``fci://`` path,
                a directory, or a glob string.

        Returns:
            True for an ``fci://`` source, a directory containing at least one ``*FDHSI*.nc``
            chunk, or a glob whose matches include one; False for an empty source. It does a
            bounded, non-recursive directory listing / glob (no file open, no network) — more than
            the string-only ``can_open`` of the other drivers, but it runs only when GDAL has
            already failed to open the source, a very broad user glob (e.g. ``**``) is the caller's
            cost, and a filesystem error (e.g. an unreadable directory) is swallowed to False so
            the method never raises. ``driver="fci"`` bypasses this, so a non-standard chunk set can
            still be read explicitly.

        Examples:
            - An ``fci://`` source is always claimed (a cheap string check):
                ```python
                >>> from pyramids_eo.drivers.fci import FciDriver
                >>> FciDriver.can_open("fci://MTG_FCI_granule")
                True

                ```
            - A non-string source is never claimed:
                ```python
                >>> FciDriver.can_open(42)
                False

                ```
        """
        if not isinstance(source, str) or not source:
            return False
        if source.lower().startswith(_SCHEME):
            return True
        # Resolve an existing path literally first, so a real granule directory whose own name
        # contains a glob metacharacter (e.g. ``granule[1]``) is stat-checked, not treated as a
        # pattern. Only a non-existent source is interpreted as a glob. The filesystem probes are
        # wrapped so can_open honours its contract of never raising (an unreadable dir -> False).
        try:
            path = Path(source)
            if path.is_dir():
                return any(path.glob(_FDHSI_GLOB))
            if path.exists():
                return False
            if any(character in source for character in "*?["):
                return any(
                    "fdhsi" in Path(match).name.lower() for match in glob(source)
                )
        except (OSError, ValueError):
            return False
        return False

    def read(
        self,
        source: Any,
        *,
        bands: Any = None,
        options: Any = None,
        **_ignored: Any,
    ) -> Dataset | dict[str, Dataset]:
        """Read one or more FCI L1C channels into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: A directory of FDHSI ``.nc`` chunks, a glob matching them, a single chunk, or
                any of those prefixed ``fci://``.
            bands: The channel(s) to read — one name for a single-channel ``Dataset``, several for
                a ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
                forwards just ``options`` to a driver, so through ``read_file`` the channel must
                come from ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
                ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
            options: Extra :func:`~pyramids_eo.sensors.readers.read_fci_l1c` keywords — ``channel``
                / ``channels``, ``calibrate``, ``sun_earth_distance``, ``cos_sza`` — as a dict or
                ``KEY=VALUE`` list.
            **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
                accepted and ignored — a granule is read whole, carries its own geostationary CRS,
                and needs no credentials.

        Returns:
            A single channel's ``Dataset``, or a ``dict[str, Dataset]`` when several channels were
            requested.

        Raises:
            ValueError: No channel was given (via ``bands`` or ``options``, counting an empty
                ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
                given; ``bands`` is not a list of channel names (a string, bytes, mapping, or other
                non-sequence); the source resolved to no chunk files; ``options`` is a bare string
                or carries an item that is not ``"KEY=VALUE"``; ``calibrate`` is a string that
                is not a recognised boolean spelling (see
                :func:`~pyramids_eo.drivers._base.coerce_booleans`); or
                ``sun_earth_distance`` is a string that is not a number (see
                :func:`~pyramids_eo.drivers._base.coerce_floats`) — which would otherwise have
                surfaced as a bare ``TypeError`` out of the calibration arithmetic.
            ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_fci_l1c` — no
                chunk carries the requested channel, or the chunks are inconsistent.
            CalibrationError: Propagated when ``calibrate`` is on and a channel lacks the
                constants its radiometric kind needs.

        Note:
            A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
            driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
            ``TypeError`` from pyramids' plugin layer. Use the reader function
            (``read_fci_l1c(..., channels=[...])``) for several channels at once. This is shared
            with the other channel-at-a-time drivers.
        """
        from pyramids_eo.sensors.readers import read_fci_l1c

        settings = options_as_dict(options)
        coerce_booleans(settings, ("calibrate",), driver="fci")
        coerce_floats(settings, ("sun_earth_distance",), driver="fci")
        channel = settings.pop("channel", None)
        channels = settings.pop("channels", None)
        if channel is not None and channels is not None:
            raise ValueError(
                "pass either a single channel or a channels list, not both."
            )
        if channel is None and channels is None and bands is not None:
            channel, channels = bands_to_channels(bands, example="ir_105")
        if isinstance(channels, (list, tuple)) and len(channels) == 0:
            channels = None  # an empty channels list names no channel
        if channel is None and channels is None:
            raise ValueError(
                "an FCI read needs a channel: pass bands=['ir_105'], "
                "open_options={'channel': 'ir_105'}."
            )
        paths = expand_sources(_strip_scheme(str(source)), pattern="*.nc")
        if not paths:
            raise ValueError(
                f"no chunk files found for FCI source {source!r}; expected a directory, glob, or "
                "fci:// path resolving to one or more .nc chunks."
            )
        return read_fci_l1c(paths, channel=channel, channels=channels, **settings)
can_open(source) classmethod #

Return whether source names a real FCI L1C FDHSI chunk set.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified) — an fci:// path, a directory, or a glob string.

required

Returns:

Type Description
bool

True for an fci:// source, a directory containing at least one *FDHSI*.nc

bool

chunk, or a glob whose matches include one; False for an empty source. It does a

bool

bounded, non-recursive directory listing / glob (no file open, no network) — more than

bool

the string-only can_open of the other drivers, but it runs only when GDAL has

bool

already failed to open the source, a very broad user glob (e.g. **) is the caller's

bool

cost, and a filesystem error (e.g. an unreadable directory) is swallowed to False so

bool

the method never raises. driver="fci" bypasses this, so a non-standard chunk set can

bool

still be read explicitly.

Examples:

  • An fci:// source is always claimed (a cheap string check):
    >>> from pyramids_eo.drivers.fci import FciDriver
    >>> FciDriver.can_open("fci://MTG_FCI_granule")
    True
    
  • A non-string source is never claimed:
    >>> FciDriver.can_open(42)
    False
    
Source code in src/pyramids_eo/drivers/fci.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` names a real FCI L1C FDHSI chunk set.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified) — an ``fci://`` path,
            a directory, or a glob string.

    Returns:
        True for an ``fci://`` source, a directory containing at least one ``*FDHSI*.nc``
        chunk, or a glob whose matches include one; False for an empty source. It does a
        bounded, non-recursive directory listing / glob (no file open, no network) — more than
        the string-only ``can_open`` of the other drivers, but it runs only when GDAL has
        already failed to open the source, a very broad user glob (e.g. ``**``) is the caller's
        cost, and a filesystem error (e.g. an unreadable directory) is swallowed to False so
        the method never raises. ``driver="fci"`` bypasses this, so a non-standard chunk set can
        still be read explicitly.

    Examples:
        - An ``fci://`` source is always claimed (a cheap string check):
            ```python
            >>> from pyramids_eo.drivers.fci import FciDriver
            >>> FciDriver.can_open("fci://MTG_FCI_granule")
            True

            ```
        - A non-string source is never claimed:
            ```python
            >>> FciDriver.can_open(42)
            False

            ```
    """
    if not isinstance(source, str) or not source:
        return False
    if source.lower().startswith(_SCHEME):
        return True
    # Resolve an existing path literally first, so a real granule directory whose own name
    # contains a glob metacharacter (e.g. ``granule[1]``) is stat-checked, not treated as a
    # pattern. Only a non-existent source is interpreted as a glob. The filesystem probes are
    # wrapped so can_open honours its contract of never raising (an unreadable dir -> False).
    try:
        path = Path(source)
        if path.is_dir():
            return any(path.glob(_FDHSI_GLOB))
        if path.exists():
            return False
        if any(character in source for character in "*?["):
            return any(
                "fdhsi" in Path(match).name.lower() for match in glob(source)
            )
    except (OSError, ValueError):
        return False
    return False
read(source, *, bands=None, options=None, **_ignored) #

Read one or more FCI L1C channels into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

A directory of FDHSI .nc chunks, a glob matching them, a single chunk, or any of those prefixed fci://.

required
bands Any

The channel(s) to read — one name for a single-channel Dataset, several for a dict[str, Dataset]. A direct-call convenience only: Dataset.read_file forwards just options to a driver, so through read_file the channel must come from options={"channel": …} / options={"channels": [...]}, and a channel/channels in options takes precedence over bands.

None
options Any

Extra :func:~pyramids_eo.sensors.readers.read_fci_l1c keywords — channel / channels, calibrate, sun_earth_distance, cos_sza — as a dict or KEY=VALUE list.

None
**_ignored Any

Any other generic driver-read parameter (bbox / crs / auth), accepted and ignored — a granule is read whole, carries its own geostationary CRS, and needs no credentials.

{}

Returns:

Type Description
Dataset | dict[str, Dataset]

A single channel's Dataset, or a dict[str, Dataset] when several channels were

Dataset | dict[str, Dataset]

requested.

Raises:

Type Description
ValueError

No channel was given (via bands or options, counting an empty channels list as none); both a single channel and a channels list were given; bands is not a list of channel names (a string, bytes, mapping, or other non-sequence); the source resolved to no chunk files; options is a bare string or carries an item that is not "KEY=VALUE"; calibrate is a string that is not a recognised boolean spelling (see :func:~pyramids_eo.drivers._base.coerce_booleans); or sun_earth_distance is a string that is not a number (see :func:~pyramids_eo.drivers._base.coerce_floats) — which would otherwise have surfaced as a bare TypeError out of the calibration arithmetic.

ReaderError

Propagated from :func:~pyramids_eo.sensors.readers.read_fci_l1c — no chunk carries the requested channel, or the chunks are inconsistent.

CalibrationError

Propagated when calibrate is on and a channel lacks the constants its radiometric kind needs.

Note

A channel set is a direct-call feature only: Dataset.read_file requires a driver to return one Dataset, so an options={'channels': [...]} read raises TypeError from pyramids' plugin layer. Use the reader function (read_fci_l1c(..., channels=[...])) for several channels at once. This is shared with the other channel-at-a-time drivers.

Source code in src/pyramids_eo/drivers/fci.py
def read(
    self,
    source: Any,
    *,
    bands: Any = None,
    options: Any = None,
    **_ignored: Any,
) -> Dataset | dict[str, Dataset]:
    """Read one or more FCI L1C channels into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: A directory of FDHSI ``.nc`` chunks, a glob matching them, a single chunk, or
            any of those prefixed ``fci://``.
        bands: The channel(s) to read — one name for a single-channel ``Dataset``, several for
            a ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
            forwards just ``options`` to a driver, so through ``read_file`` the channel must
            come from ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
            ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
        options: Extra :func:`~pyramids_eo.sensors.readers.read_fci_l1c` keywords — ``channel``
            / ``channels``, ``calibrate``, ``sun_earth_distance``, ``cos_sza`` — as a dict or
            ``KEY=VALUE`` list.
        **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
            accepted and ignored — a granule is read whole, carries its own geostationary CRS,
            and needs no credentials.

    Returns:
        A single channel's ``Dataset``, or a ``dict[str, Dataset]`` when several channels were
        requested.

    Raises:
        ValueError: No channel was given (via ``bands`` or ``options``, counting an empty
            ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
            given; ``bands`` is not a list of channel names (a string, bytes, mapping, or other
            non-sequence); the source resolved to no chunk files; ``options`` is a bare string
            or carries an item that is not ``"KEY=VALUE"``; ``calibrate`` is a string that
            is not a recognised boolean spelling (see
            :func:`~pyramids_eo.drivers._base.coerce_booleans`); or
            ``sun_earth_distance`` is a string that is not a number (see
            :func:`~pyramids_eo.drivers._base.coerce_floats`) — which would otherwise have
            surfaced as a bare ``TypeError`` out of the calibration arithmetic.
        ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_fci_l1c` — no
            chunk carries the requested channel, or the chunks are inconsistent.
        CalibrationError: Propagated when ``calibrate`` is on and a channel lacks the
            constants its radiometric kind needs.

    Note:
        A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
        driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
        ``TypeError`` from pyramids' plugin layer. Use the reader function
        (``read_fci_l1c(..., channels=[...])``) for several channels at once. This is shared
        with the other channel-at-a-time drivers.
    """
    from pyramids_eo.sensors.readers import read_fci_l1c

    settings = options_as_dict(options)
    coerce_booleans(settings, ("calibrate",), driver="fci")
    coerce_floats(settings, ("sun_earth_distance",), driver="fci")
    channel = settings.pop("channel", None)
    channels = settings.pop("channels", None)
    if channel is not None and channels is not None:
        raise ValueError(
            "pass either a single channel or a channels list, not both."
        )
    if channel is None and channels is None and bands is not None:
        channel, channels = bands_to_channels(bands, example="ir_105")
    if isinstance(channels, (list, tuple)) and len(channels) == 0:
        channels = None  # an empty channels list names no channel
    if channel is None and channels is None:
        raise ValueError(
            "an FCI read needs a channel: pass bands=['ir_105'], "
            "open_options={'channel': 'ir_105'}."
        )
    paths = expand_sources(_strip_scheme(str(source)), pattern="*.nc")
    if not paths:
        raise ValueError(
            f"no chunk files found for FCI source {source!r}; expected a directory, glob, or "
            "fci:// path resolving to one or more .nc chunks."
        )
    return read_fci_l1c(paths, channel=channel, channels=channels, **settings)

OlciDriver #

Read one or more Sentinel-3 OLCI L1B radiance bands from a .SEN3 granule.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

(".sen3",) — a granule directory is named *.SEN3.

schemes tuple[str, ...]

("olci",) — an olci:// path names a granule explicitly, and distinguishes OLCI from SLSTR when both share the .SEN3 suffix.

capabilities

read only (one granule is one acquisition).

extra str | None

None — the reader is pure pyramids-eo over pyramids' bundled GDAL.

Source code in src/pyramids_eo/drivers/olci.py
class OlciDriver:
    """Read one or more Sentinel-3 OLCI L1B radiance bands from a ``.SEN3`` granule.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: ``(".sen3",)`` — a granule directory is named ``*.SEN3``.
        schemes: ``("olci",)`` — an ``olci://`` path names a granule explicitly, and distinguishes
            OLCI from SLSTR when both share the ``.SEN3`` suffix.
        capabilities: ``read`` only (one granule is one acquisition).
        extra: ``None`` — the reader is pure pyramids-eo over pyramids' bundled GDAL.
    """

    name = "olci"
    long_name = "Sentinel-3 OLCI L1B (.SEN3)"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = (".sen3",)
    schemes: tuple[str, ...] = ("olci",)
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` names a real OLCI L1B granule.

        A ``.SEN3`` directory alone is not enough to claim, because SLSTR granules share that
        suffix; the directory must actually hold an ``Oa*_radiance.nc`` band file.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified) — an ``olci://``
                path, a ``.SEN3`` directory, or a glob string.

        Returns:
            True for an ``olci://`` source, a directory containing at least one
            ``Oa*_radiance.nc``, or a glob whose matches include one; False otherwise. The
            directory listing short-circuits on the first match but enumerates the whole
            directory when nothing matches; it runs only once GDAL has failed to open the
            source, and any filesystem error is swallowed to False so the method never raises.
            ``driver="olci"`` bypasses this entirely.

        Examples:
            - An ``olci://`` source is always claimed (a cheap string check):
                ```python
                >>> from pyramids_eo.drivers.olci import OlciDriver
                >>> OlciDriver.can_open("olci://S3A_OL_1_EFR.SEN3")
                True

                ```
            - A non-string source is never claimed:
                ```python
                >>> OlciDriver.can_open(42)
                False

                ```
        """
        if not isinstance(source, str) or not source:
            return False
        if source.lower().startswith(_SCHEME):
            return True
        # Resolve an existing path literally first, so a real granule whose own name contains a
        # glob metacharacter is stat-checked rather than treated as a pattern. The probes are
        # wrapped so can_open honours its contract of never raising.
        try:
            path = Path(source)
            if path.is_dir():
                return any(path.glob(_RADIANCE_GLOB))
            if path.exists():
                return False
            if any(character in source for character in "*?["):
                return any(
                    Path(match).is_dir() and any(Path(match).glob(_RADIANCE_GLOB))
                    for match in glob(source)
                )
        except (OSError, ValueError):
            return False
        return False

    def read(
        self,
        source: Any,
        *,
        bands: Any = None,
        options: Any = None,
        **_ignored: Any,
    ) -> Dataset | dict[str, Dataset]:
        """Read one or more OLCI L1B bands into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: A ``.SEN3`` granule directory, or that path prefixed ``olci://``.
            bands: The band(s) to read — one name for a single-band ``Dataset``, several for a
                ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
                forwards just ``options``, so through ``read_file`` the band must come from
                ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
                ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
            options: Extra :func:`~pyramids_eo.sensors.readers.read_olci` keywords — ``channel``
                / ``channels`` and ``geolocation`` — as a dict or ``KEY=VALUE`` list.
            **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
                accepted and ignored — a granule is read whole, carries its own swath geolocation,
                and needs no credentials.

        Returns:
            A single band's ``Dataset``, or a ``dict[str, Dataset]`` when several were requested.

        Raises:
            ValueError: No band was given (via ``bands`` or ``options``, counting an empty
                ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
                given; ``bands`` is not a list of band names; ``options`` is a bare string or
                carries an item that is not ``"KEY=VALUE"``; or ``geolocation`` is a string that
                is not a recognised boolean spelling (see
                :func:`~pyramids_eo.drivers._base.coerce_booleans`).
            ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_olci` — the
                band is not an OLCI one, or the granule lacks it or its geolocation file.

        Note:
            A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
            driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
            ``TypeError`` from pyramids' plugin layer. Use the reader function
            (``read_olci(..., channels=[...])``) for several channels at once. This is shared
            with the other channel-at-a-time drivers.
        """
        from pyramids_eo.sensors.readers import read_olci

        settings = options_as_dict(options)
        coerce_booleans(settings, ("geolocation",), driver="olci")
        channel = settings.pop("channel", None)
        channels = settings.pop("channels", None)
        if channel is not None and channels is not None:
            raise ValueError(
                "pass either a single channel or a channels list, not both."
            )
        if channel is None and channels is None and bands is not None:
            channel, channels = bands_to_channels(bands, example="Oa08")
        if isinstance(channels, (list, tuple)) and len(channels) == 0:
            channels = None  # an empty channels list names no band
        if channel is None and channels is None:
            raise ValueError(
                "an OLCI read needs a band: pass bands=['Oa08'], "
                "open_options={'channel': 'Oa08'}."
            )
        return read_olci(
            _strip_scheme(str(source)), channel=channel, channels=channels, **settings
        )
can_open(source) classmethod #

Return whether source names a real OLCI L1B granule.

A .SEN3 directory alone is not enough to claim, because SLSTR granules share that suffix; the directory must actually hold an Oa*_radiance.nc band file.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified) — an olci:// path, a .SEN3 directory, or a glob string.

required

Returns:

Type Description
bool

True for an olci:// source, a directory containing at least one

bool

Oa*_radiance.nc, or a glob whose matches include one; False otherwise. The

bool

directory listing short-circuits on the first match but enumerates the whole

bool

directory when nothing matches; it runs only once GDAL has failed to open the

bool

source, and any filesystem error is swallowed to False so the method never raises.

bool

driver="olci" bypasses this entirely.

Examples:

  • An olci:// source is always claimed (a cheap string check):
    >>> from pyramids_eo.drivers.olci import OlciDriver
    >>> OlciDriver.can_open("olci://S3A_OL_1_EFR.SEN3")
    True
    
  • A non-string source is never claimed:
    >>> OlciDriver.can_open(42)
    False
    
Source code in src/pyramids_eo/drivers/olci.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` names a real OLCI L1B granule.

    A ``.SEN3`` directory alone is not enough to claim, because SLSTR granules share that
    suffix; the directory must actually hold an ``Oa*_radiance.nc`` band file.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified) — an ``olci://``
            path, a ``.SEN3`` directory, or a glob string.

    Returns:
        True for an ``olci://`` source, a directory containing at least one
        ``Oa*_radiance.nc``, or a glob whose matches include one; False otherwise. The
        directory listing short-circuits on the first match but enumerates the whole
        directory when nothing matches; it runs only once GDAL has failed to open the
        source, and any filesystem error is swallowed to False so the method never raises.
        ``driver="olci"`` bypasses this entirely.

    Examples:
        - An ``olci://`` source is always claimed (a cheap string check):
            ```python
            >>> from pyramids_eo.drivers.olci import OlciDriver
            >>> OlciDriver.can_open("olci://S3A_OL_1_EFR.SEN3")
            True

            ```
        - A non-string source is never claimed:
            ```python
            >>> OlciDriver.can_open(42)
            False

            ```
    """
    if not isinstance(source, str) or not source:
        return False
    if source.lower().startswith(_SCHEME):
        return True
    # Resolve an existing path literally first, so a real granule whose own name contains a
    # glob metacharacter is stat-checked rather than treated as a pattern. The probes are
    # wrapped so can_open honours its contract of never raising.
    try:
        path = Path(source)
        if path.is_dir():
            return any(path.glob(_RADIANCE_GLOB))
        if path.exists():
            return False
        if any(character in source for character in "*?["):
            return any(
                Path(match).is_dir() and any(Path(match).glob(_RADIANCE_GLOB))
                for match in glob(source)
            )
    except (OSError, ValueError):
        return False
    return False
read(source, *, bands=None, options=None, **_ignored) #

Read one or more OLCI L1B bands into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

A .SEN3 granule directory, or that path prefixed olci://.

required
bands Any

The band(s) to read — one name for a single-band Dataset, several for a dict[str, Dataset]. A direct-call convenience only: Dataset.read_file forwards just options, so through read_file the band must come from options={"channel": …} / options={"channels": [...]}, and a channel/channels in options takes precedence over bands.

None
options Any

Extra :func:~pyramids_eo.sensors.readers.read_olci keywords — channel / channels and geolocation — as a dict or KEY=VALUE list.

None
**_ignored Any

Any other generic driver-read parameter (bbox / crs / auth), accepted and ignored — a granule is read whole, carries its own swath geolocation, and needs no credentials.

{}

Returns:

Type Description
Dataset | dict[str, Dataset]

A single band's Dataset, or a dict[str, Dataset] when several were requested.

Raises:

Type Description
ValueError

No band was given (via bands or options, counting an empty channels list as none); both a single channel and a channels list were given; bands is not a list of band names; options is a bare string or carries an item that is not "KEY=VALUE"; or geolocation is a string that is not a recognised boolean spelling (see :func:~pyramids_eo.drivers._base.coerce_booleans).

ReaderError

Propagated from :func:~pyramids_eo.sensors.readers.read_olci — the band is not an OLCI one, or the granule lacks it or its geolocation file.

Note

A channel set is a direct-call feature only: Dataset.read_file requires a driver to return one Dataset, so an options={'channels': [...]} read raises TypeError from pyramids' plugin layer. Use the reader function (read_olci(..., channels=[...])) for several channels at once. This is shared with the other channel-at-a-time drivers.

Source code in src/pyramids_eo/drivers/olci.py
def read(
    self,
    source: Any,
    *,
    bands: Any = None,
    options: Any = None,
    **_ignored: Any,
) -> Dataset | dict[str, Dataset]:
    """Read one or more OLCI L1B bands into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: A ``.SEN3`` granule directory, or that path prefixed ``olci://``.
        bands: The band(s) to read — one name for a single-band ``Dataset``, several for a
            ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
            forwards just ``options``, so through ``read_file`` the band must come from
            ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
            ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
        options: Extra :func:`~pyramids_eo.sensors.readers.read_olci` keywords — ``channel``
            / ``channels`` and ``geolocation`` — as a dict or ``KEY=VALUE`` list.
        **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
            accepted and ignored — a granule is read whole, carries its own swath geolocation,
            and needs no credentials.

    Returns:
        A single band's ``Dataset``, or a ``dict[str, Dataset]`` when several were requested.

    Raises:
        ValueError: No band was given (via ``bands`` or ``options``, counting an empty
            ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
            given; ``bands`` is not a list of band names; ``options`` is a bare string or
            carries an item that is not ``"KEY=VALUE"``; or ``geolocation`` is a string that
            is not a recognised boolean spelling (see
            :func:`~pyramids_eo.drivers._base.coerce_booleans`).
        ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_olci` — the
            band is not an OLCI one, or the granule lacks it or its geolocation file.

    Note:
        A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
        driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
        ``TypeError`` from pyramids' plugin layer. Use the reader function
        (``read_olci(..., channels=[...])``) for several channels at once. This is shared
        with the other channel-at-a-time drivers.
    """
    from pyramids_eo.sensors.readers import read_olci

    settings = options_as_dict(options)
    coerce_booleans(settings, ("geolocation",), driver="olci")
    channel = settings.pop("channel", None)
    channels = settings.pop("channels", None)
    if channel is not None and channels is not None:
        raise ValueError(
            "pass either a single channel or a channels list, not both."
        )
    if channel is None and channels is None and bands is not None:
        channel, channels = bands_to_channels(bands, example="Oa08")
    if isinstance(channels, (list, tuple)) and len(channels) == 0:
        channels = None  # an empty channels list names no band
    if channel is None and channels is None:
        raise ValueError(
            "an OLCI read needs a band: pass bands=['Oa08'], "
            "open_options={'channel': 'Oa08'}."
        )
    return read_olci(
        _strip_scheme(str(source)), channel=channel, channels=channels, **settings
    )

Sentinel2Driver #

Read a Sentinel-2 .SAFE product into a :class:~pyramids.dataset.Dataset.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

(".safe", ".safe.zip") — the two spellings a Sentinel-2 product comes in. Declaration only, and the second entry is descriptive rather than functional: pyramids matches a source's final suffix, so a zipped product presents as .zip and never as .safe.zip. Routing is decided by :meth:can_open, and the pre-emption by preempts.

schemes tuple[str, ...]

Empty — a .SAFE is a local product.

preempts tuple[str, ...]

(".zip",) — a zipped product is tried before GDAL, which would otherwise open the archive and hand back an empty container. ".safe.zip" is not usable here (pyramids matches the final suffix, so a zipped product presents as .zip), and the bare ".zip" is safe because can_open gates every claim — an ordinary archive, and a zipped Sentinel-1 product, are both left to GDAL. ".safe" is not declared: GDAL cannot open a product directory, so the fallback already serves it.

capabilities

read only (one product is one timestep; a time series goes through :func:pyramids_eo.collection_from_sentinel2).

extra str | None

None — the reader is pure pyramids-eo over pyramids' bundled GDAL, with no optional backend to gate on.

Source code in src/pyramids_eo/drivers/sentinel2.py
class Sentinel2Driver:
    """Read a Sentinel-2 ``.SAFE`` product into a :class:`~pyramids.dataset.Dataset`.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: ``(".safe", ".safe.zip")`` — the two spellings a Sentinel-2 product comes in.
            Declaration only, and the second entry is descriptive rather than functional:
            pyramids matches a source's **final** suffix, so a zipped product presents as
            ``.zip`` and never as ``.safe.zip``. Routing is decided by :meth:`can_open`, and the
            pre-emption by ``preempts``.
        schemes: Empty — a ``.SAFE`` is a local product.
        preempts: ``(".zip",)`` — a zipped product is tried *before* GDAL, which would otherwise
            open the archive and hand back an empty container. ``".safe.zip"`` is not usable here
            (pyramids matches the final suffix, so a zipped product presents as ``.zip``), and the
            bare ``".zip"`` is safe because ``can_open`` gates every claim — an ordinary archive,
            and a zipped Sentinel-1 product, are both left to GDAL. ``".safe"`` is not declared:
            GDAL cannot open a product directory, so the fallback already serves it.
        capabilities: ``read`` only (one product is one timestep; a time series goes through
            :func:`pyramids_eo.collection_from_sentinel2`).
        extra: ``None`` — the reader is pure pyramids-eo over pyramids' bundled GDAL, with no
            optional backend to gate on.
    """

    name = "s2"
    long_name = "Sentinel-2 (.SAFE)"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = (".safe", ".safe.zip")
    schemes: tuple[str, ...] = ()
    #: Tried before GDAL for a zipped product; see the class docstring for why the bare
    #: ``.zip`` is safe and why ``.safe`` is absent.
    preempts: tuple[str, ...] = (".zip",)
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` is a Sentinel-2 ``.SAFE`` product.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified) — a product
                directory or a lowercase ``*.SAFE.zip`` archive, both local.

        Returns:
            True for a source this driver should read, which differs by form because the two
            forms reach it by different routes.

            A **zipped** product is pre-empted *before* GDAL, so the claim has to be exact: the
            extension must be a lowercase ``.zip`` (what the archive reader accepts), and the
            archive must hold Sentinel-2 metadata (:data:`_S2_MARKERS`) at the product root.
            ESA shares ``.SAFE.zip`` with Sentinel-1, which GDAL reads itself, so a name alone
            must never win the claim.

            A **directory** is only reached through the post-GDAL fallback, where GDAL has
            already declined the source, so any ``.SAFE`` directory is claimed — no marker check,
            which would otherwise turn away a product whose root metadata is a bare
            ``manifest.safe``.

            In both forms a ``manifest.safe`` *as the source* is refused: it is the file inside a
            product and Sentinel-1's entry point. A **plain local** path that does not exist is
            claimed so the reader can report it, but a URL, a GDAL ``/vsi*`` path or a UNC share
            never is — this driver cannot read one and GDAL often can.

        Note:
            This is no longer free of I/O: identifying the mission requires reading a directory
            listing or a zip's central directory. Pre-emption consults only drivers whose
            ``preempts`` matches the source's suffix, but the post-GDAL fallback
            (``select_driver``) asks **every** registered driver, with no suffix filter — so this
            runs for any source GDAL failed to open. The cheap string tests come first and return
            before any I/O, so the filesystem is touched only for a source actually spelled
            ``*.SAFE`` or ``*.SAFE.zip``.

        Examples:
            - A plain raster, a bare archive and a manifest are all rejected without I/O:
                ```python
                >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
                >>> Sentinel2Driver.can_open("scene.tif")
                False
                >>> Sentinel2Driver.can_open("archive.zip")
                False
                >>> Sentinel2Driver.can_open("S2A_MSIL2A.SAFE/manifest.safe")
                False

                ```
            - A `.SAFE` path that is not on disk is claimed, so the reader reports the problem:
                ```python
                >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
                >>> Sentinel2Driver.can_open("no_such_product.SAFE")
                True

                ```
        """
        if not isinstance(source, str):
            return False
        trimmed = source.rstrip("/\\")
        lowered = trimmed.lower()
        base = lowered.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
        if base == "manifest.safe":
            return False
        if lowered.endswith(".safe.zip"):
            # Only a lowercase `.zip` is claimed: the archive reader infers the kind from the
            # extension and rejects `.ZIP`, so claiming one would route a read it cannot serve.
            if not trimmed.endswith(".zip"):
                return False
            if not os.path.exists(trimmed):
                # Nothing to inspect. Only shortcut a plain local path, where the reader
                # gives a better "no such product" message than GDAL. A URL, `/vsi*` or
                # UNC source is left to GDAL: this driver cannot read it, and claiming it
                # would pre-empt GDAL out of a read it can serve.
                return _is_plain_local_path(trimmed)
            try:
                with zipfile.ZipFile(trimmed) as archive:
                    return _holds_s2_metadata(archive.namelist())
            except (OSError, zipfile.BadZipFile, ValueError):
                return False
        if not lowered.endswith(".safe"):
            return False
        # A directory claim is NOT gated on the metadata markers. This branch is only
        # ever reached through the post-GDAL fallback — ``.safe`` is not in ``preempts``
        # — and GDAL reads a Sentinel-1 ``.SAFE`` directory itself, so by the time this
        # runs GDAL has already declined the source. Requiring a marker here only turned
        # away products whose root metadata is a bare ``manifest.safe``, which
        # ``from_sentinel2`` reads perfectly well, while buying no mission
        # discrimination that GDAL has not already provided.
        try:
            if not os.path.isdir(trimmed):
                # Not a directory on disk. A plain local path that is simply absent is
                # claimed so the reader reports it; anything remote or virtual is left to
                # GDAL, and an existing non-directory is not a product.
                return not os.path.exists(trimmed) and _is_plain_local_path(trimmed)
            return True
        except OSError:
            return False

    def read(
        self,
        source: Any,
        *,
        bbox: Any = None,
        bands: Any = None,
        crs: Any = None,
        options: Any = None,
        auth: Any = None,
        **_ignored: Any,
    ) -> Dataset:
        """Read a Sentinel-2 product into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: Path to a ``.SAFE`` product directory.
            bbox: Optional AOI ``(min_x, min_y, max_x, max_y)``.
            bands: Optional band subset (e.g. ``["B04", "B03", "B02"]``).
            crs: Optional target CRS.
            options: Extra :func:`~pyramids_eo.from_sentinel2` keywords (e.g. ``resolution``,
                ``epsg``, ``reflectance``, ``mask_scl``, ``resample``) as a dict or ``KEY=VALUE``
                list. Because ``Dataset.read_file`` forwards only ``options`` to a driver,
                ``bbox`` / ``bands`` / ``crs`` may also be given here; a non-``None`` explicit
                keyword wins over the same key in ``options``, and each is consumed so it cannot
                collide. A ``KEY=VALUE`` list keeps every value a **string**, so an option that the
                reader needs typed — ``resolution`` / ``epsg`` as ``int`` — must be passed in the
                dict form (``{"resolution": 10}``), not as ``["resolution=10"]``.
            auth: Ignored — a local ``.SAFE`` needs no credentials.
            **_ignored: Any other generic driver-read parameter, accepted and ignored.

        Returns:
            The read Sentinel-2 dataset.
        """
        from pyramids_eo import from_sentinel2

        settings = options_as_dict(options)
        opt_bbox = settings.pop("bbox", None)
        opt_bands = settings.pop("bands", None)
        opt_crs = settings.pop("crs", None)
        settings.pop("auth", None)
        bbox = bbox if bbox is not None else opt_bbox
        bands = bands if bands is not None else opt_bands
        crs = crs if crs is not None else opt_crs
        return from_sentinel2(str(source), bands=bands, bbox=bbox, crs=crs, **settings)
can_open(source) classmethod #

Return whether source is a Sentinel-2 .SAFE product.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified) — a product directory or a lowercase *.SAFE.zip archive, both local.

required

Returns:

Type Description
bool

True for a source this driver should read, which differs by form because the two

bool

forms reach it by different routes.

bool

A zipped product is pre-empted before GDAL, so the claim has to be exact: the

bool

extension must be a lowercase .zip (what the archive reader accepts), and the

bool

archive must hold Sentinel-2 metadata (:data:_S2_MARKERS) at the product root.

bool

ESA shares .SAFE.zip with Sentinel-1, which GDAL reads itself, so a name alone

bool

must never win the claim.

bool

A directory is only reached through the post-GDAL fallback, where GDAL has

bool

already declined the source, so any .SAFE directory is claimed — no marker check,

bool

which would otherwise turn away a product whose root metadata is a bare

bool

manifest.safe.

bool

In both forms a manifest.safe as the source is refused: it is the file inside a

bool

product and Sentinel-1's entry point. A plain local path that does not exist is

bool

claimed so the reader can report it, but a URL, a GDAL /vsi* path or a UNC share

bool

never is — this driver cannot read one and GDAL often can.

Note

This is no longer free of I/O: identifying the mission requires reading a directory listing or a zip's central directory. Pre-emption consults only drivers whose preempts matches the source's suffix, but the post-GDAL fallback (select_driver) asks every registered driver, with no suffix filter — so this runs for any source GDAL failed to open. The cheap string tests come first and return before any I/O, so the filesystem is touched only for a source actually spelled *.SAFE or *.SAFE.zip.

Examples:

  • A plain raster, a bare archive and a manifest are all rejected without I/O:
    >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
    >>> Sentinel2Driver.can_open("scene.tif")
    False
    >>> Sentinel2Driver.can_open("archive.zip")
    False
    >>> Sentinel2Driver.can_open("S2A_MSIL2A.SAFE/manifest.safe")
    False
    
  • A .SAFE path that is not on disk is claimed, so the reader reports the problem:
    >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
    >>> Sentinel2Driver.can_open("no_such_product.SAFE")
    True
    
Source code in src/pyramids_eo/drivers/sentinel2.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` is a Sentinel-2 ``.SAFE`` product.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified) — a product
            directory or a lowercase ``*.SAFE.zip`` archive, both local.

    Returns:
        True for a source this driver should read, which differs by form because the two
        forms reach it by different routes.

        A **zipped** product is pre-empted *before* GDAL, so the claim has to be exact: the
        extension must be a lowercase ``.zip`` (what the archive reader accepts), and the
        archive must hold Sentinel-2 metadata (:data:`_S2_MARKERS`) at the product root.
        ESA shares ``.SAFE.zip`` with Sentinel-1, which GDAL reads itself, so a name alone
        must never win the claim.

        A **directory** is only reached through the post-GDAL fallback, where GDAL has
        already declined the source, so any ``.SAFE`` directory is claimed — no marker check,
        which would otherwise turn away a product whose root metadata is a bare
        ``manifest.safe``.

        In both forms a ``manifest.safe`` *as the source* is refused: it is the file inside a
        product and Sentinel-1's entry point. A **plain local** path that does not exist is
        claimed so the reader can report it, but a URL, a GDAL ``/vsi*`` path or a UNC share
        never is — this driver cannot read one and GDAL often can.

    Note:
        This is no longer free of I/O: identifying the mission requires reading a directory
        listing or a zip's central directory. Pre-emption consults only drivers whose
        ``preempts`` matches the source's suffix, but the post-GDAL fallback
        (``select_driver``) asks **every** registered driver, with no suffix filter — so this
        runs for any source GDAL failed to open. The cheap string tests come first and return
        before any I/O, so the filesystem is touched only for a source actually spelled
        ``*.SAFE`` or ``*.SAFE.zip``.

    Examples:
        - A plain raster, a bare archive and a manifest are all rejected without I/O:
            ```python
            >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
            >>> Sentinel2Driver.can_open("scene.tif")
            False
            >>> Sentinel2Driver.can_open("archive.zip")
            False
            >>> Sentinel2Driver.can_open("S2A_MSIL2A.SAFE/manifest.safe")
            False

            ```
        - A `.SAFE` path that is not on disk is claimed, so the reader reports the problem:
            ```python
            >>> from pyramids_eo.drivers.sentinel2 import Sentinel2Driver
            >>> Sentinel2Driver.can_open("no_such_product.SAFE")
            True

            ```
    """
    if not isinstance(source, str):
        return False
    trimmed = source.rstrip("/\\")
    lowered = trimmed.lower()
    base = lowered.rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
    if base == "manifest.safe":
        return False
    if lowered.endswith(".safe.zip"):
        # Only a lowercase `.zip` is claimed: the archive reader infers the kind from the
        # extension and rejects `.ZIP`, so claiming one would route a read it cannot serve.
        if not trimmed.endswith(".zip"):
            return False
        if not os.path.exists(trimmed):
            # Nothing to inspect. Only shortcut a plain local path, where the reader
            # gives a better "no such product" message than GDAL. A URL, `/vsi*` or
            # UNC source is left to GDAL: this driver cannot read it, and claiming it
            # would pre-empt GDAL out of a read it can serve.
            return _is_plain_local_path(trimmed)
        try:
            with zipfile.ZipFile(trimmed) as archive:
                return _holds_s2_metadata(archive.namelist())
        except (OSError, zipfile.BadZipFile, ValueError):
            return False
    if not lowered.endswith(".safe"):
        return False
    # A directory claim is NOT gated on the metadata markers. This branch is only
    # ever reached through the post-GDAL fallback — ``.safe`` is not in ``preempts``
    # — and GDAL reads a Sentinel-1 ``.SAFE`` directory itself, so by the time this
    # runs GDAL has already declined the source. Requiring a marker here only turned
    # away products whose root metadata is a bare ``manifest.safe``, which
    # ``from_sentinel2`` reads perfectly well, while buying no mission
    # discrimination that GDAL has not already provided.
    try:
        if not os.path.isdir(trimmed):
            # Not a directory on disk. A plain local path that is simply absent is
            # claimed so the reader reports it; anything remote or virtual is left to
            # GDAL, and an existing non-directory is not a product.
            return not os.path.exists(trimmed) and _is_plain_local_path(trimmed)
        return True
    except OSError:
        return False
read(source, *, bbox=None, bands=None, crs=None, options=None, auth=None, **_ignored) #

Read a Sentinel-2 product into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

Path to a .SAFE product directory.

required
bbox Any

Optional AOI (min_x, min_y, max_x, max_y).

None
bands Any

Optional band subset (e.g. ["B04", "B03", "B02"]).

None
crs Any

Optional target CRS.

None
options Any

Extra :func:~pyramids_eo.from_sentinel2 keywords (e.g. resolution, epsg, reflectance, mask_scl, resample) as a dict or KEY=VALUE list. Because Dataset.read_file forwards only options to a driver, bbox / bands / crs may also be given here; a non-None explicit keyword wins over the same key in options, and each is consumed so it cannot collide. A KEY=VALUE list keeps every value a string, so an option that the reader needs typed — resolution / epsg as int — must be passed in the dict form ({"resolution": 10}), not as ["resolution=10"].

None
auth Any

Ignored — a local .SAFE needs no credentials.

None
**_ignored Any

Any other generic driver-read parameter, accepted and ignored.

{}

Returns:

Type Description
Dataset

The read Sentinel-2 dataset.

Source code in src/pyramids_eo/drivers/sentinel2.py
def read(
    self,
    source: Any,
    *,
    bbox: Any = None,
    bands: Any = None,
    crs: Any = None,
    options: Any = None,
    auth: Any = None,
    **_ignored: Any,
) -> Dataset:
    """Read a Sentinel-2 product into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: Path to a ``.SAFE`` product directory.
        bbox: Optional AOI ``(min_x, min_y, max_x, max_y)``.
        bands: Optional band subset (e.g. ``["B04", "B03", "B02"]``).
        crs: Optional target CRS.
        options: Extra :func:`~pyramids_eo.from_sentinel2` keywords (e.g. ``resolution``,
            ``epsg``, ``reflectance``, ``mask_scl``, ``resample``) as a dict or ``KEY=VALUE``
            list. Because ``Dataset.read_file`` forwards only ``options`` to a driver,
            ``bbox`` / ``bands`` / ``crs`` may also be given here; a non-``None`` explicit
            keyword wins over the same key in ``options``, and each is consumed so it cannot
            collide. A ``KEY=VALUE`` list keeps every value a **string**, so an option that the
            reader needs typed — ``resolution`` / ``epsg`` as ``int`` — must be passed in the
            dict form (``{"resolution": 10}``), not as ``["resolution=10"]``.
        auth: Ignored — a local ``.SAFE`` needs no credentials.
        **_ignored: Any other generic driver-read parameter, accepted and ignored.

    Returns:
        The read Sentinel-2 dataset.
    """
    from pyramids_eo import from_sentinel2

    settings = options_as_dict(options)
    opt_bbox = settings.pop("bbox", None)
    opt_bands = settings.pop("bands", None)
    opt_crs = settings.pop("crs", None)
    settings.pop("auth", None)
    bbox = bbox if bbox is not None else opt_bbox
    bands = bands if bands is not None else opt_bands
    crs = crs if crs is not None else opt_crs
    return from_sentinel2(str(source), bands=bands, bbox=bbox, crs=crs, **settings)

SeviriDriver #

Read one MSG SEVIRI channel from a native .nat granule.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

(".nat",) — the driver claims SEVIRI native granules by extension.

schemes tuple[str, ...]

Empty — a .nat granule is a local file.

capabilities

read only (a single granule is one timestep).

extra str | None

None — the .nat decoder is injected via parse=, so there is no hard backend to gate on.

Source code in src/pyramids_eo/drivers/seviri.py
class SeviriDriver:
    """Read one MSG SEVIRI channel from a native ``.nat`` granule.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: ``(".nat",)`` — the driver claims SEVIRI native granules by extension.
        schemes: Empty — a ``.nat`` granule is a local file.
        capabilities: ``read`` only (a single granule is one timestep).
        extra: ``None`` — the ``.nat`` decoder is injected via ``parse=``, so there is no hard
            backend to gate on.
    """

    name = "seviri"
    long_name = "MSG SEVIRI native (.nat)"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = (".nat",)
    schemes: tuple[str, ...] = ()
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` is a SEVIRI native ``.nat`` granule.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified).

        Returns:
            True for a string ending ``.nat`` (case-insensitive), else False. Cheap: no import,
            no network, no file access — ``.nat`` is the shared EUMETSAT Native extension, so a
            non-SEVIRI native file also answers True and fails later in ``read_seviri`` (see the
            module docstring), which is preferred over opening the file here.

        Examples:
            - A ``.nat`` granule is claimed; other suffixes are not:
                ```python
                >>> from pyramids_eo.drivers.seviri import SeviriDriver
                >>> SeviriDriver.can_open("MSG_SEVIRI.nat")
                True
                >>> SeviriDriver.can_open("scene.tif")
                False

                ```
        """
        return isinstance(source, str) and source.lower().endswith(".nat")

    def read(
        self,
        source: Any,
        *,
        bands: Any = None,
        options: Any = None,
        **_ignored: Any,
    ) -> Dataset:
        """Read one SEVIRI channel into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: Path to a SEVIRI native ``.nat`` granule.
            bands: The channel to read, as a one-element list (e.g. ``["IR_108"]``); an
                alternative to ``options={"channel": …}``. A SEVIRI read is a single channel, so
                more than one band is rejected rather than silently truncated.
            options: Extra :func:`~pyramids_eo.sensors.readers.read_seviri` keywords —
                ``channel``, ``parse`` (the ``.nat`` decoder), ``calibrate``, ``coeffs``, … — as
                a dict or ``KEY=VALUE`` list. ``read_file`` normalises options to the
                ``KEY=VALUE`` form, so ``calibrate`` and the two numeric keywords are coerced
                from their string spellings (see
                :func:`~pyramids_eo.drivers._base.coerce_booleans`); without that, the truthy
                string ``"false"`` would switch calibration *on*.
            **_ignored: The generic driver-read parameters a SEVIRI read does not use — ``bbox``,
                ``crs``, ``auth`` and any future one — are accepted and ignored: a granule is read
                whole, carries its own geostationary CRS, and needs no credentials.

        Returns:
            The calibrated, geolocated channel.

        Raises:
            ValueError: No channel was given (via ``bands`` or ``options``), more than one
                band was given, or a boolean / numeric option could not be read from its
                ``KEY=VALUE`` string spelling (``calibrate``, ``sun_earth_distance``,
                ``subsatellite_longitude``).
        """
        from pyramids_eo.sensors.readers import read_seviri

        settings = options_as_dict(options)
        coerce_booleans(settings, ("calibrate",), driver="seviri")
        coerce_floats(
            settings, ("sun_earth_distance", "subsatellite_longitude"), driver="seviri"
        )
        channel = settings.pop("channel", None)
        if channel is None and bands:
            if isinstance(bands, (str, bytes)):
                raise ValueError(
                    f"bands must be a list of channel names, not a bare "
                    f"{type(bands).__name__} ({bands!r}); pass bands=['IR_108']."
                )
            bands = list(bands)  # materialise a generator/iterator so len() is safe
            if len(bands) != 1:
                raise ValueError(
                    f"a SEVIRI read is one channel, but {len(bands)} bands were given "
                    f"({bands}); pass a single band or options={{'channel': 'IR_108'}}."
                )
            channel = bands[0]
        if channel is None:
            raise ValueError(
                "a SEVIRI read needs a channel: pass bands=['IR_108'] or "
                "open_options={'channel': 'IR_108'}."
            )
        return read_seviri(source, channel, **settings)
can_open(source) classmethod #

Return whether source is a SEVIRI native .nat granule.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified).

required

Returns:

Type Description
bool

True for a string ending .nat (case-insensitive), else False. Cheap: no import,

bool

no network, no file access — .nat is the shared EUMETSAT Native extension, so a

bool

non-SEVIRI native file also answers True and fails later in read_seviri (see the

bool

module docstring), which is preferred over opening the file here.

Examples:

  • A .nat granule is claimed; other suffixes are not:
    >>> from pyramids_eo.drivers.seviri import SeviriDriver
    >>> SeviriDriver.can_open("MSG_SEVIRI.nat")
    True
    >>> SeviriDriver.can_open("scene.tif")
    False
    
Source code in src/pyramids_eo/drivers/seviri.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` is a SEVIRI native ``.nat`` granule.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified).

    Returns:
        True for a string ending ``.nat`` (case-insensitive), else False. Cheap: no import,
        no network, no file access — ``.nat`` is the shared EUMETSAT Native extension, so a
        non-SEVIRI native file also answers True and fails later in ``read_seviri`` (see the
        module docstring), which is preferred over opening the file here.

    Examples:
        - A ``.nat`` granule is claimed; other suffixes are not:
            ```python
            >>> from pyramids_eo.drivers.seviri import SeviriDriver
            >>> SeviriDriver.can_open("MSG_SEVIRI.nat")
            True
            >>> SeviriDriver.can_open("scene.tif")
            False

            ```
    """
    return isinstance(source, str) and source.lower().endswith(".nat")
read(source, *, bands=None, options=None, **_ignored) #

Read one SEVIRI channel into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

Path to a SEVIRI native .nat granule.

required
bands Any

The channel to read, as a one-element list (e.g. ["IR_108"]); an alternative to options={"channel": …}. A SEVIRI read is a single channel, so more than one band is rejected rather than silently truncated.

None
options Any

Extra :func:~pyramids_eo.sensors.readers.read_seviri keywords — channel, parse (the .nat decoder), calibrate, coeffs, … — as a dict or KEY=VALUE list. read_file normalises options to the KEY=VALUE form, so calibrate and the two numeric keywords are coerced from their string spellings (see :func:~pyramids_eo.drivers._base.coerce_booleans); without that, the truthy string "false" would switch calibration on.

None
**_ignored Any

The generic driver-read parameters a SEVIRI read does not use — bbox, crs, auth and any future one — are accepted and ignored: a granule is read whole, carries its own geostationary CRS, and needs no credentials.

{}

Returns:

Type Description
Dataset

The calibrated, geolocated channel.

Raises:

Type Description
ValueError

No channel was given (via bands or options), more than one band was given, or a boolean / numeric option could not be read from its KEY=VALUE string spelling (calibrate, sun_earth_distance, subsatellite_longitude).

Source code in src/pyramids_eo/drivers/seviri.py
def read(
    self,
    source: Any,
    *,
    bands: Any = None,
    options: Any = None,
    **_ignored: Any,
) -> Dataset:
    """Read one SEVIRI channel into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: Path to a SEVIRI native ``.nat`` granule.
        bands: The channel to read, as a one-element list (e.g. ``["IR_108"]``); an
            alternative to ``options={"channel": …}``. A SEVIRI read is a single channel, so
            more than one band is rejected rather than silently truncated.
        options: Extra :func:`~pyramids_eo.sensors.readers.read_seviri` keywords —
            ``channel``, ``parse`` (the ``.nat`` decoder), ``calibrate``, ``coeffs``, … — as
            a dict or ``KEY=VALUE`` list. ``read_file`` normalises options to the
            ``KEY=VALUE`` form, so ``calibrate`` and the two numeric keywords are coerced
            from their string spellings (see
            :func:`~pyramids_eo.drivers._base.coerce_booleans`); without that, the truthy
            string ``"false"`` would switch calibration *on*.
        **_ignored: The generic driver-read parameters a SEVIRI read does not use — ``bbox``,
            ``crs``, ``auth`` and any future one — are accepted and ignored: a granule is read
            whole, carries its own geostationary CRS, and needs no credentials.

    Returns:
        The calibrated, geolocated channel.

    Raises:
        ValueError: No channel was given (via ``bands`` or ``options``), more than one
            band was given, or a boolean / numeric option could not be read from its
            ``KEY=VALUE`` string spelling (``calibrate``, ``sun_earth_distance``,
            ``subsatellite_longitude``).
    """
    from pyramids_eo.sensors.readers import read_seviri

    settings = options_as_dict(options)
    coerce_booleans(settings, ("calibrate",), driver="seviri")
    coerce_floats(
        settings, ("sun_earth_distance", "subsatellite_longitude"), driver="seviri"
    )
    channel = settings.pop("channel", None)
    if channel is None and bands:
        if isinstance(bands, (str, bytes)):
            raise ValueError(
                f"bands must be a list of channel names, not a bare "
                f"{type(bands).__name__} ({bands!r}); pass bands=['IR_108']."
            )
        bands = list(bands)  # materialise a generator/iterator so len() is safe
        if len(bands) != 1:
            raise ValueError(
                f"a SEVIRI read is one channel, but {len(bands)} bands were given "
                f"({bands}); pass a single band or options={{'channel': 'IR_108'}}."
            )
        channel = bands[0]
    if channel is None:
        raise ValueError(
            "a SEVIRI read needs a channel: pass bands=['IR_108'] or "
            "open_options={'channel': 'IR_108'}."
        )
    return read_seviri(source, channel, **settings)

SlstrDriver #

Read one or more Sentinel-3 SLSTR L1 RBT channels from a .SEN3 granule.

Attributes:

Name Type Description
name

The driver's registry name and the value accepted by read_file(driver=…).

long_name

Human-readable source name for describe_drivers.

api_version

The driver-contract version (see :data:~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION).

suffixes tuple[str, ...]

(".sen3",) — a granule directory is named *.SEN3.

schemes tuple[str, ...]

("slstr",) — a slstr:// path names a granule explicitly, and distinguishes SLSTR from OLCI when both share the .SEN3 suffix.

capabilities

read only (one granule is one acquisition).

extra str | None

None — the reader is pure pyramids-eo over pyramids' bundled GDAL.

Source code in src/pyramids_eo/drivers/slstr.py
class SlstrDriver:
    """Read one or more Sentinel-3 SLSTR L1 RBT channels from a ``.SEN3`` granule.

    Attributes:
        name: The driver's registry name and the value accepted by ``read_file(driver=…)``.
        long_name: Human-readable source name for ``describe_drivers``.
        api_version: The driver-contract version (see
            :data:`~pyramids_eo.drivers._base.RASTER_DRIVER_API_VERSION`).
        suffixes: ``(".sen3",)`` — a granule directory is named ``*.SEN3``.
        schemes: ``("slstr",)`` — a ``slstr://`` path names a granule explicitly, and
            distinguishes SLSTR from OLCI when both share the ``.SEN3`` suffix.
        capabilities: ``read`` only (one granule is one acquisition).
        extra: ``None`` — the reader is pure pyramids-eo over pyramids' bundled GDAL.
    """

    name = "slstr"
    long_name = "Sentinel-3 SLSTR L1 RBT (.SEN3)"
    api_version = RASTER_DRIVER_API_VERSION
    suffixes: tuple[str, ...] = (".sen3",)
    schemes: tuple[str, ...] = ("slstr",)
    capabilities = frozenset({"read"})
    extra: str | None = None

    @classmethod
    def can_open(cls, source: Any) -> bool:
        """Return whether ``source`` names a real SLSTR L1 RBT granule.

        A ``.SEN3`` directory alone is not enough to claim, because OLCI granules share that
        suffix; the directory must actually hold an SLSTR measurement file.

        Args:
            source: The source handed by ``Dataset.read_file`` (stringified) — a ``slstr://``
                path, a ``.SEN3`` directory, or a glob string.

        Returns:
            True for a ``slstr://`` source, a directory containing at least one measurement
            file, or a glob whose matches include such a directory; False otherwise. The
            directory listing short-circuits on the first match but enumerates the whole
            directory when nothing matches; it runs only once GDAL has failed to open the
            source, and any filesystem error is swallowed to False so the method never raises.
            ``driver="slstr"`` bypasses this entirely.

        Examples:
            - A ``slstr://`` source is always claimed (a cheap string check):
                ```python
                >>> from pyramids_eo.drivers.slstr import SlstrDriver
                >>> SlstrDriver.can_open("slstr://S3A_SL_1_RBT.SEN3")
                True

                ```
            - A non-string source is never claimed:
                ```python
                >>> SlstrDriver.can_open(None)
                False

                ```
        """
        if not isinstance(source, str) or not source:
            return False
        if source.lower().startswith(_SCHEME):
            return True
        # Resolve an existing path literally first, so a real granule whose own name contains a
        # glob metacharacter is stat-checked rather than treated as a pattern. The probes are
        # wrapped so can_open honours its contract of never raising.
        try:
            path = Path(source)
            if path.is_dir():
                return _holds_measurement(path)
            if path.exists():
                return False
            if any(character in source for character in "*?["):
                return any(_holds_measurement(Path(match)) for match in glob(source))
        except (OSError, ValueError):
            return False
        return False

    def read(
        self,
        source: Any,
        *,
        bands: Any = None,
        options: Any = None,
        **_ignored: Any,
    ) -> Dataset | dict[str, Dataset]:
        """Read one or more SLSTR L1 RBT channels into a :class:`~pyramids.dataset.Dataset`.

        Args:
            source: A ``.SEN3`` granule directory, or that path prefixed ``slstr://``.
            bands: The channel(s) to read — one name for a single-channel ``Dataset``, several for
                a ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
                forwards just ``options``, so through ``read_file`` the channel must come from
                ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
                ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
            options: Extra :func:`~pyramids_eo.sensors.readers.read_slstr` keywords — ``channel``
                / ``channels``, ``view``, ``grid`` and ``geolocation`` — as a dict or
                ``KEY=VALUE`` list.
            **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
                accepted and ignored — a granule is read whole, carries its own swath geolocation,
                and needs no credentials.

        Returns:
            A single channel's ``Dataset``, or a ``dict[str, Dataset]`` when several were
            requested.

        Raises:
            ValueError: No channel was given (via ``bands`` or ``options``, counting an empty
                ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
                given; ``bands`` is not a list of channel names; ``options`` is a bare string or
                carries an item that is not ``"KEY=VALUE"``; or ``geolocation`` is a string that
                is not a recognised boolean spelling (see
                :func:`~pyramids_eo.drivers._base.coerce_booleans`).
            ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_slstr` — the
                channel, ``view`` or ``grid`` is not an SLSTR one, or the granule lacks the
                channel on the grid(s) tried.

        Note:
            A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
            driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
            ``TypeError`` from pyramids' plugin layer. Use the reader function
            (``read_slstr(..., channels=[...])``) for several channels at once. This is shared
            with the other channel-at-a-time drivers.
        """
        from pyramids_eo.sensors.readers import read_slstr

        settings = options_as_dict(options)
        coerce_booleans(settings, ("geolocation",), driver="slstr")
        channel = settings.pop("channel", None)
        channels = settings.pop("channels", None)
        if channel is not None and channels is not None:
            raise ValueError(
                "pass either a single channel or a channels list, not both."
            )
        if channel is None and channels is None and bands is not None:
            channel, channels = bands_to_channels(bands, example="S5")
        if isinstance(channels, (list, tuple)) and len(channels) == 0:
            channels = None  # an empty channels list names no channel
        if channel is None and channels is None:
            raise ValueError(
                "an SLSTR read needs a channel: pass bands=['S5'], "
                "open_options={'channel': 'S5'}."
            )
        return read_slstr(
            _strip_scheme(str(source)), channel=channel, channels=channels, **settings
        )
can_open(source) classmethod #

Return whether source names a real SLSTR L1 RBT granule.

A .SEN3 directory alone is not enough to claim, because OLCI granules share that suffix; the directory must actually hold an SLSTR measurement file.

Parameters:

Name Type Description Default
source Any

The source handed by Dataset.read_file (stringified) — a slstr:// path, a .SEN3 directory, or a glob string.

required

Returns:

Type Description
bool

True for a slstr:// source, a directory containing at least one measurement

bool

file, or a glob whose matches include such a directory; False otherwise. The

bool

directory listing short-circuits on the first match but enumerates the whole

bool

directory when nothing matches; it runs only once GDAL has failed to open the

bool

source, and any filesystem error is swallowed to False so the method never raises.

bool

driver="slstr" bypasses this entirely.

Examples:

  • A slstr:// source is always claimed (a cheap string check):
    >>> from pyramids_eo.drivers.slstr import SlstrDriver
    >>> SlstrDriver.can_open("slstr://S3A_SL_1_RBT.SEN3")
    True
    
  • A non-string source is never claimed:
    >>> SlstrDriver.can_open(None)
    False
    
Source code in src/pyramids_eo/drivers/slstr.py
@classmethod
def can_open(cls, source: Any) -> bool:
    """Return whether ``source`` names a real SLSTR L1 RBT granule.

    A ``.SEN3`` directory alone is not enough to claim, because OLCI granules share that
    suffix; the directory must actually hold an SLSTR measurement file.

    Args:
        source: The source handed by ``Dataset.read_file`` (stringified) — a ``slstr://``
            path, a ``.SEN3`` directory, or a glob string.

    Returns:
        True for a ``slstr://`` source, a directory containing at least one measurement
        file, or a glob whose matches include such a directory; False otherwise. The
        directory listing short-circuits on the first match but enumerates the whole
        directory when nothing matches; it runs only once GDAL has failed to open the
        source, and any filesystem error is swallowed to False so the method never raises.
        ``driver="slstr"`` bypasses this entirely.

    Examples:
        - A ``slstr://`` source is always claimed (a cheap string check):
            ```python
            >>> from pyramids_eo.drivers.slstr import SlstrDriver
            >>> SlstrDriver.can_open("slstr://S3A_SL_1_RBT.SEN3")
            True

            ```
        - A non-string source is never claimed:
            ```python
            >>> SlstrDriver.can_open(None)
            False

            ```
    """
    if not isinstance(source, str) or not source:
        return False
    if source.lower().startswith(_SCHEME):
        return True
    # Resolve an existing path literally first, so a real granule whose own name contains a
    # glob metacharacter is stat-checked rather than treated as a pattern. The probes are
    # wrapped so can_open honours its contract of never raising.
    try:
        path = Path(source)
        if path.is_dir():
            return _holds_measurement(path)
        if path.exists():
            return False
        if any(character in source for character in "*?["):
            return any(_holds_measurement(Path(match)) for match in glob(source))
    except (OSError, ValueError):
        return False
    return False
read(source, *, bands=None, options=None, **_ignored) #

Read one or more SLSTR L1 RBT channels into a :class:~pyramids.dataset.Dataset.

Parameters:

Name Type Description Default
source Any

A .SEN3 granule directory, or that path prefixed slstr://.

required
bands Any

The channel(s) to read — one name for a single-channel Dataset, several for a dict[str, Dataset]. A direct-call convenience only: Dataset.read_file forwards just options, so through read_file the channel must come from options={"channel": …} / options={"channels": [...]}, and a channel/channels in options takes precedence over bands.

None
options Any

Extra :func:~pyramids_eo.sensors.readers.read_slstr keywords — channel / channels, view, grid and geolocation — as a dict or KEY=VALUE list.

None
**_ignored Any

Any other generic driver-read parameter (bbox / crs / auth), accepted and ignored — a granule is read whole, carries its own swath geolocation, and needs no credentials.

{}

Returns:

Type Description
Dataset | dict[str, Dataset]

A single channel's Dataset, or a dict[str, Dataset] when several were

Dataset | dict[str, Dataset]

requested.

Raises:

Type Description
ValueError

No channel was given (via bands or options, counting an empty channels list as none); both a single channel and a channels list were given; bands is not a list of channel names; options is a bare string or carries an item that is not "KEY=VALUE"; or geolocation is a string that is not a recognised boolean spelling (see :func:~pyramids_eo.drivers._base.coerce_booleans).

ReaderError

Propagated from :func:~pyramids_eo.sensors.readers.read_slstr — the channel, view or grid is not an SLSTR one, or the granule lacks the channel on the grid(s) tried.

Note

A channel set is a direct-call feature only: Dataset.read_file requires a driver to return one Dataset, so an options={'channels': [...]} read raises TypeError from pyramids' plugin layer. Use the reader function (read_slstr(..., channels=[...])) for several channels at once. This is shared with the other channel-at-a-time drivers.

Source code in src/pyramids_eo/drivers/slstr.py
def read(
    self,
    source: Any,
    *,
    bands: Any = None,
    options: Any = None,
    **_ignored: Any,
) -> Dataset | dict[str, Dataset]:
    """Read one or more SLSTR L1 RBT channels into a :class:`~pyramids.dataset.Dataset`.

    Args:
        source: A ``.SEN3`` granule directory, or that path prefixed ``slstr://``.
        bands: The channel(s) to read — one name for a single-channel ``Dataset``, several for
            a ``dict[str, Dataset]``. A direct-call convenience only: ``Dataset.read_file``
            forwards just ``options``, so through ``read_file`` the channel must come from
            ``options={"channel": …}`` / ``options={"channels": [...]}``, and a
            ``channel``/``channels`` in ``options`` takes precedence over ``bands``.
        options: Extra :func:`~pyramids_eo.sensors.readers.read_slstr` keywords — ``channel``
            / ``channels``, ``view``, ``grid`` and ``geolocation`` — as a dict or
            ``KEY=VALUE`` list.
        **_ignored: Any other generic driver-read parameter (``bbox`` / ``crs`` / ``auth``),
            accepted and ignored — a granule is read whole, carries its own swath geolocation,
            and needs no credentials.

    Returns:
        A single channel's ``Dataset``, or a ``dict[str, Dataset]`` when several were
        requested.

    Raises:
        ValueError: No channel was given (via ``bands`` or ``options``, counting an empty
            ``channels`` list as none); both a single ``channel`` and a ``channels`` list were
            given; ``bands`` is not a list of channel names; ``options`` is a bare string or
            carries an item that is not ``"KEY=VALUE"``; or ``geolocation`` is a string that
            is not a recognised boolean spelling (see
            :func:`~pyramids_eo.drivers._base.coerce_booleans`).
        ReaderError: Propagated from :func:`~pyramids_eo.sensors.readers.read_slstr` — the
            channel, ``view`` or ``grid`` is not an SLSTR one, or the granule lacks the
            channel on the grid(s) tried.

    Note:
        A channel **set** is a direct-call feature only: ``Dataset.read_file`` requires a
        driver to return one ``Dataset``, so an ``options={'channels': [...]}`` read raises
        ``TypeError`` from pyramids' plugin layer. Use the reader function
        (``read_slstr(..., channels=[...])``) for several channels at once. This is shared
        with the other channel-at-a-time drivers.
    """
    from pyramids_eo.sensors.readers import read_slstr

    settings = options_as_dict(options)
    coerce_booleans(settings, ("geolocation",), driver="slstr")
    channel = settings.pop("channel", None)
    channels = settings.pop("channels", None)
    if channel is not None and channels is not None:
        raise ValueError(
            "pass either a single channel or a channels list, not both."
        )
    if channel is None and channels is None and bands is not None:
        channel, channels = bands_to_channels(bands, example="S5")
    if isinstance(channels, (list, tuple)) and len(channels) == 0:
        channels = None  # an empty channels list names no channel
    if channel is None and channels is None:
        raise ValueError(
            "an SLSTR read needs a channel: pass bands=['S5'], "
            "open_options={'channel': 'S5'}."
        )
    return read_slstr(
        _strip_scheme(str(source)), channel=channel, channels=channels, **settings
    )