Skip to content

Running at scale — geopatcher.run

split / merge are the plain loop. These run it faster, in parallel, on another engine, or with random access for ML loaders.

from geopatcher.run import PatchCache, parallel_map

Parallel and prefetched runs

geopatcher.run.parallel_map(patcher, field, operator, *, n_workers=8, backend='thread', mp_context=None, show_progress=False, journal=None, on_error='raise', batch_size=64, hooks=None, max_in_flight=None)

Apply operator to each spatial patch with a reference executor.

Reads happen in the calling process, through patcher.split — so the patcher's boundary mode (pad / reflect / …), its on_error read policy (patcher.errors is populated as usual), the journal and the hooks all apply exactly as they do to a plain split loop. Patches are submitted to the executor as they are read, never more than max_in_flight at a time, so at most max_in_flight patches (plus up to batch_size read-ahead chips on the select_many path) are resident at once. The returned outputs are, of course, all kept.

Process backend: workers are started with an explicit multiprocessing start method — "forkserver" where available (Linux / macOS), "spawn" elsewhere — never the platform fork default, which is unsafe in a process running GDAL / obstore / dask threads. The operator, every patch and every output are pickled to and from the workers, so operator must be a picklable, module-level callable. The field itself is never sent. GeoArray chips and outputs travel in a compact wire form (pixels, grid config, fill, attrs) rebuilt through the constructor in the receiving process.

Parameters:

Name Type Description Default
patcher SpatialPatcher

Spatial patcher that defines the anchor schedule, the boundary mode and the read-error policy.

required
field Field

Field to split into patches.

required
operator Callable[[Any], Any]

Callable applied to each patch's data.

required
n_workers int

Number of worker threads or processes.

8
backend Backend

"thread" for ThreadPoolExecutor or "process" for ProcessPoolExecutor.

'thread'
mp_context str | BaseContext | None

Start method for the process backend: a name ("forkserver", "spawn", "fork") or a multiprocessing context. None (default) picks "forkserver" where available, else "spawn". Ignored by the thread backend.

None
show_progress bool

If True, print a lightweight completion counter to stderr.

False
journal Any | None

Optional PatchJournal. Anchors it already holds an "ok" row for are skipped (no read, no operator call); every processed patch is committed with status="ok" or status="error" (plus the operator runtime and error text), so a crashed or interrupted run resumes where it stopped.

None
on_error ErrorPolicy

Operator-error policy: "raise" to fail fast (queued patches are cancelled), or "skip" to warn and omit failed patches from the returned list. Read errors are governed by patcher.on_error, not by this argument.

'raise'
batch_size int

Maximum number of reads coalesced into one field.select_many call when the field supports it (e.g. CogField); reads are fetched one chunk ahead of the patcher, so at most batch_size chips wait in the read-ahead buffer. No effect on fields without select_many.

64
hooks Iterable[PatcherHook] | None

PatcherHook instances forwarded to patcher.split — they observe the read path (on_patch_done fires when a patch is read, before the operator runs).

None
max_in_flight int | None

Maximum number of patches submitted to the executor and not yet finished. Defaults to 2 * n_workers, enough to keep every worker busy while one batch of results is collected.

None

Returns:

Type Description
list[Patch]

Patches with data replaced by operator(patch.data), ordered by

list[Patch]

the patcher's anchor schedule.

Examples:

Thread pool over a raster, failing fast on any error::

outputs = parallel_map(patcher, field, model, n_workers=8)

Restartable process-pool job that tolerates bad tiles::

patcher = SpatialPatcher(..., on_error="skip")
journal = PatchJournal("out/run.jsonl")
outputs = parallel_map(
    patcher, field, model,
    backend="process", journal=journal, on_error="skip",
)

Explicit start method::

parallel_map(patcher, field, model, backend="process",
             mp_context="spawn")
Source code in packages/geotoolz-patcher/src/geopatcher/_src/runners.py
def parallel_map(
    patcher: SpatialPatcher,
    field: Field,
    operator: Callable[[Any], Any],
    *,
    n_workers: int = 8,
    backend: Backend = "thread",
    mp_context: str | BaseContext | None = None,
    show_progress: bool = False,
    journal: Any | None = None,
    on_error: ErrorPolicy = "raise",
    batch_size: int = 64,
    hooks: Iterable[PatcherHook] | None = None,
    max_in_flight: int | None = None,
) -> list[Patch]:
    """Apply ``operator`` to each spatial patch with a reference executor.

    Reads happen in the calling process, through ``patcher.split`` — so
    the patcher's boundary mode (``pad`` / ``reflect`` / …), its
    ``on_error`` read policy (``patcher.errors`` is populated as usual),
    the ``journal`` and the ``hooks`` all apply exactly as they do to a
    plain ``split`` loop. Patches are submitted to the executor as they
    are read, never more than ``max_in_flight`` at a time, so at most
    ``max_in_flight`` patches (plus up to ``batch_size`` read-ahead chips
    on the ``select_many`` path) are resident at once. The returned
    outputs are, of course, all kept.

    Process backend: workers are started with an explicit
    `multiprocessing` start method — ``"forkserver"`` where available
    (Linux / macOS), ``"spawn"`` elsewhere — never the platform ``fork``
    default, which is unsafe in a process running GDAL / obstore / dask
    threads. The operator, every patch and every output are pickled to
    and from the workers, so ``operator`` must be a picklable,
    module-level callable. The field itself is never sent. `GeoArray`
    chips and outputs travel in a compact wire form (pixels, grid config,
    fill, attrs) rebuilt through the constructor in the receiving process.

    Args:
        patcher: Spatial patcher that defines the anchor schedule, the
            boundary mode and the read-error policy.
        field: Field to split into patches.
        operator: Callable applied to each patch's ``data``.
        n_workers: Number of worker threads or processes.
        backend: ``"thread"`` for `ThreadPoolExecutor` or ``"process"`` for
            `ProcessPoolExecutor`.
        mp_context: Start method for the process backend: a name
            (``"forkserver"``, ``"spawn"``, ``"fork"``) or a
            `multiprocessing` context. ``None`` (default) picks
            ``"forkserver"`` where available, else ``"spawn"``. Ignored by
            the thread backend.
        show_progress: If ``True``, print a lightweight completion counter
            to stderr.
        journal: Optional `PatchJournal`. Anchors it already holds an
            ``"ok"`` row for are skipped (no read, no operator call); every
            processed patch is committed with ``status="ok"`` or
            ``status="error"`` (plus the operator runtime and error text),
            so a crashed or interrupted run resumes where it stopped.
        on_error: Operator-error policy: ``"raise"`` to fail fast (queued
            patches are cancelled), or ``"skip"`` to warn and omit failed
            patches from the returned list. Read errors are governed by
            ``patcher.on_error``, not by this argument.
        batch_size: Maximum number of reads coalesced into one
            ``field.select_many`` call when the field supports it (e.g.
            `CogField`); reads are fetched one chunk ahead of the
            patcher, so at most ``batch_size`` chips wait in the read-ahead
            buffer. No effect on fields without ``select_many``.
        hooks: `PatcherHook` instances forwarded to ``patcher.split`` —
            they observe the read path (``on_patch_done`` fires when a
            patch is read, before the operator runs).
        max_in_flight: Maximum number of patches submitted to the
            executor and not yet finished. Defaults to ``2 * n_workers``,
            enough to keep every worker busy while one batch of results is
            collected.

    Returns:
        Patches with ``data`` replaced by ``operator(patch.data)``, ordered by
        the patcher's anchor schedule.

    Examples:
        Thread pool over a raster, failing fast on any error::

            outputs = parallel_map(patcher, field, model, n_workers=8)

        Restartable process-pool job that tolerates bad tiles::

            patcher = SpatialPatcher(..., on_error="skip")
            journal = PatchJournal("out/run.jsonl")
            outputs = parallel_map(
                patcher, field, model,
                backend="process", journal=journal, on_error="skip",
            )

        Explicit start method::

            parallel_map(patcher, field, model, backend="process",
                         mp_context="spawn")
    """
    if n_workers < 1:
        raise ValueError("n_workers must be >= 1")
    if backend not in {"thread", "process"}:
        raise ValueError("backend must be 'thread' or 'process'")
    if on_error not in {"raise", "skip"}:
        raise ValueError("on_error must be 'raise' or 'skip'")
    if batch_size < 1:
        raise ValueError("batch_size must be >= 1")
    if max_in_flight is None:
        max_in_flight = 2 * n_workers
    if max_in_flight < 1:
        raise ValueError("max_in_flight must be >= 1")
    if backend == "process":
        _ensure_picklable_operator(operator)

    # Materialise the schedule once: the batched path plans its reads from
    # it, the progress counter needs its length, and an unseeded sampler
    # must not place the patches differently from the plan.
    anchors = patcher.anchors(field)
    if journal is not None:
        anchors = [anchor for anchor in anchors if not journal.has(anchor)]

    # Duck-type for the batched-read fast path. Fields that implement
    # ``select_many`` (e.g. ``CogField``) fetch a chunk of reads in
    # one coalesced request. The patcher still drives every read through
    # its own pipeline (boundary padding, ``on_error``), against a wrapper
    # whose ``select`` serves the prefetched chips.
    read_field: Any = field
    if callable(getattr(field, "select_many", None)):
        read_field = _BatchedReadField(field, patcher, anchors, batch_size)

    stream = patcher._split_anchors(read_field, anchors, hooks=hooks, journal=journal)
    with _make_executor(backend, n_workers, mp_context) as executor:
        results = _run(
            executor,
            stream,
            operator,
            to_process=backend == "process",
            max_in_flight=max_in_flight,
            journal=journal,
            on_error=on_error,
            total=len(anchors) if show_progress else None,
        )
    if show_progress:
        print(file=sys.stderr)
    return [patch for _, patch in sorted(results, key=lambda item: item[0])]

