Running at scale — geopatcher.run¶
split / merge are the plain loop. These run it faster, in parallel,
on another engine, or with random access for ML loaders.
Parallel and prefetched runs¶
geopatcher.run.parallel_map(patcher, field, operator, *, n_workers=8, backend='thread', mp_context=None, show_progress=False, journal=None, on_error='raise', batch_size=64, hooks=None, max_in_flight=None)
¶
Apply operator to each spatial patch with a reference executor.
Reads happen in the calling process, through patcher.split — so
the patcher's boundary mode (pad / reflect / …), its
on_error read policy (patcher.errors is populated as usual),
the journal and the hooks all apply exactly as they do to a
plain split loop. Patches are submitted to the executor as they
are read, never more than max_in_flight at a time, so at most
max_in_flight patches (plus up to batch_size read-ahead chips
on the select_many path) are resident at once. The returned
outputs are, of course, all kept.
Process backend: workers are started with an explicit
multiprocessing start method — "forkserver" where available
(Linux / macOS), "spawn" elsewhere — never the platform fork
default, which is unsafe in a process running GDAL / obstore / dask
threads. The operator, every patch and every output are pickled to
and from the workers, so operator must be a picklable,
module-level callable. The field itself is never sent. GeoArray
chips and outputs travel in a compact wire form (pixels, grid config,
fill, attrs) rebuilt through the constructor in the receiving process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patcher
|
SpatialPatcher
|
Spatial patcher that defines the anchor schedule, the boundary mode and the read-error policy. |
required |
field
|
Field
|
Field to split into patches. |
required |
operator
|
Callable[[Any], Any]
|
Callable applied to each patch's |
required |
n_workers
|
int
|
Number of worker threads or processes. |
8
|
backend
|
Backend
|
|
'thread'
|
mp_context
|
str | BaseContext | None
|
Start method for the process backend: a name
( |
None
|
show_progress
|
bool
|
If |
False
|
journal
|
Any | None
|
Optional |
None
|
on_error
|
ErrorPolicy
|
Operator-error policy: |
'raise'
|
batch_size
|
int
|
Maximum number of reads coalesced into one
|
64
|
hooks
|
Iterable[PatcherHook] | None
|
|
None
|
max_in_flight
|
int | None
|
Maximum number of patches submitted to the
executor and not yet finished. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
list[Patch]
|
Patches with |
list[Patch]
|
the patcher's anchor schedule. |
Examples:
Thread pool over a raster, failing fast on any error::
outputs = parallel_map(patcher, field, model, n_workers=8)
Restartable process-pool job that tolerates bad tiles::
patcher = SpatialPatcher(..., on_error="skip")
journal = PatchJournal("out/run.jsonl")
outputs = parallel_map(
patcher, field, model,
backend="process", journal=journal, on_error="skip",
)
Explicit start method::
parallel_map(patcher, field, model, backend="process",
mp_context="spawn")
Source code in packages/geotoolz-patcher/src/geopatcher/_src/runners.py
45 46 47 48 49 50 51 52 53 54 55 56 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 | |
geopatcher.run.prefetch_iterable(iterable, prefetch, *, stop=None)
¶
Return iterable with up to prefetch items read ahead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterable
|
Iterable[T]
|
The upstream items, read on a background thread. |
required |
prefetch
|
int
|
Read-ahead depth; |
required |
stop
|
Event | None
|
Optional stop event shared with the upstream iterator. The
prefetch iterator sets it on |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/prefetch.py
Dask ([dask])¶
geopatcher.run.to_delayed(patcher, field, operator=None, **kwargs)
¶
Return one Dask delayed task per patch.
Each task computes patcher.patch_at(field, anchor) (then
operator(patch) when given). The field is wrapped in a single
delayed handle shared by every task. Runner-level policies
(on_error, hooks, journal, cache, prefetch) do not apply — see
the module docstring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patcher
|
Any
|
A |
required |
field
|
Any
|
The |
required |
operator
|
Any | None
|
Optional callable mapped over each patch. |
None
|
**kwargs
|
Any
|
Forwarded to the patcher's key listing and |
{}
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/dask.py
geopatcher.run.to_dask_bag(patcher, field, **kwargs)
¶
Return a Dask bag with one element (and one partition) per patch.
Built as db.from_sequence(anchors, partition_size=1).map(...) with
the field and patcher passed as shared delayed handles, so — as in
to_delayed — the field enters the graph once and runner-level
policies do not apply.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/dask.py
Batches of patches¶
batch_split groups a raster field adapter's patches into fixed-size
PatchBatch tuples: the patches as one GeoArray with a patch batch
dim (one transform row per patch) and a (patch,) mask of the real ones
(ADR-013). The batch is NumPy; move it to JAX once with
batch.patches.to_jax() ([jax]), map a model over it with
geoarray.map_over, and hand the scored batches straight to
patcher.merge (or merge_to_field), which places each row from its
transform with the patcher's window weights and drops the padding.
unbatch does the placement alone, for code that wants Patch objects.
scored = [
PatchBatch(geoarray.map_over(patches.to_jax(), model, "patch").to_numpy(), valid)
for patches, valid in batch_split(patcher, field, batch_size=64)
]
mosaic = patcher.merge_to_field(scored, field) # GeoArray on the field's grid
A row whose pixel size or rotation differs from the target grid's raises
ValueError naming it: merging never resamples.
The grouping, padding and mask are pipekit-array's batch (a PatchBatch
has the shape of its Padded, (value, valid)), with
geoarray.stack_items stacking each patch's transform as a row.
geopatcher.run.PatchBatch
¶
Bases: NamedTuple
A batch of patches: one carrier and a mask of its real entries.
A NamedTuple, so JAX treats it as a pytree: jitting a step on a
whole batch compiles once per patch shape, whatever the patches'
positions or the mask.
Attributes:
| Name | Type | Description |
|---|---|---|
patches |
GeoArray
|
The patches as one |
valid |
ndarray
|
|
Example
for patches, valid in batch_split(patcher, field, batch_size=64): ... patches = patches.to_jax() # (64, 4, 256, 256), once ... scores = geoarray.map_over(patches, model, "patch") ... loss = masked_mean(scores.data, valid)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
geopatcher.run.batch_split(patcher, field, *, batch_size, pad_last=True)
¶
Yield the patches of patcher.split(field) as fixed-size batches.
Groups consecutive patches into batches of exactly batch_size; only
the final batch can be short, and pad_last decides what happens to
it. The grouping, padding and mask are pipekit_array.batch's (with
geoarray.stack_items stacking the transform rows), the rule every
padded batch in the stack follows. Every patch must be a GeoArray
(any raster field adapter) or a DataArray that reads as a grid
(GeoArray.from_xarray), of one shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patcher
|
Any
|
Any patcher exposing |
required |
field
|
Any
|
The field adapter to split; passed through to
|
required |
batch_size
|
int
|
Number of patches per batch. Must be positive. |
required |
pad_last
|
bool
|
If |
True
|
Yields:
| Type | Description |
|---|---|
PatchBatch
|
One |
PatchBatch
|
batch (padded or not, per |
PatchBatch
|
a multiple of |
PatchBatch
|
installed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
GridMismatchError
|
The patches of one batch differ in CRS. |
TypeError
|
A patch is not a raster carrier (a plain array, a
|
Example
batches = list(batch_split(patcher, field, batch_size=16)) batches[0].patches.dims ('patch', 'band', 'y', 'x')
Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
geopatcher.run.unbatch(batch, data=None, *, patcher, domain)
¶
Turn a batch, or a model's output for it, back into Patch objects.
Padding entries (valid == False) are dropped, so a padded final
batch gives fewer patches than its length. Each patch is placed from its
transform row against domain's grid: its anchor and indices are what
patcher.geometry gives that pixel offset, and its weights are
patcher.window's, so
patcher.merge(unbatch(...), domain) reassembles the field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
PatchBatch
|
A |
required |
data
|
Any | None
|
Optional replacement payload, typically the model output for
the batch: a |
None
|
patcher
|
Any
|
The patcher that split the field (its geometry must be
|
required |
domain
|
Any
|
The field's domain ( |
required |
Returns:
| Type | Description |
|---|---|
list[Patch]
|
One |
list[Patch]
|
that keeps the patch's spatial shape comes back as a |
list[Patch]
|
the patch's grid (a per-pixel output with a new band count drops |
list[Patch]
|
the stale per-band attrs); any other row stays a bare array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The patcher's geometry is not
|
Example
place = dict(patcher=patcher, domain=field.domain) outs = [ ... p ... for b in batch_split(patcher, field, batch_size=16) ... for p in unbatch(b, model(b.patches), **place) ... ] merged = patcher.merge(outs, field.domain)
Source code in packages/geotoolz-patcher/src/geopatcher/_src/batching.py
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 | |
geopatcher.run.stack_patches(patches, attr='data')
¶
Stack a Patch collection's per-patch attr into a single ndarray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patches
|
Iterable[Any]
|
Iterable of |
required |
attr
|
str
|
Which patch attribute to stack. Default |
'data'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
and |
ndarray
|
agrees on. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/stacking.py
Caching and random access¶
geopatcher.run.PatchCache
dataclass
¶
A local, content-addressed directory cache of read patches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str | Path
|
Directory the cache writes entries under (created if absent). The layout is fsspec-friendly (two-level shard) but v1 is a local filesystem only. |
required |
max_bytes
|
int | None
|
Soft cap on the cache size. When a write takes the
total over it, least-recently-used entries (by |
None
|
field_id
|
str | None
|
Explicit source identity for in-memory fields that
have none (a |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
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 | |
build_patch(payload, anchor, indices)
¶
Rebuild a Patch from a stored payload at anchor/indices.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
clear()
¶
Delete every cached entry; reset hit / miss counters.
An entry whose file cannot be deleted (open in another process
on Windows, a flaky network filesystem) stays tracked, so
stats and eviction keep counting the bytes still on disk.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
config_id_for(geometry, window)
staticmethod
¶
JSON config key from the geometry + window (byte-affecting axes).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
field_id_for(field)
¶
Resolve the identity of everything field reads.
The result is "<source>|<json>":
source— this cache's explicitfield_id, else the first of: aurl, the reader / field file paths (realpath+st_mtime_ns+st_sizeof every path), theencoding["source"]file of an xarray-backed field — looked up on the field and then on itsreader/da/array. A field exposing only acache_id()uses that as its source. A plainurlhas no version, so an object overwritten in place is not detected; adapters that can ask the store cheaply (CogField: an ETag / size from a HEAD) fold that intocache_id().json— the field'scache_id()(per-adapter identity, e.g.CogField's store / path /ifd_indexorReprojectingRasterField'sdst_crs/resolution/resampling), the domain (CRS, transform, shape, dtype, or a digest of the grid coordinates) and the reader's band selection (indexes) and boundlessfill_value.
cache_id() is trusted as-is: it must return a non-empty
str (anything else raises TypeError) that changes whenever
the patches the field reads could change; PatchCache cannot
verify that.
An xarray-backed field also keys on its variable name (two
variables of one file share everything else). An adapter whose
cache_id() raises UnstableIdentityError (an in-memory
object store) needs an explicit field_id.
In-memory fields with no source identity raise, since caching
against nothing would silently serve stale data — including a
field that wraps an unnamed in-memory reader, whatever its
cache_id() says.
Examples:
>>> cache = PatchCache("./.cache")
>>> cache.field_id_for(RasterField(RasterioReader("a.tif")))
'path:/data/a.tif:1700000000000000000:4096|{"adapter": null, ...}'
>>> PatchCache("./.cache", field_id="scene").field_id_for(
... RasterField(geotensor)
... )
'scene|{"adapter": null, "domain": {...}, "read": {...}}'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
get(field_id, config_id, anchor)
¶
Return the stored payload for a key, or None on a miss.
An entry that cannot be decoded — zero-byte, truncated, not a
zip, or missing the layout's fields — is a miss and is deleted,
so the following put rewrites it.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
put(field_id, config_id, anchor, patch)
¶
Store patch's reconstructable payload under its key.
Always (re)writes the entry — put follows a miss, so an
existing file at the key is one get could not use. The write
is atomic: a unique temp file in the shard directory is
published with os.replace. An entry larger than
max_bytes is discarded with a RuntimeWarning instead.
Raises:
| Type | Description |
|---|---|
TypeError
|
The patch carrier cannot be rebuilt bit-identically
from disk (see |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
stats()
¶
Return {"hits", "misses", "bytes", "entries"} for the cache.
bytes / entries are the incremental tally (see
max_bytes) — O(1), no directory walk.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
geopatcher.run.UnstableIdentityError
¶
Bases: ValueError
A field's cache_id() cannot name what it reads stably.
Raised by an adapter whose source has no identity that survives the
process (an in-memory object store, say). PatchCache then requires
an explicit field_id and keys on it plus partial — the rest
of the adapter's identity (IFD, reprojection parameters, …).
Source code in packages/geotoolz-patcher/src/geopatcher/_src/cache.py
geopatcher.run.IndexedPatchView
dataclass
¶
Bases: Sequence[Patch]
Integer-indexed view over a patcher's anchors.
Wraps a (patcher, field) pair as a Sequence[Patch] —
supports len(view), view[i], for p in view, and negative
indexing. view[i] is bit-identical to the i-th patch
patcher.split(field) yields.
Cache accesses are guarded by a threading.Lock, so a view shared
across threads (e.g. a torch DataLoader with num_workers=0 plus
background threads) is safe.
The view pickles, so it can be shipped to worker processes under
any start method — spawn (the macOS / Windows default),
forkserver (the Linux default from Python 3.14), fork, and
Grain's multiprocess RandomAccessDataSource. The anchor list and
the bound PatchCache identity travel with it; the lock is
recreated and the in-memory cache=True entries are dropped, so
each worker starts with its own empty cache (entries are never
shared back to the parent). The patcher and the field must pickle
too — every built-in Field adapter does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patcher
|
Any
|
A patcher exposing |
required |
field
|
Any
|
The |
required |
cache
|
bool | Any
|
If |
False
|
preload
|
bool
|
If |
False
|
cache_size
|
int | None
|
Optional LRU bound on the number of cached patches.
|
None
|
patcher_kwargs
|
dict[str, Any]
|
Extra keyword arguments forwarded to every
|
field(default_factory=dict)
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/indexed.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 | |
anchors
property
¶
The materialised anchor list this view dispatches into.
Same sequence patcher.anchors(field) (or
patcher.patch_anchors(field) when the patcher has it) returned
at construction time; exposed so callers can correlate view[i] with the
underlying anchor without going through patch_at.
clear_cache()
¶
Drop any cached patches; subsequent reads go back through patch_at.