Skip to content

API Reference#

The pyramids-eo public API. The top-level package (pyramids_eo) re-exports the Earth Engine and Sentinel-2 entry points; the sensor readers, registry, composites, and STAC signers live under their subpackages.

  • Earth Engine — read EE Image / ImageCollection assets into a Dataset / DatasetCollection (from_earthengine, collection_from_earthengine, cost estimation, credentials).
  • Sentinel — ESA Sentinel product readers (open_product, from_sentinel2, SCL masking).
  • Sensors — the L1 data-access layer:
    • Readers — instrument readers (MTG-FCI, MSG-SEVIRI).
    • Registry — sensor metadata (band → wavelength, native resolution, fill, calibration).
  • Composites — day/night compositing (solar / viewing geometry, Rayleigh correction, blend), plus the stretch / to_area display and resampling helpers.
  • STAC signers — EO provider asset signers (PC / Earthdata / CDSE / BDC).
  • Errors — the EOError exception family.

pyramids_eo #

pyramids-eo — the Earth-observation layer of the pyramids stack.

pyramids-eo is built on top of :mod:pyramids (pyramids-core, the generic raster/vector engine) and adds the logic that is specific to Earth-observation data. Where pyramids knows how to move rasters around, pyramids-eo knows what a pixel means for a given instrument or provider: which subdataset is which channel, how to calibrate it, how to composite it, how to resample a swath — and how to reach signed EO cloud assets. It is scoped by domain (EO data), not by a restriction on what it may do.

EarthEngineCredentials #

Application Default Credentials for the Earth Engine GDAL drivers.

Three modes:

  • service-account file — an explicit Google service-account JSON key file, surfaced to GDAL as GOOGLE_APPLICATION_CREDENTIALS (:meth:from_service_account).
  • service-account info (inline JSON) — the key material as a JSON string or mapping; it is written to a private temp file (owner-only, cleaned up when the credentials are garbage-collected) and used as the key path (:meth:from_service_account_info). Useful when the key comes from a secret store rather than a file on disk.
  • application default — no explicit key; GDAL resolves ambient ADC (an already-exported GOOGLE_APPLICATION_CREDENTIALS or gcloud login). :meth:gdal_env is empty in this mode.

Prefer the named constructors :meth:from_service_account / :meth:from_service_account_info / :meth:application_default over the raw initializer.

Parameters:

Name Type Description Default
service_account_json str | Path | None

Path to a service-account JSON key, or None for application-default resolution. ~ is expanded; the file must exist when given.

None

Raises:

Type Description
AuthenticationError

The given service_account_json path does not exist.

Examples:

Application-default credentials carry no explicit GDAL config — GDAL resolves ambient ADC on its own:

>>> from pyramids_eo.earthengine import EarthEngineCredentials
>>> EarthEngineCredentials.application_default().gdal_env()
{}

A missing service-account file is rejected early:

>>> EarthEngineCredentials.from_service_account(  # doctest: +ELLIPSIS
...     "/no/such/key.json"
... )
Traceback (most recent call last):
    ...
pyramids_eo.errors.AuthenticationError: ...not found...
Source code in src/pyramids_eo/earthengine/credentials.py
class EarthEngineCredentials:
    """Application Default Credentials for the Earth Engine GDAL drivers.

    Three modes:

    * **service-account file** — an explicit Google service-account JSON key
      file, surfaced to GDAL as ``GOOGLE_APPLICATION_CREDENTIALS``
      (:meth:`from_service_account`).
    * **service-account info (inline JSON)** — the key material as a JSON string
      or mapping; it is written to a private temp file (owner-only, cleaned up
      when the credentials are garbage-collected) and used as the key path
      (:meth:`from_service_account_info`). Useful when the key comes from a secret
      store rather than a file on disk.
    * **application default** — no explicit key; GDAL resolves ambient ADC
      (an already-exported ``GOOGLE_APPLICATION_CREDENTIALS`` or ``gcloud``
      login). :meth:`gdal_env` is empty in this mode.

    Prefer the named constructors :meth:`from_service_account` /
    :meth:`from_service_account_info` / :meth:`application_default` over the raw
    initializer.

    Args:
        service_account_json: Path to a service-account JSON key, or ``None`` for
            application-default resolution. ``~`` is expanded; the file must
            exist when given.

    Raises:
        AuthenticationError: The given ``service_account_json`` path does not
            exist.

    Examples:
        Application-default credentials carry no explicit GDAL config — GDAL
        resolves ambient ADC on its own:

            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> EarthEngineCredentials.application_default().gdal_env()
            {}

        A missing service-account file is rejected early:

            >>> EarthEngineCredentials.from_service_account(  # doctest: +ELLIPSIS
            ...     "/no/such/key.json"
            ... )
            Traceback (most recent call last):
                ...
            pyramids_eo.errors.AuthenticationError: ...not found...
    """

    def __init__(self, service_account_json: str | Path | None = None) -> None:
        self._finalizer: weakref.finalize | None = None
        self._owns_path = False
        if service_account_json is None:
            self._path: Path | None = None
            return
        path = Path(service_account_json).expanduser()
        if not path.is_file():
            raise AuthenticationError(
                f"Earth Engine service-account key file not found: {path}"
            )
        self._path = path

    @classmethod
    def from_service_account_info(cls, info: str | dict) -> EarthEngineCredentials:
        """Build credentials from inline service-account JSON (string or mapping).

        The key material is written to a private, owner-only temp file that is
        removed when the returned credentials are garbage-collected. The contents
        are never logged.

        Args:
            info: The service-account key as a JSON string or a mapping.

        Returns:
            Credentials backed by a temp key file; :meth:`gdal_env` points GDAL at
            it.

        Raises:
            AuthenticationError: ``info`` is not valid JSON, or not a string /
                mapping.

        Examples:
            - Build from a mapping and confirm a key file is materialised:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> creds = EarthEngineCredentials.from_service_account_info(
                ...     {"type": "service_account"}
                ... )
                >>> creds.service_account_path.is_file()
                True
                >>> creds.gdal_env()["GOOGLE_APPLICATION_CREDENTIALS"] == str(
                ...     creds.service_account_path
                ... )
                True

                ```
            - Invalid JSON is rejected:
                ```python
                >>> from pyramids_eo.errors import AuthenticationError
                >>> try:
                ...     EarthEngineCredentials.from_service_account_info("{not json")
                ... except AuthenticationError as exc:
                ...     print("not valid JSON" in str(exc))
                True

                ```
        """
        if isinstance(info, dict):
            try:
                text = json.dumps(info)
            except (TypeError, ValueError) as exc:
                raise AuthenticationError(
                    "Earth Engine service-account info is not JSON-serialisable."
                ) from exc
        elif isinstance(info, str):
            try:
                json.loads(info)
            except (ValueError, TypeError) as exc:
                raise AuthenticationError(
                    "Earth Engine service-account info is not valid JSON."
                ) from exc
            text = info
        else:
            raise AuthenticationError(
                "Earth Engine service-account info must be a JSON string or mapping."
            )
        path = _write_secret_json(text)
        creds = cls(path)
        creds._owns_path = True
        creds._finalizer = weakref.finalize(creds, _unlink_quiet, path)
        return creds

    @classmethod
    def from_service_account(cls, path: str | Path) -> EarthEngineCredentials:
        """Build credentials from a service-account JSON key path.

        Args:
            path: Path to the Google service-account JSON key. ``~`` is
                expanded; the file must exist.

        Returns:
            The credentials, whose :meth:`gdal_env` points GDAL at ``path``.

        Examples:
            - Build from an existing key file and read the stored path back:
                ```python
                >>> import tempfile
                >>> from pathlib import Path
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> key = Path(tempfile.mkdtemp()) / "sa.json"
                >>> _ = key.write_text("{}")
                >>> creds = EarthEngineCredentials.from_service_account(key)
                >>> creds.service_account_path == key
                True

                ```
            - A missing key path is rejected early:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> EarthEngineCredentials.from_service_account(  # doctest: +ELLIPSIS
                ...     "/no/such/key.json"
                ... )
                Traceback (most recent call last):
                    ...
                pyramids_eo.errors.AuthenticationError: ...not found...

                ```
        """
        return cls(service_account_json=path)

    @classmethod
    def application_default(cls) -> EarthEngineCredentials:
        """Build credentials that defer to ambient ADC (no explicit key).

        Returns:
            Credentials with an empty :meth:`gdal_env`; GDAL resolves an
            already-exported ``GOOGLE_APPLICATION_CREDENTIALS`` or ``gcloud``
            login at read time.

        Examples:
            - Application-default credentials hold no explicit key:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> creds = EarthEngineCredentials.application_default()
                >>> creds.service_account_path is None
                True
                >>> creds.gdal_env()
                {}

                ```
            - They report their mode in ``repr``:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> repr(EarthEngineCredentials.application_default())
                'EarthEngineCredentials(application_default)'

                ```
        """
        return cls(service_account_json=None)

    @classmethod
    def coerce(cls, credentials: CredentialsLike) -> EarthEngineCredentials:
        """Normalise a caller-supplied credentials value.

        Args:
            credentials: An :class:`EarthEngineCredentials`, a path-like pointing
                at a service-account key, a mapping of inline service-account JSON,
                or ``None`` for application-default.

        Returns:
            An :class:`EarthEngineCredentials` instance.

        Examples:
            - ``None`` becomes application-default:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> EarthEngineCredentials.coerce(None).service_account_path is None
                True

                ```
            - An existing instance passes through unchanged:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> creds = EarthEngineCredentials.application_default()
                >>> EarthEngineCredentials.coerce(creds) is creds
                True

                ```
        """
        if isinstance(credentials, EarthEngineCredentials):
            return credentials
        if credentials is None:
            return cls.application_default()
        if isinstance(credentials, dict):
            return cls.from_service_account_info(credentials)
        return cls.from_service_account(credentials)

    @property
    def service_account_path(self) -> Path | None:
        """The service-account key path, or ``None`` in application-default mode."""
        return self._path

    def gdal_env(self) -> dict[str, str]:
        """Return the GDAL-config mapping for this credential.

        Returns:
            ``{"GOOGLE_APPLICATION_CREDENTIALS": <path>}`` for a service account,
            or an empty mapping for application-default (ambient) resolution.

        Examples:
            - Application-default carries no explicit config:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> EarthEngineCredentials.application_default().gdal_env()
                {}

                ```
            - A service account surfaces its key path for GDAL:
                ```python
                >>> import tempfile
                >>> from pathlib import Path
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> key = Path(tempfile.mkdtemp()) / "sa.json"
                >>> _ = key.write_text("{}")
                >>> EarthEngineCredentials.from_service_account(key).gdal_env() == {
                ...     "GOOGLE_APPLICATION_CREDENTIALS": str(key)
                ... }
                True

                ```
        """
        if self._path is None:
            return {}
        return {GOOGLE_APPLICATION_CREDENTIALS: str(self._path)}

    @contextlib.contextmanager
    def activate(self):
        """Apply this credential's GDAL config for the duration of a ``with`` block.

        Sets each :meth:`gdal_env` key as a GDAL config option and restores the
        previous value (or clears it) on exit, so the process-wide GDAL config is
        left untouched afterwards.

        Note:
            GDAL config options are **process-global**, so this save/restore is not
            thread-safe: two threads activating different service-account
            credentials concurrently would clobber each other's
            ``GOOGLE_APPLICATION_CREDENTIALS``. The reader is intended for
            single-threaded, single-credential use per process.

        Yields:
            This :class:`EarthEngineCredentials` instance.

        Examples:
            - Application-default activation is a no-op that yields the credentials:
                ```python
                >>> from pyramids_eo.earthengine import EarthEngineCredentials
                >>> creds = EarthEngineCredentials.application_default()
                >>> with creds.activate() as active:
                ...     active is creds
                True

                ```
        """
        from osgeo import gdal

        env = self.gdal_env()
        previous: dict[str, str | None] = {}
        try:
            for key, value in env.items():
                previous[key] = gdal.GetConfigOption(key, None)
                gdal.SetConfigOption(key, value)
            yield self
        finally:
            for key, old in previous.items():
                gdal.SetConfigOption(key, old)

    def __repr__(self) -> str:
        if self._path is None:
            return f"{type(self).__name__}(application_default)"
        if self._owns_path:
            return f"{type(self).__name__}(service_account_info=<redacted>)"
        return f"{type(self).__name__}(service_account_json={str(self._path)!r})"
