Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Design Decisions

This page records the locked-in design decisions that shape geopatcher’s public API. Each one was an open question in the design phase; once decided, the rationale lives here so future contributors can answer “why this and not that?” without rerunning the discussion.

The format is loose ADR: Decision → Context → Consequences → Alternatives considered. Decisions are numbered in the order they were locked in and listed in that order; existing decisions do not change without a follow-up entry that supersedes them.


ADR-001 — Patcher.split returns Iterator[Patch]

Decision. All four patchers (SpatialPatcher, AsyncSpatialPatcher, TemporalPatcher, SpatioTemporalPatcher) expose split as an iterator, not a list. Eager materialisation is one list(patcher.split(field)) call away when needed.

Context. The patcher walks anchors placed by the sampler and reads each neighborhood out of the field. For large fields the natural mode is one patch at a time — the field has lazy Field.select, so a generator yields patches as they’re read rather than holding them all in memory.

Consequences.

Alternatives considered.


ADR-002 — Disk-backed aggregations use Zarr

Decision. Streaming aggregations that need an out-of-RAM target (spatial.aggregation.OverlapAdd(streaming=True, target_path=...), future spatial.aggregation.InvVarWeightedMean(streaming=True, ...), etc.) write to a framework-managed Zarr store by default.

Context. The streaming asymmetry (see §4 of the scaling.md design note in the planning archive; not shipped with these docs) is on the output side: the input field already has a lazy Field.select, so input scales as long as split returns an iterator. Output preallocability is the bottleneck. A disk-backed accumulator solves it.

Zarr was picked over memmap, HDF5, and “bring your own store”:

Consequences.

Alternatives considered.


ADR-003 — MatchedField is a composite Field, not a new top-level type

Decision. Co-located patching across N sources lives in geopatcher.matched.MatchedField, which satisfies the existing Field Protocol via its primary’s domain, plus three matched patchers (MatchedSpatialPatcher, MatchedTemporalPatcher, MatchedSpatioTemporalPatcher) that split and merge it. Concretely:

Context. The cross-package query→matchup→patch design (query → matchup → patch design) introduces matchups between LEO, GEO, vector, and point-cloud sources. The patching side has to read co-located neighborhoods across these heterogeneous sources without duplicating coregistration logic (which lives in geotoolz) and without forcing geopatcher’s framework-free core to depend on pipekit.

The composite-Field approach satisfies all three constraints: every existing sampler, geometry and window places anchors and indexers on a MatchedField unchanged (they only see the primary’s domain); the heavy alignment work lives in geoops.geom.coregister.* pipekit_ops.Operators; geopatcher’s only new typing dependency is the standard-library Callable (since pipekit_ops.Operator IS callable).

Consequences.

Alternatives considered.


ADR-004 — Coordinate-aware temporal patching is opt-in; stride-1 only in v0.1

Context. The temporal stack works in integer index space: temporal.sampler.Sampler.anchors(time_len) → Iterable[int], temporal.geometry.Geometry.window( time_len, anchor) → slice. This is correct and fast for in-memory arrays at a known cadence. It breaks down for ARCO-ERA5-style workloads where the natural specification is physical — “a 9-hour lookback at the source cadence, whatever that is” — and the data cadence is a property of the store, not of the caller. A TimeStencil-based layer (ported from neuralgcm/terrax) expresses windows in coordinate units and validates that the requested step exactly tiles the source grid.

Decision. Extend the temporal protocol via two ClassVar capability flags:

Coordinate-aware subclasses (temporal.geometry.StencilGeometry, temporal.sampler.StencilSampler) set the flag to True. TemporalPatcher reads the flag from both components; when either is True, every public method that takes series (split, asplit, patches_at, anchors, n_anchors) also requires a coord= keyword: a 1-D monotonic-ascending coordinate array along time_axis. Missing coord= raises ValueError at the entry point — before the sampler is invoked — so mis-wiring fails loudly.

