Skip to content

Fields — geopatcher.fields

Field adapters for every substrate other than a geoarray.RasterSource (RasterField, at the root), and the domain types samplers plan over. The extras-gated adapters resolve lazily, so importing the module never needs an optional dependency.

from geopatcher.fields import CogField, RioXarrayField, XarrayField

Raster readers

geopatcher.fields.AsyncRasterField dataclass

Async mirror of RasterField over a geoarray.AsyncRasterSource.

select is a coroutine (reader.aread_window); otherwise the surface is identical.

Parameters:

Name Type Description Default
reader AsyncRasterSource

Any geoarray.AsyncRasterSource (geocloud.cog.CogSource, geocloud.cog.AsyncCogReader, …).

required

Raises:

Type Description
TypeError

reader is a georeader object or not an AsyncRasterSource.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/raster.py
@dataclass(eq=False)
class AsyncRasterField:
    """Async mirror of `RasterField` over a `geoarray.AsyncRasterSource`.

    `select` is a coroutine (``reader.aread_window``); otherwise the
    surface is identical.

    Args:
        reader: Any `geoarray.AsyncRasterSource` (``geocloud.cog.CogSource``,
            ``geocloud.cog.AsyncCogReader``, …).

    Raises:
        TypeError: ``reader`` is a georeader object or not an
            `AsyncRasterSource`.
    """

    reader: AsyncRasterSource

    def __post_init__(self) -> None:
        _require_source(self.reader, "AsyncRasterField", AsyncRasterSource)

    @property
    def domain(self) -> AsyncRasterSource:
        return self.reader

    async def select(self, window: Any) -> GeoArray:
        return await self.reader.aread_window(as_pixel_window(window), boundless=True)

    async def aselect(self, window: Any) -> GeoArray:
        return await self.select(window)

    def with_data(self, array: Any) -> GeoArray:
        return _rewrap(self.reader, array, self.reader.grid)

geopatcher.fields.ReprojectingRasterField dataclass

Wrap a geoarray.RasterSource, presenting a reprojected destination grid.

The domain reports the destination CRS / transform / shape, so samplers place anchors on the reprojected grid; each select warps the corresponding source pixels into that chip.

Parameters:

Name Type Description Default
reader RasterSource

Any geoarray.RasterSource (a GeoArray, a lazy reader, …) in the source CRS. A georeader reader crosses with geoarray.interop.georeader.source_from_georeader.

required
dst_crs Any

Destination CRS the domain (and every chip) is expressed in — "EPSG:3857", a CRS object, or WKT.

required
resolution float | tuple[float, float] | None

Destination pixel size in dst_crs units. None (default) lets georeader pick a resolution that matches the source.

None
resampling str

Resampling method — "nearest", "bilinear", "cubic", "cubic_spline", or "lanczos".

'bilinear'

The domain shape keeps the source's leading (band / time) dims — (*reader.shape[:-2], height, width) — so chips and the merged output agree on rank.

Each select first crops the source to the chip's footprint (plus a small pixel margin for the resampling kernel, scaled up when the destination is coarser than the source) and warps only that crop, so per-chip cost scales with the chip, not the whole source.

Note

Chips are warped independently, so a stitched result can differ slightly from one full-image warp of the same source — GDAL's approximate transformer linearises per warp call, which shifts sample positions by a small fraction of a pixel (with bilinear resampling, differences stay below one ramp step on a unit-increment ramp). The source crop itself does not change the result: a chip is identical to warping the uncropped source onto the same chip grid. Warp the whole source once (geoops.geom's reprojection) when bit-exactness against a full warp matters.

Raises:

Type Description
TypeError

reader is a georeader object or not a RasterSource.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/reproject.py
@dataclass(eq=False)
class ReprojectingRasterField:
    """Wrap a `geoarray.RasterSource`, presenting a reprojected destination grid.

    The domain reports the *destination* CRS / transform / shape, so
    samplers place anchors on the reprojected grid; each `select` warps
    the corresponding source pixels into that chip.

    Args:
        reader: Any `geoarray.RasterSource` (a `GeoArray`, a lazy reader,
            …) in the source CRS. A georeader reader crosses with
            ``geoarray.interop.georeader.source_from_georeader``.
        dst_crs: Destination CRS the domain (and every chip) is expressed
            in — ``"EPSG:3857"``, a CRS object, or WKT.
        resolution: Destination pixel size in ``dst_crs`` units. ``None``
            (default) lets georeader pick a resolution that matches the
            source.
        resampling: Resampling method — ``"nearest"``, ``"bilinear"``,
            ``"cubic"``, ``"cubic_spline"``, or ``"lanczos"``.

    The domain shape keeps the source's leading (band / time) dims —
    ``(*reader.shape[:-2], height, width)`` — so chips and the merged
    output agree on rank.

    Each `select` first crops the source to the chip's footprint (plus a
    small pixel margin for the resampling kernel, scaled up when the
    destination is coarser than the source) and warps only that crop, so
    per-chip cost scales with the chip, not the whole source.

    Note:
        Chips are warped independently, so a stitched result can differ
        slightly from one full-image warp of the same source — GDAL's
        approximate transformer linearises per warp call, which shifts
        sample positions by a small fraction of a pixel (with bilinear
        resampling, differences stay below one ramp step on a
        unit-increment ramp). The source crop itself does not change the
        result: a chip is identical to warping the uncropped source onto
        the same chip grid. Warp the whole source once (``geoops.geom``'s
        reprojection) when bit-exactness against a full warp matters.

    Raises:
        TypeError: ``reader`` is a georeader object or not a `RasterSource`.
    """

    reader: RasterSource
    dst_crs: Any
    resolution: float | tuple[float, float] | None = None
    resampling: str = "bilinear"

    def __post_init__(self) -> None:
        from georeader.read import calculate_transform_window

        _require_source(self.reader, "ReprojectingRasterField", RasterSource)
        window_data, dst_transform = calculate_transform_window(
            self._engine, self.dst_crs, self.resolution
        )
        # `frozen`-friendly private state on an `eq=False` dataclass.
        object.__setattr__(self, "_transform", dst_transform)
        object.__setattr__(
            self,
            "_shape",
            (
                *(int(d) for d in self.reader.shape[:-2]),
                int(window_data.height),
                int(window_data.width),
            ),
        )
        object.__setattr__(self, "_resampling", _resampling_enum(self.resampling))
        object.__setattr__(
            self,
            "_grid",
            Grid.from_affine(dst_transform, self.dst_crs, self._shape[-2:]),
        )

    @property
    def _engine(self) -> Any:
        """The source as a georeader ``GeoData``, for georeader's ``read``."""
        return source_to_georeader(self.reader)

    def __getstate__(self) -> dict[str, Any]:
        return _pack_reader_state(self.__dict__)

    def __setstate__(self, state: dict[str, Any]) -> None:
        self.__dict__.update(_unpack_reader_state(state))

    @property
    def domain(self) -> _ReprojectedDomain:
        return _ReprojectedDomain(grid=self._grid, shape=self._shape)

    def select(self, window: Any) -> GeoArray:
        """Warp the source into ``window`` of the destination grid.

        Returns:
            ``(..., window.height, window.width)`` on the window's grid in
            ``dst_crs``.
        """
        from georeader.read import read_reproject
        from rasterio.windows import Window, transform as window_transform

        chip_transform = window_transform(window, self._transform)
        out = Window(
            col_off=0, row_off=0, width=int(window.width), height=int(window.height)
        )
        warped = read_reproject(
            self._crop_source(out, chip_transform),
            dst_crs=self.dst_crs,
            dst_transform=chip_transform,
            window_out=out,
            resampling=self._resampling,
        )
        return from_georeader(warped)

    def _crop_source(self, out: Any, chip_transform: Any) -> Any:
        """Source pixels covering the chip footprint, plus a kernel margin.

        ``read_reproject`` only crops lazy readers (and never an in-memory
        carrier), so without this each chip would warp the whole source.
        The chip polygon is densified before being mapped into the source
        CRS so curved edges of the reprojected footprint are
        covered; the margin is `_CROP_MARGIN` source pixels, scaled by
        the downsampling factor (GDAL widens the kernel when the
        destination is coarser). Returns the reader unchanged when the
        chip does not overlap the source — ``read_reproject`` then
        short-circuits to a nodata chip without reading anything — or
        when the footprint cannot be mapped into the source CRS.
        """
        from georeader import window_utils
        from georeader.read import read_from_window, window_from_polygon

        footprint = window_utils.window_polygon(out, chip_transform)
        step = max(footprint.length / 64.0, 1e-12)
        footprint = footprint.segmentize(step)
        engine = self._engine
        src_window = window_from_polygon(engine, footprint, crs_polygon=self.dst_crs)
        extent = (src_window.col_off, src_window.row_off)
        extent += (src_window.width, src_window.height)
        if not all(math.isfinite(float(v)) for v in extent):
            # Footprint not representable in the source CRS — let
            # `read_reproject` handle the full source.
            return engine
        scale = max(
            float(src_window.width) / max(float(out.width), 1.0),
            float(src_window.height) / max(float(out.height), 1.0),
            1.0,
        )
        pad = math.ceil(_CROP_MARGIN * scale)
        src_window = window_utils.round_outer_window(
            window_utils.pad_window(src_window, (pad, pad))
        )
        cropped = read_from_window(
            engine, src_window, trigger_load=True, boundless=False
        )
        return engine if cropped is None else cropped

    def cache_id(self) -> str:
        """`PatchCache` identity: the source plus the warp parameters.

        Folds in the source reader's identity (``None`` for an in-memory
        source — `PatchCache` then requires an explicit ``field_id``),
        ``dst_crs``, ``resolution`` and ``resampling``, so two
        reprojections of one source never share cache entries.

        Examples:
            >>> reader = source_from_georeader(RasterioReader("a.tif"))
            >>> ReprojectingRasterField(reader, "EPSG:3857").cache_id()
            '{"dst_crs": "EPSG:3857", "resampling": "bilinear", ...}'
            >>> ReprojectingRasterField(scene, "EPSG:3857").cache_id()
            '{"dst_crs": "EPSG:3857", ..., "source": null}'
        """
        from geopatcher._src.cache import _crs_text, _source_id

        resolution = self.resolution
        if isinstance(resolution, (tuple, list)):
            resolution = [float(r) for r in resolution]
        elif resolution is not None:
            resolution = float(resolution)
        return json.dumps(
            {
                "source": _source_id(self.reader),
                "dst_crs": _crs_text(self.dst_crs),
                "resolution": resolution,
                "resampling": self.resampling,
            },
            sort_keys=True,
        )

    def with_data(self, array: Any) -> GeoArray:
        """``array`` (``(..., H, W)`` on the destination grid) as a `GeoArray`."""
        return _rewrap(self.reader, array, self._grid)