service_account_path property #

The service-account key path, or None in application-default mode.

from_service_account_info(info) classmethod #

Build credentials from inline service-account JSON (string or mapping).

The key material is written to a private, owner-only temp file that is removed when the returned credentials are garbage-collected. The contents are never logged.

Parameters:

Name Type Description Default
info str | dict

The service-account key as a JSON string or a mapping.

required

Returns:

Type Description
EarthEngineCredentials

Credentials backed by a temp key file; :meth:gdal_env points GDAL at

EarthEngineCredentials

it.

Raises:

Type Description
AuthenticationError

info is not valid JSON, or not a string / mapping.

Examples:

  • Build from a mapping and confirm a key file is materialised:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> creds = EarthEngineCredentials.from_service_account_info(
    ...     {"type": "service_account"}
    ... )
    >>> creds.service_account_path.is_file()
    True
    >>> creds.gdal_env()["GOOGLE_APPLICATION_CREDENTIALS"] == str(
    ...     creds.service_account_path
    ... )
    True
    
  • Invalid JSON is rejected:
    >>> from pyramids_eo.errors import AuthenticationError
    >>> try:
    ...     EarthEngineCredentials.from_service_account_info("{not json")
    ... except AuthenticationError as exc:
    ...     print("not valid JSON" in str(exc))
    True
    
Source code in src/pyramids_eo/earthengine/credentials.py
@classmethod
def from_service_account_info(cls, info: str | dict) -> EarthEngineCredentials:
    """Build credentials from inline service-account JSON (string or mapping).

    The key material is written to a private, owner-only temp file that is
    removed when the returned credentials are garbage-collected. The contents
    are never logged.

    Args:
        info: The service-account key as a JSON string or a mapping.

    Returns:
        Credentials backed by a temp key file; :meth:`gdal_env` points GDAL at
        it.

    Raises:
        AuthenticationError: ``info`` is not valid JSON, or not a string /
            mapping.

    Examples:
        - Build from a mapping and confirm a key file is materialised:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> creds = EarthEngineCredentials.from_service_account_info(
            ...     {"type": "service_account"}
            ... )
            >>> creds.service_account_path.is_file()
            True
            >>> creds.gdal_env()["GOOGLE_APPLICATION_CREDENTIALS"] == str(
            ...     creds.service_account_path
            ... )
            True

            ```
        - Invalid JSON is rejected:
            ```python
            >>> from pyramids_eo.errors import AuthenticationError
            >>> try:
            ...     EarthEngineCredentials.from_service_account_info("{not json")
            ... except AuthenticationError as exc:
            ...     print("not valid JSON" in str(exc))
            True

            ```
    """
    if isinstance(info, dict):
        try:
            text = json.dumps(info)
        except (TypeError, ValueError) as exc:
            raise AuthenticationError(
                "Earth Engine service-account info is not JSON-serialisable."
            ) from exc
    elif isinstance(info, str):
        try:
            json.loads(info)
        except (ValueError, TypeError) as exc:
            raise AuthenticationError(
                "Earth Engine service-account info is not valid JSON."
            ) from exc
        text = info
    else:
        raise AuthenticationError(
            "Earth Engine service-account info must be a JSON string or mapping."
        )
    path = _write_secret_json(text)
    creds = cls(path)
    creds._owns_path = True
    creds._finalizer = weakref.finalize(creds, _unlink_quiet, path)
    return creds
from_service_account(path) classmethod #

Build credentials from a service-account JSON key path.

Parameters:

Name Type Description Default
path str | Path

Path to the Google service-account JSON key. ~ is expanded; the file must exist.

required

Returns:

Type Description
EarthEngineCredentials

The credentials, whose :meth:gdal_env points GDAL at path.

Examples:

  • Build from an existing key file and read the stored path back:
    >>> import tempfile
    >>> from pathlib import Path
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> key = Path(tempfile.mkdtemp()) / "sa.json"
    >>> _ = key.write_text("{}")
    >>> creds = EarthEngineCredentials.from_service_account(key)
    >>> creds.service_account_path == key
    True
    
  • A missing key path is rejected early:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> EarthEngineCredentials.from_service_account(  # doctest: +ELLIPSIS
    ...     "/no/such/key.json"
    ... )
    Traceback (most recent call last):
        ...
    pyramids_eo.errors.AuthenticationError: ...not found...
    
Source code in src/pyramids_eo/earthengine/credentials.py
@classmethod
def from_service_account(cls, path: str | Path) -> EarthEngineCredentials:
    """Build credentials from a service-account JSON key path.

    Args:
        path: Path to the Google service-account JSON key. ``~`` is
            expanded; the file must exist.

    Returns:
        The credentials, whose :meth:`gdal_env` points GDAL at ``path``.

    Examples:
        - Build from an existing key file and read the stored path back:
            ```python
            >>> import tempfile
            >>> from pathlib import Path
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> key = Path(tempfile.mkdtemp()) / "sa.json"
            >>> _ = key.write_text("{}")
            >>> creds = EarthEngineCredentials.from_service_account(key)
            >>> creds.service_account_path == key
            True

            ```
        - A missing key path is rejected early:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> EarthEngineCredentials.from_service_account(  # doctest: +ELLIPSIS
            ...     "/no/such/key.json"
            ... )
            Traceback (most recent call last):
                ...
            pyramids_eo.errors.AuthenticationError: ...not found...

            ```
    """
    return cls(service_account_json=path)
application_default() classmethod #

Build credentials that defer to ambient ADC (no explicit key).

Returns:

Type Description
EarthEngineCredentials

Credentials with an empty :meth:gdal_env; GDAL resolves an

EarthEngineCredentials

already-exported GOOGLE_APPLICATION_CREDENTIALS or gcloud

EarthEngineCredentials

login at read time.

Examples:

  • Application-default credentials hold no explicit key:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> creds = EarthEngineCredentials.application_default()
    >>> creds.service_account_path is None
    True
    >>> creds.gdal_env()
    {}
    
  • They report their mode in repr:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> repr(EarthEngineCredentials.application_default())
    'EarthEngineCredentials(application_default)'
    
Source code in src/pyramids_eo/earthengine/credentials.py
@classmethod
def application_default(cls) -> EarthEngineCredentials:
    """Build credentials that defer to ambient ADC (no explicit key).

    Returns:
        Credentials with an empty :meth:`gdal_env`; GDAL resolves an
        already-exported ``GOOGLE_APPLICATION_CREDENTIALS`` or ``gcloud``
        login at read time.

    Examples:
        - Application-default credentials hold no explicit key:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> creds = EarthEngineCredentials.application_default()
            >>> creds.service_account_path is None
            True
            >>> creds.gdal_env()
            {}

            ```
        - They report their mode in ``repr``:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> repr(EarthEngineCredentials.application_default())
            'EarthEngineCredentials(application_default)'

            ```
    """
    return cls(service_account_json=None)