geopatcher.run.prefetch_iterable(iterable, prefetch, *, stop=None)

Return iterable with up to prefetch items read ahead.

Parameters:

Name Type Description Default
iterable Iterable[T]

The upstream items, read on a background thread.

required
prefetch int

Read-ahead depth; 0 returns iter(iterable).

required
stop Event | None

Optional stop event shared with the upstream iterator. The prefetch iterator sets it on close() / collection, so an upstream generator blocked in its own interruptible wait (e.g. the patcher's backpressure) can notice and return.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/prefetch.py
def prefetch_iterable[T](
    iterable: Iterable[T], prefetch: int, *, stop: Event | None = None
) -> Iterator[T]:
    """Return ``iterable`` with up to ``prefetch`` items read ahead.

    Args:
        iterable: The upstream items, read on a background thread.
        prefetch: Read-ahead depth; ``0`` returns ``iter(iterable)``.
        stop: Optional stop event shared with the upstream iterator. The
            prefetch iterator sets it on ``close()`` / collection, so an
            upstream generator blocked in its own interruptible wait (e.g.
            the patcher's backpressure) can notice and return.
    """
    if prefetch < 0:
        raise ValueError("prefetch must be >= 0")
    if prefetch == 0:
        return iter(iterable)
    return _PrefetchIterator(iterable, prefetch, stop=stop)

Dask ([dask])

geopatcher.run.to_delayed(patcher, field, operator=None, **kwargs)

Return one Dask delayed task per patch.

Each task computes patcher.patch_at(field, anchor) (then operator(patch) when given). The field is wrapped in a single delayed handle shared by every task. Runner-level policies (on_error, hooks, journal, cache, prefetch) do not apply — see the module docstring.

Parameters:

Name Type Description Default
patcher Any

A SpatialPatcher or TemporalPatcher.

required
field Any

The Field (or, for a TemporalPatcher, series) to patch.

required
operator Any | None

Optional callable mapped over each patch.

None
**kwargs Any

Forwarded to the patcher's key listing and patch_at (time_axis / coord for a TemporalPatcher).

{}

Returns:

Type Description
list[Any]

list[dask.delayed.Delayed] in anchor order.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/dask.py
def to_delayed(
    patcher: Any, field: Any, operator: Any | None = None, **kwargs: Any
) -> list[Any]:
    """Return one Dask delayed task per patch.

    Each task computes ``patcher.patch_at(field, anchor)`` (then
    ``operator(patch)`` when given). The field is wrapped in a single
    delayed handle shared by every task. Runner-level policies
    (``on_error``, hooks, journal, cache, prefetch) do not apply — see
    the module docstring.

    Args:
        patcher: A `SpatialPatcher` or `TemporalPatcher`.
        field: The `Field` (or, for a `TemporalPatcher`, series) to patch.
        operator: Optional callable mapped over each patch.
        **kwargs: Forwarded to the patcher's key listing and ``patch_at``
            (``time_axis`` / ``coord`` for a `TemporalPatcher`).

    Returns:
        ``list[dask.delayed.Delayed]`` in anchor order.
    """
    delayed, patcher_h, field_h = _handles(patcher, field)
    patch_at = delayed(_patch_at, pure=True)
    tasks = [
        patch_at(patcher_h, field_h, key, **kwargs)
        for key in _patch_keys(patcher, field, kwargs)
    ]
    if operator is None:
        return tasks
    return [delayed(operator)(task) for task in tasks]

geopatcher.run.to_dask_bag(patcher, field, **kwargs)

Return a Dask bag with one element (and one partition) per patch.

Built as db.from_sequence(anchors, partition_size=1).map(...) with the field and patcher passed as shared delayed handles, so — as in to_delayed — the field enters the graph once and runner-level policies do not apply.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/dask.py
def to_dask_bag(patcher: Any, field: Any, **kwargs: Any) -> Any:
    """Return a Dask bag with one element (and one partition) per patch.

    Built as ``db.from_sequence(anchors, partition_size=1).map(...)`` with
    the field and patcher passed as shared delayed handles, so — as in
    `to_delayed` — the field enters the graph once and runner-level
    policies do not apply.
    """
    try:
        import dask.bag as db
    except ImportError as exc:
        raise missing_extra("geopatcher.run.to_dask_bag", "dask") from exc

    _, patcher_h, field_h = _handles(patcher, field)
    bag = db.from_sequence(_patch_keys(patcher, field, kwargs), partition_size=1)
    return bag.map(_swap_patch_at, patcher_h, field_h, **kwargs)

Batches of patches

batch_split groups a raster field adapter's patches into fixed-size PatchBatch tuples: the patches as one GeoArray with a patch batch dim (one transform row per patch) and a (patch,) mask of the real ones (ADR-013). The batch is NumPy; move it to JAX once with batch.patches.to_jax() ([jax]), map a model over it with geoarray.map_over, and hand the scored batches straight to patcher.merge (or merge_to_field), which places each row from its transform with the patcher's window weights and drops the padding. unbatch does the placement alone, for code that wants Patch objects.

scored = [
    PatchBatch(geoarray.map_over(patches.to_jax(), model, "patch").to_numpy(), valid)
    for patches, valid in batch_split(patcher, field, batch_size=64)
]
mosaic = patcher.merge_to_field(scored, field)  # GeoArray on the field's grid

A row whose pixel size or rotation differs from the target grid's raises ValueError naming it: merging never resamples.

The grouping, padding and mask are pipekit-array's batch (a PatchBatch has the shape of its Padded, (value, valid)), with geoarray.stack_items stacking each patch's transform as a row.

geopatcher.run.PatchBatch

Bases: NamedTuple

A batch of patches: one carrier and a mask of its real entries.

A NamedTuple, so JAX treats it as a pytree: jitting a step on a whole batch compiles once per patch shape, whatever the patches' positions or the mask.

Attributes:

Name Type Description
patches GeoArray

The patches as one GeoArray with dims ("patch", *patch_dims), a (patch, 6) transform (one row per patch) and the field's CRS, fill, coordinates and attrs. NumPy until the caller calls patches.to_jax().

valid ndarray

(patch,) bool, True for real patches. Padding rows of a final batch copy its last real patch (data and transform row), so they are finite and look like real data.

Example

for patches, valid in batch_split(patcher, field, batch_size=64): ... patches = patches.to_jax() # (64, 4, 256, 256), once ... scores = geoarray.map_over(patches, model, "patch") ... loss = masked_mean(scores.data, valid)

Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
class PatchBatch(NamedTuple):
    """A batch of patches: one carrier and a mask of its real entries.

    A `NamedTuple`, so JAX treats it as a pytree: jitting a step on a
    whole batch compiles once per patch shape, whatever the patches'
    positions or the mask.

    Attributes:
        patches: The patches as one `GeoArray` with dims
            ``("patch", *patch_dims)``, a ``(patch, 6)`` transform (one row
            per patch) and the field's CRS, fill, coordinates and attrs.
            NumPy until the caller calls ``patches.to_jax()``.
        valid: ``(patch,)`` bool, ``True`` for real patches. Padding rows
            of a final batch copy its last real patch (data and transform
            row), so they are finite and look like real data.

    Example:
        >>> for patches, valid in batch_split(patcher, field, batch_size=64):
        ...     patches = patches.to_jax()  # (64, 4, 256, 256), once
        ...     scores = geoarray.map_over(patches, model, "patch")
        ...     loss = masked_mean(scores.data, valid)
    """

    patches: GeoArray
    valid: np.ndarray

geopatcher.run.batch_split(patcher, field, *, batch_size, pad_last=True)

Yield the patches of patcher.split(field) as fixed-size batches.

Groups consecutive patches into batches of exactly batch_size; only the final batch can be short, and pad_last decides what happens to it. The grouping, padding and mask are pipekit_array.batch's (with geoarray.stack_items stacking the transform rows), the rule every padded batch in the stack follows. Every patch must be a GeoArray (any raster field adapter) or a DataArray that reads as a grid (GeoArray.from_xarray), of one shape.

Parameters:

Name Type Description Default
patcher Any

Any patcher exposing split(field) -> Iterator[Patch] (e.g. SpatialPatcher).

required
field Any

The field adapter to split; passed through to patcher.split.

required
batch_size int

Number of patches per batch. Must be positive.

required
pad_last bool

If True (default), a short final batch is padded to batch_size with copies of its last real patch and valid == False, so every batch has one shape (no recompilation on the last batch). If False, the final batch is yielded short, all valid.

True

Yields:

Type Description
PatchBatch

One PatchBatch per batch_size patches, plus a final short

PatchBatch

batch (padded or not, per pad_last) when the patch count is not

PatchBatch

a multiple of batch_size. The batch is NumPy whatever is

PatchBatch

installed.

Raises:

Type Description
ValueError

batch_size is not positive; the patches of one batch differ in shape (boundary="shrink" edge chips) or in fill, coordinates or attrs (geoarray.stack_items). A float patch with no fill takes NaN, so a float field's interior chips and the NaN its boundary="pad" edge chips declare agree.

GridMismatchError

The patches of one batch differ in CRS.

TypeError

A patch is not a raster carrier (a plain array, a DataArray with no grid): stack_patches stacks those.

Example

batches = list(batch_split(patcher, field, batch_size=16)) batches[0].patches.dims ('patch', 'band', 'y', 'x')

Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
def batch_split(
    patcher: Any,
    field: Any,
    *,
    batch_size: int,
    pad_last: bool = True,
) -> Iterator[PatchBatch]:
    """Yield the patches of ``patcher.split(field)`` as fixed-size batches.

    Groups consecutive patches into batches of exactly ``batch_size``; only
    the final batch can be short, and ``pad_last`` decides what happens to
    it. The grouping, padding and mask are `pipekit_array.batch`'s (with
    `geoarray.stack_items` stacking the transform rows), the rule every
    padded batch in the stack follows. Every patch must be a `GeoArray`
    (any raster field adapter) or a ``DataArray`` that reads as a grid
    (`GeoArray.from_xarray`), of one shape.

    Args:
        patcher: Any patcher exposing ``split(field) -> Iterator[Patch]``
            (e.g. `SpatialPatcher`).
        field: The field adapter to split; passed through to
            ``patcher.split``.
        batch_size: Number of patches per batch. Must be positive.
        pad_last: If ``True`` (default), a short final batch is padded to
            ``batch_size`` with copies of its last real patch and
            ``valid == False``, so every batch has one shape (no
            recompilation on the last batch). If ``False``, the final batch
            is yielded short, all valid.

    Yields:
        One `PatchBatch` per ``batch_size`` patches, plus a final short
        batch (padded or not, per ``pad_last``) when the patch count is not
        a multiple of ``batch_size``. The batch is NumPy whatever is
        installed.

    Raises:
        ValueError: ``batch_size`` is not positive; the patches of one
            batch differ in shape (``boundary="shrink"`` edge chips) or in
            fill, coordinates or attrs (`geoarray.stack_items`). A float
            patch with no fill takes NaN, so a float field's interior chips
            and the NaN its ``boundary="pad"`` edge chips declare agree.
        geoarray.GridMismatchError: The patches of one batch differ in CRS.
        TypeError: A patch is not a raster carrier (a plain array, a
            ``DataArray`` with no grid): `stack_patches` stacks those.

    Example:
        >>> batches = list(batch_split(patcher, field, batch_size=16))
        >>> batches[0].patches.dims
        ('patch', 'band', 'y', 'x')
    """
    if batch_size <= 0:
        raise ValueError(f"batch_size must be positive, got {batch_size}")
    from pipekit_array import batch

    items = _batch_items(patcher.split(field), batch_size)
    pad = "last" if pad_last else "none"
    for padded in batch(items, size=batch_size, dim=PATCH, pad=pad):
        yield PatchBatch(padded.value, np.asarray(padded.valid, dtype=bool))

geopatcher.run.unbatch(batch, data=None, *, patcher, domain)

Turn a batch, or a model's output for it, back into Patch objects.

Padding entries (valid == False) are dropped, so a padded final batch gives fewer patches than its length. Each patch is placed from its transform row against domain's grid: its anchor and indices are what patcher.geometry gives that pixel offset, and its weights are patcher.window's, so patcher.merge(unbatch(...), domain) reassembles the field.

Parameters:

Name Type Description Default
batch PatchBatch

A PatchBatch from batch_split.

required
data Any | None

Optional replacement payload, typically the model output for the batch: a GeoArray with the patch dim (from geoarray.map_over) or an array whose rows line up with the batch. Padding rows are ignored.

None
patcher Any

The patcher that split the field (its geometry must be spatial.geometry.Rectangular).

required
domain Any

The field's domain (field.domain, or its bare geoarray.Grid).

required

Returns:

Type Description
list[Patch]

One Patch per valid entry, in batch order, with NumPy data. A row

list[Patch]

that keeps the patch's spatial shape comes back as a GeoArray on

list[Patch]

the patch's grid (a per-pixel output with a new band count drops

list[Patch]

the stale per-band attrs); any other row stays a bare array.

