Skip to content

Spatial axes — geopatcher.spatial

The four spatial axes composed by SpatialPatcher: Geometry × Sampler × Window × Aggregation (including the streaming sketch aggregations).

Spatial axes

Geometry

geopatcher.spatial.geometry.Geometry

Base for spatial neighborhood definitions.

Subclasses override neighborhood (anchor → backend-specific indices). Anchor placement is the sampler's job.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
class Geometry:
    """Base for spatial neighborhood definitions.

    Subclasses override `neighborhood` (anchor → backend-specific
    indices). Anchor placement is the sampler's job.
    """

    forbid_in_yaml: ClassVar[bool] = False

    def neighborhood(self, domain: Any, anchor: Any) -> Any:
        raise NotImplementedError(
            f"{type(self).__name__} doesn't support {type(domain).__name__} domains."
        )

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.spatial.geometry.Rectangular dataclass

Bases: Geometry

Axis-aligned box — the bread-and-butter raster / grid geometry.

Parameters:

Name Type Description Default
size tuple[int, ...]

For raster, (height, width) in pixels. For grid, one length per declared dim in the domain's coord order.

required
boundary BoundaryMode

How to treat anchors whose patch would overflow the domain edge. See BoundaryMode and docs/patcher/patching.md.

  • "drop" (default): samplers only place anchors whose patch fits in-domain; the trailing residual is dropped, and a patch larger than the domain yields no anchors at all.
  • "pad": the sampler places the edge anchor (the first whose patch reaches the edge); out-of-bounds cells are filled with the reader's nodata, or pad_value. A GeoArray source with fill_value=None pads float data with NaN (the chip declares NaN) and raises for integer or bool data.
  • "reflect": as "pad", but the overflow is mirror-padded from the interior (numpy mode="reflect", repeated when the overflow exceeds the domain).
  • "shrink": as "pad", but the window is clipped to the domain on every side (a negative anchor included), so the patch is smaller at the edge; weights crop to match.
  • "raise": as "pad", but SpatialPatcher.split raises on the first overflowing window.

Honoured on raster domains and on GridDomain slice dicts. "pad" / "reflect" are applied by the patcher itself — the overflowing window is clipped to the domain, read once, then padded up to the full geometry size with the chip's georeferencing kept exact — so they work for any Field. Merging is likewise boundary-agnostic: every dense aggregation crops chip data and weights to the in-domain part of the patch's indices.

'drop'
pad_value float | None