coerce(credentials) classmethod #

Normalise a caller-supplied credentials value.

Parameters:

Name Type Description Default
credentials CredentialsLike

An :class:EarthEngineCredentials, a path-like pointing at a service-account key, a mapping of inline service-account JSON, or None for application-default.

required

Returns:

Name Type Description
An EarthEngineCredentials

class:EarthEngineCredentials instance.

Examples:

  • None becomes application-default:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> EarthEngineCredentials.coerce(None).service_account_path is None
    True
    
  • An existing instance passes through unchanged:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> creds = EarthEngineCredentials.application_default()
    >>> EarthEngineCredentials.coerce(creds) is creds
    True
    
Source code in src/pyramids_eo/earthengine/credentials.py
@classmethod
def coerce(cls, credentials: CredentialsLike) -> EarthEngineCredentials:
    """Normalise a caller-supplied credentials value.

    Args:
        credentials: An :class:`EarthEngineCredentials`, a path-like pointing
            at a service-account key, a mapping of inline service-account JSON,
            or ``None`` for application-default.

    Returns:
        An :class:`EarthEngineCredentials` instance.

    Examples:
        - ``None`` becomes application-default:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> EarthEngineCredentials.coerce(None).service_account_path is None
            True

            ```
        - An existing instance passes through unchanged:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> creds = EarthEngineCredentials.application_default()
            >>> EarthEngineCredentials.coerce(creds) is creds
            True

            ```
    """
    if isinstance(credentials, EarthEngineCredentials):
        return credentials
    if credentials is None:
        return cls.application_default()
    if isinstance(credentials, dict):
        return cls.from_service_account_info(credentials)
    return cls.from_service_account(credentials)
gdal_env() #

Return the GDAL-config mapping for this credential.

Returns:

Type Description
dict[str, str]

{"GOOGLE_APPLICATION_CREDENTIALS": <path>} for a service account,

dict[str, str]

or an empty mapping for application-default (ambient) resolution.

Examples:

  • Application-default carries no explicit config:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> EarthEngineCredentials.application_default().gdal_env()
    {}
    
  • A service account surfaces its key path for GDAL:
    >>> import tempfile
    >>> from pathlib import Path
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> key = Path(tempfile.mkdtemp()) / "sa.json"
    >>> _ = key.write_text("{}")
    >>> EarthEngineCredentials.from_service_account(key).gdal_env() == {
    ...     "GOOGLE_APPLICATION_CREDENTIALS": str(key)
    ... }
    True
    
Source code in src/pyramids_eo/earthengine/credentials.py
def gdal_env(self) -> dict[str, str]:
    """Return the GDAL-config mapping for this credential.

    Returns:
        ``{"GOOGLE_APPLICATION_CREDENTIALS": <path>}`` for a service account,
        or an empty mapping for application-default (ambient) resolution.

    Examples:
        - Application-default carries no explicit config:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> EarthEngineCredentials.application_default().gdal_env()
            {}

            ```
        - A service account surfaces its key path for GDAL:
            ```python
            >>> import tempfile
            >>> from pathlib import Path
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> key = Path(tempfile.mkdtemp()) / "sa.json"
            >>> _ = key.write_text("{}")
            >>> EarthEngineCredentials.from_service_account(key).gdal_env() == {
            ...     "GOOGLE_APPLICATION_CREDENTIALS": str(key)
            ... }
            True

            ```
    """
    if self._path is None:
        return {}
    return {GOOGLE_APPLICATION_CREDENTIALS: str(self._path)}
activate() #

Apply this credential's GDAL config for the duration of a with block.

Sets each :meth:gdal_env key as a GDAL config option and restores the previous value (or clears it) on exit, so the process-wide GDAL config is left untouched afterwards.

Note

GDAL config options are process-global, so this save/restore is not thread-safe: two threads activating different service-account credentials concurrently would clobber each other's GOOGLE_APPLICATION_CREDENTIALS. The reader is intended for single-threaded, single-credential use per process.

Yields:

Name Type Description
This

class:EarthEngineCredentials instance.

Examples:

  • Application-default activation is a no-op that yields the credentials:
    >>> from pyramids_eo.earthengine import EarthEngineCredentials
    >>> creds = EarthEngineCredentials.application_default()
    >>> with creds.activate() as active:
    ...     active is creds
    True
    
Source code in src/pyramids_eo/earthengine/credentials.py
@contextlib.contextmanager
def activate(self):
    """Apply this credential's GDAL config for the duration of a ``with`` block.

    Sets each :meth:`gdal_env` key as a GDAL config option and restores the
    previous value (or clears it) on exit, so the process-wide GDAL config is
    left untouched afterwards.

    Note:
        GDAL config options are **process-global**, so this save/restore is not
        thread-safe: two threads activating different service-account
        credentials concurrently would clobber each other's
        ``GOOGLE_APPLICATION_CREDENTIALS``. The reader is intended for
        single-threaded, single-credential use per process.

    Yields:
        This :class:`EarthEngineCredentials` instance.

    Examples:
        - Application-default activation is a no-op that yields the credentials:
            ```python
            >>> from pyramids_eo.earthengine import EarthEngineCredentials
            >>> creds = EarthEngineCredentials.application_default()
            >>> with creds.activate() as active:
            ...     active is creds
            True

            ```
    """
    from osgeo import gdal

    env = self.gdal_env()
    previous: dict[str, str | None] = {}
    try:
        for key, value in env.items():
            previous[key] = gdal.GetConfigOption(key, None)
            gdal.SetConfigOption(key, value)
        yield self
    finally:
        for key, old in previous.items():
            gdal.SetConfigOption(key, old)

ReadCost #

Bases: NamedTuple

A pre-read cost estimate for an ImageCollection window, from EEDA metadata.

Every figure is read from the EEDA catalog's own per-scene fields — no pixels are fetched — so a caller can size a read (and its EE egress) before paying for it.

Attributes:

Name Type Description
scene_count int

Number of scenes the date range + AOI (and any property_filter) select.

total_size_bytes int

Sum of the scenes' reported storage sizes (sizeBytes); a scene the catalog does not size contributes 0.

max_width int

Widest scene band width across the selection, in pixels.

max_height int

Tallest scene band height across the selection, in pixels.

max_band_count int

Largest per-scene band count across the selection.

min_pixel_size float

Finest ground pixel size across the selection (0.0 when the catalog reports none).

scenes list[_Scene]

The per-scene records (connection, acquisition time, and cost fields), in acquisition order.

Examples:

  • Read the aggregate figures and derive the transfer size in megabytes:
    >>> from pyramids_eo import ReadCost
    >>> cost = ReadCost(
    ...     scene_count=2,
    ...     total_size_bytes=300_000_000,
    ...     max_width=10980,
    ...     max_height=10980,
    ...     max_band_count=24,
    ...     min_pixel_size=10.0,
    ...     scenes=[],
    ... )
    >>> cost.scene_count
    2
    >>> round(cost.total_size_bytes / 1e6)
    300
    >>> cost.max_width, cost.min_pixel_size
    (10980, 10.0)
    
  • A pixel budget for the widest scene, all bands:
    >>> from pyramids_eo import ReadCost
    >>> cost = ReadCost(1, 0, 5490, 5490, 13, 20.0, [])
    >>> cost.max_width * cost.max_height * cost.max_band_count
    391821300
    
Source code in src/pyramids_eo/earthengine/reader.py
class ReadCost(NamedTuple):
    """A pre-read cost estimate for an ``ImageCollection`` window, from EEDA metadata.

    Every figure is read from the EEDA catalog's own per-scene fields — no pixels are
    fetched — so a caller can size a read (and its EE egress) before paying for it.

    Attributes:
        scene_count: Number of scenes the date range + AOI (and any ``property_filter``)
            select.
        total_size_bytes: Sum of the scenes' reported storage sizes (``sizeBytes``); a
            scene the catalog does not size contributes ``0``.
        max_width: Widest scene band width across the selection, in pixels.
        max_height: Tallest scene band height across the selection, in pixels.
        max_band_count: Largest per-scene band count across the selection.
        min_pixel_size: Finest ground pixel size across the selection (``0.0`` when the
            catalog reports none).
        scenes: The per-scene records (connection, acquisition time, and cost fields),
            in acquisition order.

    Examples:
        - Read the aggregate figures and derive the transfer size in megabytes:
            ```python
            >>> from pyramids_eo import ReadCost
            >>> cost = ReadCost(
            ...     scene_count=2,
            ...     total_size_bytes=300_000_000,
            ...     max_width=10980,
            ...     max_height=10980,
            ...     max_band_count=24,
            ...     min_pixel_size=10.0,
            ...     scenes=[],
            ... )
            >>> cost.scene_count
            2
            >>> round(cost.total_size_bytes / 1e6)
            300
            >>> cost.max_width, cost.min_pixel_size
            (10980, 10.0)

            ```
        - A pixel budget for the widest scene, all bands:
            ```python
            >>> from pyramids_eo import ReadCost
            >>> cost = ReadCost(1, 0, 5490, 5490, 13, 20.0, [])
            >>> cost.max_width * cost.max_height * cost.max_band_count
            391821300

            ```
    """

    scene_count: int
    total_size_bytes: int
    max_width: int
    max_height: int
    max_band_count: int
    min_pixel_size: float
    scenes: list[_Scene]