Raises:

Type Description
ValueError

The patcher's geometry is not spatial.geometry.Rectangular, the patches were clipped by boundary="shrink", domain is not a raster domain, or a transform row is not on the domain's pixel grid (another pixel size or rotation, naming the patch, or an origin between pixels).

Example

place = dict(patcher=patcher, domain=field.domain) outs = [ ... p ... for b in batch_split(patcher, field, batch_size=16) ... for p in unbatch(b, model(b.patches), **place) ... ] merged = patcher.merge(outs, field.domain)

Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
def unbatch(
    batch: PatchBatch,
    data: Any | None = None,
    *,
    patcher: Any,
    domain: Any,
) -> list[Patch]:
    """Turn a batch, or a model's output for it, back into `Patch` objects.

    Padding entries (``valid == False``) are dropped, so a padded final
    batch gives fewer patches than its length. Each patch is placed from its
    transform row against ``domain``'s grid: its anchor and indices are what
    ``patcher.geometry`` gives that pixel offset, and its weights are
    ``patcher.window``'s, so
    ``patcher.merge(unbatch(...), domain)`` reassembles the field.

    Args:
        batch: A `PatchBatch` from `batch_split`.
        data: Optional replacement payload, typically the model output for
            the batch: a `GeoArray` with the ``patch`` dim (from
            `geoarray.map_over`) or an array whose rows line up with the
            batch. Padding rows are ignored.
        patcher: The patcher that split the field (its geometry must be
            `spatial.geometry.Rectangular`).
        domain: The field's domain (``field.domain``, or its bare
            `geoarray.Grid`).

    Returns:
        One `Patch` per valid entry, in batch order, with NumPy data. A row
        that keeps the patch's spatial shape comes back as a `GeoArray` on
        the patch's grid (a per-pixel output with a new band count drops
        the stale per-band attrs); any other row stays a bare array.

    Raises:
        ValueError: The patcher's geometry is not
            `spatial.geometry.Rectangular`, the patches were clipped by
            ``boundary="shrink"``, ``domain`` is not a raster domain, or a
            transform row is not on the domain's pixel grid (another pixel
            size or rotation, naming the patch, or an origin between pixels).

    Example:
        >>> place = dict(patcher=patcher, domain=field.domain)
        >>> outs = [
        ...     p
        ...     for b in batch_split(patcher, field, batch_size=16)
        ...     for p in unbatch(b, model(b.patches), **place)
        ... ]
        >>> merged = patcher.merge(outs, field.domain)
    """
    from geopatcher._src.spatial.geometry import Rectangular
    from geopatcher._src.spatial.patcher import _safe_base_weights

    geometry = patcher.geometry
    if not isinstance(geometry, Rectangular):
        raise ValueError(
            "unbatch places a PatchBatch with a Rectangular geometry, got "
            f"{type(geometry).__name__}"
        )
    size = tuple(int(n) for n in geometry.size[-2:])
    if tuple(batch.patches.shape[-2:]) != size:
        # a chip clipped by boundary="shrink": its anchor and window weights
        # cannot be recovered from the transform row alone
        raise ValueError(
            f"unbatch places full {size} patches, got {batch.patches.shape[-2:]} "
            "ones: patches clipped by boundary='shrink' cannot be placed from "
            "their transforms; use boundary='pad', 'reflect' or 'drop'"
        )
    grid = raster_grid(domain)
    if grid is None:
        raise ValueError(
            "unbatch places a PatchBatch on a raster domain (a geoarray.Grid or an "
            f"object with a .grid), got {type(domain).__name__}"
        )
    _check_resolution(batch.patches, grid)
    to_pixel = ~grid.affine
    weights = _safe_base_weights(patcher.window, geometry)
    patches = []
    for i in np.flatnonzero(np.asarray(batch.valid, dtype=bool)):
        item = isel(batch.patches, **{PATCH: int(i)}).to_numpy()
        anchor = _pixel_offset(to_pixel, item)
        if data is None:
            out: Any = item
        elif isinstance(data, GeoArray) and PATCH in data.dims:
            out = isel(data, **{PATCH: int(i)}).to_numpy()
        else:
            out = _rebuild(item, data[i])
        patches.append(
            Patch(
                data=out,
                anchor=anchor,
                indices=geometry.neighborhood(domain, anchor),
                weights=weights,
            )
        )
    return patches

