Skip to content

API reference

geocloud.store

The process-wide client pool and test mounts.

geocloud.store.SUPPORTED_SCHEMES = _S3_SCHEMES | _GCS_SCHEMES | _AZ_SCHEMES | _ABFS_SCHEMES | _HTTP_SCHEMES | _HF_SCHEMES module-attribute

Remote URI schemes the pool can build a client for.

Local paths and file:// URIs are served too (see local_path); they are not in this set, which names what counts as remote.

geocloud.store.get_obstore(uri, *, storage_options=None)

Return the pooled ObjectStore for uri.

The first call for a pool key builds the client; later calls with the same key return the same instance, so HTTP/2 connection pooling and TLS sessions survive across files. Request objects from it with object_key. A store mount-ed at the URI's root wins over the pool.

Credentials registered for the URI's root with geocloud.credentials.set_credentials (or the credentials file) are merged under storage_options: an option passed here wins over the registered one.

Parameters:

Name Type Description Default
uri Location

A cloud URI or a local path (see the module docstring for the forms).

required
storage_options Mapping[str, Any] | None

Keyword arguments for the obstore store constructor (client_options, retry_config, credentials, ...), over the registered ones. They are part of the pool key, so different options give a different client. prefix is rejected, and Azure account_name / container_name must agree with the URI.

None

Raises:

Type Description
ValueError

unsupported scheme, malformed URI, or conflicting storage_options.

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def get_obstore(
    uri: Location,
    *,
    storage_options: Mapping[str, Any] | None = None,
) -> ObjectStore:
    """Return the pooled ``ObjectStore`` for ``uri``.

    The first call for a pool key builds the client; later calls with
    the same key return the same instance, so HTTP/2 connection pooling
    and TLS sessions survive across files. Request objects from it with
    `object_key`. A store `mount`-ed at the URI's root wins over the pool.

    Credentials registered for the URI's root with
    `geocloud.credentials.set_credentials` (or the credentials file) are merged
    under ``storage_options``: an option passed here wins over the
    registered one.

    Args:
        uri: A cloud URI or a local path (see the module docstring for the
            forms).
        storage_options: Keyword arguments for the obstore store
            constructor (``client_options``, ``retry_config``,
            credentials, ...), over the registered ones. They are part of
            the pool key, so
            different options give a different client. ``prefix`` is
            rejected, and Azure ``account_name`` / ``container_name``
            must agree with the URI.

    Raises:
        ValueError: unsupported scheme, malformed URI, or conflicting
            ``storage_options``.
    """
    from geocloud._src.credentials import registered_options

    registered = registered_options(uri)
    if registered:
        given = dict(storage_options or {})
        merged = {**registered, **given}
        # One level deeper for the HTTP client settings, so a call's
        # `timeout` keeps the registered `default_headers` (and vice versa).
        if isinstance(registered.get("client_options"), Mapping) and isinstance(
            given.get("client_options"), Mapping
        ):
            merged["client_options"] = {
                **registered["client_options"],
                **given["client_options"],
            }
        storage_options = merged
    key = _pool_key(uri, storage_options)
    with _POOL_LOCK:
        mounted = _MOUNTS.get(_mount_key(uri))
        if mounted is not None:
            return mounted
        existing = _POOL.get(key)
        if existing is not None:
            _POOL.move_to_end(key)
            return existing
        store = _build_store(uri, storage_options)
        _POOL[key] = store
        while len(_POOL) > _POOL_MAXSIZE:
            _POOL.popitem(last=False)
        return store

geocloud.store.object_key(uri)

Return the key to request from get_obstore(uri) for uri.