Window #

Bases: NamedTuple

The output window of an Earth Engine read: which ground, in which CRS, on which grid.

Groups the five values that describe where and at what resolution to read — the AOI, its CRS, the output pixel size or shape, and the resampler — into one object that :func:from_earthengine and :func:collection_from_earthengine take as their window argument.

Attributes:

Name Type Description
bbox BBox | None

AOI (min_x, min_y, max_x, max_y) in crs, or None for a whole-asset (lazy) read with no window.

crs str

The CRS bbox is expressed in and the output is delivered in; defaults to "EPSG:4326".

scale float | None

Output pixel size in crs units, or None. Mutually exclusive with shape.

shape tuple[int, int] | None

Output (rows, cols), or None. Mutually exclusive with scale.

resample str

Resampling algorithm for the warp; defaults to "nearest".

Examples:

  • A windowed read at an explicit pixel size:
    >>> from pyramids_eo import Window
    >>> w = Window(bbox=(86.9, 27.9, 87.0, 28.0), scale=0.01)
    >>> w.bbox
    (86.9, 27.9, 87.0, 28.0)
    >>> w.crs, w.resample
    ('EPSG:4326', 'nearest')
    
  • A projected read at an exact output shape:
    >>> from pyramids_eo import Window
    >>> w = Window(bbox=(3.0e5, 5.1e6, 3.1e5, 5.2e6), crs="EPSG:32645", shape=(256, 256))
    >>> w.shape
    (256, 256)
    >>> w.scale is None
    True
    
Source code in src/pyramids_eo/earthengine/reader.py
class Window(NamedTuple):
    """The output window of an Earth Engine read: which ground, in which CRS, on which grid.

    Groups the five values that describe *where and at what resolution* to read — the
    AOI, its CRS, the output pixel size or shape, and the resampler — into one object
    that :func:`from_earthengine` and :func:`collection_from_earthengine` take as their
    ``window`` argument.

    Attributes:
        bbox: AOI ``(min_x, min_y, max_x, max_y)`` in ``crs``, or ``None`` for a
            whole-asset (lazy) read with no window.
        crs: The CRS ``bbox`` is expressed in and the output is delivered in; defaults
            to ``"EPSG:4326"``.
        scale: Output pixel size in ``crs`` units, or ``None``. Mutually exclusive with
            ``shape``.
        shape: Output ``(rows, cols)``, or ``None``. Mutually exclusive with ``scale``.
        resample: Resampling algorithm for the warp; defaults to ``"nearest"``.

    Examples:
        - A windowed read at an explicit pixel size:
            ```python
            >>> from pyramids_eo import Window
            >>> w = Window(bbox=(86.9, 27.9, 87.0, 28.0), scale=0.01)
            >>> w.bbox
            (86.9, 27.9, 87.0, 28.0)
            >>> w.crs, w.resample
            ('EPSG:4326', 'nearest')

            ```
        - A projected read at an exact output shape:
            ```python
            >>> from pyramids_eo import Window
            >>> w = Window(bbox=(3.0e5, 5.1e6, 3.1e5, 5.2e6), crs="EPSG:32645", shape=(256, 256))
            >>> w.shape
            (256, 256)
            >>> w.scale is None
            True

            ```
    """

    bbox: BBox | None = None
    crs: str = _DEFAULT_CRS
    scale: float | None = None
    shape: tuple[int, int] | None = None
    resample: str = "nearest"

    def _for_tile(self, sub_bbox: BBox, tile_shape: tuple[int, int]) -> Window:
        """Derive a tile's window: the tile's sub-bounds at its exact pixel shape.

        The tile is sized by ``shape`` (its exact ``(rows, cols)``), so ``scale`` is
        dropped — the two are mutually exclusive and the tile grid is shape-driven.

        Args:
            sub_bbox: The tile's bounds in ``crs``.
            tile_shape: The tile's ``(rows, cols)``.

        Returns:
            A ``Window`` for the tile, sharing this window's CRS and resampler.
        """
        return self._replace(bbox=sub_bbox, shape=tile_shape, scale=None)

SclClass #

Bases: IntEnum

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

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