geopatcher.run.stack_patches(patches, attr='data')

Stack a Patch collection's per-patch attr into a single ndarray.

Parameters:

Name Type Description Default
patches Iterable[Any]

Iterable of Patch / TemporalPatch / SpatioTemporalPatch. Materialised to a list internally.

required
attr str

Which patch attribute to stack. Default "data"; "weights" is the other common choice (for COLA normalisation, sample weighting, masking).

'data'

Returns:

Type Description
ndarray

(N, *element_shape) np.ndarray where N == len(patches)

ndarray

and element_shape is the shape every per-patch attr

ndarray

agrees on.

Raises:

Type Description
ValueError

When patches is empty, when any patch's attr is None, when a per-patch attr is not numeric array data (a lazy reader or wrapper that np.asarray turns into a 0-d / object-dtype array), or when the per-patch shapes don't agree. The error message names the first mismatching patch so ragged geometries (spatial.geometry.PolygonIntersection, spatial.geometry.RadiusGraph) surface early rather than producing numpy object arrays.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/stacking.py
def stack_patches(
    patches: Iterable[Any],
    attr: str = "data",
) -> np.ndarray:
    """Stack a `Patch` collection's per-patch ``attr`` into a single ndarray.

    Args:
        patches: Iterable of `Patch` / `TemporalPatch` /
            `SpatioTemporalPatch`. Materialised to a list internally.
        attr: Which patch attribute to stack. Default ``"data"``;
            ``"weights"`` is the other common choice (for COLA
            normalisation, sample weighting, masking).

    Returns:
        ``(N, *element_shape)`` ``np.ndarray`` where ``N == len(patches)``
        and ``element_shape`` is the shape every per-patch ``attr``
        agrees on.

    Raises:
        ValueError: When ``patches`` is empty, when any patch's
            ``attr`` is ``None``, when a per-patch ``attr`` is not numeric
            array data (a lazy reader or wrapper that ``np.asarray`` turns
            into a 0-d / object-dtype array), or when the per-patch shapes don't
            agree. The error message names the first mismatching patch
            so ragged geometries (`spatial.geometry.PolygonIntersection`,
            `spatial.geometry.RadiusGraph`) surface early rather than producing
            numpy object arrays.
    """
    patches_list = list(patches)
    if not patches_list:
        raise ValueError(
            "stack_patches: empty input. Materialise patches first via "
            "list(patcher.split(field)), patcher.patch_at(field, anchor) "
            "(spatial), or patcher.patches_at(series, anchor) (temporal), "
            "and check the field actually has data."
        )

    arrays: list[np.ndarray] = []
    expected_shape: tuple[int, ...] | None = None
    for i, p in enumerate(patches_list):
        value = getattr(p, attr, None)
        if value is None:
            raise ValueError(
                f"stack_patches: patch {i} has {attr}=None — "
                "every patch must carry the requested attribute."
            )
        arr = np.asarray(value)
        if arr.dtype == object or arr.ndim == 0:
            raise ValueError(
                f"stack_patches: patch {i} has {attr} of type "
                f"{type(value).__name__!r}, which converts to a "
                f"{arr.ndim}-d {arr.dtype} array rather than numeric data. "
                "The field's select() must return a materialised array "
                "(e.g. a GeoArray or DataArray), not a lazy reader or a "
                "Field wrapper — call .load() / .values on it first."
            )
        if expected_shape is None:
            expected_shape = arr.shape
        elif arr.shape != expected_shape:
            raise ValueError(
                f"stack_patches: patch {i} has {attr}.shape={arr.shape}, "
                f"expected {expected_shape}. Stacking only works for "
                "uniform-shape geometries (e.g. spatial.geometry.Rectangular, "
                "spatial.geometry.KNNGraph). For ragged geometries "
                "(spatial.geometry.RadiusGraph, "
                "spatial.geometry.PolygonIntersection) keep "
                "the per-patch list and feed your model one patch at a "
                "time, or pad to a common shape first."
            )
        arrays.append(arr)

    return np.stack(arrays, axis=0)

Caching and random access

geopatcher.run.PatchCache dataclass

A local, content-addressed directory cache of read patches.

Parameters:

Name Type Description Default
root str | Path

Directory the cache writes entries under (created if absent). The layout is fsspec-friendly (two-level shard) but v1 is a local filesystem only.

required
max_bytes int | None

Soft cap on the cache size. When a write takes the total over it, least-recently-used entries (by get hit or put) are evicted until the total is back under the cap. An entry that alone exceeds the cap is not stored and a RuntimeWarning is issued. The tally is this instance's: entries other processes write to the same root are only counted once this instance hits them (or on the next construction), so with several writers the cap is per writer. None (default) is unbounded.

None
field_id str | None

