Skip to content

Patch — geocatalog.patch

The bridge to geopatcher: turn catalog rows into a RasterField to split, or iterate a catalog's footprint as a patcher Domain. field_for needs the [patch] extra.

Fields from a catalog

geocatalog.patch.field_for(catalog, slice_=None, *, asset=None, band_indexes=None, resampling=None, merge_method='last', nodata=None, materialize=True, mode='raster')

field_for(catalog: InMemoryGeoCatalog, slice_: GeoSlice | None = ..., *, asset: str | None = ..., band_indexes: Sequence[int] | None = ..., resampling: Any | None = ..., merge_method: str = ..., nodata: float | None = ..., materialize: Literal[True] = ..., mode: str = ...) -> RasterField
field_for(catalog: InMemoryGeoCatalog, slice_: GeoSlice | None = ..., *, asset: str | None = ..., band_indexes: Sequence[int] | None = ..., resampling: Any | None = ..., merge_method: str = ..., nodata: float | None = ..., materialize: Literal[False], mode: str = ...) -> list[RasterField]

Build a geopatcher RasterField over a staged catalog.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

A raster catalog whose rows reference local files — typically the output of stage().

required
slice_ GeoSlice | None

The grid to build the field on: its bounds, CRS and resolution. None covers the whole catalog in the catalog CRS, on the first row's file grid (resolution and pixel alignment; that file must then be in the catalog CRS), with the bounds grown outward to whole pixels. With materialize=False it selects every row and needs no grid.

None
asset str | None

Asset key to read from each row's assets map. None reads the row's filepath — the right default for build_raster_catalog catalogs, which carry no map.

None
band_indexes Sequence[int] | None

1-indexed bands to keep (see load_raster).

None
resampling Any | None

A rasterio.enums.Resampling for files whose grid differs from the slice (default bilinear; use Resampling.nearest for categorical rasters).

None
merge_method str

How overlapping rows combine (see load_raster).

'last'
nodata float | None

Nodata override for the mosaic (see load_raster).

None
materialize bool

True (default) reads and mosaics the selected rows into one geoarray.GeoArray on the slice grid and wraps it — a field SpatialPatcher.split / merge can round-trip, whose domain is that GeoArray. False reads nothing and returns one lazy field per selected row (catalog order), each over a lazy geoarray.RasterSource in its file's own CRS and grid (its domain.grid); each select reads its window on demand, restricted to band_indexes. There is no mosaic and no reprojection on this path (resampling, merge_method and nodata do not apply).

True
mode str

Field flavour; only "raster" is supported.

'raster'

Returns:

Type Description
RasterField | list[RasterField]

One RasterField (materialize=True) or a list of lazy ones.

Raises:

Type Description
ImportError

If geopatcher, or (for materialize=False) georeader, is missing — both come with the [patch] extra.

TypeError

If slice_ is a string (asset is keyword-only).

ValueError

