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
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, |
required |
boundary
|
BoundaryMode
|
How to treat anchors whose patch would overflow the
domain edge. See
Honoured on raster domains and on |
'drop'
|
pad_value
|
float | None
|
Constant fill for |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
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
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
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 ( |
required |
metric
|
str
|
|
'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
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'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/geometry.py
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 |
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
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
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 |
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 whenP > 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
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
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 |
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 |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
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 ( |
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 |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
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— inO(N)expected time via a background grid.max_triesdoes not apply: every point is tried exactly once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_dist
|
float
|
Minimum allowed separation between anchors ( |
required |
max_tries
|
int
|
Bridson parameter — attempts per active anchor
(raster only, |
30
|
seed
|
int | None
|
Optional integer seed. |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
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
|
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
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 |
required |
crs
|
Any | None
|
CRS the coordinates are in. When set and different from
|
None
|
polar_guard
|
Literal['warn', 'raise', 'ignore']
|
Same geographic-edge guard as |
'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
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 |
required |
spacing
|
float | None
|
Along-track resampling distance in coordinate units, or
|
None
|
crs
|
Any | None
|
CRS the |
None
|
polar_guard
|
Literal['warn', 'raise', 'ignore']
|
Behaviour when a geographic |
'warn'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/sampler.py
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
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
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
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
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
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.5
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
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
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
geopatcher.spatial.window.Custom
dataclass
¶
Bases: Window
Caller-supplied weight function — the escape hatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Geometry], ndarray]
|
Callable |
required |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/window.py
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 — |
required |
Returns:
| Type | Description |
|---|---|
tuple[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
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
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
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
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 |
nan
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
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 |
False
|
target_path
|
str | None
|
With |
None
|
chunks
|
tuple[int, ...] | None
|
Zarr chunk shape of the streaming accumulators — required
for |
None
|
shard_shape
|
tuple[int, ...] | None
|
Optional zarr v3 shard shape (right-aligned like
|
None
|
writer
|
str
|
|
'zarr'
|
cog
|
dict[str, Any] | None
|
|
None
|
normalize_by_window
|
bool
|
Divide by the accumulated weight at the end
(default |
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'
|
overwrite
|
bool
|
Replace an existing store / file at |
False
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 | |
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 |
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
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 |
nan
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 | |
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
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
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
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
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 |
required |
fill_value
|
int | float
|
Label of cells that received no vote. Default |
-1
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
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 |
required |
fill_value
|
int | float
|
Label of cells no valid probability reached. Default
|
-1
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
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
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
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. |
nan
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
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
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.5
|
k
|
int
|
Reservoir size — number of values retained for the estimate. |
200
|
seed
|
int | None
|
RNG seed. |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/aggregation.py
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
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
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
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
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 | |
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
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
|