Explicit source identity for in-memory fields that have none (a RasterField over an in-memory GeoArray). Leave None for path- or URL-backed fields, whose identity is derived automatically. It replaces only the source part of the key: the domain, band selection and the adapter's cache_id() are still folded in.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
@dataclass
class PatchCache:
    """A local, content-addressed directory cache of read patches.

    Args:
        root: Directory the cache writes entries under (created if
            absent). The layout is fsspec-friendly (two-level shard) but
            v1 is a local filesystem only.
        max_bytes: Soft cap on the cache size. When a write takes the
            total over it, least-recently-used entries (by `get` hit or
            `put`) are evicted until the total is back under the cap.
            An entry that alone exceeds the cap is not stored and a
            `RuntimeWarning` is issued. The tally is this instance's:
            entries other processes write to the same ``root`` are only
            counted once this instance hits them (or on the next
            construction), so with several writers the cap is per
            writer. ``None`` (default) is unbounded.
        field_id: Explicit source identity for in-memory fields that
            have none (a `RasterField` over an in-memory `GeoArray`). Leave
            ``None`` for path- or URL-backed fields, whose identity is
            derived automatically. It replaces only the *source* part of
            the key: the domain, band selection and the adapter's
            ``cache_id()`` are still folded in.
    """

    root: str | Path
    max_bytes: int | None = None
    field_id: str | None = None
    _hits: int = field(default=0, init=False, repr=False)
    _misses: int = field(default=0, init=False, repr=False)
    # Entry path → size, least-recently-used first; `_bytes` is its sum.
    _lru: OrderedDict[Path, int] = field(
        default_factory=OrderedDict, init=False, repr=False, compare=False
    )
    _bytes: int = field(default=0, init=False, repr=False, compare=False)
    _lock: threading.Lock = field(
        default_factory=threading.Lock, init=False, repr=False, compare=False
    )

    def __post_init__(self) -> None:
        self.root = Path(self.root)
        self.root.mkdir(parents=True, exist_ok=True)
        if self.max_bytes is not None and self.max_bytes < 1:
            raise ValueError("max_bytes must be >= 1 (or None for unbounded).")
        self._scan()

    def __getstate__(self) -> dict[str, Any]:
        # A `threading.Lock` doesn't pickle (`IndexedPatchView` ships the
        # cache to DataLoader workers); each copy gets a fresh lock.
        state = self.__dict__.copy()
        del state["_lock"]
        return state

    def __setstate__(self, state: dict[str, Any]) -> None:
        self.__dict__.update(state)
        self._lock = threading.Lock()

    def _scan(self) -> None:
        """Seed the size tally and LRU order from disk (construction only)."""
        found: list[tuple[int, Path, int]] = []
        for path in Path(self.root).rglob("*.npz"):
            with suppress(OSError):
                st = path.stat()
                found.append((st.st_atime_ns, path, st.st_size))
        found.sort(key=lambda item: item[0])  # oldest access first
        self._lru = OrderedDict((path, size) for _, path, size in found)
        self._bytes = sum(self._lru.values())

    # -- key derivation ---------------------------------------------------

    def field_id_for(self, field: Any) -> str:
        """Resolve the identity of everything ``field`` reads.

        The result is ``"<source>|<json>"``:

        - ``source`` — this cache's explicit ``field_id``, else the
          first of: a ``url``, the reader / field file paths
          (``realpath`` + ``st_mtime_ns`` + ``st_size`` of every path),
          the ``encoding["source"]`` file of an xarray-backed field —
          looked up on the field and then on its ``reader`` / ``da`` /
          ``array``. A field exposing only a ``cache_id()`` uses that as
          its source. A plain ``url`` has no version, so an object
          overwritten in place is not detected; adapters that can ask
          the store cheaply (`CogField`: an ETag / size from a
          HEAD) fold that into ``cache_id()``.
        - ``json`` — the field's ``cache_id()`` (per-adapter identity,
          e.g. `CogField`'s store / path / ``ifd_index`` or
          `ReprojectingRasterField`'s ``dst_crs`` / ``resolution`` /
          ``resampling``), the domain (CRS, transform, shape, dtype, or
          a digest of the grid coordinates) and the reader's band
          selection (``indexes``) and boundless ``fill_value``.

        ``cache_id()`` is trusted as-is: it must return a non-empty
        ``str`` (anything else raises `TypeError`) that changes whenever
        the patches the field reads could change; PatchCache cannot
        verify that.

        An xarray-backed field also keys on its variable name (two
        variables of one file share everything else). An adapter whose
        ``cache_id()`` raises `UnstableIdentityError` (an in-memory
        object store) needs an explicit ``field_id``.

        In-memory fields with no source identity raise, since caching
        against nothing would silently serve stale data — including a
        field that wraps an unnamed in-memory reader, whatever its
        ``cache_id()`` says.

        Examples:
            >>> cache = PatchCache("./.cache")
            >>> cache.field_id_for(RasterField(RasterioReader("a.tif")))
            'path:/data/a.tif:1700000000000000000:4096|{"adapter": null, ...}'
            >>> PatchCache("./.cache", field_id="scene").field_id_for(
            ...     RasterField(geotensor)
            ... )
            'scene|{"adapter": null, "domain": {...}, "read": {...}}'
        """
        try:
            adapter_id = _adapter_id(field)
        except UnstableIdentityError as exc:
            if self.field_id is None:
                raise ValueError(
                    f"PatchCache cannot derive a stable identity for a "
                    f"{type(field).__name__}: {exc} Pass field_id=... to "
                    f"PatchCache, distinct for every object it caches."
                ) from exc
            adapter_id = exc.partial
        source = self.field_id if self.field_id is not None else _source_id(field)
        if source is None:
            if adapter_id is None or _wraps_unnamed_source(field):
                raise ValueError(
                    f"PatchCache cannot derive a stable identity for a "
                    f"{type(field).__name__}: it exposes no cache_id(), url, or "
                    f"file path. Pass field_id=... to PatchCache for in-memory "
                    f"fields."
                )
            source = f"id:{adapter_id}"
        signature = {
            "adapter": adapter_id,
            "domain": _domain_signature(field),
            "read": _read_signature(field),
        }
        return f"{source}|{json.dumps(signature, sort_keys=True)}"

    @staticmethod
    def config_id_for(geometry: Any, window: Any) -> str:
        """JSON config key from the geometry + window (byte-affecting axes)."""
        for axis in (geometry, window):
            if getattr(axis, "forbid_in_yaml", False):
                raise ValueError(
                    f"{type(axis).__name__} is forbid_in_yaml (it carries a "
                    f"closure or runtime objects with no faithful config) and "
                    f"cannot be used as a cache key; give it a serialisable "
                    f"config or drop the cache for this run."
                )
        return json.dumps(
            {"geometry": geometry.get_config(), "window": window.get_config()},
            sort_keys=True,
        )

    def _key(self, field_id: str, config_id: str, anchor: Any) -> str:
        h = hashlib.sha256()
        for part in (_FORMAT, field_id, config_id, _anchor_key(anchor)):
            h.update(part.encode("utf-8"))
            h.update(b"\x00")
        return h.hexdigest()

    def _path(self, key: str) -> Path:
        return Path(self.root) / key[:2] / f"{key}.npz"

    # -- get / put --------------------------------------------------------

    def get(self, field_id: str, config_id: str, anchor: Any) -> dict[str, Any] | None:
        """Return the stored payload for a key, or ``None`` on a miss.

        An entry that cannot be decoded — zero-byte, truncated, not a
        zip, or missing the layout's fields — is a miss and is deleted,
        so the following `put` rewrites it.
        """
        path = self._path(self._key(field_id, config_id, anchor))
        try:
            payload = _load_entry(path)
            # Rebuild the carrier here, inside the repair guard: an entry
            # with an unknown kind or inconsistent metadata is as unusable
            # as a torn zip and must not fail later, on every run.
            payload["decoded"] = _decode_carrier(payload)
        except FileNotFoundError:
            with self._lock:
                # Another thread may have published this key between our
                # failed open and taking the lock; only forget a file that
                # is really gone.
                if not path.exists():
                    self._forget(path)
                self._misses += 1
            return None
        except Exception:
            # Any decode failure (zipfile.BadZipFile, EOFError, KeyError,
            # a JSON error, a carrier that won't rebuild, …) means the
            # entry is unusable: repair it.
            with suppress(OSError):
                path.unlink()
            with self._lock:
                self._forget(path)
                self._misses += 1
            return None
        with self._lock:
            self._hits += 1
            if path in self._lru:
                self._lru.move_to_end(path)
            else:  # written by another process since our construction scan
                with suppress(OSError):
                    self._track(path, path.stat().st_size)
        if self.max_bytes is not None:
            # Persist the recency for the next construction scan, even on
            # relatime/noatime mounts.
            with suppress(OSError):
                os.utime(path)
        return payload

    def put(self, field_id: str, config_id: str, anchor: Any, patch: Patch) -> None:
        """Store ``patch``'s reconstructable payload under its key.

        Always (re)writes the entry — `put` follows a miss, so an
        existing file at the key is one `get` could not use. The write
        is atomic: a unique temp file in the shard directory is
        published with ``os.replace``. An entry larger than
        ``max_bytes`` is discarded with a `RuntimeWarning` instead.

        Raises:
            TypeError: The patch carrier cannot be rebuilt bit-identically
                from disk (see `_encode_patch`).
        """
        path = self._path(self._key(field_id, config_id, anchor))
        arrays = _encode_patch(patch)
        path.parent.mkdir(parents=True, exist_ok=True)
        # A unique temp per writer (mkstemp is atomic) so concurrent writers
        # of the same key — same PID across threads included — never share
        # a scratch file; the os.replace then publishes atomically.
        fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
        try:
            with os.fdopen(fd, "wb") as f:
                np.savez(f, **arrays)
                f.flush()
                size = f.tell()
                if self.max_bytes is not None and size > self.max_bytes:
                    warnings.warn(
                        f"PatchCache: a {size}-byte entry exceeds max_bytes="
                        f"{self.max_bytes} and is not cached; raise max_bytes "
                        f"to cache patches of this size.",
                        RuntimeWarning,
                        stacklevel=2,
                    )
                    return
                with suppress(OSError):
                    os.fsync(f.fileno())
            # Publish and account as one step: a `clear` (or a racing
            # miss) between the two would otherwise track a file it had
            # already removed.
            with self._lock:
                os.replace(tmp_name, path)
                self._track(path, size)
                if self.max_bytes is not None and self._bytes > self.max_bytes:
                    self._evict()
        finally:
            with suppress(OSError):
                if os.path.exists(tmp_name):
                    os.unlink(tmp_name)

    def build_patch(self, payload: dict[str, Any], anchor: Any, indices: Any) -> Patch:
        """Rebuild a `Patch` from a stored ``payload`` at ``anchor``/``indices``."""
        data = payload["decoded"] if "decoded" in payload else _decode_carrier(payload)
        weights = payload.get("weights")
        return Patch(data=data, anchor=anchor, indices=indices, weights=weights)

    # -- introspection ----------------------------------------------------

    def stats(self) -> dict[str, Any]:
        """Return ``{"hits", "misses", "bytes", "entries"}`` for the cache.

        ``bytes`` / ``entries`` are the incremental tally (see
        ``max_bytes``) — O(1), no directory walk.
        """
        with self._lock:
            return {
                "hits": self._hits,
                "misses": self._misses,
                "bytes": self._bytes,
                "entries": len(self._lru),
            }

    def clear(self) -> None:
        """Delete every cached entry; reset hit / miss counters.

        An entry whose file cannot be deleted (open in another process
        on Windows, a flaky network filesystem) stays tracked, so
        `stats` and eviction keep counting the bytes still on disk.
        """
        with self._lock:
            for path in Path(self.root).rglob("*.npz"):
                try:
                    path.unlink()
                except FileNotFoundError:
                    pass
                except OSError:
                    if path not in self._lru:
                        self._track(path, _size(path))
                    continue
                self._forget(path)
            # Anything tracked but no longer on disk is gone too.
            for path in [p for p in self._lru if not p.exists()]:
                self._forget(path)
            self._hits = 0
            self._misses = 0

    # -- accounting (callers hold `_lock`) ---------------------------------

    def _track(self, path: Path, size: int) -> None:
        """Record ``path`` as (re)written or found at ``size``, most recent."""
        self._bytes += size - self._lru.pop(path, 0)
        self._lru[path] = size

    def _forget(self, path: Path) -> None:
        self._bytes -= self._lru.pop(path, 0)

    def _evict(self) -> None:
        """Drop least-recently-used entries until under ``max_bytes``.

        The entry just written is the most recent and fits the cap on
        its own (oversize entries are never stored), so it survives.

        An entry is forgotten only once its file is gone: when ``unlink``
        fails (a file held open on Windows, a flaky network filesystem)
        it stays tracked, so `stats` still counts it and a later sweep
        retries it, and the sweep moves on to the next-oldest entry.
        """
        max_bytes = self.max_bytes
        if max_bytes is None:
            return
        for path in list(self._lru):
            if self._bytes <= max_bytes:
                break
            try:
                path.unlink()
            except FileNotFoundError:
                pass  # already gone: just stop counting it
            except OSError:
                continue
            self._forget(path)