If mode is unsupported, the backend is not raster, the catalog (or the slice's selection) is empty, or slice_ is None and the grid cannot be inferred.

KeyError

If asset is missing from a row's asset map, or a resolved path is a non-local URI — which happens when stage(on_error="skip") kept an unstaged URI. The message names the offending rows so the caller can re-stage or drop them.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/patch/field_for.py
def field_for(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice | None = None,
    *,
    asset: str | None = None,
    band_indexes: Sequence[int] | None = None,
    resampling: Any | None = None,
    merge_method: str = "last",
    nodata: float | None = None,
    materialize: bool = True,
    mode: str = "raster",
) -> RasterField | list[RasterField]:
    """Build a geopatcher `RasterField` over a staged catalog.

    Args:
        catalog: A raster catalog whose rows reference local files —
            typically the output of `stage()`.
        slice_: The grid to build the field on: its bounds, CRS and
            resolution. ``None`` covers the whole catalog in the
            catalog CRS, on the first row's file grid (resolution and
            pixel alignment; that file must then be in the catalog CRS),
            with the bounds grown outward to whole pixels. With
            ``materialize=False`` it selects every row and needs no grid.
        asset: Asset key to read from each row's ``assets`` map.
            ``None`` reads the row's ``filepath`` — the right default
            for `build_raster_catalog` catalogs, which carry no map.
        band_indexes: 1-indexed bands to keep (see `load_raster`).
        resampling: A ``rasterio.enums.Resampling`` for files whose
            grid differs from the slice (default bilinear; use
            ``Resampling.nearest`` for categorical rasters).
        merge_method: How overlapping rows combine (see `load_raster`).
        nodata: Nodata override for the mosaic (see `load_raster`).
        materialize: ``True`` (default) reads and mosaics the selected
            rows into one `geoarray.GeoArray` on the slice grid and wraps
            it — a field `SpatialPatcher.split` / ``merge`` can
            round-trip, whose ``domain`` is that GeoArray. ``False``
            reads nothing and returns one lazy field per selected row
            (catalog order), each over a lazy `geoarray.RasterSource`
            in its file's own CRS and grid (its ``domain.grid``); each
            ``select`` reads its window on demand, restricted to
            ``band_indexes``. There is no mosaic and no reprojection on
            this path (``resampling``, ``merge_method`` and ``nodata``
            do not apply).
        mode: Field flavour; only ``"raster"`` is supported.

    Returns:
        One `RasterField` (``materialize=True``) or a list of lazy ones.

    Raises:
        ImportError: If geopatcher, or (for ``materialize=False``)
            georeader, is missing — both come with the ``[patch]`` extra.
        TypeError: If ``slice_`` is a string (``asset`` is keyword-only).
        ValueError: If ``mode`` is unsupported, the backend is not
            raster, the catalog (or the slice's selection) is empty, or
            ``slice_`` is ``None`` and the grid cannot be inferred.
        KeyError: If ``asset`` is missing from a row's asset map, or a
            resolved path is a non-local URI — which happens when
            ``stage(on_error="skip")`` kept an unstaged URI. The message
            names the offending rows so the caller can re-stage or drop
            them.
    """
    try:
        from geopatcher import RasterField
    except ImportError as exc:
        raise missing_extra(
            "`field_for()`", "patch", packages="geotoolz-patcher"
        ) from exc

    if isinstance(slice_, str):
        raise TypeError(
            f"field_for(catalog, {slice_!r}): the second argument is a GeoSlice; "
            f"pass the asset by keyword — field_for(catalog, asset={slice_!r})."
        )
    if mode != "raster":
        raise ValueError(f"field_for(mode={mode!r}): only 'raster' is supported today.")
    # `kind` is set by every catalog constructor we ship; tolerate
    # third-party catalogs that omit it by skipping the check rather
    # than crashing with AttributeError.
    kind = _catalog_kind(catalog)
    if kind is not None and kind != "raster":
        raise ValueError(
            f"field_for(mode='raster') requires a raster catalog; "
            f"got kind={kind!r}. Pass a catalog produced by "
            "`build_raster_catalog` / `stage()` over raster sources."
        )
    if len(catalog) == 0:
        raise ValueError("field_for: catalog is empty; nothing to wrap.")

    if slice_ is None:
        selected = _with_asset_paths(catalog, asset=asset)
        if materialize:  # the lazy path needs no grid
            slice_ = _whole_catalog_slice(selected)
    else:
        # Only the rows the slice selects need to carry `asset`.
        selected = catalog.query(slice_)
        if len(selected) == 0:
            raise ValueError(f"field_for: no catalog row intersects {slice_!r}.")
        selected = _with_asset_paths(selected, asset=asset)
    paths = [str(p) for p in selected.gdf["filepath"]]
    _reject_unstaged_uris(paths, asset=asset)

    if not materialize:
        return [RasterField(source) for source in _lazy_sources(paths, band_indexes)]
    assert slice_ is not None

    from geocatalog._src.formats.raster import load_raster

    mosaic = load_raster(  # (bands, H, W) on slice_.grid
        selected,
        slice_,
        band_indexes=band_indexes,
        resampling=resampling,
        merge_method=merge_method,  # type: ignore[arg-type]
        nodata=nodata,
    )
    return RasterField(mosaic)

A catalog as a patcher domain

geocatalog.patch.CatalogDomain dataclass

A patcher Domain view of a GeoCatalog.

Use this when you want to run a SpatialPatcher (or any consumer that takes a Domain) across a multi-file archive instead of a single in-RAM raster. Each catalog row becomes one sub-domain; the patcher iterates them, the loader opens each in turn, the operator runs per file, and stitching reassembles the result.

The dataclass is frozen=True so it can be cached, hashed, and safely shipped across function boundaries — useful when feeding the same domain into multiple parallel pipelines.

Parameters:

Name Type Description Default
catalog GeoCatalog

The catalog being adapted. Any backend tag ("raster", "xarray", "vector") is accepted — the loader you pair this with downstream is what makes it concrete. Must be non-empty for slices to return anything useful.

required
resolution tuple[float, float]

Target (x_res, y_res) in CRS units, baked into every GeoSlice produced by slices. Drives the pixel shape a downstream loader will materialise; pick whatever your operator expects.

required
Example

Tiled per-row inference across a multi-file S2 archive::

import geocatalog as gc
import numpy as np

catalog = gc.build.build_raster_catalog(paths)
domain = gc.patch.CatalogDomain(catalog, resolution=(10.0, 10.0))
for slice_ in domain.slices():
    chip = gc.load.load_raster(catalog, slice_)  # (C, H, W) GeoArray
    predictions.append(model(np.asarray(chip)))
Source code in packages/geotoolz-catalog/src/geocatalog/_src/patch/domain.py
@dataclass(frozen=True)
class CatalogDomain:
    """A patcher ``Domain`` view of a `GeoCatalog`.

    Use this when you want to run a `SpatialPatcher` (or any consumer
    that takes a `Domain`) across a multi-file archive instead of a
    single in-RAM raster. Each catalog row becomes one sub-domain; the
    patcher iterates them, the loader opens each in turn, the operator
    runs per file, and stitching reassembles the result.

    The dataclass is ``frozen=True`` so it can be cached, hashed, and
    safely shipped across function boundaries — useful when feeding the
    same domain into multiple parallel pipelines.

    Args:
        catalog: The catalog being adapted. Any backend tag (``"raster"``,
            ``"xarray"``, ``"vector"``) is accepted — the loader you pair
            this with downstream is what makes it concrete. Must be
            non-empty for `slices` to return anything useful.
        resolution: Target ``(x_res, y_res)`` in CRS units, baked into
            every `GeoSlice` produced by `slices`. Drives the pixel
            shape a downstream loader will materialise; pick whatever
            your operator expects.

    Example:
        Tiled per-row inference across a multi-file S2 archive::

            import geocatalog as gc
            import numpy as np

            catalog = gc.build.build_raster_catalog(paths)
            domain = gc.patch.CatalogDomain(catalog, resolution=(10.0, 10.0))
            for slice_ in domain.slices():
                chip = gc.load.load_raster(catalog, slice_)  # (C, H, W) GeoArray
                predictions.append(model(np.asarray(chip)))
    """

    catalog: GeoCatalog
    resolution: tuple[float, float]

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        """Union bbox over the catalog — the outer envelope of every row.

        Returns:
            ``(xmin, ymin, xmax, ymax)`` in catalog-CRS units. Four NaNs
            if the catalog is empty.
        """
        return self.catalog.total_bounds

    @property
    def crs(self) -> Any:
        """The catalog's CRS — ``catalog.crs``; never materialises rows."""
        return self.catalog.crs

    def __len__(self) -> int:
        """Number of sub-domains (== number of catalog rows)."""
        return len(self.catalog)

    def slices(self) -> Sequence[GeoSlice]:
        """Materialise the catalog's per-row `GeoSlice` list.

        Eager (returns a list) rather than lazy because most callers
        want ``len(slices())`` for progress bars or to shard work
        upfront. Iterate the catalog's `iter_slices` directly if you
        want streaming.

        Returns:
            A list of `GeoSlice` instances, one per catalog row, each
            carrying this domain's ``resolution`` and the row's
            footprint + interval.
        """
        return list(self.catalog.iter_slices(resolution=self.resolution))

    def get_config(self) -> dict[str, Any]:
        """Return a JSON-serialisable summary — for logging and audits.

        Returns:
            ``{"catalog": <catalog.get_config()>, "resolution": (x, y)}``.
            Round-trippable through ``json.dumps`` provided the catalog's
            own ``get_config`` is.
        """
        return {
            "catalog": self.catalog.get_config(),
            "resolution": self.resolution,
        }

bounds property

Union bbox over the catalog — the outer envelope of every row.

Returns:

Type Description
float

(xmin, ymin, xmax, ymax) in catalog-CRS units. Four NaNs

float

if the catalog is empty.

crs property

The catalog's CRS — catalog.crs; never materialises rows.

__len__()

Number of sub-domains (== number of catalog rows).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/patch/domain.py
def __len__(self) -> int:
    """Number of sub-domains (== number of catalog rows)."""
    return len(self.catalog)

get_config()

Return a JSON-serialisable summary — for logging and audits.

Returns:

Type Description
``{"catalog"

, "resolution": (x, y)}``.

dict[str, Any]

Round-trippable through json.dumps provided the catalog's

dict[str, Any]

own get_config is.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/patch/domain.py
def get_config(self) -> dict[str, Any]:
    """Return a JSON-serialisable summary — for logging and audits.

    Returns:
        ``{"catalog": <catalog.get_config()>, "resolution": (x, y)}``.
        Round-trippable through ``json.dumps`` provided the catalog's
        own ``get_config`` is.
    """
    return {
        "catalog": self.catalog.get_config(),
        "resolution": self.resolution,
    }

slices()

Materialise the catalog's per-row GeoSlice list.

Eager (returns a list) rather than lazy because most callers want len(slices()) for progress bars or to shard work upfront. Iterate the catalog's iter_slices directly if you want streaming.

Returns:

Type Description
Sequence[GeoSlice]

A list of GeoSlice instances, one per catalog row, each

Sequence[GeoSlice]

carrying this domain's resolution and the row's

Sequence[GeoSlice]

footprint + interval.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/patch/domain.py
def slices(self) -> Sequence[GeoSlice]:
    """Materialise the catalog's per-row `GeoSlice` list.

    Eager (returns a list) rather than lazy because most callers
    want ``len(slices())`` for progress bars or to shard work
    upfront. Iterate the catalog's `iter_slices` directly if you
    want streaming.

    Returns:
        A list of `GeoSlice` instances, one per catalog row, each
        carrying this domain's ``resolution`` and the row's
        footprint + interval.
    """
    return list(self.catalog.iter_slices(resolution=self.resolution))