The path inside the bucket / container, without a leading /; for a local path, the absolute path below its filesystem anchor. For Azure the container is bound into the pooled store, so it is not part of the key (az://acct/cont/a/b.tif → a/b.tif). For http(s) the query string is carried by the pooled store, not the key.

Raises:

Type Description
ValueError

unsupported scheme or malformed Azure URI.

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def object_key(uri: Location) -> str:
    """Return the key to request from ``get_obstore(uri)`` for ``uri``.

    The path inside the bucket / container, without a leading ``/``; for a
    local path, the absolute path below its filesystem anchor.
    For Azure the container is bound into the pooled store, so it is
    not part of the key (``az://acct/cont/a/b.tif`` → ``a/b.tif``). For
    ``http(s)`` the query string is carried by the pooled store, not the
    key.

    Raises:
        ValueError: unsupported scheme or malformed Azure URI.
    """
    return _locate(uri).key

geocloud.store.get_range_bytes(uri, start, length, *, storage_options=None, store=None) async

Fetch length bytes starting at start from uri.

Parameters:

Name Type Description Default
uri Location

Cloud URI or local path of the object.

required
start int

Byte offset of the read.

required
length int

Number of bytes.

required
storage_options Mapping[str, Any] | None

Forwarded to get_obstore.

None
store ObjectStore | None

A pre-built store to use instead of the pool (tests with LocalStore / MemoryStore, or credential setups the pool key cannot express). It must be laid out like the pooled store: rooted at the bucket / container, without a prefix.

None

Returns:

Type Description
bytes

The requested bytes.

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
async def get_range_bytes(
    uri: Location,
    start: int,
    length: int,
    *,
    storage_options: Mapping[str, Any] | None = None,
    store: ObjectStore | None = None,
) -> bytes:
    """Fetch ``length`` bytes starting at ``start`` from ``uri``.

    Args:
        uri: Cloud URI or local path of the object.
        start: Byte offset of the read.
        length: Number of bytes.
        storage_options: Forwarded to `get_obstore`.
        store: A pre-built store to use instead of the pool (tests with
            ``LocalStore`` / ``MemoryStore``, or credential setups the
            pool key cannot express). It must be laid out like the pooled
            store: rooted at the bucket / container, without a prefix.

    Returns:
        The requested bytes.
    """
    if store is None:
        store = get_obstore(uri, storage_options=storage_options)
    from geocloud._src.retry import awith_bucket_retry

    key = object_key(uri)
    blob = await awith_bucket_retry(
        lambda: store.get_range_async(key, start=start, length=length)
    )
    return bytes(blob)

geocloud.store.local_path(location)

The filesystem path location names; None for a remote URI.

A Path, a string without scheme:// (data/a.tif, C:\data\a.tif, \\server\share\a.tif) and a file:// URI are local. A file:// URI is percent-decoded (file:///data/a%20b.tif → /data/a b.tif), and a host other than localhost names a UNC share (file://server/share/a.tif → //server/share/a.tif). The path is returned as written (relative paths stay relative). Every other scheme:// URI is remote.

Parameters:

Name Type Description Default
location Location

A URI, a local path string, or a Path.

required

Returns:

Type Description
Path | None

The Path, or None when location is a remote URI.

Examples:

>>> local_path("file:///data/a%20b.tif").as_posix()
'/data/a b.tif'
>>> local_path("s3://bucket/a.tif") is None
True
Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def local_path(location: Location) -> Path | None:
    """The filesystem path ``location`` names; ``None`` for a remote URI.

    A ``Path``, a string without ``scheme://`` (``data/a.tif``,
    ``C:\\data\\a.tif``, ``\\\\server\\share\\a.tif``) and a ``file://``
    URI are local. A ``file://`` URI is percent-decoded
    (``file:///data/a%20b.tif`` → ``/data/a b.tif``), and a host other than
    ``localhost`` names a UNC share (``file://server/share/a.tif`` →
    ``//server/share/a.tif``). The path is returned as written (relative
    paths stay relative). Every other ``scheme://`` URI is remote.

    Args:
        location: A URI, a local path string, or a ``Path``.

    Returns:
        The ``Path``, or ``None`` when ``location`` is a remote URI.

    Examples:
        >>> local_path("file:///data/a%20b.tif").as_posix()
        '/data/a b.tif'
        >>> local_path("s3://bucket/a.tif") is None
        True
    """
    if isinstance(location, os.PathLike):
        return Path(location)
    text = str(location)
    head, sep, _ = text.partition("://")
    if not sep or _DRIVE.match(text) or not _SCHEME.match(head):
        return Path(text)
    if head.lower() != "file":
        return None
    parts = urlsplit(text)
    path = parts.path
    if parts.netloc and parts.netloc.lower() != "localhost":
        path = f"//{parts.netloc}{path}"  # a UNC share
    return Path(url2pathname(path))

geocloud.store.clear_obstore_pool()

Drop every pooled client (stores put there by mount stay).

Use after rotating credentials in a long-running process. Runs automatically in a forked child (reqwest connection pools are not fork-safe).

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def clear_obstore_pool() -> None:
    """Drop every pooled client (stores put there by `mount` stay).

    Use after rotating credentials in a long-running process. Runs
    automatically in a forked child (reqwest connection pools are not
    fork-safe).
    """
    with _POOL_LOCK:
        _POOL.clear()

geocloud.store.set_obstore_pool_maxsize(maxsize)

Set the pool's LRU cap (default 64), evicting the oldest entries.

Raises:

Type Description
ValueError

maxsize < 1.

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def set_obstore_pool_maxsize(maxsize: int) -> None:
    """Set the pool's LRU cap (default 64), evicting the oldest entries.

    Raises:
        ValueError: ``maxsize < 1``.
    """
    global _POOL_MAXSIZE
    if maxsize < 1:
        raise ValueError(f"maxsize must be >= 1, got {maxsize}")
    with _POOL_LOCK:
        _POOL_MAXSIZE = maxsize
        while len(_POOL) > _POOL_MAXSIZE:
            _POOL.popitem(last=False)

geocloud.store.mount(uri, store)

Serve every URI under the root uri from store.

get_obstore (and so get_range_bytes, geocloud.files and every package on the pool) returns store for any URI in the same bucket, Azure container or HTTP origin, whatever storage_options it is given. Use it for a MemoryStore / LocalStore stand-in in tests, or a store whose configuration the pool cannot express. store must be laid out like the pooled one: rooted at the bucket / container, without a prefix. clear_obstore_pool leaves mounts in place, including in a forked child (where the pool is emptied because network clients are not fork-safe): mount network stores after forking. unmount removes one.

Parameters:

Name Type Description Default
uri Location

The root to mount, with no object key: s3://bucket, az://account/container, https://host.

required
store ObjectStore

Any obstore ObjectStore.

required

Raises:

Type Description
ValueError

uri names an object rather than a root, or is not a supported URI.

Examples:

>>> from obstore.store import MemoryStore
>>> mount("s3://test-bucket", MemoryStore())
>>> type(get_obstore("s3://test-bucket/a/b.tif")).__name__
'MemoryStore'
>>> unmount("s3://test-bucket")
Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def mount(uri: Location, store: ObjectStore) -> None:
    """Serve every URI under the root ``uri`` from ``store``.

    `get_obstore` (and so `get_range_bytes`, `geocloud.files` and every
    package on the pool) returns ``store`` for any URI in the same bucket,
    Azure container or HTTP origin, whatever ``storage_options`` it is
    given. Use it for a ``MemoryStore`` / ``LocalStore`` stand-in in tests,
    or a store whose configuration the pool cannot express. ``store``
    must be laid out like the pooled one: rooted at the bucket /
    container, without a prefix. `clear_obstore_pool` leaves mounts in
    place, including in a forked child (where the pool is emptied because
    network clients are not fork-safe): mount network stores after
    forking. `unmount` removes one.

    Args:
        uri: The root to mount, with no object key: ``s3://bucket``,
            ``az://account/container``, ``https://host``.
        store: Any obstore ``ObjectStore``.

    Raises:
        ValueError: ``uri`` names an object rather than a root, or is
            not a supported URI.

    Examples:
        >>> from obstore.store import MemoryStore
        >>> mount("s3://test-bucket", MemoryStore())
        >>> type(get_obstore("s3://test-bucket/a/b.tif")).__name__
        'MemoryStore'
        >>> unmount("s3://test-bucket")
    """
    loc = _locate(uri)
    if loc.key:
        raise ValueError(
            f"mount: {_r(uri)} names an object ({loc.key!r}); mount the bucket, "
            "container or host it lives under."
        )
    with _POOL_LOCK:
        _MOUNTS[_mount_key(uri)] = store

geocloud.store.unmount(uri)

Remove the store mount put at uri's root (no-op if none).

Source code in packages/geotoolz-cloud/src/geocloud/_src/store.py
def unmount(uri: Location) -> None:
    """Remove the store `mount` put at ``uri``'s root (no-op if none)."""
    with _POOL_LOCK:
        _MOUNTS.pop(_mount_key(uri), None)

geocloud.files

Whole-object verbs on the pool, cloud or local.

geocloud.files.ObjectInfo dataclass

One object (or, from a non-recursive ls, one sub-directory).

Attributes:

Name Type Description
uri str

Where it is, in the form of the listed URI: a full URI for remote objects, a local path for local ones.

size int

Size in bytes (0 for a directory entry).

last_modified datetime | None

Last modification time, UTC; None for a directory entry.

e_tag str | None

The store's entity tag, when it reports one.

is_dir bool

True for a common prefix returned by ls(..., recursive=False).

Examples:

>>> ObjectInfo("s3://bucket/a.tif", 10).is_dir
False
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
@dataclass(frozen=True)
class ObjectInfo:
    """One object (or, from a non-recursive `ls`, one sub-directory).

    Attributes:
        uri: Where it is, in the form of the listed URI: a full URI for
            remote objects, a local path for local ones.
        size: Size in bytes (``0`` for a directory entry).
        last_modified: Last modification time, UTC; ``None`` for a
            directory entry.
        e_tag: The store's entity tag, when it reports one.
        is_dir: ``True`` for a common prefix returned by
            ``ls(..., recursive=False)``.

    Examples:
        >>> ObjectInfo("s3://bucket/a.tif", 10).is_dir
        False
    """

    uri: str
    size: int
    last_modified: datetime | None = None
    e_tag: str | None = None
    is_dir: bool = False

geocloud.files.ls(prefix, *, recursive=True, storage_options=None)

List the objects under prefix, sorted by URI.

The prefix is matched by whole path segments, like a directory: s3://bucket/2026 lists 2026/… but not 2026-old/….

Parameters:

Name Type Description Default
prefix Location

A bucket / container root, a "directory" URI, or a local directory.

required
recursive bool

List everything below prefix (default); False lists one level, with sub-directories as is_dir entries.

True
storage_options Mapping[str, Any] | None

Forwarded to get_obstore for a remote prefix.

None

Returns:

Type Description
list[ObjectInfo]

One ObjectInfo per object (and directory, when not recursive).

Raises:

Type Description
ValueError

prefix is a plain http(s):// or hf:// URL, which cannot be listed.

Examples:

>>> import tempfile, pathlib
>>> root = pathlib.Path(tempfile.mkdtemp())
>>> write_bytes(root / "a" / "x.bin", b"abc")
>>> [(p.uri.removeprefix(str(root)), p.size) for p in ls(root)]
[('/a/x.bin', 3)]
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def ls(
    prefix: Location,
    *,
    recursive: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> list[ObjectInfo]:
    """List the objects under ``prefix``, sorted by URI.

    The prefix is matched by whole path segments, like a directory:
    ``s3://bucket/2026`` lists ``2026/…`` but not ``2026-old/…``.

    Args:
        prefix: A bucket / container root, a "directory" URI, or a local
            directory.
        recursive: List everything below ``prefix`` (default); ``False``
            lists one level, with sub-directories as ``is_dir`` entries.
        storage_options: Forwarded to `get_obstore` for a remote prefix.

    Returns:
        One `ObjectInfo` per object (and directory, when not recursive).

    Raises:
        ValueError: ``prefix`` is a plain ``http(s)://`` or ``hf://`` URL,
            which cannot be listed.

    Examples:
        >>> import tempfile, pathlib
        >>> root = pathlib.Path(tempfile.mkdtemp())
        >>> write_bytes(root / "a" / "x.bin", b"abc")
        >>> [(p.uri.removeprefix(str(root)), p.size) for p in ls(root)]
        [('/a/x.bin', 3)]
    """
    target = _resolve(prefix, storage_options)
    _require_listable(target, prefix)
    if recursive:
        found = [
            target.describe(meta)
            for meta in with_bucket_retry(
                lambda: [
                    meta
                    for page in obstore.list(target.store, prefix=_prefix(target))
                    for meta in page
                ]
            )
        ]
    else:
        level = with_bucket_retry(
            lambda: obstore.list_with_delimiter(target.store, prefix=_prefix(target))
        )
        found = [target.describe(meta) for meta in level["objects"]]
        found += [
            ObjectInfo(target.child(path) + "/", 0, is_dir=True)
            for path in level["common_prefixes"]
        ]
    return sorted(found, key=lambda item: item.uri)

geocloud.files.info(uri, *, storage_options=None)

Size, modification time and entity tag of one object.

Raises:

Type Description
FileNotFoundError

No object at uri.

Examples:

>>> import tempfile, pathlib
>>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
>>> write_bytes(path, b"abc")
>>> info(path).size
3
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def info(
    uri: Location, *, storage_options: Mapping[str, Any] | None = None
) -> ObjectInfo:
    """Size, modification time and entity tag of one object.

    Raises:
        FileNotFoundError: No object at ``uri``.

    Examples:
        >>> import tempfile, pathlib
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
        >>> write_bytes(path, b"abc")
        >>> info(path).size
        3
    """
    target = _resolve(uri, storage_options)
    return target.describe(target.head())

geocloud.files.exists(uri, *, storage_options=None)

Whether an object exists at uri (a prefix alone does not count).

Examples:

>>> exists("/no/such/file.bin")
False
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def exists(uri: Location, *, storage_options: Mapping[str, Any] | None = None) -> bool:
    """Whether an object exists at ``uri`` (a prefix alone does not count).

    Examples:
        >>> exists("/no/such/file.bin")
        False
    """
    try:
        info(uri, storage_options=storage_options)
    except FileNotFoundError:
        return False
    return True

geocloud.files.read_bytes(uri, *, storage_options=None)

The whole object at uri, in memory.

Raises:

Type Description
FileNotFoundError

No object at uri.

Examples:

>>> import tempfile, pathlib
>>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
>>> write_bytes(path, b"abc")
>>> read_bytes(path)
b'abc'
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def read_bytes(
    uri: Location, *, storage_options: Mapping[str, Any] | None = None
) -> bytes:
    """The whole object at ``uri``, in memory.

    Raises:
        FileNotFoundError: No object at ``uri``.

    Examples:
        >>> import tempfile, pathlib
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
        >>> write_bytes(path, b"abc")
        >>> read_bytes(path)
        b'abc'
    """
    target = _resolve(uri, storage_options)
    return with_bucket_retry(
        lambda: bytes(obstore.get(target.store, target.key).bytes()),
        probe=target.probe,
    )

geocloud.files.write_bytes(uri, data, *, storage_options=None)

Write data as the object at uri, replacing any existing one.

Local parent directories are created. The store writes the object atomically: readers see the old object or the new one, never a part.

Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def write_bytes(
    uri: Location,
    data: bytes | bytearray | memoryview,
    *,
    storage_options: Mapping[str, Any] | None = None,
) -> None:
    """Write ``data`` as the object at ``uri``, replacing any existing one.

    Local parent directories are created. The store writes the object
    atomically: readers see the old object or the new one, never a part.
    """
    target = _resolve(uri, storage_options)
    with_bucket_retry(lambda: obstore.put(target.store, target.key, bytes(data)))

geocloud.files.open(uri, mode='rb', *, storage_options=None)

A file-like handle on the object at uri.

"rb" returns a seekable reader that fetches byte ranges on demand (hand it to h5py, zipfile, …; close() it when done); "wb" a buffered writer, used as a context manager, whose object appears when it is closed.

Parameters:

Name Type Description Default
uri Location

The object.

required
mode Literal['rb', 'wb']

"rb" or "wb".

'rb'
storage_options Mapping[str, Any] | None

Forwarded to get_obstore for a remote URI.

None

Raises:

Type Description
ValueError

Any other mode.

FileNotFoundError

"rb" and no object at uri.

Examples:

>>> import tempfile, pathlib
>>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
>>> with open(path, "wb") as fh:
...     _ = fh.write(b"abcdef")
>>> fh = open(path)
>>> _ = fh.seek(2)
>>> bytes(fh.read(2))
b'cd'
>>> fh.close()
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def open(  # `geocloud.files.open`, like `fsspec.open`
    uri: Location,
    mode: Literal["rb", "wb"] = "rb",
    *,
    storage_options: Mapping[str, Any] | None = None,
) -> ReadableFile | WritableFile:
    """A file-like handle on the object at ``uri``.

    ``"rb"`` returns a seekable reader that fetches byte ranges on demand
    (hand it to h5py, ``zipfile``, …; ``close()`` it when done); ``"wb"``
    a buffered writer, used as a context manager, whose object appears
    when it is closed.

    Args:
        uri: The object.
        mode: ``"rb"`` or ``"wb"``.
        storage_options: Forwarded to `get_obstore` for a remote URI.

    Raises:
        ValueError: Any other ``mode``.
        FileNotFoundError: ``"rb"`` and no object at ``uri``.

    Examples:
        >>> import tempfile, pathlib
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
        >>> with open(path, "wb") as fh:
        ...     _ = fh.write(b"abcdef")
        >>> fh = open(path)
        >>> _ = fh.seek(2)
        >>> bytes(fh.read(2))
        b'cd'
        >>> fh.close()
    """
    target = _resolve(uri, storage_options)
    if mode == "rb":
        return cast(
            "ReadableFile",
            _RetryingReader(
                with_bucket_retry(
                    lambda: obstore.open_reader(target.store, target.key),
                    probe=target.probe,
                )
            ),
        )
    if mode == "wb":
        return obstore.open_writer(target.store, target.key)
    raise ValueError(f"open: mode must be 'rb' or 'wb'; got {mode!r}.")

geocloud.files.download(uri, dest, *, overwrite=True, storage_options=None)

Download the object at uri to the local file dest.

Fetched in 16 MiB byte ranges into a hidden .part sibling, each range pinned to the object's entity tag, checked against the object's size, then renamed into place; parent directories are made.

Parameters:

Name Type Description Default
uri Location

The object.

required
dest Location

The local file, or a directory (existing, or spelled with a trailing /) to download into under the object's name.

required
overwrite bool

Replace an existing file (default); False keeps it and skips the download.

True
storage_options Mapping[str, Any] | None

Forwarded to get_obstore.

None

Returns:

Type Description
Path

The local path written (or kept).

Raises:

Type Description
ValueError

dest is a remote URI (use copy).

FileNotFoundError

No object at uri.

OSError

The transfer ended short of the object's size.

Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def download(
    uri: Location,
    dest: Location,
    *,
    overwrite: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> Path:
    """Download the object at ``uri`` to the local file ``dest``.

    Fetched in 16 MiB byte ranges into a hidden ``.part`` sibling, each
    range pinned to the object's entity tag, checked against the
    object's size, then renamed into place; parent directories are made.

    Args:
        uri: The object.
        dest: The local file, or a directory (existing, or spelled with a
            trailing ``/``) to download into under the object's name.
        overwrite: Replace an existing file (default); ``False`` keeps it
            and skips the download.
        storage_options: Forwarded to `get_obstore`.

    Returns:
        The local path written (or kept).

    Raises:
        ValueError: ``dest`` is a remote URI (use `copy`).
        FileNotFoundError: No object at ``uri``.
        OSError: The transfer ended short of the object's size.
    """
    if local_path(dest) is None:
        raise ValueError(f"download: dest must be a local path; got {_r(dest)}.")
    return Path(copy(uri, dest, overwrite=overwrite, storage_options=storage_options))

geocloud.files.upload(path, uri, *, overwrite=True, storage_options=None)

Upload the local file path to uri (multipart when large).

Parameters:

Name Type Description Default
path Location

The local file.

required
uri Location

Destination; a trailing / keeps the file's name.

required
overwrite bool

Replace an existing object (default); False keeps it and skips the upload.

True
storage_options Mapping[str, Any] | None

Forwarded to get_obstore.

None

Returns:

Type Description
Location

The destination URI.

Raises:

Type Description
ValueError

path is not a local path (use copy).

FileNotFoundError

path does not exist.

Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def upload(
    path: Location,
    uri: Location,
    *,
    overwrite: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> Location:
    """Upload the local file ``path`` to ``uri`` (multipart when large).

    Args:
        path: The local file.
        uri: Destination; a trailing ``/`` keeps the file's name.
        overwrite: Replace an existing object (default); ``False`` keeps
            it and skips the upload.
        storage_options: Forwarded to `get_obstore`.

    Returns:
        The destination URI.

    Raises:
        ValueError: ``path`` is not a local path (use `copy`).
        FileNotFoundError: ``path`` does not exist.
    """
    if local_path(path) is None:
        raise ValueError(f"upload: path must be a local file; got {_r(path)}.")
    return copy(path, uri, overwrite=overwrite, storage_options=storage_options)

geocloud.files.copy(src, dst, *, overwrite=True, storage_options=None)

Copy one object, between any two locations.

Server-side within one bucket / container; a multipart upload from a local file; a ranged, atomic download to a local file; ranged reads feeding a multipart upload between two stores (see the module docstring).

Parameters:

Name Type Description Default
src Location

The object to copy (URI or local path).

required
dst Location

Where to put it. A trailing / (or an existing local directory) keeps the source's file name.

required
overwrite bool

Replace an existing destination (default). False leaves an existing destination alone and returns it.

True
storage_options Mapping[str, Any] | None

Forwarded to get_obstore for each remote end.

None

Returns:

Type Description
Location

The destination location (with the file name filled in).

Raises:

Type Description
ValueError

src or dst names a bucket root or a prefix (.../) rather than an object.

FileNotFoundError

No object at src.

Examples:

>>> import tempfile, pathlib
>>> root = pathlib.Path(tempfile.mkdtemp())
>>> write_bytes(root / "a.bin", b"abc")
>>> copy(root / "a.bin", f"{root}/out/") == root / "out" / "a.bin"
True
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def copy(
    src: Location,
    dst: Location,
    *,
    overwrite: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> Location:
    """Copy one object, between any two locations.

    Server-side within one bucket / container; a multipart upload from a
    local file; a ranged, atomic download to a local file; ranged reads
    feeding a multipart upload between two stores (see the module
    docstring).

    Args:
        src: The object to copy (URI or local path).
        dst: Where to put it. A trailing ``/`` (or an existing local
            directory) keeps the source's file name.
        overwrite: Replace an existing destination (default). ``False``
            leaves an existing destination alone and returns it.
        storage_options: Forwarded to `get_obstore` for each remote end.

    Returns:
        The destination location (with the file name filled in).

    Raises:
        ValueError: ``src`` or ``dst`` names a bucket root or a prefix
            (``.../``) rather than an object.
        FileNotFoundError: No object at ``src``.

    Examples:
        >>> import tempfile, pathlib
        >>> root = pathlib.Path(tempfile.mkdtemp())
        >>> write_bytes(root / "a.bin", b"abc")
        >>> copy(root / "a.bin", f"{root}/out/") == root / "out" / "a.bin"
        True
    """
    source = _resolve(src, storage_options)
    _require_object(source, src, "source")
    dst = _into(dst, source.name)
    dest = _resolve(dst, storage_options)
    _require_object(dest, dst, "destination")
    if not overwrite and exists(dst, storage_options=storage_options):
        return dst
    if dest.local:
        _stream_to_file(source, Path(dest.root) / dest.key)
    elif source.store is dest.store and source.root == dest.root:
        with_bucket_retry(lambda: obstore.copy(dest.store, source.key, dest.key))
    elif source.local:
        with_bucket_retry(
            lambda: obstore.put(dest.store, dest.key, Path(source.root) / source.key)
        )
    else:
        _run_coroutine_safely(_stream_between(source, dest))
    return dst

geocloud.files.sync(src, dst, *, overwrite=False, max_concurrency=8, storage_options=None)

Copy every object under src to the same relative path under dst.

Mirrors a prefix (or local directory) into another, in any direction. Objects already at the destination with the same size are skipped unless overwrite is set, so re-running a sync resumes it. Nothing is deleted at the destination.

Parameters:

Name Type Description Default
src Location

Source prefix or local directory.

required
dst Location

Destination prefix or local directory.

required
overwrite bool

Copy every object even when the destination has one of the same size.

False
max_concurrency int

Objects copied at once.

8
storage_options Mapping[str, Any] | None

Forwarded to get_obstore for each remote end.

None

Returns:

Type Description
list[Location]

The destination of every object copied (skipped ones excluded).

Raises:

Type Description
ValueError

max_concurrency < 1, or an end cannot be listed.

Examples:

>>> import tempfile, pathlib
>>> a, b = pathlib.Path(tempfile.mkdtemp()), pathlib.Path(tempfile.mkdtemp())
>>> write_bytes(a / "x" / "1.bin", b"1")
>>> len(sync(a, b)), len(sync(a, b))  # the second run skips it
(1, 0)
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def sync(
    src: Location,
    dst: Location,
    *,
    overwrite: bool = False,
    max_concurrency: int = 8,
    storage_options: Mapping[str, Any] | None = None,
) -> list[Location]:
    """Copy every object under ``src`` to the same relative path under ``dst``.

    Mirrors a prefix (or local directory) into another, in any direction.
    Objects already at the destination with the same size are skipped
    unless ``overwrite`` is set, so re-running a sync resumes it. Nothing
    is deleted at the destination.

    Args:
        src: Source prefix or local directory.
        dst: Destination prefix or local directory.
        overwrite: Copy every object even when the destination has one of
            the same size.
        max_concurrency: Objects copied at once.
        storage_options: Forwarded to `get_obstore` for each remote end.

    Returns:
        The destination of every object copied (skipped ones excluded).

    Raises:
        ValueError: ``max_concurrency < 1``, or an end cannot be listed.

    Examples:
        >>> import tempfile, pathlib
        >>> a, b = pathlib.Path(tempfile.mkdtemp()), pathlib.Path(tempfile.mkdtemp())
        >>> write_bytes(a / "x" / "1.bin", b"1")
        >>> len(sync(a, b)), len(sync(a, b))  # the second run skips it
        (1, 0)
    """
    if max_concurrency < 1:
        raise ValueError(f"max_concurrency must be >= 1; got {max_concurrency}.")
    source = _resolve(src, storage_options)
    _require_listable(source, src)
    present: dict[str, tuple[str, int]] = {}
    if not overwrite:
        dest = _resolve(dst, storage_options)
        _require_listable(dest, dst)
        present = _walk(dest)
    todo = [
        (source.child(key), _join(dst, rel))
        for rel, (key, size) in _walk(source).items()
        if overwrite or present.get(rel, ("", -1))[1] != size
    ]
    with ThreadPoolExecutor(max_workers=max_concurrency) as pool:
        return list(
            pool.map(lambda pair: copy(*pair, storage_options=storage_options), todo)
        )

geocloud.files.rm(uri, *, recursive=False, storage_options=None)

Delete the object at uri, or every object under it.

Parameters:

Name Type Description Default
uri Location

An object, or with recursive a prefix / local directory.

required
recursive bool

Delete everything under uri (batched requests). Empty local directories are left in place.

False
storage_options Mapping[str, Any] | None

Forwarded to get_obstore.

None

Returns:

Type Description
int

The number of objects deleted.

Raises:

Type Description
FileNotFoundError

Not recursive and no object at uri.

Examples:

>>> import tempfile, pathlib
>>> root = pathlib.Path(tempfile.mkdtemp())
>>> write_bytes(root / "a.bin", b"1"); write_bytes(root / "b.bin", b"2")
>>> rm(root, recursive=True)
2
Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def rm(
    uri: Location,
    *,
    recursive: bool = False,
    storage_options: Mapping[str, Any] | None = None,
) -> int:
    """Delete the object at ``uri``, or every object under it.

    Args:
        uri: An object, or with ``recursive`` a prefix / local directory.
        recursive: Delete everything under ``uri`` (batched requests).
            Empty local directories are left in place.
        storage_options: Forwarded to `get_obstore`.

    Returns:
        The number of objects deleted.

    Raises:
        FileNotFoundError: Not ``recursive`` and no object at ``uri``.

    Examples:
        >>> import tempfile, pathlib
        >>> root = pathlib.Path(tempfile.mkdtemp())
        >>> write_bytes(root / "a.bin", b"1"); write_bytes(root / "b.bin", b"2")
        >>> rm(root, recursive=True)
        2
    """
    target = _resolve(uri, storage_options)
    if not recursive:
        target.head()  # FileNotFoundError if absent
        with_bucket_retry(lambda: obstore.delete(target.store, target.key))
        return 1
    _require_listable(target, uri)
    keys = with_bucket_retry(
        lambda: [
            meta["path"]
            for page in obstore.list(target.store, prefix=_prefix(target))
            for meta in page
        ]
    )
    for start in range(0, len(keys), _DELETE_BATCH):
        batch = keys[start : start + _DELETE_BATCH]
        with_bucket_retry(lambda batch=batch: obstore.delete(target.store, batch))
    return len(keys)

geocloud.files.sign(uri, *, expires=timedelta(hours=1), method='GET', storage_options=None)

A pre-signed HTTPS URL for uri, valid for expires.

Anyone holding the URL can GET (or PUT) the object without credentials until it expires: hand it to curl, a browser, or GDAL (/vsicurl/<url>). The signature is computed locally from the store's credentials; no request is made.

Parameters:

Name Type Description Default
uri str

An s3://, gs:// or Azure object URI.

required
expires timedelta

Lifetime of the URL.

timedelta(hours=1)
method Literal['GET', 'PUT']

"GET" to read, "PUT" to let the holder upload.

'GET'
storage_options Mapping[str, Any] | None

Forwarded to get_obstore.

None

Raises:

Type Description
ValueError

The store cannot sign (local paths, plain http(s)://, hf://), or has no credentials to sign with.

Source code in packages/geotoolz-cloud/src/geocloud/_src/files.py
def sign(
    uri: str,
    *,
    expires: timedelta = timedelta(hours=1),
    method: Literal["GET", "PUT"] = "GET",
    storage_options: Mapping[str, Any] | None = None,
) -> str:
    """A pre-signed HTTPS URL for ``uri``, valid for ``expires``.

    Anyone holding the URL can ``GET`` (or ``PUT``) the object without
    credentials until it expires: hand it to ``curl``, a browser, or GDAL
    (``/vsicurl/<url>``). The signature is computed locally from the
    store's credentials; no request is made.

    Args:
        uri: An ``s3://``, ``gs://`` or Azure object URI.
        expires: Lifetime of the URL.
        method: ``"GET"`` to read, ``"PUT"`` to let the holder upload.
        storage_options: Forwarded to `get_obstore`.

    Raises:
        ValueError: The store cannot sign (local paths, plain
            ``http(s)://``, ``hf://``), or has no credentials to sign with.
    """
    if local_path(uri) is not None:
        raise ValueError(f"sign: {_r(uri)} is a local path; only cloud objects sign.")
    target = _resolve(uri, storage_options)
    try:
        return obstore.sign(target.store, method, target.key, expires)
    except (ValueError, TypeError) as exc:
        raise ValueError(
            f"sign: cannot pre-sign {_r(uri)} — only s3://, gs:// "
            f"and Azure stores with credentials sign URLs ({exc})."
        ) from exc

geocloud.hdf

HDF5 / NetCDF / HDF4 from any location, and CF decoding.

geocloud.hdf.read_netcdf(source, variable, *, group=None, indexes=None, decode_cf=True, use_cf_grid_mapping=True, storage_options=None)

Read one variable of a NetCDF-3 / NetCDF-4 file as a geoarray.GeoArray.

netCDF4 opens a local copy (geocloud.cache.localize; a local path is used in place). With decode_cf the CF mask / scale_factor / add_offset are applied and masked pixels become the fill (NaN for decoded floats). The CRS comes from the variable's CF grid_mapping; the transform from GDAL's GeoTransform attribute, or else from evenly spaced 1-D coordinate variables of the last two dimensions (CF x / y or lon / lat pixel centres). When neither is there the transform is the identity and a UserWarning says why.

Parameters:

Name Type Description Default
source Location

A URI in any form the pool accepts, or a local path.

required
variable str

Variable name within group.

required
group str | None

Slash-separated NetCDF group path.

None
indexes list[int] | None

1-based band indexes along the leading variable axis.

None
decode_cf bool

Apply CF masking and scale / offset.

True
use_cf_grid_mapping bool

Recover the CRS from grid_mapping.

True
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore.

None

Returns:

Type Description
GeoArray

The variable (..., H, W), its attributes under attrs["attrs"];

GeoArray

a declared fill its dtype cannot hold becomes fill_value=None.

Dims are named from the variable's CF dims

the last two are

GeoArray

y x, a time dim is time (with a TimeAxis for CF since

units), a vertical one is ``level`` (with a `VerticalAxis`

CF

GeoArray

depth is Vertical(kind="depth", positive="down")), and any

GeoArray

other keeps its NetCDF name.

Raises:

Type Description
ImportError

netCDF4 is missing (the [netcdf] extra).

KeyError

No such group or variable.

ValueError

indexes do not fit the variable, or it is not 2-D to 4-D.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def read_netcdf(
    source: Location,
    variable: str,
    *,
    group: str | None = None,
    indexes: list[int] | None = None,
    decode_cf: bool = True,
    use_cf_grid_mapping: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> GeoArray:
    """Read one variable of a NetCDF-3 / NetCDF-4 file as a `geoarray.GeoArray`.

    netCDF4 opens a local copy (`geocloud.cache.localize`; a local path is
    used in place). With ``decode_cf`` the CF mask / ``scale_factor`` /
    ``add_offset`` are applied and masked pixels become the fill (``NaN``
    for decoded floats). The CRS comes from the variable's CF
    ``grid_mapping``; the transform from GDAL's ``GeoTransform`` attribute,
    or else from evenly spaced 1-D coordinate variables of the last two
    dimensions (CF ``x`` / ``y`` or ``lon`` / ``lat`` pixel centres). When
    neither is there the transform is the identity and a `UserWarning`
    says why.

    Args:
        source: A URI in any form the pool accepts, or a local path.
        variable: Variable name within ``group``.
        group: Slash-separated NetCDF group path.
        indexes: 1-based band indexes along the leading variable axis.
        decode_cf: Apply CF masking and scale / offset.
        use_cf_grid_mapping: Recover the CRS from ``grid_mapping``.
        storage_options: Forwarded to `geocloud.store.get_obstore`.

    Returns:
        The variable ``(..., H, W)``, its attributes under ``attrs["attrs"]``;
        a declared fill its dtype cannot hold becomes ``fill_value=None``.
        Dims are named from the variable's CF dims: the last two are
        ``y x``, a time dim is ``time`` (with a `TimeAxis` for CF ``since``
        units), a vertical one is ``level`` (with a `VerticalAxis`: CF
        ``depth`` is ``Vertical(kind="depth", positive="down")``), and any
        other keeps its NetCDF name.

    Raises:
        ImportError: netCDF4 is missing (the ``[netcdf]`` extra).
        KeyError: No such group or variable.
        ValueError: ``indexes`` do not fit the variable, or it is not 2-D
            to 4-D.
    """
    netcdf4 = _require("netCDF4", "netcdf", "geocloud.hdf.read_netcdf")
    with netcdf4.Dataset(_localize(source, storage_options), "r") as root:
        holder = _netcdf_group(root, group)
        var = holder.variables[variable]
        var.set_auto_maskandscale(decode_cf)
        attrs = _plain(dict(var.__dict__))
        values = select_indexes(var[:], indexes)
        fill_value = fill_value_from_attrs(attrs)
        if np.ma.isMaskedArray(values):
            # Decoded (scaled) floats are NaN-filled, so NaN is the
            # sentinel the returned tensor actually carries.
            if values.dtype.kind == "f":
                fill_value = np.nan
            elif fill_value is None:
                # Masked against netCDF's default fill: that value marks them.
                fill_value = np.asarray(values.fill_value).item()
            values = values.filled(fill_value)
        crs, mapping = _netcdf_crs(holder, var, use_cf_grid_mapping)
        dims, coords = _cf_dims(holder, var, indexes)
        return _geoarray(
            values,
            crs=crs,
            fill_value=fill_value,
            attrs={"attrs": attrs},
            transform=_netcdf_transform(holder, var, mapping, crs),
            dims=dims,
            coords=coords,
        )

geocloud.hdf.read_hdf(source, dataset, *, indexes=None, metadata_groups=None, storage_options=None)

Read one dataset of an HDF5 or HDF4 / HDF-EOS file as a geoarray.GeoArray.

The format is told by the file signature. HDF5 is read through h5py with ranged reads (open_hdf5), only the requested bands off disk; HDF4 through pyhdf on a local copy (geocloud.cache.localize). The result has an identity transform. A swath product carries its georeferencing in latitude / longitude datasets on the same pixel grid: read each with its own read_hdf call (attrs are frozen and hashable, so they never hold 2-D arrays).

Parameters:

Name Type Description Default
source Location

A URI in any form the pool accepts, or a local path.

required
dataset str

Dataset path inside the file.

required
indexes list[int] | None

1-based band indexes along the leading dataset axis.

None
metadata_groups list[str] | None

HDF5 group paths whose attributes are copied into attrs["metadata"].

None
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore.

None

Returns:

Type Description
GeoArray

The dataset (..., H, W), its attributes under attrs["attrs"]

GeoArray

and its declared fill (else None) as the carrier's fill_value

GeoArray

(None when the dataset's dtype cannot hold the declared fill).

Raises:

Type Description
ImportError

h5py ([hdf5]) or pyhdf ([hdf4]) is missing.

ValueError

The file is neither HDF5 nor HDF4, indexes do not fit the dataset, or the dataset is not 2-D to 4-D.

KeyError

No such dataset.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def read_hdf(
    source: Location,
    dataset: str,
    *,
    indexes: list[int] | None = None,
    metadata_groups: list[str] | None = None,
    storage_options: Mapping[str, Any] | None = None,
) -> GeoArray:
    """Read one dataset of an HDF5 or HDF4 / HDF-EOS file as a `geoarray.GeoArray`.

    The format is told by the file signature. HDF5 is read through h5py
    with ranged reads (`open_hdf5`), only the requested bands off disk;
    HDF4 through pyhdf on a local copy (`geocloud.cache.localize`). The
    result has an identity transform. A swath product carries its
    georeferencing in latitude / longitude datasets on the same pixel grid:
    read each with its own ``read_hdf`` call (attrs are frozen and
    hashable, so they never hold 2-D arrays).

    Args:
        source: A URI in any form the pool accepts, or a local path.
        dataset: Dataset path inside the file.
        indexes: 1-based band indexes along the leading dataset axis.
        metadata_groups: HDF5 group paths whose attributes are copied into
            ``attrs["metadata"]``.
        storage_options: Forwarded to `geocloud.store.get_obstore`.

    Returns:
        The dataset ``(..., H, W)``, its attributes under ``attrs["attrs"]``
        and its declared fill (else ``None``) as the carrier's ``fill_value``
        (``None`` when the dataset's dtype cannot hold the declared fill).

    Raises:
        ImportError: h5py (``[hdf5]``) or pyhdf (``[hdf4]``) is missing.
        ValueError: The file is neither HDF5 nor HDF4, ``indexes`` do
            not fit the dataset, or the dataset is not 2-D to 4-D.
        KeyError: No such dataset.
    """
    signature = _signature(source, storage_options)
    if signature.startswith(HDF5_SIGNATURE):
        return _read_hdf5(source, dataset, indexes, metadata_groups, storage_options)
    if signature.startswith(HDF4_SIGNATURE):
        return _read_hdf4(source, dataset, indexes, storage_options)
    raise ValueError(f"{os.fspath(source)!r} is neither an HDF5 nor an HDF4 file.")

geocloud.hdf.open_hdf5(source, *, storage_options=None)

An open h5py.File on source, read-only.

A local path is opened directly; a remote URI through geocloud.files.open, so h5py fetches only the byte ranges it needs (the header, then the chunks it reads); an open binary file object is used as is.

Parameters:

Name Type Description Default
source HdfSource

A URI in any form the pool accepts, a local path, or an open binary file.

required
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore.

None

Yields:

Type Description
Any

The h5py.File; it (and the remote handle) close on exit.

Raises:

Type Description
ImportError

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

Examples:

>>> import tempfile, pathlib, h5py
>>> path = pathlib.Path(tempfile.mkdtemp()) / "a.h5"
>>> with h5py.File(path, "w") as f:
...     f["x"] = [1, 2, 3]
>>> with open_hdf5(path) as f:
...     f["x"][1]
np.int64(2)
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
@contextmanager
def open_hdf5(
    source: HdfSource, *, storage_options: Mapping[str, Any] | None = None
) -> Iterator[Any]:
    """An open ``h5py.File`` on ``source``, read-only.

    A local path is opened directly; a remote URI through
    `geocloud.files.open`, so h5py fetches only the byte ranges it needs
    (the header, then the chunks it reads); an open binary file object is
    used as is.

    Args:
        source: A URI in any form the pool accepts, a local path, or an
            open binary file.
        storage_options: Forwarded to `geocloud.store.get_obstore`.

    Yields:
        The ``h5py.File``; it (and the remote handle) close on exit.

    Raises:
        ImportError: h5py is not installed (the ``[hdf5]`` extra).

    Examples:
        >>> import tempfile, pathlib, h5py
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "a.h5"
        >>> with h5py.File(path, "w") as f:
        ...     f["x"] = [1, 2, 3]
        >>> with open_hdf5(path) as f:
        ...     f["x"][1]
        np.int64(2)
    """
    h5py = _require("h5py", "hdf5", "geocloud.hdf.open_hdf5")
    if hasattr(source, "read"):
        with h5py.File(source, "r") as f:
            yield f
        return
    local = local_path(source)  # type: ignore[arg-type]
    if local is not None:
        with h5py.File(local, "r") as f:
            yield f
        return
    from geocloud._src.files import open as open_object

    handle = _RangedFile(
        open_object(source, "rb", storage_options=storage_options)  # type: ignore[arg-type]
    )
    try:
        with h5py.File(handle, "r") as f:
            yield f
    finally:
        handle.close()

geocloud.hdf.PackedVariable dataclass

How to decode one CF-packed variable.

Attributes:

Name Type Description
name str

Variable name in the file.

storage dtype

The integer / float dtype pixels are interpreted as (the unsigned twin of the stored dtype when _Unsigned).

fill int | float | None

_FillValue in storage terms, or None.

scale float | None

scale_factor (None when unpacked).

offset float | None

add_offset (None when unpacked).

units str

CF units ("" when absent).

long_name str

CF long_name ("" when absent).

Examples:

>>> v = PackedVariable("t", np.dtype("u2"), 65535, 0.01, 200.0, "K", "")
>>> v.decode(np.array([0, 100, 65535], dtype="u2")).tolist()
[200.0, 201.0, nan]
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
@dataclass(frozen=True)
class PackedVariable:
    """How to decode one CF-packed variable.

    Attributes:
        name: Variable name in the file.
        storage: The integer / float dtype pixels are *interpreted* as
            (the unsigned twin of the stored dtype when ``_Unsigned``).
        fill: ``_FillValue`` in ``storage`` terms, or ``None``.
        scale: ``scale_factor`` (``None`` when unpacked).
        offset: ``add_offset`` (``None`` when unpacked).
        units: CF ``units`` (``""`` when absent).
        long_name: CF ``long_name`` (``""`` when absent).

    Examples:
        >>> v = PackedVariable("t", np.dtype("u2"), 65535, 0.01, 200.0, "K", "")
        >>> v.decode(np.array([0, 100, 65535], dtype="u2")).tolist()
        [200.0, 201.0, nan]
    """

    name: str
    storage: np.dtype
    fill: int | float | None
    scale: float | None
    offset: float | None
    units: str
    long_name: str

    @classmethod
    def from_file(cls, f: Any, name: str) -> PackedVariable:
        """Read the packing attributes of ``name`` from an open file."""
        var = f[name]
        storage = np.dtype(var.dtype)
        if attr(var, "_Unsigned") == "true" and storage.kind == "i":
            storage = np.dtype(f"u{storage.itemsize}")
        fill = None
        if "_FillValue" in var.attrs:
            raw_fill = np.asarray(var.attrs["_FillValue"]).reshape(-1)[:1]
            fill = raw_fill.astype(var.dtype).view(storage).item()
        scale = attr(var, "scale_factor")
        offset = attr(var, "add_offset")
        return cls(
            name=name,
            storage=storage,
            fill=fill,
            scale=None if scale is None else float(scale),
            offset=None if offset is None else float(offset),
            units=str(attr(var, "units", "")),
            long_name=str(attr(var, "long_name", "")),
        )

    @property
    def is_packed(self) -> bool:
        """Whether decoding changes values (scale / offset applied)."""
        return self.scale is not None or self.offset is not None

    @property
    def is_categorical(self) -> bool:
        """An unpacked integer variable: masks, flags, class codes."""
        return not self.is_packed and self.storage.kind in "iub"

    def raw(self, values: np.ndarray) -> np.ndarray:
        """Stored values reinterpreted in ``storage`` (``_Unsigned`` view)."""
        values = np.asarray(values)
        if values.dtype == self.storage:
            return values
        return np.ascontiguousarray(values).view(self.storage)

    def decode(self, values: np.ndarray) -> np.ndarray:
        """Physical values as ``float32``; fill pixels become ``NaN``."""
        raw = self.raw(values)
        out = raw.astype(np.float32)
        if self.scale is not None:
            out *= np.float32(self.scale)
        if self.offset is not None:
            out += np.float32(self.offset)
        if self.fill is not None:
            out[raw == self.fill] = np.nan
        return out

is_categorical property

An unpacked integer variable: masks, flags, class codes.

is_packed property

Whether decoding changes values (scale / offset applied).

decode(values)

Physical values as float32; fill pixels become NaN.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def decode(self, values: np.ndarray) -> np.ndarray:
    """Physical values as ``float32``; fill pixels become ``NaN``."""
    raw = self.raw(values)
    out = raw.astype(np.float32)
    if self.scale is not None:
        out *= np.float32(self.scale)
    if self.offset is not None:
        out += np.float32(self.offset)
    if self.fill is not None:
        out[raw == self.fill] = np.nan
    return out

from_file(f, name) classmethod

Read the packing attributes of name from an open file.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
@classmethod
def from_file(cls, f: Any, name: str) -> PackedVariable:
    """Read the packing attributes of ``name`` from an open file."""
    var = f[name]
    storage = np.dtype(var.dtype)
    if attr(var, "_Unsigned") == "true" and storage.kind == "i":
        storage = np.dtype(f"u{storage.itemsize}")
    fill = None
    if "_FillValue" in var.attrs:
        raw_fill = np.asarray(var.attrs["_FillValue"]).reshape(-1)[:1]
        fill = raw_fill.astype(var.dtype).view(storage).item()
    scale = attr(var, "scale_factor")
    offset = attr(var, "add_offset")
    return cls(
        name=name,
        storage=storage,
        fill=fill,
        scale=None if scale is None else float(scale),
        offset=None if offset is None else float(offset),
        units=str(attr(var, "units", "")),
        long_name=str(attr(var, "long_name", "")),
    )

raw(values)

Stored values reinterpreted in storage (_Unsigned view).

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def raw(self, values: np.ndarray) -> np.ndarray:
    """Stored values reinterpreted in ``storage`` (``_Unsigned`` view)."""
    values = np.asarray(values)
    if values.dtype == self.storage:
        return values
    return np.ascontiguousarray(values).view(self.storage)

geocloud.hdf.attr(obj, name, default=None)

An HDF5 attribute as a plain Python scalar / str (arrays kept).

Examples:

>>> class V:
...     attrs = {"units": np.bytes_(b"K"), "scale": np.array([0.5])}
>>> attr(V, "units"), attr(V, "scale"), attr(V, "nope", 1)
('K', 0.5, 1)
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def attr(obj: Any, name: str, default: Any = None) -> Any:
    """An HDF5 attribute as a plain Python scalar / ``str`` (arrays kept).

    Examples:
        >>> class V:
        ...     attrs = {"units": np.bytes_(b"K"), "scale": np.array([0.5])}
        >>> attr(V, "units"), attr(V, "scale"), attr(V, "nope", 1)
        ('K', 0.5, 1)
    """
    if name not in obj.attrs:
        return default
    value = obj.attrs[name]
    if isinstance(value, np.ndarray):
        value = value.item() if value.size == 1 else value
    if isinstance(value, bytes | np.bytes_):
        value = value.decode("utf-8")
    elif isinstance(value, np.generic):
        value = value.item()
    return value

geocloud.hdf.scalar(f, name, *, fill=None)

A scalar variable as float; NaN when absent or filled.

The fill is the variable's own _FillValue, or fill when the product documents one the file does not declare.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def scalar(f: Any, name: str, *, fill: float | None = None) -> float:
    """A scalar variable as ``float``; ``NaN`` when absent or filled.

    The fill is the variable's own ``_FillValue``, or ``fill`` when the
    product documents one the file does not declare.
    """
    if name not in f:
        return float("nan")
    var = f[name]
    value = float(np.asarray(var[()]).reshape(-1)[0])
    declared = attr(var, "_FillValue")
    fills = {v for v in (declared, fill) if v is not None}
    return float("nan") if value in fills else value

geocloud.hdf.unpacked(f, name)

A packed variable (typically a coordinate) decoded to float64.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def unpacked(f: Any, name: str) -> np.ndarray:
    """A packed variable (typically a coordinate) decoded to ``float64``."""
    var = f[name]
    raw = np.asarray(var[()], dtype=np.float64)
    scale = float(attr(var, "scale_factor", 1.0))
    return raw * scale + float(attr(var, "add_offset", 0.0))

geocloud.hdf.time_attr(obj, name)

An ISO-8601 attribute (time_coverage_start, …) as a datetime.

Returns None when the attribute is absent or not a timestamp.

Examples:

>>> class V:
...     attrs = {"t": b"2024-06-01T12:00:00"}
>>> time_attr(V, "t")
datetime.datetime(2024, 6, 1, 12, 0)
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def time_attr(obj: Any, name: str) -> datetime | None:
    """An ISO-8601 attribute (``time_coverage_start``, …) as a ``datetime``.

    Returns ``None`` when the attribute is absent or not a timestamp.

    Examples:
        >>> class V:
        ...     attrs = {"t": b"2024-06-01T12:00:00"}
        >>> time_attr(V, "t")
        datetime.datetime(2024, 6, 1, 12, 0)
    """
    value = attr(obj, name)
    try:
        return None if value is None else datetime.fromisoformat(str(value))
    except ValueError:
        return None

geocloud.hdf.grid_variables(f, shape)

Names of the file's top-level variables of shape shape.

Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def grid_variables(f: Any, shape: tuple[int, int]) -> tuple[str, ...]:
    """Names of the file's top-level variables of shape ``shape``."""
    # Groups carry no ``shape``; datasets do.
    return tuple(
        name
        for name, var in f.items()
        if tuple(getattr(var, "shape", ()) or ()) == shape
    )

geocloud.hdf.fill_value_from_attrs(attrs)

The scalar fill value declared in attrs, or None when none is.

Looks up _FillValue, missing_value, fill_value and nodata in that order. Size-1 arrays / lists (how netCDF4 / xarray write HDF5 attributes) are unwrapped; multi-element values are skipped, since a carrier's fill_value must be a scalar.

Examples:

>>> fill_value_from_attrs({"_FillValue": [-9999]})
-9999
>>> fill_value_from_attrs({}) is None
True
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def fill_value_from_attrs(attrs: Mapping[str, Any]) -> Any:
    """The scalar fill value declared in ``attrs``, or ``None`` when none is.

    Looks up ``_FillValue``, ``missing_value``, ``fill_value`` and
    ``nodata`` in that order. Size-1 arrays / lists (how netCDF4 / xarray
    write HDF5 attributes) are unwrapped; multi-element values are skipped,
    since a carrier's ``fill_value`` must be a scalar.

    Examples:
        >>> fill_value_from_attrs({"_FillValue": [-9999]})
        -9999
        >>> fill_value_from_attrs({}) is None
        True
    """
    for name in ("_FillValue", "missing_value", "fill_value", "nodata"):
        if name not in attrs:
            continue
        value = attrs[name]
        if isinstance(value, list | tuple | np.ndarray):
            flat = np.ravel(np.asarray(value))
            if flat.size != 1:
                continue
            value = flat[0].item()
        return value
    return None

geocloud.hdf.affine_from_geotransform(geotransform)

Parse a GDAL GeoTransform attribute into an Affine.

Parameters:

Name Type Description Default
geotransform Any

Six whitespace-separated numbers "x0 dx rx y0 ry dy" (GDAL order), or None.

required

Returns:

Type Description
Affine

The affine, or the identity when geotransform is None or

Affine

does not hold exactly six numbers.

Examples:

>>> affine_from_geotransform("100 10 0 200 0 -10")
Affine(10.0, 0.0, 100.0,
       0.0, -10.0, 200.0)
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def affine_from_geotransform(geotransform: Any) -> Affine:
    """Parse a GDAL ``GeoTransform`` attribute into an ``Affine``.

    Args:
        geotransform: Six whitespace-separated numbers
            ``"x0 dx rx y0 ry dy"`` (GDAL order), or ``None``.

    Returns:
        The affine, or the identity when ``geotransform`` is ``None`` or
        does not hold exactly six numbers.

    Examples:
        >>> affine_from_geotransform("100 10 0 200 0 -10")
        Affine(10.0, 0.0, 100.0,
               0.0, -10.0, 200.0)
    """
    if geotransform is None:
        return Affine.identity()
    parts = [float(part) for part in str(geotransform).split()]
    if len(parts) != 6:
        return Affine.identity()
    return Affine.from_gdal(*parts)

geocloud.hdf.select_indexes(values, indexes)

Select 1-based band indexes along the leading axis of values.

Parameters:

Name Type Description Default
values Any

Array-like (C, ...) stack, or a 2-D single-layer map.

required
indexes list[int] | None

1-based band numbers (rasterio convention), or None for every band. A 2-D map accepts only [1] (a no-op).

required

Returns:

Type Description
ndarray

The selected bands (values itself when indexes is None).

Raises:

Type Description
ValueError

An index is not positive, or values has no band axis and indexes is not [1].

Examples:

>>> select_indexes(np.arange(12).reshape(3, 2, 2), [3, 1])[:, 0, 0]
array([8, 0])
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def select_indexes(values: Any, indexes: list[int] | None) -> np.ndarray:
    """Select 1-based band ``indexes`` along the leading axis of ``values``.

    Args:
        values: Array-like ``(C, ...)`` stack, or a 2-D single-layer map.
        indexes: 1-based band numbers (rasterio convention), or ``None``
            for every band. A 2-D map accepts only ``[1]`` (a no-op).

    Returns:
        The selected bands (``values`` itself when ``indexes`` is ``None``).

    Raises:
        ValueError: An index is not positive, or ``values`` has no band
            axis and ``indexes`` is not ``[1]``.

    Examples:
        >>> select_indexes(np.arange(12).reshape(3, 2, 2), [3, 1])[:, 0, 0]
        array([8, 0])
    """
    array = np.asanyarray(values)
    if indexes is None:
        return array
    zero_based = [index - 1 for index in indexes]
    if any(index < 0 for index in zero_based):
        raise ValueError("indexes are 1-based and must be positive.")
    if array.ndim < 3:
        # A non-band dataset is a single-layer raster: indexes=[1] selects
        # the only layer and is a no-op; anything else is invalid.
        if zero_based != [0]:
            raise ValueError("indexes require a dataset with a leading band axis.")
        return array
    return np.take(array, zero_based, axis=0)

geocloud.hdf.read_indexes(source, indexes)

Read 1-based band indexes from a lazily sliced dataset.

Same contract as select_indexes, but source is sliced (an h5py-style hyperslab read) instead of materialised first, so requesting one band reads only that band. h5py only fancy-indexes the leading axis with increasing indices, so the read is sorted and then reordered.

Parameters:

Name Type Description Default
source Any

Dataset supporting source[...] and source[list_of_ints] (e.g. h5py.Dataset).

required
indexes list[int] | None

1-based band numbers, or None for every band.

required

Returns:

Type Description
ndarray

The selected bands.

Raises:

Type Description
ValueError

See select_indexes.

Examples:

>>> read_indexes(np.arange(12).reshape(3, 2, 2), [3, 1])[:, 0, 0]
array([8, 0])
Source code in packages/geotoolz-cloud/src/geocloud/_src/hdf.py
def read_indexes(source: Any, indexes: list[int] | None) -> np.ndarray:
    """Read 1-based band ``indexes`` from a lazily sliced dataset.

    Same contract as `select_indexes`, but ``source`` is sliced (an
    h5py-style hyperslab read) instead of materialised first, so requesting
    one band reads only that band. h5py only fancy-indexes the leading axis
    with increasing indices, so the read is sorted and then reordered.

    Args:
        source: Dataset supporting ``source[...]`` and
            ``source[list_of_ints]`` (e.g. ``h5py.Dataset``).
        indexes: 1-based band numbers, or ``None`` for every band.

    Returns:
        The selected bands.

    Raises:
        ValueError: See `select_indexes`.

    Examples:
        >>> read_indexes(np.arange(12).reshape(3, 2, 2), [3, 1])[:, 0, 0]
        array([8, 0])
    """
    if indexes is None:
        return np.asanyarray(source[...])
    zero_based = [index - 1 for index in indexes]
    if any(index < 0 for index in zero_based):
        raise ValueError("indexes are 1-based and must be positive.")
    ndim = getattr(source, "ndim", None)
    if ndim is None:
        ndim = np.asarray(source.shape).size
    if ndim < 3:
        if zero_based != [0]:
            raise ValueError("indexes require a dataset with a leading band axis.")
        return np.asanyarray(source[...])
    order = np.argsort(zero_based)
    sorted_indexes = [zero_based[i] for i in order]
    sliced = np.asanyarray(source[sorted_indexes])
    if list(order) == list(range(len(order))):
        return sliced
    return sliced[np.argsort(order)]

geocloud.cache

Complete local copies of remote objects.

geocloud.cache.localize(uri, *, cache=None, storage_options=None)

A local file holding uri: in place when local, else a cached copy.

For readers that need a real file (HDF4, memory-mapped binaries, GDAL drivers without /vsi*/).

Parameters:

Name Type Description Default
uri Location

A URI in any form the pool accepts, or a local path.

required
cache LocalCache | None

The cache to use; None uses the default LocalCache.

None
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore.

None

Returns:

Type Description
Path

The local path.

Raises:

Type Description
FileNotFoundError

Nothing at uri.

Examples:

>>> import tempfile, pathlib
>>> path = pathlib.Path(tempfile.mkdtemp()) / "a.bin"
>>> _ = path.write_bytes(b"x")
>>> localize(path) == path
True
Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def localize(
    uri: Location,
    *,
    cache: LocalCache | None = None,
    storage_options: Mapping[str, Any] | None = None,
) -> Path:
    """A local file holding ``uri``: in place when local, else a cached copy.

    For readers that need a real file (HDF4, memory-mapped binaries, GDAL
    drivers without ``/vsi*/``).

    Args:
        uri: A URI in any form the pool accepts, or a local path.
        cache: The cache to use; ``None`` uses the default `LocalCache`.
        storage_options: Forwarded to `geocloud.store.get_obstore`.

    Returns:
        The local path.

    Raises:
        FileNotFoundError: Nothing at ``uri``.

    Examples:
        >>> import tempfile, pathlib
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "a.bin"
        >>> _ = path.write_bytes(b"x")
        >>> localize(path) == path
        True
    """
    return (cache or LocalCache()).fetch(uri, storage_options=storage_options)

geocloud.cache.LocalCache dataclass

A directory of complete local copies of remote objects.

Files land at {root}/{key[:2]}/{key}{ext}, where key is the SHA-256 of cache_key of the URI. The two-letter prefix keeps any one directory under a few thousand entries.

Parameters:

Name Type Description Default
root PathLike[str] | str | None

The cache directory. None resolves $GEOCLOUD_CACHE when set, else ~/.cache/geocloud (lazily, so a process can set the variable before its first fetch).

None
ttl_days int | None

Lifetime of a cached copy. Older copies are fetched again on their next use, and prune deletes them. None caches forever.

None
timeout float | None

Per-request timeout, in seconds, for the downloads. Objects move in 16 MiB ranges, one request each, so this bounds one range, not a whole file. None keeps the client's default (30 s).

60.0

Examples:

>>> import tempfile, pathlib
>>> cache = LocalCache(root=tempfile.mkdtemp())
>>> cache.path_for("s3://bucket/a.tif").suffix
'.tif'
Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
@dataclasses.dataclass
class LocalCache:
    """A directory of complete local copies of remote objects.

    Files land at ``{root}/{key[:2]}/{key}{ext}``, where ``key`` is the
    SHA-256 of `cache_key` of the URI. The two-letter prefix keeps any one
    directory under a few thousand entries.

    Args:
        root: The cache directory. ``None`` resolves ``$GEOCLOUD_CACHE``
            when set, else ``~/.cache/geocloud`` (lazily, so a process
            can set the variable before its first fetch).
        ttl_days: Lifetime of a cached copy. Older copies are fetched
            again on their next use, and `prune` deletes them. ``None``
            caches forever.
        timeout: Per-request timeout, in seconds, for the downloads.
            Objects move in 16 MiB ranges, one request each, so this
            bounds one range, not a whole file. ``None`` keeps the
            client's default (30 s).

    Examples:
        >>> import tempfile, pathlib
        >>> cache = LocalCache(root=tempfile.mkdtemp())
        >>> cache.path_for("s3://bucket/a.tif").suffix
        '.tif'
    """

    root: os.PathLike[str] | str | None = None
    ttl_days: int | None = None
    timeout: float | None = 60.0

    def resolve_root(self) -> Path:
        """The cache directory, created on first use."""
        if self.root is not None:
            root = Path(self.root)
        else:
            env = os.environ.get("GEOCLOUD_CACHE")
            root = Path(env) if env else Path.home() / _DEFAULT_SUBDIR
        root.mkdir(parents=True, exist_ok=True)
        return root

    def path_for(self, uri: str) -> Path:
        """The slot ``uri`` is cached in (whether or not it is there yet)."""
        digest = hashlib.sha256(cache_key(uri).encode("utf-8")).hexdigest()
        return self.resolve_root() / digest[:2] / f"{digest}{_suffix(uri)}"

    def is_fresh(self, path: Path) -> bool:
        """Whether the cached ``path`` exists and is within ``ttl_days``."""
        if not path.exists():
            return False
        return self.ttl_days is None or not self._expired(path)

    def fetch(
        self,
        uri: Location,
        *,
        storage_options: Mapping[str, Any] | None = None,
    ) -> Path:
        """A complete local file holding ``uri``'s bytes.

        A local path (or ``file://`` URI) is returned in place: nothing is
        copied. A remote URI is served from the cache when fresh, else
        downloaded with `geocloud.files.download` into its slot.

        Args:
            uri: A URI in any form the pool accepts, or a local path.
            storage_options: Forwarded to `geocloud.store.get_obstore`,
                over the registered credentials and ``timeout``.

        Returns:
            The local path.

        Raises:
            FileNotFoundError: A local path that does not exist, or no
                object at a remote URI.
        """
        local = local_path(uri)
        if local is not None:
            if not local.exists():
                raise FileNotFoundError(f"localize: no local file at {str(uri)!r}")
            return local
        uri = str(uri)
        dest = self.path_for(uri)
        if self.is_fresh(dest):
            return dest
        from geocloud import files  # the public module, so tests can stand in

        options = dict(storage_options or {})
        if self.timeout is not None:
            client = dict(options.get("client_options") or {})
            client.setdefault("timeout", timedelta(seconds=self.timeout))
            options["client_options"] = client
        files.download(uri, dest, storage_options=options or None)
        return dest

    def prune(self) -> int:
        """Delete expired copies and abandoned partial downloads.

        Returns:
            The number of files removed. Without ``ttl_days`` only
            partial downloads (``*.part``) are removed.
        """
        removed = 0
        for path in self.resolve_root().glob("*/*"):
            if not path.is_file():
                continue
            if _PART_NAME.match(path.name) or (
                self.ttl_days is not None and self._expired(path)
            ):
                with contextlib.suppress(OSError):
                    path.unlink()
                    removed += 1
        return removed

    def _expired(self, path: Path) -> bool:
        assert self.ttl_days is not None
        age = datetime.now(tz=UTC) - datetime.fromtimestamp(
            path.stat().st_mtime, tz=UTC
        )
        return age >= timedelta(days=self.ttl_days)

fetch(uri, *, storage_options=None)

A complete local file holding uri's bytes.

A local path (or file:// URI) is returned in place: nothing is copied. A remote URI is served from the cache when fresh, else downloaded with geocloud.files.download into its slot.

Parameters:

Name Type Description Default
uri Location

A URI in any form the pool accepts, or a local path.

required
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore, over the registered credentials and timeout.

None

Returns:

Type Description
Path

The local path.

Raises:

Type Description
FileNotFoundError

A local path that does not exist, or no object at a remote URI.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def fetch(
    self,
    uri: Location,
    *,
    storage_options: Mapping[str, Any] | None = None,
) -> Path:
    """A complete local file holding ``uri``'s bytes.

    A local path (or ``file://`` URI) is returned in place: nothing is
    copied. A remote URI is served from the cache when fresh, else
    downloaded with `geocloud.files.download` into its slot.

    Args:
        uri: A URI in any form the pool accepts, or a local path.
        storage_options: Forwarded to `geocloud.store.get_obstore`,
            over the registered credentials and ``timeout``.

    Returns:
        The local path.

    Raises:
        FileNotFoundError: A local path that does not exist, or no
            object at a remote URI.
    """
    local = local_path(uri)
    if local is not None:
        if not local.exists():
            raise FileNotFoundError(f"localize: no local file at {str(uri)!r}")
        return local
    uri = str(uri)
    dest = self.path_for(uri)
    if self.is_fresh(dest):
        return dest
    from geocloud import files  # the public module, so tests can stand in

    options = dict(storage_options or {})
    if self.timeout is not None:
        client = dict(options.get("client_options") or {})
        client.setdefault("timeout", timedelta(seconds=self.timeout))
        options["client_options"] = client
    files.download(uri, dest, storage_options=options or None)
    return dest

is_fresh(path)

Whether the cached path exists and is within ttl_days.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def is_fresh(self, path: Path) -> bool:
    """Whether the cached ``path`` exists and is within ``ttl_days``."""
    if not path.exists():
        return False
    return self.ttl_days is None or not self._expired(path)

path_for(uri)

The slot uri is cached in (whether or not it is there yet).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def path_for(self, uri: str) -> Path:
    """The slot ``uri`` is cached in (whether or not it is there yet)."""
    digest = hashlib.sha256(cache_key(uri).encode("utf-8")).hexdigest()
    return self.resolve_root() / digest[:2] / f"{digest}{_suffix(uri)}"

prune()

Delete expired copies and abandoned partial downloads.

Returns:

Type Description
int

The number of files removed. Without ttl_days only

int

partial downloads (*.part) are removed.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def prune(self) -> int:
    """Delete expired copies and abandoned partial downloads.

    Returns:
        The number of files removed. Without ``ttl_days`` only
        partial downloads (``*.part``) are removed.
    """
    removed = 0
    for path in self.resolve_root().glob("*/*"):
        if not path.is_file():
            continue
        if _PART_NAME.match(path.name) or (
            self.ttl_days is not None and self._expired(path)
        ):
            with contextlib.suppress(OSError):
                path.unlink()
                removed += 1
    return removed

resolve_root()

The cache directory, created on first use.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def resolve_root(self) -> Path:
    """The cache directory, created on first use."""
    if self.root is not None:
        root = Path(self.root)
    else:
        env = os.environ.get("GEOCLOUD_CACHE")
        root = Path(env) if env else Path.home() / _DEFAULT_SUBDIR
    root.mkdir(parents=True, exist_ok=True)
    return root

geocloud.cache.cache_key(uri)

uri without the parameters of an expiring signature.

Azure SAS (when sig is present), AWS / GCS query signing (X-Amz-* / X-Goog-*) and CloudFront signed-URL parameters are dropped; every other query parameter is kept, so URLs that select different content keep different keys. A local path is returned as is.

Parameters:

Name Type Description Default
uri str

A URI or local path.

required

Returns:

Type Description
str

The URI that names the same content for as long as it exists.

Examples:

>>> cache_key("https://h/a.tif?X-Amz-Signature=abc&v=2")
'https://h/a.tif?v=2'
Source code in packages/geotoolz-cloud/src/geocloud/_src/cache.py
def cache_key(uri: str) -> str:
    """``uri`` without the parameters of an expiring signature.

    Azure SAS (when ``sig`` is present), AWS / GCS query signing
    (``X-Amz-*`` / ``X-Goog-*``) and CloudFront signed-URL parameters are
    dropped; every other query parameter is kept, so URLs that select
    different content keep different keys. A local path is returned as is.

    Args:
        uri: A URI or local path.

    Returns:
        The URI that names the same content for as long as it exists.

    Examples:
        >>> cache_key("https://h/a.tif?X-Amz-Signature=abc&v=2")
        'https://h/a.tif?v=2'
    """
    if local_path(uri) is not None:
        return uri
    parts = urlsplit(uri)
    params = parse_qsl(parts.query, keep_blank_values=True)
    if not params:
        return uri
    names = {k.lower() for k, _ in params}

    def signing(name: str) -> bool:
        n = name.lower()
        return (
            n.startswith(("x-amz-", "x-goog-"))
            or ("sig" in names and n in _AZURE_SAS)
            or ({"signature", "key-pair-id"} <= names and n in _CLOUDFRONT)
        )

    kept = [(k, v) for k, v in params if not signing(k)]
    if len(kept) == len(params):
        return uri
    return urlunsplit(parts._replace(query=urlencode(kept)))

geocloud.fs

An fsspec filesystem on the pool ([fsspec] extra).

geocloud.fs.filesystem(storage_options=None)

An fsspec filesystem that reads and writes through the shared pool.

Parameters:

Name Type Description Default
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore for every remote path, over the registered credentials.

None

Returns:

Type Description
GeoCloudFileSystem

A GeoCloudFileSystem.

Examples:

>>> fs = filesystem()
>>> fs.exists("/no/such/file.bin")
False
Source code in packages/geotoolz-cloud/src/geocloud/_src/fs.py
def filesystem(storage_options: Mapping[str, Any] | None = None) -> GeoCloudFileSystem:
    """An fsspec filesystem that reads and writes through the shared pool.

    Args:
        storage_options: Forwarded to `geocloud.store.get_obstore` for
            every remote path, over the registered credentials.

    Returns:
        A `GeoCloudFileSystem`.

    Examples:
        >>> fs = filesystem()
        >>> fs.exists("/no/such/file.bin")
        False
    """
    return GeoCloudFileSystem(storage_options)

geocloud.fs.GeoCloudFileSystem

Bases: AbstractFileSystem

fsspec over geocloud.store: any URI or local path, one engine.

Reads are ranged GETs through fsspec's block cache; writes go through geocloud.files.open ("wb"), so the object appears when the file is closed. Listing works where geocloud.files.ls does (S3, GCS, Azure, local directories).

Parameters:

Name Type Description Default
storage_options Mapping[str, Any] | None

Forwarded to geocloud.store.get_obstore for every remote path (over the registered credentials).

None

Examples:

>>> import tempfile, pathlib
>>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
>>> fs = GeoCloudFileSystem()
>>> fs.pipe_file(str(path), b"abcdef")
>>> with fs.open(str(path)) as fh:
...     _ = fh.seek(2)
...     fh.read(3)
b'cde'
Source code in packages/geotoolz-cloud/src/geocloud/_src/fs.py
class GeoCloudFileSystem(AbstractFileSystem):
    """fsspec over `geocloud.store`: any URI or local path, one engine.

    Reads are ranged GETs through fsspec's block cache; writes go
    through `geocloud.files.open` (``"wb"``), so the object appears
    when the file is closed. Listing works where `geocloud.files.ls`
    does (S3, GCS, Azure, local directories).

    Args:
        storage_options: Forwarded to `geocloud.store.get_obstore` for
            every remote path (over the registered credentials).

    Examples:
        >>> import tempfile, pathlib
        >>> path = pathlib.Path(tempfile.mkdtemp()) / "x.bin"
        >>> fs = GeoCloudFileSystem()
        >>> fs.pipe_file(str(path), b"abcdef")
        >>> with fs.open(str(path)) as fh:
        ...     _ = fh.seek(2)
        ...     fh.read(3)
        b'cde'
    """

    protocol = ("geocloud",)
    root_marker = ""
    cachable = False  # the pool already caches the clients

    def __init__(
        self, storage_options: Mapping[str, Any] | None = None, **kwargs: Any
    ) -> None:
        super().__init__(**kwargs)
        self._pool_options = dict(storage_options or {})

    @classmethod
    def _strip_protocol(cls, path: Any) -> str:
        """Keep the location as written: the scheme says which store."""
        if isinstance(path, list):  # fsspec passes lists through here too
            return [cls._strip_protocol(p) for p in path]  # type: ignore[return-value]
        text = os.fspath(path)
        return text.rstrip("/") if text.rstrip("/") else text

    def _parent(self, path: str) -> str:
        return path.rstrip("/").rsplit("/", 1)[0]

    def _options(self) -> Mapping[str, Any] | None:
        return self._pool_options or None

    def info(self, path: str, **kwargs: Any) -> dict[str, Any]:
        path = self._strip_protocol(path)
        try:
            meta = info(path, storage_options=self._options())
        except FileNotFoundError:
            if self._is_dir(path):
                return {"name": path, "size": 0, "type": "directory"}
            raise
        return {
            "name": path,
            "size": meta.size,
            "type": "file",
            "mtime": meta.last_modified,
            "ETag": meta.e_tag,
        }

    def _is_dir(self, path: str) -> bool:
        local = local_path(path)
        if local is not None:
            return local.is_dir()
        try:
            return bool(ls(path, recursive=False, storage_options=self._options()))
        except (FileNotFoundError, ValueError):
            return False

    def ls(self, path: str, detail: bool = True, **kwargs: Any) -> list[Any]:
        path = self._strip_protocol(path)
        entries = [
            {
                "name": e.uri.rstrip("/"),
                "size": e.size,
                "type": "directory" if e.is_dir else "file",
            }
            for e in ls(path, recursive=False, storage_options=self._options())
        ]
        if not entries and not self._is_dir(path):
            # `ls` of one file names the file itself, as fsspec expects.
            entries = [self.info(path)]
        return entries if detail else [e["name"] for e in entries]

    def cat_file(
        self,
        path: str,
        start: int | None = None,
        end: int | None = None,
        **kwargs: Any,
    ) -> bytes:
        path = self._strip_protocol(path)
        if start is None and end is None:
            return read_bytes(path, storage_options=self._options())
        size = self.size(path)
        start = 0 if start is None else (start if start >= 0 else size + start)
        end = size if end is None else (end if end >= 0 else size + end)
        target = _resolve(path, self._options())
        if end <= start:
            return b""
        return with_bucket_retry(
            lambda: bytes(
                obstore.get_range(target.store, target.key, start=start, end=end)
            )
        )

    def pipe_file(
        self, path: str, value: bytes, mode: str = "overwrite", **kwargs: Any
    ) -> None:
        path = self._strip_protocol(path)
        local = local_path(path)
        if local is not None:
            local.parent.mkdir(parents=True, exist_ok=True)
        write_bytes(path, value, storage_options=self._options())

    def rm_file(self, path: str) -> None:
        rm(self._strip_protocol(path), storage_options=self._options())

    def _rm(self, path: str) -> None:
        self.rm_file(path)

    def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None:
        local = local_path(path)
        if local is not None:  # object stores have no directories
            local.mkdir(parents=create_parents, exist_ok=True)

    def makedirs(self, path: str, exist_ok: bool = False) -> None:
        local = local_path(path)
        if local is not None:
            local.mkdir(parents=True, exist_ok=exist_ok)

    def _open(
        self,
        path: str,
        mode: str = "rb",
        block_size: int | None = None,
        autocommit: bool = True,
        cache_options: dict[str, Any] | None = None,
        **kwargs: Any,
    ) -> Any:
        path = self._strip_protocol(path)
        if mode == "rb":
            return _ObjectFile(
                self,
                path,
                mode,
                block_size=block_size or "default",
                cache_options=cache_options,
                size=self.size(path),
            )
        if mode == "wb":
            local = local_path(path)
            if local is not None:
                local.parent.mkdir(parents=True, exist_ok=True)
            return _ObjectWriter(
                open_object(path, "wb", storage_options=self._options())
            )
        raise ValueError(
            f"GeoCloudFileSystem: mode must be 'rb' or 'wb'; got {mode!r}."
        )

geocloud.credentials

Credentials per store root, for the pool and GDAL.

geocloud.credentials.set_credentials(uri, *, anonymous=False, sas_token=None, **storage_options)

Use these credentials for every object under the store root uri.

get_obstore (and so geocloud.files, geocloud.cog and every package on the pool) merges them under the storage_options a call passes; an Azure container's registration wins over its account's. The options are checked by building a store now, so an unknown key or a missing key file fails here rather than at first read. Registering a root again replaces its entry.

Parameters:

Name Type Description Default
uri str

The store root: s3://bucket, gs://bucket, az://account (all its containers) or az://account/container, https://host.

required
anonymous bool

Send unsigned requests (public buckets and containers); no credential lookup, no instance-metadata probe.

False
sas_token str | None

An Azure SAS token. Rejected when it has expired, or when a container-scoped SAS is registered for a whole account.

None
**storage_options Any

Any other obstore store option for the backend (aws_access_key_id / aws_secret_access_key / region, account_key, use_azure_cli, service_account, credential_provider, client_options, …).

{}

Raises:

Type Description
ValueError

uri names an object or an hf:// repo, an option does not apply to the backend, or the SAS is expired / mis-scoped.

Examples:

>>> set_credentials("s3://noaa-goes19", anonymous=True, region="us-east-1")
>>> credential_roots()
['s3://noaa-goes19']
>>> remove_credentials("s3://noaa-goes19")
Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def set_credentials(
    uri: str,
    *,
    anonymous: bool = False,
    sas_token: str | None = None,
    **storage_options: Any,
) -> None:
    """Use these credentials for every object under the store root ``uri``.

    `get_obstore` (and so `geocloud.files`, `geocloud.cog` and every
    package on the pool) merges them under the ``storage_options`` a call
    passes; an Azure container's registration wins over its account's.
    The options are checked by building a store now, so an unknown key or
    a missing key file fails here rather than at first read. Registering
    a root again replaces its entry.

    Args:
        uri: The store root: ``s3://bucket``, ``gs://bucket``,
            ``az://account`` (all its containers) or
            ``az://account/container``, ``https://host``.
        anonymous: Send unsigned requests (public buckets and containers);
            no credential lookup, no instance-metadata probe.
        sas_token: An Azure SAS token. Rejected when it has expired, or
            when a container-scoped SAS is registered for a whole account.
        **storage_options: Any other obstore store option for the
            backend (``aws_access_key_id`` / ``aws_secret_access_key`` /
            ``region``, ``account_key``, ``use_azure_cli``,
            ``service_account``, ``credential_provider``,
            ``client_options``, …).

    Raises:
        ValueError: ``uri`` names an object or an ``hf://`` repo, an
            option does not apply to the backend, or the SAS is expired /
            mis-scoped.

    Examples:
        >>> set_credentials("s3://noaa-goes19", anonymous=True, region="us-east-1")
        >>> credential_roots()
        ['s3://noaa-goes19']
        >>> remove_credentials("s3://noaa-goes19")
    """
    scope = _scope(uri)
    options = dict(storage_options)
    for name in _SAS_KEYS:
        if name in options:
            if sas_token is not None:
                raise ValueError(f"credentials: pass the SAS once, not also as {name}.")
            sas_token = options.pop(name)
    if sas_token is not None:
        if scope[0] != "azure":
            raise ValueError("credentials: `sas_token` applies to Azure roots only.")
        options["sas_key"] = _check_sas(sas_token, scope)
    if anonymous:
        if scope[0] == "http":
            raise ValueError(
                "credentials: plain HTTP stores are already anonymous unless "
                "given headers; drop `anonymous`."
            )
        options["skip_signature"] = True
    if scope[0] != "http":
        probe = _scope_uri(
            scope if scope[2] or scope[0] != "azure" else (*scope[:2], "probe")
        )
        try:
            _build_store(probe, options)
        except Exception as exc:
            raise ValueError(
                f"credentials: invalid options for {_scope_uri(scope)}: "
                f"{redact(str(exc).split(chr(10), 1)[0])}"
            ) from None
    with _LOCK:
        _REGISTRY[scope] = options

geocloud.credentials.remove_credentials(uri)

Forget the credentials registered at the root uri (no-op if none).

Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def remove_credentials(uri: str) -> None:
    """Forget the credentials registered at the root ``uri`` (no-op if none)."""
    with _LOCK:
        _REGISTRY.pop(_scope(uri), None)

geocloud.credentials.credential_roots()

The store roots that have credentials registered (never the secrets).

Examples:

>>> isinstance(credential_roots(), list)
True
Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def credential_roots() -> list[str]:
    """The store roots that have credentials registered (never the secrets).

    Examples:
        >>> isinstance(credential_roots(), list)
        True
    """
    with _LOCK:
        _autoload()
        return sorted(_scope_uri(scope) for scope in _REGISTRY)

geocloud.credentials.load_credentials(path=None)

Register every store root in a TOML credentials file.

Each table is a store root; its keys are set_credentials's keywords. ${VAR} inside a string value is read from the environment, so the file can hold references rather than secrets::

["s3://noaa-goes19"]
anonymous = true
region = "us-east-1"

["az://myaccount/raw"]
sas_token = "${RAW_SAS}"

["s3://private-bucket"]
aws_access_key_id = "${AWS_KEY}"
aws_secret_access_key = "${AWS_SECRET}"
region = "eu-west-1"

A file other users can read triggers a warning.

Parameters:

Name Type Description Default
path str | PathLike[str] | None

The file; None uses credentials_path (and returns [] when it does not exist).

None

Returns:

Type Description
list[str]

The roots registered.

Raises:

Type Description
FileNotFoundError

An explicit path does not exist.

ValueError

A table is not a root, a ${VAR} is unset, or set_credentials rejects an entry (the message names the root).

Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def load_credentials(path: str | os.PathLike[str] | None = None) -> list[str]:
    """Register every store root in a TOML credentials file.

    Each table is a store root; its keys are `set_credentials`'s keywords.
    ``${VAR}`` inside a string value is read from the environment, so the
    file can hold references rather than secrets::

        ["s3://noaa-goes19"]
        anonymous = true
        region = "us-east-1"

        ["az://myaccount/raw"]
        sas_token = "${RAW_SAS}"

        ["s3://private-bucket"]
        aws_access_key_id = "${AWS_KEY}"
        aws_secret_access_key = "${AWS_SECRET}"
        region = "eu-west-1"

    A file other users can read triggers a warning.

    Args:
        path: The file; ``None`` uses `credentials_path` (and returns ``[]``
            when it does not exist).

    Returns:
        The roots registered.

    Raises:
        FileNotFoundError: An explicit ``path`` does not exist.
        ValueError: A table is not a root, a ``${VAR}`` is unset, or
            `set_credentials` rejects an entry (the message names the root).
    """
    target = Path(path).expanduser() if path is not None else credentials_path()
    if target is None or (path is None and not target.is_file()):
        return []
    data = tomllib.loads(target.read_text(encoding="utf-8"))
    if os.name == "posix" and target.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
        warnings.warn(
            f"{target} is readable by other users; `chmod 600` it.",
            stacklevel=2,
        )
    roots: list[str] = []
    for root, entry in data.items():
        if not isinstance(entry, Mapping):
            raise ValueError(f"credentials: {target}: `{root}` must be a table.")
        set_credentials(root, **_expand(dict(entry), f"{target} [{root}]"))
        roots.append(root)
    return roots

geocloud.credentials.credentials_path()

The default credentials file, or None when turned off.

$GEOCLOUD_CREDENTIALS when set (empty turns the file off), else $XDG_CONFIG_HOME/geocloud/credentials.toml (~/.config/…).

Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def credentials_path() -> Path | None:
    """The default credentials file, or ``None`` when turned off.

    ``$GEOCLOUD_CREDENTIALS`` when set (empty turns the file off), else
    ``$XDG_CONFIG_HOME/geocloud/credentials.toml`` (``~/.config/…``).
    """
    explicit = os.environ.get("GEOCLOUD_CREDENTIALS")
    if explicit is not None:
        return Path(explicit).expanduser() if explicit else None
    config = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
    return Path(config).expanduser() / "geocloud" / "credentials.toml"

geocloud.credentials.gdal_access(uri)

GDAL path and config options to read uri with its registered credentials.

The options come from the same registry as get_obstore, so a root registered once reads through both obstore and GDAL. Nothing is set in os.environ; pass the options to rasterio.Env or to georeader::

path, env = gdal_access("az://account/raw/scene.tif")
reader = RasterioReader(path, rio_env_options=env)
with rasterio.Env(**env), rasterio.open(path) as src: ...

A container-scoped Azure SAS is put in an HTTPS URL (/vsicurl/), because GDAL's /vsiaz/ expects an account-level grant; an account SAS or key goes to /vsiaz/ as config options. Credentials neither side can express (a credential-provider object, an inline service-account key) raise: pre-sign the object with geocloud.files.sign and read /vsicurl/<url> instead.

Parameters:

Name Type Description Default
uri str

A s3://, gs://, Azure, http(s):// URI or a local path.

required

Returns:

Type Description
GdalAccess

A GdalAccess (path, options).

Raises:

Type Description
ValueError

hf:// URIs, mounted stores, or credentials GDAL cannot take as config options.

Examples:

>>> set_credentials("s3://open-data", anonymous=True, region="us-west-2")
>>> path, options = gdal_access("s3://open-data/a/b.tif")
>>> path
'/vsis3/open-data/a/b.tif'
>>> options
{'AWS_NO_SIGN_REQUEST': 'YES', 'AWS_REGION': 'us-west-2'}
>>> remove_credentials("s3://open-data")
Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
def gdal_access(uri: str) -> GdalAccess:
    """GDAL path and config options to read ``uri`` with its registered credentials.

    The options come from the same registry as `get_obstore`, so a root
    registered once reads through both obstore and GDAL. Nothing is set in
    ``os.environ``; pass the options to ``rasterio.Env`` or to georeader::

        path, env = gdal_access("az://account/raw/scene.tif")
        reader = RasterioReader(path, rio_env_options=env)
        with rasterio.Env(**env), rasterio.open(path) as src: ...

    A container-scoped Azure SAS is put in an HTTPS URL (``/vsicurl/``),
    because GDAL's ``/vsiaz/`` expects an account-level grant; an
    account SAS or key goes to ``/vsiaz/`` as config options. Credentials
    neither side can express (a credential-provider object, an inline
    service-account key) raise: pre-sign the object with
    `geocloud.files.sign` and read ``/vsicurl/<url>`` instead.

    Args:
        uri: A ``s3://``, ``gs://``, Azure, ``http(s)://`` URI or a local
            path.

    Returns:
        A `GdalAccess` ``(path, options)``.

    Raises:
        ValueError: ``hf://`` URIs, mounted stores, or credentials GDAL
            cannot take as config options.

    Examples:
        >>> set_credentials("s3://open-data", anonymous=True, region="us-west-2")
        >>> path, options = gdal_access("s3://open-data/a/b.tif")
        >>> path
        '/vsis3/open-data/a/b.tif'
        >>> options
        {'AWS_NO_SIGN_REQUEST': 'YES', 'AWS_REGION': 'us-west-2'}
        >>> remove_credentials("s3://open-data")
    """
    local = local_path(uri)
    if local is not None:
        return GdalAccess(str(local), {})
    scheme = urlsplit(uri).scheme.lower()
    if scheme == "hf":
        raise ValueError(
            "gdal_access: hf:// is not a GDAL path; read it with geocloud.cog."
        )
    loc = _locate(uri)
    if loc.backend == "http":
        return GdalAccess(f"/vsicurl/{uri}", {})

    from geocloud._src.store import get_obstore

    store = get_obstore(uri)
    config: dict[str, Any] = dict(getattr(store, "config", None) or {})
    if not config:
        raise ValueError(
            f"gdal_access: {redact(uri)!r} is served by a mounted store; GDAL "
            "cannot read it."
        )
    if getattr(store, "credential_provider", None) is not None:
        raise ValueError(
            "gdal_access: a credential provider cannot be handed to GDAL; "
            "pre-sign with geocloud.files.sign and read /vsicurl/<url>."
        )
    options: dict[str, str] = {}
    if loc.backend == "s3":
        for key, name in (
            ("access_key_id", "AWS_ACCESS_KEY_ID"),
            ("secret_access_key", "AWS_SECRET_ACCESS_KEY"),
            ("session_token", "AWS_SESSION_TOKEN"),
            ("region", "AWS_REGION"),
        ):
            if key in config:
                options[name] = str(config[key])
        if _true(config.get("skip_signature")):
            options["AWS_NO_SIGN_REQUEST"] = "YES"
        if _true(config.get("request_payer")):
            options["AWS_REQUEST_PAYER"] = "requester"
        if endpoint := config.get("endpoint"):
            parts = urlsplit(str(endpoint))
            options["AWS_S3_ENDPOINT"] = parts.netloc or str(endpoint)
            options["AWS_HTTPS"] = "NO" if parts.scheme == "http" else "YES"
            options["AWS_VIRTUAL_HOSTING"] = (
                "TRUE" if _true(config.get("virtual_hosted_style_request")) else "FALSE"
            )
        return GdalAccess(
            f"/vsis3/{loc.bucket}/{loc.key}", dict(sorted(options.items()))
        )
    if loc.backend == "gcs":
        if "service_account_key" in config:
            raise ValueError(
                "gdal_access: an inline service-account key cannot be handed to "
                "GDAL; register `service_account` (a key file path) instead."
            )
        if "service_account" in config:
            options["GOOGLE_APPLICATION_CREDENTIALS"] = str(config["service_account"])
        if _true(config.get("skip_signature")):
            options["GS_NO_SIGN_REQUEST"] = "YES"
        return GdalAccess(f"/vsigs/{loc.bucket}/{loc.key}", options)
    # Azure
    account, container = loc.bucket, loc.scope
    sas = config.get("sas_key")
    if sas and _sas_is_service_scoped(str(sas)):
        url = f"https://{account}.blob.core.windows.net/{container}/{quote(loc.key)}"
        return GdalAccess(f"/vsicurl/{url}?{sas}", {})
    options["AZURE_STORAGE_ACCOUNT"] = account
    if sas:
        options["AZURE_STORAGE_SAS_TOKEN"] = str(sas)
    if "account_key" in config:
        options["AZURE_STORAGE_ACCESS_KEY"] = str(config["account_key"])
    if _true(config.get("skip_signature")):
        options["AZURE_NO_SIGN_REQUEST"] = "YES"
    return GdalAccess(f"/vsiaz/{container}/{loc.key}", dict(sorted(options.items())))

geocloud.credentials.GdalAccess

Bases: NamedTuple

How GDAL (rasterio, georeader) reads a URI with the registered credentials.

Attributes:

Name Type Description
path str

The GDAL path (/vsis3/…, /vsigs/…, /vsiaz/…, /vsicurl/… or a local path).

options dict[str, str]

GDAL config options for rasterio.Env(**options) or georeader's rio_env_options.

Source code in packages/geotoolz-cloud/src/geocloud/_src/credentials.py
class GdalAccess(NamedTuple):
    """How GDAL (rasterio, georeader) reads a URI with the registered credentials.

    Attributes:
        path: The GDAL path (``/vsis3/…``, ``/vsigs/…``, ``/vsiaz/…``,
            ``/vsicurl/…`` or a local path).
        options: GDAL config options for ``rasterio.Env(**options)`` or
            georeader's ``rio_env_options``.
    """

    path: str
    options: dict[str, str]

geocloud.credentials.redact(text)

text with URL signatures, tokens and bearer credentials masked.

Use it on any URI or message that may reach a log, an exception or a notebook output: SAS sig=, S3 / GCS query signatures and credentials, token= / key= parameters and Bearer headers become REDACTED. Everything else (paths, expiry times) is kept, so the redacted text still says which object and which window.

Parameters:

Name Type Description Default
text str

Any string.

required

Returns:

Type Description
str

The string with secrets masked.

Examples:

>>> redact("https://a.blob.core.windows.net/c/x.tif?se=2026-11-01&sig=abc%3D")
'https://a.blob.core.windows.net/c/x.tif?se=2026-11-01&sig=REDACTED'
>>> redact("Authorization: Bearer eyJhbGciOi")
'Authorization: Bearer REDACTED'
Source code in packages/geotoolz-cloud/src/geocloud/_src/redact.py
def redact(text: str) -> str:
    """``text`` with URL signatures, tokens and bearer credentials masked.

    Use it on any URI or message that may reach a log, an exception or a
    notebook output: SAS ``sig=``, S3 / GCS query signatures and
    credentials, ``token=`` / ``key=`` parameters and ``Bearer`` headers
    become ``REDACTED``. Everything else (paths, expiry times) is kept, so
    the redacted text still says which object and which window.

    Args:
        text: Any string.

    Returns:
        The string with secrets masked.

    Examples:
        >>> redact("https://a.blob.core.windows.net/c/x.tif?se=2026-11-01&sig=abc%3D")
        'https://a.blob.core.windows.net/c/x.tif?se=2026-11-01&sig=REDACTED'
        >>> redact("Authorization: Bearer eyJhbGciOi")
        'Authorization: Bearer REDACTED'
    """
    return _BEARER.sub(r"\1REDACTED", _SECRET_PARAM.sub(r"\1REDACTED", text))

geocloud.cog

COG reads ([cog] extra) and the validated COG writer.

geocloud.cog.CogSource dataclass

An opened, tiled COG with batched range-fetch reads.

Open via :meth:open (or await :meth:aopen); the constructor takes the parsed handles. read_window / read_windows return geoarray.GeoArray chips (bands, h, w) with the window's transform, the CRS and the COG's nodata as fill_value; out-of-image pixels, and pixels the COG's internal mask marks invalid, are filled with it. A source is a geoarray.RasterSource (grid, shape, dtype, fill_value, attrs, read_window, load) and a geoarray.AsyncRasterSource (aread_window, aload). It pickles by URL (see __reduce__).

Note

Lossless codecs match rasterio.read exactly. JPEG tiles are decoded by async-tiff, not GDAL's libjpeg: expect differences of a few DN (up to ±3 for PHOTOMETRIC=YCbCr, ±1 for RGB JPEG).

Parameters:

Name Type Description Default
url str

Cloud URI the COG was opened from.

required
level Any

The async_geotiff.GeoTIFF (ifd_index 0) or async_geotiff.Overview being read.

required
ifd Any

The selected async_tiff.ImageFileDirectory (level.ifd).

required
domain CogDomain

I/O-free metadata twin (see CogDomain).

required
timeout float | None

Per-network-operation deadline in seconds for tile fetch + decode batches (read_window / read_windows). None disables the bound. On expiry a :class:TimeoutError naming the URL and tile batch is raised instead of hanging the calling (or worker) thread forever on a stalled read.

120.0
ifd_index int

Which IFD ifd is (0 = full resolution). Recorded so pickling re-opens the same overview.

0
storage_options dict[str, Any] | None

Options the pooled store was built with; recorded for pickling.

None
store Any

The explicit obstore store passed to :meth:open, if any (None = the process-global pool). Recorded for pickling; obstore stores pickle by configuration.

None
path str | None

Object key inside store (only with an explicit store).

None
dtype Any

Pixel dtype (None = derived from level's parent GeoTIFF by :meth:open).

None

Examples:

Two overlapping windows share their tile fetches::

src = CogSource.open("s3://bucket/scene.tif")
src.shape                            # (bands, H, W)
a, b = src.read_windows([
    PixelWindow(col_off=0, row_off=0, width=256, height=256),
    PixelWindow(col_off=128, row_off=0, width=256, height=256),
])                                   # 2 x (bands, 256, 256)
Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
@dataclass(eq=False)
class CogSource:
    """An opened, tiled COG with batched range-fetch reads.

    Open via :meth:`open` (or ``await`` :meth:`aopen`); the constructor
    takes the parsed handles. ``read_window`` / ``read_windows`` return
    `geoarray.GeoArray` chips ``(bands, h, w)`` with the window's
    transform, the CRS and the COG's nodata as ``fill_value``; out-of-image
    pixels, and pixels the COG's internal mask marks invalid, are filled
    with it. A source is a `geoarray.RasterSource` (``grid``, ``shape``,
    ``dtype``, ``fill_value``, ``attrs``, ``read_window``, ``load``) and a
    `geoarray.AsyncRasterSource` (``aread_window``, ``aload``). It pickles
    by URL (see ``__reduce__``).

    Note:
        Lossless codecs match ``rasterio.read`` exactly. JPEG tiles are
        decoded by async-tiff, not GDAL's libjpeg: expect differences of
        a few DN (up to ±3 for ``PHOTOMETRIC=YCbCr``, ±1 for RGB JPEG).

    Args:
        url: Cloud URI the COG was opened from.
        level: The ``async_geotiff.GeoTIFF`` (``ifd_index`` 0) or
            ``async_geotiff.Overview`` being read.
        ifd: The selected ``async_tiff.ImageFileDirectory``
            (``level.ifd``).
        domain: I/O-free metadata twin (see `CogDomain`).
        timeout: Per-network-operation deadline in seconds for tile
            fetch + decode batches (`read_window` / `read_windows`).
            ``None`` disables the bound. On expiry a :class:`TimeoutError`
            naming the URL and tile batch is raised instead of hanging the
            calling (or worker) thread forever on a stalled read.
        ifd_index: Which IFD ``ifd`` is (``0`` = full resolution).
            Recorded so pickling re-opens the same overview.
        storage_options: Options the pooled store was built with;
            recorded for pickling.
        store: The explicit obstore store passed to :meth:`open`, if any
            (``None`` = the process-global pool). Recorded for pickling;
            obstore stores pickle by configuration.
        path: Object key inside ``store`` (only with an explicit store).
        dtype: Pixel dtype (``None`` = derived from ``level``'s parent
            GeoTIFF by :meth:`open`).

    Examples:
        Two overlapping windows share their tile fetches::

            src = CogSource.open("s3://bucket/scene.tif")
            src.shape                            # (bands, H, W)
            a, b = src.read_windows([
                PixelWindow(col_off=0, row_off=0, width=256, height=256),
                PixelWindow(col_off=128, row_off=0, width=256, height=256),
            ])                                   # 2 x (bands, 256, 256)
    """

    url: str
    level: Any  # async_geotiff.GeoTIFF | async_geotiff.Overview
    ifd: Any  # async_tiff.ImageFileDirectory
    domain: CogDomain
    timeout: float | None = 120.0
    ifd_index: int = 0
    storage_options: dict[str, Any] | None = None
    store: Any = None
    path: str | None = None
    dtype: Any = None

    @classmethod
    def open(
        cls,
        url: str,
        *,
        storage_options: dict[str, Any] | None = None,
        ifd_index: int = 0,
        store: Any = None,
        path: str | None = None,
        timeout: float | None = 120.0,
    ) -> Self:
        """Open a remote COG, parse its IFD, return a ready source.

        Args:
            url: Cloud URI (``s3://``, ``gs://``, ``https://``, …).
                Used both as the pool key and (after stripping scheme/
                bucket) as the object-store key for the file. Ignored
                when ``store`` is supplied — see below.
            storage_options: Forwarded to obstore on the first call
                for the URL's pool key (bucket + region).
            ifd_index: Which IFD to open — ``0`` for the full-resolution
                image, ``1+`` for overviews. Overviews inherit the CRS
                and origin of IFD 0 with the pixel size scaled by the
                size ratio.
            store: Optional pre-built obstore ``ObjectStore`` instance.
                When supplied, bypasses the pool — useful for tests
                with ``LocalStore`` / ``MemoryStore``, or for a custom
                auth / endpoint config that doesn't fit the pool's
                environment-driven keying.
            path: Object key inside ``store``. Required when ``store``
                is supplied; ignored otherwise (derived from ``url``).
            timeout: Deadline in seconds for opening/parsing the COG
                header, and (stored on the source) for each subsequent
                tile fetch + decode batch. ``None`` disables the bound.

        Raises:
            ImportError: ``[cog]`` extra missing.
            ValueError: COG is striped (not tiled), ``ifd_index`` names
                a mask IFD or no IFD, the file carries no GeoTIFF keys,
                or the tags needed to derive an affine transform or a
                dtype are missing.
            TimeoutError: Opening the COG took longer than ``timeout``
                seconds.
        """
        return _run_coroutine_safely(
            cls.aopen(
                url,
                storage_options=storage_options,
                ifd_index=ifd_index,
                store=store,
                path=path,
                timeout=timeout,
            )
        )

    @classmethod
    async def aopen(
        cls,
        url: str,
        *,
        storage_options: dict[str, Any] | None = None,
        ifd_index: int = 0,
        store: Any = None,
        path: str | None = None,
        timeout: float | None = 120.0,
    ) -> Self:
        """Async twin of :meth:`open` — same arguments, same source.

        For callers already inside an event loop (tile servers, async
        inference): awaits the header fetch instead of driving it on a
        helper thread.
        """
        async_geotiff = _require_async_geotiff()

        explicit_store = store
        if store is None:
            from geocloud._src.store import get_obstore

            store = get_obstore(url, storage_options=storage_options)
            object_path = _uri_path(url)
        else:
            if path is None:
                raise ValueError(
                    "CogSource.open: when `store` is supplied, `path` (the key "
                    "inside the store) must also be supplied."
                )
            object_path = path

        # Upstream only warns on striped TIFFs; the tiled check below raises.
        geotiff = await _with_timeout(
            awith_bucket_retry(
                lambda: async_geotiff.GeoTIFF.open(object_path, store=store),
                probe=lambda: _list_parent(store, object_path),
            ),
            timeout=timeout,
            message=f"opening COG {url!r}",
        )
        ifd = geotiff.tiff.ifd(ifd_index)
        if ifd.tile_width is None or ifd.tile_height is None:
            raise ValueError(
                "CogSource: COG must be tiled (TileWidth + TileLength); "
                "striped TIFFs aren't supported. Read those with rasterio."
            )
        subfile_type = getattr(ifd, "new_subfile_type", None)
        if subfile_type is not None and int(subfile_type) & 4:
            raise ValueError(
                f"CogSource: IFD {ifd_index} of {url!r} is a "
                "transparency mask, not image data."
            )
        level = _level_for_ifd(geotiff, ifd_index, ifd, url=url)
        domain = _build_domain(level, geotiff, url=url)
        return cls(
            url=url,
            level=level,
            ifd=level.ifd,
            domain=domain,
            timeout=timeout,
            ifd_index=ifd_index,
            storage_options=storage_options,
            store=explicit_store,
            path=path if explicit_store is not None else None,
            dtype=_dtype(geotiff, url=url),
        )

    def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
        """Pickle by URL: the parsed TIFF handle is a Rust object.

        Unpickling calls :meth:`open` on the same class with the recorded
        ``ifd_index`` / ``storage_options`` / ``timeout`` (and the explicit
        ``store`` + ``path`` when one was supplied), so a worker process
        re-reads only the COG header.
        """
        options: dict[str, Any] = {
            "ifd_index": self.ifd_index,
            "storage_options": self.storage_options,
            "timeout": self.timeout,
        }
        if self.store is not None:
            options["store"] = self.store
            options["path"] = self.path
        return (_reopen, (type(self), self.url, options))

    def identity(self) -> dict[str, Any]:
        """What this source reads, as plain JSON-able data (no credentials).

        With the process pool the object is the ``url`` (plus a digest of
        ``storage_options``: the same url can name different objects under
        different endpoints); with an explicit ``store`` the ``url`` is
        only a label, so the identity is the store's printable
        configuration (e.g. ``LocalStore("/data")``) plus ``path``.
        ``store`` is ``None`` for an explicit store without one
        (``MemoryStore``, whose contents live only in that instance).

        Returns:
            ``{"url", "options", "store", "path", "ifd_index"}``.
        """
        explicit = self.store is not None
        return {
            "url": None if explicit else self.url,
            "options": None if explicit else _options_digest(self.storage_options),
            "store": _store_identity(self.store) if explicit else None,
            "path": self.path if explicit else None,
            "ifd_index": int(self.ifd_index),
        }

    def object_version(self) -> str | None:
        """ETag (else ``size:last_modified``) of the object, or ``None``.

        One ``HEAD`` request. When the store refuses it, or answers with
        neither an ETag nor a last-modified time, a `RuntimeWarning` says
        changes to the object cannot be detected and ``None`` is returned.
        """
        if self.store is not None:
            store, key = self.store, self.path
        else:
            from geocloud._src.store import get_obstore

            store = get_obstore(self.url, storage_options=self.storage_options)
            key = _uri_path(self.url)
        try:
            meta = with_bucket_retry(
                lambda: store.head(key), probe=lambda: _list_parent(store, key)
            )
        except Exception as exc:
            warnings.warn(
                f"CogSource: HEAD of {self.url!r} failed ({exc}); changes to "
                f"the object will not be detected.",
                RuntimeWarning,
                stacklevel=3,
            )
            return None
        e_tag = meta.get("e_tag")
        if e_tag:
            return f"etag:{e_tag}"
        last_modified = meta.get("last_modified")
        if last_modified is None:
            # Size alone cannot tell an overwrite of the same length apart.
            warnings.warn(
                f"CogSource: HEAD of {self.url!r} returned neither an ETag nor "
                f"a Last-Modified time; changes to the object will not be "
                f"detected.",
                RuntimeWarning,
                stacklevel=3,
            )
            return None
        return f"size:{meta.get('size')}:{last_modified}"

    # ------------------------------------------------------------- RasterSource
    @property
    def grid(self) -> Grid:
        """The pixel grid of the opened IFD (`CogDomain.grid`)."""
        return self.domain.grid

    @property
    def shape(self) -> tuple[int, ...]:
        """``(bands, H, W)``, the shape `load` returns."""
        return tuple(int(n) for n in self.domain.shape)

    @property
    def fill_value(self) -> float | int:
        """Fill for out-of-image and masked pixels: nodata, else ``0``."""
        return self.domain.fill_value

    @property
    def attrs(self) -> FrozenAttrs:
        """Metadata every read carries (none: a COG chip is pixels + grid)."""
        return FrozenAttrs()

    def _whole(self) -> PixelWindow:
        _, height, width = self.shape
        return PixelWindow(col_off=0, row_off=0, width=width, height=height)

    def load(self) -> GeoArray:
        """Every pixel of the opened IFD, ``(bands, H, W)``.

        Raises:
            TimeoutError: The tile fetch + decode did not finish within
                ``self.timeout`` seconds.
        """
        return self.read_window(self._whole())

    async def aload(self) -> GeoArray:
        """Async twin of :meth:`load`."""
        return await self.aread_window(self._whole())

    def read_window(
        self, window: PixelWindow | Window, *, boundless: bool = True
    ) -> GeoArray:
        """Read one window via the COG's tile grid.

        A thin wrapper around ``read_windows([window])``, so the
        single-window path goes through the same tile-coalescing code as
        the batched path; see :meth:`aread_windows` for the semantics.
        """
        return self.read_windows([window], boundless=boundless)[0]

    async def aread_window(
        self, window: PixelWindow | Window, *, boundless: bool = True
    ) -> GeoArray:
        """Async twin of :meth:`read_window`."""
        return (await self.aread_windows([window], boundless=boundless))[0]

    def read_windows(
        self, windows: list[PixelWindow | Window], *, boundless: bool = True
    ) -> list[GeoArray]:
        """Bulk-read every window, fetching each overlapping tile once.

        Sync facade over :meth:`aread_windows` (safe inside a running
        event loop — the coroutine then runs on a helper thread); see
        there for the read semantics.

        Raises:
            ValueError: ``boundless=False`` and a window misses the image.
            TimeoutError: The tile fetch + decode did not finish within
                ``self.timeout`` seconds.
        """
        return _run_coroutine_safely(self.aread_windows(windows, boundless=boundless))

    async def aread_windows(
        self, windows: list[PixelWindow | Window], *, boundless: bool = True
    ) -> list[GeoArray]:
        """Async bulk read: every window, each overlapping tile fetched once.

        The headline path: collect every unique tile coordinate
        across all windows, fetch + decode them in concurrent groups
        (see `_fetch_and_decode_tiles`), then assemble per-window
        arrays by cropping each decoded tile to its window's
        intersection.

        Args:
            windows: `geoarray.PixelWindow` (or ``rasterio.windows.Window``)
                rectangles to read. Fractional windows are snapped outward
                to whole pixels.
            boundless: ``True`` (default) returns each window whole: parts
                past (or entirely outside) the image get ``fill_value``.
                ``False`` clips each window to the image first.

        Returns:
            One `geoarray.GeoArray` per input window, in input order, each
            shaped ``(bands, height, width)`` with the (snapped, clipped)
            window's transform, the domain CRS and ``fill_value`` set to the
            COG's nodata (else ``0``).

        Raises:
            ValueError: ``boundless=False`` and a window misses the image.
            TimeoutError: The batched tile fetch + decode did not
                finish within ``self.timeout`` seconds.
        """
        if len(windows) == 0:
            return []

        tile_w = int(self.ifd.tile_width)
        tile_h = int(self.ifd.tile_height)
        image_w = int(self.ifd.image_width)
        image_h = int(self.ifd.image_height)

        # Collect the unique tile coordinates spanned by all windows.
        pixel_windows = [_snap_window(w) for w in windows]
        if not boundless:
            image = PixelWindow(col_off=0, row_off=0, width=image_w, height=image_h)
            pixel_windows = [
                _clip_window(w, image, url=self.url) for w in pixel_windows
            ]
        tile_coords: dict[tuple[int, int], None] = {}
        per_window_tile_ranges: list[tuple[int, int, int, int]] = []
        for w in pixel_windows:
            ranges = _tile_range_for_window(
                w,
                tile_w=tile_w,
                tile_h=tile_h,
                image_w=image_w,
                image_h=image_h,
            )
            per_window_tile_ranges.append(ranges)
            tx_min, ty_min, tx_max, ty_max = ranges
            for ty in range(ty_min, ty_max + 1):
                for tx in range(tx_min, tx_max + 1):
                    tile_coords[(tx, ty)] = None

        coord_list = list(tile_coords.keys())
        decoded = await _with_timeout(
            _fetch_and_decode_tiles(self.level, coord_list),
            timeout=self.timeout,
            message=(
                f"fetching/decoding a batch of {len(coord_list)} tiles "
                f"from {self.url!r}"
            ),
        )
        # Map decoded tiles by coord for the assembly loop.
        tile_data: dict[tuple[int, int], np.ndarray] = dict(
            zip(coord_list, decoded, strict=True)
        )

        # Derive (bands, dtype) from the metadata so the empty-tile-range
        # path (window entirely outside the image) returns an array of
        # the right shape/dtype even when no tile was fetched.
        bands = int(self.domain.shape[0])
        dtype = np.dtype(self.dtype)
        fill = self.fill_value
        attrs = self.attrs
        names = self.domain.band_names
        coords = () if names is None else (SpectralAxis(names),)

        results: list[GeoArray] = []
        for window, (tx_min, ty_min, tx_max, ty_max) in zip(
            pixel_windows, per_window_tile_ranges, strict=True
        ):
            values = _assemble_window(
                window,
                tile_data=tile_data,
                tx_min=tx_min,
                ty_min=ty_min,
                tx_max=tx_max,
                ty_max=ty_max,
                tile_w=tile_w,
                tile_h=tile_h,
                image_w=image_w,
                image_h=image_h,
                bands=bands,
                dtype=dtype,
                fill=fill,
            )
            results.append(
                GeoArray(
                    values,
                    self.domain.transform
                    * Affine.translation(window.col_off, window.row_off),
                    self.domain.crs,
                    fill_value=fill,
                    attrs=attrs,
                    dims=("band", "y", "x"),
                    coords=coords,
                )
            )
        return results

attrs property

Metadata every read carries (none: a COG chip is pixels + grid).

fill_value property

Fill for out-of-image and masked pixels: nodata, else 0.

grid property

The pixel grid of the opened IFD (CogDomain.grid).

shape property

(bands, H, W), the shape load returns.

__reduce__()

Pickle by URL: the parsed TIFF handle is a Rust object.

Unpickling calls :meth:open on the same class with the recorded ifd_index / storage_options / timeout (and the explicit store + path when one was supplied), so a worker process re-reads only the COG header.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:
    """Pickle by URL: the parsed TIFF handle is a Rust object.

    Unpickling calls :meth:`open` on the same class with the recorded
    ``ifd_index`` / ``storage_options`` / ``timeout`` (and the explicit
    ``store`` + ``path`` when one was supplied), so a worker process
    re-reads only the COG header.
    """
    options: dict[str, Any] = {
        "ifd_index": self.ifd_index,
        "storage_options": self.storage_options,
        "timeout": self.timeout,
    }
    if self.store is not None:
        options["store"] = self.store
        options["path"] = self.path
    return (_reopen, (type(self), self.url, options))

aload() async

Async twin of :meth:load.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
async def aload(self) -> GeoArray:
    """Async twin of :meth:`load`."""
    return await self.aread_window(self._whole())

aopen(url, *, storage_options=None, ifd_index=0, store=None, path=None, timeout=120.0) async classmethod

Async twin of :meth:open — same arguments, same source.

For callers already inside an event loop (tile servers, async inference): awaits the header fetch instead of driving it on a helper thread.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
@classmethod
async def aopen(
    cls,
    url: str,
    *,
    storage_options: dict[str, Any] | None = None,
    ifd_index: int = 0,
    store: Any = None,
    path: str | None = None,
    timeout: float | None = 120.0,
) -> Self:
    """Async twin of :meth:`open` — same arguments, same source.

    For callers already inside an event loop (tile servers, async
    inference): awaits the header fetch instead of driving it on a
    helper thread.
    """
    async_geotiff = _require_async_geotiff()

    explicit_store = store
    if store is None:
        from geocloud._src.store import get_obstore

        store = get_obstore(url, storage_options=storage_options)
        object_path = _uri_path(url)
    else:
        if path is None:
            raise ValueError(
                "CogSource.open: when `store` is supplied, `path` (the key "
                "inside the store) must also be supplied."
            )
        object_path = path

    # Upstream only warns on striped TIFFs; the tiled check below raises.
    geotiff = await _with_timeout(
        awith_bucket_retry(
            lambda: async_geotiff.GeoTIFF.open(object_path, store=store),
            probe=lambda: _list_parent(store, object_path),
        ),
        timeout=timeout,
        message=f"opening COG {url!r}",
    )
    ifd = geotiff.tiff.ifd(ifd_index)
    if ifd.tile_width is None or ifd.tile_height is None:
        raise ValueError(
            "CogSource: COG must be tiled (TileWidth + TileLength); "
            "striped TIFFs aren't supported. Read those with rasterio."
        )
    subfile_type = getattr(ifd, "new_subfile_type", None)
    if subfile_type is not None and int(subfile_type) & 4:
        raise ValueError(
            f"CogSource: IFD {ifd_index} of {url!r} is a "
            "transparency mask, not image data."
        )
    level = _level_for_ifd(geotiff, ifd_index, ifd, url=url)
    domain = _build_domain(level, geotiff, url=url)
    return cls(
        url=url,
        level=level,
        ifd=level.ifd,
        domain=domain,
        timeout=timeout,
        ifd_index=ifd_index,
        storage_options=storage_options,
        store=explicit_store,
        path=path if explicit_store is not None else None,
        dtype=_dtype(geotiff, url=url),
    )

aread_window(window, *, boundless=True) async

Async twin of :meth:read_window.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
async def aread_window(
    self, window: PixelWindow | Window, *, boundless: bool = True
) -> GeoArray:
    """Async twin of :meth:`read_window`."""
    return (await self.aread_windows([window], boundless=boundless))[0]

aread_windows(windows, *, boundless=True) async

Async bulk read: every window, each overlapping tile fetched once.

The headline path: collect every unique tile coordinate across all windows, fetch + decode them in concurrent groups (see _fetch_and_decode_tiles), then assemble per-window arrays by cropping each decoded tile to its window's intersection.

Parameters:

Name Type Description Default
windows list[PixelWindow | Window]

geoarray.PixelWindow (or rasterio.windows.Window) rectangles to read. Fractional windows are snapped outward to whole pixels.

required
boundless bool

True (default) returns each window whole: parts past (or entirely outside) the image get fill_value. False clips each window to the image first.

True

Returns:

Type Description
list[GeoArray]

One geoarray.GeoArray per input window, in input order, each

list[GeoArray]

shaped (bands, height, width) with the (snapped, clipped)

list[GeoArray]

window's transform, the domain CRS and fill_value set to the

list[GeoArray]

COG's nodata (else 0).

Raises:

Type Description
ValueError

boundless=False and a window misses the image.

TimeoutError

The batched tile fetch + decode did not finish within self.timeout seconds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
async def aread_windows(
    self, windows: list[PixelWindow | Window], *, boundless: bool = True
) -> list[GeoArray]:
    """Async bulk read: every window, each overlapping tile fetched once.

    The headline path: collect every unique tile coordinate
    across all windows, fetch + decode them in concurrent groups
    (see `_fetch_and_decode_tiles`), then assemble per-window
    arrays by cropping each decoded tile to its window's
    intersection.

    Args:
        windows: `geoarray.PixelWindow` (or ``rasterio.windows.Window``)
            rectangles to read. Fractional windows are snapped outward
            to whole pixels.
        boundless: ``True`` (default) returns each window whole: parts
            past (or entirely outside) the image get ``fill_value``.
            ``False`` clips each window to the image first.

    Returns:
        One `geoarray.GeoArray` per input window, in input order, each
        shaped ``(bands, height, width)`` with the (snapped, clipped)
        window's transform, the domain CRS and ``fill_value`` set to the
        COG's nodata (else ``0``).

    Raises:
        ValueError: ``boundless=False`` and a window misses the image.
        TimeoutError: The batched tile fetch + decode did not
            finish within ``self.timeout`` seconds.
    """
    if len(windows) == 0:
        return []

    tile_w = int(self.ifd.tile_width)
    tile_h = int(self.ifd.tile_height)
    image_w = int(self.ifd.image_width)
    image_h = int(self.ifd.image_height)

    # Collect the unique tile coordinates spanned by all windows.
    pixel_windows = [_snap_window(w) for w in windows]
    if not boundless:
        image = PixelWindow(col_off=0, row_off=0, width=image_w, height=image_h)
        pixel_windows = [
            _clip_window(w, image, url=self.url) for w in pixel_windows
        ]
    tile_coords: dict[tuple[int, int], None] = {}
    per_window_tile_ranges: list[tuple[int, int, int, int]] = []
    for w in pixel_windows:
        ranges = _tile_range_for_window(
            w,
            tile_w=tile_w,
            tile_h=tile_h,
            image_w=image_w,
            image_h=image_h,
        )
        per_window_tile_ranges.append(ranges)
        tx_min, ty_min, tx_max, ty_max = ranges
        for ty in range(ty_min, ty_max + 1):
            for tx in range(tx_min, tx_max + 1):
                tile_coords[(tx, ty)] = None

    coord_list = list(tile_coords.keys())
    decoded = await _with_timeout(
        _fetch_and_decode_tiles(self.level, coord_list),
        timeout=self.timeout,
        message=(
            f"fetching/decoding a batch of {len(coord_list)} tiles "
            f"from {self.url!r}"
        ),
    )
    # Map decoded tiles by coord for the assembly loop.
    tile_data: dict[tuple[int, int], np.ndarray] = dict(
        zip(coord_list, decoded, strict=True)
    )

    # Derive (bands, dtype) from the metadata so the empty-tile-range
    # path (window entirely outside the image) returns an array of
    # the right shape/dtype even when no tile was fetched.
    bands = int(self.domain.shape[0])
    dtype = np.dtype(self.dtype)
    fill = self.fill_value
    attrs = self.attrs
    names = self.domain.band_names
    coords = () if names is None else (SpectralAxis(names),)

    results: list[GeoArray] = []
    for window, (tx_min, ty_min, tx_max, ty_max) in zip(
        pixel_windows, per_window_tile_ranges, strict=True
    ):
        values = _assemble_window(
            window,
            tile_data=tile_data,
            tx_min=tx_min,
            ty_min=ty_min,
            tx_max=tx_max,
            ty_max=ty_max,
            tile_w=tile_w,
            tile_h=tile_h,
            image_w=image_w,
            image_h=image_h,
            bands=bands,
            dtype=dtype,
            fill=fill,
        )
        results.append(
            GeoArray(
                values,
                self.domain.transform
                * Affine.translation(window.col_off, window.row_off),
                self.domain.crs,
                fill_value=fill,
                attrs=attrs,
                dims=("band", "y", "x"),
                coords=coords,
            )
        )
    return results

identity()

What this source reads, as plain JSON-able data (no credentials).

With the process pool the object is the url (plus a digest of storage_options: the same url can name different objects under different endpoints); with an explicit store the url is only a label, so the identity is the store's printable configuration (e.g. LocalStore("/data")) plus path. store is None for an explicit store without one (MemoryStore, whose contents live only in that instance).

Returns:

Type Description
dict[str, Any]

{"url", "options", "store", "path", "ifd_index"}.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def identity(self) -> dict[str, Any]:
    """What this source reads, as plain JSON-able data (no credentials).

    With the process pool the object is the ``url`` (plus a digest of
    ``storage_options``: the same url can name different objects under
    different endpoints); with an explicit ``store`` the ``url`` is
    only a label, so the identity is the store's printable
    configuration (e.g. ``LocalStore("/data")``) plus ``path``.
    ``store`` is ``None`` for an explicit store without one
    (``MemoryStore``, whose contents live only in that instance).

    Returns:
        ``{"url", "options", "store", "path", "ifd_index"}``.
    """
    explicit = self.store is not None
    return {
        "url": None if explicit else self.url,
        "options": None if explicit else _options_digest(self.storage_options),
        "store": _store_identity(self.store) if explicit else None,
        "path": self.path if explicit else None,
        "ifd_index": int(self.ifd_index),
    }

load()

Every pixel of the opened IFD, (bands, H, W).

Raises:

Type Description
TimeoutError

The tile fetch + decode did not finish within self.timeout seconds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def load(self) -> GeoArray:
    """Every pixel of the opened IFD, ``(bands, H, W)``.

    Raises:
        TimeoutError: The tile fetch + decode did not finish within
            ``self.timeout`` seconds.
    """
    return self.read_window(self._whole())

object_version()

ETag (else size:last_modified) of the object, or None.

One HEAD request. When the store refuses it, or answers with neither an ETag nor a last-modified time, a RuntimeWarning says changes to the object cannot be detected and None is returned.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def object_version(self) -> str | None:
    """ETag (else ``size:last_modified``) of the object, or ``None``.

    One ``HEAD`` request. When the store refuses it, or answers with
    neither an ETag nor a last-modified time, a `RuntimeWarning` says
    changes to the object cannot be detected and ``None`` is returned.
    """
    if self.store is not None:
        store, key = self.store, self.path
    else:
        from geocloud._src.store import get_obstore

        store = get_obstore(self.url, storage_options=self.storage_options)
        key = _uri_path(self.url)
    try:
        meta = with_bucket_retry(
            lambda: store.head(key), probe=lambda: _list_parent(store, key)
        )
    except Exception as exc:
        warnings.warn(
            f"CogSource: HEAD of {self.url!r} failed ({exc}); changes to "
            f"the object will not be detected.",
            RuntimeWarning,
            stacklevel=3,
        )
        return None
    e_tag = meta.get("e_tag")
    if e_tag:
        return f"etag:{e_tag}"
    last_modified = meta.get("last_modified")
    if last_modified is None:
        # Size alone cannot tell an overwrite of the same length apart.
        warnings.warn(
            f"CogSource: HEAD of {self.url!r} returned neither an ETag nor "
            f"a Last-Modified time; changes to the object will not be "
            f"detected.",
            RuntimeWarning,
            stacklevel=3,
        )
        return None
    return f"size:{meta.get('size')}:{last_modified}"

open(url, *, storage_options=None, ifd_index=0, store=None, path=None, timeout=120.0) classmethod

Open a remote COG, parse its IFD, return a ready source.

Parameters:

Name Type Description Default
url str

Cloud URI (s3://, gs://, https://, …). Used both as the pool key and (after stripping scheme/ bucket) as the object-store key for the file. Ignored when store is supplied — see below.

required
storage_options dict[str, Any] | None

Forwarded to obstore on the first call for the URL's pool key (bucket + region).

None
ifd_index int

Which IFD to open — 0 for the full-resolution image, 1+ for overviews. Overviews inherit the CRS and origin of IFD 0 with the pixel size scaled by the size ratio.

0
store Any

Optional pre-built obstore ObjectStore instance. When supplied, bypasses the pool — useful for tests with LocalStore / MemoryStore, or for a custom auth / endpoint config that doesn't fit the pool's environment-driven keying.

None
path str | None

Object key inside store. Required when store is supplied; ignored otherwise (derived from url).

None
timeout float | None

Deadline in seconds for opening/parsing the COG header, and (stored on the source) for each subsequent tile fetch + decode batch. None disables the bound.

120.0

Raises:

Type Description
ImportError

[cog] extra missing.

ValueError

COG is striped (not tiled), ifd_index names a mask IFD or no IFD, the file carries no GeoTIFF keys, or the tags needed to derive an affine transform or a dtype are missing.

TimeoutError

Opening the COG took longer than timeout seconds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
@classmethod
def open(
    cls,
    url: str,
    *,
    storage_options: dict[str, Any] | None = None,
    ifd_index: int = 0,
    store: Any = None,
    path: str | None = None,
    timeout: float | None = 120.0,
) -> Self:
    """Open a remote COG, parse its IFD, return a ready source.

    Args:
        url: Cloud URI (``s3://``, ``gs://``, ``https://``, …).
            Used both as the pool key and (after stripping scheme/
            bucket) as the object-store key for the file. Ignored
            when ``store`` is supplied — see below.
        storage_options: Forwarded to obstore on the first call
            for the URL's pool key (bucket + region).
        ifd_index: Which IFD to open — ``0`` for the full-resolution
            image, ``1+`` for overviews. Overviews inherit the CRS
            and origin of IFD 0 with the pixel size scaled by the
            size ratio.
        store: Optional pre-built obstore ``ObjectStore`` instance.
            When supplied, bypasses the pool — useful for tests
            with ``LocalStore`` / ``MemoryStore``, or for a custom
            auth / endpoint config that doesn't fit the pool's
            environment-driven keying.
        path: Object key inside ``store``. Required when ``store``
            is supplied; ignored otherwise (derived from ``url``).
        timeout: Deadline in seconds for opening/parsing the COG
            header, and (stored on the source) for each subsequent
            tile fetch + decode batch. ``None`` disables the bound.

    Raises:
        ImportError: ``[cog]`` extra missing.
        ValueError: COG is striped (not tiled), ``ifd_index`` names
            a mask IFD or no IFD, the file carries no GeoTIFF keys,
            or the tags needed to derive an affine transform or a
            dtype are missing.
        TimeoutError: Opening the COG took longer than ``timeout``
            seconds.
    """
    return _run_coroutine_safely(
        cls.aopen(
            url,
            storage_options=storage_options,
            ifd_index=ifd_index,
            store=store,
            path=path,
            timeout=timeout,
        )
    )

read_window(window, *, boundless=True)

Read one window via the COG's tile grid.

A thin wrapper around read_windows([window]), so the single-window path goes through the same tile-coalescing code as the batched path; see :meth:aread_windows for the semantics.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def read_window(
    self, window: PixelWindow | Window, *, boundless: bool = True
) -> GeoArray:
    """Read one window via the COG's tile grid.

    A thin wrapper around ``read_windows([window])``, so the
    single-window path goes through the same tile-coalescing code as
    the batched path; see :meth:`aread_windows` for the semantics.
    """
    return self.read_windows([window], boundless=boundless)[0]

read_windows(windows, *, boundless=True)

Bulk-read every window, fetching each overlapping tile once.

Sync facade over :meth:aread_windows (safe inside a running event loop — the coroutine then runs on a helper thread); see there for the read semantics.

Raises:

Type Description
ValueError

boundless=False and a window misses the image.

TimeoutError

The tile fetch + decode did not finish within self.timeout seconds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
def read_windows(
    self, windows: list[PixelWindow | Window], *, boundless: bool = True
) -> list[GeoArray]:
    """Bulk-read every window, fetching each overlapping tile once.

    Sync facade over :meth:`aread_windows` (safe inside a running
    event loop — the coroutine then runs on a helper thread); see
    there for the read semantics.

    Raises:
        ValueError: ``boundless=False`` and a window misses the image.
        TimeoutError: The tile fetch + decode did not finish within
            ``self.timeout`` seconds.
    """
    return _run_coroutine_safely(self.aread_windows(windows, boundless=boundless))

geocloud.cog.CogDomain dataclass

Raster-domain view over a remote COG IFD.

The I/O-free metadata twin of a CogSource (crs, transform, shape, bounds, res, grid) — the attributes geopatcher's samplers and geometries expect from a raster domain — without holding the IFD.

transform is an affine.Affine; grid is the same georeferencing as a hashable geoarray.Grid. nodata is the parsed GDAL_NODATA tag (cast to the pixel dtype's kind), or None when the COG declares none; fill_value is what reads fill with. band_names are the bands' GDAL descriptions (GDAL_METADATA) when every band has a distinct one, else None; reads carry them as a SpectralAxis.

Example

from affine import Affine domain = CogDomain( ... crs=None, transform=Affine(10, 0, 0, 0, -10, 0), shape=(1, 4, 6), ... bounds=(0.0, -40.0, 60.0, 0.0), res=(10.0, 10.0), ... ) domain.grid.shape, domain.fill_value ((4, 6), 0)

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_source.py
@dataclass(frozen=True)
class CogDomain:
    """Raster-domain view over a remote COG IFD.

    The I/O-free metadata twin of a `CogSource` (``crs``, ``transform``,
    ``shape``, ``bounds``, ``res``, ``grid``) — the attributes geopatcher's
    samplers and geometries expect from a raster domain — without holding
    the IFD.

    ``transform`` is an ``affine.Affine``; ``grid`` is the same georeferencing
    as a hashable `geoarray.Grid`. ``nodata`` is the parsed ``GDAL_NODATA``
    tag (cast to the pixel dtype's kind), or ``None`` when the COG declares
    none; ``fill_value`` is what reads fill with. ``band_names`` are the
    bands' GDAL descriptions (``GDAL_METADATA``) when every band has a
    distinct one, else ``None``; reads carry them as a `SpectralAxis`.

    Example:
        >>> from affine import Affine
        >>> domain = CogDomain(
        ...     crs=None, transform=Affine(10, 0, 0, 0, -10, 0), shape=(1, 4, 6),
        ...     bounds=(0.0, -40.0, 60.0, 0.0), res=(10.0, 10.0),
        ... )
        >>> domain.grid.shape, domain.fill_value
        ((4, 6), 0)
    """

    crs: Any
    transform: Any
    shape: tuple[int, ...]
    bounds: tuple[float, float, float, float]
    res: tuple[float, float]
    nodata: float | int | None = None
    band_names: tuple[str, ...] | None = None

    @property
    def fill_value(self) -> float | int:
        """Value used for out-of-image and masked pixels: ``nodata``, else ``0``."""
        return 0 if self.nodata is None else self.nodata

    @property
    def grid(self) -> Grid:
        """The pixel grid: ``transform``, ``crs`` and ``(H, W)``."""
        return Grid.from_affine(self.transform, self.crs, self.shape[-2:])

fill_value property

Value used for out-of-image and masked pixels: nodata, else 0.

grid property

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

geocloud.cog.AsyncCogReader dataclass

await-native COG reader over a CogSource.

Open with :meth:open; metadata is then sync and free, reads are coroutines returning geoarray.GeoArray::

reader = await AsyncCogReader.open("s3://bucket/scene.tif")
view = reader.read_from_window(Window(0, 0, 512, 512))  # no I/O
chip = await view.load()                     # (bands, 512, 512)
chips = await reader.load_many(windows)  # shared tiles fetched once

A reader is a geoarray.AsyncRasterSource: grid, shape, dtype, fill_value, attrs, aread_window(PixelWindow) and aload().

A view shares the parsed header with its parent and only carries a different window_focus. As with georeader's RasterioReader, a view is an offset into the image, not a crop: a window read from a view is placed relative to the view's origin but may reach past the view's edges (it is clipped or filled only at the image's edges). Out-of-image pixels, and pixels the COG's internal mask marks invalid, read as fill_value. The reader pickles (by URL, through its source).

Parameters:

Name Type Description Default
source CogSource

The CogSource doing the reading.

required
window_focus Window | None

The pixel window this view covers, in the source's pixel grid (None = the whole image). Snapped outward to whole pixels.

None
Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
@dataclasses.dataclass(eq=False)
class AsyncCogReader:
    """``await``-native COG reader over a `CogSource`.

    Open with :meth:`open`; metadata is then sync and free, reads are
    coroutines returning `geoarray.GeoArray`::

        reader = await AsyncCogReader.open("s3://bucket/scene.tif")
        view = reader.read_from_window(Window(0, 0, 512, 512))  # no I/O
        chip = await view.load()                     # (bands, 512, 512)
        chips = await reader.load_many(windows)  # shared tiles fetched once

    A reader is a `geoarray.AsyncRasterSource`: ``grid``, ``shape``,
    ``dtype``, ``fill_value``, ``attrs``, ``aread_window(PixelWindow)`` and
    ``aload()``.

    A view shares the parsed header with its parent and only carries a
    different ``window_focus``. As with georeader's `RasterioReader`, a
    view is an offset into the image, not a crop: a window read from a
    view is placed relative to the view's origin but may reach past the
    view's edges (it is clipped or filled only at the image's edges).
    Out-of-image pixels, and pixels the
    COG's internal mask marks invalid, read as ``fill_value``.
    The reader pickles (by URL, through its source).

    Args:
        source: The `CogSource` doing the reading.
        window_focus: The pixel window this view covers, in the source's
            pixel grid (``None`` = the whole image). Snapped outward to
            whole pixels.
    """

    source: CogSource
    window_focus: Window | None = None

    def __post_init__(self) -> None:
        if self.window_focus is not None:
            self.window_focus = _snapped(self.window_focus)

    @classmethod
    async def open(
        cls,
        url: str,
        *,
        storage_options: dict[str, Any] | None = None,
        ifd_index: int = 0,
        store: Any = None,
        path: str | None = None,
        timeout: float | None = 120.0,
    ) -> AsyncCogReader:
        """Fetch and parse the COG header; return a reader over the whole image.

        Arguments are those of `CogSource.open` (pooled store
        from ``url``, or an explicit ``store`` + ``path``; ``ifd_index``
        ``1+`` opens an overview).

        Raises:
            ImportError: ``[cog]`` extra missing.
            ValueError: See `CogSource.open`.
            TimeoutError: Opening took longer than ``timeout`` seconds.
        """
        source = await CogSource.aopen(
            url,
            storage_options=storage_options,
            ifd_index=ifd_index,
            store=store,
            path=path,
            timeout=timeout,
        )
        return cls(source)

    # ------------------------------------------------------------- metadata
    @property
    def _raster_window(self) -> Window:
        _, height, width = self.source.domain.shape
        return _window(0, 0, width, height)

    @property
    def _focus(self) -> Window:
        return (
            self.window_focus if self.window_focus is not None else self._raster_window
        )

    @property
    def crs(self) -> Any:
        """CRS of the image (``None`` when it could not be built)."""
        return self.source.domain.crs

    @property
    def transform(self) -> Affine:
        """Affine transform of this view's top-left pixel (``affine.Affine``)."""
        focus = self._focus
        return self.source.domain.transform * Affine.translation(
            focus.col_off, focus.row_off
        )

    @property
    def shape(self) -> tuple[int, int, int]:
        """``(bands, height, width)`` of this view."""
        focus = self._focus
        return (int(self.source.domain.shape[0]), int(focus.height), int(focus.width))

    @property
    def width(self) -> int:
        return self.shape[2]

    @property
    def height(self) -> int:
        return self.shape[1]

    @property
    def count(self) -> int:
        return self.shape[0]

    @property
    def dims(self) -> list[str]:
        return ["band", "y", "x"]

    @property
    def dtype(self) -> np.dtype:
        return np.dtype(self.source.dtype)

    @property
    def fill_value(self) -> float | int:
        """Nodata, else ``0``: the value of out-of-image and masked pixels."""
        return self.source.fill_value

    @property
    def grid(self) -> Grid:
        """This view's pixel grid: ``transform``, ``crs`` and ``(H, W)``."""
        return Grid.from_affine(self.transform, self.crs, self.shape[-2:])

    @property
    def attrs(self) -> FrozenAttrs:
        """Metadata every read carries (`CogSource.attrs`)."""
        return self.source.attrs

    @property
    def res(self) -> tuple[float, float]:
        return self.source.domain.res

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """``(minx, miny, maxx, maxy)`` of this view in its CRS."""
        return window_utils.window_bounds(self._focus, self.source.domain.transform)

    def footprint(self, crs: Any = None) -> BaseGeometry:
        """This view's outline as a polygon, in ``crs`` (default: its own)."""
        polygon = window_utils.window_polygon(self._focus, self.source.domain.transform)
        if crs is None or window_utils.compare_crs(crs, self.crs):
            return polygon
        return window_utils.polygon_to_crs(polygon, self.crs, crs)

    # ------------------------------------------------------------- reading
    def read_from_window(
        self, window: Window | PixelWindow, boundless: bool = True
    ) -> AsyncCogReader:
        """A view of ``window``, offset from this view's origin. **Sync, no I/O.**

        Like `RasterioReader.read_from_window`, the window is not clipped
        to this view, only to the image: ``boundless=False`` clips it to
        the image and raises
        ``rasterio.windows.WindowError`` when they are disjoint;
        ``boundless=True`` lets it extend past the image (filled on load).
        """
        focus = self._focus
        absolute = _window(
            window.col_off + focus.col_off,
            window.row_off + focus.row_off,
            window.width,
            window.height,
        )
        if not boundless:
            absolute = rasterio.windows.intersection(
                _snapped(absolute), self._raster_window
            )
        return dataclasses.replace(self, window_focus=absolute)

    async def load(self, boundless: bool = True) -> GeoArray:
        """Read this view as a `geoarray.GeoArray` ``(bands, h, w)``.

        ``boundless=True`` returns the full view, out-of-image pixels
        filled; ``boundless=False`` returns its intersection with the
        image (``rasterio.windows.WindowError`` when disjoint).
        """
        focus = self._focus
        if not boundless:
            focus = rasterio.windows.intersection(focus, self._raster_window)
        return await self.source.aread_window(focus)

    async def aread_window(
        self, window: PixelWindow | Window, *, boundless: bool = True
    ) -> GeoArray:
        """Read ``window`` (offset from this view's origin) — `AsyncRasterSource`.

        ``boundless=True`` returns the whole snapped window: pixels off the
        image read as ``fill_value`` (on a view, pixels past the view's edge
        but inside the image are read, as with :meth:`read_from_window`).
        ``boundless=False`` clips the window to this view's grid.

        Raises:
            ValueError: ``boundless=False`` and the window misses the grid.
        """
        snapped = _snap_window(window)
        if not boundless:
            extent = PixelWindow(
                col_off=0, row_off=0, width=self.width, height=self.height
            )
            inside = snapped.intersection(extent)
            if inside is None:
                raise ValueError(
                    f"AsyncCogReader: window {snapped} does not overlap the "
                    f"grid {extent.shape} (boundless=False)."
                )
            snapped = inside
        focus = self._focus
        return await self.source.aread_window(
            PixelWindow(
                col_off=snapped.col_off + int(focus.col_off),
                row_off=snapped.row_off + int(focus.row_off),
                width=snapped.width,
                height=snapped.height,
            )
        )

    async def aload(self) -> GeoArray:
        """Every pixel of this view — `AsyncRasterSource` (same as `load`)."""
        return await self.load()

    async def load_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
        """Read many windows (offset from this view's origin) in one batch.

        Tiles shared between windows are fetched and decoded once (see
        `CogSource.aread_windows`); windows may extend past the image.
        """
        focus = self._focus
        absolute = [
            _window(
                w.col_off + focus.col_off, w.row_off + focus.row_off, w.width, w.height
            )
            for w in windows
        ]
        return await self.source.aread_windows(absolute)

    # ------------------------------------------------------------- overviews
    def overviews(self) -> list[int]:
        """Decimation factors of the COG's overviews (e.g. ``[2, 4, 8]``).

        Empty for a reader already opened on an overview.
        """
        level = self.source.level
        width = int(self.source.domain.shape[2])
        return [round(width / int(ov.width)) for ov in getattr(level, "overviews", [])]

    def reader_overview(self, overview: int) -> AsyncCogReader:
        """A whole-image reader on overview ``overview`` (0-based). **No I/O.**

        Shares the parsed header; pixel windows then refer to the
        overview's grid.

        Raises:
            ValueError: This reader is itself an overview, or ``overview``
                is out of range.
        """
        geotiff = self.source.level
        overviews = list(getattr(geotiff, "overviews", []))
        if not 0 <= overview < len(overviews):
            raise ValueError(
                f"AsyncCogReader: overview {overview} out of range for "
                f"{self.source.url!r} ({len(overviews)} overview(s) on this reader)."
            )
        level = overviews[overview]
        size = (int(level.width), int(level.height))
        ifd_index = next(
            i
            for i, ifd in enumerate(geotiff.tiff.ifds)
            if i > 0
            and (int(ifd.image_width), int(ifd.image_height)) == size
            and not int(getattr(ifd, "new_subfile_type", None) or 0) & 4
        )
        source = dataclasses.replace(
            self.source,
            level=level,
            ifd=level.ifd,
            domain=_build_domain(level, geotiff, url=self.source.url),
            ifd_index=ifd_index,
        )
        return AsyncCogReader(source)

attrs property

Metadata every read carries (CogSource.attrs).

bounds property

(minx, miny, maxx, maxy) of this view in its CRS.

crs property

CRS of the image (None when it could not be built).

fill_value property

Nodata, else 0: the value of out-of-image and masked pixels.

grid property

This view's pixel grid: transform, crs and (H, W).

shape property

(bands, height, width) of this view.

transform property

Affine transform of this view's top-left pixel (affine.Affine).

aload() async

Every pixel of this view — AsyncRasterSource (same as load).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def aload(self) -> GeoArray:
    """Every pixel of this view — `AsyncRasterSource` (same as `load`)."""
    return await self.load()

aread_window(window, *, boundless=True) async

Read window (offset from this view's origin) — AsyncRasterSource.

boundless=True returns the whole snapped window: pixels off the image read as fill_value (on a view, pixels past the view's edge but inside the image are read, as with :meth:read_from_window). boundless=False clips the window to this view's grid.

Raises:

Type Description
ValueError

boundless=False and the window misses the grid.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def aread_window(
    self, window: PixelWindow | Window, *, boundless: bool = True
) -> GeoArray:
    """Read ``window`` (offset from this view's origin) — `AsyncRasterSource`.

    ``boundless=True`` returns the whole snapped window: pixels off the
    image read as ``fill_value`` (on a view, pixels past the view's edge
    but inside the image are read, as with :meth:`read_from_window`).
    ``boundless=False`` clips the window to this view's grid.

    Raises:
        ValueError: ``boundless=False`` and the window misses the grid.
    """
    snapped = _snap_window(window)
    if not boundless:
        extent = PixelWindow(
            col_off=0, row_off=0, width=self.width, height=self.height
        )
        inside = snapped.intersection(extent)
        if inside is None:
            raise ValueError(
                f"AsyncCogReader: window {snapped} does not overlap the "
                f"grid {extent.shape} (boundless=False)."
            )
        snapped = inside
    focus = self._focus
    return await self.source.aread_window(
        PixelWindow(
            col_off=snapped.col_off + int(focus.col_off),
            row_off=snapped.row_off + int(focus.row_off),
            width=snapped.width,
            height=snapped.height,
        )
    )

footprint(crs=None)

This view's outline as a polygon, in crs (default: its own).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
def footprint(self, crs: Any = None) -> BaseGeometry:
    """This view's outline as a polygon, in ``crs`` (default: its own)."""
    polygon = window_utils.window_polygon(self._focus, self.source.domain.transform)
    if crs is None or window_utils.compare_crs(crs, self.crs):
        return polygon
    return window_utils.polygon_to_crs(polygon, self.crs, crs)

load(boundless=True) async

Read this view as a geoarray.GeoArray (bands, h, w).

boundless=True returns the full view, out-of-image pixels filled; boundless=False returns its intersection with the image (rasterio.windows.WindowError when disjoint).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def load(self, boundless: bool = True) -> GeoArray:
    """Read this view as a `geoarray.GeoArray` ``(bands, h, w)``.

    ``boundless=True`` returns the full view, out-of-image pixels
    filled; ``boundless=False`` returns its intersection with the
    image (``rasterio.windows.WindowError`` when disjoint).
    """
    focus = self._focus
    if not boundless:
        focus = rasterio.windows.intersection(focus, self._raster_window)
    return await self.source.aread_window(focus)

load_many(windows) async

Read many windows (offset from this view's origin) in one batch.

Tiles shared between windows are fetched and decoded once (see CogSource.aread_windows); windows may extend past the image.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def load_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
    """Read many windows (offset from this view's origin) in one batch.

    Tiles shared between windows are fetched and decoded once (see
    `CogSource.aread_windows`); windows may extend past the image.
    """
    focus = self._focus
    absolute = [
        _window(
            w.col_off + focus.col_off, w.row_off + focus.row_off, w.width, w.height
        )
        for w in windows
    ]
    return await self.source.aread_windows(absolute)

open(url, *, storage_options=None, ifd_index=0, store=None, path=None, timeout=120.0) async classmethod

Fetch and parse the COG header; return a reader over the whole image.

Arguments are those of CogSource.open (pooled store from url, or an explicit store + path; ifd_index 1+ opens an overview).

Raises:

Type Description
ImportError

[cog] extra missing.

ValueError

See CogSource.open.

TimeoutError

Opening took longer than timeout seconds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
@classmethod
async def open(
    cls,
    url: str,
    *,
    storage_options: dict[str, Any] | None = None,
    ifd_index: int = 0,
    store: Any = None,
    path: str | None = None,
    timeout: float | None = 120.0,
) -> AsyncCogReader:
    """Fetch and parse the COG header; return a reader over the whole image.

    Arguments are those of `CogSource.open` (pooled store
    from ``url``, or an explicit ``store`` + ``path``; ``ifd_index``
    ``1+`` opens an overview).

    Raises:
        ImportError: ``[cog]`` extra missing.
        ValueError: See `CogSource.open`.
        TimeoutError: Opening took longer than ``timeout`` seconds.
    """
    source = await CogSource.aopen(
        url,
        storage_options=storage_options,
        ifd_index=ifd_index,
        store=store,
        path=path,
        timeout=timeout,
    )
    return cls(source)

overviews()

Decimation factors of the COG's overviews (e.g. [2, 4, 8]).

Empty for a reader already opened on an overview.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
def overviews(self) -> list[int]:
    """Decimation factors of the COG's overviews (e.g. ``[2, 4, 8]``).

    Empty for a reader already opened on an overview.
    """
    level = self.source.level
    width = int(self.source.domain.shape[2])
    return [round(width / int(ov.width)) for ov in getattr(level, "overviews", [])]

read_from_window(window, boundless=True)

A view of window, offset from this view's origin. Sync, no I/O.

Like RasterioReader.read_from_window, the window is not clipped to this view, only to the image: boundless=False clips it to the image and raises rasterio.windows.WindowError when they are disjoint; boundless=True lets it extend past the image (filled on load).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
def read_from_window(
    self, window: Window | PixelWindow, boundless: bool = True
) -> AsyncCogReader:
    """A view of ``window``, offset from this view's origin. **Sync, no I/O.**

    Like `RasterioReader.read_from_window`, the window is not clipped
    to this view, only to the image: ``boundless=False`` clips it to
    the image and raises
    ``rasterio.windows.WindowError`` when they are disjoint;
    ``boundless=True`` lets it extend past the image (filled on load).
    """
    focus = self._focus
    absolute = _window(
        window.col_off + focus.col_off,
        window.row_off + focus.row_off,
        window.width,
        window.height,
    )
    if not boundless:
        absolute = rasterio.windows.intersection(
            _snapped(absolute), self._raster_window
        )
    return dataclasses.replace(self, window_focus=absolute)

reader_overview(overview)

A whole-image reader on overview overview (0-based). No I/O.

Shares the parsed header; pixel windows then refer to the overview's grid.

Raises:

Type Description
ValueError

This reader is itself an overview, or overview is out of range.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
def reader_overview(self, overview: int) -> AsyncCogReader:
    """A whole-image reader on overview ``overview`` (0-based). **No I/O.**

    Shares the parsed header; pixel windows then refer to the
    overview's grid.

    Raises:
        ValueError: This reader is itself an overview, or ``overview``
            is out of range.
    """
    geotiff = self.source.level
    overviews = list(getattr(geotiff, "overviews", []))
    if not 0 <= overview < len(overviews):
        raise ValueError(
            f"AsyncCogReader: overview {overview} out of range for "
            f"{self.source.url!r} ({len(overviews)} overview(s) on this reader)."
        )
    level = overviews[overview]
    size = (int(level.width), int(level.height))
    ifd_index = next(
        i
        for i, ifd in enumerate(geotiff.tiff.ifds)
        if i > 0
        and (int(ifd.image_width), int(ifd.image_height)) == size
        and not int(getattr(ifd, "new_subfile_type", None) or 0) & 4
    )
    source = dataclasses.replace(
        self.source,
        level=level,
        ifd=level.ifd,
        domain=_build_domain(level, geotiff, url=self.source.url),
        ifd_index=ifd_index,
    )
    return AsyncCogReader(source)

geocloud.cog.read_from_window(reader, window, boundless=True) async

Read window of reader (see AsyncCogReader.read_from_window).

Like georeader.read.read_from_window, boundless=False on a window that misses the reader's own extent (the view, for a view) returns None (no fetch).

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_from_window(
    reader: AsyncCogReader, window: Window | PixelWindow, boundless: bool = True
) -> GeoArray | None:
    """Read ``window`` of ``reader`` (see `AsyncCogReader.read_from_window`).

    Like `georeader.read.read_from_window`, ``boundless=False`` on a
    window that misses the reader's own extent (the view, for a view)
    returns ``None`` (no fetch).
    """
    extent = _window(0, 0, reader.width, reader.height)
    if not boundless and not rasterio.windows.intersect([_snapped(window), extent]):
        return None
    return await reader.read_from_window(window, boundless=boundless).load(
        boundless=boundless
    )

geocloud.cog.read_from_bounds(reader, bounds, crs_bounds=None, pad_add=(0, 0), boundless=True) async

Async georeader.read.read_from_bounds: the pixels covering bounds.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_from_bounds(
    reader: AsyncCogReader,
    bounds: tuple[float, float, float, float],
    crs_bounds: Any = None,
    pad_add: tuple[int, int] = (0, 0),
    boundless: bool = True,
) -> GeoArray | None:
    """Async `georeader.read.read_from_bounds`: the pixels covering ``bounds``."""
    window = _read.window_from_bounds(reader, bounds, crs_bounds)
    if any(p > 0 for p in pad_add):
        window = window_utils.pad_window(window, pad_add)
    return await read_from_window(
        reader, window_utils.round_outer_window(window), boundless=boundless
    )

geocloud.cog.read_from_polygon(reader, polygon, crs_polygon=None, pad_add=(0, 0), boundless=True, window_surrounding=False) async

Async georeader.read.read_from_polygon: the pixels covering polygon.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_from_polygon(
    reader: AsyncCogReader,
    polygon: BaseGeometry,
    crs_polygon: Any = None,
    pad_add: tuple[int, int] = (0, 0),
    boundless: bool = True,
    window_surrounding: bool = False,
) -> GeoArray | None:
    """Async `georeader.read.read_from_polygon`: the pixels covering ``polygon``."""
    window = _read.window_from_polygon(
        reader, polygon, crs_polygon, window_surrounding=window_surrounding
    )
    if any(p > 0 for p in pad_add):
        window = window_utils.pad_window(window, pad_add)
    return await read_from_window(
        reader, window_utils.round_outer_window(window), boundless=boundless
    )

geocloud.cog.read_from_center_coords(reader, center_coords, shape, crs_center_coords=None, boundless=True) async

Async georeader.read.read_from_center_coords: a shape chip at a point.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_from_center_coords(
    reader: AsyncCogReader,
    center_coords: tuple[float, float],
    shape: tuple[int, int],
    crs_center_coords: Any = None,
    boundless: bool = True,
) -> GeoArray | None:
    """Async `georeader.read.read_from_center_coords`: a ``shape`` chip at a point."""
    window = _read.window_from_center_coords(
        reader, center_coords, shape, crs_center_coords
    )
    return await read_from_window(reader, window, boundless=boundless)

geocloud.cog.read_reproject(reader, dst_crs=None, bounds=None, resolution_dst_crs=None, dst_transform=None, window_out=None, resampling=Resampling.cubic_spline, dtype_dst=None, dst_nodata=None) async

Async georeader.read.read_reproject onto a destination grid.

The grid is dst_transform + window_out, or derived from bounds (+ resolution_dst_crs) exactly as georeader does; only the source pixels under it are fetched.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_reproject(
    reader: AsyncCogReader,
    dst_crs: Any = None,
    bounds: tuple[float, float, float, float] | None = None,
    resolution_dst_crs: float | tuple[float, float] | None = None,
    dst_transform: Affine | None = None,
    window_out: Window | None = None,
    resampling: Resampling = Resampling.cubic_spline,
    dtype_dst: Any = None,
    dst_nodata: Any = None,
) -> GeoArray:
    """Async `georeader.read.read_reproject` onto a destination grid.

    The grid is ``dst_transform`` + ``window_out``, or derived from
    ``bounds`` (+ ``resolution_dst_crs``) exactly as georeader does;
    only the source pixels under it are fetched.
    """
    dst_transform = window_utils.figure_out_transform(
        transform=dst_transform, bounds=bounds, resolution_dst=resolution_dst_crs
    )
    if window_out is None:
        if bounds is None:
            raise ValueError(
                "read_reproject: pass `window_out` or `bounds` to size the output."
            )
        window_out = rasterio.windows.from_bounds(
            *bounds, transform=dst_transform
        ).round_lengths(op="ceil", pixel_precision=window_utils.PIXEL_PRECISION)
    if dst_crs is None:
        dst_crs = reader.crs
    chunk = await _load_footprint(
        reader, window_utils.window_polygon(window_out, dst_transform), dst_crs
    )
    warped = from_georeader(
        _read.read_reproject(
            to_georeader(chunk),
            dst_crs=dst_crs,
            dst_transform=dst_transform,
            window_out=window_out,
            resampling=resampling,
            dtype_dst=dtype_dst,
            dst_nodata=dst_nodata,
        )
    )
    # georeader keeps the bands but not their names: carry the chunk's over
    if warped.shape[:-2] == chunk.shape[:-2]:
        return warped.with_data(warped.data, dims=chunk.dims, coords=chunk.coords)
    return warped

geocloud.cog.read_reproject_like(reader, data_like, resolution_dst=None, resampling=Resampling.cubic_spline, dtype_dst=None, dst_nodata=None) async

Async georeader.read.read_reproject_like: onto data_like's grid.

data_like is a geoarray.GeoArray or any geoarray.RasterSource (anything with a grid). With resolution_dst (a number, or (x, y) like grid.res) the grid keeps data_like's extent at the new pixel size. Unlike georeader 2.2, whose output shape takes the x resolution for the height, anisotropic tuples size rows from y and columns from x.

Raises:

Type Description
TypeError

data_like is a georeader object (convert it with geoarray.interop.georeader), or has no grid.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_reproject_like(
    reader: AsyncCogReader,
    data_like: Any,
    resolution_dst: float | tuple[float, float] | None = None,
    resampling: Resampling = Resampling.cubic_spline,
    dtype_dst: Any = None,
    dst_nodata: Any = None,
) -> GeoArray:
    """Async `georeader.read.read_reproject_like`: onto ``data_like``'s grid.

    ``data_like`` is a `geoarray.GeoArray` or any `geoarray.RasterSource`
    (anything with a ``grid``). With ``resolution_dst`` (a number, or
    ``(x, y)`` like ``grid.res``) the grid keeps ``data_like``'s extent at
    the new pixel size. Unlike georeader 2.2, whose output shape takes the
    x resolution for the height, anisotropic tuples size rows from y and
    columns from x.

    Raises:
        TypeError: ``data_like`` is a georeader object (convert it with
            ``geoarray.interop.georeader``), or has no ``grid``.
    """
    reject_georeader(data_like, "read_reproject_like")
    grid = getattr(data_like, "grid", None)
    if not isinstance(grid, Grid):
        raise TypeError(
            "read_reproject_like takes a GeoArray or a geoarray.RasterSource as "
            f"data_like, got {type(data_like).__name__}"
        )
    height, width = grid.shape
    if resolution_dst is not None:
        res_x, res_y = (
            (resolution_dst, resolution_dst)
            if isinstance(resolution_dst, int | float)
            else resolution_dst
        )
        like_x, like_y = grid.res
        height = round(height * like_y / res_y)
        width = round(width * like_x / res_x)
    return await read_reproject(
        reader,
        dst_crs=grid.crs,
        dst_transform=grid.affine,
        resolution_dst_crs=resolution_dst,
        window_out=_window(0, 0, width, height),
        resampling=resampling,
        dtype_dst=dtype_dst,
        dst_nodata=dst_nodata,
    )

geocloud.cog.read_to_crs(reader, dst_crs, resampling=Resampling.cubic_spline, resolution_dst_crs=None) async

Async georeader.read.read_to_crs: the whole view, reprojected.

Already in dst_crs: the view is loaded as is.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_to_crs(
    reader: AsyncCogReader,
    dst_crs: Any,
    resampling: Resampling = Resampling.cubic_spline,
    resolution_dst_crs: float | tuple[float, float] | None = None,
) -> GeoArray:
    """Async `georeader.read.read_to_crs`: the whole view, reprojected.

    Already in ``dst_crs``: the view is loaded as is.
    """
    if window_utils.compare_crs(reader.crs, dst_crs):
        return await reader.load()
    window_out, dst_transform = _read.calculate_transform_window(
        reader, dst_crs, resolution_dst_crs
    )
    return await read_reproject(
        reader,
        dst_crs=dst_crs,
        dst_transform=dst_transform,
        window_out=window_out,
        resampling=resampling,
    )

geocloud.cog.read_from_tile(reader, x, y, z, out_shape=(256, 256), resampling=Resampling.cubic_spline) async

The XYZ (slippy-map) tile (x, y, z) in EPSG:3857, out_shape pixels.

Tiles off the image come back filled with fill_value without any fetch. For tiles much coarser than the source pixels, pass a AsyncCogReader.reader_overview of matching resolution.

Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_reader.py
async def read_from_tile(
    reader: AsyncCogReader,
    x: int,
    y: int,
    z: int,
    out_shape: tuple[int, int] = (256, 256),
    resampling: Resampling = Resampling.cubic_spline,
) -> GeoArray:
    """The XYZ (slippy-map) tile ``(x, y, z)`` in EPSG:3857, ``out_shape`` pixels.

    Tiles off the image come back filled with ``fill_value``
    without any fetch. For tiles much coarser than the source pixels,
    pass a `AsyncCogReader.reader_overview` of matching resolution.
    """
    span = 2 * _WEB_MERCATOR_HALF / 2**z
    left = -_WEB_MERCATOR_HALF + x * span
    top = _WEB_MERCATOR_HALF - y * span
    height, width = out_shape
    return await read_reproject(
        reader,
        dst_crs="EPSG:3857",
        dst_transform=_transform_from_bounds(
            left, top - span, left + span, top, width, height
        ),
        window_out=_window(0, 0, width, height),
        resampling=resampling,
    )

geocloud.cog.write_cog(data, dest, *, compress='deflate', level=None, predictor=True, blocksize=512, overviews=True, resampling=None, nodata='auto', descriptions=None, tags=None, creation_options=None, overwrite=True, validate=True, storage_options=None)

Write data as a Cloud-Optimized GeoTIFF at dest.

The COG is built and checked in a private temporary directory, then renamed into place (a local dest) or uploaded (a cloud URI), so dest only ever holds a complete, valid file. See the module docstring for the steps.

Parameters:

Name Type Description Default
data GeoArray | RasterSource

A geoarray.GeoArray with dims y x or <dim> y x (band, level, …; the leading dim becomes the bands, never time), or any lazy geoarray.RasterSource (grid, shape, dtype, fill_value, attrs, read_window), which is staged strip by strip without loading it whole. It must carry a CRS.

required
dest str | PathLike[str]

A local path or a URI geocloud.files can upload to (s3://, gs://, az:// / abfs[s]://, Azure https://).

required
compress str

"deflate" (default), "zstd", "lzw", "lerc" / "lerc_deflate" / "lerc_zstd", "webp", "jpeg" (both 8-bit only) or "none".

'deflate'
level int | None

Compression level (DEFLATE 1-12, ZSTD 1-22, …); None keeps GDAL's default.

None
predictor bool

Apply the predictor GDAL picks for the dtype (horizontal for integers, floating-point for floats) with DEFLATE / LZW / ZSTD — usually a large size win.

True
blocksize int

Tile size in pixels (a power of two; 256 or 512).

512
overviews bool

Build overviews down to a single tile.

True
resampling str | None

Overview resampling ("nearest", "average", "bilinear", "cubic", "cubicspline", "lanczos", "mode", "rms", "gauss"). None picks "nearest" for integer and boolean data (classes and masks keep their values) and "average" for floats.

None
nodata float | int | None | Auto

The nodata value. "auto" (default) takes the data's fill_value when the dtype can hold it (never for a boolean mask, written as uint8 0 / 1); None writes none. An explicit value must fit the dtype.

'auto'
descriptions Sequence[str] | None

Band descriptions; None takes the leading dim's labels (a SpectralAxis's names, which CogSource reads back), else the 0.2 band_names / descriptions attrs.

None
tags Mapping[str, Any] | None

Dataset metadata tags (values written as strings).

None
creation_options Mapping[str, Any] | None

Extra GDAL COG driver options, passed as is ({"NUM_THREADS": "4", "STATISTICS": "YES"}); they win over the keywords above.

None
overwrite bool

Replace an existing dest (default); False raises FileExistsError instead.

True
validate bool

Check the written file is a COG with the expected shape, dtype, tiling and overviews before it reaches dest.

True
storage_options Mapping[str, Any] | None

Forwarded to get_obstore for a cloud dest.

None

Returns:

Type Description
str | Path

dest (a Path for a local destination).

Raises:

Type Description
TypeError

data is not a GeoArray or RasterSource — a georeader GeoTensor / reader is refused with the geoarray.interop.georeader function that converts it.

ValueError

The data is not 2-D / 3-D, has a time dim, or has no CRS, an option is unknown, blocksize is not a power of two, or nodata / descriptions do not fit the data.

FileExistsError

overwrite=False and dest exists.

RuntimeError

validate found the output is not the expected COG.

Examples:

>>> import tempfile, pathlib
>>> import numpy as np, rasterio
>>> from affine import Affine
>>> from geoarray import GeoArray
>>> scene = GeoArray(
...     np.arange(2 * 600 * 600, dtype="float32").reshape(2, 600, 600),
...     Affine(10, 0, 500_000, 0, -10, 4_000_000),
...     "EPSG:32630", fill_value=np.nan,
...     attrs={"band_names": ["red", "nir"]},
... )
>>> path = write_cog(scene, pathlib.Path(tempfile.mkdtemp()) / "scene.tif",
...                  blocksize=256)
>>> with rasterio.open(path) as src:
...     layout = src.tags(ns="IMAGE_STRUCTURE")["LAYOUT"]
...     layout, src.descriptions, src.overviews(1)
('COG', ('red', 'nir'), [2, 4])
Source code in packages/geotoolz-cloud/src/geocloud/_src/cog_write.py
def write_cog(
    data: GeoArray | RasterSource,
    dest: str | os.PathLike[str],
    *,
    compress: str = "deflate",
    level: int | None = None,
    predictor: bool = True,
    blocksize: int = 512,
    overviews: bool = True,
    resampling: str | None = None,
    nodata: float | int | None | Auto = "auto",
    descriptions: Sequence[str] | None = None,
    tags: Mapping[str, Any] | None = None,
    creation_options: Mapping[str, Any] | None = None,
    overwrite: bool = True,
    validate: bool = True,
    storage_options: Mapping[str, Any] | None = None,
) -> str | Path:
    """Write ``data`` as a Cloud-Optimized GeoTIFF at ``dest``.

    The COG is built and checked in a private temporary directory, then
    renamed into place (a local ``dest``) or uploaded (a cloud URI), so
    ``dest`` only ever holds a complete, valid file. See the module
    docstring for the steps.

    Args:
        data: A `geoarray.GeoArray` with dims ``y x`` or ``<dim> y x``
            (``band``, ``level``, …; the leading dim becomes the bands, never
            ``time``), or any lazy `geoarray.RasterSource` (``grid``, ``shape``,
            ``dtype``, ``fill_value``, ``attrs``, ``read_window``), which
            is staged strip by strip without loading it whole. It must
            carry a CRS.
        dest: A local path or a URI `geocloud.files` can upload to
            (``s3://``, ``gs://``, ``az://`` / ``abfs[s]://``, Azure
            ``https://``).
        compress: ``"deflate"`` (default), ``"zstd"``, ``"lzw"``,
            ``"lerc"`` / ``"lerc_deflate"`` / ``"lerc_zstd"``, ``"webp"``,
            ``"jpeg"`` (both 8-bit only) or ``"none"``.
        level: Compression level (DEFLATE 1-12, ZSTD 1-22, …); ``None``
            keeps GDAL's default.
        predictor: Apply the predictor GDAL picks for the dtype
            (horizontal for integers, floating-point for floats) with
            DEFLATE / LZW / ZSTD — usually a large size win.
        blocksize: Tile size in pixels (a power of two; 256 or 512).
        overviews: Build overviews down to a single tile.
        resampling: Overview resampling (``"nearest"``, ``"average"``,
            ``"bilinear"``, ``"cubic"``, ``"cubicspline"``,
            ``"lanczos"``, ``"mode"``, ``"rms"``, ``"gauss"``). ``None``
            picks ``"nearest"`` for integer and boolean data (classes and
            masks keep their values) and ``"average"`` for floats.
        nodata: The nodata value. ``"auto"`` (default) takes the data's
            ``fill_value`` when the dtype can hold it (never for a
            boolean mask, written as ``uint8`` 0 / 1); ``None`` writes
            none. An explicit value must fit the dtype.
        descriptions: Band descriptions; ``None`` takes the leading dim's
            labels (a `SpectralAxis`'s names, which `CogSource` reads back),
            else the 0.2 ``band_names`` / ``descriptions`` attrs.
        tags: Dataset metadata tags (values written as strings).
        creation_options: Extra GDAL ``COG`` driver options, passed as is
            (``{"NUM_THREADS": "4", "STATISTICS": "YES"}``); they win over
            the keywords above.
        overwrite: Replace an existing ``dest`` (default); ``False``
            raises `FileExistsError` instead.
        validate: Check the written file is a COG with the expected
            shape, dtype, tiling and overviews before it reaches ``dest``.
        storage_options: Forwarded to `get_obstore` for a cloud ``dest``.

    Returns:
        ``dest`` (a ``Path`` for a local destination).

    Raises:
        TypeError: ``data`` is not a GeoArray or RasterSource — a georeader
            ``GeoTensor`` / reader is refused with the
            ``geoarray.interop.georeader`` function that converts it.
        ValueError: The data is not 2-D / 3-D, has a ``time`` dim, or has no
            CRS, an option is
            unknown, ``blocksize`` is not a power of two, or ``nodata`` /
            ``descriptions`` do not fit the data.
        FileExistsError: ``overwrite=False`` and ``dest`` exists.
        RuntimeError: ``validate`` found the output is not the expected COG.

    Examples:
        >>> import tempfile, pathlib
        >>> import numpy as np, rasterio
        >>> from affine import Affine
        >>> from geoarray import GeoArray
        >>> scene = GeoArray(
        ...     np.arange(2 * 600 * 600, dtype="float32").reshape(2, 600, 600),
        ...     Affine(10, 0, 500_000, 0, -10, 4_000_000),
        ...     "EPSG:32630", fill_value=np.nan,
        ...     attrs={"band_names": ["red", "nir"]},
        ... )
        >>> path = write_cog(scene, pathlib.Path(tempfile.mkdtemp()) / "scene.tif",
        ...                  blocksize=256)
        >>> with rasterio.open(path) as src:
        ...     layout = src.tags(ns="IMAGE_STRUCTURE")["LAYOUT"]
        ...     layout, src.descriptions, src.overviews(1)
        ('COG', ('red', 'nir'), [2, 4])
    """
    import rasterio
    import rasterio.shutil

    compress = compress.lower()
    if compress not in COMPRESSIONS:
        raise ValueError(
            f"write_cog: compress={compress!r}; choose one of {sorted(COMPRESSIONS)}."
        )
    if blocksize < 16 or blocksize & (blocksize - 1):
        raise ValueError(
            f"write_cog: blocksize must be a power of two >= 16; got {blocksize}."
        )
    reject_georeader(data, "write_cog")
    if not isinstance(data, GeoArray | RasterSource):
        raise TypeError(
            "write_cog takes a geoarray.GeoArray or a geoarray.RasterSource, "
            f"got {type(data).__name__}"
        )
    count, height, width = _bands_hw(data.shape)
    if isinstance(data, GeoArray) and "time" in data.dims:
        # (time, y, x) would otherwise be written as bands
        raise ValueError(
            f"write_cog: a COG holds one scene, got dims {data.dims}; write each "
            "time step to its own COG (geoarray.isel(data, time=i))."
        )
    grid = data.grid
    if grid.crs is None:
        raise ValueError(
            "write_cog: the data has no CRS; a COG without georeferencing is "
            "just a TIFF. Set one on the GeoArray first."
        )
    values = _values(data)
    source_dtype = values.dtype if values is not None else np.dtype(data.dtype)
    dtype = _output_dtype(np.dtype(source_dtype))
    if resampling is None:
        resampling = "average" if dtype.kind == "f" else "nearest"
    resampling = resampling.lower()
    if resampling not in RESAMPLINGS:
        raise ValueError(
            f"write_cog: resampling={resampling!r}; "
            f"choose one of {sorted(RESAMPLINGS)}."
        )
    fill = data.fill_value
    if np.dtype(source_dtype) == np.bool_:
        fill = None  # a mask's False is data, not nodata
    written_nodata = _resolve_nodata(nodata, fill, dtype)
    names = _resolve_descriptions(
        descriptions, _band_labels(data), data.attrs or {}, count
    )

    local = local_path(dest)
    if not overwrite and exists(dest, storage_options=storage_options):
        raise FileExistsError(
            f"write_cog: {redact(str(dest))!r} exists (overwrite=False)."
        )

    options: dict[str, Any] = {
        "COMPRESS": compress.upper(),
        "BLOCKSIZE": blocksize,
        "OVERVIEWS": "AUTO" if overviews else "NONE",
        "RESAMPLING": resampling.upper(),
        "BIGTIFF": "IF_SAFER",
    }
    if level is not None:
        options["LEVEL"] = level
    if predictor and compress in _PREDICTED:
        options["PREDICTOR"] = "YES"
    options.update({str(k).upper(): v for k, v in (creation_options or {}).items()})

    # A temporary directory beside a local `dest` keeps the final rename on
    # one filesystem (atomic); a cloud `dest` stages in the system temp dir.
    if local is not None:
        local = Path(os.path.abspath(local.expanduser()))
        local.parent.mkdir(parents=True, exist_ok=True)
        workdir = tempfile.mkdtemp(prefix=f".{local.name}.", dir=local.parent)
    else:
        workdir = tempfile.mkdtemp(prefix="geocloud-cog-")
    try:
        staged = Path(workdir) / "stage.tif"
        built = Path(workdir) / "cog.tif"
        _stage(
            data,
            grid,
            values,
            staged,
            dtype=dtype,
            count=count,
            height=height,
            width=width,
            blocksize=blocksize,
            nodata=written_nodata,
            descriptions=names,
            tags=tags,
        )
        with rasterio.Env(GDAL_NUM_THREADS="ALL_CPUS"):
            rasterio.shutil.copy(staged, built, driver="COG", **options)
        if validate:
            _check(
                built,
                count=count,
                height=height,
                width=width,
                dtype=dtype,
                blocksize=blocksize,
                overviews=overviews,
            )
        if local is not None:
            os.replace(built, local)
            return local
        upload(built, dest, storage_options=storage_options)
        return str(dest)
    finally:
        shutil.rmtree(workdir, ignore_errors=True)