build_patch(payload, anchor, indices)

Rebuild a Patch from a stored payload at anchor/indices.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def build_patch(self, payload: dict[str, Any], anchor: Any, indices: Any) -> Patch:
    """Rebuild a `Patch` from a stored ``payload`` at ``anchor``/``indices``."""
    data = payload["decoded"] if "decoded" in payload else _decode_carrier(payload)
    weights = payload.get("weights")
    return Patch(data=data, anchor=anchor, indices=indices, weights=weights)

clear()

Delete every cached entry; reset hit / miss counters.

An entry whose file cannot be deleted (open in another process on Windows, a flaky network filesystem) stays tracked, so stats and eviction keep counting the bytes still on disk.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def clear(self) -> None:
    """Delete every cached entry; reset hit / miss counters.

    An entry whose file cannot be deleted (open in another process
    on Windows, a flaky network filesystem) stays tracked, so
    `stats` and eviction keep counting the bytes still on disk.
    """
    with self._lock:
        for path in Path(self.root).rglob("*.npz"):
            try:
                path.unlink()
            except FileNotFoundError:
                pass
            except OSError:
                if path not in self._lru:
                    self._track(path, _size(path))
                continue
            self._forget(path)
        # Anything tracked but no longer on disk is gone too.
        for path in [p for p in self._lru if not p.exists()]:
            self._forget(path)
        self._hits = 0
        self._misses = 0

config_id_for(geometry, window) staticmethod

JSON config key from the geometry + window (byte-affecting axes).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
@staticmethod
def config_id_for(geometry: Any, window: Any) -> str:
    """JSON config key from the geometry + window (byte-affecting axes)."""
    for axis in (geometry, window):
        if getattr(axis, "forbid_in_yaml", False):
            raise ValueError(
                f"{type(axis).__name__} is forbid_in_yaml (it carries a "
                f"closure or runtime objects with no faithful config) and "
                f"cannot be used as a cache key; give it a serialisable "
                f"config or drop the cache for this run."
            )
    return json.dumps(
        {"geometry": geometry.get_config(), "window": window.get_config()},
        sort_keys=True,
    )

field_id_for(field)

Resolve the identity of everything field reads.

The result is "<source>|<json>":

  • source — this cache's explicit field_id, else the first of: a url, the reader / field file paths (realpath + st_mtime_ns + st_size of every path), the encoding["source"] file of an xarray-backed field — looked up on the field and then on its reader / da / array. A field exposing only a cache_id() uses that as its source. A plain url has no version, so an object overwritten in place is not detected; adapters that can ask the store cheaply (CogField: an ETag / size from a HEAD) fold that into cache_id().
  • json — the field's cache_id() (per-adapter identity, e.g. CogField's store / path / ifd_index or ReprojectingRasterField's dst_crs / resolution / resampling), the domain (CRS, transform, shape, dtype, or a digest of the grid coordinates) and the reader's band selection (indexes) and boundless fill_value.

cache_id() is trusted as-is: it must return a non-empty str (anything else raises TypeError) that changes whenever the patches the field reads could change; PatchCache cannot verify that.

An xarray-backed field also keys on its variable name (two variables of one file share everything else). An adapter whose cache_id() raises UnstableIdentityError (an in-memory object store) needs an explicit field_id.

In-memory fields with no source identity raise, since caching against nothing would silently serve stale data — including a field that wraps an unnamed in-memory reader, whatever its cache_id() says.

Examples:

>>> cache = PatchCache("./.cache")
>>> cache.field_id_for(RasterField(RasterioReader("a.tif")))
'path:/data/a.tif:1700000000000000000:4096|{"adapter": null, ...}'
>>> PatchCache("./.cache", field_id="scene").field_id_for(
...     RasterField(geotensor)
... )
'scene|{"adapter": null, "domain": {...}, "read": {...}}'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def field_id_for(self, field: Any) -> str:
    """Resolve the identity of everything ``field`` reads.

    The result is ``"<source>|<json>"``:

    - ``source`` — this cache's explicit ``field_id``, else the
      first of: a ``url``, the reader / field file paths
      (``realpath`` + ``st_mtime_ns`` + ``st_size`` of every path),
      the ``encoding["source"]`` file of an xarray-backed field —
      looked up on the field and then on its ``reader`` / ``da`` /
      ``array``. A field exposing only a ``cache_id()`` uses that as
      its source. A plain ``url`` has no version, so an object
      overwritten in place is not detected; adapters that can ask
      the store cheaply (`CogField`: an ETag / size from a
      HEAD) fold that into ``cache_id()``.
    - ``json`` — the field's ``cache_id()`` (per-adapter identity,
      e.g. `CogField`'s store / path / ``ifd_index`` or
      `ReprojectingRasterField`'s ``dst_crs`` / ``resolution`` /
      ``resampling``), the domain (CRS, transform, shape, dtype, or
      a digest of the grid coordinates) and the reader's band
      selection (``indexes``) and boundless ``fill_value``.

    ``cache_id()`` is trusted as-is: it must return a non-empty
    ``str`` (anything else raises `TypeError`) that changes whenever
    the patches the field reads could change; PatchCache cannot
    verify that.

    An xarray-backed field also keys on its variable name (two
    variables of one file share everything else). An adapter whose
    ``cache_id()`` raises `UnstableIdentityError` (an in-memory
    object store) needs an explicit ``field_id``.

    In-memory fields with no source identity raise, since caching
    against nothing would silently serve stale data — including a
    field that wraps an unnamed in-memory reader, whatever its
    ``cache_id()`` says.

    Examples:
        >>> cache = PatchCache("./.cache")
        >>> cache.field_id_for(RasterField(RasterioReader("a.tif")))
        'path:/data/a.tif:1700000000000000000:4096|{"adapter": null, ...}'
        >>> PatchCache("./.cache", field_id="scene").field_id_for(
        ...     RasterField(geotensor)
        ... )
        'scene|{"adapter": null, "domain": {...}, "read": {...}}'
    """
    try:
        adapter_id = _adapter_id(field)
    except UnstableIdentityError as exc:
        if self.field_id is None:
            raise ValueError(
                f"PatchCache cannot derive a stable identity for a "
                f"{type(field).__name__}: {exc} Pass field_id=... to "
                f"PatchCache, distinct for every object it caches."
            ) from exc
        adapter_id = exc.partial
    source = self.field_id if self.field_id is not None else _source_id(field)
    if source is None:
        if adapter_id is None or _wraps_unnamed_source(field):
            raise ValueError(
                f"PatchCache cannot derive a stable identity for a "
                f"{type(field).__name__}: it exposes no cache_id(), url, or "
                f"file path. Pass field_id=... to PatchCache for in-memory "
                f"fields."
            )
        source = f"id:{adapter_id}"
    signature = {
        "adapter": adapter_id,
        "domain": _domain_signature(field),
        "read": _read_signature(field),
    }
    return f"{source}|{json.dumps(signature, sort_keys=True)}"