Dispatch inside _patches_for_anchor:

The sampler always returns int anchors (indices into coord, not coordinate values), so the rest of _patches_for_anchor, the patch carrier, and the hook contract are byte-identical to the integer path.

v0.1 stride-1 constraint. temporal.window.Window.weights(geometry, length) and temporal.aggregation.Aggregation.merge(patches) both assume contiguous integer index ranges (s.stop - s.start is the realised window length). A stencil with step > source_step would yield a strided slice, silently breaking both. temporal.geometry.StencilGeometry.__post_init__ raises when source_step is supplied and stencil.step / source_step != 1; window_coord re-checks the resolved slice’s stride at resolve time as a belt-and-braces guard for callers that omit source_step. Strided reads are deferred to v0.2 — they need temporal.window.Window.weights and temporal.aggregation.Aggregation.merge to take a realised-length argument.

Hook payload extension. PatcherHook.on_patch_start and on_patch_done gain an optional trailing coord_value (the resolved coord[anchor], or None for the integer path). _dispatch trims trailing args to the callback’s positional arity so pre-extension hooks written as on_patch_start(self, anchor) keep working without RuntimeWarnings.

Consequences.

Alternatives considered.

See also. GitHub issue jejjohnson/geopatcher#56 (the design doc and tracking issue for this work); the upstream neuralgcm/terrax xreader.stencils module (Apache-2.0, © Google LLC) from which the stencil math was ported.


ADR-005 — Random access is a Sequence wrapper, cache lives on the view

Superseded in part by ADR-008: IndexedPatchView now lives in geopatcher.run, not at the root.

Context. The patcher’s canonical surface is SpatialPatcher.split → Iterator[Patch] (ADR-001). xrpatcher’s XRDAPatcher[i] API gives random-access by integer index, and xrpatcher also bundles in-memory caching (cache=True/preload=True) for ML loaders that re-read the same anchors per epoch. Migrants want the same ergonomics without losing the iterator-first contract; the question is where the random-access surface lives and what protocol it speaks.

Decision. Add geopatcher.run.IndexedPatchView:

Alongside the view, the PR ships three sympathetic conveniences:

Precursor change: XarrayField.select now returns the bare xarray.DataArray rather than another XarrayField. This brings it in line with RasterField.select → GeoTensor (select returns the natural data payload, not another field wrapper) and unblocks spatial.aggregation.OverlapAdd.merge, which np.asarray’s every patch’s data.

Consequences.

Alternatives considered.

See also. GitHub issue jejjohnson/geopatcher#60 (the design doc and tracking issue for this work); the upstream xrpatcher (the migration target); recipes/xarray-nd-patching.md for side-by-side migration; jejjohnson/geopatcher#24 for the deeper content-addressed cache; ADR-001 (iterator-first split) and ADR-004 (coordinate-aware temporal).


ADR-006 — streaming_safe violations: configurable, warn by default

Renumbered from ADR-003 — that number had accidentally been assigned twice. References to “ADR-003” for the streaming_safe / set_strict decision (e.g. in the get_strict docstring) resolve here; ADR-003 now refers only to the MatchedField decision below.

Decision. When a caller passes a streaming_safe = False aggregation into a context that expects streaming (Patcher.merge, streaming OverlapAdd, future PatchJournal jobs), the framework emits a RuntimeWarning by default. A module-level toggle promotes the warning to a hard RuntimeError for callers (CI, batch jobs) that want to fail fast.

Toggle API:

import geopatcher as gp

gp.observe.set_strict(True)      # promotes streaming_safe warnings to errors
gp.observe.set_strict(False)     # back to warn-only (default)
gp.observe.get_strict()          # bool

Environment variable equivalent: GEOPATCHER_STRICT=1 (read once at import time; runtime set_strict() overrides it).

Context. Today _warn_if_unsafe_streaming always emits a warning. That is right for interactive notebook work — the user sees the warning and either ignores it (the in-RAM merge fits fine) or swaps in a streaming-safe alternative. It is wrong for batch / CI contexts where silently falling back to RAM defeats the streaming guarantee that called the job into existence.