cache_id()

PatchCache identity: the source plus the warp parameters.

Folds in the source reader's identity (None for an in-memory source — PatchCache then requires an explicit field_id), dst_crs, resolution and resampling, so two reprojections of one source never share cache entries.

Examples:

>>> reader = source_from_georeader(RasterioReader("a.tif"))
>>> ReprojectingRasterField(reader, "EPSG:3857").cache_id()
'{"dst_crs": "EPSG:3857", "resampling": "bilinear", ...}'
>>> ReprojectingRasterField(scene, "EPSG:3857").cache_id()
'{"dst_crs": "EPSG:3857", ..., "source": null}'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/reproject.py
def cache_id(self) -> str:
    """`PatchCache` identity: the source plus the warp parameters.

    Folds in the source reader's identity (``None`` for an in-memory
    source — `PatchCache` then requires an explicit ``field_id``),
    ``dst_crs``, ``resolution`` and ``resampling``, so two
    reprojections of one source never share cache entries.

    Examples:
        >>> reader = source_from_georeader(RasterioReader("a.tif"))
        >>> ReprojectingRasterField(reader, "EPSG:3857").cache_id()
        '{"dst_crs": "EPSG:3857", "resampling": "bilinear", ...}'
        >>> ReprojectingRasterField(scene, "EPSG:3857").cache_id()
        '{"dst_crs": "EPSG:3857", ..., "source": null}'
    """
    from geopatcher._src.cache import _crs_text, _source_id

    resolution = self.resolution
    if isinstance(resolution, (tuple, list)):
        resolution = [float(r) for r in resolution]
    elif resolution is not None:
        resolution = float(resolution)
    return json.dumps(
        {
            "source": _source_id(self.reader),
            "dst_crs": _crs_text(self.dst_crs),
            "resolution": resolution,
            "resampling": self.resampling,
        },
        sort_keys=True,
    )

select(window)

Warp the source into window of the destination grid.

Returns:

Type Description
GeoArray

(..., window.height, window.width) on the window's grid in

GeoArray

dst_crs.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/reproject.py
def select(self, window: Any) -> GeoArray:
    """Warp the source into ``window`` of the destination grid.

    Returns:
        ``(..., window.height, window.width)`` on the window's grid in
        ``dst_crs``.
    """
    from georeader.read import read_reproject
    from rasterio.windows import Window, transform as window_transform

    chip_transform = window_transform(window, self._transform)
    out = Window(
        col_off=0, row_off=0, width=int(window.width), height=int(window.height)
    )
    warped = read_reproject(
        self._crop_source(out, chip_transform),
        dst_crs=self.dst_crs,
        dst_transform=chip_transform,
        window_out=out,
        resampling=self._resampling,
    )
    return from_georeader(warped)

with_data(array)

array ((..., H, W) on the destination grid) as a GeoArray.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/reproject.py
def with_data(self, array: Any) -> GeoArray:
    """``array`` (``(..., H, W)`` on the destination grid) as a `GeoArray`."""
    return _rewrap(self.reader, array, self._grid)

Cloud-Optimized GeoTIFFs ([cog])

CogField is geotoolz-cloud's CogSource as a Field: tiles a batch of windows touches are fetched once, in concurrent groups, and parallel_map / AsyncSpatialPatcher use the batched and async paths automatically.

geopatcher.fields.CogField

Bases: CogSource

A tiled COG Field with batched range-fetch reads.

Open with :meth:open (await :meth:aopen inside an event loop); every argument is geocloud.cog.CogSource.open's. Patches are geoarray.GeoArray chips (bands, h, w) with the window's transform, the CRS and the COG's nodata as fill_value. The field's domain is geocloud.cog.CogDomain (a RasterDomain: grid and shape). The field pickles by URL, so it ships to process-pool workers.

Examples:

Patch a remote scene; parallel_map reads each chunk of patches with one batched fetch::

field = CogField.open("s3://bucket/scene.tif")
patches = list(patcher.split(field))
Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
class CogField(CogSource):
    """A tiled COG `Field` with batched range-fetch reads.

    Open with :meth:`open` (``await`` :meth:`aopen` inside an event loop);
    every argument is `geocloud.cog.CogSource.open`'s. Patches are
    `geoarray.GeoArray` chips ``(bands, h, w)`` with the window's transform,
    the CRS and the COG's nodata as ``fill_value``. The field's domain is
    `geocloud.cog.CogDomain` (a `RasterDomain`: ``grid`` and ``shape``). The
    field pickles by URL, so it ships to process-pool workers.

    Examples:
        Patch a remote scene; `parallel_map` reads each chunk of patches
        with one batched fetch::

            field = CogField.open("s3://bucket/scene.tif")
            patches = list(patcher.split(field))
    """

    def select(self, window: Window | PixelWindow) -> GeoArray:
        """Read one window (`read_window`)."""
        return self.read_window(window)

    async def aselect(self, window: Window | PixelWindow) -> GeoArray:
        """Async twin of :meth:`select` (the `AsyncField` spelling)."""
        return await self.aread_window(window)

    def select_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
        """Read every window, fetching each overlapping tile once (`read_windows`)."""
        return self.read_windows(windows)

    async def aselect_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
        """Async twin of :meth:`select_many`."""
        return await self.aread_windows(windows)

    def with_data(self, array: np.ndarray) -> GeoArray:
        """Wrap an operator output on the full grid as a `geoarray.GeoArray`.

        Carries the COG's grid (transform, CRS), attrs and nodata, by the
        rule every raster ``with_data`` follows (`RasterField.with_data`):
        the COG's nodata while the output carries its values and its dtype
        holds it, NaN for a new float quantity, else no fill.

        Raises:
            TypeError: ``array`` is a georeader ``GeoTensor``.
        """
        from geopatcher._src.fields.raster import _rewrap

        return _rewrap(self, array, self.grid)

    def cache_id(self) -> str:
        """`PatchCache` identity: the object read, its version and the IFD.

        `CogSource.identity` (the URL — or the explicit store's
        configuration plus ``path`` — and the IFD) plus
        `CogSource.object_version` (one ``HEAD`` per `split`: the ETag,
        else size + last-modified), so an object overwritten in place
        invalidates its cache entries.

        Raises:
            UnstableIdentityError: The explicit ``store`` has no printable
                configuration (``MemoryStore``); ``partial`` carries the
                rest of the identity (``path``, ``ifd_index``).
        """
        from geopatcher._src.cache import UnstableIdentityError

        identity: dict[str, Any] = {
            **self.identity(),
            "version": self.object_version(),
        }
        if self.store is not None and identity["store"] is None:
            raise UnstableIdentityError(
                f"its {type(self.store).__qualname__} has no configuration that "
                f"names its contents.",
                partial=json.dumps(identity, sort_keys=True),
            )
        return json.dumps(identity, sort_keys=True)