get(field_id, config_id, anchor)

Return the stored payload for a key, or None on a miss.

An entry that cannot be decoded — zero-byte, truncated, not a zip, or missing the layout's fields — is a miss and is deleted, so the following put rewrites it.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def get(self, field_id: str, config_id: str, anchor: Any) -> dict[str, Any] | None:
    """Return the stored payload for a key, or ``None`` on a miss.

    An entry that cannot be decoded — zero-byte, truncated, not a
    zip, or missing the layout's fields — is a miss and is deleted,
    so the following `put` rewrites it.
    """
    path = self._path(self._key(field_id, config_id, anchor))
    try:
        payload = _load_entry(path)
        # Rebuild the carrier here, inside the repair guard: an entry
        # with an unknown kind or inconsistent metadata is as unusable
        # as a torn zip and must not fail later, on every run.
        payload["decoded"] = _decode_carrier(payload)
    except FileNotFoundError:
        with self._lock:
            # Another thread may have published this key between our
            # failed open and taking the lock; only forget a file that
            # is really gone.
            if not path.exists():
                self._forget(path)
            self._misses += 1
        return None
    except Exception:
        # Any decode failure (zipfile.BadZipFile, EOFError, KeyError,
        # a JSON error, a carrier that won't rebuild, …) means the
        # entry is unusable: repair it.
        with suppress(OSError):
            path.unlink()
        with self._lock:
            self._forget(path)
            self._misses += 1
        return None
    with self._lock:
        self._hits += 1
        if path in self._lru:
            self._lru.move_to_end(path)
        else:  # written by another process since our construction scan
            with suppress(OSError):
                self._track(path, path.stat().st_size)
    if self.max_bytes is not None:
        # Persist the recency for the next construction scan, even on
        # relatime/noatime mounts.
        with suppress(OSError):
            os.utime(path)
    return payload

put(field_id, config_id, anchor, patch)

Store patch's reconstructable payload under its key.

Always (re)writes the entry — put follows a miss, so an existing file at the key is one get could not use. The write is atomic: a unique temp file in the shard directory is published with os.replace. An entry larger than max_bytes is discarded with a RuntimeWarning instead.

Raises:

Type Description
TypeError

The patch carrier cannot be rebuilt bit-identically from disk (see _encode_patch).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def put(self, field_id: str, config_id: str, anchor: Any, patch: Patch) -> None:
    """Store ``patch``'s reconstructable payload under its key.

    Always (re)writes the entry — `put` follows a miss, so an
    existing file at the key is one `get` could not use. The write
    is atomic: a unique temp file in the shard directory is
    published with ``os.replace``. An entry larger than
    ``max_bytes`` is discarded with a `RuntimeWarning` instead.

    Raises:
        TypeError: The patch carrier cannot be rebuilt bit-identically
            from disk (see `_encode_patch`).
    """
    path = self._path(self._key(field_id, config_id, anchor))
    arrays = _encode_patch(patch)
    path.parent.mkdir(parents=True, exist_ok=True)
    # A unique temp per writer (mkstemp is atomic) so concurrent writers
    # of the same key — same PID across threads included — never share
    # a scratch file; the os.replace then publishes atomically.
    fd, tmp_name = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
    try:
        with os.fdopen(fd, "wb") as f:
            np.savez(f, **arrays)
            f.flush()
            size = f.tell()
            if self.max_bytes is not None and size > self.max_bytes:
                warnings.warn(
                    f"PatchCache: a {size}-byte entry exceeds max_bytes="
                    f"{self.max_bytes} and is not cached; raise max_bytes "
                    f"to cache patches of this size.",
                    RuntimeWarning,
                    stacklevel=2,
                )
                return
            with suppress(OSError):
                os.fsync(f.fileno())
        # Publish and account as one step: a `clear` (or a racing
        # miss) between the two would otherwise track a file it had
        # already removed.
        with self._lock:
            os.replace(tmp_name, path)
            self._track(path, size)
            if self.max_bytes is not None and self._bytes > self.max_bytes:
                self._evict()
    finally:
        with suppress(OSError):
            if os.path.exists(tmp_name):
                os.unlink(tmp_name)

stats()

Return {"hits", "misses", "bytes", "entries"} for the cache.

bytes / entries are the incremental tally (see max_bytes) — O(1), no directory walk.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
def stats(self) -> dict[str, Any]:
    """Return ``{"hits", "misses", "bytes", "entries"}`` for the cache.

    ``bytes`` / ``entries`` are the incremental tally (see
    ``max_bytes``) — O(1), no directory walk.
    """
    with self._lock:
        return {
            "hits": self._hits,
            "misses": self._misses,
            "bytes": self._bytes,
            "entries": len(self._lru),
        }

geopatcher.run.UnstableIdentityError

Bases: ValueError

A field's cache_id() cannot name what it reads stably.

Raised by an adapter whose source has no identity that survives the process (an in-memory object store, say). PatchCache then requires an explicit field_id and keys on it plus partial — the rest of the adapter's identity (IFD, reprojection parameters, …).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
class UnstableIdentityError(ValueError):
    """A field's ``cache_id()`` cannot name what it reads stably.

    Raised by an adapter whose source has no identity that survives the
    process (an in-memory object store, say). `PatchCache` then requires
    an explicit ``field_id`` and keys on it plus ``partial`` — the rest
    of the adapter's identity (IFD, reprojection parameters, …).
    """

    def __init__(self, message: str, *, partial: str) -> None:
        super().__init__(message)
        self.partial = partial

geopatcher.run.IndexedPatchView dataclass

Bases: Sequence[Patch]

Integer-indexed view over a patcher's anchors.

Wraps a (patcher, field) pair as a Sequence[Patch] — supports len(view), view[i], for p in view, and negative indexing. view[i] is bit-identical to the i-th patch patcher.split(field) yields.

Cache accesses are guarded by a threading.Lock, so a view shared across threads (e.g. a torch DataLoader with num_workers=0 plus background threads) is safe.

The view pickles, so it can be shipped to worker processes under any start method — spawn (the macOS / Windows default), forkserver (the Linux default from Python 3.14), fork, and Grain's multiprocess RandomAccessDataSource. The anchor list and the bound PatchCache identity travel with it; the lock is recreated and the in-memory cache=True entries are dropped, so each worker starts with its own empty cache (entries are never shared back to the parent). The patcher and the field must pickle too — every built-in Field adapter does.

Parameters:

Name Type Description Default
patcher Any

A patcher exposing anchors(field) -> list and patch_at(field, anchor) -> Patch. SpatialPatcher and TemporalPatcher satisfy this; other patchers can opt in by providing the same two methods. A patcher that also has patch_anchors(field) — one key per patch split yields, as TemporalPatcher provides for multi-scale geometries — is indexed by those keys instead.

required
field Any

The Field (or, for TemporalPatcher, the series) to read from.

required
cache bool | Any

