Core — geopatcher¶
What every patching job touches: the patchers, the patch carriers, the
Field / Domain protocols and RasterField, the adapter for any
geoarray.RasterSource (a GeoArray or a lazy reader).
Patchers¶
geopatcher.SpatialPatcher
dataclass
¶
Bases: _SpatialPatcherBase
The four-axis spatial Patcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
Geometry
|
How a neighborhood is shaped around an anchor. |
required |
sampler
|
Sampler
|
Where anchors go. |
required |
window
|
Window
|
Boundary treatment / per-pixel weights. |
required |
aggregation
|
Aggregation
|
Local → global merge strategy. |
required |
on_error
|
OnErrorPolicy
|
Patch-read error policy. |
'raise'
|
max_retries
|
int
|
Number of retries when |
0
|
retry_on
|
tuple[type[BaseException] | str, ...]
|
Exception classes or class names that should be retried.
Defaults to I/O-shaped failures ( |
(OSError, TimeoutError)
|
capture_traceback
|
bool
|
If |
True
|
errors holds the failures of the latest split / asplit /
reduce / two_pass call (both passes of a two_pass): each
call starts a fresh list.
Examples:
Sliding-window inference over a raster::
patcher = SpatialPatcher(
geometry = spatial.geometry.Rectangular(size=(256, 256)),
sampler = spatial.sampler.RegularStride(step=(192, 192)),
window = spatial.window.Hann(),
aggregation = spatial.aggregation.OverlapAdd(),
)
patches = list(patcher.split(field))
outs = [run_operator(p) for p in patches]
stitched = patcher.merge(outs, field.domain)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 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 | |
amerge(patches, domain, hooks=None)
async
¶
Async-friendly merge that accepts async or sync patch iterables.
An async stream is not materialised: the aggregation runs in a
worker thread and pulls one patch at a time from the event loop,
so a streaming-safe aggregation holds one patch, not the stream.
Batches are accepted as in merge.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
anchors(field)
¶
Materialise the sampler's anchor sequence for field.
Returns the same sequence split(field) walks, as a list
the caller can len() and index. Anchors are placed without
touching the field (only its domain), so this is sync on the
async patcher too. Same determinism contract as n_anchors
(deterministic given an int sampler seed, re-drawn when seed is
None).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
asplit(field, hooks=None, *, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async mirror of split over an AsyncField.
The same anchor walk as split — on_error / max_retries /
retry_on (failures in errors), hooks, journal,
cache (looked up and stored in a worker thread) and the
max_in_flight / max_in_flight_bytes slot-ownership
contract: close each yielded patch promptly (patch.close() or
with patch: ...); the finalizer-based release on garbage
collection is a safety net, not the mechanism. prefetch has
no async counterpart: reads are awaited one at a time, leaving
concurrency to the caller.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
get_config()
¶
Axes as {"class", "config"} envelopes; retry_on as qualified names.
geopatcher.config.from_config rebuilds the patcher from
axis_envelope(patcher).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
merge(patches, domain, hooks=None)
¶
Hand the patches to the aggregation and return its raw output.
The result is whatever self.aggregation.merge produces — a bare
np.ndarray on the domain grid for the dense aggregations, a
dict for spatial.aggregation.MeanStd /
spatial.aggregation.InvVarWeightedMean / spatial.aggregation.ByIndex, a zarr
array for streaming spatial.aggregation.OverlapAdd. Use merge_to_field (or
merge_to_xarray) to get a georeferenced carrier back. A streaming_safe =
False aggregation warns (or raises under set_strict) at the caller's line.
patches may hold batches as well as patches: a geopatcher.run.PatchBatch
(or a model's output for one, PatchBatch(scores, batch.valid)), or a
GeoArray with a patch batch dim, one or a stream of them. Each row is
placed from its transform against domain's grid, with this patcher's
geometry and window weights (geopatcher.run.unbatch); padding rows are
dropped. A row whose pixel size or rotation differs from the grid's
raises ValueError naming it.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
merge_to_field(patches, field, hooks=None)
¶
merge + rebuild a georeferenced carrier via field.with_data.
merge returns the aggregation's raw output (see ADR-007 in
docs/patcher/decisions.md); this wraps it back onto the
field's grid so the transform, CRS, nodata
(fill_value / rio.nodata) and attrs of the source
survive. What comes back is the adapter's with_data result: a
geoarray.GeoArray for RasterField, a RioXarrayField / XarrayField
wrapping the rebuilt DataArray (.da) for the xarray
adapters.
The merged values keep the source dtype when they fit it (the
rule in merge_to_xarray); otherwise the aggregation's dtype is
kept — e.g. float64 carrying a NaN fill on an integer source.
On a raster field the patches may carry a different band count
than the source — a per-patch operator that turns four bands into
one index merges into a (1, H, W) GeoArray on the source
grid, with the stale per-band attrs dropped and a NaN fill for
the new float quantity. The xarray adapters keep their dims and
coords, so they need the domain's own shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patches
|
Iterable[Any]
|
Iterable of patches to merge. |
required |
field
|
Field
|
The |
required |
hooks
|
Iterable[PatcherHook] | None
|
Optional observability hooks forwarded to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Examples:
Stitch Hann-weighted chips back into a GeoArray::
out = patcher.merge_to_field(patcher.split(field), field)
out.grid == field.reader.grid # True
Keep the raw array instead::
arr = patcher.merge(patcher.split(field), field.domain)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | |
merge_to_xarray(patches, field, hooks=None)
¶
merge + rewrap as xarray.DataArray, restoring the original coords.
Convenience wrapper for the xrpatcher-style migration story: the
bare merge returns an np.ndarray against the field's domain
shape; this calls field.with_data(...) to put it back inside a
DataArray with the field's coord metadata intact, and unwraps the
resulting XarrayField to return the underlying xarray.DataArray.
Dtype rule (shared with merge_to_field): the merged values are
cast back to the source dtype when every value is representable
in it. An integer / bool source needs every value finite, integral
and in range — otherwise (a fractional mean, a NaN fill) the
aggregation's dtype is kept. A floating source is cast whenever no
finite value overflows it (precision is rounded, as for the
source). Other dtypes are left untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patches
|
Iterable[Any]
|
Iterable of patches to merge. |
required |
field
|
Field
|
The |
required |
hooks
|
Iterable[PatcherHook] | None
|
Optional observability hooks forwarded to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
original coords. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
n_anchors(field)
¶
Number of patches split(field) will yield.
Enumerates the sampler's anchors without touching the field — only the domain is consulted.
Determinism contract: holds exactly for samplers that return the
same anchor set on every call given the same (domain,
geometry). That covers all five samplers when a seed is set;
for unseeded spatial.sampler.Random / spatial.sampler.JitteredStride /
spatial.sampler.PoissonDisk the count is still well-defined
(n_samples for the first two; a probabilistic estimate for
the third), but the anchors materialised here are different
draws from the ones a subsequent split will see. See
docs/patcher/decisions.md (ADR-001) for why split returns an
iterator and this helper exists as the len substitute.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
patch_at(field, anchor, *, cache=None, field_id=None)
¶
Read a single Patch at a specific anchor.
The same geometry → field.select → window-weights pipeline
as split, but driven by one explicit anchor instead of
walking the sampler. Designed for random-access ML datasets
(torch Dataset.__getitem__, Grain RandomAccessDataSource)
that need lazy single-patch reads without materialising the
whole iterator first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
Field
|
The |
required |
anchor
|
Any
|
An anchor in the same format the sampler emits
(e.g. |
required |
cache
|
Any | None
|
Optional |
None
|
field_id
|
str | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
Patch
|
A single |
Patch
|
yield for the same anchor. |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
reduce(field, agg, hooks=None, *, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Run one streaming pass of split into agg and return its result.
The patches come from split, so the patcher's on_error /
retry policy and the hooks / prefetch / journal /
cache / backpressure knobs apply exactly as they do there;
each patch is closed (its backpressure slot released) once agg
moves on to the next. agg gets the same streaming-safety check
as merge (a warning, or RuntimeError under set_strict).
Examples:
Global statistics for a normalisation pass::
stats = patcher.reduce(field, spatial.aggregation.MeanStd())
Tolerate unreadable tiles while reducing::
patcher = replace(patcher, on_error="skip")
bounds = patcher.reduce(field, spatial.aggregation.MinMax(), prefetch=2)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
split(field, hooks=None, *, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Yield patches lazily — one per anchor placed by the sampler.
When max_in_flight / max_in_flight_bytes bound the number
of outstanding patches, each yielded patch owns one backpressure
slot until it is released. Consumers must release promptly by
calling patch.close() (or using each patch as a context
manager: with patch: ...). A garbage-collection finalizer
returns leaked slots eventually, but it is a safety net, not the
mechanism — relying on it can stall this iterator until the
collector runs.
A PatchCache passed as cache is consulted before every
read: on a hit the source is never touched (only field.domain
metadata is), on a miss the patch is read then stored. Composes
with journal (whose anchors are skipped and reported to the
on_patch_skipped hook) and prefetch (the cache check runs
in the producer thread).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
to_dask_bag(field)
¶
Build a Dask bag with one item (and one partition) per patch.
Same per-patch tasks and policy caveats as to_delayed.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
to_delayed(field, operator=None)
¶
Build a Dask delayed graph for patches, optionally mapped by an operator.
One patch_at task per anchor; the field enters the graph once.
Runner-level policies (on_error, hooks, journal, cache,
prefetch) do not apply — see geopatcher.run.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
two_pass(field, *, reduce_with, apply, aggregation=None, hooks=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Run a global-statistics pass, then apply an operator with the result.
Pass one is reduce with reduce_with; pass two splits again,
maps every patch through apply(data, stats) (via
Patch.with_data) and merges with aggregation (default: the
patcher's own). Both passes go through split — on_error,
hooks, journal, cache, prefetch and backpressure apply to each —
over one anchor list materialised up front, so an unseeded random
sampler places both passes identically. Each patch is read twice;
pass a cache to serve the second pass without re-reading.
Examples:
Standardise a scene with its global mean / std::
out = patcher.two_pass(
field,
reduce_with=spatial.aggregation.MeanStd(),
apply=lambda x, s: (np.asarray(x) - s["mean"]) / s["std"],
)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
geopatcher.AsyncSpatialPatcher
dataclass
¶
Bases: _SpatialPatcherBase
Async mirror of SpatialPatcher over an AsyncField.
split is an async for-able iterator (an alias of asplit).
Useful with AsyncGeoTIFFReader for high-concurrency per-tile
fan-out. The fields, the on_error / max_retries /
retry_on / capture_traceback knobs and the anchor walk are
SpatialPatcher's. Iteration is serialized (one await per
anchor), so the errors accumulator is safe to read from the same
coroutine without external locking.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
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 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 | |
amerge(patches, domain, hooks=None)
async
¶
Async-friendly merge that accepts async or sync patch iterables.
An async stream is not materialised: the aggregation runs in a
worker thread and pulls one patch at a time from the event loop,
so a streaming-safe aggregation holds one patch, not the stream.
Batches are accepted as in merge.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
anchors(field)
¶
Materialise the sampler's anchor sequence for field.
Returns the same sequence split(field) walks, as a list
the caller can len() and index. Anchors are placed without
touching the field (only its domain), so this is sync on the
async patcher too. Same determinism contract as n_anchors
(deterministic given an int sampler seed, re-drawn when seed is
None).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
asplit(field, hooks=None, *, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async mirror of split over an AsyncField.
The same anchor walk as split — on_error / max_retries /
retry_on (failures in errors), hooks, journal,
cache (looked up and stored in a worker thread) and the
max_in_flight / max_in_flight_bytes slot-ownership
contract: close each yielded patch promptly (patch.close() or
with patch: ...); the finalizer-based release on garbage
collection is a safety net, not the mechanism. prefetch has
no async counterpart: reads are awaited one at a time, leaving
concurrency to the caller.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
get_config()
¶
Axes as {"class", "config"} envelopes; retry_on as qualified names.
geopatcher.config.from_config rebuilds the patcher from
axis_envelope(patcher).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
merge(patches, domain, hooks=None)
¶
Hand the patches to the aggregation and return its raw output.
The result is whatever self.aggregation.merge produces — a bare
np.ndarray on the domain grid for the dense aggregations, a
dict for spatial.aggregation.MeanStd /
spatial.aggregation.InvVarWeightedMean / spatial.aggregation.ByIndex, a zarr
array for streaming spatial.aggregation.OverlapAdd. Use merge_to_field (or
merge_to_xarray) to get a georeferenced carrier back. A streaming_safe =
False aggregation warns (or raises under set_strict) at the caller's line.
patches may hold batches as well as patches: a geopatcher.run.PatchBatch
(or a model's output for one, PatchBatch(scores, batch.valid)), or a
GeoArray with a patch batch dim, one or a stream of them. Each row is
placed from its transform against domain's grid, with this patcher's
geometry and window weights (geopatcher.run.unbatch); padding rows are
dropped. A row whose pixel size or rotation differs from the grid's
raises ValueError naming it.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
n_anchors(field)
¶
Number of patches split(field) will yield.
Enumerates the sampler's anchors without touching the field — only the domain is consulted.
Determinism contract: holds exactly for samplers that return the
same anchor set on every call given the same (domain,
geometry). That covers all five samplers when a seed is set;
for unseeded spatial.sampler.Random / spatial.sampler.JitteredStride /
spatial.sampler.PoissonDisk the count is still well-defined
(n_samples for the first two; a probabilistic estimate for
the third), but the anchors materialised here are different
draws from the ones a subsequent split will see. See
docs/patcher/decisions.md (ADR-001) for why split returns an
iterator and this helper exists as the len substitute.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
patch_at(field, anchor)
async
¶
Read a single Patch at a specific anchor.
Async mirror of SpatialPatcher.patch_at — the read goes
through await field.select(...). Designed for random-access
cloud-tile readers driving a Grain / torch Dataset with
per-item HTTP fan-out.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
reduce(field, agg, hooks=None, *, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async SpatialPatcher.reduce: one streaming pass of asplit into agg.
The on_error / retry policy, hooks, journal, cache
and backpressure apply as in asplit; each patch is closed once
agg moves on. The aggregation folds the stream in a worker
thread, one patch at a time (as in amerge).
Examples:
Global statistics over a remote COG::
stats = await patcher.reduce(field, spatial.aggregation.MeanStd())
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
split(field, hooks=None, *, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Alias for asplit.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
two_pass(field, *, reduce_with, apply, aggregation=None, hooks=None, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async SpatialPatcher.two_pass: a statistics pass, then an apply pass.
Both passes walk one anchor list materialised up front and record
into one errors list; each patch is read twice unless a
cache serves the second pass. apply(data, stats) runs on
the event loop, so keep it cheap or offload it yourself.
Examples:
Standardise a remote scene with its global mean / std::
out = await patcher.two_pass(
field,
reduce_with=spatial.aggregation.MeanStd(),
apply=lambda x, s: (np.asarray(x) - s["mean"]) / s["std"],
)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
geopatcher.TemporalPatcher
dataclass
¶
Four-axis temporal Patcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geometry
|
Geometry
|
How a temporal window is shaped around an anchor. |
required |
sampler
|
Sampler
|
Where time anchors are placed. |
required |
window
|
Window
|
Temporal boundary treatment (recency / taper / periodic). |
required |
aggregation
|
Aggregation
|
Time → time merge strategy. |
required |
on_error
|
OnErrorPolicy
|
Patch-read error policy, as |
'raise'
|
max_retries
|
int
|
Number of retries when |
0
|
retry_on
|
tuple[type[BaseException] | str, ...]
|
Exception classes or class names that should be retried. |
(OSError, TimeoutError)
|
capture_traceback
|
bool
|
If |
True
|
Examples:
Lookback + horizon forecasting on a (time, feature) array::
tp = TemporalPatcher(
geometry = temporal.geometry.LookbackHorizon(lookback=12, horizon=6),
sampler = temporal.sampler.RegularStride(step=1),
window = temporal.window.CausalBoxcar(),
aggregation = temporal.aggregation.Forecast(horizon=6),
)
patches = list(tp.split(series))
preds = [p.with_data(model(p.data)) for p in patches]
aligned = tp.merge(preds) # {anchor: horizon block}
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
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 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 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 830 831 832 833 834 835 836 837 838 839 | |
amerge(patches, hooks=None)
async
¶
Async-friendly merge over an async or sync patch iterable.
An async stream is not materialised: the aggregation runs in a worker thread and pulls one patch at a time from the event loop.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
anchors(series, *, time_axis=0, coord=None)
¶
Materialise the anchors split yields patches for.
The sampler's sequence minus the anchors the geometry's
boundary="drop" drops, so every returned anchor yields at
least one patch. len(anchors) <= n_anchors — multi-window
geometries emit several patches per anchor. Same determinism
contract as n_anchors. See SpatialPatcher.anchors.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
asplit(series, *, time_axis=0, coord=None, hooks=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async iterator over split for async pipeline composition.
Takes split's arguments; each patch is pulled in a worker thread
(asyncio.to_thread), so reads never block the event loop and
prefetch overlaps them with the consumer.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
get_config()
¶
Axes as {"class", "config"} envelopes plus the runner knobs.
Same shape as SpatialPatcher.get_config (patcher_config):
geopatcher.config.from_config rebuilds the patcher, on_error /
retry_on included.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
merge(patches, hooks=None)
¶
Hand the patches to the aggregation and return its output.
A streaming_safe = False aggregation warns (or raises under
set_strict) at the caller's line, as SpatialPatcher.merge does.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
n_anchors(series, *, time_axis=0, coord=None)
¶
Number of patches split(series) will yield.
Walks the sampler and the geometry's per-anchor window — a
single geometry call may return a list[slice] (e.g.
temporal.geometry.MultiScale), in which case split yields one patch
per slice. Only series.shape (or a field's domain) is read,
so lazy series don't get materialised here. See
docs/patcher/decisions.md (ADR-001).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
patch_anchors(series, *, time_axis=0, coord=None)
¶
One patch_at key per patch split yields, in split order.
A bare anchor where the geometry yields one window for it, and
(anchor, k) for each of the windows a multi-window geometry
(temporal.geometry.MultiScale) yields, so
len(patch_anchors(series)) == n_anchors(series).
IndexedPatchView indexes by these keys; the journal, cache and
errors record the same keys.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
patch_at(series, anchor, *, time_axis=0, coord=None, cache=None, field_id=None)
¶
Return the single patch split yields for one patch key.
The temporal counterpart of SpatialPatcher.patch_at, so a
TemporalPatcher drops into IndexedPatchView (including its
cache=PatchCache(...) mode). Only the selected window is read
from series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
Any
|
Same input as |
required |
anchor
|
int | tuple[int, int]
|
A key from |
required |
time_axis
|
int
|
Which axis is the time axis. Default 0. |
0
|
coord
|
Any | None
|
See |
None
|
cache
|
Any | None
|
Optional |
None
|
field_id
|
str | None
|
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a bare anchor is given for a geometry that
yields several windows for it, or |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
patches_at(series, anchor, *, time_axis=0, coord=None)
¶
Return the patches split would yield for a single anchor.
Always a list — length 1 for the common single-slice
geometries, length N for temporal.geometry.MultiScale /
temporal.geometry.PhaseWindow (one entry per window), and empty when the
geometry's boundary="drop" drops the anchor.
The spatial counterpart returns a single Patch; the temporal
side has to flatten the multi-scale case, so the return type
is a list either way for callers to handle uniformly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
Any
|
Same input as |
required |
anchor
|
int
|
A single anchor value (typically from
|
required |
time_axis
|
int
|
Which axis is the time axis. Default 0. |
0
|
coord
|
Any | None
|
See |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
reduce(series, agg, *, time_axis=0, coord=None, hooks=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Run one streaming pass of split into agg and return its result.
The split knobs (on_error, hooks, prefetch, journal, cache,
backpressure) apply as there; each patch is closed (its
backpressure slot released) once agg moves on, and agg
gets merge's streaming-safety check.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
split(series, *, time_axis=0, coord=None, hooks=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Yield temporal patches lazily.
Same runner contract as SpatialPatcher.split: the on_error
policy, journal (skips patch keys it has), cache (a
PatchCache consulted before every read), prefetch and the
max_in_flight / max_in_flight_bytes backpressure, whose
slots each yielded patch owns until patch.close() (or
with patch: ...).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
series
|
Any
|
What to patch along |
required |
time_axis
|
int
|
Which axis is the time axis. Default 0. |
0
|
coord
|
Any | None
|
1-D, strictly increasing coordinate along |
None
|
hooks
|
Iterable[PatcherHook] | None
|
Optional observability hooks for split callbacks. |
None
|
prefetch
|
int
|
If positive, eagerly buffer up to |
0
|
journal
|
Any | None
|
Optional |
None
|
cache
|
Any | None
|
Optional |
None
|
max_in_flight
|
int | None
|
Maximum number of unreleased patches. |
None
|
max_in_flight_bytes
|
int | None
|
Maximum total bytes of unreleased patches. |
None
|
Raises:
| Type | Description |
|---|---|
IncompleteScanConfiguration
|
The sampler sets
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
to_dask_bag(series, *, time_axis=0, coord=None)
¶
A Dask bag with one item (and one partition) per patch key.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
to_delayed(series, operator=None, *, time_axis=0, coord=None)
¶
One Dask delayed patch_at task per patch key (see geopatcher.run).
Runner-level policies (on_error, hooks, journal, cache,
prefetch) do not apply.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
two_pass(series, *, reduce_with, apply, aggregation=None, time_axis=0, coord=None, hooks=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
A statistics pass, then apply(data, stats) and a merge.
Mirrors SpatialPatcher.two_pass: pass one is reduce with
reduce_with; pass two maps every patch through
apply(data, stats) and merges with aggregation (default:
the patcher's own). Both passes walk one anchor list materialised
up front, so an unseeded temporal.sampler.Random places them identically.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
geopatcher.SpatioTemporalPatcher
dataclass
¶
Composition of a spatial and a temporal Patcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spatial
|
SpatialPatcher
|
A |
required |
temporal
|
TemporalPatcher
|
A |
required |
coupling
|
Literal['product', 'coupled']
|
|
'product'
|
time_axis
|
int
|
Which axis of the spatial patch's data is the time
axis after the spatial slice has been read. Default |
0
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
57 58 59 60 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 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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | |
asplit(field, hooks=None, *, coord=None, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
async
¶
Async mirror of split for async spatial fields.
The same walk as split (policy, hooks, journal, cache,
backpressure); each chip is awaited (aselect / select).
prefetch has no async counterpart.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
get_config()
¶
merge(patches, field, hooks=None)
¶
Group patches by spatial anchor and apply the temporal aggregation.
Returns [(spatial_anchor, temporal_aggregation_result), …] — a
list of pairs rather than a dict because GridDomain anchors are
dict[str, …] (unhashable), KNN-graph anchors are numpy arrays
(also unhashable), and we want to preserve the original anchor
object on the result. The per-anchor temporal merge runs through
self.temporal.aggregation, but the spatial aggregation is
intentionally not applied — the returned list is the
by-anchor view callers typically want for spatiotemporal
workflows (e.g. event-triggered patching, where the anchor is
the unit of interest). Users who need a full spatial merge
across the temporal results can pass the values through
self.spatial.aggregation.merge themselves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patches
|
Iterable[Any]
|
Iterable of |
required |
field
|
Any
|
The original field — currently unused, kept for the
symmetry with |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[Any, Any]]
|
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
split(field, hooks=None, *, coord=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)
¶
Yield SpatioTemporalPatches lazily.
The coupled mode expects self.spatial.sampler.anchors_ to be
an iterable of (space_anchor, time_anchor) tuples and is
only valid with spatial.sampler.Explicit spatial / time samplers.
Each spatial chip is read once — through the spatial patcher's
read pipeline and on_error policy — then sliced into its time
windows. A patch is keyed (journal) by (space_anchor,
time_key), time_key being the temporal patch_anchors key
(the time anchor, or (anchor, k) for a multi-window geometry);
hooks receive (space_anchor, time_anchor) and the time
anchor's coord_value. A failed chip read reaches the
on_error hooks with the spatial anchor (product) or the pair
(coupled). Product mode reports UNKNOWN_TOTAL to
on_split_start (the window count needs the chips' time
length); coupled mode the number of pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
Any
|
The field to split. |
required |
hooks
|
Iterable[PatcherHook] | None
|
Optional observability hooks for split callbacks. |
None
|
coord
|
ndarray | None
|
1-D coordinate vector along |
None
|
prefetch
|
int
|
If positive, eagerly buffer up to |
0
|
journal
|
Any | None
|
Optional |
None
|
cache
|
Any | None
|
Optional |
None
|
max_in_flight
|
int | None
|
Maximum number of unreleased patches. |
None
|
max_in_flight_bytes
|
int | None
|
Maximum total bytes of unreleased patches. |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
Carriers¶
geopatcher.Patch
dataclass
¶
Bases: _ReleaseLifecycleMixin
A single patch produced by a SpatialPatcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataT
|
The substrate slice the operator consumes (a
|
required |
anchor
|
AnchorT
|
Where this patch lives in the global field. Shape varies
with the |
required |
indices
|
IndicesT
|
Backend-specific indexer used to extract |
required |
weights
|
Any | None
|
Optional window weights — used by |
None
|
masked
|
bool
|
|
False
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
with_data(data)
¶
Return a data-replaced copy that does not own this patch's release slot.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
geopatcher.TemporalPatch
dataclass
¶
Bases: _ReleaseLifecycleMixin
A single patch produced by a TemporalPatcher.
Mirrors Patch but indexes along the time axis only.
window_index is the patch's position among the windows its
geometry returned for anchor — k for scale scales[k] of a
temporal.geometry.MultiScale, the cycle slot of a temporal.geometry.PhaseWindow,
and 0 for single-window geometries. It matches the k of the
(anchor, k) key TemporalPatcher.patch_anchors emits. None
(the default for hand-built patches) means "not recorded".
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
with_data(data)
¶
Return a data-replaced copy that does not own this patch's release slot.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
geopatcher.SpatioTemporalPatch
dataclass
¶
Bases: _ReleaseLifecycleMixin
A patch carrying both a spatial and a temporal anchor.
Produced by SpatioTemporalPatcher. The data field is the
spatial-then-temporal (or coupled) slice; space and time keep the
two anchors separately so downstream operators / aggregations can
treat them as peers rather than packed.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
with_data(data)
¶
Return a data-replaced copy that does not own this patch's release slot.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
Protocols¶
geopatcher.Field
¶
Bases: Protocol
A substrate the Patcher reads patches out of.
Three operations:
- domain exposes the I/O-free metadata view used by the
spatial.sampler.Sampler and spatial.geometry.Geometry.
- select(indexer) reads a slice of the field. The shape of
indexer is decided by domain (a rasterio.windows.Window
for RasterDomain, a dict[str, slice] for GridDomain, a list
of row indices for PointDomain / VectorDomain).
- with_data(array) reconstructs a field-shaped value (the
source's georeferencing, nodata and attrs around array) from
an array on the domain grid. Aggregations never call it —
spatial.aggregation.Aggregation.merge and SpatialPatcher.merge return the
raw output (usually a bare np.ndarray); SpatialPatcher.merge_to_field
and SpatialPatcher.merge_to_xarray call it to rebuild a global
field (ADR-007).
Optional: placeholder(indexer, data) returns data (an all-NaN
array) in the carrier select(indexer) would return, without
reading; the patchers use it for the on_error="mask" placeholder
(ADR-011). Without it, a raster window on a RasterDomain becomes a
NaN geoarray.GeoArray on the window's grid, and anything else stays
a bare array.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/protocols.py
geopatcher.AsyncField
¶
Bases: Protocol
Async mirror of Field — concurrent select over remote tiles.
AsyncSpatialPatcher.split consumes this Protocol; the sync surface
is otherwise identical. aselect is the explicit async spelling used
by new code; select is kept for compatibility with the original
async patcher API and may delegate to aselect.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/protocols.py
geopatcher.Domain
¶
Bases: Protocol
Metadata view of a field — bounds, CRS, no I/O.
Concrete subclasses (RasterDomain, GridDomain, VectorDomain,
PointDomain) carry the backend-specific shape that a
spatial.geometry.Geometry.neighborhood(domain, anchor) dispatch needs.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/protocols.py
The raster adapter¶
geopatcher.RasterField
dataclass
¶
A geoarray.RasterSource (a GeoArray, a lazy reader, …) as a Field.
The source doubles as the RasterDomain: its grid and shape are
metadata, known before any pixel is read. Each select reads one
window through source.read_window — a lazy source reads window by
window, a GeoArray slices its memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader
|
RasterSource
|
Any |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Example
import numpy as np from geoarray import GeoArray scene = GeoArray( ... np.zeros((4, 512, 512), np.float32), # (C, H, W) float32 ... (10.0, 0.0, 500000.0, 0.0, -10.0, 4600000.0), ... "EPSG:32630", ... fill_value=np.nan, ... ) field = RasterField(scene) field.domain.grid.shape (512, 512)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/raster.py
select(window)
¶
Read window (boundless) as a GeoArray on the window's grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window
|
Any
|
A |
required |
Returns:
| Type | Description |
|---|---|
GeoArray
|
|
GeoArray
|
hold the source's |
GeoArray
|
when the window leaves the grid). |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/raster.py
with_data(array)
¶
array ((..., H, W) on the source grid) as a GeoArray.