aselect(window) async

Async twin of :meth:select (the AsyncField spelling).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
async def aselect(self, window: Window | PixelWindow) -> GeoArray:
    """Async twin of :meth:`select` (the `AsyncField` spelling)."""
    return await self.aread_window(window)

aselect_many(windows) async

Async twin of :meth:select_many.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
async def aselect_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
    """Async twin of :meth:`select_many`."""
    return await self.aread_windows(windows)

cache_id()

PatchCache identity: the object read, its version and the IFD.

CogSource.identity (the URL — or the explicit store's configuration plus path — and the IFD) plus CogSource.object_version (one HEAD per split: the ETag, else size + last-modified), so an object overwritten in place invalidates its cache entries.

Raises:

Type Description
UnstableIdentityError

The explicit store has no printable configuration (MemoryStore); partial carries the rest of the identity (path, ifd_index).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
def cache_id(self) -> str:
    """`PatchCache` identity: the object read, its version and the IFD.

    `CogSource.identity` (the URL — or the explicit store's
    configuration plus ``path`` — and the IFD) plus
    `CogSource.object_version` (one ``HEAD`` per `split`: the ETag,
    else size + last-modified), so an object overwritten in place
    invalidates its cache entries.

    Raises:
        UnstableIdentityError: The explicit ``store`` has no printable
            configuration (``MemoryStore``); ``partial`` carries the
            rest of the identity (``path``, ``ifd_index``).
    """
    from geopatcher._src.cache import UnstableIdentityError

    identity: dict[str, Any] = {
        **self.identity(),
        "version": self.object_version(),
    }
    if self.store is not None and identity["store"] is None:
        raise UnstableIdentityError(
            f"its {type(self.store).__qualname__} has no configuration that "
            f"names its contents.",
            partial=json.dumps(identity, sort_keys=True),
        )
    return json.dumps(identity, sort_keys=True)

select(window)

Read one window (read_window).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
def select(self, window: Window | PixelWindow) -> GeoArray:
    """Read one window (`read_window`)."""
    return self.read_window(window)

select_many(windows)

Read every window, fetching each overlapping tile once (read_windows).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
def select_many(self, windows: list[Window | PixelWindow]) -> list[GeoArray]:
    """Read every window, fetching each overlapping tile once (`read_windows`)."""
    return self.read_windows(windows)

with_data(array)

Wrap an operator output on the full grid as a geoarray.GeoArray.

Carries the COG's grid (transform, CRS), attrs and nodata, by the rule every raster with_data follows (RasterField.with_data): the COG's nodata while the output carries its values and its dtype holds it, NaN for a new float quantity, else no fill.

Raises:

Type Description
TypeError

array is a georeader GeoTensor.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/cog.py
def with_data(self, array: np.ndarray) -> GeoArray:
    """Wrap an operator output on the full grid as a `geoarray.GeoArray`.

    Carries the COG's grid (transform, CRS), attrs and nodata, by the
    rule every raster ``with_data`` follows (`RasterField.with_data`):
    the COG's nodata while the output carries its values and its dtype
    holds it, NaN for a new float quantity, else no fill.

    Raises:
        TypeError: ``array`` is a georeader ``GeoTensor``.
    """
    from geopatcher._src.fields.raster import _rewrap

    return _rewrap(self, array, self.grid)

Gridded N-D data ([grid], [xarray-raster], [dask])

geopatcher.fields.XarrayField dataclass

Wrap an xarray.DataArray as a Field[GridDomain].

Parameters:

Name Type Description Default
da Any

The underlying xarray.DataArray. Any CRS must be exposed via the rioxarray accessor (da.rio.crs); None is allowed for non-georeferenced cubes.

required

domain is built on first access and cached; treat da as immutable once wrapped.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xarray.py
@dataclass(eq=False)
class XarrayField:
    """Wrap an `xarray.DataArray` as a `Field[GridDomain]`.

    Args:
        da: The underlying `xarray.DataArray`. Any CRS must be exposed
            via the rioxarray accessor (``da.rio.crs``); ``None`` is
            allowed for non-georeferenced cubes.

    ``domain`` is built on first access and cached; treat ``da`` as
    immutable once wrapped.
    """

    da: Any

    def __post_init__(self) -> None:
        if xr is None:
            raise missing_extra("XarrayField", "grid", "xarray>=2024.1")

    @cached_property
    def domain(self) -> GridDomain:
        coords = {d: np.asarray(self.da[d].values) for d in self.da.dims}
        crs = getattr(self.da, "rio", None)
        crs = crs.crs if crs is not None else None
        return GridDomain(coords=coords, crs=crs)

    def select(self, indexer: dict[str, slice]) -> Any:
        """Read a sliced `xarray.DataArray` patch.

        Returns the bare `DataArray` (not another `XarrayField`) so the
        result is `np.asarray`-able and feeds straight into the spatial
        aggregations. Mirrors `RasterField.select → GeoArray`: select
        returns the natural data payload, not another field wrapper. Use
        `XarrayField(da_sliced)` if you need to keep treating the slice
        as a sub-Field.
        """
        return self.da.isel(**indexer)

    def placeholder(self, indexer: dict[str, slice], data: np.ndarray) -> Any:
        """``data`` as the `DataArray` `select` would return, without reading.

        Used for the ``on_error="mask"`` placeholder. The chip's coords
        come from the (lazy) slice; when its shape differs from ``data``
        (a padded window past the edge) ``data`` is returned bare.
        """
        import xarray as xr

        template = self.da.isel(**indexer)
        if tuple(template.shape) != data.shape:
            return data
        return xr.DataArray(
            data, dims=template.dims, coords=template.coords, name=template.name
        )

    def with_data(self, array: Any) -> XarrayField:
        reject_georeader(array, "XarrayField.with_data")
        new = self.da.copy(data=np.asarray(array))
        return XarrayField(new)

    def time_coord(self, name: str = "time") -> np.ndarray:
        """Return the 1-D time coordinate as a NumPy array.

        Helper for the coordinate-aware temporal patcher path. Resolves the
        coordinate by name (defaults to ``"time"``) and materialises its
        values so callers don't repeat ``ds[name].values`` boilerplate.

        Args:
            name: Name of the time-like coordinate. Defaults to ``"time"``.

        Returns:
            ``np.ndarray`` of dtype ``datetime64[ns]`` (or whatever NumPy
            unit xarray exposes for that coord).

        Raises:
            KeyError: If ``name`` is absent from the DataArray's coords.
            TypeError: If the coordinate is `cftime`-typed — convert via
                ``xarray.coding.times.convert_calendar(...)`` or
                ``ds.indexes['time'].to_datetimeindex()`` first.
        """
        if name not in self.da.coords:
            raise KeyError(
                f"XarrayField has no coord named {name!r}; "
                f"available: {list(self.da.coords)}"
            )
        values = np.asarray(self.da.coords[name].values)
        if values.dtype == np.dtype("O"):
            raise TypeError(
                f"Coord {name!r} has object dtype (likely cftime). "
                "Convert with xarray.coding.times.convert_calendar(...) "
                "or DataArray.indexes['time'].to_datetimeindex() before "
                "passing to TemporalPatcher."
            )
        return values

    def coords_per_patch(self, patches: Iterable[Any]) -> list[Any]:
        """xrpatcher.get_coords() equivalent — one coord Dataset per patch.

        For each patch, run ``self.da.isel(**patch.indices).coords.to_dataset()``
        so the caller gets the coord values aligned with the patch slice
        without re-reading data.

        Args:
            patches: Iterable of `Patch` (or anything with an `indices`
                attribute consumable by ``DataArray.isel``).

        Returns:
            ``list[xr.Dataset]`` — same length as ``patches``, each Dataset
            containing only the coord variables (no data variables).

        Raises:
            TypeError: If a patch's ``indices`` is not a ``dict`` and can't
                be coerced to ``DataArray.isel`` kwargs. Raster-style
                ``rasterio.windows.Window`` indices are converted using
                the underlying DataArray's last two dims as ``(row, col)``.
        """
        out: list[Any] = []
        for p in patches:
            indexer = _patch_indices_to_isel(p, self.da)
            out.append(self.da.isel(**indexer).coords.to_dataset())
        return out

coords_per_patch(patches)

xrpatcher.get_coords() equivalent — one coord Dataset per patch.

For each patch, run self.da.isel(**patch.indices).coords.to_dataset() so the caller gets the coord values aligned with the patch slice without re-reading data.

Parameters:

Name Type Description Default
patches Iterable[Any]

Iterable of Patch (or anything with an indices attribute consumable by DataArray.isel).

required

Returns:

Type Description
list[Any]

list[xr.Dataset] — same length as patches, each Dataset

list[Any]

containing only the coord variables (no data variables).

Raises:

Type Description
TypeError

If a patch's indices is not a dict and can't be coerced to DataArray.isel kwargs. Raster-style rasterio.windows.Window indices are converted using the underlying DataArray's last two dims as (row, col).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xarray.py
def coords_per_patch(self, patches: Iterable[Any]) -> list[Any]:
    """xrpatcher.get_coords() equivalent — one coord Dataset per patch.

    For each patch, run ``self.da.isel(**patch.indices).coords.to_dataset()``
    so the caller gets the coord values aligned with the patch slice
    without re-reading data.

    Args:
        patches: Iterable of `Patch` (or anything with an `indices`
            attribute consumable by ``DataArray.isel``).

    Returns:
        ``list[xr.Dataset]`` — same length as ``patches``, each Dataset
        containing only the coord variables (no data variables).

    Raises:
        TypeError: If a patch's ``indices`` is not a ``dict`` and can't
            be coerced to ``DataArray.isel`` kwargs. Raster-style
            ``rasterio.windows.Window`` indices are converted using
            the underlying DataArray's last two dims as ``(row, col)``.
    """
    out: list[Any] = []
    for p in patches:
        indexer = _patch_indices_to_isel(p, self.da)
        out.append(self.da.isel(**indexer).coords.to_dataset())
    return out

placeholder(indexer, data)

data as the DataArray select would return, without reading.

Used for the on_error="mask" placeholder. The chip's coords come from the (lazy) slice; when its shape differs from data (a padded window past the edge) data is returned bare.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xarray.py
def placeholder(self, indexer: dict[str, slice], data: np.ndarray) -> Any:
    """``data`` as the `DataArray` `select` would return, without reading.

    Used for the ``on_error="mask"`` placeholder. The chip's coords
    come from the (lazy) slice; when its shape differs from ``data``
    (a padded window past the edge) ``data`` is returned bare.
    """
    import xarray as xr

    template = self.da.isel(**indexer)
    if tuple(template.shape) != data.shape:
        return data
    return xr.DataArray(
        data, dims=template.dims, coords=template.coords, name=template.name
    )

select(indexer)

Read a sliced xarray.DataArray patch.

Returns the bare DataArray (not another XarrayField) so the result is np.asarray-able and feeds straight into the spatial aggregations. Mirrors RasterField.select → GeoArray: select returns the natural data payload, not another field wrapper. Use XarrayField(da_sliced) if you need to keep treating the slice as a sub-Field.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xarray.py
def select(self, indexer: dict[str, slice]) -> Any:
    """Read a sliced `xarray.DataArray` patch.

    Returns the bare `DataArray` (not another `XarrayField`) so the
    result is `np.asarray`-able and feeds straight into the spatial
    aggregations. Mirrors `RasterField.select → GeoArray`: select
    returns the natural data payload, not another field wrapper. Use
    `XarrayField(da_sliced)` if you need to keep treating the slice
    as a sub-Field.
    """
    return self.da.isel(**indexer)

time_coord(name='time')

Return the 1-D time coordinate as a NumPy array.

Helper for the coordinate-aware temporal patcher path. Resolves the coordinate by name (defaults to "time") and materialises its values so callers don't repeat ds[name].values boilerplate.

Parameters:

Name Type Description Default
name str

Name of the time-like coordinate. Defaults to "time".

'time'

Returns:

Type Description
ndarray

np.ndarray of dtype datetime64[ns] (or whatever NumPy

ndarray

unit xarray exposes for that coord).

Raises:

Type Description
KeyError

If name is absent from the DataArray's coords.

TypeError

If the coordinate is cftime-typed — convert via xarray.coding.times.convert_calendar(...) or ds.indexes['time'].to_datetimeindex() first.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xarray.py
def time_coord(self, name: str = "time") -> np.ndarray:
    """Return the 1-D time coordinate as a NumPy array.

    Helper for the coordinate-aware temporal patcher path. Resolves the
    coordinate by name (defaults to ``"time"``) and materialises its
    values so callers don't repeat ``ds[name].values`` boilerplate.

    Args:
        name: Name of the time-like coordinate. Defaults to ``"time"``.

    Returns:
        ``np.ndarray`` of dtype ``datetime64[ns]`` (or whatever NumPy
        unit xarray exposes for that coord).

    Raises:
        KeyError: If ``name`` is absent from the DataArray's coords.
        TypeError: If the coordinate is `cftime`-typed — convert via
            ``xarray.coding.times.convert_calendar(...)`` or
            ``ds.indexes['time'].to_datetimeindex()`` first.
    """
    if name not in self.da.coords:
        raise KeyError(
            f"XarrayField has no coord named {name!r}; "
            f"available: {list(self.da.coords)}"
        )
    values = np.asarray(self.da.coords[name].values)
    if values.dtype == np.dtype("O"):
        raise TypeError(
            f"Coord {name!r} has object dtype (likely cftime). "
            "Convert with xarray.coding.times.convert_calendar(...) "
            "or DataArray.indexes['time'].to_datetimeindex() before "
            "passing to TemporalPatcher."
        )
    return values

geopatcher.fields.RioXarrayField dataclass

Wrap a rioxarray-flavoured xarray.DataArray as a raster Field.

The domain view exposes the pixel grid (a geoarray.Grid from the rasterio affine and the CRS) and the array shape — the RasterDomain protocol — so it takes the same raster patching path as RasterField.

Parameters:

Name Type Description Default
da Any

An xarray.DataArray with a working da.rio accessor.

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/rio_xarray.py
@dataclass(eq=False)
class RioXarrayField:
    """Wrap a rioxarray-flavoured `xarray.DataArray` as a raster `Field`.

    The `domain` view exposes the pixel grid (a `geoarray.Grid` from the
    rasterio affine and the CRS) and the array shape — the `RasterDomain`
    protocol — so it takes the same raster patching path as `RasterField`.

    Args:
        da: An `xarray.DataArray` with a working ``da.rio`` accessor.
    """

    da: Any

    def __post_init__(self) -> None:
        if rioxarray is None:  # pragma: no cover
            raise missing_extra("RioXarrayField", "xarray-raster", "rioxarray>=0.15")

    @property
    def domain(self) -> Any:
        return _RioDomain(self.da)

    def select(self, window: Any) -> Any:
        """Return the window as a georeferenced `xarray.DataArray`.

        The chip carries an explicit window transform
        (``rasterio.windows.transform(window, domain.transform)``) and,
        when the source has spatial coordinates, coordinates rebuilt from
        it — so ``chip.rio.transform()`` / ``chip.rio.bounds()`` are exact
        whether the source is coordinate-bearing or ``write_transform``-only.

        Windows that extend past the raster are read *boundless*, like
        `RasterField`: the in-range part is read and the rest padded to
        the requested size with ``rio.nodata`` (``0`` when unset), so the
        chip shape always equals the window shape. The returned chip is
        materialised (``.compute()``), also for dask-backed sources.
        """
        from rasterio.windows import Window, transform as window_transform

        y_dim, x_dim = self.da.rio.y_dim, self.da.rio.x_dim
        height, width = int(self.da.sizes[y_dim]), int(self.da.sizes[x_dim])
        r0, c0 = int(window.row_off), int(window.col_off)
        h, w = int(window.height), int(window.width)
        if h < 0 or w < 0:
            raise ValueError(f"window {window!r} has a negative size")
        cr0, cr1 = max(r0, 0), min(r0 + h, height)
        cc0, cc1 = max(c0, 0), min(c0 + w, width)
        if cr1 <= cr0 or cc1 <= cc0:
            # No overlap with the raster: an empty read anchored at the
            # window origin, padded below/right to the full window.
            cr0 = cr1 = r0
            cc0 = cc1 = c0
            sub = self.da.isel({y_dim: slice(0, 0), x_dim: slice(0, 0)})
        else:
            sub = self.da.isel({y_dim: slice(cr0, cr1), x_dim: slice(cc0, cc1)})
        clipped = Window(col_off=cc0, row_off=cr0, width=cc1 - cc0, height=cr1 - cr0)
        transform = window_transform(clipped, self.da.rio.transform())
        sub = _georeference(sub, transform)
        pads = (cr0 - r0, r0 + h - cr1, cc0 - c0, c0 + w - cc1)
        if any(pads):
            sub = pad_dataarray(
                sub, pads, mode="constant", fill=_nodata(self.da), transform=transform
            )
        # Materialise lazily-backed sources (``open_rasterio(chunks=...)``)
        # so the payload is a concrete array, like every other adapter's.
        return sub.compute()

    def placeholder(self, window: Any, data: np.ndarray) -> Any:
        """``data`` as a chip of ``window``: a `DataArray` on its grid, no read.

        Used for the ``on_error="mask"`` placeholder, so a failed read
        has the carrier and georeferencing of a successful `select`.
        """
        import xarray as xr
        from rasterio.windows import transform as window_transform

        y_dim, x_dim = self.da.rio.y_dim, self.da.rio.x_dim
        if data.ndim != self.da.ndim:
            return data
        coords = {
            d: self.da[d]
            for d in self.da.dims
            if d not in (y_dim, x_dim) and d in self.da.coords
        }
        chip = xr.DataArray(data, dims=self.da.dims, coords=coords)
        for dim in (y_dim, x_dim):
            if dim in self.da.coords:  # rebuilt from the transform below
                chip = chip.assign_coords({dim: np.zeros(chip.sizes[dim])})
        chip = chip.rio.set_spatial_dims(x_dim=x_dim, y_dim=y_dim)
        if self.da.rio.crs is not None:
            chip = chip.rio.write_crs(self.da.rio.crs)
        return _georeference(chip, window_transform(window, self.da.rio.transform()))

    def with_data(self, array: Any) -> RioXarrayField:
        reject_georeader(array, "RioXarrayField.with_data")
        return RioXarrayField(self.da.copy(data=np.asarray(array)))

placeholder(window, data)

data as a chip of window: a DataArray on its grid, no read.

Used for the on_error="mask" placeholder, so a failed read has the carrier and georeferencing of a successful select.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/rio_xarray.py
def placeholder(self, window: Any, data: np.ndarray) -> Any:
    """``data`` as a chip of ``window``: a `DataArray` on its grid, no read.

    Used for the ``on_error="mask"`` placeholder, so a failed read
    has the carrier and georeferencing of a successful `select`.
    """
    import xarray as xr
    from rasterio.windows import transform as window_transform

    y_dim, x_dim = self.da.rio.y_dim, self.da.rio.x_dim
    if data.ndim != self.da.ndim:
        return data
    coords = {
        d: self.da[d]
        for d in self.da.dims
        if d not in (y_dim, x_dim) and d in self.da.coords
    }
    chip = xr.DataArray(data, dims=self.da.dims, coords=coords)
    for dim in (y_dim, x_dim):
        if dim in self.da.coords:  # rebuilt from the transform below
            chip = chip.assign_coords({dim: np.zeros(chip.sizes[dim])})
    chip = chip.rio.set_spatial_dims(x_dim=x_dim, y_dim=y_dim)
    if self.da.rio.crs is not None:
        chip = chip.rio.write_crs(self.da.rio.crs)
    return _georeference(chip, window_transform(window, self.da.rio.transform()))

select(window)

Return the window as a georeferenced xarray.DataArray.

The chip carries an explicit window transform (rasterio.windows.transform(window, domain.transform)) and, when the source has spatial coordinates, coordinates rebuilt from it — so chip.rio.transform() / chip.rio.bounds() are exact whether the source is coordinate-bearing or write_transform-only.

Windows that extend past the raster are read boundless, like RasterField: the in-range part is read and the rest padded to the requested size with rio.nodata (0 when unset), so the chip shape always equals the window shape. The returned chip is materialised (.compute()), also for dask-backed sources.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/rio_xarray.py
def select(self, window: Any) -> Any:
    """Return the window as a georeferenced `xarray.DataArray`.

    The chip carries an explicit window transform
    (``rasterio.windows.transform(window, domain.transform)``) and,
    when the source has spatial coordinates, coordinates rebuilt from
    it — so ``chip.rio.transform()`` / ``chip.rio.bounds()`` are exact
    whether the source is coordinate-bearing or ``write_transform``-only.

    Windows that extend past the raster are read *boundless*, like
    `RasterField`: the in-range part is read and the rest padded to
    the requested size with ``rio.nodata`` (``0`` when unset), so the
    chip shape always equals the window shape. The returned chip is
    materialised (``.compute()``), also for dask-backed sources.
    """
    from rasterio.windows import Window, transform as window_transform

    y_dim, x_dim = self.da.rio.y_dim, self.da.rio.x_dim
    height, width = int(self.da.sizes[y_dim]), int(self.da.sizes[x_dim])
    r0, c0 = int(window.row_off), int(window.col_off)
    h, w = int(window.height), int(window.width)
    if h < 0 or w < 0:
        raise ValueError(f"window {window!r} has a negative size")
    cr0, cr1 = max(r0, 0), min(r0 + h, height)
    cc0, cc1 = max(c0, 0), min(c0 + w, width)
    if cr1 <= cr0 or cc1 <= cc0:
        # No overlap with the raster: an empty read anchored at the
        # window origin, padded below/right to the full window.
        cr0 = cr1 = r0
        cc0 = cc1 = c0
        sub = self.da.isel({y_dim: slice(0, 0), x_dim: slice(0, 0)})
    else:
        sub = self.da.isel({y_dim: slice(cr0, cr1), x_dim: slice(cc0, cc1)})
    clipped = Window(col_off=cc0, row_off=cr0, width=cc1 - cc0, height=cr1 - cr0)
    transform = window_transform(clipped, self.da.rio.transform())
    sub = _georeference(sub, transform)
    pads = (cr0 - r0, r0 + h - cr1, cc0 - c0, c0 + w - cc1)
    if any(pads):
        sub = pad_dataarray(
            sub, pads, mode="constant", fill=_nodata(self.da), transform=transform
        )
    # Materialise lazily-backed sources (``open_rasterio(chunks=...)``)
    # so the payload is a concrete array, like every other adapter's.
    return sub.compute()

geopatcher.fields.DaskField dataclass

Wrap a dask-backed xarray.DataArray as a lazy grid Field.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/dask.py
@dataclass(eq=False)
class DaskField:
    """Wrap a dask-backed `xarray.DataArray` as a lazy grid `Field`."""

    array: Any

    def __post_init__(self) -> None:
        if da is None or xr is None:
            raise missing_extra("DaskField", "dask", "dask[bag]>=2024.8.3")
        if not isinstance(self.array.data, da.Array):
            self.array = self.array.chunk()

    @classmethod
    def from_zarr(
        cls, store: Any, *, var: str | None = None, **kwargs: Any
    ) -> DaskField:
        """Open one variable of a zarr store with xarray as a `DaskField`.

        ``xr.open_zarr`` returns a `Dataset`; the field wraps one of its
        data variables.

        Args:
            store: Anything ``xarray.open_zarr`` accepts (path, URL, store).
            var: Data variable to wrap. May be omitted when the store holds
                exactly one data variable.
            **kwargs: Forwarded to ``xarray.open_zarr``.

        Raises:
            KeyError: ``var`` is not a data variable of the store.
            ValueError: ``var`` is omitted and the store holds zero or
                several data variables.
        """
        if xr is None:
            raise missing_extra("DaskField", "dask", "dask[bag]>=2024.8.3")
        ds = xr.open_zarr(store, **kwargs)
        names = list(ds.data_vars)
        if var is None:
            if len(names) != 1:
                raise ValueError(
                    f"DaskField.from_zarr: store {store!r} has data variables "
                    f"{names}; pass var=<name> to choose one."
                )
            var = names[0]
        elif var not in ds.data_vars:
            raise KeyError(
                f"DaskField.from_zarr: {var!r} is not a data variable of "
                f"{store!r}; available: {names}."
            )
        return cls(ds[var])

    @cached_property
    def domain(self) -> GridDomain:
        coords = {d: np.asarray(self.array[d].values) for d in self.array.dims}
        crs = getattr(self.array, "rio", None)
        crs = crs.crs if crs is not None else None
        return GridDomain(coords=coords, crs=crs)

    def select(self, indexer: dict[str, slice]) -> Any:
        """Read one patch as a materialised `xarray.DataArray`.

        Returns the computed slice (not another `DaskField`), so the
        payload is `np.asarray`-able and feeds the spatial aggregations
        directly — mirroring `XarrayField.select`. Coordinates come along
        with ``isel``; when the source is georeferenced through rioxarray
        (it carries a grid-mapping coordinate) the chip also gets an
        explicit window transform, since ``rio.transform()`` on a
        coordinate-free slice would otherwise report the full-array affine.
        """
        sub = _write_window_transform(self.array, self.array.isel(**indexer), indexer)
        return sub.compute()

    def with_data(self, array: Any) -> DaskField:
        reject_georeader(array, "DaskField.with_data")
        return DaskField(self.array.copy(data=array))

from_zarr(store, *, var=None, **kwargs) classmethod

Open one variable of a zarr store with xarray as a DaskField.

xr.open_zarr returns a Dataset; the field wraps one of its data variables.

Parameters:

Name Type Description Default
store Any

Anything xarray.open_zarr accepts (path, URL, store).

required
var str | None

Data variable to wrap. May be omitted when the store holds exactly one data variable.

None
**kwargs Any

Forwarded to xarray.open_zarr.

{}

Raises:

Type Description
KeyError

var is not a data variable of the store.

ValueError

var is omitted and the store holds zero or several data variables.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/dask.py
@classmethod
def from_zarr(
    cls, store: Any, *, var: str | None = None, **kwargs: Any
) -> DaskField:
    """Open one variable of a zarr store with xarray as a `DaskField`.

    ``xr.open_zarr`` returns a `Dataset`; the field wraps one of its
    data variables.

    Args:
        store: Anything ``xarray.open_zarr`` accepts (path, URL, store).
        var: Data variable to wrap. May be omitted when the store holds
            exactly one data variable.
        **kwargs: Forwarded to ``xarray.open_zarr``.

    Raises:
        KeyError: ``var`` is not a data variable of the store.
        ValueError: ``var`` is omitted and the store holds zero or
            several data variables.
    """
    if xr is None:
        raise missing_extra("DaskField", "dask", "dask[bag]>=2024.8.3")
    ds = xr.open_zarr(store, **kwargs)
    names = list(ds.data_vars)
    if var is None:
        if len(names) != 1:
            raise ValueError(
                f"DaskField.from_zarr: store {store!r} has data variables "
                f"{names}; pass var=<name> to choose one."
            )
        var = names[0]
    elif var not in ds.data_vars:
        raise KeyError(
            f"DaskField.from_zarr: {var!r} is not a data variable of "
            f"{store!r}; available: {names}."
        )
    return cls(ds[var])

select(indexer)

Read one patch as a materialised xarray.DataArray.

Returns the computed slice (not another DaskField), so the payload is np.asarray-able and feeds the spatial aggregations directly — mirroring XarrayField.select. Coordinates come along with isel; when the source is georeferenced through rioxarray (it carries a grid-mapping coordinate) the chip also gets an explicit window transform, since rio.transform() on a coordinate-free slice would otherwise report the full-array affine.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/dask.py
def select(self, indexer: dict[str, slice]) -> Any:
    """Read one patch as a materialised `xarray.DataArray`.

    Returns the computed slice (not another `DaskField`), so the
    payload is `np.asarray`-able and feeds the spatial aggregations
    directly — mirroring `XarrayField.select`. Coordinates come along
    with ``isel``; when the source is georeferenced through rioxarray
    (it carries a grid-mapping coordinate) the chip also gets an
    explicit window transform, since ``rio.transform()`` on a
    coordinate-free slice would otherwise report the full-array affine.
    """
    sub = _write_window_transform(self.array, self.array.isel(**indexer), indexer)
    return sub.compute()

Vector features and points ([vector], [point])

geopatcher.fields.GeoPandasField dataclass

Wrap a geopandas.GeoDataFrame as a Field[VectorDomain].

If every geometry is a shapely.Point, callers can ask for a PointDomain view via the as_points=True flag — that branch builds a cKDTree on the point coordinates so KNNGraph / RadiusGraph queries are cheap.

Parameters:

Name Type Description Default
gdf Any

The underlying geopandas.GeoDataFrame.

required
as_points bool

If True, expose a PointDomain instead of a VectorDomain. The GDF must hold Point geometries.

False

domain (including its spatial index / cKDTree) is built on first access and cached; treat gdf as immutable once wrapped.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/geopandas.py
@dataclass(eq=False)
class GeoPandasField:
    """Wrap a `geopandas.GeoDataFrame` as a `Field[VectorDomain]`.

    If every geometry is a `shapely.Point`, callers can ask for a
    `PointDomain` view via the ``as_points=True`` flag — that branch
    builds a `cKDTree` on the point coordinates so `KNNGraph` /
    `RadiusGraph` queries are cheap.

    Args:
        gdf: The underlying `geopandas.GeoDataFrame`.
        as_points: If ``True``, expose a `PointDomain` instead of a
            `VectorDomain`. The GDF must hold Point geometries.

    ``domain`` (including its spatial index / ``cKDTree``) is built on
    first access and cached; treat ``gdf`` as immutable once wrapped.
    """

    gdf: Any
    as_points: bool = False

    def __post_init__(self) -> None:
        if gpd is None:
            raise missing_extra(
                "GeoPandasField", "vector", "geopandas>=0.14 shapely>=2"
            )

    @cached_property
    def domain(self) -> VectorDomain | PointDomain:
        if self.as_points:
            coords = np.c_[self.gdf.geometry.x, self.gdf.geometry.y]
            return PointDomain(coords=coords, kdtree=cKDTree(coords), crs=self.gdf.crs)
        return VectorDomain(
            geometry=self.gdf.geometry, sindex=self.gdf.sindex, crs=self.gdf.crs
        )

    def select(self, indexer: Any) -> GeoPandasField:
        """Return the sub-field at ``indexer`` — positional indexing only.

        ``indexer`` is a boolean mask, an integer position array, or a
        positional slice, all resolved via ``gdf.iloc``. Row *labels* are
        never consulted: samplers emit positions into the domain
        (``PointDomain.coords`` / ``VectorDomain.geometry`` order), so a
        label fallback would silently read the wrong rows whenever the
        index is not a ``RangeIndex``.
        """
        return GeoPandasField(self.gdf.iloc[indexer].copy(), as_points=self.as_points)

    def with_data(self, array: Any) -> GeoPandasField:
        """Attach one value per row as a ``_value`` column.

        Args:
            array: A 1-D array with exactly one entry per row of ``gdf``.
                Multi-dimensional payloads (e.g. per-row feature vectors)
                are not supported — a GeoDataFrame column holds scalars.

        Raises:
            ValueError: If ``array`` is not 1-D or its length differs
                from the number of rows.
        """
        reject_georeader(array, "GeoPandasField.with_data")
        values = np.asarray(array)
        if values.ndim != 1 or values.shape[0] != len(self.gdf):
            raise ValueError(
                "GeoPandasField.with_data expects a 1-D array with one value "
                f"per row ({len(self.gdf)}); got shape {values.shape}."
            )
        new = self.gdf.copy()
        new["_value"] = values
        return GeoPandasField(new, as_points=self.as_points)

select(indexer)

Return the sub-field at indexer — positional indexing only.

indexer is a boolean mask, an integer position array, or a positional slice, all resolved via gdf.iloc. Row labels are never consulted: samplers emit positions into the domain (PointDomain.coords / VectorDomain.geometry order), so a label fallback would silently read the wrong rows whenever the index is not a RangeIndex.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/geopandas.py
def select(self, indexer: Any) -> GeoPandasField:
    """Return the sub-field at ``indexer`` — positional indexing only.

    ``indexer`` is a boolean mask, an integer position array, or a
    positional slice, all resolved via ``gdf.iloc``. Row *labels* are
    never consulted: samplers emit positions into the domain
    (``PointDomain.coords`` / ``VectorDomain.geometry`` order), so a
    label fallback would silently read the wrong rows whenever the
    index is not a ``RangeIndex``.
    """
    return GeoPandasField(self.gdf.iloc[indexer].copy(), as_points=self.as_points)

with_data(array)

Attach one value per row as a _value column.

Parameters:

Name Type Description Default
array Any

A 1-D array with exactly one entry per row of gdf. Multi-dimensional payloads (e.g. per-row feature vectors) are not supported — a GeoDataFrame column holds scalars.

required

Raises:

Type Description
ValueError

If array is not 1-D or its length differs from the number of rows.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/geopandas.py
def with_data(self, array: Any) -> GeoPandasField:
    """Attach one value per row as a ``_value`` column.

    Args:
        array: A 1-D array with exactly one entry per row of ``gdf``.
            Multi-dimensional payloads (e.g. per-row feature vectors)
            are not supported — a GeoDataFrame column holds scalars.

    Raises:
        ValueError: If ``array`` is not 1-D or its length differs
            from the number of rows.
    """
    reject_georeader(array, "GeoPandasField.with_data")
    values = np.asarray(array)
    if values.ndim != 1 or values.shape[0] != len(self.gdf):
        raise ValueError(
            "GeoPandasField.with_data expects a 1-D array with one value "
            f"per row ({len(self.gdf)}); got shape {values.shape}."
        )
    new = self.gdf.copy()
    new["_value"] = values
    return GeoPandasField(new, as_points=self.as_points)

geopatcher.fields.XvecField dataclass

Wrap a vector data cube (xarray + xvec) as a Field[PointDomain].

Parameters:

Name Type Description Default
ds Any

An xarray.Dataset with a geometry coordinate of shapely.Point instances (the xvec convention).

required
geometry_dim str

Name of the geometry dimension / coordinate. Defaults to "geometry".

'geometry'

domain (including its cKDTree) is built on first access and cached; treat ds as immutable once wrapped.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/xvec.py
@dataclass(eq=False)
class XvecField:
    """Wrap a vector data cube (xarray + xvec) as a `Field[PointDomain]`.

    Args:
        ds: An `xarray.Dataset` with a ``geometry`` coordinate of
            `shapely.Point` instances (the xvec convention).
        geometry_dim: Name of the geometry dimension / coordinate.
            Defaults to ``"geometry"``.

    ``domain`` (including its ``cKDTree``) is built on first access and
    cached; treat ``ds`` as immutable once wrapped.
    """

    ds: Any
    geometry_dim: str = "geometry"

    def __post_init__(self) -> None:
        if xvec is None:
            raise missing_extra("XvecField", "point", "xvec>=0.4 scipy")

    @cached_property
    def domain(self) -> PointDomain:
        geom_var = self.ds[self.geometry_dim]
        coords = np.c_[[g.x for g in geom_var.values], [g.y for g in geom_var.values]]
        # xvec stashes the CRS on the geometry coord's attrs (set_geom_indexes
        # writes `crs=...` there). Newer xvec versions may expose it through
        # the xvec accessor — try the attr path first, fall back to None.
        crs = geom_var.attrs.get("crs")
        return PointDomain(coords=coords, kdtree=cKDTree(coords), crs=crs)

    def select(self, indexer: Any) -> XvecField:
        return XvecField(
            self.ds.isel({self.geometry_dim: indexer}), geometry_dim=self.geometry_dim
        )

    def with_data(self, array: Any) -> XvecField:
        reject_georeader(array, "XvecField.with_data")
        new = self.ds.copy()
        new["_value"] = ((self.geometry_dim,), np.asarray(array))
        return XvecField(new, geometry_dim=self.geometry_dim)

Domains

geopatcher.fields.RasterDomain

Bases: Protocol

A raster domain: a geoarray.Grid plus the full array shape.

The samplers and geometries plan windows on grid (transform, CRS, (H, W)); the aggregations size their output from shape ((..., H, W), leading band / time axes included). Every geoarray.RasterSource satisfies it, so RasterField.domain is the source itself and costs no read; so do geocloud.cog.CogDomain and the reprojected / rioxarray domain views. A bare geoarray.Grid is also accepted wherever a raster domain is (its shape is (H, W)), to plan anchors before any data exists.

Attributes:

Name Type Description
grid Grid

The pixel grid.

shape tuple[int, ...]

(..., H, W); the last two entries equal grid.shape.

Example

import numpy as np from geoarray import GeoArray scene = GeoArray( ... np.zeros((4, 64, 64), np.float32), ... (10.0, 0.0, 500000.0, 0.0, -10.0, 4600000.0), ... "EPSG:32630", ... ) isinstance(scene, RasterDomain), scene.grid.shape (True, (64, 64))

Source code in packages/geotoolz-patcher/src/geopatcher/_src/domains.py
@runtime_checkable
class RasterDomain(Protocol):
    """A raster domain: a `geoarray.Grid` plus the full array shape.

    The samplers and geometries plan windows on ``grid`` (transform, CRS,
    ``(H, W)``); the aggregations size their output from ``shape``
    (``(..., H, W)``, leading band / time axes included). Every
    `geoarray.RasterSource` satisfies it, so `RasterField.domain` is the
    source itself and costs no read; so do `geocloud.cog.CogDomain` and the
    reprojected / rioxarray domain views. A bare `geoarray.Grid` is also
    accepted wherever a raster domain is (its shape is ``(H, W)``), to plan
    anchors before any data exists.

    Attributes:
        grid: The pixel grid.
        shape: ``(..., H, W)``; the last two entries equal ``grid.shape``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> scene = GeoArray(
        ...     np.zeros((4, 64, 64), np.float32),
        ...     (10.0, 0.0, 500000.0, 0.0, -10.0, 4600000.0),
        ...     "EPSG:32630",
        ... )
        >>> isinstance(scene, RasterDomain), scene.grid.shape
        (True, (64, 64))
    """

    @property
    def grid(self) -> Grid: ...

    @property
    def shape(self) -> tuple[int, ...]: ...

geopatcher.fields.GridDomain dataclass

A dense, labeled N-D grid — the xarray.DataArray shape.

Parameters:

Name Type Description Default
coords dict[str, ndarray]

{dim_name: 1-D coordinate array}. The order of keys defines the canonical dim order used by Rectangular samplers on this domain.

required
crs Any | None

CRS of the spatial dims (lat/lon, x/y). Optional — non-georeferenced cubes are fine.

None

Attributes:

Name Type Description
shape tuple[int, ...]

tuple(len(coords[d]) for d in coords).

bounds dict[str, tuple[Any, Any]]

{dim: (min, max)} — derived lazily on access. Values keep the coordinate's own type (np.datetime64 for a time axis, a float for lat/lon, …) rather than being coerced to float, so time-bearing cubes honour the Domain contract.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/domains.py
@dataclass(eq=False)
class GridDomain:
    """A dense, labeled N-D grid — the `xarray.DataArray` shape.

    Args:
        coords: ``{dim_name: 1-D coordinate array}``. The order of keys
            defines the canonical dim order used by `Rectangular`
            samplers on this domain.
        crs: CRS of the spatial dims (lat/lon, x/y). Optional —
            non-georeferenced cubes are fine.

    Attributes:
        shape: ``tuple(len(coords[d]) for d in coords)``.
        bounds: ``{dim: (min, max)}`` — derived lazily on access. Values
            keep the coordinate's own type (``np.datetime64`` for a time
            axis, a float for lat/lon, …) rather than being coerced to
            ``float``, so time-bearing cubes honour the `Domain` contract.
    """

    coords: dict[str, np.ndarray]
    crs: Any | None = None

    @property
    def shape(self) -> tuple[int, ...]:
        return tuple(len(self.coords[d]) for d in self.coords)

    @property
    def bounds(self) -> dict[str, tuple[Any, Any]]:
        return {d: (np.min(c), np.max(c)) for d, c in self.coords.items()}

geopatcher.fields.VectorDomain dataclass

Vector geometries — polygons / lines indexed by an STRtree.

Parameters:

Name Type Description Default
geometry Any

A geopandas.GeoSeries of shapely geometries.

required
sindex Any

The geometry.sindex object — kept on the domain so spatial-index queries don't trigger a re-build.

required
crs Any

The series' CRS.

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/domains.py
@dataclass(eq=False)
class VectorDomain:
    """Vector geometries — polygons / lines indexed by an STRtree.

    Args:
        geometry: A `geopandas.GeoSeries` of shapely geometries.
        sindex: The `geometry.sindex` object — kept on the domain so
            spatial-index queries don't trigger a re-build.
        crs: The series' CRS.
    """

    geometry: Any
    sindex: Any
    crs: Any

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        b = self.geometry.total_bounds
        return float(b[0]), float(b[1]), float(b[2]), float(b[3])

geopatcher.fields.PointDomain dataclass

Scattered points — coordinates + a cKDTree for nearest-neighbor lookups.

Parameters:

Name Type Description Default
coords ndarray

(N, 2) array of point coordinates in the domain's CRS.

required
kdtree Any

A scipy.spatial.cKDTree over coords. Built once at domain-construction and reused by KNNGraph / RadiusGraph.

required
crs Any | None

Coordinate reference system, or None for arbitrary in-plane coordinates.

None
interp str

Interpolation used by sample when extracting raster values at this domain's points — "nearest" (containing pixel, the historical behaviour) or "bilinear" (interpolate between the four surrounding pixel centres).

'nearest'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/domains.py
@dataclass(eq=False)
class PointDomain:
    """Scattered points — coordinates + a `cKDTree` for nearest-neighbor lookups.

    Args:
        coords: ``(N, 2)`` array of point coordinates in the domain's CRS.
        kdtree: A `scipy.spatial.cKDTree` over ``coords``. Built once at
            domain-construction and reused by `KNNGraph` / `RadiusGraph`.
        crs: Coordinate reference system, or ``None`` for arbitrary
            in-plane coordinates.
        interp: Interpolation used by `sample` when extracting raster
            values at this domain's points — ``"nearest"`` (containing
            pixel, the historical behaviour) or ``"bilinear"``
            (interpolate between the four surrounding pixel centres).
    """

    coords: np.ndarray
    kdtree: Any
    crs: Any | None = None
    interp: str = "nearest"

    _VALID_INTERP: ClassVar[tuple[str, ...]] = ("nearest", "bilinear")

    def __post_init__(self) -> None:
        if self.interp not in self._VALID_INTERP:
            raise ValueError(
                f"invalid interp {self.interp!r}; expected one of {self._VALID_INTERP}"
            )

    @property
    def bounds(self) -> tuple[float, float, float, float]:
        mins = self.coords.min(axis=0)
        maxs = self.coords.max(axis=0)
        return float(mins[0]), float(mins[1]), float(maxs[0]), float(maxs[1])

    def sample(self, raster: Any) -> np.ndarray:
        """Extract raster values at this domain's points.

        Uses the domain's `interp` mode: ``"nearest"`` reads the pixel
        containing each point, ``"bilinear"`` interpolates between the
        four surrounding pixel centres (clamped at the raster edge).
        Points falling outside the raster extent return ``NaN``.

        Args:
            raster: A `geoarray.GeoArray` (``(..., H, W)``), assumed to
                share this domain's CRS.

        Returns:
            ``(N,)`` float array of sampled values for 2-D rasters, or
            ``(..., N)`` for rasters with leading band dims.
        """
        reject_georeader(raster, "PointDomain.sample")
        grid = raster_grid(raster)
        if grid is None:
            raise TypeError(
                "PointDomain.sample takes a geoarray.GeoArray, got "
                f"{type(raster).__name__}"
            )
        values = np.asarray(raster, dtype=float)
        h, w = values.shape[-2], values.shape[-1]
        inv = ~grid.affine
        xs = self.coords[:, 0].astype(float)
        ys = self.coords[:, 1].astype(float)
        # Fractional pixel coords, measured from the raster's UL corner.
        cols = inv.a * xs + inv.b * ys + inv.c
        rows = inv.d * xs + inv.e * ys + inv.f
        inside = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w)
        out_shape = (*values.shape[:-2], len(self.coords))
        out = np.full(out_shape, np.nan, dtype=float)
        if not inside.any():
            return out
        if self.interp == "nearest":
            r = np.floor(rows[inside]).astype(int)
            c = np.floor(cols[inside]).astype(int)
            out[..., inside] = values[..., r, c]
            return out
        # Bilinear between pixel centres (which sit at +0.5 in pixel space).
        u = cols[inside] - 0.5
        v = rows[inside] - 0.5
        c0 = np.floor(u).astype(int)
        r0 = np.floor(v).astype(int)
        wu = u - c0
        wv = v - r0
        c0c = np.clip(c0, 0, w - 1)
        c1c = np.clip(c0 + 1, 0, w - 1)
        r0c = np.clip(r0, 0, h - 1)
        r1c = np.clip(r0 + 1, 0, h - 1)
        out[..., inside] = (
            values[..., r0c, c0c] * (1 - wv) * (1 - wu)
            + values[..., r0c, c1c] * (1 - wv) * wu
            + values[..., r1c, c0c] * wv * (1 - wu)
            + values[..., r1c, c1c] * wv * wu
        )
        return out