If True, cache patches in memory by integer index after the first access (mirrors xrpatcher's cache=True). A PatchCache instead routes reads through the cross-run, content-addressed on-disk cache (jejjohnson/geopatcher#24); preload and cache_size do not apply in that mode, and the patcher's patch_at must accept cache= (SpatialPatcher's does; TemporalPatcher's does not).

False
preload bool

If True and cache=True, eagerly materialise each patch's data (via xarray.DataArray.load / dask.compute / numpy passthrough) before caching, so cached entries are fully in RAM rather than lazy views. Requires cache=True. Mirrors xrpatcher's preload=True.

False
cache_size int | None

Optional LRU bound on the number of cached patches. None (default) keeps the cache unbounded, matching xrpatcher's behaviour. Requires cache=True.

None
patcher_kwargs dict[str, Any]

Extra keyword arguments forwarded to every anchors / patch_anchors / patch_at call — e.g. {"time_axis": 1, "coord": times} for a TemporalPatcher.

field(default_factory=dict)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/indexed.py
@dataclass
class IndexedPatchView(Sequence[Patch]):
    """Integer-indexed view over a patcher's anchors.

    Wraps a ``(patcher, field)`` pair as a ``Sequence[Patch]`` —
    supports ``len(view)``, ``view[i]``, ``for p in view``, and negative
    indexing. ``view[i]`` is bit-identical to the ``i``-th patch
    `patcher.split(field)` yields.

    Cache accesses are guarded by a `threading.Lock`, so a view shared
    across threads (e.g. a torch DataLoader with ``num_workers=0`` plus
    background threads) is safe.

    The view pickles, so it can be shipped to worker *processes* under
    any start method — ``spawn`` (the macOS / Windows default),
    ``forkserver`` (the Linux default from Python 3.14), ``fork``, and
    Grain's multiprocess ``RandomAccessDataSource``. The anchor list and
    the bound `PatchCache` identity travel with it; the lock is
    recreated and the in-memory ``cache=True`` entries are dropped, so
    each worker starts with its own empty cache (entries are never
    shared back to the parent). The patcher and the field must pickle
    too — every built-in `Field` adapter does.

    Args:
        patcher: A patcher exposing ``anchors(field) -> list`` and
            ``patch_at(field, anchor) -> Patch``. `SpatialPatcher` and
            `TemporalPatcher` satisfy this; other patchers can opt in by
            providing the same two methods. A patcher that also has
            ``patch_anchors(field)`` — one key per patch ``split``
            yields, as `TemporalPatcher` provides for multi-scale
            geometries — is indexed by those keys instead.
        field: The `Field` (or, for `TemporalPatcher`, the series) to
            read from.
        cache: If ``True``, cache patches in memory by integer index after
            the first access (mirrors xrpatcher's ``cache=True``). A
            `PatchCache` instead routes reads through the cross-run,
            content-addressed on-disk cache (jejjohnson/geopatcher#24); ``preload`` and
            ``cache_size`` do not apply in that mode, and the patcher's
            ``patch_at`` must accept ``cache=`` (`SpatialPatcher`'s does;
            `TemporalPatcher`'s does not).
        preload: If ``True`` and ``cache=True``, eagerly materialise each
            patch's data (via `xarray.DataArray.load` / `dask.compute` /
            numpy passthrough) before caching, so cached entries are
            fully in RAM rather than lazy views. Requires
            ``cache=True``. Mirrors xrpatcher's ``preload=True``.
        cache_size: Optional LRU bound on the number of cached patches.
            ``None`` (default) keeps the cache unbounded, matching
            xrpatcher's behaviour. Requires ``cache=True``.
        patcher_kwargs: Extra keyword arguments forwarded to every
            ``anchors`` / ``patch_anchors`` / ``patch_at`` call — e.g.
            ``{"time_axis": 1, "coord": times}`` for a `TemporalPatcher`.
    """

    patcher: Any
    field: Any
    cache: bool | Any = False
    preload: bool = False
    cache_size: int | None = None
    patcher_kwargs: dict[str, Any] = field(default_factory=dict)
    _anchors: list[Any] = field(default_factory=list, init=False, repr=False)
    _cache: OrderedDict[int, Patch] = field(
        default_factory=OrderedDict, init=False, repr=False
    )
    _disk_cache: Any = field(default=None, init=False, repr=False, compare=False)
    _field_id: str | None = field(default=None, init=False, repr=False, compare=False)
    _patch_at_takes_field_id: bool = field(
        default=False, init=False, repr=False, compare=False
    )
    _cache_lock: threading.Lock = field(
        default_factory=threading.Lock, init=False, repr=False, compare=False
    )

    def __post_init__(self) -> None:
        # A non-bool `cache` is a `PatchCache` (content-addressed, on-disk);
        # `cache=True` is the in-memory index cache. `preload` / `cache_size`
        # only apply to the latter.
        self._disk_cache = None if isinstance(self.cache, bool) else self.cache
        mem_cache = self.cache is True
        for name, given in (
            ("preload=True", self.preload),
            ("cache_size", self.cache_size is not None),
        ):
            if not given or mem_cache:
                continue
            if self._disk_cache is not None:
                raise ValueError(
                    f"{name} applies only to the in-memory cache (cache=True); "
                    "a PatchCache already serves materialised patches from "
                    f"disk. Drop {name}, or pass cache=True instead."
                )
            raise ValueError(f"{name} requires cache=True.")
        if self.cache_size is not None and self.cache_size < 1:
            raise ValueError("cache_size must be >= 1 (or None for unbounded).")
        anchors = getattr(self.patcher, "patch_anchors", None) or getattr(
            self.patcher, "anchors", None
        )
        patch_at = getattr(self.patcher, "patch_at", None)
        if anchors is None or patch_at is None:
            raise TypeError(
                "IndexedPatchView needs a patcher with both `anchors(field)` "
                "and `patch_at(field, anchor)`; got "
                f"{type(self.patcher).__name__}."
            )
        if self._disk_cache is not None and not _accepts_kwarg(patch_at, "cache"):
            raise TypeError(
                "cache=PatchCache(...) needs a patcher whose "
                "`patch_at(field, anchor, *, cache=...)` accepts a cache; "
                f"{type(self.patcher).__name__}.patch_at does not. Use "
                "cache=True for the in-memory index cache instead."
            )
        self._anchors = list(anchors(self.field, **self.patcher_kwargs))
        self._patch_at_takes_field_id = _accepts_kwarg(patch_at, "field_id")

    def __getstate__(self) -> dict[str, Any]:
        # `threading.Lock` doesn't pickle, and in-memory cache entries are
        # process-local by design: ship the anchors, the bound PatchCache
        # identity and the configuration, not the cached patches.
        state = self.__dict__.copy()
        del state["_cache_lock"]
        state["_cache"] = OrderedDict()
        return state

    def __setstate__(self, state: dict[str, Any]) -> None:
        self.__dict__.update(state)
        self._cache_lock = threading.Lock()

    def __len__(self) -> int:
        return len(self._anchors)

    @overload
    def __getitem__(self, idx: int) -> Patch: ...

    @overload
    def __getitem__(self, idx: slice) -> list[Patch]: ...

    def __getitem__(self, idx: int | slice) -> Patch | list[Patch]:
        if isinstance(idx, slice):
            return [self[i] for i in range(*idx.indices(len(self._anchors)))]
        try:
            # `operator.index`, not `int`: ``view[1.9]`` must not silently
            # read patch 1. numpy integers still work.
            i = operator.index(idx)
        except TypeError:
            raise TypeError(
                "IndexedPatchView indices must be integers or slices, not "
                f"{type(idx).__name__}."
            ) from None
        if i < 0:
            i += len(self._anchors)
        if i < 0 or i >= len(self._anchors):
            raise IndexError(
                f"IndexedPatchView index {idx} out of range [0, {len(self._anchors)})"
            )
        kwargs = self.patcher_kwargs
        if self._disk_cache is not None:
            # Only reached when `patch_at` accepts ``cache=`` (checked at
            # construction). A patcher written against the original
            # protocol, ``patch_at(field, anchor, cache=...)``, does not
            # also get ``field_id=``.
            kwargs = {**kwargs, "cache": self._disk_cache}
            if self._patch_at_takes_field_id:
                kwargs["field_id"] = self._disk_field_id()
            return self.patcher.patch_at(self.field, self._anchors[i], **kwargs)
        if self.cache:
            with self._cache_lock:
                cached = self._cache.get(i)
                if cached is not None:
                    self._cache.move_to_end(i)
                    return cached
        patch = self.patcher.patch_at(self.field, self._anchors[i], **kwargs)
        if self.cache:
            if self.preload:
                patch = _materialise(patch)
            with self._cache_lock:
                # Two threads may race to build the same index; keep the
                # first stored entry so repeated reads return one object.
                existing = self._cache.get(i)
                if existing is not None:
                    self._cache.move_to_end(i)
                    return existing
                self._cache[i] = patch
                if self.cache_size is not None:
                    while len(self._cache) > self.cache_size:
                        self._cache.popitem(last=False)
        return patch

    def _disk_field_id(self) -> str:
        """The field's `PatchCache` identity, resolved once per view.

        Like the anchor list, it is bound when first needed: deriving it
        per item would stat files — or, for `CogField`, send a
        ``HEAD`` — on every ``view[i]``. A source changed after that is
        not noticed by this view; build a new one to pick it up.
        """
        with self._cache_lock:
            if self._field_id is None:
                self._field_id = self._disk_cache.field_id_for(self.field)
            return self._field_id

    @property
    def anchors(self) -> list[Any]:
        """The materialised anchor list this view dispatches into.

        Same sequence ``patcher.anchors(field)`` (or
        ``patcher.patch_anchors(field)`` when the patcher has it) returned
        at construction time; exposed so callers can correlate ``view[i]`` with the
        underlying anchor without going through `patch_at`.
        """
        return list(self._anchors)

    def clear_cache(self) -> None:
        """Drop any cached patches; subsequent reads go back through `patch_at`."""
        with self._cache_lock:
            self._cache.clear()

anchors property

The materialised anchor list this view dispatches into.

Same sequence patcher.anchors(field) (or patcher.patch_anchors(field) when the patcher has it) returned at construction time; exposed so callers can correlate view[i] with the underlying anchor without going through patch_at.

clear_cache()

Drop any cached patches; subsequent reads go back through patch_at.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/indexed.py
def clear_cache(self) -> None:
    """Drop any cached patches; subsequent reads go back through `patch_at`."""
    with self._cache_lock:
        self._cache.clear()