Constant fill for boundary="pad". When None (default) the out-of-bounds region is filled with the reader's nodata; set a number to force a specific constant. It must be representable in the field's dtype (checked at read time — -999 into a uint16 raster raises instead of wrapping). Ignored by every other boundary mode.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
@dataclass(eq=False)
class Rectangular(Geometry):
    """Axis-aligned box — the bread-and-butter raster / grid geometry.

    Args:
        size: For raster, ``(height, width)`` in pixels. For grid, one
            length per declared dim in the domain's coord order.
        boundary: How to treat anchors whose patch would overflow the
            domain edge. See `BoundaryMode` and ``docs/patcher/patching.md``.

            - ``"drop"`` (default): samplers only place anchors whose
              patch fits in-domain; the trailing residual is dropped, and
              a patch larger than the domain yields no anchors at all.
            - ``"pad"``: the sampler places the edge anchor (the first
              whose patch reaches the edge); out-of-bounds cells are
              filled with the reader's nodata, or ``pad_value``. A
              `GeoArray` source with ``fill_value=None`` pads float data
              with NaN (the chip declares NaN) and raises for integer or
              bool data.
            - ``"reflect"``: as ``"pad"``, but the overflow is
              mirror-padded from the interior (numpy ``mode="reflect"``,
              repeated when the overflow exceeds the domain).
            - ``"shrink"``: as ``"pad"``, but the window is clipped to the
              domain on every side (a negative anchor included), so the
              patch is smaller at the edge; weights crop to match.
            - ``"raise"``: as ``"pad"``, but `SpatialPatcher.split`
              raises on the first overflowing window.

            Honoured on raster domains and on `GridDomain` slice dicts.
            ``"pad"`` / ``"reflect"`` are applied by the patcher itself —
            the overflowing window is clipped to the domain, read once,
            then padded up to the full geometry size with the chip's
            georeferencing kept exact — so they work for any `Field`.
            Merging is likewise boundary-agnostic: every dense
            aggregation crops chip data and weights to the in-domain part
            of the patch's indices.
        pad_value: Constant fill for ``boundary="pad"``. When ``None``
            (default) the out-of-bounds region is filled with the
            reader's nodata; set a number to force a specific constant.
            It must be representable in the field's dtype (checked at
            read time — ``-999`` into a ``uint16`` raster raises instead
            of wrapping). Ignored by every other boundary mode.
    """

    size: tuple[int, ...]
    boundary: BoundaryMode = "drop"
    pad_value: float | None = None

    def __post_init__(self) -> None:
        if self.boundary not in _VALID_BOUNDARY_MODES:
            raise ValueError(
                f"invalid boundary mode {self.boundary!r}; "
                f"expected one of {_VALID_BOUNDARY_MODES}"
            )
        if self.pad_value is not None and (
            isinstance(self.pad_value, bool)
            or not isinstance(self.pad_value, numbers.Real)
        ):
            raise TypeError(
                f"pad_value must be a real number or None, got {self.pad_value!r}"
            )

    def neighborhood(self, domain: Any, anchor: Any) -> Any:
        if _is_raster_domain(domain):
            from rasterio.windows import Window

            row_off, col_off = int(anchor[0]), int(anchor[1])
            ph, pw = int(self.size[-2]), int(self.size[-1])
            if self.boundary == "shrink":
                dh, dw = int(domain.shape[-2]), int(domain.shape[-1])
                row_off, ph = _shrink_axis(row_off, ph, dh)
                col_off, pw = _shrink_axis(col_off, pw, dw)
            return Window(col_off=col_off, row_off=row_off, width=pw, height=ph)
        if isinstance(domain, GridDomain):
            dims = list(domain.coords)
            if len(self.size) != len(dims):
                raise ValueError(
                    f"size must name every GridDomain dim: got size={tuple(self.size)} "
                    f"for dims {tuple(dims)}."
                )
            out = {}
            for d, sz in zip(dims, self.size, strict=True):
                start, length = int(anchor[d]), int(sz)
                if self.boundary == "shrink":
                    start, length = _shrink_axis(start, length, len(domain.coords[d]))
                out[d] = slice(start, start + length)
            return out
        raise NotImplementedError(
            f"spatial.geometry.Rectangular doesn't support "
            f"{type(domain).__name__} domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.geometry.SphericalCap dataclass

Bases: Geometry

Geodesic cap of radius radius_km — for lat/lon fields near the poles.

On a GridDomain the latitude / longitude dims are found by name (lat / latitude and lon / longitude). The anchor is either the index dict a grid sampler yields (the cap is centred on the cell at those indices) or a (lat, lon) value pair. The neighborhood is the cap's bounding box as a {dim: slice} dict — every other dim kept whole — plus the boolean mask of cells inside the cap, which becomes the patch weights. On a PointDomain it is the indices of the points inside the cap.

Parameters:

Name Type Description Default
radius_km float

Cap radius in kilometres, used as great-circle distance from the anchor, on the IUGG mean sphere (R = 6371.0088 km).

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
@dataclass(eq=False)
class SphericalCap(Geometry):
    """Geodesic cap of radius ``radius_km`` — for lat/lon fields near the poles.

    On a `GridDomain` the latitude / longitude dims are found by name
    (``lat`` / ``latitude`` and ``lon`` / ``longitude``). The anchor is
    either the index dict a grid sampler yields (the cap is centred on
    the cell at those indices) or a ``(lat, lon)`` value pair. The
    neighborhood is the cap's bounding box as a ``{dim: slice}`` dict —
    every other dim kept whole — plus the boolean mask of cells inside
    the cap, which becomes the patch weights. On a `PointDomain` it is
    the indices of the points inside the cap.

    Args:
        radius_km: Cap radius in kilometres, used as great-circle distance
            from the anchor, on the IUGG mean sphere (R = 6371.0088 km).
    """

    radius_km: float

    def neighborhood(self, domain: Any, anchor: Any) -> Any:
        if isinstance(domain, GridDomain):
            return self._grid_neighborhood(domain, anchor)
        if isinstance(domain, PointDomain):
            # PointDomain coords are (x, y) = (lon, lat), matching the
            # GeoPandas / xvec adapter convention. The KNN/radius haversine
            # paths on PointDomain use anchor[0] = lon, anchor[1] = lat;
            # mirror that here so spherical-cap on the natural (lon, lat)
            # anchor doesn't quietly swap coordinates.
            lon_a, lat_a = float(anchor[0]), float(anchor[1])
            lat_pts = domain.coords[:, 1]
            lon_pts = domain.coords[:, 0]
            d = _haversine_km(lat_a, lon_a, lat_pts, lon_pts)
            return np.flatnonzero(d <= self.radius_km)
        raise NotImplementedError(
            f"spatial.geometry.SphericalCap doesn't support {type(domain).__name__} "
            "domains."
        )

    def _grid_neighborhood(self, domain: GridDomain, anchor: Any) -> _MaskedWindow:
        lat_dim = _find_dim(domain, ("lat", "latitude"))
        lon_dim = _find_dim(domain, ("lon", "longitude"))
        lat = np.asarray(domain.coords[lat_dim], dtype=float)
        lon = np.asarray(domain.coords[lon_dim], dtype=float)
        if isinstance(anchor, dict):
            lat_a, lon_a = lat[int(anchor[lat_dim])], lon[int(anchor[lon_dim])]
        else:
            lat_a, lon_a = float(anchor[0]), float(anchor[1])
        llat, llon = np.meshgrid(lat, lon, indexing="ij")
        inside = _haversine_km(lat_a, lon_a, llat, llon) <= self.radius_km
        rows, cols = (
            np.flatnonzero(inside.any(axis=1)),
            np.flatnonzero(inside.any(axis=0)),
        )
        if rows.size == 0:
            raise ValueError(
                f"spatial.geometry.SphericalCap of {self.radius_km} km around "
                f"({lat_a}, {lon_a}) contains no grid cell."
            )
        box = {
            lat_dim: slice(int(rows[0]), int(rows[-1]) + 1),
            lon_dim: slice(int(cols[0]), int(cols[-1]) + 1),
        }
        mask_2d = inside[box[lat_dim], box[lon_dim]]
        indexer = {
            d: box.get(d, slice(0, len(domain.coords[d]))) for d in domain.coords
        }
        # Lay the (lat, lon) mask out in the domain's dim order, broadcast
        # over every other dim, so it matches the selected chip's shape.
        spatial = [d for d in domain.coords if d in box]
        if spatial != [lat_dim, lon_dim]:
            mask_2d = mask_2d.T
        shape = [s.stop - s.start for s in indexer.values()]
        expand = [1 if d not in box else n for d, n in zip(indexer, shape, strict=True)]
        mask = np.broadcast_to(mask_2d.reshape(expand), shape)
        return _MaskedWindow(window=indexer, mask=mask)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.geometry.KNNGraph dataclass

Bases: Geometry

Fixed-k nearest-neighbor neighborhood.

Parameters:

Name Type Description Default
k int

Number of neighbors to return per anchor (>= 1); capped at the number of features, so k > N returns all N.

required
metric str

"euclidean" (planar; uses the domain's kdtree) or "haversine" (great-circle; requires lat/lon coords).

'euclidean'

An integer anchor (e.g. from spatial.sampler.Random) is the index of a point, or of a vector feature whose centroid is used.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
@dataclass(eq=False)
class KNNGraph(Geometry):
    """Fixed-k nearest-neighbor neighborhood.

    Args:
        k: Number of neighbors to return per anchor (``>= 1``); capped at
            the number of features, so ``k > N`` returns all ``N``.
        metric: ``"euclidean"`` (planar; uses the domain's kdtree) or
            ``"haversine"`` (great-circle; requires lat/lon coords).

    An integer anchor (e.g. from `spatial.sampler.Random`) is the index of a point,
    or of a vector feature whose centroid is used.
    """

    k: int
    metric: str = "euclidean"

    def __post_init__(self) -> None:
        if int(self.k) != self.k or self.k < 1:
            raise ValueError(f"k must be an integer >= 1, got {self.k!r}")

    def neighborhood(self, domain: Any, anchor: Any) -> np.ndarray:
        if isinstance(domain, PointDomain):
            anchor_xy = _to_xy(domain, anchor)
            if self.metric == "euclidean":
                # scipy pads k > N with the sentinel index N; cap k instead.
                k = min(int(self.k), len(domain.coords))
                _, idx = domain.kdtree.query(anchor_xy, k=k)
                return np.atleast_1d(idx).astype(int)
            if self.metric == "haversine":
                lats = domain.coords[:, 1]
                lons = domain.coords[:, 0]
                d = _haversine_km(anchor_xy[1], anchor_xy[0], lats, lons)
                return np.argsort(d)[: self.k]
            raise ValueError(f"unknown metric: {self.metric!r}")
        if isinstance(domain, VectorDomain):
            anchor_geom = _to_shapely_point(anchor, domain)
            centroids = domain.geometry.centroid
            d = centroids.distance(anchor_geom).values
            return np.argsort(d)[: self.k]
        raise NotImplementedError(
            f"spatial.geometry.KNNGraph doesn't support {type(domain).__name__} "
            "domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.geometry.RadiusGraph dataclass

Bases: Geometry

All neighbors within a fixed radius — variable patch size.

Parameters:

Name Type Description Default
radius float

Radius in the domain's coordinate units.

required
metric str

"euclidean" for planar coords, "haversine" for lat/lon (radius then interpreted as km).

'euclidean'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
@dataclass(eq=False)
class RadiusGraph(Geometry):
    """All neighbors within a fixed radius — variable patch size.

    Args:
        radius: Radius in the domain's coordinate units.
        metric: ``"euclidean"`` for planar coords, ``"haversine"`` for
            lat/lon (radius then interpreted as km).
    """

    radius: float
    metric: str = "euclidean"

    def neighborhood(self, domain: Any, anchor: Any) -> Any:
        if isinstance(domain, PointDomain):
            anchor_xy = _to_xy(domain, anchor)
            if self.metric == "euclidean":
                idx = domain.kdtree.query_ball_point(anchor_xy, r=self.radius)
                return np.asarray(idx, dtype=int)
            if self.metric == "haversine":
                lats = domain.coords[:, 1]
                lons = domain.coords[:, 0]
                d = _haversine_km(anchor_xy[1], anchor_xy[0], lats, lons)
                return np.flatnonzero(d <= self.radius)
            raise ValueError(f"unknown metric: {self.metric!r}")
        if isinstance(domain, VectorDomain):
            anchor_geom = _to_shapely_point(anchor, domain)
            buf = anchor_geom.buffer(self.radius)
            tree = domain.sindex
            hits = tree.query(buf, predicate="intersects")
            return np.asarray(hits, dtype=int)
        raise NotImplementedError(
            f"spatial.geometry.RadiusGraph doesn't support {type(domain).__name__} "
            "domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.geometry.PolygonIntersection dataclass

Bases: Geometry

Patch = pixels (or features) lying inside a given polygon.

On a RasterDomain, neighborhood returns a MaskedWindow: the bounding rasterio.windows.Window of the polygon's footprint, rounded outward to whole pixels and clipped to the domain, + the boolean mask of the window's pixels whose centre lies inside the polygon. A polygon that does not overlap the raster at all raises ValueError. On a VectorDomain, it returns the indices of geometries that intersect.

Parameters:

Name Type Description Default
polygons Any

Sequence (typically a geopandas.GeoSeries) of polygons. The anchor passed to neighborhood indexes into this sequence.

required
Note

forbid_in_yaml = True — the polygons are runtime geometries with no faithful JSON form, so get_config() is a debug summary ({"n_polygons": ...}), not a rebuild recipe, and PatchCache refuses this geometry as a cache key (two polygon sets of equal length would otherwise share keys).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
@dataclass(eq=False)
class PolygonIntersection(Geometry):
    """Patch = pixels (or features) lying inside a given polygon.

    On a `RasterDomain`, ``neighborhood`` returns a ``MaskedWindow``: the
    bounding `rasterio.windows.Window` of the polygon's footprint, rounded
    outward to whole pixels and clipped to the domain, + the boolean mask
    of the window's pixels whose centre lies inside the polygon. A polygon
    that does not overlap the raster at all raises ``ValueError``. On a
    `VectorDomain`, it returns the indices of geometries that intersect.

    Args:
        polygons: Sequence (typically a ``geopandas.GeoSeries``) of
            polygons. The ``anchor`` passed to ``neighborhood`` indexes
            into this sequence.

    Note:
        ``forbid_in_yaml = True`` — the polygons are runtime geometries
        with no faithful JSON form, so ``get_config()`` is a debug summary
        (``{"n_polygons": ...}``), not a rebuild recipe, and `PatchCache`
        refuses this geometry as a cache key (two polygon sets of equal
        length would otherwise share keys).
    """

    polygons: Any

    forbid_in_yaml: ClassVar[bool] = True

    def neighborhood(self, domain: Any, anchor: Any) -> Any:
        poly = self.polygons.iloc[int(anchor)]
        if _is_raster_domain(domain):
            return _polygon_masked_window(domain, poly, int(anchor))
        if isinstance(domain, VectorDomain):
            hits = domain.sindex.query(poly, predicate="intersects")
            return np.asarray(hits, dtype=int)
        raise NotImplementedError(
            "spatial.geometry.PolygonIntersection doesn't support "
            f"{type(domain).__name__} domains."
        )

    def get_config(self) -> dict[str, Any]:
        return {"n_polygons": len(self.polygons)}

Sampler

geopatcher.spatial.sampler.Sampler

Base for anchor-placement strategies.

Subclasses implement anchors(domain, geometry) -> Iterable[Anchor]. The geometry is passed so size-dependent samplers (spatial.sampler.RegularStride, spatial.sampler.JitteredStride) can compute valid anchor ranges.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
class Sampler:
    """Base for anchor-placement strategies.

    Subclasses implement `anchors(domain, geometry) -> Iterable[Anchor]`.
    The geometry is passed so size-dependent samplers (`spatial.sampler.RegularStride`,
    `spatial.sampler.JitteredStride`) can compute valid anchor ranges.
    """

    forbid_in_yaml: ClassVar[bool] = False

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterable[Any]:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.spatial.sampler.RegularStride dataclass

Bases: Sampler

Regular lattice — step along each axis.

On a raster, step is in pixels; the anchors are upper-left corners. On a grid, step is per declared dim in coord order.

Parameters:

Name Type Description Default
step int | tuple[int, ...]

Stride. A scalar broadcasts; a sequence is per-axis.

required
check_full_scan bool

If True, raise IncompleteScanConfiguration at anchor time when boundary="drop" would silently lose cells on any axis — (domain_len - patch_size) % step != 0 (a partial tile at the trailing edge) or a patch larger than the domain. Only checked under "drop": the other boundary modes cover the trailing edge themselves. Off by default; opt in for xrpatcher-style strict-tiling workloads. The temporal counterpart is exact_quotient in temporal/stencils.py.

False

Anchor placement per axis of length L, patch P, step S:

  • "drop": 0, S, 2S, … while the patch fits (≤ L - P); none at all when P > L.
  • any other mode: 0, S, 2S, … up to and including the first anchor whose patch reaches the edge (stop = max(L - P, 0) + S), so the trailing strip is covered without a redundant extra row.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class RegularStride(Sampler):
    """Regular lattice — step along each axis.

    On a raster, ``step`` is in pixels; the anchors are upper-left
    corners. On a grid, ``step`` is per declared dim in coord order.

    Args:
        step: Stride. A scalar broadcasts; a sequence is per-axis.
        check_full_scan: If ``True``, raise `IncompleteScanConfiguration`
            at anchor time when ``boundary="drop"`` would silently lose
            cells on any axis — ``(domain_len - patch_size) % step != 0``
            (a partial tile at the trailing edge) or a patch larger than
            the domain. Only checked under ``"drop"``: the other boundary
            modes cover the trailing edge themselves. Off by default;
            opt in for xrpatcher-style strict-tiling workloads. The
            temporal counterpart is `exact_quotient` in `temporal/stencils.py`.

    Anchor placement per axis of length ``L``, patch ``P``, step ``S``:

    - ``"drop"``: ``0, S, 2S, …`` while the patch fits (``≤ L - P``);
      none at all when ``P > L``.
    - any other mode: ``0, S, 2S, …`` up to and including the first
      anchor whose patch reaches the edge (``stop = max(L - P, 0) + S``),
      so the trailing strip is covered without a redundant extra row.
    """

    step: int | tuple[int, ...]
    check_full_scan: bool = False

    def __post_init__(self) -> None:
        _validate_step(self.step)

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        boundary = getattr(geometry, "boundary", "drop")
        if self.check_full_scan and boundary == "drop":
            self._assert_full_scan(domain, geometry)
        if _is_raster_domain(domain):
            h, w = int(domain.shape[-2]), int(domain.shape[-1])
            sh, sw = self._broadcast(2)
            size = getattr(geometry, "size", (1, 1))
            ph, pw = int(size[-2]), int(size[-1])
            if _drop_oversize(type(self).__name__, boundary, (h, w), (ph, pw)):
                return
            for r in _lattice(h, ph, sh, boundary):
                for c in _lattice(w, pw, sw, boundary):
                    yield (r, c)
            return
        if isinstance(domain, GridDomain):
            dims = list(domain.coords)
            steps = self._broadcast(len(dims))
            size = _grid_size(domain, geometry)
            lens = [len(domain.coords[d]) for d in dims]
            if _drop_oversize(type(self).__name__, boundary, lens, size):
                return
            ranges = [
                _lattice(L, int(p), int(s), boundary)
                for L, p, s in zip(lens, size, steps, strict=True)
            ]
            for idxs in _ndrange(ranges):
                yield dict(zip(dims, idxs, strict=True))
            return
        raise NotImplementedError(
            f"spatial.sampler.RegularStride doesn't support {type(domain).__name__} "
            "domains."
        )

    def _assert_full_scan(self, domain: Any, geometry: SpatialGeometry) -> None:
        """Raise `IncompleteScanConfiguration` if any axis would drop a tile."""
        if _is_raster_domain(domain):
            lens = (int(domain.shape[-2]), int(domain.shape[-1]))
            sizes = tuple(int(s) for s in getattr(geometry, "size", (1, 1)))
            steps = self._broadcast(2)
            axes = ("row", "col")
        elif isinstance(domain, GridDomain):
            dims = list(domain.coords)
            lens = tuple(len(domain.coords[d]) for d in dims)
            sizes = _grid_size(domain, geometry)
            steps = self._broadcast(len(dims))
            axes = tuple(dims)
        else:
            # Domains without a dense axis structure (Point/Vector) — the
            # check doesn't apply; defer to the per-domain anchor logic.
            return
        for axis, length, size, step in zip(axes, lens, sizes, steps, strict=True):
            if size > length:
                raise IncompleteScanConfiguration(
                    f"Incomplete scan on axis {axis!r}: patch size {size} "
                    f"exceeds the axis length {length}, so boundary='drop' "
                    "places no anchor. Use a smaller size, or "
                    "boundary='pad' / 'reflect' / 'shrink'."
                )
            remainder = (length - size) % step
            if remainder != 0:
                raise IncompleteScanConfiguration(
                    f"Incomplete scan on axis {axis!r}: "
                    f"(length - size) % step = ({length} - {size}) % {step} "
                    f"= {remainder} ≠ 0. Adjust size/step or set "
                    "check_full_scan=False to allow the trailing partial tile."
                )

    def _broadcast(self, n: int) -> tuple[int, ...]:
        if isinstance(self.step, int):
            return tuple([self.step] * n)
        return tuple(int(s) for s in self.step)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.sampler.JitteredStride dataclass

Bases: Sampler

spatial.sampler.RegularStride + per-anchor uniform jitter (training augmentation).

Each offset is floor(u · step) with u ~ U(-jitter, jitter), so with jitter=0.5 and step=16 the offsets are uniform over the 16 integers -8 … 7 (truncating toward zero would pile ~2/16 of the mass on 0 and never reach ±8). Jittered anchors are clamped to [0, L - P].

Parameters:

Name Type Description Default
step int | tuple[int, ...]

As for spatial.sampler.RegularStride.

required
jitter float

Maximum jitter in step-units (0.0 = no jitter, 0.5 = ± half a step). Must be finite and non-negative.

0.5
seed int | None

Integer seed for reproducible draws. When set, two samplers with the same configuration return bit-identical anchors across calls and across instances (the contract tested in tests/test_determinism.py for issue jejjohnson/geopatcher#18). None (the default) re-seeds from OS entropy on every call — anchors will differ between calls.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class JitteredStride(Sampler):
    """`spatial.sampler.RegularStride` + per-anchor uniform jitter (training
    augmentation).

    Each offset is ``floor(u · step)`` with ``u ~ U(-jitter, jitter)``, so
    with ``jitter=0.5`` and ``step=16`` the offsets are uniform over the 16
    integers ``-8 … 7`` (truncating toward zero would pile ~2/16 of the
    mass on ``0`` and never reach ``±8``). Jittered anchors are clamped to
    ``[0, L - P]``.

    Args:
        step: As for `spatial.sampler.RegularStride`.
        jitter: Maximum jitter in step-units (0.0 = no jitter, 0.5 = ± half
            a step). Must be finite and non-negative.
        seed: Integer seed for reproducible draws. When set, two
            samplers with the same configuration return bit-identical
            anchors across calls and across instances (the contract
            tested in ``tests/test_determinism.py`` for issue jejjohnson/geopatcher#18).
            ``None`` (the default) re-seeds from OS entropy on every
            call — anchors will differ between calls.
    """

    step: int | tuple[int, ...]
    jitter: float = 0.5
    seed: int | None = None

    def __post_init__(self) -> None:
        _validate_step(self.step)
        if not (np.isfinite(self.jitter) and self.jitter >= 0):
            raise ValueError(f"jitter must be finite and >= 0, got {self.jitter!r}")

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        rng = np.random.default_rng(self.seed)
        base = RegularStride(step=self.step)
        if _is_raster_domain(domain):
            sh, sw = base._broadcast(2)
            h, w = int(domain.shape[-2]), int(domain.shape[-1])
            size = getattr(geometry, "size", (1, 1))
            ph, pw = int(size[-2]), int(size[-1])
            # Clamp jittered anchors to [0, L - P]: the patch fits, or —
            # when it is larger than the domain under a non-drop mode —
            # sits at the origin and the boundary policy handles the
            # overflow. (Under "drop" an oversize patch places nothing.)
            rmax, cmax = max(h - ph, 0), max(w - pw, 0)
            for r, c in base.anchors(domain, geometry):
                dr = _jitter_offset(rng, self.jitter, sh)
                dc = _jitter_offset(rng, self.jitter, sw)
                yield (min(rmax, max(0, r + dr)), min(cmax, max(0, c + dc)))
            return
        if isinstance(domain, GridDomain):
            dims = list(domain.coords)
            steps = base._broadcast(len(dims))
            size = _grid_size(domain, geometry)
            lens = [len(domain.coords[d]) for d in dims]
            maxes = {
                d: max(L - int(p), 0) for d, L, p in zip(dims, lens, size, strict=True)
            }
            for anchor in base.anchors(domain, geometry):
                out: dict[str, int] = {}
                for d, s in zip(dims, steps, strict=True):
                    dj = _jitter_offset(rng, self.jitter, s)
                    out[d] = min(maxes[d], max(0, int(anchor[d]) + dj))
                yield out
            return
        raise NotImplementedError(
            f"spatial.sampler.JitteredStride doesn't support {type(domain).__name__} "
            "domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.sampler.Random dataclass

Bases: Sampler

N uniformly-random anchors over the domain's placement space.

On a PointDomain / VectorDomain the anchors are feature indices; the graph geometries resolve them to the point / the feature's centroid.

Parameters:

Name Type Description Default
n_samples int

Number of anchors to draw (>= 0).

required
seed int | None

Integer seed for reproducible draws. When set, two samplers with the same configuration return bit-identical anchors across calls and across instances (the contract tested in tests/test_determinism.py for issue jejjohnson/geopatcher#18). None (the default) re-seeds from OS entropy on every call — anchors will differ between calls.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class Random(Sampler):
    """N uniformly-random anchors over the domain's placement space.

    On a `PointDomain` / `VectorDomain` the anchors are feature indices;
    the graph geometries resolve them to the point / the feature's
    centroid.

    Args:
        n_samples: Number of anchors to draw (``>= 0``).
        seed: Integer seed for reproducible draws. When set, two
            samplers with the same configuration return bit-identical
            anchors across calls and across instances (the contract
            tested in ``tests/test_determinism.py`` for issue jejjohnson/geopatcher#18).
            ``None`` (the default) re-seeds from OS entropy on every
            call — anchors will differ between calls.
    """

    n_samples: int
    seed: int | None = None

    def __post_init__(self) -> None:
        if int(self.n_samples) != self.n_samples or self.n_samples < 0:
            raise ValueError(
                f"n_samples must be a non-negative integer, got {self.n_samples!r}"
            )

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        rng = np.random.default_rng(self.seed)
        boundary = getattr(geometry, "boundary", "drop")
        if _is_raster_domain(domain):
            h, w = int(domain.shape[-2]), int(domain.shape[-1])
            size = getattr(geometry, "size", (1, 1))
            ph, pw = int(size[-2]), int(size[-1])
            # Draw from [0, L - P] so every patch fits; an anchor past
            # L - P would only add padding. A patch larger than the
            # domain sits at the origin (non-drop) or places nothing.
            if _drop_oversize(type(self).__name__, boundary, (h, w), (ph, pw)):
                return
            rhi, chi = max(h - ph, 0) + 1, max(w - pw, 0) + 1
            rs = rng.integers(0, rhi, size=self.n_samples)
            cs = rng.integers(0, chi, size=self.n_samples)
            for r, c in zip(rs, cs, strict=True):
                yield (int(r), int(c))
            return
        if isinstance(domain, GridDomain):
            dims = list(domain.coords)
            size = _grid_size(domain, geometry)
            lens = [len(domain.coords[d]) for d in dims]
            if _drop_oversize(type(self).__name__, boundary, lens, size):
                return
            for _ in range(self.n_samples):
                yield {
                    d: int(rng.integers(0, max(L - int(p), 0) + 1))
                    for d, L, p in zip(dims, lens, size, strict=True)
                }
            return
        if isinstance(domain, PointDomain | VectorDomain):
            n = (
                len(domain.coords)
                if isinstance(domain, PointDomain)
                else len(domain.geometry)
            )
            idx = rng.integers(0, n, size=self.n_samples)
            for i in idx:
                yield int(i)
            return
        raise NotImplementedError(
            f"spatial.sampler.Random doesn't support {type(domain).__name__} domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.sampler.PoissonDisk dataclass

Bases: Sampler

Well-spaced random anchors (raster + point).

Anchors are returned in arbitrary order; no two anchors are closer than min_dist in pixel (raster) or coord (point) units — exactly, between the integer anchors actually yielded.

  • Raster: Bridson's algorithm on the integer pixel lattice — each annulus candidate is snapped to its pixel before the distance test, so the guarantee holds for the yielded integer anchors.
  • PointDomain: greedy random-order thinning (dart throwing) of the existing points — a maximal subset with pairwise distance >= min_dist — in O(N) expected time via a background grid. max_tries does not apply: every point is tried exactly once.

Parameters:

Name Type Description Default
min_dist float

Minimum allowed separation between anchors (> 0).

required
max_tries int

Bridson parameter — attempts per active anchor (raster only, >= 1).

30
seed int | None

Optional integer seed.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class PoissonDisk(Sampler):
    """Well-spaced random anchors (raster + point).

    Anchors are returned in arbitrary order; no two anchors are closer
    than ``min_dist`` in pixel (raster) or coord (point) units — exactly,
    between the integer anchors actually yielded.

    - Raster: Bridson's algorithm on the integer pixel lattice — each
      annulus candidate is snapped to its pixel *before* the distance
      test, so the guarantee holds for the yielded integer anchors.
    - `PointDomain`: greedy random-order thinning (dart throwing) of the
      existing points — a maximal subset with pairwise distance
      ``>= min_dist`` — in ``O(N)`` expected time via a background grid.
      ``max_tries`` does not apply: every point is tried exactly once.

    Args:
        min_dist: Minimum allowed separation between anchors (``> 0``).
        max_tries: Bridson parameter — attempts per active anchor
            (raster only, ``>= 1``).
        seed: Optional integer seed.
    """

    min_dist: float
    max_tries: int = 30
    seed: int | None = None

    def __post_init__(self) -> None:
        if not (np.isfinite(self.min_dist) and self.min_dist > 0):
            raise ValueError(f"min_dist must be finite and > 0, got {self.min_dist!r}")
        if int(self.max_tries) != self.max_tries or self.max_tries < 1:
            raise ValueError(
                f"max_tries must be an integer >= 1, got {self.max_tries!r}"
            )

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        rng = np.random.default_rng(self.seed)
        boundary = getattr(geometry, "boundary", "drop")
        if _is_raster_domain(domain):
            h, w = int(domain.shape[-2]), int(domain.shape[-1])
            size = getattr(geometry, "size", (1, 1))
            ph, pw = int(size[-2]), int(size[-1])
            # See spatial.sampler.Random — anchors are drawn from [0, L - P].
            if _drop_oversize(type(self).__name__, boundary, (h, w), (ph, pw)):
                return
            region = (max(h - ph, 0) + 1, max(w - pw, 0) + 1)
            yield from _bridson_2d(region, self.min_dist, self.max_tries, rng)
            return
        if isinstance(domain, PointDomain):
            yield from _poisson_subset(domain.coords, self.min_dist, rng)
            return
        raise NotImplementedError(
            f"spatial.sampler.PoissonDisk doesn't support {type(domain).__name__} "
            "domains."
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.sampler.Explicit dataclass

Bases: Sampler

Caller-supplied anchors — the universal escape hatch.

Parameters:

Name Type Description Default
anchors_ Iterable[Any]

Sequence of anchors. Type must match what the spatial.geometry.Geometry expects on the target domain. Accepts any iterable at construction time; materialised to a list in __post_init__ so anchors() and get_config() can both walk it independently (the previous Iterable typing meant get_config() consumed one-shot iterators and silently left anchors() empty afterwards).

list()
Note

forbid_in_yaml = True — anchors are backend-native objects (pixel tuples, point indices, shapely geometries, …) with no faithful JSON form, so get_config() is a debug summary ({"n_anchors": ...}), not a rebuild recipe.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class Explicit(Sampler):
    """Caller-supplied anchors — the universal escape hatch.

    Args:
        anchors_: Sequence of anchors. Type must match what the
            `spatial.geometry.Geometry` expects on the target domain. Accepts any
            iterable at construction time; materialised to a list in
            ``__post_init__`` so ``anchors()`` and ``get_config()`` can
            both walk it independently (the previous Iterable typing
            meant ``get_config()`` consumed one-shot iterators and
            silently left ``anchors()`` empty afterwards).

    Note:
        ``forbid_in_yaml = True`` — anchors are backend-native objects
        (pixel tuples, point indices, shapely geometries, …) with no
        faithful JSON form, so ``get_config()`` is a debug summary
        (``{"n_anchors": ...}``), not a rebuild recipe.
    """

    anchors_: Iterable[Any] = field(default_factory=list)

    forbid_in_yaml: ClassVar[bool] = True

    def __post_init__(self) -> None:
        if not isinstance(self.anchors_, list):
            self.anchors_ = list(self.anchors_)

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        yield from self.anchors_

    def get_config(self) -> dict[str, Any]:
        return {"n_anchors": len(self.anchors_)}

geopatcher.spatial.sampler.ExplicitCoords dataclass

Bases: Sampler

Caller-supplied world coordinates, one centred chip per coordinate.

The coordinate analogue of spatial.sampler.Explicit (which passes backend-native anchors through untouched): each (x, y) is a world coordinate, optionally in a foreign crs, and the yielded anchor is the upper-left corner that centres the geometry's patch on the pixel that coordinate lands in — the same geo→pixel→centred-UL contract as spatial.sampler.AlongTrack. Coordinates outside the raster are skipped. On a PointDomain, the (reprojected) (x, y) is yielded directly. The coordinates are an unordered catalogue, so the antimeridian guard (which looks for consecutive steps across ±180°) does not apply.

Parameters:

Name Type Description Default
coords Any

Ordered (N, 2) array of (x, y) world coordinates, or any track-like object (GeoDataFrame / GeoSeries / LineString) spatial.sampler.AlongTrack accepts.

required
crs Any | None

CRS the coordinates are in. When set and different from domain.crs they are reprojected to the domain CRS before the pixel mapping. None (default) assumes the domain's CRS.

None
polar_guard Literal['warn', 'raise', 'ignore']

Same geographic-edge guard as spatial.sampler.AlongTrack.

'warn'

Centring convention: the coordinate's pixel lands at chip index (size_h // 2, size_w // 2), for odd and even sizes alike. georeader.read.read_from_center_coords instead rounds the continuous upper-left corner (round(px - size / 2), banker's rounding), so for an even size it can place the chip one pixel up/left of this one, depending on where in the pixel the coordinate falls.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class ExplicitCoords(Sampler):
    """Caller-supplied world coordinates, one centred chip per coordinate.

    The coordinate analogue of `spatial.sampler.Explicit` (which passes
    backend-native anchors through untouched): each ``(x, y)`` is a world
    coordinate, optionally in a foreign ``crs``, and the yielded anchor is
    the upper-left corner that **centres** the geometry's patch on the
    pixel that coordinate lands in — the same geo→pixel→centred-UL contract
    as `spatial.sampler.AlongTrack`. Coordinates outside the raster are skipped.
    On a `PointDomain`, the (reprojected) ``(x, y)`` is yielded directly.
    The coordinates are an unordered catalogue, so the antimeridian guard
    (which looks for consecutive steps across ±180°) does not apply.

    Args:
        coords: Ordered ``(N, 2)`` array of ``(x, y)`` world coordinates,
            or any track-like object (`GeoDataFrame` / `GeoSeries` /
            `LineString`) `spatial.sampler.AlongTrack` accepts.
        crs: CRS the coordinates are in. When set and different from
            ``domain.crs`` they are reprojected to the domain CRS before
            the pixel mapping. ``None`` (default) assumes the domain's CRS.
        polar_guard: Same geographic-edge guard as `spatial.sampler.AlongTrack`.

    Centring convention: the coordinate's pixel lands at chip index
    ``(size_h // 2, size_w // 2)``, for odd and even sizes alike.
    `georeader.read.read_from_center_coords` instead rounds the continuous
    upper-left corner (``round(px - size / 2)``, banker's rounding), so
    for an even size it can place the chip one pixel up/left of this
    one, depending on where in the pixel the coordinate falls.
    """

    coords: Any
    crs: Any | None = None
    polar_guard: Literal["warn", "raise", "ignore"] = "warn"

    def __post_init__(self) -> None:
        self.coords = _track_coords(self.coords)
        _validate_polar_guard(self.polar_guard)

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        points = self.coords
        if self.crs is not None:
            points = _to_domain_crs(
                points, self.crs, _domain_crs(domain), self.polar_guard, ordered=False
            )
        if _is_raster_domain(domain):
            yield from _raster_center_anchors(points, domain, geometry)
            return
        if isinstance(domain, PointDomain):
            for x, y in points:
                yield (float(x), float(y))
            return
        raise NotImplementedError(
            f"spatial.sampler.ExplicitCoords doesn't support {type(domain).__name__} "
            "domains."
        )

    def get_config(self) -> dict[str, Any]:
        return {
            **config_from_fields(self, exclude=("crs",)),
            "crs": None if self.crs is None else str(self.crs),
        }

geopatcher.spatial.sampler.AlongTrack dataclass

Bases: Sampler

Anchors along an ordered track, optionally resampled to fixed spacing.

The track is an ordered polyline of (x, y) coordinates in the domain's CRS (an altimetry ground track, a flight line, a ship transect, …). With spacing set, the track is resampled to points at a fixed along-track distance (linear interpolation along the cumulative Euclidean arc length, in coordinate units), always ending on the final vertex — the last interval is shorter when the track length is not a multiple of spacing; with spacing=None the original vertices are used as-is.

On a raster domain, each track point maps through the inverse affine to a pixel and the yielded anchor is the upper-left corner that centres the geometry's patch on that pixel; track points falling outside the raster are skipped, and (under the default "drop" boundary) anchors are clamped so the patch stays in-domain. On a PointDomain, the (x, y) coordinates themselves are yielded — ready for spatial.geometry.KNNGraph / spatial.geometry.RadiusGraph neighborhoods.

Parameters:

Name Type Description Default
track Any

Ordered (N, 2) array of (x, y) coordinates. Also accepts a geopandas.GeoDataFrame / GeoSeries of points or a shapely.LineString — anything exposing .geometry, .x / .y, or .coords.

required
spacing float | None

Along-track resampling distance in coordinate units, or None to anchor at the original vertices. Requires at least two distinct vertices when set.

None
crs Any | None

CRS the track coordinates are expressed in. When set and different from domain.crs, the track is reprojected to the domain CRS before anchoring; the spacing resample then runs in domain-CRS units. None (default) assumes the track is already in the domain's CRS (bit-identical to the old path).

None
polar_guard Literal['warn', 'raise', 'ignore']

Behaviour when a geographic crs places points beyond ±80° latitude or a track straddles the ±180° antimeridian — reprojection is unreliable there. "warn" (default) emits a RuntimeWarning, "raise" errors, "ignore" is silent.

'warn'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
@dataclass(eq=False)
class AlongTrack(Sampler):
    """Anchors along an ordered track, optionally resampled to fixed spacing.

    The track is an ordered polyline of ``(x, y)`` coordinates in the
    domain's CRS (an altimetry ground track, a flight line, a ship
    transect, …). With ``spacing`` set, the track is resampled to points
    at a fixed along-track distance (linear interpolation along the
    cumulative Euclidean arc length, in coordinate units), always ending
    on the final vertex — the last interval is shorter when the track
    length is not a multiple of ``spacing``; with ``spacing=None`` the
    original vertices are used as-is.

    On a raster domain, each track point maps through the inverse affine
    to a pixel and the yielded anchor is the upper-left corner that
    **centres** the geometry's patch on that pixel; track points falling
    outside the raster are skipped, and (under the default ``"drop"``
    boundary) anchors are clamped so the patch stays in-domain. On a
    `PointDomain`, the ``(x, y)`` coordinates themselves are yielded —
    ready for `spatial.geometry.KNNGraph` / `spatial.geometry.RadiusGraph`
    neighborhoods.

    Args:
        track: Ordered ``(N, 2)`` array of ``(x, y)`` coordinates. Also
            accepts a `geopandas.GeoDataFrame` / `GeoSeries` of points
            or a `shapely.LineString` — anything exposing ``.geometry``,
            ``.x`` / ``.y``, or ``.coords``.
        spacing: Along-track resampling distance in coordinate units, or
            ``None`` to anchor at the original vertices. Requires at
            least two distinct vertices when set.
        crs: CRS the ``track`` coordinates are expressed in. When set and
            different from ``domain.crs``, the track is reprojected to the
            domain CRS before anchoring; the ``spacing`` resample then runs
            in domain-CRS units. ``None`` (default) assumes the track is
            already in the domain's CRS (bit-identical to the old path).
        polar_guard: Behaviour when a *geographic* ``crs`` places points
            beyond ±80° latitude or a track straddles the ±180°
            antimeridian — reprojection is unreliable there. ``"warn"``
            (default) emits a `RuntimeWarning`, ``"raise"`` errors,
            ``"ignore"`` is silent.
    """

    track: Any
    spacing: float | None = None
    crs: Any | None = None
    polar_guard: Literal["warn", "raise", "ignore"] = "warn"

    def __post_init__(self) -> None:
        self.track = _track_coords(self.track)
        if self.spacing is not None and not (
            np.isfinite(self.spacing) and self.spacing > 0
        ):
            raise ValueError(f"spacing must be positive, got {self.spacing}")
        _validate_polar_guard(self.polar_guard)

    def anchors(self, domain: Any, geometry: SpatialGeometry) -> Iterator[Any]:
        track = self.track
        if self.crs is not None:
            track = _to_domain_crs(
                track, self.crs, _domain_crs(domain), self.polar_guard, ordered=True
            )
        points = self._resampled(track)
        if _is_raster_domain(domain):
            yield from _raster_center_anchors(points, domain, geometry)
            return
        if isinstance(domain, PointDomain):
            for x, y in points:
                yield (float(x), float(y))
            return
        raise NotImplementedError(
            f"spatial.sampler.AlongTrack doesn't support {type(domain).__name__} "
            "domains."
        )

    def _resampled(self, track: np.ndarray | None = None) -> np.ndarray:
        """Return track vertices, resampled to `spacing` when it is set."""
        pts = np.asarray(self.track if track is None else track, dtype=float)
        if self.spacing is None:
            return pts
        seg = np.linalg.norm(np.diff(pts, axis=0), axis=1)
        keep = seg > 0
        # Collapse zero-length segments so the arc-length axis is
        # strictly increasing for np.interp.
        pts = np.concatenate([pts[:1], pts[1:][keep]])
        if len(pts) < 2:
            raise ValueError(
                "spatial.sampler.AlongTrack with spacing needs at least two distinct "
                "track vertices."
            )
        dist = np.concatenate([[0.0], np.cumsum(seg[keep])])
        total = float(dist[-1])
        n_steps = int(np.floor(total / self.spacing + 1e-9))
        s = np.arange(n_steps + 1, dtype=float) * self.spacing
        if total - s[-1] > 1e-9 * max(total, 1.0):
            # Keep the final vertex: the track's end is a real anchor.
            s = np.append(s, total)
        return np.column_stack(
            [np.interp(s, dist, pts[:, 0]), np.interp(s, dist, pts[:, 1])]
        )

    def get_config(self) -> dict[str, Any]:
        return {
            **config_from_fields(self, exclude=("crs",)),
            "crs": None if self.crs is None else str(self.crs),
        }

geopatcher.spatial.sampler.IncompleteScanConfiguration

Bases: ValueError

A sampler's (size, step) does not exactly tile the domain.

Raised by spatial.sampler.RegularStride(check_full_scan=True) and by TemporalPatcher when its temporal.sampler.RegularStride(check_full_scan=True) windows leave time steps uncovered. A ValueError, so a plain except ValueError: catches it too.

Mirrors xrpatcher's exception of the same name so migration paths can keep their existing except IncompleteScanConfiguration: clauses unchanged.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/exceptions.py
class IncompleteScanConfiguration(ValueError):
    """A sampler's ``(size, step)`` does not exactly tile the domain.

    Raised by `spatial.sampler.RegularStride(check_full_scan=True)` and by
    `TemporalPatcher` when its `temporal.sampler.RegularStride(check_full_scan=True)`
    windows leave time steps uncovered. A `ValueError`, so a plain
    ``except ValueError:`` catches it too.

    Mirrors `xrpatcher`'s exception of the same name so migration paths
    can keep their existing ``except IncompleteScanConfiguration:``
    clauses unchanged.
    """

Window

geopatcher.spatial.window.Window

Base for window functions.

Subclasses implement weights(geometry) -> Array. The base class handles the trivial spatial.window.Boxcar default.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
class Window:
    """Base for window functions.

    Subclasses implement `weights(geometry) -> Array`. The base class
    handles the trivial `spatial.window.Boxcar` default.
    """

    forbid_in_yaml: ClassVar[bool] = False

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.spatial.window.Boxcar dataclass

Bases: Window

Constant 1.0 — no edge taper.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
@dataclass(eq=False)
class Boxcar(Window):
    """Constant 1.0 — no edge taper."""

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        shape = geom_shape(geometry)
        return np.ones(shape, dtype=np.float64)

geopatcher.spatial.window.Hann dataclass

Bases: Window

Hann (raised-cosine) window — the standard overlap-add taper.

Each axis of length n is sin²(π (k + 1/2) / n) for k = 0 .. n - 1: a periodic Hann sampled at the pixel centres. It is exactly COLA at hop n / 2: with an even patch size and step = size / 2 the windows of neighbouring chips sum to 1, so even un-normalised overlap-add reproduces a constant field across interior seams.

The window is symmetric and never 0 (the edge weight is sin²(π / 2n)), so merged with spatial.aggregation.OverlapAdd every covered pixel keeps its value — the scene's first row and column included — and step == size tiles reproduce the field exactly.

Example

from geopatcher import spatial w = spatial.window.Hann().weights( ... spatial.geometry.Rectangular(size=(4, 4)) ... ) # (4, 4) float64 bool((w > 0).all()) True

Axes shorter than 3 samples fall back to boxcar (all ones).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
@dataclass(eq=False)
class Hann(Window):
    """Hann (raised-cosine) window — the standard overlap-add taper.

    Each axis of length ``n`` is ``sin²(π (k + 1/2) / n)`` for
    ``k = 0 .. n - 1``: a periodic Hann sampled at the pixel centres. It is
    exactly COLA at hop ``n / 2``: with an even patch size and
    ``step = size / 2`` the windows of neighbouring chips sum to ``1``, so
    even un-normalised overlap-add reproduces a constant field across
    interior seams.

    The window is symmetric and never ``0`` (the edge weight is
    ``sin²(π / 2n)``), so merged with `spatial.aggregation.OverlapAdd` every
    covered pixel keeps its value — the scene's first row and column
    included — and ``step == size`` tiles reproduce the field exactly.

    Example:
        >>> from geopatcher import spatial
        >>> w = spatial.window.Hann().weights(
        ...     spatial.geometry.Rectangular(size=(4, 4))
        ... )  # (4, 4) float64
        >>> bool((w > 0).all())
        True

    Axes shorter than 3 samples fall back to boxcar (all ones).
    """

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        shape = geom_shape(geometry)
        return _separable(shape, lambda n: _tapered(n, lambda m: _tukey_1d(m, 1.0)))

geopatcher.spatial.window.Tukey dataclass

Bases: Window

Tukey (tapered-cosine) window.

Each axis of length n is a periodic Tukey of period n — cosine tapers over a fraction alpha of the window, flat in between — sampled at the pixel centres t = (k + 1/2) / n, the same convention as spatial.window.Hann: alpha = 1.0 is exactly spatial.window.Hann and alpha = 0.0 is exactly spatial.window.Boxcar. It is COLA at hop n * (1 - alpha / 2) (0.75 * n for the default alpha = 0.5); other hops still reconstruct correctly under spatial.aggregation.OverlapAdd's normalisation, just not as a partition of unity.

Like spatial.window.Hann it is symmetric and never 0, and axes shorter than 3 samples fall back to boxcar.

Parameters:

Name Type Description Default
alpha float

Fraction of the window occupied by the cosine taper (0.0 is spatial.window.Boxcar, 1.0 is spatial.window.Hann). Defaults to 0.5.

0.5
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
@dataclass(eq=False)
class Tukey(Window):
    """Tukey (tapered-cosine) window.

    Each axis of length ``n`` is a periodic Tukey of period ``n`` — cosine
    tapers over a fraction ``alpha`` of the window, flat in between —
    sampled at the pixel centres ``t = (k + 1/2) / n``, the same convention
    as `spatial.window.Hann`: ``alpha = 1.0`` is exactly `spatial.window.Hann`
    and ``alpha = 0.0`` is exactly `spatial.window.Boxcar`. It is COLA at hop
    ``n * (1 - alpha / 2)`` (``0.75 * n`` for the default ``alpha = 0.5``);
    other hops still reconstruct correctly under
    `spatial.aggregation.OverlapAdd`'s normalisation, just not as a partition of unity.

    Like `spatial.window.Hann` it is symmetric and never ``0``, and axes
    shorter than 3 samples fall back to boxcar.

    Args:
        alpha: Fraction of the window occupied by the cosine taper
            (``0.0`` is `spatial.window.Boxcar`, ``1.0`` is `spatial.window.Hann`).
            Defaults to ``0.5``.
    """

    alpha: float = 0.5

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        shape = geom_shape(geometry)
        return _separable(
            shape, lambda n: _tapered(n, lambda m: _tukey_1d(m, self.alpha))
        )

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.window.Gaussian dataclass

Bases: Window

Separable Gaussian envelope centred on the patch.

sigma is a fraction of the patch half-width, not a pixel count: along an axis of length n the standard deviation is sigma * n / 2 pixels, centred at (n - 1) / 2 (symmetric). The same value therefore gives geometrically similar tapers on different patch shapes; the default 0.5 puts the patch edge at about two standard deviations (edge weight ≈ exp(-2) ≈ 0.14 for large patches). The weights never reach zero, so a Gaussian has no zero-weight border ring, but it is not a partition of unity — rely on spatial.aggregation.OverlapAdd's normalisation.

Parameters:

Name Type Description Default
sigma float

Standard deviation as a fraction of the half-width. Defaults to 0.5.

0.5
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
@dataclass(eq=False)
class Gaussian(Window):
    """Separable Gaussian envelope centred on the patch.

    ``sigma`` is a **fraction of the patch half-width**, not a pixel
    count: along an axis of length ``n`` the standard deviation is
    ``sigma * n / 2`` pixels, centred at ``(n - 1) / 2`` (symmetric). The
    same value therefore gives geometrically similar tapers on different
    patch shapes; the default ``0.5`` puts the patch edge at about two
    standard deviations (edge weight ``≈ exp(-2) ≈ 0.14`` for large patches).
    The weights never reach zero, so a Gaussian has no zero-weight border
    ring, but it is not a partition of unity — rely on
    `spatial.aggregation.OverlapAdd`'s normalisation.

    Args:
        sigma: Standard deviation as a fraction of the half-width.
            Defaults to ``0.5``.
    """

    sigma: float = 0.5

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        shape = geom_shape(geometry)
        return _separable(shape, lambda n: _gaussian_1d(n, self.sigma))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.window.Custom dataclass

Bases: Window

Caller-supplied weight function — the escape hatch.

Parameters:

Name Type Description Default
fn Callable[[Geometry], ndarray]

Callable (geometry) -> np.ndarray returning the weight array. Carries closures, so forbid_in_yaml = True.

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
@dataclass(eq=False)
class Custom(Window):
    """Caller-supplied weight function — the escape hatch.

    Args:
        fn: Callable ``(geometry) -> np.ndarray`` returning the weight
            array. Carries closures, so ``forbid_in_yaml = True``.
    """

    fn: Callable[[SpatialGeometry], np.ndarray]

    forbid_in_yaml: ClassVar[bool] = True

    def weights(self, geometry: SpatialGeometry) -> np.ndarray:
        return self.fn(geometry)

geopatcher.spatial.window.geom_shape(geometry)

Shape of the weight array a spatial.window.Window returns for geometry.

Public so third-party windows (e.g. geoops.patch_ops.TriangularWindow) size their weights exactly like the built-in ones.

Parameters:

Name Type Description Default
geometry Geometry

A fixed-size geometry — spatial.geometry.Rectangular, or any object exposing a size sequence.

required

Returns:

Type Description
tuple[int, ...]

size with every entry coerced to int.

Raises:

Type Description
TypeError

if the geometry has no fixed size (ragged geometries).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
def geom_shape(geometry: SpatialGeometry) -> tuple[int, ...]:
    """Shape of the weight array a `spatial.window.Window` returns for ``geometry``.

    Public so third-party windows (e.g. ``geoops.patch_ops.TriangularWindow``)
    size their weights exactly like the built-in ones.

    Args:
        geometry: A fixed-size geometry — `spatial.geometry.Rectangular`, or any
            object exposing a ``size`` sequence.

    Returns:
        ``size`` with every entry coerced to ``int``.

    Raises:
        TypeError: if the geometry has no fixed size (ragged geometries).
    """
    if isinstance(geometry, SpatialRectangular):
        return tuple(int(s) for s in geometry.size)
    size = getattr(geometry, "size", None)
    if size is not None:
        return tuple(int(s) for s in size)
    raise TypeError(
        f"spatial.window.Window weights aren't defined for {type(geometry).__name__} - "
        "only fixed-shape geometries (e.g. spatial.geometry.Rectangular). Use "
        "spatial.window.Boxcar for ragged geometries like "
        "spatial.geometry.RadiusGraph / spatial.geometry.KNNGraph / "
        "spatial.geometry.PolygonIntersection."
    )

Aggregation

geopatcher.spatial.aggregation.Aggregation

Base for local → global merging strategies.

Subclasses implement merge(patches, domain) -> field-like.

streaming_safe = True means the aggregation can be reduced one patch at a time without keeping per-cell history; the disk-backed spatial.aggregation.OverlapAdd(streaming=True, target_path=...) path lights up automatically for these.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
class Aggregation:
    """Base for local → global merging strategies.

    Subclasses implement ``merge(patches, domain) -> field-like``.

    ``streaming_safe = True`` means the aggregation can be reduced one
    patch at a time without keeping per-cell history; the disk-backed
    `spatial.aggregation.OverlapAdd(streaming=True, target_path=...)` path lights up
    automatically for these.
    """

    streaming_safe: ClassVar[bool] = False
    forbid_in_yaml: ClassVar[bool] = False

    def merge(self, patches: Iterable[Any], domain: Any) -> Any:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.spatial.aggregation.Sum dataclass

Bases: Aggregation

Per-cell sum across patches (NaN / masked samples skipped).

Parameters:

Name Type Description Default
fill_value float

Written into cells no valid sample reached (uncovered, all-NaN or outside every mask). Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Sum(Aggregation):
    """Per-cell sum across patches (NaN / masked samples skipped).

    Args:
        fill_value: Written into cells no valid sample reached
            (uncovered, all-NaN or outside every mask). Default NaN;
            pass e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        acc = np.zeros(shape, dtype=np.float64)
        covered = np.zeros(shape, dtype=bool)
        for p in patches:
            placed = _placed(p, shape)
            if placed is None:
                continue
            pl, x = placed
            valid = pl.valid(x)
            acc[pl.acc] += np.where(valid, x, 0.0)
            covered[pl.acc] |= valid
        return _with_fill(acc, covered, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Mean dataclass

Bases: Aggregation

Per-cell mean — runs spatial.aggregation.Sum and a count accumulator in parallel.

NaN samples and cells outside a _MaskedWindow mask are not counted.

Parameters:

Name Type Description Default
fill_value float

Written into cells no valid sample reached. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Mean(Aggregation):
    """Per-cell mean — runs `spatial.aggregation.Sum` and a count accumulator in
    parallel.

    NaN samples and cells outside a `_MaskedWindow` mask are not counted.

    Args:
        fill_value: Written into cells no valid sample reached. Default
            NaN; pass e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        total = np.zeros(shape, dtype=np.float64)
        count = np.zeros(shape, dtype=np.float64)
        for p in patches:
            placed = _placed(p, shape)
            if placed is None:
                continue
            pl, x = placed
            valid = pl.valid(x)
            total[pl.acc] += np.where(valid, x, 0.0)
            count[pl.acc] += valid
        with np.errstate(invalid="ignore", divide="ignore"):
            return _with_fill(total / count, count > 0, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Variance dataclass

Bases: Aggregation

Per-cell sample variance via Welford's online algorithm.

Returns the unbiased estimate (ddof=1, as np.nanvar); NaN and masked samples are not counted.

Parameters:

Name Type Description Default
fill_value float

Written into cells with fewer than two valid samples, where the ddof=1 variance is undefined. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Variance(Aggregation):
    """Per-cell sample variance via Welford's online algorithm.

    Returns the unbiased estimate (``ddof=1``, as ``np.nanvar``); NaN and
    masked samples are not counted.

    Args:
        fill_value: Written into cells with fewer than two valid samples,
            where the ``ddof=1`` variance is undefined. Default NaN; pass
            e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        mean = np.zeros(shape, dtype=np.float64)
        m2 = np.zeros(shape, dtype=np.float64)
        count = np.zeros(shape, dtype=np.float64)
        for p in patches:
            placed = _placed(p, shape)
            if placed is None:
                continue
            pl, x = placed
            sl = pl.acc
            valid = pl.valid(x)
            x_clean = np.where(valid, x, 0.0)
            next_count = count[sl] + valid
            delta = np.where(valid, x_clean - mean[sl], 0.0)
            denom = np.where(next_count > 0, next_count, 1.0)
            mean[sl] += np.where(next_count > 0, delta / denom, 0.0)
            m2[sl] += np.where(valid, delta * (x_clean - mean[sl]), 0.0)
            count[sl] = next_count
        with np.errstate(invalid="ignore", divide="ignore"):
            return _with_fill(m2 / (count - 1), count > 1, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.OverlapAdd dataclass

Bases: Aggregation

spatial.window.Window-weighted overlap-add — the canonical chip-stitching aggregator.

Computes Σ wᵢ xᵢ / Σ wᵢ per cell. When stride < patch size and a spatial.window.Hann (or similar partition-of-unity) window is used, the resulting field equals the original (modulo the operator's effect) — the standard inference-time stitching pattern.

With streaming=True and a target_path the two accumulators live in a chunked on-disk zarr store instead of RAM: each patch is a read-modify-write of the blocks it touches, and the final normalisation runs block by block, so peak memory is one patch plus one block — never the whole field.

Parameters:

Name Type Description Default
streaming bool

If True and target_path is set, accumulate on disk (see writer) rather than in RAM.

False
target_path str | None

With writer="zarr", the directory holding the rec.zarr (result) and wsum.zarr (accumulated weight) arrays; with writer="cog", the output GeoTIFF path.

None
chunks tuple[int, ...] | None

Zarr chunk shape of the streaming accumulators — required for writer="zarr"; pass the patch geometry's size (e.g. chunks=geometry.size) so each patch writes whole blocks. Right-aligned against the domain shape: leading band / time dims missing from it get their full extent. With writer="cog" it defaults to the COG block size.

None
shard_shape tuple[int, ...] | None

Optional zarr v3 shard shape (right-aligned like chunks).

None
writer str

"zarr" (default) returns the result zarr.Array; "cog" streams through a temporary zarr store and converts it, block by block, into a Cloud-Optimized GeoTIFF (GDAL COG driver: tiled, overviews, nodata = fill_value), returning target_path.

'zarr'
cog dict[str, Any] | None

writer="cog" options — blocksize (default 512), compress (default "DEFLATE"), bigtiff (default "IF_SAFER"); any other key is forwarded upper-cased as a GDAL COG creation option (e.g. overview_resampling).

None
normalize_by_window bool

Divide by the accumulated weight at the end (default True). Set to False for the raw weighted sum.

True
fill_value float

Written into cells whose accumulated weight of valid samples is zero — uncovered, all-NaN, or outside every mask. Default NaN; pass e.g. the domain's nodata to override. It is also the COG's nodata.

nan
dtype str

Floating dtype of the streaming accumulators and output (default "float32"). The in-RAM path is float64.

'float32'
overwrite bool

Replace an existing store / file at target_path. Default False: a second merge onto the same path raises FileExistsError instead of silently destroying the first.

False
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class OverlapAdd(Aggregation):
    """spatial.window.Window-weighted overlap-add — the canonical chip-stitching
    aggregator.

    Computes ``Σ wᵢ xᵢ / Σ wᵢ`` per cell. When stride < patch size and a
    `spatial.window.Hann` (or similar partition-of-unity) window is used, the resulting
    field equals the original (modulo the operator's effect) — the
    standard inference-time stitching pattern.

    With ``streaming=True`` and a ``target_path`` the two accumulators
    live in a chunked on-disk zarr store instead of RAM: each patch is a
    read-modify-write of the blocks it touches, and the final
    normalisation runs block by block, so peak memory is one patch plus
    one block — never the whole field.

    Args:
        streaming: If ``True`` and ``target_path`` is set, accumulate
            on disk (see ``writer``) rather than in RAM.
        target_path: With ``writer="zarr"``, the directory holding the
            ``rec.zarr`` (result) and ``wsum.zarr`` (accumulated weight)
            arrays; with ``writer="cog"``, the output GeoTIFF path.
        chunks: Zarr chunk shape of the streaming accumulators — required
            for ``writer="zarr"``; pass the patch geometry's size (e.g.
            ``chunks=geometry.size``) so each patch writes whole blocks.
            Right-aligned against the domain shape: leading band / time
            dims missing from it get their full extent. With
            ``writer="cog"`` it defaults to the COG block size.
        shard_shape: Optional zarr v3 shard shape (right-aligned like
            ``chunks``).
        writer: ``"zarr"`` (default) returns the result ``zarr.Array``;
            ``"cog"`` streams through a temporary zarr store and converts
            it, block by block, into a Cloud-Optimized GeoTIFF (GDAL
            ``COG`` driver: tiled, overviews, ``nodata = fill_value``),
            returning ``target_path``.
        cog: ``writer="cog"`` options — ``blocksize`` (default 512),
            ``compress`` (default ``"DEFLATE"``), ``bigtiff`` (default
            ``"IF_SAFER"``); any other key is forwarded upper-cased as a
            GDAL COG creation option (e.g. ``overview_resampling``).
        normalize_by_window: Divide by the accumulated weight at the end
            (default ``True``). Set to ``False`` for the raw weighted
            sum.
        fill_value: Written into cells whose accumulated weight of valid
            samples is zero — uncovered, all-NaN, or outside every mask.
            Default NaN; pass e.g. the
            domain's nodata to override. It is also the COG's nodata.
        dtype: Floating dtype of the streaming accumulators and output
            (default ``"float32"``). The in-RAM path is float64.
        overwrite: Replace an existing store / file at ``target_path``.
            Default ``False``: a second merge onto the same path raises
            `FileExistsError` instead of silently destroying the first.
    """

    streaming: bool = False
    target_path: str | None = None
    chunks: tuple[int, ...] | None = None
    shard_shape: tuple[int, ...] | None = None
    writer: str = "zarr"
    cog: dict[str, Any] | None = None
    normalize_by_window: bool = True
    fill_value: float = math.nan
    dtype: str = "float32"
    overwrite: bool = False

    streaming_safe: ClassVar[bool] = True

    def __post_init__(self) -> None:
        if self.writer not in (ZARR_WRITER, COG_WRITER):
            raise ValueError(
                f"writer must be {ZARR_WRITER!r} or {COG_WRITER!r}, got {self.writer!r}"
            )
        if not np.issubdtype(np.dtype(self.dtype), np.floating):
            raise ValueError(
                f"dtype must be a floating dtype to hold the fill, got {self.dtype!r}"
            )

    def merge(self, patches: Iterable[Any], domain: Any) -> Any:
        if not (self.streaming and self.target_path):
            return self._merge_in_memory(patches, domain)
        if self.writer == COG_WRITER:
            return self._merge_cog(patches, domain, self.target_path)
        if self.chunks is None:
            raise ValueError(
                "spatial.aggregation.OverlapAdd(streaming=True) needs chunks= — pass "
                "the "
                "patch geometry's size (e.g. chunks=geometry.size) so each "
                "patch writes whole blocks"
            )
        return self._merge_streaming(patches, domain, self.target_path, self.chunks)

    def _merge_in_memory(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        acc = np.zeros(shape, dtype=np.float64)
        wsum = np.zeros(shape, dtype=np.float64)
        for p in patches:
            pl = _resolve_indices(p.indices, shape)
            if pl is None:
                continue
            contrib, weight = _weighted_block(pl, p, np.float64, len(shape))
            acc[pl.acc] += contrib
            wsum[pl.acc] += weight
        out = acc
        if self.normalize_by_window:
            with np.errstate(invalid="ignore", divide="ignore"):
                out = acc / wsum
        return _with_fill(out, wsum > 0, self.fill_value)

    def _merge_streaming(
        self,
        patches: Iterable[Any],
        domain: Any,
        root: str,
        chunks: tuple[int, ...],
        *,
        overwrite: bool | None = None,
        layout: tuple[tuple[int, ...], Iterator[Any]] | None = None,
    ) -> Any:
        shape, patches = layout or _dense_layout(patches, domain)
        chunks = _right_align(chunks, shape, "chunks")
        shards = (
            None
            if self.shard_shape is None
            else _right_align(self.shard_shape, shape, "shard_shape")
        )
        replace = self.overwrite if overwrite is None else overwrite
        dtype = np.dtype(self.dtype)
        rec, wsum = (
            _open_zarr_array(
                f"{root}/{name}.zarr",
                shape=shape,
                chunks=chunks,
                dtype=dtype,
                shard_shape=shards,
                overwrite=replace,
            )
            for name in ("rec", "wsum")
        )
        for p in patches:
            pl = _resolve_indices(p.indices, shape)
            if pl is None:
                continue
            contrib, weight = _weighted_block(pl, p, dtype.type, len(shape))
            rec[pl.acc] = np.asarray(rec[pl.acc]) + contrib
            wsum[pl.acc] = np.asarray(wsum[pl.acc]) + weight
        # Normalise block by block (one shard, or one chunk, at a time) so
        # the final pass never loads a full-domain accumulator.
        for blk in _blocks(shape, shards or chunks):
            weight = np.asarray(wsum[blk])
            out = np.asarray(rec[blk])
            if self.normalize_by_window:
                with np.errstate(invalid="ignore", divide="ignore"):
                    out = out / weight
            rec[blk] = _with_fill(out, weight > 0, self.fill_value)
        return rec

    def _merge_cog(self, patches: Iterable[Any], domain: Any, target: str) -> str:
        import os
        import tempfile

        if os.path.exists(target) and not self.overwrite:
            raise FileExistsError(
                f"{target} already exists; pass overwrite=True to replace it"
            )
        options = dict(self.cog or {})
        blocksize = int(options.pop("blocksize", DEFAULT_COG_BLOCKSIZE))
        layout = _dense_layout(patches, domain)
        shape = layout[0]
        if len(shape) not in (2, 3):
            raise ValueError(
                "COG writer expects a 2-D or a 3-D band-first output; the "
                f"patches merge into shape {shape}"
            )
        chunks = self.chunks or tuple(min(blocksize, n) for n in shape[-2:])
        parent = os.path.dirname(os.path.abspath(target))
        os.makedirs(parent, exist_ok=True)  # as the zarr writer does
        with tempfile.TemporaryDirectory(dir=parent, prefix=".geopatcher-") as tmp:
            rec = self._merge_streaming(
                patches, domain, tmp, chunks, overwrite=True, layout=layout
            )
            _zarr_to_cog(
                rec,
                domain,
                target,
                blocksize=blocksize,
                fill_value=self.fill_value,
                scratch=os.path.join(tmp, "stage.tif"),
                options=options,
            )
        return target

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.WeightedSum dataclass

Bases: Aggregation

Per-cell weighted sum — each patch's window weights multiply in.

Parameters:

Name Type Description Default
weight_fn Callable[[Any], ndarray] | None

Optional callable (patch) -> Array overriding the per-patch weights. None uses patch.weights directly.

None
fill_value float

Written into cells whose accumulated weight of valid samples is not positive (uncovered, all-NaN, outside every mask, or a taper's zero edge). Default NaN; pass e.g. the domain's nodata to override.

nan
Note

With a weight_fn the instance is forbid_in_yaml: the callable has no JSON form, so get_config() records only its name, a debug record that from_config refuses to rebuild. Without one the config rebuilds the aggregation.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class WeightedSum(Aggregation):
    """Per-cell weighted sum — each patch's window weights multiply in.

    Args:
        weight_fn: Optional callable ``(patch) -> Array`` overriding the
            per-patch weights. ``None`` uses ``patch.weights`` directly.
        fill_value: Written into cells whose accumulated weight of valid
            samples is not positive (uncovered, all-NaN, outside every
            mask, or a taper's zero edge). Default NaN; pass e.g. the
            domain's nodata to override.

    Note:
        With a ``weight_fn`` the instance is ``forbid_in_yaml``: the
        callable has no JSON form, so ``get_config()`` records only its
        name, a debug record that `from_config` refuses to rebuild.
        Without one the config rebuilds the aggregation.
    """

    weight_fn: Callable[[Any], np.ndarray] | None = None
    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def __post_init__(self) -> None:
        if self.weight_fn is None:
            return
        if not callable(self.weight_fn):
            raise TypeError(
                "spatial.aggregation.WeightedSum.weight_fn must be a callable or "
                "None, got "
                f"{self.weight_fn!r} — a config naming a weight_fn cannot be "
                "rebuilt; construct it in code."
            )
        # Per-instance flag (shadowing the ClassVar): only a weight_fn makes
        # the config unfaithful, so `spatial.aggregation.WeightedSum()` stays
        # rebuildable.
        object.__setattr__(self, "forbid_in_yaml", True)

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        acc = np.zeros(shape, dtype=np.float64)
        wsum = np.zeros(shape, dtype=np.float64)
        for p in patches:
            placed = _placed(p, shape)
            if placed is None:
                continue
            pl, x = placed
            raw_w = self.weight_fn(p) if self.weight_fn else p.weights
            w = np.float64(1.0) if raw_w is None else _as_float(pl.crop(raw_w))
            valid = pl.valid(x)
            acc[pl.acc] += np.where(valid, x * w, 0.0)
            wsum[pl.acc] += np.where(valid, w, 0.0)
        return _with_fill(acc, wsum > 0, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        fn = self.weight_fn
        return {
            "weight_fn": None if fn is None else getattr(fn, "__name__", repr(fn)),
            **config_from_fields(self, exclude=("weight_fn",)),
        }

geopatcher.spatial.aggregation.InvVarWeightedMean dataclass

Bases: Aggregation

Bayesian inverse-variance weighting for overlapping local posteriors.

Each patch produces (mu, var) — i.e. patch.data is a tuple or a dict with "mu" / "var" keys. Returns a dict {"mu": global_mu, "var": global_var} with Kalman-optimal combination::

μ_global = Σ wᵢ μᵢ / σᵢ² / Σ wᵢ / σᵢ²
σ²_global = 1 / Σ wᵢ / σᵢ²

A sample with var == 0 is exact: it has infinite precision, so a cell with any such sample takes the (w-weighted mean of the) exact mu and var = 0. Samples with NaN mu / var, negative var, non-positive weight or outside a _MaskedWindow mask are skipped.

Parameters:

Name Type Description Default
fill_value float

Written into both mu and var of cells no valid sample reached. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class InvVarWeightedMean(Aggregation):
    """Bayesian inverse-variance weighting for overlapping local posteriors.

    Each patch produces ``(mu, var)`` — i.e. ``patch.data`` is a tuple or
    a dict with ``"mu"`` / ``"var"`` keys. Returns a dict ``{"mu":
    global_mu, "var": global_var}`` with Kalman-optimal combination::

        μ_global = Σ wᵢ μᵢ / σᵢ² / Σ wᵢ / σᵢ²
        σ²_global = 1 / Σ wᵢ / σᵢ²

    A sample with ``var == 0`` is exact: it has infinite precision, so a
    cell with any such sample takes the (``w``-weighted mean of the) exact
    ``mu`` and ``var = 0``. Samples with NaN ``mu`` / ``var``, negative
    ``var``, non-positive weight or outside a `_MaskedWindow` mask are
    skipped.

    Args:
        fill_value: Written into both ``mu`` and ``var`` of cells no valid
            sample reached. Default NaN; pass e.g. the domain's nodata to
            override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> dict[str, np.ndarray]:
        shape, patches = _dense_layout(
            patches, domain, lambda data: np.shape(_unpack_mu_var(data)[0])
        )
        mu_acc = np.zeros(shape, dtype=np.float64)
        prec = np.zeros(shape, dtype=np.float64)
        exact_mu = np.zeros(shape, dtype=np.float64)
        exact_w = np.zeros(shape, dtype=np.float64)
        for p in patches:
            pl = _resolve_indices(p.indices, shape)
            if pl is None:
                continue
            mu, var = (_as_float(pl.crop(part)) for part in _unpack_mu_var(p.data))
            w = (
                _as_float(pl.crop(p.weights))
                if p.weights is not None
                else np.ones_like(mu)
            )
            ok = pl.valid(mu) & _not_nan(var) & (w > 0)
            exact = ok & (var == 0)
            regular = ok & (var > 0)
            inv_var = np.divide(
                w, var, out=np.zeros(np.broadcast(w, var).shape), where=regular
            )
            mu_acc[pl.acc] += np.where(regular, inv_var * mu, 0.0)
            prec[pl.acc] += inv_var
            exact_mu[pl.acc] += np.where(exact, w * mu, 0.0)
            exact_w[pl.acc] += np.where(exact, w, 0.0)
        is_exact = exact_w > 0
        with np.errstate(invalid="ignore", divide="ignore"):
            mu_g = np.where(is_exact, exact_mu / exact_w, mu_acc / prec)
            var_g = np.where(is_exact, 0.0, 1.0 / prec)
        covered = is_exact | (prec > 0)
        return {
            "mu": _with_fill(mu_g, covered, self.fill_value),
            "var": _with_fill(var_g, covered, self.fill_value),
        }

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Max dataclass

Bases: Aggregation

Per-cell maximum across patches (NaN / masked samples skipped).

Parameters:

Name Type Description Default
fill_value float

Written into cells no valid sample reached. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Max(Aggregation):
    """Per-cell maximum across patches (NaN / masked samples skipped).

    Args:
        fill_value: Written into cells no valid sample reached. Default
            NaN; pass e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        return _extreme(patches, domain, np.fmax, -np.inf, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Min dataclass

Bases: Aggregation

Per-cell minimum across patches (NaN / masked samples skipped).

Parameters:

Name Type Description Default
fill_value float

Written into cells no valid sample reached. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Min(Aggregation):
    """Per-cell minimum across patches (NaN / masked samples skipped).

    Args:
        fill_value: Written into cells no valid sample reached. Default
            NaN; pass e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        return _extreme(patches, domain, np.fmin, np.inf, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.MeanStd dataclass

Bases: Aggregation

Global mean and sample standard deviation across patch data.

NaN samples are skipped. On a dense (raster / grid) domain only each chip's in-domain, in-mask part counts, so pad / reflect fill is not data; on other domains every non-NaN sample counts.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class MeanStd(Aggregation):
    """Global mean and sample standard deviation across patch data.

    NaN samples are skipped. On a dense (raster / grid) domain only each
    chip's in-domain, in-mask part counts, so pad / reflect fill is not
    data; on other domains every non-NaN sample counts.
    """

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> dict[str, float]:
        shape = _dense_shape_or_none(domain)
        count = 0
        mean = 0.0
        m2 = 0.0
        for p in patches:
            x = _global_values(p, shape)
            if x.size == 0:
                continue
            batch_count = int(x.size)
            batch_mean = float(np.mean(x))
            batch_m2 = float(np.sum((x - batch_mean) ** 2))
            next_count = count + batch_count
            delta = batch_mean - mean
            m2 += batch_m2 + delta * delta * count * batch_count / next_count
            mean += delta * batch_count / next_count
            count = next_count
        if count == 0:
            raise ValueError("spatial.aggregation.MeanStd requires at least one value")
        var = m2 / (count - 1) if count > 1 else 0.0
        return {"mean": mean, "std": float(np.sqrt(var))}

geopatcher.spatial.aggregation.MinMax dataclass

Bases: Aggregation

Global minimum and maximum across patch data.

NaN samples are skipped. On a dense (raster / grid) domain only each chip's in-domain, in-mask part counts.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class MinMax(Aggregation):
    """Global minimum and maximum across patch data.

    NaN samples are skipped. On a dense (raster / grid) domain only each
    chip's in-domain, in-mask part counts.
    """

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> dict[str, float]:
        shape = _dense_shape_or_none(domain)
        min_value = np.inf
        max_value = -np.inf
        seen = False
        for p in patches:
            x = _global_values(p, shape)
            if x.size == 0:
                continue
            min_value = min(min_value, float(np.min(x)))
            max_value = max(max_value, float(np.max(x)))
            seen = True
        if not seen:
            raise ValueError("spatial.aggregation.MinMax requires at least one value")
        return {"min": min_value, "max": max_value}

geopatcher.spatial.aggregation.HardVote dataclass

Bases: Aggregation

Per-cell majority vote — patches carry integer class predictions.

Values outside [0, n_classes), NaN and samples outside a _MaskedWindow mask cast no vote. Ties go to the lowest class index (np.argmax).

Parameters:

Name Type Description Default
n_classes int

Total number of classes K. Accumulator shape is (K, *domain_shape).

required
fill_value int | float

Label of cells that received no vote. Default -1 (never a class); the output is int64 for an integral fill and float64 otherwise (e.g. fill_value=float("nan")).

-1
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class HardVote(Aggregation):
    """Per-cell majority vote — patches carry integer class predictions.

    Values outside ``[0, n_classes)``, NaN and samples outside a
    `_MaskedWindow` mask cast no vote. **Ties** go to the lowest class
    index (``np.argmax``).

    Args:
        n_classes: Total number of classes ``K``. Accumulator shape is
            ``(K, *domain_shape)``.
        fill_value: Label of cells that received no vote. Default ``-1``
            (never a class); the output is ``int64`` for an integral fill
            and ``float64`` otherwise (e.g. ``fill_value=float("nan")``).
    """

    n_classes: int
    fill_value: int | float = -1

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        votes = np.zeros((self.n_classes, *shape), dtype=np.int64)
        for p in patches:
            placed = _placed(p, shape)
            if placed is None:
                continue
            pl, x = placed
            valid = pl.valid(x) & np.isfinite(x)
            cls = np.where(valid, x, -1).astype(np.int64)
            for k in range(self.n_classes):
                votes[k][pl.acc] += cls == k
        out = _with_fill(np.argmax(votes, axis=0), votes.any(axis=0), self.fill_value)
        return out.astype(_label_dtype(self.fill_value))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.SoftVote dataclass

Bases: Aggregation

Per-cell soft vote — patches carry per-class probabilities.

Each patch's data has shape (n_classes, ...): the class axis first, then the cell axes. The per-class probabilities accumulate and the argmax across the class axis is returned, on the cell axes the patches carry — (K, h, w) probabilities on a (band, H, W) domain give an (H, W) label map. A cell counts only where none of its class probabilities is NaN and it lies inside a _MaskedWindow mask. Ties go to the lowest class index.

Parameters:

Name Type Description Default
n_classes int

Total number of classes K.

required
fill_value int | float

Label of cells no valid probability reached. Default -1; the output is int64 for an integral fill and float64 otherwise.

-1
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class SoftVote(Aggregation):
    """Per-cell soft vote — patches carry per-class probabilities.

    Each patch's data has shape ``(n_classes, ...)``: the class axis
    first, then the cell axes. The per-class probabilities accumulate and
    the argmax across the class axis is returned, on the cell axes the
    patches carry — ``(K, h, w)`` probabilities on a ``(band, H, W)``
    domain give an ``(H, W)`` label map. A cell counts only
    where none of its class probabilities is NaN and it lies inside a
    `_MaskedWindow` mask. **Ties** go to the lowest class index.

    Args:
        n_classes: Total number of classes ``K``.
        fill_value: Label of cells no valid probability reached. Default
            ``-1``; the output is ``int64`` for an integral fill and
            ``float64`` otherwise.
    """

    n_classes: int
    fill_value: int | float = -1

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain, lambda data: np.shape(data)[1:])
        acc = np.zeros((self.n_classes, *shape), dtype=np.float64)
        covered = np.zeros(shape, dtype=bool)
        for p in patches:
            pl = _resolve_indices(p.indices, shape)
            if pl is None:
                continue
            probs = _as_float(p.data)
            # (K, h, w) on an N-D domain → (K, 1, …, 1, h, w): the class
            # axis stays first and the cell axes stay trailing.
            missing = len(shape) - (probs.ndim - 1)
            if missing > 0:
                probs = probs.reshape(
                    (probs.shape[0], *([1] * missing), *probs.shape[1:])
                )
            # The leading class axis is kept whole on both sides.
            probs = probs[(slice(None), *pl.chip)]
            cell_ok = pl.valid(probs).all(axis=0)
            acc[(slice(None), *pl.acc)] += np.where(cell_ok, probs, 0.0)
            covered[pl.acc] |= cell_ok
        out = _with_fill(np.argmax(acc, axis=0), covered, self.fill_value)
        return out.astype(_label_dtype(self.fill_value))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.ByIndex dataclass

Bases: Aggregation

Don't merge — return the [(anchor, data), …] pairs in patch order.

The natural choice for ragged geometries (spatial.geometry.RadiusGraph, spatial.geometry.KNNGraph, spatial.geometry.PolygonIntersection) where the per-patch outputs aren't laid out on a regular grid. A list of pairs rather than a dict: GridDomain anchors are dicts and graph / array anchors are numpy arrays (both unhashable), and two patches may share an anchor — the same convention as SpatioTemporalPatcher.merge. Build dict(out) yourself when the anchors are hashable and unique.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class ByIndex(Aggregation):
    """Don't merge — return the ``[(anchor, data), …]`` pairs in patch order.

    The natural choice for ragged geometries (`spatial.geometry.RadiusGraph`,
    `spatial.geometry.KNNGraph`, `spatial.geometry.PolygonIntersection`) where the
    per-patch
    outputs aren't laid out on a regular grid. A list of pairs rather
    than a ``dict``: `GridDomain` anchors are ``dict``s and graph / array
    anchors are numpy arrays (both unhashable), and two patches may share
    an anchor — the same convention as `SpatioTemporalPatcher.merge`.
    Build ``dict(out)`` yourself when the anchors are hashable and unique.
    """

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> list[tuple[Any, Any]]:
        return [(p.anchor, p.data) for p in patches]

geopatcher.spatial.aggregation.Median dataclass

Bases: Aggregation

Per-cell median — exact, requires per-cell history.

NaN and masked samples are skipped. The per-cell history is a stack as deep as the largest overlap (not one full-domain layer per patch).

streaming_safe = False and there is no streamable per-cell substitute. spatial.aggregation.ApproxQuantile(q=0.5) is not one: it is a global sketch returning one scalar for the whole field.

Parameters:

Name Type Description Default
fill_value float

Written into cells no valid sample reached. Default NaN; pass e.g. the domain's nodata to override.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Median(Aggregation):
    """Per-cell median — exact, requires per-cell history.

    NaN and masked samples are skipped. The per-cell history is a stack
    as deep as the largest overlap (not one full-domain layer per patch).

    ``streaming_safe = False`` and there is no streamable per-cell
    substitute. ``spatial.aggregation.ApproxQuantile(q=0.5)`` is *not* one: it is a
    global sketch returning one scalar for the whole field.

    Args:
        fill_value: Written into cells no valid sample reached. Default
            NaN; pass e.g. the domain's nodata to override.
    """

    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = False

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        stack, count = _overlap_stack(patches, shape)
        if stack.shape[0] == 0:
            return np.full(shape, self.fill_value, dtype=np.float64)
        with warnings.catch_warnings():
            # Uncovered cells are an all-NaN column; they get the fill below.
            warnings.simplefilter("ignore", RuntimeWarning)
            median = np.nanmedian(stack, axis=0)
        return _with_fill(median, count > 0, self.fill_value)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Mode dataclass

Bases: Aggregation

Per-cell exact mode — not streamable. Use spatial.aggregation.HardVote for streaming.

NaN and masked samples are skipped. Ties go to the smallest value. The per-cell history is a stack as deep as the largest overlap, and the mode is computed vectorised over it.

Parameters:

Name Type Description Default
fill_value int | float

Written into cells no valid sample reached. Default NaN, so the output is float64; an integral fill (e.g. -1) makes it int64 — values are then truncated to integers, which suits the class labels a mode is meant for.

nan
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Mode(Aggregation):
    """Per-cell exact mode — not streamable. Use `spatial.aggregation.HardVote` for
    streaming.

    NaN and masked samples are skipped. **Ties** go to the smallest
    value. The per-cell history is a stack as deep as the largest
    overlap, and the mode is computed vectorised over it.

    Args:
        fill_value: Written into cells no valid sample reached. Default
            NaN, so the output is float64; an integral fill (e.g. ``-1``)
            makes it ``int64`` — values are then truncated to integers,
            which suits the class labels a mode is meant for.
    """

    fill_value: int | float = math.nan

    streaming_safe: ClassVar[bool] = False

    def merge(self, patches: Iterable[Any], domain: Any) -> np.ndarray:
        shape, patches = _dense_layout(patches, domain)
        stack, count = _overlap_stack(patches, shape)
        out = _with_fill(_arraywise_mode(stack), count > 0, self.fill_value)
        return out.astype(_label_dtype(self.fill_value))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.Learned dataclass

Bases: Aggregation

Caller-supplied merge — model(patches, domain) -> field.

Carries closures, so forbid_in_yaml = True. Streaming behaviour is the model's responsibility, so streaming_safe = False.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Learned(Aggregation):
    """Caller-supplied merge — ``model(patches, domain) -> field``.

    Carries closures, so ``forbid_in_yaml = True``. Streaming behaviour is
    the model's responsibility, so ``streaming_safe = False``.
    """

    model: Callable[[Iterable[Any], Any], Any]

    streaming_safe: ClassVar[bool] = False
    forbid_in_yaml: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any], domain: Any) -> Any:
        return self.model(patches, domain)

Approximate (sketches)

geopatcher.spatial.aggregation.ApproxQuantile dataclass

Bases: _ReservoirSketch

Global approximate quantile(s) from a uniform reservoir of k values.

A global reducer: merge returns {str(float(q)): value} for the whole field, not a per-cell quantile field. There is no streamable per-cell median; spatial.aggregation.Median stays the exact in-RAM option.

Parameters:

Name Type Description Default
q float | list[float]

Quantile or list of quantiles in [0, 1] (int or float).

0.5
k int

Reservoir size — number of values retained for the estimate.

200
seed int | None

RNG seed. None (the default, as for the samplers) draws fresh OS entropy on every merge; pass an int to make repeated merge() calls on one instance reproducible.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class ApproxQuantile(_ReservoirSketch):
    """Global approximate quantile(s) from a uniform reservoir of ``k`` values.

    A **global** reducer: ``merge`` returns ``{str(float(q)): value}`` for
    the whole field, not a per-cell quantile field. There is no streamable
    per-cell median; `spatial.aggregation.Median` stays the exact in-RAM option.

    Args:
        q: Quantile or list of quantiles in ``[0, 1]`` (int or float).
        k: Reservoir size — number of values retained for the estimate.
        seed: RNG seed. ``None`` (the default, as for the samplers) draws
            fresh OS entropy on every ``merge``; pass an int to make
            repeated ``merge()`` calls on one instance reproducible.
    """

    q: float | list[float] = 0.5
    k: int = 200
    seed: int | None = None
    _sample: list[Any] = field(default_factory=list, init=False, repr=False)
    _seen: int = field(default=0, init=False, repr=False)
    _rng: np.random.Generator = field(init=False, repr=False)

    def __post_init__(self) -> None:
        if self.k < 1:
            raise ValueError("k must be >= 1")
        for q in self._quantiles():
            if not 0.0 <= q <= 1.0:
                raise ValueError(f"q must be in [0, 1], got {q!r}")
        self._reset()

    def _quantiles(self) -> list[float]:
        if isinstance(self.q, (list, tuple)):
            return [float(q) for q in self.q]
        return [float(self.q)]

    def _coerce(self, value: Any) -> Any:
        return float(value)

    def finalize(self) -> dict[str, float]:
        if not self._sample:
            return {}
        values = np.asarray(self._sample, dtype=np.float64)
        return {str(q): float(np.quantile(values, q)) for q in self._quantiles()}

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.ApproxCardinality dataclass

Bases: _SketchAggregation

Global approximate unique-value count via HyperLogLog.

A global reducer: merge returns one float for the whole field.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class ApproxCardinality(_SketchAggregation):
    """Global approximate unique-value count via HyperLogLog.

    A **global** reducer: ``merge`` returns one float for the whole field.
    """

    p: int = 14
    _registers: np.ndarray = field(init=False, repr=False)

    def __post_init__(self) -> None:
        if not 4 <= self.p <= 16:
            raise ValueError("p must be between 4 and 16")
        self._reset()

    def _reset(self) -> None:
        self._registers = np.zeros(1 << self.p, dtype=np.uint8)

    def update_many(self, values: Iterable[Any]) -> None:
        for value in values:
            h = _hash64(value)
            idx = h & ((1 << self.p) - 1)
            w = h >> self.p
            rank = (
                (HASH_BITS - self.p) - w.bit_length() + 1
                if w
                else HASH_BITS - self.p + 1
            )
            self._registers[idx] = max(int(self._registers[idx]), rank)

    def finalize(self) -> float:
        m = 1 << self.p
        estimate = (
            _hll_alpha(m) * m * m / np.sum(2.0 ** (-self._registers.astype(float)))
        )
        zeros = int(np.count_nonzero(self._registers == 0))
        if estimate <= 2.5 * m and zeros > 0:
            estimate = m * math.log(m / zeros)
        return float(estimate)

    def merge_state(self, other: ApproxCardinality) -> None:
        self._check_mergeable(other, "p")
        self._registers = np.maximum(self._registers, other._registers)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.spatial.aggregation.ApproxMode dataclass

Bases: _SketchAggregation

Global approximate heavy hitters via Misra-Gries counters.

A global reducer: merge returns {value: count} for the whole field, not a per-cell mode. For a streamable per-cell majority use spatial.aggregation.HardVote.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class ApproxMode(_SketchAggregation):
    """Global approximate heavy hitters via Misra-Gries counters.

    A **global** reducer: ``merge`` returns ``{value: count}`` for the
    whole field, not a per-cell mode. For a streamable per-cell majority
    use `spatial.aggregation.HardVote`.
    """

    k: int = 16
    _counts: dict[Any, int] = field(default_factory=dict, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.k < 1:
            raise ValueError("k must be >= 1")

    def _reset(self) -> None:
        self._counts = {}

    def update_many(self, values: Iterable[Any]) -> None:
        for value in values:
            key = _python_scalar(value)
            if key in self._counts:
                self._counts[key] += 1
            elif len(self._counts) < self.k:
                self._counts[key] = 1
            else:
                drop = []
                for item in self._counts:
                    self._counts[item] -= 1
                    if self._counts[item] == 0:
                        drop.append(item)
                for item in drop:
                    del self._counts[item]

    def finalize(self) -> dict[Any, int]:
        return dict(
            sorted(self._counts.items(), key=lambda item: item[1], reverse=True)
        )

    def merge_state(self, other: ApproxMode) -> None:
        """Mergeable Misra-Gries union (Agarwal et al. 2012).

        Sum the counters; if more than ``k`` survive, subtract the
        ``(k + 1)``-th largest count from all and drop the non-positive ones.
        """
        self._check_mergeable(other, "k")
        counts = dict(self._counts)
        for key, count in other._counts.items():
            counts[key] = counts.get(key, 0) + count
        if len(counts) > self.k:
            cut = sorted(counts.values(), reverse=True)[self.k]
            counts = {key: c - cut for key, c in counts.items() if c > cut}
        self._counts = counts

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

merge_state(other)

Mergeable Misra-Gries union (Agarwal et al. 2012).

Sum the counters; if more than k survive, subtract the (k + 1)-th largest count from all and drop the non-positive ones.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
def merge_state(self, other: ApproxMode) -> None:
    """Mergeable Misra-Gries union (Agarwal et al. 2012).

    Sum the counters; if more than ``k`` survive, subtract the
    ``(k + 1)``-th largest count from all and drop the non-positive ones.
    """
    self._check_mergeable(other, "k")
    counts = dict(self._counts)
    for key, count in other._counts.items():
        counts[key] = counts.get(key, 0) + count
    if len(counts) > self.k:
        cut = sorted(counts.values(), reverse=True)[self.k]
        counts = {key: c - cut for key, c in counts.items() if c > cut}
    self._counts = counts

geopatcher.spatial.aggregation.StreamingHistogram dataclass

Bases: _SketchAggregation

Global online histogram with at most bins centroids.

A global reducer: merge returns {"centers", "counts"} for the whole field.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class StreamingHistogram(_SketchAggregation):
    """Global online histogram with at most ``bins`` centroids.

    A **global** reducer: ``merge`` returns ``{"centers", "counts"}`` for
    the whole field.
    """

    bins: int = 64
    _centers: list[float] = field(default_factory=list, init=False, repr=False)
    _counts: list[int] = field(default_factory=list, init=False, repr=False)

    def __post_init__(self) -> None:
        if self.bins < 1:
            raise ValueError("bins must be >= 1")

    def _reset(self) -> None:
        self._centers = []
        self._counts = []

    def update_many(self, values: Iterable[Any]) -> None:
        for value in values:
            self._centers.append(float(value))
            self._counts.append(1)
            while len(self._centers) > self.bins:
                self._merge_closest_bins()

    def finalize(self) -> dict[str, np.ndarray]:
        order = np.argsort(self._centers)
        return {
            "centers": np.asarray(self._centers, dtype=np.float64)[order],
            "counts": np.asarray(self._counts, dtype=np.int64)[order],
        }

    def merge_state(self, other: StreamingHistogram) -> None:
        """Add ``other``'s weighted centroids, then re-compress to ``bins``."""
        self._check_mergeable(other, "bins")
        self._centers = [*self._centers, *other._centers]
        self._counts = [*self._counts, *other._counts]
        while len(self._centers) > self.bins:
            self._merge_closest_bins()

    def _merge_closest_bins(self) -> None:
        order = np.argsort(self._centers)
        centers = [self._centers[i] for i in order]
        counts = [self._counts[i] for i in order]
        idx = min(
            range(len(centers) - 1),
            key=lambda i: abs(centers[i + 1] - centers[i]),
        )
        count = counts[idx] + counts[idx + 1]
        center = (
            centers[idx] * counts[idx] + centers[idx + 1] * counts[idx + 1]
        ) / count
        centers[idx : idx + 2] = [center]
        counts[idx : idx + 2] = [count]
        self._centers = centers
        self._counts = counts

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

merge_state(other)

Add other's weighted centroids, then re-compress to bins.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
def merge_state(self, other: StreamingHistogram) -> None:
    """Add ``other``'s weighted centroids, then re-compress to ``bins``."""
    self._check_mergeable(other, "bins")
    self._centers = [*self._centers, *other._centers]
    self._counts = [*self._counts, *other._counts]
    while len(self._centers) > self.bins:
        self._merge_closest_bins()

geopatcher.spatial.aggregation.Reservoir dataclass

Bases: _ReservoirSketch

Uniform global reservoir sample of k values (Vitter's Algorithm R).

A global reducer: merge returns a 1-D array of at most k values drawn uniformly from every finite value of every patch.

Parameters:

Name Type Description Default
k int

Reservoir size.

100
seed int | None

RNG seed. None (the default, as for the samplers) draws fresh OS entropy on every merge; pass an int to make repeated merge() calls on one instance reproducible.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
@dataclass(eq=False)
class Reservoir(_ReservoirSketch):
    """Uniform global reservoir sample of ``k`` values (Vitter's Algorithm R).

    A **global** reducer: ``merge`` returns a 1-D array of at most ``k``
    values drawn uniformly from every finite value of every patch.

    Args:
        k: Reservoir size.
        seed: RNG seed. ``None`` (the default, as for the samplers) draws
            fresh OS entropy on every ``merge``; pass an int to make
            repeated ``merge()`` calls on one instance reproducible.
    """

    k: int = 100
    seed: int | None = None
    _sample: list[Any] = field(default_factory=list, init=False, repr=False)
    _seen: int = field(default=0, init=False, repr=False)
    _rng: np.random.Generator = field(init=False, repr=False)

    def __post_init__(self) -> None:
        if self.k < 1:
            raise ValueError("k must be >= 1")
        self._reset()

    def finalize(self) -> np.ndarray:
        return np.asarray(self._sample)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)