sample(raster)

Extract raster values at this domain's points.

Uses the domain's interp mode: "nearest" reads the pixel containing each point, "bilinear" interpolates between the four surrounding pixel centres (clamped at the raster edge). Points falling outside the raster extent return NaN.

Parameters:

Name Type Description Default
raster Any

A geoarray.GeoArray ((..., H, W)), assumed to share this domain's CRS.

required

Returns:

Type Description
ndarray

(N,) float array of sampled values for 2-D rasters, or

ndarray

(..., N) for rasters with leading band dims.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/domains.py
def sample(self, raster: Any) -> np.ndarray:
    """Extract raster values at this domain's points.

    Uses the domain's `interp` mode: ``"nearest"`` reads the pixel
    containing each point, ``"bilinear"`` interpolates between the
    four surrounding pixel centres (clamped at the raster edge).
    Points falling outside the raster extent return ``NaN``.

    Args:
        raster: A `geoarray.GeoArray` (``(..., H, W)``), assumed to
            share this domain's CRS.

    Returns:
        ``(N,)`` float array of sampled values for 2-D rasters, or
        ``(..., N)`` for rasters with leading band dims.
    """
    reject_georeader(raster, "PointDomain.sample")
    grid = raster_grid(raster)
    if grid is None:
        raise TypeError(
            "PointDomain.sample takes a geoarray.GeoArray, got "
            f"{type(raster).__name__}"
        )
    values = np.asarray(raster, dtype=float)
    h, w = values.shape[-2], values.shape[-1]
    inv = ~grid.affine
    xs = self.coords[:, 0].astype(float)
    ys = self.coords[:, 1].astype(float)
    # Fractional pixel coords, measured from the raster's UL corner.
    cols = inv.a * xs + inv.b * ys + inv.c
    rows = inv.d * xs + inv.e * ys + inv.f
    inside = (rows >= 0) & (rows < h) & (cols >= 0) & (cols < w)
    out_shape = (*values.shape[:-2], len(self.coords))
    out = np.full(out_shape, np.nan, dtype=float)
    if not inside.any():
        return out
    if self.interp == "nearest":
        r = np.floor(rows[inside]).astype(int)
        c = np.floor(cols[inside]).astype(int)
        out[..., inside] = values[..., r, c]
        return out
    # Bilinear between pixel centres (which sit at +0.5 in pixel space).
    u = cols[inside] - 0.5
    v = rows[inside] - 0.5
    c0 = np.floor(u).astype(int)
    r0 = np.floor(v).astype(int)
    wu = u - c0
    wv = v - r0
    c0c = np.clip(c0, 0, w - 1)
    c1c = np.clip(c0 + 1, 0, w - 1)
    r0c = np.clip(r0, 0, h - 1)
    r1c = np.clip(r0 + 1, 0, h - 1)
    out[..., inside] = (
        values[..., r0c, c0c] * (1 - wv) * (1 - wu)
        + values[..., r0c, c1c] * (1 - wv) * wu
        + values[..., r1c, c0c] * wv * (1 - wu)
        + values[..., r1c, c1c] * wv * wu
    )
    return out