Three options were on the table:

  1. Hard error. Loud, but breaks every quick-iteration use of spatial.aggregation.Median / spatial.aggregation.Learned in a notebook.

  2. Warning only. What we have. Quiet failures in batch jobs.

  3. Configurable. Best of both — default-permissive, opt-in strict.

Consequences.

Alternatives considered.


ADR-007 — merge returns the raw aggregation output; merge_to_field rebuilds the Field

Partly superseded by ADR-009: the output’s band axes come from the patches, and merge_to_field accepts a changed band count on raster fields.

Carrier amended by ADR-012: a raster with_data returns a geoarray.GeoArray, not a GeoTensor.

Decision. SpatialPatcher.merge(patches, domain) keeps returning whatever the aggregation’s 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. A sibling, SpatialPatcher.merge_to_field(patches, field), returns field.with_data(merged): a GeoTensor for RasterField (transform, CRS, fill_value_default and attrs of the source), a RioXarrayField / XarrayField wrapping the rebuilt DataArray for the xarray adapters. It raises TypeError for a dict output, a non-array output, or an array whose shape is not field.domain.shape. MatchedSpatialPatcher.merge_to_field(patches, mfield) does the same per source, wrapping every source through the primary’s with_data (each secondary was coregistered onto the primary’s grid). The temporal and spatio-temporal patchers have no field-shaped merge output and get no merge_to_field.

merge_to_field and merge_to_xarray share one dtype rule: the merged values are cast back to the source dtype when every value is representable in it — finite, integral and in range for an integer / bool source, no finite overflow for a floating one. Otherwise the aggregation’s dtype is kept (a fractional mean or a NaN fill on a uint16 source stays float64).