Examples:

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

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

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

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

            ```
    """

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

collection_from_earthengine(asset_id, *, start, end, window=Window(), geometry=None, bands=None, credentials=None, block_size=None, property_filter=None, nodata=None) #

Read an Earth Engine ImageCollection into a DatasetCollection.

Discovers the collection's scenes over the AOI + date range via the GDAL EEDA catalog driver, then reads each one (EEDAI) windowed to a common grid — one aligned :class:~pyramids.dataset.Dataset per scene, in acquisition order.

Parameters:

Name Type Description Default
asset_id str

EE ImageCollection id (e.g. "COPERNICUS/S2_SR_HARMONIZED").

required
start str

Inclusive ISO start of the acquisition window.

required
end str

Inclusive ISO end of the acquisition window.

required
window Window

The output window — a :class:Window grouping the AOI bbox with the crs / scale / shape / resample grid spec shared by every scene. A bbox is required (to bound scene discovery) unless a geometry is given. When both scale and shape are omitted the first scene's native windowed grid is used for every scene. See :func:from_earthengine for the CRS/units contract.

Window()
geometry object | None

Optional polygon AOI (a geopandas GeoDataFrame / pyramids FeatureCollection). A geometry carrying its own CRS is reprojected to the window's crs; one without is assumed to already be in it. Its envelope bounds scene discovery and each scene is clipped to the polygon cutline. Takes the place of the window's bbox when that is omitted.

None
bands list[str] | None

Band names to request; None reads every band.

None
credentials CredentialsLike

An :class:~pyramids_eo.earthengine.credentials.EarthEngineCredentials, a path to a service-account JSON key, or None for ADC.

None
block_size int | None

EEDAI transfer block size (pixels per side); None uses the conservative default. See :func:from_earthengine.

None
property_filter str | None

OGR attribute-filter fragment on the collection's own property fields (e.g. "CLOUDY_PIXEL_PERCENTAGE < 20") constraining which scenes are read. Filtered client-side over the discovered scene page (trims pixel fetches, not the catalog query), not server-side. It is interpolated verbatim and not escaped/validated — build it in code, never from untrusted input.

None
nodata float | int | None

Fill value to tag on every scene's bands (EEDAI exposes none). See :func:from_earthengine; None leaves the scenes untagged.

None

Returns:

Type Description
DatasetCollection

A pyramids :class:~pyramids.dataset.DatasetCollection, one timestep per

DatasetCollection

scene, with the acquisition times as its time axis. The scenes are held in

DatasetCollection

memory (files is None), which pyramids-core >= 0.73.0 reduces directly:

DatasetCollection

reduce_time and mean / min / max / sum need no spill to

DatasetCollection

disk. Two caveats:

DatasetCollection
  • Gaps must be NaN first. Those reductions do not mask the scenes' declared nodata — including anything passed as nodata= above — so a sentinel cell is reduced as an ordinary value. With nodata=-32768 and one gapped cell, sum over scenes 10/20/30 returns -32728 for that cell against 60 elsewhere, and min returns -32768.
DatasetCollection
  • Memory. The in-memory cube reads every scene's array eagerly (only the time stack is lazy), so the whole series is resident. For a series larger than RAM, write the scenes out and reduce a file-backed collection, which reads tile-by-tile.
DatasetCollection

The reductions read DatasetCollection.data, which needs dask, so they are

DatasetCollection

gated behind this package's lazy extra — install

DatasetCollection

pip install 'pyramids-eo[lazy]' or accessing .data raises

DatasetCollection

pyramids.errors.OptionalPackageDoesNotExist. to_zarr /

DatasetCollection

to_kerchunk still require a file-backed collection; write the scenes out

DatasetCollection

(e.g. to_cog_stack + DatasetCollection.from_files) for those.

Raises:

Type Description
ValueError

scale and shape are both given, or neither bbox nor geometry is given.

ReaderError

The catalog could not be opened, or the date range + AOI matched no scenes.

Examples:

  • Read a Sentinel-2 collection over a date range (skipped offline):
    >>> from pyramids_eo import collection_from_earthengine, Window
    >>> collection = collection_from_earthengine(  # doctest: +SKIP
    ...     "COPERNICUS/S2_SR_HARMONIZED",
    ...     start="2024-06-01",
    ...     end="2024-06-10",
    ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
    ... )
    
Source code in src/pyramids_eo/earthengine/reader.py
def collection_from_earthengine(
    asset_id: str,
    *,
    start: str,
    end: str,
    window: Window = Window(),
    geometry: object | None = None,
    bands: list[str] | None = None,
    credentials: CredentialsLike = None,
    block_size: int | None = None,
    property_filter: str | None = None,
    nodata: float | int | None = None,
) -> DatasetCollection:
    """Read an Earth Engine ``ImageCollection`` into a ``DatasetCollection``.

    Discovers the collection's scenes over the AOI + date range via the GDAL EEDA
    catalog driver, then reads each one (EEDAI) windowed to a common grid — one
    aligned :class:`~pyramids.dataset.Dataset` per scene, in acquisition order.

    Args:
        asset_id: EE ``ImageCollection`` id (e.g. ``"COPERNICUS/S2_SR_HARMONIZED"``).
        start: Inclusive ISO start of the acquisition window.
        end: Inclusive ISO end of the acquisition window.
        window: The output window — a :class:`Window` grouping the AOI ``bbox`` with the
            ``crs`` / ``scale`` / ``shape`` / ``resample`` grid spec shared by every
            scene. A ``bbox`` is required (to bound scene discovery) unless a
            ``geometry`` is given. When both ``scale`` and ``shape`` are omitted the
            first scene's native windowed grid is used for every scene. See
            :func:`from_earthengine` for the CRS/units contract.
        geometry: Optional polygon AOI (a geopandas ``GeoDataFrame`` / pyramids
            ``FeatureCollection``). A geometry carrying its own CRS is reprojected to
            the window's ``crs``; one without is assumed to already be in it. Its
            envelope bounds scene discovery and each scene is clipped to the polygon
            cutline. Takes the place of the window's ``bbox`` when that is omitted.
        bands: Band names to request; ``None`` reads every band.
        credentials: An
            :class:`~pyramids_eo.earthengine.credentials.EarthEngineCredentials`, a
            path to a service-account JSON key, or ``None`` for ADC.
        block_size: EEDAI transfer block size (pixels per side); ``None`` uses the
            conservative default. See :func:`from_earthengine`.
        property_filter: OGR attribute-filter fragment on the collection's own
            property fields (e.g. ``"CLOUDY_PIXEL_PERCENTAGE < 20"``) constraining
            which scenes are read. Filtered client-side over the discovered scene
            page (trims pixel fetches, not the catalog query), not server-side. It is
            interpolated verbatim and not escaped/validated — build it in code, never
            from untrusted input.
        nodata: Fill value to tag on every scene's bands (EEDAI exposes none). See
            :func:`from_earthengine`; ``None`` leaves the scenes untagged.

    Returns:
        A pyramids :class:`~pyramids.dataset.DatasetCollection`, one timestep per
        scene, with the acquisition times as its time axis. The scenes are held in
        memory (``files is None``), which `pyramids-core` >= 0.73.0 reduces directly:
        ``reduce_time`` and ``mean`` / ``min`` / ``max`` / ``sum`` need no spill to
        disk. Two caveats:

        * **Gaps must be ``NaN`` first.** Those reductions do not mask the scenes'
          declared nodata — including anything passed as ``nodata=`` above — so a
          sentinel cell is reduced as an ordinary value. With ``nodata=-32768`` and
          one gapped cell, ``sum`` over scenes 10/20/30 returns ``-32728`` for that
          cell against ``60`` elsewhere, and ``min`` returns ``-32768``.
        * **Memory.** The in-memory cube reads every scene's array eagerly (only the
          time stack is lazy), so the whole series is resident. For a series larger
          than RAM, write the scenes out and reduce a file-backed collection, which
          reads tile-by-tile.

        The reductions read ``DatasetCollection.data``, which needs dask, so they are
        gated behind this package's ``lazy`` extra — install
        ``pip install 'pyramids-eo[lazy]'`` or accessing ``.data`` raises
        ``pyramids.errors.OptionalPackageDoesNotExist``. ``to_zarr`` /
        ``to_kerchunk`` still require a file-backed collection; write the scenes out
        (e.g. ``to_cog_stack`` + ``DatasetCollection.from_files``) for those.

    Raises:
        ValueError: ``scale`` and ``shape`` are both given, or neither ``bbox``
            nor ``geometry`` is given.
        ReaderError: The catalog could not be opened, or the date range + AOI
            matched no scenes.

    Examples:
        - Read a Sentinel-2 collection over a date range (skipped offline):
            ```python
            >>> from pyramids_eo import collection_from_earthengine, Window
            >>> collection = collection_from_earthengine(  # doctest: +SKIP
            ...     "COPERNICUS/S2_SR_HARMONIZED",
            ...     start="2024-06-01",
            ...     end="2024-06-10",
            ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
            ... )

            ```
    """
    if window.scale is not None and window.shape is not None:
        raise ValueError("Pass at most one of 'scale' or 'shape', not both.")
    _resample_alg(window.resample)  # validate up front, before any network call
    if geometry is not None:
        geometry = _geometry_in_crs(geometry, window.crs)
    if window.bbox is None:
        if geometry is None:
            raise ValueError("Pass a 'bbox' or a 'geometry'.")
        window = window._replace(bbox=_geometry_bounds(geometry))
    assert window.bbox is not None  # resolved above from bbox or the geometry envelope

    creds = EarthEngineCredentials.coerce(credentials)
    scenes = _discover_scenes(
        asset_id,
        start=start,
        end=end,
        bbox_4326=_bbox_to_4326(window.bbox, window.crs),
        credentials=creds,
        property_filter=property_filter,
    )
    if not scenes:
        raise ReaderError(
            f"No Earth Engine scenes for {asset_id!r} in [{start}, {end}] over "
            f"{window.bbox}."
        )
    # Keep the credential config in effect across the scene reads, then restore it.
    with creds.activate():
        windowed = _read_scenes_aligned(
            scenes,
            window=window,
            bands=bands,
            credentials=creds,
            block_size=block_size,
        )
    env = creds.gdal_env()
    # ``windowed`` scenes are already fully-materialised pyramids Datasets (the warp
    # read every pixel eagerly), so they need no re-wrapping or credential env.
    datasets = [
        _retain_credentials(
            _apply_nodata(_apply_geometry(scene, geometry), nodata), creds
        )
        for scene in windowed
    ]
    collection = DatasetCollection(
        datasets[0],
        time_length=len(datasets),
        datasets=datasets,
        time=[scene.time for scene in scenes],
        gdal_env=env,
    )
    return _retain_credentials(collection, creds)

estimate_earthengine_cost(asset_id, *, start, end, bbox=None, geometry=None, crs=_DEFAULT_CRS, credentials=None, property_filter=None) #

Estimate what an ImageCollection read would cost, without fetching pixels.

Runs only the EEDA scene discovery (the catalog query) and aggregates the cost fields the catalog reports per scene — band count, pixel dimensions, pixel size and storage size — into a :class:ReadCost. This answers "how big is this read" as a fact about the actual scenes rather than a guess from asset-level metadata.

Parameters:

Name Type Description Default
asset_id str

EE ImageCollection id (e.g. "COPERNICUS/S2_SR_HARMONIZED").

required
start str

Inclusive ISO start of the acquisition window.

required
end str

Inclusive ISO end of the acquisition window.

required
bbox BBox | None

AOI (min_x, min_y, max_x, max_y) in crs. Required unless a geometry is given.

None
geometry object | None

Optional polygon AOI whose envelope bounds scene discovery (its CRS is honoured as in :func:collection_from_earthengine).

None
crs str

The CRS bbox is expressed in. Defaults to "EPSG:4326".

_DEFAULT_CRS
credentials CredentialsLike

Credentials authorising the catalog query (see :func:collection_from_earthengine).

None
property_filter str | None

Optional scene property filter (e.g. cloud cover), applied client-side over the discovered page — the same selection a matching read would see. Interpolated verbatim into the OGR filter and not escaped/validated, so build it in code, never from untrusted input.

None

Returns:

Name Type Description
A ReadCost

class:ReadCost for the selected scenes.

Raises:

Type Description
ValueError

Neither bbox nor geometry is given.

ReaderError

The catalog could not be opened, or the date range + AOI matched no scenes.

Examples:

  • Size a Sentinel-2 window before fetching any pixels (needs live credentials):
    >>> from pyramids_eo import estimate_earthengine_cost
    >>> cost = estimate_earthengine_cost(  # doctest: +SKIP
    ...     "COPERNICUS/S2_SR_HARMONIZED",
    ...     start="2024-06-01",
    ...     end="2024-06-30",
    ...     bbox=(86.90, 27.90, 86.94, 27.94),
    ... )
    >>> cost.scene_count, cost.max_band_count  # doctest: +SKIP
    (6, 24)
    
  • Narrow the estimate to low-cloud scenes with a property filter:
    >>> from pyramids_eo import estimate_earthengine_cost
    >>> clear = estimate_earthengine_cost(  # doctest: +SKIP
    ...     "COPERNICUS/S2_SR_HARMONIZED",
    ...     start="2024-06-01",
    ...     end="2024-06-30",
    ...     bbox=(86.90, 27.90, 86.94, 27.94),
    ...     property_filter="CLOUDY_PIXEL_PERCENTAGE < 20",
    ... )
    >>> clear.scene_count <= 6  # doctest: +SKIP
    True
    
See Also

collection_from_earthengine: Actually read the selected scenes into a DatasetCollection.

Source code in src/pyramids_eo/earthengine/reader.py
def estimate_earthengine_cost(
    asset_id: str,
    *,
    start: str,
    end: str,
    bbox: BBox | None = None,
    geometry: object | None = None,
    crs: str = _DEFAULT_CRS,
    credentials: CredentialsLike = None,
    property_filter: str | None = None,
) -> ReadCost:
    """Estimate what an ``ImageCollection`` read would cost, without fetching pixels.

    Runs only the EEDA scene discovery (the catalog query) and aggregates the cost
    fields the catalog reports per scene — band count, pixel dimensions, pixel size and
    storage size — into a :class:`ReadCost`. This answers "how big is this read" as a
    fact about the actual scenes rather than a guess from asset-level metadata.

    Args:
        asset_id: EE ``ImageCollection`` id (e.g. ``"COPERNICUS/S2_SR_HARMONIZED"``).
        start: Inclusive ISO start of the acquisition window.
        end: Inclusive ISO end of the acquisition window.
        bbox: AOI ``(min_x, min_y, max_x, max_y)`` in ``crs``. Required unless a
            ``geometry`` is given.
        geometry: Optional polygon AOI whose envelope bounds scene discovery (its CRS
            is honoured as in :func:`collection_from_earthengine`).
        crs: The CRS ``bbox`` is expressed in. Defaults to ``"EPSG:4326"``.
        credentials: Credentials authorising the catalog query (see
            :func:`collection_from_earthengine`).
        property_filter: Optional scene property filter (e.g. cloud cover), applied
            client-side over the discovered page — the same selection a matching read
            would see. Interpolated verbatim into the OGR filter and not
            escaped/validated, so build it in code, never from untrusted input.

    Returns:
        A :class:`ReadCost` for the selected scenes.

    Raises:
        ValueError: Neither ``bbox`` nor ``geometry`` is given.
        ReaderError: The catalog could not be opened, or the date range + AOI matched
            no scenes.

    Examples:
        - Size a Sentinel-2 window before fetching any pixels (needs live credentials):
            ```python
            >>> from pyramids_eo import estimate_earthengine_cost
            >>> cost = estimate_earthengine_cost(  # doctest: +SKIP
            ...     "COPERNICUS/S2_SR_HARMONIZED",
            ...     start="2024-06-01",
            ...     end="2024-06-30",
            ...     bbox=(86.90, 27.90, 86.94, 27.94),
            ... )
            >>> cost.scene_count, cost.max_band_count  # doctest: +SKIP
            (6, 24)

            ```
        - Narrow the estimate to low-cloud scenes with a property filter:
            ```python
            >>> from pyramids_eo import estimate_earthengine_cost
            >>> clear = estimate_earthengine_cost(  # doctest: +SKIP
            ...     "COPERNICUS/S2_SR_HARMONIZED",
            ...     start="2024-06-01",
            ...     end="2024-06-30",
            ...     bbox=(86.90, 27.90, 86.94, 27.94),
            ...     property_filter="CLOUDY_PIXEL_PERCENTAGE < 20",
            ... )
            >>> clear.scene_count <= 6  # doctest: +SKIP
            True

            ```

    See Also:
        collection_from_earthengine: Actually read the selected scenes into a
            ``DatasetCollection``.
    """
    if geometry is not None:
        geometry = _geometry_in_crs(geometry, crs)
    if bbox is None:
        if geometry is None:
            raise ValueError("Pass a 'bbox' or a 'geometry'.")
        bbox = _geometry_bounds(geometry)

    creds = EarthEngineCredentials.coerce(credentials)
    scenes = _discover_scenes(
        asset_id,
        start=start,
        end=end,
        bbox_4326=_bbox_to_4326(bbox, crs),
        credentials=creds,
        property_filter=property_filter,
    )
    if not scenes:
        raise ReaderError(
            f"No Earth Engine scenes for {asset_id!r} in [{start}, {end}] over {bbox}."
        )
    pixel_sizes = [s.pixel_size for s in scenes if s.pixel_size > 0]
    return ReadCost(
        scene_count=len(scenes),
        total_size_bytes=sum(s.size_bytes for s in scenes),
        max_width=max(s.width for s in scenes),
        max_height=max(s.height for s in scenes),
        max_band_count=max(s.band_count for s in scenes),
        min_pixel_size=min(pixel_sizes) if pixel_sizes else 0.0,
        scenes=list(scenes),
    )

from_earthengine(asset_id, *, window=Window(), bands=None, geometry=None, start=None, end=None, reducer=None, credentials=None, tile_size=None, path=None, block_size=None, property_filter=None, nodata=None) #

Read an Earth Engine Image (or reduced ImageCollection) into a Dataset.

Two modes:

  • Single Image (default): opens asset_id through the GDAL EEDAI driver and, when a bbox is given, warps it to crs at the requested resolution.
  • ImageCollection composite: when start / end + reducer are given, discovers the collection's scenes over the AOI + date range (EEDA), reads them aligned, and reduces them client-side into one composite Dataset. Server-side EE reducers are out of scope.

Parameters:

Name Type Description Default
asset_id str

EE image asset id (single mode) or ImageCollection id (composite mode), e.g. "USGS/SRTMGL1_003" / "COPERNICUS/S2_SR_HARMONIZED".

required
bands list[str] | None

Band names to request; None reads every band. When the requested bands span multiple resolution groups (EEDAI exposes them as separate subdatasets — e.g. Sentinel-2's 10 m / 20 m / 60 m bands), a single open can only return one group. Rather than silently drop the rest, the reader resamples every requested band onto one grid when a target grid is given (the window's bbox with scale or shape), stacking them in request order; if no target grid resolves the ambiguity (a whole-asset read, or a windowed read without scale/shape) it raises rather than return a subset. A single-resolution band set is read in one pass, unchanged.

None
window Window

The output window — a :class:Window grouping the AOI bbox with the crs / scale / shape / resample grid spec. Window() (the default) reads the whole asset lazily. For an asset whose CRS the EEDAI driver cannot parse (e.g. MODIS' sinusoidal grid served as a spatialreference.org URL, #108), a windowed read recovers and applies the CRS, but the whole-asset lazy read returns the raw, un-georeferenced pixels (crs == "") — pass a bbox to obtain the recovered CRS. The AOI's coordinates are read in the window's crs — degrees under the default "EPSG:4326", the projection's metres under a projected crs (e.g. "EPSG:32645"); the box is reprojected to EPSG:4326 to bound the source and the pixels warped back to crs, so the same ground is read either way (passing lon/lat under a projected crs, or metres under 4326, silently reads the wrong ground). scale and shape are mutually exclusive; resample is one of "nearest" (default), "bilinear", "cubic", "average", "mode" (a resampling algorithm, distinct from the "mode" composite reducer). A bbox is required to window (single mode) and for the composite mode, unless a geometry supplies it.

Window()
geometry object | None

Optional polygon AOI (a geopandas GeoDataFrame / pyramids FeatureCollection). A geometry carrying its own CRS is reprojected to the window's crs; one without is assumed to already be in it. Its envelope drives the read window and the result is clipped to the polygon cutline. Takes the place of the window's bbox when that is omitted.

None
start str | None

Inclusive ISO start of the acquisition window (composite mode).

None
end str | None

Inclusive ISO end of the acquisition window (composite mode).

None
reducer str | None

Client-side reducer for the composite mode — one of "median", "mean", "min", "max", "sum", "mode", "mosaic". mode is computed per pixel in Python, so it is slower than the others over a large AOI.

None
credentials CredentialsLike

An :class:~pyramids_eo.earthengine.credentials.EarthEngineCredentials, a path to a service-account JSON key, or None for ADC.

None
tile_size int | None

Maximum tile size (pixels per side) for an oversize read. When set, the output grid is split into grid-aligned tiles of at most this size, each read and written to disk in turn, then mosaicked into path — bounding the peak of the per-tile warp/write step rather than materialising the whole output at once. When no reprojection is involved (crs equals the source/scene CRS) the mosaic reproduces the equivalent un-tiled read: nearest exactly and with no overhead, and an interpolating resample via a kernel-sized halo read and trimmed per tile so seam pixels match (#65). Under a reprojecting crs a tiled read (interpolating single-image or composite) can differ from the un-tiled read by a few LSBs at a handful of seam pixels — GDAL's warp is not bit-exact between a per-tile and a whole-window pass — so it is a close but not bit-exact reproduction there. It works with a geometry cutline — the envelope is tiled and the cutline applied to the finished mosaic (#64) — and with the composite mode (start/end + reducer), where each tile reduces its own scene stack so a seam is a mosaic boundary, not a reduction boundary (#59). Requires a bbox or geometry, a path, and scale or shape (the combinations that genuinely cannot tile). Peak memory is still governed by each tile's native-resolution window (see the Performance note), so choose tile_size relative to the asset's native resolution.

None
path str | Path | None

Output raster path. When given, the result is written there and a file-backed Dataset reading it is returned instead of an in-memory one; required when tile_size is set, and honoured for the single-image and composite paths alike. Needs a bbox or geometry (the whole-asset read is lazy). Its extension names the format, and must be one GDAL can create directly — a write-by-copy-only format (.png, .jpg, .jp2, .asc, .vrt) is refused, because the tiled mosaic path cannot produce it and the destination's legality would otherwise depend on tile_size.

None
block_size int | None

EEDAI transfer block size (pixels per side); None uses the conservative default (256). A larger block reads a window in fewer round trips; pixels are unchanged (verified byte-identical across sizes).

None
property_filter str | None

OGR attribute-filter fragment on the collection's own property fields (e.g. "CLOUDY_PIXEL_PERCENTAGE < 20"), used only in the ImageCollection composite mode to constrain which scenes are reduced. Filtered client-side over the discovered scene page (it trims pixel fetches, not the catalog query), so it is not server-side filtering. It is interpolated verbatim into the OGR attribute filter and is not escaped or validated, so build it in code — never from untrusted / user input.

None
nodata float | int | None

Fill value to tag on the returned dataset's bands. EEDAI exposes no no-data value, so a real sentinel (e.g. GSW occurrence's -128) has to be supplied from the Earth Engine catalog. For the single-image EEDAI read this targets — an untagged integer source — the value is recognised without altering any pixel, so downstream masking treats fill as fill (it is not intended for the composite/collection paths, where a source that already carries a nodata would only be re-tagged in metadata). None (default) leaves the dataset untagged — an unknown fill stays explicit rather than guessed. Scale/offset and band descriptions are carried through by the read where the source provides them; the EEDAI driver provides none.

None

Returns:

Type Description
Dataset

A pyramids :class:~pyramids.dataset.Dataset — the windowed image or the

Dataset

reduced composite (file-backed when path is given).

Note

A service-account credential is bound per read, never left in the process-global GDAL config. The windowed and composite paths scope it to the eager read and restore it afterward; the no-bbox lazy wrap carries it as the returned Dataset's own gdal_env, which pyramids re-applies and restores around every deferred pixel read. So two different service accounts can be read in one process — each Dataset keeps its own credential — and nothing leaks into unrelated GDAL work. (GDAL's EEDAI VSI_PATH_FOR_AUTH open option is not used: in the bundled GDAL it does not resolve a path-specific service-account key, falling back to metadata-server auth; the per-Dataset gdal_env is the mechanism that actually binds credentials per-open here.) See also the thread-safety note on :meth:EarthEngineCredentials.activate.

Note

Performance. The EEDAI driver's overviews are unreliable, so the reader always fetches the AOI at the asset's native resolution (block by block) and downsamples locally with resample (nearest by default). A small shape/scale output from a fine-resolution asset over a wide AOI therefore still transfers the full native window — e.g. a 32x32 read of 10 m Sentinel-2 over a 0.1° box pulls ~1100x1100 native pixels. It is correct but can be slow/data-heavy; keep the AOI tight for fine-resolution assets.

Raises:

Type Description
ValueError

scale and shape are both given; start / end are given without a reducer (use :func:collection_from_earthengine for a DatasetCollection); the composite mode is missing start / end / bbox; path is given without a bbox / geometry; or tile_size is invalid or set without its required path / scale or shape.

ReaderError

The asset could not be opened or windowed, or the composite date range + AOI matched no scenes.

Examples:

  • Read a small SRTM window (requires Earth Engine credentials, so skipped offline):
    >>> from pyramids_eo import from_earthengine, Window
    >>> ds = from_earthengine(  # doctest: +SKIP
    ...     "USGS/SRTMGL1_003",
    ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
    ... )
    
  • A median composite over an ImageCollection date range (skipped offline):
    >>> from pyramids_eo import from_earthengine, Window
    >>> composite = from_earthengine(  # doctest: +SKIP
    ...     "COPERNICUS/S2_SR_HARMONIZED",
    ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
    ...     start="2024-06-01",
    ...     end="2024-06-30",
    ...     reducer="median",
    ... )
    
  • Clip to a polygon AOI instead of a bbox (skipped offline):
    >>> import geopandas as gpd  # doctest: +SKIP
    >>> from pyramids_eo import from_earthengine
    >>> aoi = gpd.read_file("basin.geojson")  # doctest: +SKIP
    >>> ds = from_earthengine("USGS/SRTMGL1_003", geometry=aoi)  # doctest: +SKIP
    
  • Stream an oversize window to disk in 1024-px tiles (skipped offline):
    >>> from pyramids_eo import from_earthengine, Window
    >>> ds = from_earthengine(  # doctest: +SKIP
    ...     "USGS/SRTMGL1_003",
    ...     window=Window(bbox=(86.0, 27.0, 88.0, 29.0), scale=0.0003),
    ...     tile_size=1024,
    ...     path="srtm_big.tif",
    ... )
    
  • tile_size without a path is rejected before any read:
    >>> from pyramids_eo import from_earthengine, Window
    >>> from_earthengine(
    ...     "USGS/SRTMGL1_003",
    ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0), shape=(4096, 4096)),
    ...     tile_size=1024,
    ... )
    Traceback (most recent call last):
        ...
    ValueError: 'tile_size' needs 'path' to stream the mosaic to disk.
    
  • Passing both scale and shape is rejected before any read:
    >>> from pyramids_eo import from_earthengine, Window
    >>> from_earthengine(
    ...     "USGS/SRTMGL1_003",
    ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0), scale=0.01, shape=(5, 5)),
    ... )
    Traceback (most recent call last):
        ...
    ValueError: Pass at most one of 'scale' or 'shape', not both.
    
Source code in src/pyramids_eo/earthengine/reader.py
def from_earthengine(
    asset_id: str,
    *,
    window: Window = Window(),
    bands: list[str] | None = None,
    geometry: object | None = None,
    start: str | None = None,
    end: str | None = None,
    reducer: str | None = None,
    credentials: CredentialsLike = None,
    tile_size: int | None = None,
    path: str | Path | None = None,
    block_size: int | None = None,
    property_filter: str | None = None,
    nodata: float | int | None = None,
) -> Dataset:
    """Read an Earth Engine ``Image`` (or reduced ``ImageCollection``) into a ``Dataset``.

    Two modes:

    * **Single ``Image``** (default): opens ``asset_id`` through the GDAL EEDAI
      driver and, when a ``bbox`` is given, warps it to ``crs`` at the requested
      resolution.
    * **``ImageCollection`` composite**: when ``start`` / ``end`` + ``reducer`` are
      given, discovers the collection's scenes over the AOI + date range (EEDA),
      reads them aligned, and reduces them **client-side** into one composite
      ``Dataset``. Server-side EE reducers are out of scope.

    Args:
        asset_id: EE image asset id (single mode) or ``ImageCollection`` id
            (composite mode), e.g. ``"USGS/SRTMGL1_003"`` /
            ``"COPERNICUS/S2_SR_HARMONIZED"``.
        bands: Band names to request; ``None`` reads every band. When the requested
            bands span multiple resolution groups (EEDAI exposes them as separate
            subdatasets — e.g. Sentinel-2's 10 m / 20 m / 60 m bands), a single open
            can only return one group. Rather than silently drop the rest, the reader
            resamples every requested band onto one grid **when a target grid is given**
            (the window's ``bbox`` with ``scale`` or ``shape``), stacking them in request
            order; if no target grid resolves the ambiguity (a whole-asset read, or a
            windowed read without ``scale``/``shape``) it raises rather than return a
            subset. A
            single-resolution band set is read in one pass, unchanged.
        window: The output window — a :class:`Window` grouping the AOI ``bbox`` with the
            ``crs`` / ``scale`` / ``shape`` / ``resample`` grid spec. ``Window()`` (the
            default) reads the whole asset lazily. For an asset whose CRS the EEDAI
            driver cannot parse (e.g. MODIS' sinusoidal grid served as a
            spatialreference.org URL, #108), a *windowed* read recovers and applies the
            CRS, but the whole-asset lazy read returns the raw, un-georeferenced pixels
            (``crs == ""``) — pass a ``bbox`` to obtain the recovered CRS. The AOI's
            coordinates are read in the
            window's ``crs`` — degrees under the default ``"EPSG:4326"``, the
            projection's metres under a projected ``crs`` (e.g. ``"EPSG:32645"``); the
            box is reprojected to EPSG:4326 to bound the source and the pixels warped
            back to ``crs``, so the same ground is read either way (passing lon/lat under
            a projected ``crs``, or metres under 4326, silently reads the wrong ground).
            ``scale`` and ``shape`` are mutually exclusive; ``resample`` is one of
            ``"nearest"`` (default), ``"bilinear"``, ``"cubic"``, ``"average"``,
            ``"mode"`` (a *resampling* algorithm, distinct from the ``"mode"`` composite
            ``reducer``). A ``bbox`` is required to window (single mode) and for the
            composite mode, unless a ``geometry`` supplies it.
        geometry: Optional polygon AOI (a geopandas ``GeoDataFrame`` / pyramids
            ``FeatureCollection``). A geometry carrying its own CRS is reprojected to the
            window's ``crs``; one without is assumed to already be in it. Its envelope
            drives the read window and the result is clipped to the polygon cutline.
            Takes the place of the window's ``bbox`` when that is omitted.
        start: Inclusive ISO start of the acquisition window (composite mode).
        end: Inclusive ISO end of the acquisition window (composite mode).
        reducer: Client-side reducer for the composite mode — one of ``"median"``,
            ``"mean"``, ``"min"``, ``"max"``, ``"sum"``, ``"mode"``, ``"mosaic"``.
            ``mode`` is computed per pixel in Python, so it is slower than the
            others over a large AOI.
        credentials: An
            :class:`~pyramids_eo.earthengine.credentials.EarthEngineCredentials`, a
            path to a service-account JSON key, or ``None`` for ADC.
        tile_size: Maximum tile size (pixels per side) for an oversize read. When
            set, the output grid is split into grid-aligned tiles of at most this
            size, each read and written to disk in turn, then mosaicked into
            ``path`` — bounding the peak of the per-tile warp/write step rather than
            materialising the whole output at once. When no reprojection is involved
            (``crs`` equals the source/scene CRS) the mosaic reproduces the equivalent
            un-tiled read: ``nearest`` exactly and with no overhead, and an
            interpolating ``resample`` via a kernel-sized halo read and trimmed per tile
            so seam pixels match (#65). Under a **reprojecting** ``crs`` a tiled read
            (interpolating single-image or composite) can differ from the un-tiled read
            by a few LSBs at a handful of seam pixels — GDAL's warp is not bit-exact
            between a per-tile and a whole-window pass — so it is a close but not
            bit-exact reproduction there. It works with a ``geometry`` cutline — the
            envelope is tiled and the cutline applied to the finished mosaic (#64) — and
            with the composite mode (``start``/``end`` + ``reducer``), where each tile
            reduces its own scene stack so a seam is a mosaic boundary, not a reduction
            boundary (#59). Requires a ``bbox`` or ``geometry``, a
            ``path``, and ``scale`` or ``shape`` (the combinations that genuinely
            cannot tile). Peak memory is still governed by each tile's
            **native-resolution** window (see the Performance note), so choose
            ``tile_size`` relative to the asset's native resolution.
        path: Output raster path. When given, the result is written there and a
            file-backed ``Dataset`` reading it is returned instead of an in-memory
            one; required when ``tile_size`` is set, and honoured for the single-image
            and composite paths alike. Needs a ``bbox`` or ``geometry`` (the
            whole-asset read is lazy). Its extension names the format, and must be
            one GDAL can create directly — a write-by-copy-only format (``.png``,
            ``.jpg``, ``.jp2``, ``.asc``, ``.vrt``) is refused, because the tiled
            mosaic path cannot produce it and the destination's legality would
            otherwise depend on ``tile_size``.
        block_size: EEDAI transfer block size (pixels per side); ``None`` uses the
            conservative default (256). A larger block reads a window in fewer round
            trips; pixels are unchanged (verified byte-identical across sizes).
        property_filter: OGR attribute-filter fragment on the collection's own
            property fields (e.g. ``"CLOUDY_PIXEL_PERCENTAGE < 20"``), used only in the
            ``ImageCollection`` composite mode to constrain which scenes are reduced.
            Filtered client-side over the discovered scene page (it trims pixel
            fetches, not the catalog query), so it is not server-side filtering. It is
            interpolated verbatim into the OGR attribute filter and is **not** escaped
            or validated, so build it in code — never from untrusted / user input.
        nodata: Fill value to tag on the returned dataset's bands. EEDAI exposes no
            no-data value, so a real sentinel (e.g. GSW ``occurrence``'s ``-128``) has
            to be supplied from the Earth Engine catalog. For the single-image EEDAI
            read this targets — an untagged integer source — the value is recognised
            without altering any pixel, so downstream masking treats fill as fill (it
            is not intended for the composite/collection paths, where a source that
            already carries a nodata would only be re-tagged in metadata). ``None``
            (default) leaves the dataset untagged — an unknown fill stays explicit
            rather than guessed. Scale/offset and band descriptions are carried through
            by the read where the source provides them; the EEDAI driver provides none.

    Returns:
        A pyramids :class:`~pyramids.dataset.Dataset` — the windowed image or the
        reduced composite (file-backed when ``path`` is given).

    Note:
        A service-account credential is bound **per read**, never left in the
        process-global GDAL config. The windowed and composite paths scope it to the
        eager read and restore it afterward; the no-bbox lazy wrap carries it as the
        returned ``Dataset``'s own ``gdal_env``, which pyramids re-applies and restores
        around every deferred pixel read. So two different service accounts can be read
        in one process — each ``Dataset`` keeps its own credential — and nothing leaks
        into unrelated GDAL work. (GDAL's EEDAI ``VSI_PATH_FOR_AUTH`` open option is not
        used: in the bundled GDAL it does not resolve a path-specific service-account
        key, falling back to metadata-server auth; the per-``Dataset`` ``gdal_env`` is
        the mechanism that actually binds credentials per-open here.) See also the
        thread-safety note on :meth:`EarthEngineCredentials.activate`.

    Note:
        **Performance.** The EEDAI driver's overviews are unreliable, so the reader
        always fetches the AOI at the asset's **native resolution** (block by
        block) and downsamples locally with ``resample`` (nearest by default). A
        small ``shape``/``scale`` output from a fine-resolution asset over a wide
        AOI therefore still transfers the full native window — e.g. a 32x32 read of
        10 m Sentinel-2 over a 0.1° box pulls ~1100x1100 native pixels. It is
        correct but can be slow/data-heavy; keep the AOI tight for fine-resolution
        assets.

    Raises:
        ValueError: ``scale`` and ``shape`` are both given; ``start`` / ``end`` are
            given without a ``reducer`` (use :func:`collection_from_earthengine` for
            a ``DatasetCollection``); the composite mode is missing
            ``start`` / ``end`` / ``bbox``; ``path`` is given without a
            ``bbox`` / ``geometry``; or ``tile_size`` is invalid or set without its
            required ``path`` / ``scale`` or ``shape``.
        ReaderError: The asset could not be opened or windowed, or the composite
            date range + AOI matched no scenes.

    Examples:
        - Read a small SRTM window (requires Earth Engine credentials, so skipped
          offline):
            ```python
            >>> from pyramids_eo import from_earthengine, Window
            >>> ds = from_earthengine(  # doctest: +SKIP
            ...     "USGS/SRTMGL1_003",
            ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
            ... )

            ```
        - A median composite over an ``ImageCollection`` date range (skipped
          offline):
            ```python
            >>> from pyramids_eo import from_earthengine, Window
            >>> composite = from_earthengine(  # doctest: +SKIP
            ...     "COPERNICUS/S2_SR_HARMONIZED",
            ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0)),
            ...     start="2024-06-01",
            ...     end="2024-06-30",
            ...     reducer="median",
            ... )

            ```
        - Clip to a polygon AOI instead of a bbox (skipped offline):
            ```python
            >>> import geopandas as gpd  # doctest: +SKIP
            >>> from pyramids_eo import from_earthengine
            >>> aoi = gpd.read_file("basin.geojson")  # doctest: +SKIP
            >>> ds = from_earthengine("USGS/SRTMGL1_003", geometry=aoi)  # doctest: +SKIP

            ```
        - Stream an oversize window to disk in 1024-px tiles (skipped offline):
            ```python
            >>> from pyramids_eo import from_earthengine, Window
            >>> ds = from_earthengine(  # doctest: +SKIP
            ...     "USGS/SRTMGL1_003",
            ...     window=Window(bbox=(86.0, 27.0, 88.0, 29.0), scale=0.0003),
            ...     tile_size=1024,
            ...     path="srtm_big.tif",
            ... )

            ```
        - ``tile_size`` without a ``path`` is rejected before any read:
            ```python
            >>> from pyramids_eo import from_earthengine, Window
            >>> from_earthengine(
            ...     "USGS/SRTMGL1_003",
            ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0), shape=(4096, 4096)),
            ...     tile_size=1024,
            ... )
            Traceback (most recent call last):
                ...
            ValueError: 'tile_size' needs 'path' to stream the mosaic to disk.

            ```
        - Passing both ``scale`` and ``shape`` is rejected before any read:
            ```python
            >>> from pyramids_eo import from_earthengine, Window
            >>> from_earthengine(
            ...     "USGS/SRTMGL1_003",
            ...     window=Window(bbox=(86.9, 27.9, 87.0, 28.0), scale=0.01, shape=(5, 5)),
            ... )
            Traceback (most recent call last):
                ...
            ValueError: Pass at most one of 'scale' or 'shape', not both.

            ```
    """
    _validate_read_request(
        scale=window.scale,
        shape=window.shape,
        resample=window.resample,
        path=path,
        bbox=window.bbox,
        geometry=geometry,
        tile_size=tile_size,
        reducer=reducer,
        start=start,
        end=end,
        property_filter=property_filter,
    )

    creds = EarthEngineCredentials.coerce(credentials)
    if geometry is not None:
        geometry = _geometry_in_crs(geometry, window.crs)
        if window.bbox is None:
            window = window._replace(bbox=_geometry_bounds(geometry))

    if reducer is not None or start is not None or end is not None:
        result = _composite_read(
            asset_id,
            bands=bands,
            window=window,
            start=start,
            end=end,
            reducer=reducer,
            geometry=geometry,
            credentials=creds,
            path=path,
            block_size=block_size,
            property_filter=property_filter,
            tile_size=tile_size,
        )
    else:
        result = _single_image_read(
            asset_id,
            bands=bands,
            window=window,
            geometry=geometry,
            credentials=creds,
            tile_size=tile_size,
            path=path,
            block_size=block_size,
        )
    return _apply_nodata(result, nodata, credentials=creds)

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

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

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

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

Parameters:

Name Type Description Default
paths Sequence[str | Path]

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

required
root_dir str | Path

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

required
**kwargs Any

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

{}

Returns:

Type Description
Any

A pyramids.dataset.DatasetCollection over the written scenes.

Raises:

Type Description
ProductError

paths is empty.

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

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

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

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

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

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

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

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

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

Read a Sentinel-2 product into a pyramids Dataset.

Parameters:

Name Type Description Default
path str | Path | S2Product

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

required
bands list[str] | None

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

None
resolution int | None

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

None
epsg int | None

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

None
bbox BBox | None

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

None
crs str | int | None

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

None
reflectance bool

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

True
mask_scl list[Any] | None

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

None
path_out str | Path | None

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

None

Returns:

Type Description
Any

A pyramids Dataset of the requested bands.

Note

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

Raises:

Type Description
ProductError

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

Examples:

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

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

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

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

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

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

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

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

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

open_product(path) #

Open a Sentinel product and return its typed model.

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

Parameters:

Name Type Description Default
path str | Path

The product to open.

required

Returns:

Name Type Description
A SentinelProduct

class:SentinelProduct — currently an

SentinelProduct

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

Raises:

Type Description
UnsupportedProductError

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

ProductError

The path cannot be opened as a product.

Examples:

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

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

    Args:
        path: The product to open.

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

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

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

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

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

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

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

Mask dataset pixels whose SCL class is in classes.

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

Parameters:

Name Type Description Default
dataset Any

The pyramids Dataset to mask.

required
classes Sequence[SclClass | str | int]

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

required
scl Any

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

None

Returns:

Type Description
Any

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

Any

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

Raises:

Type Description
ProductError

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

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

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

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

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

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

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

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

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

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