Skip to content

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).

from geopatcher import RasterField, SpatialPatcher, spatial

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" preserves the historical fail-fast behavior, "skip" logs and omits the failed anchor, "mask" emits a NaN-valued patch for the failed anchor, and "retry" retries matching exceptions up to max_retries before logging and skipping.

'raise'
max_retries int

Number of retries when on_error is "retry".

0
retry_on tuple[type[BaseException] | str, ...]

Exception classes or class names that should be retried. Defaults to I/O-shaped failures (OSError, TimeoutError) so programmer errors are not retried unless explicitly requested. A name matches any class in the exception's MRO, by bare name ("OSError") or module.qualname ("rasterio.errors.RasterioIOError"), so it keeps the subclass semantics of the class it names.

(OSError, TimeoutError)
capture_traceback bool

If True (default), each PatchErrorRecord includes a formatted traceback. Set to False to skip formatting — useful for high-volume "skip" workloads where thousands of expected failures would otherwise inflate errors with megabytes of formatted frames.

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
@dataclass(eq=False)
class SpatialPatcher(_SpatialPatcherBase):
    """The four-axis spatial Patcher.

    Args:
        geometry: How a neighborhood is shaped around an anchor.
        sampler: Where anchors go.
        window: Boundary treatment / per-pixel weights.
        aggregation: Local → global merge strategy.
        on_error: Patch-read error policy. ``"raise"`` preserves the
            historical fail-fast behavior, ``"skip"`` logs and omits the
            failed anchor, ``"mask"`` emits a NaN-valued patch for the
            failed anchor, and ``"retry"`` retries matching exceptions up to
            `max_retries` before logging and skipping.
        max_retries: Number of retries when `on_error` is ``"retry"``.
        retry_on: Exception classes or class names that should be retried.
            Defaults to I/O-shaped failures (`OSError`, `TimeoutError`) so
            programmer errors are not retried unless explicitly requested.
            A name matches any class in the exception's MRO, by bare name
            (``"OSError"``) or ``module.qualname``
            (``"rasterio.errors.RasterioIOError"``), so it keeps the
            subclass semantics of the class it names.
        capture_traceback: If ``True`` (default), each `PatchErrorRecord`
            includes a formatted traceback. Set to ``False`` to skip
            formatting — useful for high-volume ``"skip"`` workloads
            where thousands of expected failures would otherwise inflate
            ``errors`` with megabytes of formatted frames.

    ``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)
    """

    def split(
        self,
        field: Field,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Iterator[Patch]:
        """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).
        """
        return self._split_anchors(
            field,
            None,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )

    def _split_anchors(
        self,
        field: Field,
        anchors: Iterable[Any] | None,
        *,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
        policy: ReadPolicy | None = None,
    ) -> Iterator[Patch]:
        """`split` over explicit ``anchors`` (``None`` walks the sampler).

        `two_pass` hands both passes the same materialised anchor list so
        an unseeded sampler cannot place the second pass differently, and
        the first pass's ``policy`` so both record into one ``errors``.
        """
        _validate_backpressure(max_in_flight, max_in_flight_bytes)
        if policy is None:
            policy = self._start_split()
        # Shared with the prefetch iterator: its ``close()`` (or its
        # collection) sets ``stop``, which interrupts a producer blocked
        # in a backpressure wait.
        stop = Event()
        return prefetch_iterable(
            self._walk(
                field,
                anchors,
                policy=policy,
                hooks=hooks,
                journal=journal,
                cache=cache,
                backpressure=_Backpressure(max_in_flight, max_in_flight_bytes, stop),
            ),
            prefetch,
            stop=stop,
        )

    def _walk(
        self,
        field: Field,
        anchors: Iterable[Any] | None,
        *,
        policy: ReadPolicy,
        hooks: Iterable[PatcherHook] | None,
        journal: Any | None,
        cache: Any | None,
        backpressure: _Backpressure,
    ) -> Iterator[Patch]:
        domain = field.domain
        if anchors is None:
            anchors = self.sampler.anchors(domain, self.geometry)
        reader = self._chip_reader(field, domain, cache, aio=False)
        yield from walk(
            anchors,
            reader.units,
            policy=policy,
            backpressure=backpressure,
            hooks=hooks,
            journal=journal,
        )

    def patch_at(
        self,
        field: Field,
        anchor: Any,
        *,
        cache: Any | None = None,
        field_id: str | None = None,
    ) -> Patch:
        """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.

        Args:
            field: The `Field` to read from.
            anchor: An anchor in the same format the sampler emits
                (e.g. ``(row, col)`` for raster, ``dict`` for grid).
                Typically obtained from
                ``patcher.anchors(field)[index]``.
            cache: Optional `PatchCache`. When set, a cache hit returns
                the stored patch without touching the source; a miss
                reads then stores it.
            field_id: ``cache.field_id_for(field)`` resolved once by the
                caller and reused for every anchor (`IndexedPatchView`
                does this). Without it each call re-derives the identity,
                which for `CogField` is a ``HEAD`` per patch.

        Returns:
            A single `Patch` bit-identical to the one ``split`` would
            yield for the same anchor.
        """
        domain = field.domain
        base_weights = _safe_base_weights(self.window, self.geometry)
        boundary = getattr(self.geometry, "boundary", "drop")
        cache_ctx = self._cache_context(cache, field, field_id=field_id)
        cached = self._cached_patch(cache_ctx, domain, anchor)
        if cached is not None:
            return cached
        patch = _build_patch(
            field, domain, anchor, self.geometry, base_weights, boundary
        )
        self._store_patch(cache_ctx, anchor, patch)
        return patch

    def merge_to_field(
        self,
        patches: Iterable[Any],
        field: Field,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> Any:
        """`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.

        Args:
            patches: Iterable of patches to merge.
            field: The `Field` the patches came from; must expose
                ``with_data``.
            hooks: Optional observability hooks forwarded to `merge`.

        Returns:
            ``field.with_data(merged)``.

        Raises:
            TypeError: If ``field`` has no ``with_data``, if the aggregation
                returns a ``dict`` (`spatial.aggregation.MeanStd`,
                `spatial.aggregation.InvVarWeightedMean`, `spatial.aggregation.ByIndex`,
                …) or anything without an array ``shape``, or if the output is
                not on the field's grid (its trailing ``(H, W)`` differs from
                the domain's, or — on an xarray field — any axis does).

        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)
        """
        with_data = _require_with_data(field, "merge_to_field")
        patches = expand_batches(patches, self, field.domain)
        merged = _merge_with_hooks(
            self.aggregation, patches, field.domain, hooks, stacklevel=2
        )
        values = _field_values(
            merged,
            self.aggregation,
            shape=_domain_shape(field.domain),
            dtype=_source_dtype(field),
            caller="merge_to_field",
            bands_may_change=_is_raster_field(field),
        )
        values, fill = _merge_nodata(
            values,
            self.aggregation,
            shape=_domain_shape(field.domain),
            dtype=_source_dtype(field),
            source_fill=_source_fill(field),
        )
        return _with_nodata(with_data(values), fill)

    def merge_to_xarray(
        self,
        patches: Iterable[Any],
        field: Field,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> Any:
        """`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.

        Args:
            patches: Iterable of patches to merge.
            field: The `Field` the patches came from. Must expose
                `with_data(array) -> Field` returning a wrapper that
                exposes the rebuilt array via a `.da` attribute — i.e.
                an `XarrayField` (or equivalent).
            hooks: Optional observability hooks forwarded to `merge`.

        Returns:
            ``xarray.DataArray`` carrying the merged values and the
            original coords.

        Raises:
            TypeError: If ``field`` does not expose `with_data`, if the
                aggregation returns a ``dict`` (or anything that is not an
                array on the domain grid), or if the wrapper returned by
                `with_data` has no `.da` attribute.
        """
        with_data = _require_with_data(field, "merge_to_xarray")
        patches = expand_batches(patches, self, field.domain)
        merged = _merge_with_hooks(
            self.aggregation, patches, field.domain, hooks, stacklevel=2
        )
        rewrapped = with_data(
            _field_values(
                merged,
                self.aggregation,
                shape=_domain_shape(field.domain),
                dtype=_source_dtype(field),
                caller="merge_to_xarray",
            )
        )
        if not hasattr(rewrapped, "da"):
            raise TypeError(
                f"{type(field).__name__}.with_data must return a wrapper "
                "exposing the rebuilt array via `.da` (got "
                f"{type(rewrapped).__name__}). XarrayField is the canonical "
                "implementation."
            )
        return rewrapped.da

    def to_delayed(self, field: Field, operator: Any | None = None) -> list[Any]:
        """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`.
        """
        from geopatcher._src.dask import to_delayed

        return to_delayed(self, field, operator)

    def to_dask_bag(self, field: Field) -> Any:
        """Build a Dask bag with one item (and one partition) per patch.

        Same per-patch tasks and policy caveats as `to_delayed`.
        """
        from geopatcher._src.dask import to_dask_bag

        return to_dask_bag(self, field)

    def reduce(
        self,
        field: Field,
        agg: SpatialAggregation,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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)
        """
        patches = self._split_anchors(
            field,
            None,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )
        return _merge_with_hooks(
            agg, _closing(patches), field.domain, hooks, stacklevel=2
        )

    def two_pass(
        self,
        field: Field,
        *,
        reduce_with: SpatialAggregation,
        apply: Callable[[Any, Any], Any],
        aggregation: SpatialAggregation | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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"],
                )
        """
        anchors = self.anchors(field)
        split_kwargs: dict[str, Any] = {
            "hooks": hooks,
            "prefetch": prefetch,
            "journal": journal,
            "cache": cache,
            "max_in_flight": max_in_flight,
            "max_in_flight_bytes": max_in_flight_bytes,
            "policy": self._start_split(),  # both passes record into one list
        }
        stats = _merge_with_hooks(
            reduce_with,
            _closing(self._split_anchors(field, anchors, **split_kwargs)),
            field.domain,
            hooks,
            stacklevel=2,
        )
        applied = (
            patch.with_data(apply(patch.data, stats))
            for patch in _closing(self._split_anchors(field, anchors, **split_kwargs))
        )
        return _merge_with_hooks(
            aggregation or self.aggregation,
            applied,
            field.domain,
            hooks,
            stacklevel=2,
        )

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
async def amerge(
    self,
    patches: AsyncIterable[Any] | Iterable[Any],
    domain: Any,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """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`.
    """
    patches = aexpand_batches(patches, self, domain)
    return await _amerge_with_hooks(
        self.aggregation, patches, domain, hooks, stacklevel=2
    )

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
def anchors(self, field: Field | AsyncField) -> list[Any]:
    """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``).
    """
    return list(self.sampler.anchors(field.domain, self.geometry))

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
async def asplit(
    self,
    field: AsyncField,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> AsyncIterator[Patch]:
    """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.
    """
    async for patch in self._asplit_anchors(
        field,
        None,
        hooks=hooks,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    ):
        yield patch

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
def get_config(self) -> dict[str, Any]:
    """Axes as ``{"class", "config"}`` envelopes; ``retry_on`` as qualified names.

    `geopatcher.config.from_config` rebuilds the patcher from
    ``axis_envelope(patcher)``.
    """
    return patcher_config(self)

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
def merge(
    self,
    patches: Iterable[Any],
    domain: Any,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """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.
    """
    patches = expand_batches(patches, self, domain)
    return _merge_with_hooks(self.aggregation, patches, domain, hooks, stacklevel=2)

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 Field the patches came from; must expose with_data.

required
hooks Iterable[PatcherHook] | None

Optional observability hooks forwarded to merge.

None

Returns:

Type Description
Any

field.with_data(merged).

Raises:

Type Description
TypeError

If field has no with_data, if the aggregation returns a dict (spatial.aggregation.MeanStd, spatial.aggregation.InvVarWeightedMean, spatial.aggregation.ByIndex, …) or anything without an array shape, or if the output is not on the field's grid (its trailing (H, W) differs from the domain's, or — on an xarray field — any axis does).

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
def merge_to_field(
    self,
    patches: Iterable[Any],
    field: Field,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """`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.

    Args:
        patches: Iterable of patches to merge.
        field: The `Field` the patches came from; must expose
            ``with_data``.
        hooks: Optional observability hooks forwarded to `merge`.

    Returns:
        ``field.with_data(merged)``.

    Raises:
        TypeError: If ``field`` has no ``with_data``, if the aggregation
            returns a ``dict`` (`spatial.aggregation.MeanStd`,
            `spatial.aggregation.InvVarWeightedMean`, `spatial.aggregation.ByIndex`,
            …) or anything without an array ``shape``, or if the output is
            not on the field's grid (its trailing ``(H, W)`` differs from
            the domain's, or — on an xarray field — any axis does).

    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)
    """
    with_data = _require_with_data(field, "merge_to_field")
    patches = expand_batches(patches, self, field.domain)
    merged = _merge_with_hooks(
        self.aggregation, patches, field.domain, hooks, stacklevel=2
    )
    values = _field_values(
        merged,
        self.aggregation,
        shape=_domain_shape(field.domain),
        dtype=_source_dtype(field),
        caller="merge_to_field",
        bands_may_change=_is_raster_field(field),
    )
    values, fill = _merge_nodata(
        values,
        self.aggregation,
        shape=_domain_shape(field.domain),
        dtype=_source_dtype(field),
        source_fill=_source_fill(field),
    )
    return _with_nodata(with_data(values), fill)

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 Field the patches came from. Must expose with_data(array) -> Field returning a wrapper that exposes the rebuilt array via a .da attribute — i.e. an XarrayField (or equivalent).

required
hooks Iterable[PatcherHook] | None

Optional observability hooks forwarded to merge.

None

Returns:

Type Description
Any

xarray.DataArray carrying the merged values and the

Any

original coords.

Raises:

Type Description
TypeError

If field does not expose with_data, if the aggregation returns a dict (or anything that is not an array on the domain grid), or if the wrapper returned by with_data has no .da attribute.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
def merge_to_xarray(
    self,
    patches: Iterable[Any],
    field: Field,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """`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.

    Args:
        patches: Iterable of patches to merge.
        field: The `Field` the patches came from. Must expose
            `with_data(array) -> Field` returning a wrapper that
            exposes the rebuilt array via a `.da` attribute — i.e.
            an `XarrayField` (or equivalent).
        hooks: Optional observability hooks forwarded to `merge`.

    Returns:
        ``xarray.DataArray`` carrying the merged values and the
        original coords.

    Raises:
        TypeError: If ``field`` does not expose `with_data`, if the
            aggregation returns a ``dict`` (or anything that is not an
            array on the domain grid), or if the wrapper returned by
            `with_data` has no `.da` attribute.
    """
    with_data = _require_with_data(field, "merge_to_xarray")
    patches = expand_batches(patches, self, field.domain)
    merged = _merge_with_hooks(
        self.aggregation, patches, field.domain, hooks, stacklevel=2
    )
    rewrapped = with_data(
        _field_values(
            merged,
            self.aggregation,
            shape=_domain_shape(field.domain),
            dtype=_source_dtype(field),
            caller="merge_to_xarray",
        )
    )
    if not hasattr(rewrapped, "da"):
        raise TypeError(
            f"{type(field).__name__}.with_data must return a wrapper "
            "exposing the rebuilt array via `.da` (got "
            f"{type(rewrapped).__name__}). XarrayField is the canonical "
            "implementation."
        )
    return rewrapped.da

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
def n_anchors(self, field: Field | AsyncField) -> int:
    """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.
    """
    return sum(1 for _ in self.sampler.anchors(field.domain, self.geometry))

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 Field to read from.

required
anchor Any

An anchor in the same format the sampler emits (e.g. (row, col) for raster, dict for grid). Typically obtained from patcher.anchors(field)[index].

required
cache Any | None

Optional PatchCache. When set, a cache hit returns the stored patch without touching the source; a miss reads then stores it.

None
field_id str | None

cache.field_id_for(field) resolved once by the caller and reused for every anchor (IndexedPatchView does this). Without it each call re-derives the identity, which for CogField is a HEAD per patch.

None

Returns:

Type Description
Patch

A single Patch bit-identical to the one split would

Patch

yield for the same anchor.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial/patcher.py
def patch_at(
    self,
    field: Field,
    anchor: Any,
    *,
    cache: Any | None = None,
    field_id: str | None = None,
) -> Patch:
    """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.

    Args:
        field: The `Field` to read from.
        anchor: An anchor in the same format the sampler emits
            (e.g. ``(row, col)`` for raster, ``dict`` for grid).
            Typically obtained from
            ``patcher.anchors(field)[index]``.
        cache: Optional `PatchCache`. When set, a cache hit returns
            the stored patch without touching the source; a miss
            reads then stores it.
        field_id: ``cache.field_id_for(field)`` resolved once by the
            caller and reused for every anchor (`IndexedPatchView`
            does this). Without it each call re-derives the identity,
            which for `CogField` is a ``HEAD`` per patch.

    Returns:
        A single `Patch` bit-identical to the one ``split`` would
        yield for the same anchor.
    """
    domain = field.domain
    base_weights = _safe_base_weights(self.window, self.geometry)
    boundary = getattr(self.geometry, "boundary", "drop")
    cache_ctx = self._cache_context(cache, field, field_id=field_id)
    cached = self._cached_patch(cache_ctx, domain, anchor)
    if cached is not None:
        return cached
    patch = _build_patch(
        field, domain, anchor, self.geometry, base_weights, boundary
    )
    self._store_patch(cache_ctx, anchor, patch)
    return patch

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
def reduce(
    self,
    field: Field,
    agg: SpatialAggregation,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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)
    """
    patches = self._split_anchors(
        field,
        None,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )
    return _merge_with_hooks(
        agg, _closing(patches), field.domain, hooks, stacklevel=2
    )

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
def split(
    self,
    field: Field,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Iterator[Patch]:
    """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).
    """
    return self._split_anchors(
        field,
        None,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )

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
def to_dask_bag(self, field: Field) -> Any:
    """Build a Dask bag with one item (and one partition) per patch.

    Same per-patch tasks and policy caveats as `to_delayed`.
    """
    from geopatcher._src.dask import to_dask_bag

    return to_dask_bag(self, field)

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
def to_delayed(self, field: Field, operator: Any | None = None) -> list[Any]:
    """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`.
    """
    from geopatcher._src.dask import to_delayed

    return to_delayed(self, field, operator)

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
def two_pass(
    self,
    field: Field,
    *,
    reduce_with: SpatialAggregation,
    apply: Callable[[Any, Any], Any],
    aggregation: SpatialAggregation | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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"],
            )
    """
    anchors = self.anchors(field)
    split_kwargs: dict[str, Any] = {
        "hooks": hooks,
        "prefetch": prefetch,
        "journal": journal,
        "cache": cache,
        "max_in_flight": max_in_flight,
        "max_in_flight_bytes": max_in_flight_bytes,
        "policy": self._start_split(),  # both passes record into one list
    }
    stats = _merge_with_hooks(
        reduce_with,
        _closing(self._split_anchors(field, anchors, **split_kwargs)),
        field.domain,
        hooks,
        stacklevel=2,
    )
    applied = (
        patch.with_data(apply(patch.data, stats))
        for patch in _closing(self._split_anchors(field, anchors, **split_kwargs))
    )
    return _merge_with_hooks(
        aggregation or self.aggregation,
        applied,
        field.domain,
        hooks,
        stacklevel=2,
    )

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
@dataclass(eq=False)
class AsyncSpatialPatcher(_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.
    """

    async def split(
        self,
        field: AsyncField,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> AsyncIterator[Patch]:
        """Alias for `asplit`."""
        async for patch in self.asplit(
            field,
            hooks,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        ):
            yield patch

    async def reduce(
        self,
        field: AsyncField,
        agg: SpatialAggregation,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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())
        """
        patches = self._asplit_anchors(
            field,
            None,
            hooks=hooks,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )
        return await _amerge_with_hooks(
            agg, _aclosing(patches), field.domain, hooks, stacklevel=2
        )

    async def two_pass(
        self,
        field: AsyncField,
        *,
        reduce_with: SpatialAggregation,
        apply: Callable[[Any, Any], Any],
        aggregation: SpatialAggregation | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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"],
                )
        """
        anchors = self.anchors(field)
        split_kwargs: dict[str, Any] = {
            "hooks": hooks,
            "journal": journal,
            "cache": cache,
            "max_in_flight": max_in_flight,
            "max_in_flight_bytes": max_in_flight_bytes,
            "policy": self._start_split(),  # both passes record into one list
        }
        stats = await _amerge_with_hooks(
            reduce_with,
            _aclosing(self._asplit_anchors(field, anchors, **split_kwargs)),
            field.domain,
            hooks,
            stacklevel=2,
        )

        async def applied() -> AsyncIterator[Patch]:
            async for patch in _aclosing(
                self._asplit_anchors(field, anchors, **split_kwargs)
            ):
                yield patch.with_data(apply(patch.data, stats))

        return await _amerge_with_hooks(
            aggregation or self.aggregation,
            applied(),
            field.domain,
            hooks,
            stacklevel=2,
        )

    async def patch_at(self, field: AsyncField, anchor: Any) -> Patch:
        """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.
        """
        domain = field.domain
        base_weights = _safe_base_weights(self.window, self.geometry)
        boundary = getattr(self.geometry, "boundary", "drop")
        return await _build_patch_async(
            field, domain, anchor, self.geometry, base_weights, boundary
        )

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
async def amerge(
    self,
    patches: AsyncIterable[Any] | Iterable[Any],
    domain: Any,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """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`.
    """
    patches = aexpand_batches(patches, self, domain)
    return await _amerge_with_hooks(
        self.aggregation, patches, domain, hooks, stacklevel=2
    )

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
def anchors(self, field: Field | AsyncField) -> list[Any]:
    """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``).
    """
    return list(self.sampler.anchors(field.domain, self.geometry))

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
async def asplit(
    self,
    field: AsyncField,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> AsyncIterator[Patch]:
    """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.
    """
    async for patch in self._asplit_anchors(
        field,
        None,
        hooks=hooks,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    ):
        yield patch

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
def get_config(self) -> dict[str, Any]:
    """Axes as ``{"class", "config"}`` envelopes; ``retry_on`` as qualified names.

    `geopatcher.config.from_config` rebuilds the patcher from
    ``axis_envelope(patcher)``.
    """
    return patcher_config(self)

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
def merge(
    self,
    patches: Iterable[Any],
    domain: Any,
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """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.
    """
    patches = expand_batches(patches, self, domain)
    return _merge_with_hooks(self.aggregation, patches, domain, hooks, stacklevel=2)

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
def n_anchors(self, field: Field | AsyncField) -> int:
    """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.
    """
    return sum(1 for _ in self.sampler.anchors(field.domain, self.geometry))

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
async def patch_at(self, field: AsyncField, anchor: Any) -> Patch:
    """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.
    """
    domain = field.domain
    base_weights = _safe_base_weights(self.window, self.geometry)
    boundary = getattr(self.geometry, "boundary", "drop")
    return await _build_patch_async(
        field, domain, anchor, self.geometry, base_weights, boundary
    )

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
async def reduce(
    self,
    field: AsyncField,
    agg: SpatialAggregation,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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())
    """
    patches = self._asplit_anchors(
        field,
        None,
        hooks=hooks,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )
    return await _amerge_with_hooks(
        agg, _aclosing(patches), field.domain, hooks, stacklevel=2
    )

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
async def split(
    self,
    field: AsyncField,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> AsyncIterator[Patch]:
    """Alias for `asplit`."""
    async for patch in self.asplit(
        field,
        hooks,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    ):
        yield patch

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
async def two_pass(
    self,
    field: AsyncField,
    *,
    reduce_with: SpatialAggregation,
    apply: Callable[[Any, Any], Any],
    aggregation: SpatialAggregation | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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"],
            )
    """
    anchors = self.anchors(field)
    split_kwargs: dict[str, Any] = {
        "hooks": hooks,
        "journal": journal,
        "cache": cache,
        "max_in_flight": max_in_flight,
        "max_in_flight_bytes": max_in_flight_bytes,
        "policy": self._start_split(),  # both passes record into one list
    }
    stats = await _amerge_with_hooks(
        reduce_with,
        _aclosing(self._asplit_anchors(field, anchors, **split_kwargs)),
        field.domain,
        hooks,
        stacklevel=2,
    )

    async def applied() -> AsyncIterator[Patch]:
        async for patch in _aclosing(
            self._asplit_anchors(field, anchors, **split_kwargs)
        ):
            yield patch.with_data(apply(patch.data, stats))

    return await _amerge_with_hooks(
        aggregation or self.aggregation,
        applied(),
        field.domain,
        hooks,
        stacklevel=2,
    )

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 SpatialPatcher.on_error: "raise" (default), "skip", "mask" (a NaN patch of the window's shape) or "retry". Failures are recorded in errors keyed by the patch key (see patch_anchors).

'raise'
max_retries int

Number of retries when on_error is "retry".

0
retry_on tuple[type[BaseException] | str, ...]

Exception classes or class names that should be retried.

(OSError, TimeoutError)
capture_traceback bool

If False, PatchErrorRecord.traceback is left empty.

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
@dataclass(eq=False)
class TemporalPatcher:
    """Four-axis temporal Patcher.

    Args:
        geometry: How a temporal window is shaped around an anchor.
        sampler: Where time anchors are placed.
        window: Temporal boundary treatment (recency / taper / periodic).
        aggregation: Time → time merge strategy.
        on_error: Patch-read error policy, as `SpatialPatcher.on_error`:
            ``"raise"`` (default), ``"skip"``, ``"mask"`` (a NaN patch of
            the window's shape) or ``"retry"``. Failures are recorded in
            ``errors`` keyed by the patch key (see `patch_anchors`).
        max_retries: Number of retries when `on_error` is ``"retry"``.
        retry_on: Exception classes or class names that should be retried.
        capture_traceback: If ``False``, `PatchErrorRecord.traceback` is
            left empty.

    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}
    """

    geometry: TemporalGeometry
    sampler: TemporalSampler
    window: TemporalWindow
    aggregation: TemporalAggregation
    on_error: OnErrorPolicy = "raise"
    max_retries: int = 0
    retry_on: tuple[type[BaseException] | str, ...] = (OSError, TimeoutError)
    capture_traceback: bool = True
    errors: list[PatchErrorRecord] = field(default_factory=list, init=False)

    def __post_init__(self) -> None:
        _validate_error_policy(self.on_error, self.max_retries)
        self.retry_on = _validate_retry_on(self.retry_on)

    # -- coordinate plumbing ---------------------------------------------

    def _needs_coord(self) -> bool:
        return bool(
            getattr(self.geometry, "needs_coord", False)
            or getattr(self.sampler, "needs_coord", False)
        )

    def _require_coord(
        self, coord: Any | None, time_len: int | None = None
    ) -> np.ndarray | None:
        """Validate ``coord`` once and return it as an ndarray (or ``None``).

        1-D, ``time_len`` long and strictly increasing; evenly spaced too
        when a component is coordinate-aware (the stencil path resolves
        windows arithmetically from the step).
        """
        if self._needs_coord() and coord is None:
            raise ValueError(
                "Coordinate-aware geometry/sampler requires coord= "
                "(a 1-D monotonic-ascending coordinate along time_axis)."
            )
        if coord is None:
            return None
        coord = np.asarray(coord)
        if coord.ndim != 1:
            raise ValueError(f"coord must be 1-D; got shape {coord.shape}.")
        if time_len is not None and coord.shape[0] != int(time_len):
            # Catches mixed pipelines (e.g. integer sampler + stencil
            # geometry) where the sampler would yield indices past the
            # coord without this check.
            raise ValueError(
                "coord length must equal series.shape[time_axis]: "
                f"got coord.shape={coord.shape} vs time_len={time_len}."
            )
        if self._needs_coord():
            coord_step(coord)
        elif coord.shape[0] > 1:
            steps = np.diff(coord)
            if not np.all(steps > steps.dtype.type(0)):
                raise ValueError(
                    "coord must be strictly increasing (sorted ascending, no "
                    "duplicates)."
                )
        return coord

    def _resolve_coord(self, src: _TimeSource, coord: Any | None) -> np.ndarray | None:
        if coord is None and self._needs_coord() and src.dim is not None:
            coord = src.time_coord()
        return self._require_coord(coord, src.time_len)

    def _sampler_anchors(
        self, time_len: int, coord: np.ndarray | None
    ) -> Iterable[int]:
        if getattr(self.sampler, "needs_coord", False):
            return self.sampler.anchors(time_len, coord=coord)  # type: ignore[call-arg]
        return self.sampler.anchors(time_len)

    # -- window resolution -----------------------------------------------

    def _window(
        self, time_len: int, anchor: int, coord: np.ndarray | None
    ) -> slice | list[slice] | None:
        if getattr(self.geometry, "needs_coord", False):
            return self.geometry.window_coord(coord, anchor)  # type: ignore[attr-defined]
        return self.geometry.window(time_len, anchor)

    def _keyed_windows(
        self, time_len: int, anchor: int, coord: np.ndarray | None
    ) -> list[tuple[Any, int, slice]]:
        """``(patch key, window index, slice)`` for each window of ``anchor``.

        The key is the bare anchor for a single-window geometry and
        ``(anchor, k)`` for each window of a multi-window one — the keys
        `patch_anchors` lists, `patch_at` accepts, and the journal /
        cache / ``errors`` record.
        """
        window = self._window(time_len, anchor, coord)
        if window is None:
            return []
        if isinstance(window, list):
            return [((anchor, k), k, s) for k, s in enumerate(window)]
        return [(anchor, 0, window)]

    def _window_slices(
        self, time_len: int, anchor: int, coord: np.ndarray | None
    ) -> list[slice]:
        """The windows ``anchor`` yields, as a list (empty when dropped).

        The one place every temporal family (`TemporalPatcher`,
        `SpatioTemporalPatcher`, the matched patchers) resolves a temporal
        window: coord-aware geometries go through ``window_coord``, the
        rest through ``window``, and a ``None`` (dropped by the geometry's
        ``boundary``) becomes ``[]``.
        """
        return [s for _, _, s in self._keyed_windows(time_len, anchor, coord)]

    def _check_full_scan(
        self, anchors: list[int], time_len: int, coord: np.ndarray | None
    ) -> None:
        covered = np.zeros(int(time_len), dtype=bool)
        for anchor in anchors:
            for s in self._window_slices(time_len, anchor, coord):
                covered[s] = True
        if not covered.all():
            missing = np.flatnonzero(~covered)
            raise IncompleteScanConfiguration(
                f"{type(self.sampler).__name__}(check_full_scan=True): the "
                f"{type(self.geometry).__name__} windows leave {missing.size} of "
                f"{time_len} time steps uncovered (first: {missing[:5].tolist()}). "
                "Use a step no longer than the window, a start that reaches the "
                "head, or boundary='shrink'."
            )

    # -- reading ---------------------------------------------------------

    def _read_patch(
        self,
        src: _TimeSource,
        anchor: int,
        k: int,
        s: slice,
        weights: np.ndarray | None = None,
    ) -> TemporalPatch:
        if weights is None:
            weights = self.window.weights(self.geometry, s.stop - s.start)
        return TemporalPatch(
            data=src.read(s), anchor=anchor, indices=s, weights=weights, window_index=k
        )

    def _mask_patch(
        self, src: _TimeSource, anchor: int, k: int, s: slice, weights: np.ndarray
    ) -> TemporalPatch:
        return TemporalPatch(
            data=src.mask(s), anchor=anchor, indices=s, weights=weights, window_index=k
        )

    def _cache_context(
        self, cache: Any | None, src: _TimeSource, *, field_id: str | None = None
    ) -> Any | None:
        """Bind ``cache`` to this series + config, or ``None`` when disabled."""
        if cache is None:
            return None
        if field_id is None:
            field_id = cache.field_id_for(src.series)
        config_id = (
            f"{cache.config_id_for(self.geometry, self.window)}"
            f"|time_axis={src.time_axis}"
        )
        return (cache, field_id, config_id)

    def _cached_patch(
        self, ctx: Any | None, key: Any, anchor: int, k: int, s: slice
    ) -> TemporalPatch | None:
        if ctx is None:
            return None
        cache, field_id, config_id = ctx
        payload = cache.get(field_id, config_id, key)
        if payload is None:
            return None
        hit = cache.build_patch(payload, anchor, s)
        return TemporalPatch(
            data=hit.data, anchor=anchor, indices=s, weights=hit.weights, window_index=k
        )

    def _store_patch(self, ctx: Any | None, key: Any, patch: TemporalPatch) -> None:
        if ctx is not None:
            cache, field_id, config_id = ctx
            cache.put(field_id, config_id, key, patch)

    def _units(
        self,
        src: _TimeSource,
        coord: np.ndarray | None,
        cache_ctx: Any | None,
    ) -> Callable[[int], list[_Read]]:
        """``anchor -> [_Read per window]`` for the walk core.

        Each window is one leaf keyed by its `patch_anchors` key; window
        weights depend only on the window length, so each length is
        computed once per split.
        """
        time_len = src.time_len
        weights_by_len: dict[int, np.ndarray] = {}

        def units(anchor: int) -> list[_Read]:
            coord_value = None if coord is None else coord[anchor]
            out = []
            for key, k, s in self._keyed_windows(time_len, anchor, coord):
                n = s.stop - s.start
                weights = weights_by_len.get(n)
                if weights is None:
                    weights = weights_by_len[n] = self.window.weights(self.geometry, n)
                out.append(
                    _Read(
                        key=key,
                        anchor=anchor,
                        coord_value=coord_value,
                        read=partial(self._read_patch, src, anchor, k, s, weights),
                        mask=partial(self._mask_patch, src, anchor, k, s, weights),
                        cached=None
                        if cache_ctx is None
                        else partial(self._cached_patch, cache_ctx, key, anchor, k, s),
                        store=None
                        if cache_ctx is None
                        else partial(self._store_patch, cache_ctx, key),
                    )
                )
            return out

        return units

    # -- split -----------------------------------------------------------

    def split(
        self,
        series: Any,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Iterator[TemporalPatch]:
        """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: ...``).

        Args:
            series: What to patch along ``time_axis``: a `Field` with a
                `GridDomain` (read through ``select``), or any array-like
                with ``shape`` that slices (numpy, dask, xarray, zarr) —
                only each window is read. Anything else goes through
                ``np.asarray``.
            time_axis: Which axis is the time axis. Default 0.
            coord: 1-D, strictly increasing coordinate along ``time_axis``.
                Required (and must be evenly spaced) when the geometry or
                sampler is coordinate-aware — a `GridDomain` field supplies
                its time coordinate by default; otherwise only reported to
                hooks as ``coord_value``.
            hooks: Optional observability hooks for split callbacks.
            prefetch: If positive, eagerly buffer up to ``prefetch`` patches
                in a background thread for I/O overlap.
            journal: Optional `PatchJournal`; patch keys it has are skipped.
            cache: Optional `PatchCache`.
            max_in_flight: Maximum number of unreleased patches.
            max_in_flight_bytes: Maximum total bytes of unreleased patches.

        Raises:
            IncompleteScanConfiguration: The sampler sets
                ``check_full_scan=True`` and the windows leave time steps
                uncovered (raised before the first patch).
        """
        return self._split_anchors(
            series,
            None,
            time_axis=time_axis,
            coord=coord,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )

    def _split_anchors(
        self,
        series: Any,
        anchors: Iterable[int] | None,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
        policy: ReadPolicy | None = None,
    ) -> Iterator[TemporalPatch]:
        """`split` over explicit ``anchors`` (``None`` walks the sampler).

        `two_pass` passes its first pass's ``policy`` so both passes
        record into one ``errors`` list.
        """
        _validate_backpressure(max_in_flight, max_in_flight_bytes)
        src = _source(series, time_axis)
        coord = self._resolve_coord(src, coord)
        if policy is None:
            policy = self._start_split()
        stop = Event()
        return prefetch_iterable(
            self._walk(
                src,
                anchors=anchors,
                coord=coord,
                policy=policy,
                hooks=hooks,
                journal=journal,
                cache=cache,
                backpressure=_Backpressure(max_in_flight, max_in_flight_bytes, stop),
            ),
            prefetch,
            stop=stop,
        )

    def _start_split(self) -> ReadPolicy:
        """A fresh ``errors`` list for a new split (see `SpatialPatcher`)."""
        self.errors = []
        return ReadPolicy.of(self)

    def _walk(
        self,
        src: _TimeSource,
        *,
        anchors: Iterable[int] | None,
        coord: np.ndarray | None,
        policy: ReadPolicy,
        hooks: Iterable[PatcherHook] | None,
        journal: Any | None,
        cache: Any | None,
        backpressure: _Backpressure,
    ) -> Iterator[TemporalPatch]:
        time_len = src.time_len
        if anchors is None:
            anchors = self._sampler_anchors(time_len, coord)
        anchors = (int(a) for a in anchors)
        if getattr(self.sampler, "check_full_scan", False):
            anchors = list(anchors)
            self._check_full_scan(anchors, time_len, coord)
        yield from walk(
            anchors,
            self._units(src, coord, self._cache_context(cache, src)),
            policy=policy,
            backpressure=backpressure,
            hooks=hooks,
            journal=journal,
        )

    async def asplit(
        self,
        series: Any,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> AsyncIterator[TemporalPatch]:
        """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.
        """
        patches = self.split(
            series,
            time_axis=time_axis,
            coord=coord,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )
        try:
            while True:
                patch: TemporalPatch | None = await asyncio.to_thread(
                    next, patches, None
                )
                if patch is None:
                    return
                yield patch
        finally:
            close = getattr(patches, "close", None)
            if close is not None:
                # A cancelled pull may still be running in its thread.
                with contextlib.suppress(ValueError):
                    close()

    # -- random access ---------------------------------------------------

    def patches_at(
        self,
        series: Any,
        anchor: int,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
    ) -> list[TemporalPatch]:
        """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.

        Args:
            series: Same input as `split`; only the anchor's windows are
                read.
            anchor: A single anchor value (typically from
                ``patcher.anchors(series)[index]``).
            time_axis: Which axis is the time axis. Default 0.
            coord: See `split`.
        """
        src = _source(series, time_axis)
        coord = self._resolve_coord(src, coord)
        return [
            self._read_patch(src, int(anchor), k, s)
            for _, k, s in self._keyed_windows(src.time_len, int(anchor), coord)
        ]

    def patch_at(
        self,
        series: Any,
        anchor: int | tuple[int, int],
        *,
        time_axis: int = 0,
        coord: Any | None = None,
        cache: Any | None = None,
        field_id: str | None = None,
    ) -> TemporalPatch:
        """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``.

        Args:
            series: Same input as `split`.
            anchor: A key from `patch_anchors` — a bare anchor for a
                single-window geometry, or ``(anchor, k)`` for the
                ``k``-th window of a multi-window geometry such as
                `temporal.geometry.MultiScale` (``(anchor, 0)`` also works for a
                single-window geometry).
            time_axis: Which axis is the time axis. Default 0.
            coord: See `split`.
            cache: Optional `PatchCache`, as in `SpatialPatcher.patch_at`.
            field_id: ``cache.field_id_for(series)`` resolved once by the
                caller and reused for every key.

        Raises:
            ValueError: If a bare anchor is given for a geometry that
                yields several windows for it, or ``k`` is out of range.
        """
        if isinstance(anchor, tuple):
            base, k = int(anchor[0]), int(anchor[1])
        else:
            base, k = int(anchor), None
        src = _source(series, time_axis)
        coord = self._resolve_coord(src, coord)
        windows = self._keyed_windows(src.time_len, base, coord)
        if k is None:
            if len(windows) != 1:
                raise ValueError(
                    f"anchor {base} yields {len(windows)} patches with "
                    f"{type(self.geometry).__name__}; pass ({base}, k) to pick "
                    "one (see `patch_anchors`) or use `patches_at`."
                )
            k = 0
        if not 0 <= k < len(windows):
            raise ValueError(
                f"anchor {base} yields {len(windows)} patches; window index "
                f"{k} is out of range."
            )
        key, k, s = windows[k]
        ctx = self._cache_context(cache, src, field_id=field_id)
        cached = self._cached_patch(ctx, key, base, k, s)
        if cached is not None:
            return cached
        patch = self._read_patch(src, base, k, s)
        self._store_patch(ctx, key, patch)
        return patch

    def patch_anchors(
        self,
        series: Any,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
    ) -> list[int | tuple[int, int]]:
        """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.
        """
        src = _source(series, time_axis)
        coord = self._resolve_coord(src, coord)
        return [
            key
            for anchor in self._sampler_anchors(src.time_len, coord)
            for key, _, _ in self._keyed_windows(src.time_len, int(anchor), coord)
        ]

    def anchors(
        self,
        series: Any,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
    ) -> list[int]:
        """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`.
        """
        src = _source(series, time_axis)
        coord = self._resolve_coord(src, coord)
        return [
            int(a)
            for a in self._sampler_anchors(src.time_len, coord)
            if self._window_slices(src.time_len, int(a), coord)
        ]

    def n_anchors(
        self,
        series: Any,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
    ) -> int:
        """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).
        """
        return len(self.patch_anchors(series, time_axis=time_axis, coord=coord))

    # -- merge -----------------------------------------------------------

    def merge(
        self, patches: Iterable[Any], hooks: Iterable[PatcherHook] | None = None
    ) -> Any:
        """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.
        """
        return _merge_with_hooks(
            self.aggregation, patches, _NO_DOMAIN, hooks, stacklevel=2
        )

    async def amerge(
        self,
        patches: AsyncIterable[Any] | Iterable[Any],
        hooks: Iterable[PatcherHook] | None = None,
    ) -> Any:
        """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.
        """
        return await _amerge_with_hooks(
            self.aggregation, patches, _NO_DOMAIN, hooks, stacklevel=2
        )

    def reduce(
        self,
        series: Any,
        agg: TemporalAggregation,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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.
        """
        patches = self._split_anchors(
            series,
            None,
            time_axis=time_axis,
            coord=coord,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )
        return _merge_with_hooks(
            agg,
            _closing(patches),
            _NO_DOMAIN,
            hooks,
            stacklevel=2,
        )

    def two_pass(
        self,
        series: Any,
        *,
        reduce_with: TemporalAggregation,
        apply: Callable[[Any, Any], Any],
        aggregation: TemporalAggregation | None = None,
        time_axis: int = 0,
        coord: Any | None = None,
        hooks: Iterable[PatcherHook] | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Any:
        """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.
        """
        src = _source(series, time_axis)
        anchors = [
            int(a)
            for a in self._sampler_anchors(
                src.time_len, self._resolve_coord(src, coord)
            )
        ]
        split_kwargs: dict[str, Any] = {
            "time_axis": time_axis,
            "coord": coord,
            "hooks": hooks,
            "prefetch": prefetch,
            "journal": journal,
            "cache": cache,
            "max_in_flight": max_in_flight,
            "max_in_flight_bytes": max_in_flight_bytes,
            "policy": self._start_split(),  # both passes record into one list
        }
        stats = _merge_with_hooks(
            reduce_with,
            _closing(self._split_anchors(series, anchors, **split_kwargs)),
            _NO_DOMAIN,
            hooks,
            stacklevel=2,
        )
        applied = (
            patch.with_data(apply(patch.data, stats))
            for patch in _closing(self._split_anchors(series, anchors, **split_kwargs))
        )
        return _merge_with_hooks(
            aggregation or self.aggregation,
            applied,
            _NO_DOMAIN,
            hooks,
            stacklevel=2,
        )

    def to_delayed(
        self,
        series: Any,
        operator: Any | None = None,
        *,
        time_axis: int = 0,
        coord: Any | None = None,
    ) -> list[Any]:
        """One Dask delayed `patch_at` task per patch key (see `geopatcher.run`).

        Runner-level policies (``on_error``, hooks, journal, cache,
        prefetch) do not apply.
        """
        from geopatcher._src.dask import to_delayed

        return to_delayed(self, series, operator, time_axis=time_axis, coord=coord)

    def to_dask_bag(
        self, series: Any, *, time_axis: int = 0, coord: Any | None = None
    ) -> Any:
        """A Dask bag with one item (and one partition) per patch key."""
        from geopatcher._src.dask import to_dask_bag

        return to_dask_bag(self, series, time_axis=time_axis, coord=coord)

    def get_config(self) -> dict[str, Any]:
        """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.
        """
        return patcher_config(self)

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
async def amerge(
    self,
    patches: AsyncIterable[Any] | Iterable[Any],
    hooks: Iterable[PatcherHook] | None = None,
) -> Any:
    """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.
    """
    return await _amerge_with_hooks(
        self.aggregation, patches, _NO_DOMAIN, hooks, stacklevel=2
    )

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
def anchors(
    self,
    series: Any,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
) -> list[int]:
    """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`.
    """
    src = _source(series, time_axis)
    coord = self._resolve_coord(src, coord)
    return [
        int(a)
        for a in self._sampler_anchors(src.time_len, coord)
        if self._window_slices(src.time_len, int(a), coord)
    ]

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
async def asplit(
    self,
    series: Any,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> AsyncIterator[TemporalPatch]:
    """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.
    """
    patches = self.split(
        series,
        time_axis=time_axis,
        coord=coord,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )
    try:
        while True:
            patch: TemporalPatch | None = await asyncio.to_thread(
                next, patches, None
            )
            if patch is None:
                return
            yield patch
    finally:
        close = getattr(patches, "close", None)
        if close is not None:
            # A cancelled pull may still be running in its thread.
            with contextlib.suppress(ValueError):
                close()

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
def get_config(self) -> dict[str, Any]:
    """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.
    """
    return patcher_config(self)

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
def merge(
    self, patches: Iterable[Any], hooks: Iterable[PatcherHook] | None = None
) -> Any:
    """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.
    """
    return _merge_with_hooks(
        self.aggregation, patches, _NO_DOMAIN, hooks, stacklevel=2
    )

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
def n_anchors(
    self,
    series: Any,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
) -> int:
    """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).
    """
    return len(self.patch_anchors(series, time_axis=time_axis, coord=coord))

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
def patch_anchors(
    self,
    series: Any,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
) -> list[int | tuple[int, int]]:
    """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.
    """
    src = _source(series, time_axis)
    coord = self._resolve_coord(src, coord)
    return [
        key
        for anchor in self._sampler_anchors(src.time_len, coord)
        for key, _, _ in self._keyed_windows(src.time_len, int(anchor), coord)
    ]

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 split.

required
anchor int | tuple[int, int]

A key from patch_anchors — a bare anchor for a single-window geometry, or (anchor, k) for the k-th window of a multi-window geometry such as temporal.geometry.MultiScale ((anchor, 0) also works for a single-window geometry).

required
time_axis int

Which axis is the time axis. Default 0.

0
coord Any | None

See split.

None
cache Any | None

Optional PatchCache, as in SpatialPatcher.patch_at.

None
field_id str | None

cache.field_id_for(series) resolved once by the caller and reused for every key.

None

Raises:

Type Description
ValueError

If a bare anchor is given for a geometry that yields several windows for it, or k is out of range.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
def patch_at(
    self,
    series: Any,
    anchor: int | tuple[int, int],
    *,
    time_axis: int = 0,
    coord: Any | None = None,
    cache: Any | None = None,
    field_id: str | None = None,
) -> TemporalPatch:
    """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``.

    Args:
        series: Same input as `split`.
        anchor: A key from `patch_anchors` — a bare anchor for a
            single-window geometry, or ``(anchor, k)`` for the
            ``k``-th window of a multi-window geometry such as
            `temporal.geometry.MultiScale` (``(anchor, 0)`` also works for a
            single-window geometry).
        time_axis: Which axis is the time axis. Default 0.
        coord: See `split`.
        cache: Optional `PatchCache`, as in `SpatialPatcher.patch_at`.
        field_id: ``cache.field_id_for(series)`` resolved once by the
            caller and reused for every key.

    Raises:
        ValueError: If a bare anchor is given for a geometry that
            yields several windows for it, or ``k`` is out of range.
    """
    if isinstance(anchor, tuple):
        base, k = int(anchor[0]), int(anchor[1])
    else:
        base, k = int(anchor), None
    src = _source(series, time_axis)
    coord = self._resolve_coord(src, coord)
    windows = self._keyed_windows(src.time_len, base, coord)
    if k is None:
        if len(windows) != 1:
            raise ValueError(
                f"anchor {base} yields {len(windows)} patches with "
                f"{type(self.geometry).__name__}; pass ({base}, k) to pick "
                "one (see `patch_anchors`) or use `patches_at`."
            )
        k = 0
    if not 0 <= k < len(windows):
        raise ValueError(
            f"anchor {base} yields {len(windows)} patches; window index "
            f"{k} is out of range."
        )
    key, k, s = windows[k]
    ctx = self._cache_context(cache, src, field_id=field_id)
    cached = self._cached_patch(ctx, key, base, k, s)
    if cached is not None:
        return cached
    patch = self._read_patch(src, base, k, s)
    self._store_patch(ctx, key, patch)
    return patch

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 split; only the anchor's windows are read.

required
anchor int

A single anchor value (typically from patcher.anchors(series)[index]).

required
time_axis int

Which axis is the time axis. Default 0.

0
coord Any | None

See split.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
def patches_at(
    self,
    series: Any,
    anchor: int,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
) -> list[TemporalPatch]:
    """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.

    Args:
        series: Same input as `split`; only the anchor's windows are
            read.
        anchor: A single anchor value (typically from
            ``patcher.anchors(series)[index]``).
        time_axis: Which axis is the time axis. Default 0.
        coord: See `split`.
    """
    src = _source(series, time_axis)
    coord = self._resolve_coord(src, coord)
    return [
        self._read_patch(src, int(anchor), k, s)
        for _, k, s in self._keyed_windows(src.time_len, int(anchor), coord)
    ]

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
def reduce(
    self,
    series: Any,
    agg: TemporalAggregation,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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.
    """
    patches = self._split_anchors(
        series,
        None,
        time_axis=time_axis,
        coord=coord,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )
    return _merge_with_hooks(
        agg,
        _closing(patches),
        _NO_DOMAIN,
        hooks,
        stacklevel=2,
    )

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 time_axis: a Field with a GridDomain (read through select), or any array-like with shape that slices (numpy, dask, xarray, zarr) — only each window is read. Anything else goes through np.asarray.

required
time_axis int

Which axis is the time axis. Default 0.

0
coord Any | None

1-D, strictly increasing coordinate along time_axis. Required (and must be evenly spaced) when the geometry or sampler is coordinate-aware — a GridDomain field supplies its time coordinate by default; otherwise only reported to hooks as coord_value.

None
hooks Iterable[PatcherHook] | None

Optional observability hooks for split callbacks.

None
prefetch int

If positive, eagerly buffer up to prefetch patches in a background thread for I/O overlap.

0
journal Any | None

Optional PatchJournal; patch keys it has are skipped.

None
cache Any | None

Optional PatchCache.

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 check_full_scan=True and the windows leave time steps uncovered (raised before the first patch).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/patcher.py
def split(
    self,
    series: Any,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Iterator[TemporalPatch]:
    """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: ...``).

    Args:
        series: What to patch along ``time_axis``: a `Field` with a
            `GridDomain` (read through ``select``), or any array-like
            with ``shape`` that slices (numpy, dask, xarray, zarr) —
            only each window is read. Anything else goes through
            ``np.asarray``.
        time_axis: Which axis is the time axis. Default 0.
        coord: 1-D, strictly increasing coordinate along ``time_axis``.
            Required (and must be evenly spaced) when the geometry or
            sampler is coordinate-aware — a `GridDomain` field supplies
            its time coordinate by default; otherwise only reported to
            hooks as ``coord_value``.
        hooks: Optional observability hooks for split callbacks.
        prefetch: If positive, eagerly buffer up to ``prefetch`` patches
            in a background thread for I/O overlap.
        journal: Optional `PatchJournal`; patch keys it has are skipped.
        cache: Optional `PatchCache`.
        max_in_flight: Maximum number of unreleased patches.
        max_in_flight_bytes: Maximum total bytes of unreleased patches.

    Raises:
        IncompleteScanConfiguration: The sampler sets
            ``check_full_scan=True`` and the windows leave time steps
            uncovered (raised before the first patch).
    """
    return self._split_anchors(
        series,
        None,
        time_axis=time_axis,
        coord=coord,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )

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
def to_dask_bag(
    self, series: Any, *, time_axis: int = 0, coord: Any | None = None
) -> Any:
    """A Dask bag with one item (and one partition) per patch key."""
    from geopatcher._src.dask import to_dask_bag

    return to_dask_bag(self, series, time_axis=time_axis, coord=coord)

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
def to_delayed(
    self,
    series: Any,
    operator: Any | None = None,
    *,
    time_axis: int = 0,
    coord: Any | None = None,
) -> list[Any]:
    """One Dask delayed `patch_at` task per patch key (see `geopatcher.run`).

    Runner-level policies (``on_error``, hooks, journal, cache,
    prefetch) do not apply.
    """
    from geopatcher._src.dask import to_delayed

    return to_delayed(self, series, operator, time_axis=time_axis, coord=coord)

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
def two_pass(
    self,
    series: Any,
    *,
    reduce_with: TemporalAggregation,
    apply: Callable[[Any, Any], Any],
    aggregation: TemporalAggregation | None = None,
    time_axis: int = 0,
    coord: Any | None = None,
    hooks: Iterable[PatcherHook] | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Any:
    """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.
    """
    src = _source(series, time_axis)
    anchors = [
        int(a)
        for a in self._sampler_anchors(
            src.time_len, self._resolve_coord(src, coord)
        )
    ]
    split_kwargs: dict[str, Any] = {
        "time_axis": time_axis,
        "coord": coord,
        "hooks": hooks,
        "prefetch": prefetch,
        "journal": journal,
        "cache": cache,
        "max_in_flight": max_in_flight,
        "max_in_flight_bytes": max_in_flight_bytes,
        "policy": self._start_split(),  # both passes record into one list
    }
    stats = _merge_with_hooks(
        reduce_with,
        _closing(self._split_anchors(series, anchors, **split_kwargs)),
        _NO_DOMAIN,
        hooks,
        stacklevel=2,
    )
    applied = (
        patch.with_data(apply(patch.data, stats))
        for patch in _closing(self._split_anchors(series, anchors, **split_kwargs))
    )
    return _merge_with_hooks(
        aggregation or self.aggregation,
        applied,
        _NO_DOMAIN,
        hooks,
        stacklevel=2,
    )

geopatcher.SpatioTemporalPatcher dataclass

Composition of a spatial and a temporal Patcher.

Parameters:

Name Type Description Default
spatial SpatialPatcher

A SpatialPatcher. Its geometry, window and read policy (on_error / max_retries / retry_on) read every spatial chip; failures are recorded in spatial.errors.

required
temporal TemporalPatcher

A TemporalPatcher.

required
coupling Literal['product', 'coupled']

"product" (Cartesian product of anchors) or "coupled" (explicit (space, time) tuples from the spatial sampler's anchors_).

'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.

0
Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
@dataclass(eq=False)
class SpatioTemporalPatcher:
    """Composition of a spatial and a temporal Patcher.

    Args:
        spatial: A `SpatialPatcher`. Its geometry, window and read policy
            (``on_error`` / ``max_retries`` / ``retry_on``) read every
            spatial chip; failures are recorded in ``spatial.errors``.
        temporal: A `TemporalPatcher`.
        coupling: ``"product"`` (Cartesian product of anchors) or
            ``"coupled"`` (explicit ``(space, time)`` tuples from the
            spatial sampler's anchors_).
        time_axis: Which axis of the spatial patch's data is the time
            axis after the spatial slice has been read. Default ``0``.
    """

    spatial: SpatialPatcher
    temporal: TemporalPatcher
    coupling: Literal["product", "coupled"] = "product"
    time_axis: int = 0

    def split(
        self,
        field: Any,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        coord: np.ndarray | None = None,
        prefetch: int = 0,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> Iterator[SpatioTemporalPatch]:
        """Yield `SpatioTemporalPatch`es 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.

        Args:
            field: The field to split.
            hooks: Optional observability hooks for split callbacks.
            coord: 1-D coordinate vector along ``time_axis`` of the
                spatial patch's data. Required when the temporal
                geometry or sampler is coordinate-aware
                (``needs_coord = True``); otherwise only reported to
                hooks as ``coord_value``.
            prefetch: If positive, eagerly buffer up to ``prefetch``
                patches in a background thread for I/O overlap.
            journal: Optional `PatchJournal`; patch keys it has are
                skipped (a chip whose every window is journaled is not
                read once the time length is known).
            cache: Optional `PatchCache` for the spatial chips, keyed as
                `SpatialPatcher.split` keys them.
            max_in_flight: Maximum number of unreleased patches.
            max_in_flight_bytes: Maximum total bytes of unreleased patches.
        """
        return self._split(
            field,
            hooks,
            coord=coord,
            prefetch=prefetch,
            journal=journal,
            cache=cache,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )

    def _split(
        self,
        field: Any,
        hooks: Iterable[PatcherHook] | None,
        *,
        coord: np.ndarray | None,
        prefetch: int,
        journal: Any | None,
        cache: Any | None,
        max_in_flight: int | None,
        max_in_flight_bytes: int | None,
        unpack: Callable[[Any], Any] | None = None,
    ) -> Iterator[SpatioTemporalPatch]:
        """`split`; ``unpack`` maps each chip's data before it is sliced.

        `MatchedSpatioTemporalPatcher` passes one that turns a
        `MatchedField` read into its checked ``{source: data}`` dict, each
        member of which is then sliced in lockstep.
        """
        _validate_backpressure(max_in_flight, max_in_flight_bytes)
        policy = _start_split(self.spatial)
        stop = Event()
        return prefetch_iterable(
            self._walk(
                field,
                coord=coord,
                policy=policy,
                hooks=hooks,
                journal=journal,
                cache=cache,
                backpressure=_Backpressure(max_in_flight, max_in_flight_bytes, stop),
                unpack=unpack,
            ),
            prefetch,
            stop=stop,
        )

    def _walk(
        self,
        field: Any,
        *,
        coord: np.ndarray | None,
        policy: ReadPolicy,
        hooks: Iterable[PatcherHook] | None,
        journal: Any | None,
        cache: Any | None,
        backpressure: _Backpressure,
        unpack: Callable[[Any], Any] | None,
    ) -> Iterator[Any]:
        plan = self._plan(field, coord, cache, aio=False, unpack=unpack)
        yield from walk(
            plan.anchors,
            plan.units,
            policy=policy,
            backpressure=backpressure,
            hooks=hooks,
            journal=journal,
            total=plan.total,
        )

    async def asplit(
        self,
        field: Any,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        coord: np.ndarray | None = None,
        journal: Any | None = None,
        cache: Any | None = None,
        max_in_flight: int | None = None,
        max_in_flight_bytes: int | None = None,
    ) -> AsyncIterator[SpatioTemporalPatch]:
        """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.
        """
        _validate_backpressure(max_in_flight, max_in_flight_bytes)
        policy = _start_split(self.spatial)
        plan = self._plan(field, coord, cache, aio=True)
        async for patch in awalk(
            plan.anchors,
            plan.units,
            policy=policy,
            backpressure=_AsyncBackpressure(max_in_flight, max_in_flight_bytes),
            hooks=hooks,
            journal=journal,
            total=plan.total,
        ):
            yield patch

    def _checked_coupling(self) -> Literal["product", "coupled"]:
        if self.coupling not in {"product", "coupled"}:
            raise ValueError(f"unknown coupling: {self.coupling!r}")
        return self.coupling

    def _plan(
        self,
        field: Any,
        coord: Any | None,
        cache: Any | None,
        *,
        aio: bool,
        unpack: Callable[[Any], Any] | None = None,
    ) -> _STPlan:
        coupling = self._checked_coupling()
        coord = self.temporal._require_coord(coord)
        domain = field.domain
        if coupling == "product":
            anchors: Iterable[Any] = self.spatial.sampler.anchors(
                domain, self.spatial.geometry
            )
        else:
            anchors = _coupled_pairs(self.spatial)
        return _STPlan(
            stp=self,
            reader=_chip_reader(self.spatial, field, domain, cache, aio=aio),
            coord=coord,
            coupled=coupling == "coupled",
            anchors=anchors,
            unpack=unpack,
        )

    def _time_len(self, data: Any) -> int:
        """Length of a chip's ``data`` along ``time_axis``.

        A ``{source: data}`` mapping (a matched read, already checked to
        share one time axis) answers with its first member.
        """
        member: Any = next(iter(data.values())) if isinstance(data, Mapping) else data
        return int(np.shape(member)[self.time_axis])

    def _slice_time(self, data: Any, s: slice) -> Any:
        """``data`` sliced to ``s`` along ``time_axis``, keeping its carrier.

        Positional indexing keeps a `GeoArray` (``__getitem__`` keeps its
        grid), an `xarray.DataArray`, a dask or a numpy array as it is;
        a mapping is sliced member by member (keeping its type).
        """
        if isinstance(data, Mapping):
            return type(data)({k: self._slice_time(v, s) for k, v in data.items()})
        idx: list[Any] = [slice(None)] * len(np.shape(data))
        idx[self.time_axis] = s
        return data[tuple(idx)]

    def _patch(self, chip: Any, data: Any, time: int, s: slice) -> Any:
        """The `SpatioTemporalPatch` of window ``s`` of ``chip`` (``data``)."""
        return SpatioTemporalPatch(
            data=self._slice_time(data, s),
            space=chip.anchor,
            time=time,
            spatial_indices=chip.indices,
            temporal_indices=s,
            weights=chip.weights,
        )

    def merge(
        self,
        patches: Iterable[Any],
        field: Any,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> list[tuple[Any, Any]]:
        """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.

        Args:
            patches: Iterable of `SpatioTemporalPatch` instances.
            field: The original field — currently unused, kept for the
                symmetry with `SpatialPatcher.merge(patches, domain)` so
                callers can wire the two interchangeably.

        Returns:
            ``[(anchor, merged), …]`` in first-seen anchor order.
        """
        hook_list = _as_hooks(hooks)
        _dispatch(hook_list, "on_merge_start", _len_or_unknown(patches))
        try:
            output = _merge_by_space(patches, self.temporal.aggregation)
        except Exception as exc:
            _dispatch(hook_list, "on_error", None, exc)
            raise
        _dispatch(hook_list, "on_merge_end", _nbytes(output))
        return output

    def get_config(self) -> dict[str, Any]:
        """Inner patchers as ``{"class", "config"}`` envelopes (`patcher_config`)."""
        return patcher_config(self)

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
async def asplit(
    self,
    field: Any,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    coord: np.ndarray | None = None,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> AsyncIterator[SpatioTemporalPatch]:
    """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.
    """
    _validate_backpressure(max_in_flight, max_in_flight_bytes)
    policy = _start_split(self.spatial)
    plan = self._plan(field, coord, cache, aio=True)
    async for patch in awalk(
        plan.anchors,
        plan.units,
        policy=policy,
        backpressure=_AsyncBackpressure(max_in_flight, max_in_flight_bytes),
        hooks=hooks,
        journal=journal,
        total=plan.total,
    ):
        yield patch

get_config()

Inner patchers as {"class", "config"} envelopes (patcher_config).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
def get_config(self) -> dict[str, Any]:
    """Inner patchers as ``{"class", "config"}`` envelopes (`patcher_config`)."""
    return patcher_config(self)

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 SpatioTemporalPatch instances.

required
field Any

The original field — currently unused, kept for the symmetry with SpatialPatcher.merge(patches, domain) so callers can wire the two interchangeably.

required

Returns:

Type Description
list[tuple[Any, Any]]

[(anchor, merged), …] in first-seen anchor order.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/spatial_time.py
def merge(
    self,
    patches: Iterable[Any],
    field: Any,
    hooks: Iterable[PatcherHook] | None = None,
) -> list[tuple[Any, Any]]:
    """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.

    Args:
        patches: Iterable of `SpatioTemporalPatch` instances.
        field: The original field — currently unused, kept for the
            symmetry with `SpatialPatcher.merge(patches, domain)` so
            callers can wire the two interchangeably.

    Returns:
        ``[(anchor, merged), …]`` in first-seen anchor order.
    """
    hook_list = _as_hooks(hooks)
    _dispatch(hook_list, "on_merge_start", _len_or_unknown(patches))
    try:
        output = _merge_by_space(patches, self.temporal.aggregation)
    except Exception as exc:
        _dispatch(hook_list, "on_error", None, exc)
        raise
    _dispatch(hook_list, "on_merge_end", _nbytes(output))
    return output

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 time_axis of the spatial patch's data. Required when the temporal geometry or sampler is coordinate-aware (needs_coord = True); otherwise only reported to hooks as coord_value.

None
prefetch int

If positive, eagerly buffer up to prefetch patches in a background thread for I/O overlap.

0
journal Any | None

Optional PatchJournal; patch keys it has are skipped (a chip whose every window is journaled is not read once the time length is known).

None
cache Any | None

Optional PatchCache for the spatial chips, keyed as SpatialPatcher.split keys them.

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
def split(
    self,
    field: Any,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    coord: np.ndarray | None = None,
    prefetch: int = 0,
    journal: Any | None = None,
    cache: Any | None = None,
    max_in_flight: int | None = None,
    max_in_flight_bytes: int | None = None,
) -> Iterator[SpatioTemporalPatch]:
    """Yield `SpatioTemporalPatch`es 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.

    Args:
        field: The field to split.
        hooks: Optional observability hooks for split callbacks.
        coord: 1-D coordinate vector along ``time_axis`` of the
            spatial patch's data. Required when the temporal
            geometry or sampler is coordinate-aware
            (``needs_coord = True``); otherwise only reported to
            hooks as ``coord_value``.
        prefetch: If positive, eagerly buffer up to ``prefetch``
            patches in a background thread for I/O overlap.
        journal: Optional `PatchJournal`; patch keys it has are
            skipped (a chip whose every window is journaled is not
            read once the time length is known).
        cache: Optional `PatchCache` for the spatial chips, keyed as
            `SpatialPatcher.split` keys them.
        max_in_flight: Maximum number of unreleased patches.
        max_in_flight_bytes: Maximum total bytes of unreleased patches.
    """
    return self._split(
        field,
        hooks,
        coord=coord,
        prefetch=prefetch,
        journal=journal,
        cache=cache,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )

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 geoarray.GeoArray, a sub-DataArray, a GeoDataFrame slice, …).

required
anchor AnchorT

Where this patch lives in the global field. Shape varies with the Sampler (pixel coords, lat/lon, polygon id, …).

required
indices IndicesT

Backend-specific indexer used to extract data from the parent field (a rasterio.windows.Window, a dict[str, slice], a list of row indices, …).

required
weights Any | None

Optional window weights — used by OverlapAdd and WeightedSum aggregations, and by PolygonIntersection to carry an interior mask. None is equivalent to a Boxcar.

None
masked bool

True for the all-NaN placeholder an on_error="mask" policy yields in place of a failed read. The data keeps the carrier and georeferencing of a successful read where the field allows (see Field.placeholder), so this flag — not the array type — is how to tell a placeholder apart.

False
Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
@dataclass(eq=False)
class Patch[AnchorT, IndicesT, DataT](_ReleaseLifecycleMixin):
    """A single patch produced by a `SpatialPatcher`.

    Args:
        data: The substrate slice the operator consumes (a
            `geoarray.GeoArray`, a sub-`DataArray`, a `GeoDataFrame`
            slice, …).
        anchor: Where this patch lives in the global field. Shape varies
            with the `Sampler` (pixel coords, lat/lon, polygon id, …).
        indices: Backend-specific indexer used to extract `data` from
            the parent field (a `rasterio.windows.Window`, a
            `dict[str, slice]`, a list of row indices, …).
        weights: Optional window weights — used by `OverlapAdd` and
            `WeightedSum` aggregations, and by `PolygonIntersection` to
            carry an interior mask. ``None`` is equivalent to a Boxcar.
        masked: ``True`` for the all-NaN placeholder an ``on_error="mask"``
            policy yields in place of a failed read. The data keeps the
            carrier and georeferencing of a successful read where the
            field allows (see `Field.placeholder`), so this flag — not
            the array type — is how to tell a placeholder apart.
    """

    data: DataT
    anchor: AnchorT
    indices: IndicesT
    weights: Any | None = None
    masked: bool = False
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

    def with_data[NewDataT](self, data: NewDataT) -> Patch[AnchorT, IndicesT, NewDataT]:
        """Return a data-replaced copy that does not own this patch's release slot.

        Raises:
            TypeError: ``data`` is a georeader ``GeoTensor`` (convert it with
                ``geoarray.interop.georeader.from_georeader``).
        """
        reject_georeader_data(data, "Patch.with_data")
        return replace(self, data=data, _release=None)

with_data(data)

Return a data-replaced copy that does not own this patch's release slot.

Raises:

Type Description
TypeError

data is a georeader GeoTensor (convert it with geoarray.interop.georeader.from_georeader).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/patch.py
def with_data[NewDataT](self, data: NewDataT) -> Patch[AnchorT, IndicesT, NewDataT]:
    """Return a data-replaced copy that does not own this patch's release slot.

    Raises:
        TypeError: ``data`` is a georeader ``GeoTensor`` (convert it with
            ``geoarray.interop.georeader.from_georeader``).
    """
    reject_georeader_data(data, "Patch.with_data")
    return replace(self, data=data, _release=None)

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
@dataclass(eq=False)
class TemporalPatch[AnchorT, IndicesT, DataT](_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".
    """

    data: DataT
    anchor: AnchorT
    indices: IndicesT
    weights: Any | None = None
    window_index: int | None = None
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

    def with_data[NewDataT](
        self, data: NewDataT
    ) -> TemporalPatch[AnchorT, IndicesT, NewDataT]:
        """Return a data-replaced copy that does not own this patch's release slot."""
        reject_georeader_data(data, "TemporalPatch.with_data")
        return replace(self, data=data, _release=None)

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
def with_data[NewDataT](
    self, data: NewDataT
) -> TemporalPatch[AnchorT, IndicesT, NewDataT]:
    """Return a data-replaced copy that does not own this patch's release slot."""
    reject_georeader_data(data, "TemporalPatch.with_data")
    return replace(self, data=data, _release=None)

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
@dataclass(eq=False)
class SpatioTemporalPatch(_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.
    """

    data: Any
    space: Any
    time: Any
    spatial_indices: Any = None
    temporal_indices: Any = None
    weights: Any = field(default=None)
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

    def with_data(self, data: Any) -> SpatioTemporalPatch:
        """Return a data-replaced copy that does not own this patch's release slot."""
        reject_georeader_data(data, "SpatioTemporalPatch.with_data")
        return replace(self, data=data, _release=None)

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
def with_data(self, data: Any) -> SpatioTemporalPatch:
    """Return a data-replaced copy that does not own this patch's release slot."""
    reject_georeader_data(data, "SpatioTemporalPatch.with_data")
    return replace(self, data=data, _release=None)

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
@runtime_checkable
class Field(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.
    """

    @property
    def domain(self) -> Domain: ...

    def select(self, indexer: Any) -> Any: ...

    def with_data(self, array: Any) -> Any: ...

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
@runtime_checkable
class AsyncField(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`.
    """

    @property
    def domain(self) -> Domain: ...

    async def select(self, indexer: Any) -> Any: ...

    async def aselect(self, indexer: Any) -> Any: ...

    def with_data(self, array: Any) -> Any: ...

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
@runtime_checkable
class Domain(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.
    """

    @property
    def crs(self) -> Any: ...

    @property
    def bounds(self) -> Any: ...

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 geoarray.RasterSource. A georeader GeoTensor or reader is refused; convert it with geoarray.interop.georeader.from_georeader / source_from_georeader.

required

Raises:

Type Description
TypeError

reader is a georeader object or not a RasterSource.

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
@dataclass(eq=False)
class RasterField:
    """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.

    Args:
        reader: Any `geoarray.RasterSource`. A georeader ``GeoTensor`` or
            reader is refused; convert it with
            ``geoarray.interop.georeader.from_georeader`` /
            ``source_from_georeader``.

    Raises:
        TypeError: ``reader`` is a georeader object or not a `RasterSource`.

    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)
    """

    reader: RasterSource

    def __post_init__(self) -> None:
        _require_source(self.reader, "RasterField", RasterSource)

    @property
    def domain(self) -> RasterSource:
        return self.reader

    def select(self, window: Any) -> GeoArray:
        """Read ``window`` (boundless) as a `GeoArray` on the window's grid.

        Args:
            window: A ``rasterio.windows.Window`` (what the geometries
                produce) or a `geoarray.PixelWindow`.

        Returns:
            ``(..., window.height, window.width)``; pixels past the grid
            hold the source's ``fill_value`` (a source without one raises
            when the window leaves the grid).
        """
        return self.reader.read_window(as_pixel_window(window), boundless=True)

    def with_data(self, array: Any) -> GeoArray:
        """``array`` (``(..., H, W)`` on the source grid) as a `GeoArray`."""
        return _rewrap(self.reader, array, self.reader.grid)

    def __getstate__(self) -> dict[str, Any]:
        return _pack_reader_state(self.__dict__)

    def __setstate__(self, state: dict[str, Any]) -> None:
        self.__dict__.update(_unpack_reader_state(state))

select(window)

Read window (boundless) as a GeoArray on the window's grid.

Parameters:

Name Type Description Default
window Any

A rasterio.windows.Window (what the geometries produce) or a geoarray.PixelWindow.

required

Returns:

Type Description
GeoArray

(..., window.height, window.width); pixels past the grid

GeoArray

hold the source's fill_value (a source without one raises

GeoArray

when the window leaves the grid).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/raster.py
def select(self, window: Any) -> GeoArray:
    """Read ``window`` (boundless) as a `GeoArray` on the window's grid.

    Args:
        window: A ``rasterio.windows.Window`` (what the geometries
            produce) or a `geoarray.PixelWindow`.

    Returns:
        ``(..., window.height, window.width)``; pixels past the grid
        hold the source's ``fill_value`` (a source without one raises
        when the window leaves the grid).
    """
    return self.reader.read_window(as_pixel_window(window), boundless=True)

with_data(array)

array ((..., H, W) on the source grid) as a GeoArray.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/fields/raster.py
def with_data(self, array: Any) -> GeoArray:
    """``array`` (``(..., H, W)`` on the source grid) as a `GeoArray`."""
    return _rewrap(self.reader, array, self.reader.grid)