Context. The Field protocol docstring said with_data was “used by Aggregation.merge to rebuild a global field”, and the matched-patcher docstring said merge returns “typically a GeoTensor”. Neither was true: every aggregation returns a bare float64 array and only merge_to_xarray called with_data (#194). Two fixes were on the table — make merge wrap its output through with_data (option A in #194), or keep merge raw and fix the docs (option B).

Consequences.

Alternatives considered.

See also. #194; ADR-005 (merge_to_xarray).


ADR-008 — Public namespaces are organised by task, one home per name

Status. Accepted.

Context. The root namespace had grown to 112 names, mostly every axis twice — once at the root and again in its family module, both with a Spatial / Temporal name prefix — and the public modules mixed concepts (spatial, time, fields, matched) with plumbing (runners, dask, jax, hooks, objstore, cog). Users had no map from “what am I trying to do” to “where is it”.

Decision.

Consequences. Every import of an axis changes (from geopatcher import spatial then spatial.window.Hann()), and configs saved with the old bare class names must be re-saved. In return each name is findable from its task, and the root is short enough to read.


ADR-009 — The domain fixes the grid, the patches fix the bands

Supersedes the shape rule of ADR-007.

Carrier amended by ADR-012: the raster carrier it names is now geoarray.GeoArray (fill_value, not fill_value_default).

Status. Accepted.

Context. Every dense aggregation sized its accumulator from domain.shape. A per-patch operator that changes the band count — NDVI turns a (4, 256, 256) chip into a (256, 256) map, a model returns K class scores — was then numpy-broadcast into the domain’s bands: merging NDVI onto a 4-band domain returned four identical copies of the index, silently. merge_to_field refused the honest shape, so the documented workaround was a hand-built one-band “output grid” domain, and the pipekit MergePatches (then named Stitch) returned a bare array where its input chips were GeoTensors.

Decision.

Consequences. MergePatches(domain=field.domain) is right for every operator, band-collapsing or not, and its output is a georeferenced GeoTensor that writes straight to a COG. Code that relied on the broadcast (SoftVote (K, h, w) chips on a (band, H, W) domain gave (band, H, W) copies; it now gives one (H, W) map) sees the patches’ shape instead. A patch with more axes than the domain no longer raises in OverlapAdd: its leading axes are kept.


ADR-010 — Tapered windows sample their taper at the pixel centres

Status. Accepted.

Context. spatial.window.Hann and spatial.window.Tukey were SciPy’s periodic windows, hann(n, sym=False) / tukey(n, alpha, sym=False), sampled at t = k / n. That puts w[0] = 0 on every patch’s first row and column. A pixel that only one patch covers there — the scene’s first row and column under any regular sampler, and every seam with step == size — had zero accumulated weight, so OverlapAdd and WeightedSum wrote it as the fill (NaN): a padded Hann merge of a (450, 400) scene lost 849 pixels. The docs told users to crop the ring.

Decision.

Alternatives considered.

Consequences. Every covered pixel keeps its value: the 849 NaNs of the example are gone and step == size reproduces the field. The weights change slightly (e.g. the 8-sample Hann was [0, 0.146, …], now [0.038, 0.309, …]), so merged outputs of overlapping tapered patches differ in the last digits from earlier releases; a window’s config is unchanged.


ADR-011 — A masked read keeps the carrier of a successful one

Carrier amended by ADR-012: the raster placeholder is a NaN geoarray.GeoArray (fill_value NaN), built on a raster domain whose grid has a CRS.

Status. Accepted.

Context. Under on_error="mask" a failed read became a bare np.full(shape, nan) patch. A per-patch operator that reads .transform, .crs or .rio failed on exactly the patches that already failed once, and the matched patchers told a placeholder apart from a real chip by its type (type(data) is np.ndarray and all NaN), which a source that reads into plain arrays could not distinguish.

Decision.

Alternatives considered.

Consequences. Operators run on placeholders unchanged and merge_to_field stitches them like any patch. Code that detected a placeholder by isinstance(data, np.ndarray) must read patch.masked.


ADR-012 — Raster fields take a geoarray.RasterSource; patches are GeoArray

Amends the raster carrier named in ADR-007, ADR-009 and ADR-011.

Status. Accepted (the workspace-wide switch to geoarray.GeoArray).

Context. The raster path was georeader’s: RasterField wrapped any GeoData, its domain was the reader (GeoDataBase, re-exported as RasterDomain), patches and merged outputs were GeoTensors. The stack now has one carrier, geoarray.GeoArray (immutable, hashable attrs, NumPy or JAX data, fill None by default), with lazy readers implementing geoarray.RasterSource.

Decision.

Alternatives considered.

Consequences. Breaking for code that built RasterField(GeoTensor) / RasterField(RasterioReader(...)) (wrap with the adapter), read patch.data.values / .transform.c (use np.asarray / .grid.affine), mutated attrs, or wrote a custom raster domain with transform / shape / crs (add a grid). A source without a fill can no longer be read past its edge (there is no value to pad with).

Amendment — fills an output can hold. geoarray.GeoArray refuses a fill_value its dtype cannot hold (NaN or -9999.0 in uint8), and a fill of None means “no nodata”, so the patcher never pads or rewraps with a value the chip would read as data:


ADR-013 — A batch of patches is one GeoArray with a patch batch dim

Replaces BatchedPatch as what batch_split yields (#529); stitch reads it back in #530. Design: geostack’s geoarray design (stage 5 of the running example, gate GA-G15).

Status. Accepted; implemented in #529. unbatch takes the patcher= and domain= the transform rows are placed against (anchor and indices from a Rectangular geometry, weights from the window axis).

Context. batch_split yields BatchedPatch: the patch payloads stacked on a leading axis, next to Python lists of per-patch anchors, indices, weights and carrier templates. Three things are wrong with it.

  1. It moves data to JAX behind the caller’s back (jnp = np when JAX is missing, jnp.stack when it is present), the silent promotion geotoolz-array 0.3 deprecates (GA-C1).

  2. Its metadata is static pytree data compared by identity, so a jitted function taking a whole batch retraces for every batch. The docstring says to pass batch.data instead, which drops the georeference.

  3. It is geoarray.map_over built by hand. geotoolz-array 0.3 has the real thing: a carrier whose leading dims are batch dims, with one transform row per item, mapped in one jax.vmap.

The batch geoarray already knows how to carry:

batch: GeoArray                       (patch, band, y, x)
  data       (patch, band, y, x)      leaf: NumPy, or JAX after to_jax()
  transform  (patch, 6)               leaf: one row per patch → batch dim
  dims, coords, crs, fill, attrs      static: equal for every full batch
        │
        │ geoarray.map_over(batch, model, "patch")
        ▼
one trace for every full batch, whatever the patches' positions (GA-G15)

What it cannot carry is the per-patch validity of a padded final batch, and that is where the options differ.

Decision.

  1. The batch is a GeoArray with patch as its batch dim.

    • data is (patch, *patch_dims) and transform is (patch, 6).

    • Every other field is static and equal across full batches: the patch dims, the field’s coordinates sliced like each patch (band names), the CRS, the fill and the attrs.

    • Every patch of one batch must have the same shape (as today).

  2. The padding mask is a leaf next to the batch, not inside it.

    • batch_split yields PatchBatch(patches: GeoArray, valid: ndarray), a NamedTuple: JAX treats it as a pytree, and jitting a step on it does not retrace when the mask changes.

    • valid is (patch,) bool, True for real patches.

  3. Padding rows copy the last real patch, its data and its transform row, with valid=False.

    • Their values and transforms are finite, so a masked loss and its gradient are finite (the same rule as pad_points, GA-G16).

    • Their statistics look like real data, which matters to normalisation layers that see the whole batch.

    • Today’s padding is zeros.

  4. NumPy in, NumPy out.

    • The batch is NumPy whatever is installed; the caller crosses to JAX once, with batch.patches.to_jax().

    • The jnp = np fallback goes.

    • The [jax] extra depends on geotoolz-array[jax], not bare jax.

  5. The dim is named patch, not sample.

    • Each item carries its own place on the ground (its transform row); patch says that.

    • sample stays the name of an item of an ML dataset, which may batch patches from several scenes (pipekit-train’s level, GA-B3).

  6. Raster fields batch; the others do not.

    • GeoArray patches (every raster field) and DataArray patches that read as a grid (geoarray.from_xarray) give a PatchBatch.

    • Patches of any other carrier (plain arrays, non-grid DataArrays) raise TypeError naming stack_patches. BatchedPatch still batched them, deprecated, in 0.14 and 0.15; it is removed in geotoolz-patcher 0.16.

  7. Same call, new yield type.

    • batch_split(patcher, field, *, batch_size, pad_last=True) keeps its signature and yields PatchBatch.

    • unbatch accepts a PatchBatch, placing patches by their transform rows.

    • The anchors, indices and weights lists are not carried. stitch (#530) recomputes each patch’s offset from its transform row against the target grid, and the window weights from the patcher’s window axis.

    • Breaking, with a BREAKING CHANGE: footer.

for batch, valid in batch_split(patcher, field, batch_size=64):  # PatchBatch
    patches = batch.to_jax()                         # (64, 4, 256, 256), once
    scores = geoarray.map_over(patches, model, "patch")  # one trace per shape
    loss = masked_mean(scores.data, valid)           # padding rows ignored

Alternatives considered.

Consequences.


How to add a decision

  1. Open a PR with the proposed addition. The PR description argues the decision; the diff adds the ADR to this page.

  2. Decisions are not changed in place. A new ADR supersedes an older one with a > Supersedes ADR-NNN note at the top and the superseded ADR keeps a > Superseded by ADR-MMM line.

  3. Cross-reference the affected issues and design docs. Each ADR should be reachable from the issue or design discussion it resolved.