Skip to content

Matched multi-source patching — geopatcher.matched

Co-located patching across N sources: a MatchedField wraps one primary Field plus named secondaries and per-secondary coregistration callables, and is split and merged per source by the matched patchers. See ADR-003 in Design decisions and the query → matchup → patch design.

from geopatcher.matched import MatchedField, MatchedSpatialPatcher

Field

geopatcher.matched.MatchedField dataclass

N co-registered Fields presented as one Field.

Parameters:

Name Type Description Default
primary Field

The Field that defines the anchor space, CRS, and domain. Existing samplers run against this.

required
secondaries Mapping[str, Field]

{name: Field} for the matched secondaries. Names appear as keys in MatchedPatch.members.

dict()
coreg Mapping[str, CoregFn]

{name: CoregFn} — one coregistration callable per secondary. Typically a geoops.geom.coregister.* operator, but any Callable[[Any, Any], Any] works. The callable is invoked as coreg[name](raw_secondary, primary_patch) and its return value lands in MatchedPatch.members[name].data.

dict()
valid_mask bool

When True, the matched patchers (MatchedSpatialPatcher, MatchedTemporalPatcher, MatchedSpatioTemporalPatcher) compute a per-source valid_mask (True = data present) and pack it on each matched patch: False where a member equals its carrier's declared nodata (fill_value / rio.nodata) and, for float data, where it is NaN / ±inf. Useful when secondaries have partial coverage (LEO swath ↔ GEO grid). MatchedField.select itself returns data only, so a plain SpatialPatcher over a MatchedField yields no masks.

True
Notes

The set of keys in secondaries and coreg must match exactly; mismatched keys raise on construction.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/field.py
@dataclass(eq=False)
class MatchedField:
    """N co-registered Fields presented as one `Field`.

    Args:
        primary: The `Field` that defines the anchor space, CRS,
            and domain. Existing samplers run against this.
        secondaries: ``{name: Field}`` for the matched secondaries.
            Names appear as keys in `MatchedPatch.members`.
        coreg: ``{name: CoregFn}`` — one coregistration callable
            per secondary. Typically a
            ``geoops.geom.coregister.*`` operator, but any
            ``Callable[[Any, Any], Any]`` works. The callable is
            invoked as ``coreg[name](raw_secondary, primary_patch)``
            and its return value lands in
            ``MatchedPatch.members[name].data``.
        valid_mask: When True, the matched patchers
            (`MatchedSpatialPatcher`, `MatchedTemporalPatcher`,
            `MatchedSpatioTemporalPatcher`) compute a per-source
            ``valid_mask`` (True = data present) and pack it on each
            matched patch: False where a member equals its carrier's
            declared nodata (``fill_value`` / ``rio.nodata``)
            and, for float data, where it is NaN / ±inf. Useful when
            secondaries have partial coverage (LEO swath ↔ GEO grid).
            `MatchedField.select` itself returns data only, so a plain
            `SpatialPatcher` over a `MatchedField` yields no masks.

    Notes:
        The set of keys in ``secondaries`` and ``coreg`` must match
        exactly; mismatched keys raise on construction.
    """

    primary: Field
    secondaries: Mapping[str, Field] = field(default_factory=dict)
    coreg: Mapping[str, CoregFn] = field(default_factory=dict)
    valid_mask: bool = True

    # Carries live Field handles and coregistration callables, which
    # are not reconstructable from config — mirror the
    # `spatial.aggregation.Learned` convention and forbid YAML round-trips.
    forbid_in_yaml: ClassVar[bool] = True

    def get_config(self) -> dict[str, Any]:
        """Best-effort, JSON-able description of this composite field.

        `Field` instances and coregistration callables are not
        config-serializable (they carry live data handles / closures),
        so each member is represented as a ``{"class": name}`` envelope
        without a ``config`` payload — enough to identify the pipeline
        shape, not enough to reconstruct it (hence
        ``forbid_in_yaml = True``).

        Returns:
            Dict with the primary's class-name envelope, per-secondary
            class-name envelopes keyed by member name, and the
            ``valid_mask`` flag.
        """
        return {
            "primary": {"class": type(self.primary).__name__},
            "secondaries": {
                name: {"class": type(f).__name__}
                for name, f in self.secondaries.items()
            },
            "valid_mask": self.valid_mask,
        }

    def __post_init__(self) -> None:
        sec_keys = set(self.secondaries.keys())
        cor_keys = set(self.coreg.keys())
        if sec_keys != cor_keys:
            missing = sec_keys - cor_keys
            extra = cor_keys - sec_keys
            raise ValueError(
                "MatchedField.secondaries and .coreg must have the same keys; "
                f"missing coreg for {sorted(missing)!r}, "
                f"extra coreg for {sorted(extra)!r}."
            )
        # `PRIMARY_KEY` is reserved for the primary in `MatchedPatch.members`;
        # a secondary named "primary" would silently overwrite it on
        # patch construction. Reject up front with a clear message.
        if PRIMARY_KEY in sec_keys:
            raise ValueError(
                f"MatchedField.secondaries cannot use the reserved key "
                f"{PRIMARY_KEY!r}; pick another name."
            )

    @property
    def domain(self) -> Domain:
        """Forward the primary's domain so existing samplers work."""
        return self.primary.domain

    def select(self, indexer: Any) -> dict[str, Any]:
        """Read primary + all secondaries at ``indexer`` and align them.

        Returns a `dict[str, data]` keyed by source name — the primary
        under ``PRIMARY_KEY`` (``"primary"``), each secondary under
        the name supplied to `MatchedField.secondaries`. The values
        are whatever the underlying Fields' `select` returns: a
        `geoarray.GeoArray` for raster, a sub-`xarray.DataArray` for grid,
        etc.

        Each secondary is read over the primary chip's geographic
        footprint (see the module docstring), so the coreg callable
        receives a raw chip covering the whole primary chip even when
        the secondary's grid differs in resolution, origin or CRS.

        The per-source aligned data flows through `Patch.data` when
        a plain `SpatialPatcher` consumes a `MatchedField`. Consumers
        that want the matched-patch carrier shape go through
        `MatchedSpatialPatcher.split`, which unpacks the dict.
        """
        return self._select(indexer, _plain_read)

    def _select(self, indexer: Any, read: SourceRead) -> dict[str, Any]:
        """`select` body with each source read routed through ``read``.

        ``read(name, field, indexer)`` performs one source's read;
        `MatchedSpatialPatcher.split(cache=...)` passes one that consults
        a `PatchCache` keyed per source, while the coregistration still
        runs on every call.
        """
        primary_data = read(PRIMARY_KEY, self.primary, indexer)
        result: dict[str, Any] = {PRIMARY_KEY: primary_data}
        primary_domain = self.primary.domain
        for name, sec in self.secondaries.items():
            sec_indexer = _footprint_indexer(indexer, primary_domain, sec.domain)
            raw = read(name, sec, sec_indexer)
            # Coreg callable: (secondary_raw, primary_data) -> aligned.
            # The runtime contract is intentionally loose so any
            # callable — pipekit_ops.Operator, partial, lambda — works.
            result[name] = self.coreg[name](raw, primary_data)
        return result

    def with_data(self, array: Any) -> Any:
        """Forward to the primary — every source is merged on its grid.

        The single-array ``with_data`` signature is the primary's
        reconstruction path. `MatchedSpatialPatcher.merge` returns each
        source's raw aggregation output on the primary's grid;
        `MatchedSpatialPatcher.merge_to_field` wraps every one of them
        through this (the primary's) ``with_data``, since the
        coregistration already mapped each secondary onto that grid.
        """
        reject_georeader(array, "MatchedField.with_data")
        return self.primary.with_data(array)

domain property

Forward the primary's domain so existing samplers work.

get_config()

Best-effort, JSON-able description of this composite field.

Field instances and coregistration callables are not config-serializable (they carry live data handles / closures), so each member is represented as a {"class": name} envelope without a config payload — enough to identify the pipeline shape, not enough to reconstruct it (hence forbid_in_yaml = True).

Returns:

Type Description
dict[str, Any]

Dict with the primary's class-name envelope, per-secondary

dict[str, Any]

class-name envelopes keyed by member name, and the

dict[str, Any]

valid_mask flag.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/field.py
def get_config(self) -> dict[str, Any]:
    """Best-effort, JSON-able description of this composite field.

    `Field` instances and coregistration callables are not
    config-serializable (they carry live data handles / closures),
    so each member is represented as a ``{"class": name}`` envelope
    without a ``config`` payload — enough to identify the pipeline
    shape, not enough to reconstruct it (hence
    ``forbid_in_yaml = True``).

    Returns:
        Dict with the primary's class-name envelope, per-secondary
        class-name envelopes keyed by member name, and the
        ``valid_mask`` flag.
    """
    return {
        "primary": {"class": type(self.primary).__name__},
        "secondaries": {
            name: {"class": type(f).__name__}
            for name, f in self.secondaries.items()
        },
        "valid_mask": self.valid_mask,
    }

select(indexer)

Read primary + all secondaries at indexer and align them.

Returns a dict[str, data] keyed by source name — the primary under PRIMARY_KEY ("primary"), each secondary under the name supplied to MatchedField.secondaries. The values are whatever the underlying Fields' select returns: a geoarray.GeoArray for raster, a sub-xarray.DataArray for grid, etc.

Each secondary is read over the primary chip's geographic footprint (see the module docstring), so the coreg callable receives a raw chip covering the whole primary chip even when the secondary's grid differs in resolution, origin or CRS.

The per-source aligned data flows through Patch.data when a plain SpatialPatcher consumes a MatchedField. Consumers that want the matched-patch carrier shape go through MatchedSpatialPatcher.split, which unpacks the dict.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/field.py
def select(self, indexer: Any) -> dict[str, Any]:
    """Read primary + all secondaries at ``indexer`` and align them.

    Returns a `dict[str, data]` keyed by source name — the primary
    under ``PRIMARY_KEY`` (``"primary"``), each secondary under
    the name supplied to `MatchedField.secondaries`. The values
    are whatever the underlying Fields' `select` returns: a
    `geoarray.GeoArray` for raster, a sub-`xarray.DataArray` for grid,
    etc.

    Each secondary is read over the primary chip's geographic
    footprint (see the module docstring), so the coreg callable
    receives a raw chip covering the whole primary chip even when
    the secondary's grid differs in resolution, origin or CRS.

    The per-source aligned data flows through `Patch.data` when
    a plain `SpatialPatcher` consumes a `MatchedField`. Consumers
    that want the matched-patch carrier shape go through
    `MatchedSpatialPatcher.split`, which unpacks the dict.
    """
    return self._select(indexer, _plain_read)

with_data(array)

Forward to the primary — every source is merged on its grid.

The single-array with_data signature is the primary's reconstruction path. MatchedSpatialPatcher.merge returns each source's raw aggregation output on the primary's grid; MatchedSpatialPatcher.merge_to_field wraps every one of them through this (the primary's) with_data, since the coregistration already mapped each secondary onto that grid.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/field.py
def with_data(self, array: Any) -> Any:
    """Forward to the primary — every source is merged on its grid.

    The single-array ``with_data`` signature is the primary's
    reconstruction path. `MatchedSpatialPatcher.merge` returns each
    source's raw aggregation output on the primary's grid;
    `MatchedSpatialPatcher.merge_to_field` wraps every one of them
    through this (the primary's) ``with_data``, since the
    coregistration already mapped each secondary onto that grid.
    """
    reject_georeader(array, "MatchedField.with_data")
    return self.primary.with_data(array)

Carriers

geopatcher.matched.MatchedPatch dataclass

Bases: _MatchedMembersBase['Patch']

A co-located patch read from N sources at a single anchor.

Parameters:

Name Type Description Default
anchor Any

Where the patch lives in the primary's coordinate system. Same shape the primary's Sampler emits.

required
members dict[str, Patch]

{name: Patch}. members["primary"] is the primary; secondary keys are the names given to MatchedField.secondaries.

required
valid_mask dict[str, ndarray] | None

Optional {name: ndarray} of per-source masks indicating which pixels of each member contain valid data (False = nodata / out-of-swath / off-edge). When a secondary's coregistration produces partial coverage — e.g. the LEO swath only crosses half the GEO patch — the mask is the workhorse the downstream operator uses to decide what to ignore.

None
weights dict[str, ndarray] | None

Optional {name: ndarray} of per-source window weights. The matched patchers fill it from each member's weights (the primary window's weights, since every member is on the primary's grid); None when the window has none.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patch.py
@dataclass(eq=False)
class MatchedPatch(_MatchedMembersBase["Patch"]):
    """A co-located patch read from N sources at a single anchor.

    Args:
        anchor: Where the patch lives in the primary's coordinate
            system. Same shape the primary's `Sampler` emits.
        members: ``{name: Patch}``. ``members["primary"]`` is the
            primary; secondary keys are the names given to
            `MatchedField.secondaries`.
        valid_mask: Optional ``{name: ndarray}`` of per-source masks
            indicating which pixels of each member contain valid
            data (False = nodata / out-of-swath / off-edge). When a
            secondary's coregistration produces partial coverage —
            e.g. the LEO swath only crosses half the GEO patch —
            the mask is the workhorse the downstream operator uses
            to decide what to ignore.
        weights: Optional ``{name: ndarray}`` of per-source window
            weights. The matched patchers fill it from each member's
            ``weights`` (the primary window's weights, since every
            member is on the primary's grid); `None` when the window
            has none.
    """

    anchor: Any
    members: dict[str, Patch]
    valid_mask: dict[str, np.ndarray] | None = None
    weights: dict[str, np.ndarray] | None = field(default=None)
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

geopatcher.matched.MatchedTemporalPatch dataclass

Bases: _MatchedMembersBase['TemporalPatch']

A co-located temporal patch read from N sources at a single anchor.

Sibling of MatchedPatch for the temporal axis. members holds TemporalPatch values rather than Patch so the temporal anchor (an int time index) and indices (a slice along the time axis) flow through to downstream temporal.aggregation.Aggregation consumers.

Parameters:

Name Type Description Default
anchor Any

The time-index anchor in the primary's time axis.

required
members dict[str, TemporalPatch]

{name: TemporalPatch}. members["primary"] is the primary; secondary keys are the names given to MatchedField.secondaries.

required
valid_mask dict[str, ndarray] | None

Optional {name: ndarray} of per-source masks indicating which time steps of each member contain valid data (False = nodata / gap / off-edge).

None
weights dict[str, ndarray] | None

Optional {name: ndarray} of per-source time weights, filled by MatchedTemporalPatcher from each member's weights.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patch.py
@dataclass(eq=False)
class MatchedTemporalPatch(_MatchedMembersBase["TemporalPatch"]):
    """A co-located temporal patch read from N sources at a single anchor.

    Sibling of `MatchedPatch` for the temporal axis. ``members`` holds
    `TemporalPatch` values rather than `Patch` so the temporal
    ``anchor`` (an ``int`` time index) and ``indices`` (a ``slice``
    along the time axis) flow through to downstream
    `temporal.aggregation.Aggregation` consumers.

    Args:
        anchor: The time-index anchor in the primary's time axis.
        members: ``{name: TemporalPatch}``. ``members["primary"]`` is
            the primary; secondary keys are the names given to
            `MatchedField.secondaries`.
        valid_mask: Optional ``{name: ndarray}`` of per-source masks
            indicating which time steps of each member contain valid
            data (False = nodata / gap / off-edge).
        weights: Optional ``{name: ndarray}`` of per-source time
            weights, filled by `MatchedTemporalPatcher` from each
            member's ``weights``.
    """

    anchor: Any
    members: dict[str, TemporalPatch]
    valid_mask: dict[str, np.ndarray] | None = None
    weights: dict[str, np.ndarray] | None = field(default=None)
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

geopatcher.matched.MatchedSpatioTemporalPatch dataclass

Bases: _MatchedMembersBase['SpatioTemporalPatch']

A co-located spatio-temporal patch read from N sources.

Sibling of MatchedPatch for the spatio-temporal axis. members holds SpatioTemporalPatch values so both spatial and temporal anchors flow through to downstream aggregations.

Parameters:

Name Type Description Default
space Any

Spatial anchor in the primary's coordinate system.

required
time Any

Time anchor in the primary's time axis.

required
members dict[str, SpatioTemporalPatch]

{name: SpatioTemporalPatch}. members["primary"] is the primary; secondary keys are the names given to MatchedField.secondaries.

required
valid_mask dict[str, ndarray] | None

Optional {name: ndarray} of per-source masks indicating which pixels/time steps of each member contain valid data.

None
weights dict[str, ndarray] | None

Optional {name: ndarray} of per-source weights, filled by MatchedSpatioTemporalPatcher from each member's weights.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patch.py
@dataclass(eq=False)
class MatchedSpatioTemporalPatch(_MatchedMembersBase["SpatioTemporalPatch"]):
    """A co-located spatio-temporal patch read from N sources.

    Sibling of `MatchedPatch` for the spatio-temporal axis. ``members``
    holds `SpatioTemporalPatch` values so both spatial and temporal
    anchors flow through to downstream aggregations.

    Args:
        space: Spatial anchor in the primary's coordinate system.
        time: Time anchor in the primary's time axis.
        members: ``{name: SpatioTemporalPatch}``.
            ``members["primary"]`` is the primary; secondary keys are
            the names given to `MatchedField.secondaries`.
        valid_mask: Optional ``{name: ndarray}`` of per-source masks
            indicating which pixels/time steps of each member contain
            valid data.
        weights: Optional ``{name: ndarray}`` of per-source weights,
            filled by `MatchedSpatioTemporalPatcher` from each member's
            ``weights``.
    """

    space: Any
    time: Any
    members: dict[str, SpatioTemporalPatch]
    valid_mask: dict[str, np.ndarray] | None = None
    weights: dict[str, np.ndarray] | None = field(default=None)
    _release: Callable[[], None] | None = field(default=None, repr=False, compare=False)

Patchers

geopatcher.matched.MatchedSpatialPatcher dataclass

Bases: _MatchedConfigMixin

Spatial patcher that yields MatchedPatches and merges per-source.

Parameters:

Name Type Description Default
primary SpatialPatcher

A regular SpatialPatcher configured for the primary Field. Drives anchor placement, geometry, window, primary aggregation and the on_error policy (which covers every source's read and coregistration).

required
secondary_aggregators Mapping[str, Aggregation]

{name: spatial.aggregation.Aggregation} — one aggregator per secondary. Names that don't match any entry in mfield.secondaries raise on split / merge rather than silently skipping (catches config typos like "s22" instead of "s2"). Omitting a secondary from this mapping is fine — that source is simply not merged back, which is the documented opt-out.

dict()
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
@dataclass(eq=False)
class MatchedSpatialPatcher(_MatchedConfigMixin):
    """Spatial patcher that yields `MatchedPatch`es and merges per-source.

    Args:
        primary: A regular `SpatialPatcher` configured for the
            primary `Field`. Drives anchor placement, geometry,
            window, primary aggregation and the ``on_error`` policy
            (which covers every source's read and coregistration).
        secondary_aggregators: ``{name: spatial.aggregation.Aggregation}`` — one
            aggregator per secondary. Names that don't match any
            entry in ``mfield.secondaries`` raise on ``split`` /
            ``merge`` rather than silently skipping (catches config
            typos like ``"s22"`` instead of ``"s2"``). Omitting a
            secondary from this mapping is fine — that source is
            simply not merged back, which is the documented opt-out.
    """

    primary: SpatialPatcher
    secondary_aggregators: Mapping[str, SpatialAggregation] = field(
        default_factory=dict
    )

    def split(
        self,
        mfield: MatchedField,
        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[MatchedPatch]:
        """Yield `MatchedPatch`es by walking ``mfield`` with the primary's sampler.

        Internally drives ``self.primary.split(mfield)`` — since
        `MatchedField` already satisfies the `Field` Protocol, the
        existing sampler / geometry / window machinery works
        unchanged. Each outer ``Patch`` carries the per-source
        ``dict`` returned by `MatchedField.select` in its ``data``
        field; this method unpacks that dict into a `MatchedPatch`
        whose ``members`` is ``{name: Patch}``, whose ``anchor`` /
        ``indices`` / ``weights`` mirror the outer patch, and whose
        ``weights`` maps each member to its window weights.

        Per-source ``valid_mask`` arrays are computed when
        ``mfield.valid_mask`` is True (the default): for numeric
        array-coercible data a cell is invalid where it equals the
        carrier's declared nodata (``fill_value`` /
        ``rio.nodata``) or, for float data, is NaN / ±inf. Non-array
        members are simply omitted from the mask dict (and the dict
        drops to ``None`` if no member produced a mask).

        The primary's ``on_error`` policy covers every source: a failed
        read or coregistration raises (``"raise"``), drops the anchor
        (``"skip"`` / exhausted ``"retry"``), or under ``"mask"`` yields a
        `MatchedPatch` whose every member is the all-NaN placeholder on the
        primary's grid with an all-False ``valid_mask``.

        Args:
            mfield: A `MatchedField` to drive the primary sampler over.
            hooks: Optional observability hooks, dispatched by the primary
                `SpatialPatcher.split` once per matched patch; the
                ``on_patch_done`` byte count sums every member.
            prefetch: Forwarded to `SpatialPatcher.split` — read ahead up
                to this many matched patches on a background thread.
            journal: Forwarded to `SpatialPatcher.split` — anchors the
                `PatchJournal` already holds are skipped.
            cache: A `PatchCache` consulted per source: each source's raw
                read is keyed on its own identity and role name, so a hit
                skips that source's I/O (the coregistration still runs).
                In-memory sources need ``PatchCache(field_id=...)``.
            max_in_flight: Forwarded to `SpatialPatcher.split`; each
                yielded `MatchedPatch` owns the slot — release it with
                ``mp.close()`` or ``with mp: ...``.
            max_in_flight_bytes: Forwarded to `SpatialPatcher.split`; a
                matched patch is sized as the sum of its members' bytes.
        """
        _validate_aggregator_names(
            self.secondary_aggregators, mfield, type(self).__name__
        )
        source: Any = mfield if cache is None else _CachedSourceReads(mfield, cache)
        outers = self.primary.split(
            source,
            hooks=hooks,
            prefetch=prefetch,
            journal=journal,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
        )
        cls_name = type(self).__name__
        for outer in outers:
            data_by_name, masked = _unpack_matched(
                outer, mfield, cls_name, "each Patch.data to be"
            )
            members = {
                name: outer.with_data(data) for name, data in data_by_name.items()
            }
            matched = MatchedPatch(
                anchor=outer.anchor,
                members=members,
                valid_mask=_compute_member_masks(members, mfield, masked=masked),
                weights=_member_weights(members),
            )
            _hand_over_release(outer, matched)
            yield matched

    def n_anchors(self, mfield: MatchedField) -> int:
        """Number of `MatchedPatch`es ``split`` will yield (no reads)."""
        return self.primary.n_anchors(mfield)

    def anchors(self, mfield: MatchedField) -> list[Any]:
        """Materialise the sampler's anchor sequence for ``mfield`` (no reads)."""
        return self.primary.anchors(mfield)

    def merge(
        self,
        patches: Iterable[MatchedPatch],
        mfield: MatchedField,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> dict[str, Any]:
        """Per-source merge: dict of ``name -> aggregation result``.

        Returns the primary under ``MatchedPatch.PRIMARY_KEY``;
        secondaries appear under the names supplied to
        ``MatchedField.secondaries``. Names whose
        ``secondary_aggregators`` entry is missing are skipped (you
        can choose to only reconstruct a subset). Names that *are*
        in ``secondary_aggregators`` but not in
        ``mfield.secondaries`` raise — typo guard.

        Each value is the aggregation's raw output, exactly as
        `SpatialPatcher.merge` returns it: a bare ``np.ndarray`` on the
        primary's grid for the dense aggregations (no transform, CRS,
        nodata or attrs), a ``dict`` for `spatial.aggregation.MeanStd` /
        `spatial.aggregation.InvVarWeightedMean` / `spatial.aggregation.ByIndex`. Use
        `merge_to_field` to get georeferenced carriers back.

        Every source is aggregated against the primary's domain
        because the coregistration callable mapped each secondary
        onto the primary's grid at split time. Reconstructing a
        secondary back into its own original grid would require
        re-inverting the coregistration, which is the user's
        problem if they need it.

        Streaming: ``patches`` is consumed once and each source's
        aggregation runs on its own thread over a bounded queue, so only
        a few patches per source are resident at a time — a streaming
        aggregation (e.g. zarr-backed `spatial.aggregation.OverlapAdd`) keeps its
        bound on every source. Every aggregation (primary and secondary)
        gets the strict-mode streaming-safety check, which warns (or
        raises under `set_strict`) for a ``streaming_safe = False`` one.

        Args:
            patches: Iterable of `MatchedPatch` instances; each is closed
                once its members are handed on.
            mfield: Original `MatchedField` (used for typo-guard and
                to recover the primary domain for aggregation).
            hooks: Optional observability hooks, dispatched once at the
                matched level (one ``on_merge_start`` / ``on_merge_end``
                per call; the output bytes sum every source).
        """
        return self._merge_sources(patches, mfield, hooks, stacklevel=2)

    def merge_to_field(
        self,
        patches: Iterable[MatchedPatch],
        mfield: MatchedField,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> dict[str, Any]:
        """`merge` + rebuild each source on the primary's grid via ``with_data``.

        Every source was aggregated on the primary's domain, so each
        value is wrapped with ``mfield.primary.with_data`` — it carries
        the primary's transform and CRS, and also the primary's nodata
        and attrs (a secondary's own nodata / attrs are not carried; its
        values keep that secondary's dtype when they fit, by the
        `SpatialPatcher.merge_to_xarray` rule).

        Raises:
            TypeError: As `SpatialPatcher.merge_to_field` — for a ``dict``
                output, a non-array output, or a shape that is not the
                primary domain's.
        """
        from geopatcher._src.spatial.patcher import (
            _domain_shape,
            _field_values,
            _is_raster_field,
            _merge_nodata,
            _require_with_data,
            _source_dtype,
            _source_fill,
            _with_nodata,
        )

        with_data = _require_with_data(mfield.primary, "merge_to_field")
        merged = self._merge_sources(patches, mfield, hooks, stacklevel=2)
        shape = _domain_shape(mfield.domain)
        out: dict[str, Any] = {}
        for name, value in merged.items():
            if name == PRIMARY_KEY:
                agg, source = self.primary.aggregation, mfield.primary
            else:
                agg, source = self.secondary_aggregators[name], mfield.secondaries[name]
            values = _field_values(
                value,
                agg,
                shape=shape,
                dtype=_source_dtype(source),
                caller="merge_to_field",
                bands_may_change=_is_raster_field(mfield.primary),
            )
            values, fill = _merge_nodata(
                values,
                agg,
                shape=shape,
                dtype=_source_dtype(source),
                source_fill=_source_fill(source),
            )
            out[name] = _with_nodata(with_data(values), fill)
        return out

    def _merge_sources(
        self,
        patches: Iterable[MatchedPatch],
        mfield: MatchedField,
        hooks: Iterable[PatcherHook] | None,
        *,
        stacklevel: int,
    ) -> dict[str, Any]:
        """`merge` body; ``stacklevel`` (from the caller) places the warning."""
        from geopatcher._src.spatial.patcher import (
            _check_streaming,
            refusing_georeader,
        )

        patches = refusing_georeader(patches, "merge")
        _validate_aggregator_names(
            self.secondary_aggregators, mfield, type(self).__name__
        )
        aggregations = {
            PRIMARY_KEY: self.primary.aggregation,
            **self.secondary_aggregators,
        }
        for agg in aggregations.values():
            _check_streaming(agg, stacklevel=stacklevel + 1)
        domain = mfield.domain

        def consumer(agg: Any) -> Callable[[Iterator[Any]], Any]:
            return lambda members: agg.merge(members, domain)

        return _merge_per_source(
            patches,
            {name: consumer(agg) for name, agg in aggregations.items()},
            hooks,
        )

anchors(mfield)

Materialise the sampler's anchor sequence for mfield (no reads).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def anchors(self, mfield: MatchedField) -> list[Any]:
    """Materialise the sampler's anchor sequence for ``mfield`` (no reads)."""
    return self.primary.anchors(mfield)

merge(patches, mfield, hooks=None)

Per-source merge: dict of name -> aggregation result.

Returns the primary under MatchedPatch.PRIMARY_KEY; secondaries appear under the names supplied to MatchedField.secondaries. Names whose secondary_aggregators entry is missing are skipped (you can choose to only reconstruct a subset). Names that are in secondary_aggregators but not in mfield.secondaries raise — typo guard.

Each value is the aggregation's raw output, exactly as SpatialPatcher.merge returns it: a bare np.ndarray on the primary's grid for the dense aggregations (no transform, CRS, nodata or attrs), a dict for spatial.aggregation.MeanStd / spatial.aggregation.InvVarWeightedMean / spatial.aggregation.ByIndex. Use merge_to_field to get georeferenced carriers back.

Every source is aggregated against the primary's domain because the coregistration callable mapped each secondary onto the primary's grid at split time. Reconstructing a secondary back into its own original grid would require re-inverting the coregistration, which is the user's problem if they need it.

Streaming: patches is consumed once and each source's aggregation runs on its own thread over a bounded queue, so only a few patches per source are resident at a time — a streaming aggregation (e.g. zarr-backed spatial.aggregation.OverlapAdd) keeps its bound on every source. Every aggregation (primary and secondary) gets the strict-mode streaming-safety check, which warns (or raises under set_strict) for a streaming_safe = False one.

Parameters:

Name Type Description Default
patches Iterable[MatchedPatch]

Iterable of MatchedPatch instances; each is closed once its members are handed on.

required
mfield MatchedField

Original MatchedField (used for typo-guard and to recover the primary domain for aggregation).

required
hooks Iterable[PatcherHook] | None

Optional observability hooks, dispatched once at the matched level (one on_merge_start / on_merge_end per call; the output bytes sum every source).

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def merge(
    self,
    patches: Iterable[MatchedPatch],
    mfield: MatchedField,
    hooks: Iterable[PatcherHook] | None = None,
) -> dict[str, Any]:
    """Per-source merge: dict of ``name -> aggregation result``.

    Returns the primary under ``MatchedPatch.PRIMARY_KEY``;
    secondaries appear under the names supplied to
    ``MatchedField.secondaries``. Names whose
    ``secondary_aggregators`` entry is missing are skipped (you
    can choose to only reconstruct a subset). Names that *are*
    in ``secondary_aggregators`` but not in
    ``mfield.secondaries`` raise — typo guard.

    Each value is the aggregation's raw output, exactly as
    `SpatialPatcher.merge` returns it: a bare ``np.ndarray`` on the
    primary's grid for the dense aggregations (no transform, CRS,
    nodata or attrs), a ``dict`` for `spatial.aggregation.MeanStd` /
    `spatial.aggregation.InvVarWeightedMean` / `spatial.aggregation.ByIndex`. Use
    `merge_to_field` to get georeferenced carriers back.

    Every source is aggregated against the primary's domain
    because the coregistration callable mapped each secondary
    onto the primary's grid at split time. Reconstructing a
    secondary back into its own original grid would require
    re-inverting the coregistration, which is the user's
    problem if they need it.

    Streaming: ``patches`` is consumed once and each source's
    aggregation runs on its own thread over a bounded queue, so only
    a few patches per source are resident at a time — a streaming
    aggregation (e.g. zarr-backed `spatial.aggregation.OverlapAdd`) keeps its
    bound on every source. Every aggregation (primary and secondary)
    gets the strict-mode streaming-safety check, which warns (or
    raises under `set_strict`) for a ``streaming_safe = False`` one.

    Args:
        patches: Iterable of `MatchedPatch` instances; each is closed
            once its members are handed on.
        mfield: Original `MatchedField` (used for typo-guard and
            to recover the primary domain for aggregation).
        hooks: Optional observability hooks, dispatched once at the
            matched level (one ``on_merge_start`` / ``on_merge_end``
            per call; the output bytes sum every source).
    """
    return self._merge_sources(patches, mfield, hooks, stacklevel=2)

merge_to_field(patches, mfield, hooks=None)

merge + rebuild each source on the primary's grid via with_data.

Every source was aggregated on the primary's domain, so each value is wrapped with mfield.primary.with_data — it carries the primary's transform and CRS, and also the primary's nodata and attrs (a secondary's own nodata / attrs are not carried; its values keep that secondary's dtype when they fit, by the SpatialPatcher.merge_to_xarray rule).

Raises:

Type Description
TypeError

As SpatialPatcher.merge_to_field — for a dict output, a non-array output, or a shape that is not the primary domain's.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def merge_to_field(
    self,
    patches: Iterable[MatchedPatch],
    mfield: MatchedField,
    hooks: Iterable[PatcherHook] | None = None,
) -> dict[str, Any]:
    """`merge` + rebuild each source on the primary's grid via ``with_data``.

    Every source was aggregated on the primary's domain, so each
    value is wrapped with ``mfield.primary.with_data`` — it carries
    the primary's transform and CRS, and also the primary's nodata
    and attrs (a secondary's own nodata / attrs are not carried; its
    values keep that secondary's dtype when they fit, by the
    `SpatialPatcher.merge_to_xarray` rule).

    Raises:
        TypeError: As `SpatialPatcher.merge_to_field` — for a ``dict``
            output, a non-array output, or a shape that is not the
            primary domain's.
    """
    from geopatcher._src.spatial.patcher import (
        _domain_shape,
        _field_values,
        _is_raster_field,
        _merge_nodata,
        _require_with_data,
        _source_dtype,
        _source_fill,
        _with_nodata,
    )

    with_data = _require_with_data(mfield.primary, "merge_to_field")
    merged = self._merge_sources(patches, mfield, hooks, stacklevel=2)
    shape = _domain_shape(mfield.domain)
    out: dict[str, Any] = {}
    for name, value in merged.items():
        if name == PRIMARY_KEY:
            agg, source = self.primary.aggregation, mfield.primary
        else:
            agg, source = self.secondary_aggregators[name], mfield.secondaries[name]
        values = _field_values(
            value,
            agg,
            shape=shape,
            dtype=_source_dtype(source),
            caller="merge_to_field",
            bands_may_change=_is_raster_field(mfield.primary),
        )
        values, fill = _merge_nodata(
            values,
            agg,
            shape=shape,
            dtype=_source_dtype(source),
            source_fill=_source_fill(source),
        )
        out[name] = _with_nodata(with_data(values), fill)
    return out

n_anchors(mfield)

Number of MatchedPatches split will yield (no reads).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def n_anchors(self, mfield: MatchedField) -> int:
    """Number of `MatchedPatch`es ``split`` will yield (no reads)."""
    return self.primary.n_anchors(mfield)

split(mfield, hooks=None, *, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)

Yield MatchedPatches by walking mfield with the primary's sampler.

Internally drives self.primary.split(mfield) — since MatchedField already satisfies the Field Protocol, the existing sampler / geometry / window machinery works unchanged. Each outer Patch carries the per-source dict returned by MatchedField.select in its data field; this method unpacks that dict into a MatchedPatch whose members is {name: Patch}, whose anchor / indices / weights mirror the outer patch, and whose weights maps each member to its window weights.

Per-source valid_mask arrays are computed when mfield.valid_mask is True (the default): for numeric array-coercible data a cell is invalid where it equals the carrier's declared nodata (fill_value / rio.nodata) or, for float data, is NaN / ±inf. Non-array members are simply omitted from the mask dict (and the dict drops to None if no member produced a mask).

The primary's on_error policy covers every source: a failed read or coregistration raises ("raise"), drops the anchor ("skip" / exhausted "retry"), or under "mask" yields a MatchedPatch whose every member is the all-NaN placeholder on the primary's grid with an all-False valid_mask.

Parameters:

Name Type Description Default
mfield MatchedField

A MatchedField to drive the primary sampler over.

required
hooks Iterable[PatcherHook] | None

Optional observability hooks, dispatched by the primary SpatialPatcher.split once per matched patch; the on_patch_done byte count sums every member.

None
prefetch int

Forwarded to SpatialPatcher.split — read ahead up to this many matched patches on a background thread.

0
journal Any | None

Forwarded to SpatialPatcher.split — anchors the PatchJournal already holds are skipped.

None
cache Any | None

A PatchCache consulted per source: each source's raw read is keyed on its own identity and role name, so a hit skips that source's I/O (the coregistration still runs). In-memory sources need PatchCache(field_id=...).

None
max_in_flight int | None

Forwarded to SpatialPatcher.split; each yielded MatchedPatch owns the slot — release it with mp.close() or with mp: ....

None
max_in_flight_bytes int | None

Forwarded to SpatialPatcher.split; a matched patch is sized as the sum of its members' bytes.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def split(
    self,
    mfield: MatchedField,
    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[MatchedPatch]:
    """Yield `MatchedPatch`es by walking ``mfield`` with the primary's sampler.

    Internally drives ``self.primary.split(mfield)`` — since
    `MatchedField` already satisfies the `Field` Protocol, the
    existing sampler / geometry / window machinery works
    unchanged. Each outer ``Patch`` carries the per-source
    ``dict`` returned by `MatchedField.select` in its ``data``
    field; this method unpacks that dict into a `MatchedPatch`
    whose ``members`` is ``{name: Patch}``, whose ``anchor`` /
    ``indices`` / ``weights`` mirror the outer patch, and whose
    ``weights`` maps each member to its window weights.

    Per-source ``valid_mask`` arrays are computed when
    ``mfield.valid_mask`` is True (the default): for numeric
    array-coercible data a cell is invalid where it equals the
    carrier's declared nodata (``fill_value`` /
    ``rio.nodata``) or, for float data, is NaN / ±inf. Non-array
    members are simply omitted from the mask dict (and the dict
    drops to ``None`` if no member produced a mask).

    The primary's ``on_error`` policy covers every source: a failed
    read or coregistration raises (``"raise"``), drops the anchor
    (``"skip"`` / exhausted ``"retry"``), or under ``"mask"`` yields a
    `MatchedPatch` whose every member is the all-NaN placeholder on the
    primary's grid with an all-False ``valid_mask``.

    Args:
        mfield: A `MatchedField` to drive the primary sampler over.
        hooks: Optional observability hooks, dispatched by the primary
            `SpatialPatcher.split` once per matched patch; the
            ``on_patch_done`` byte count sums every member.
        prefetch: Forwarded to `SpatialPatcher.split` — read ahead up
            to this many matched patches on a background thread.
        journal: Forwarded to `SpatialPatcher.split` — anchors the
            `PatchJournal` already holds are skipped.
        cache: A `PatchCache` consulted per source: each source's raw
            read is keyed on its own identity and role name, so a hit
            skips that source's I/O (the coregistration still runs).
            In-memory sources need ``PatchCache(field_id=...)``.
        max_in_flight: Forwarded to `SpatialPatcher.split`; each
            yielded `MatchedPatch` owns the slot — release it with
            ``mp.close()`` or ``with mp: ...``.
        max_in_flight_bytes: Forwarded to `SpatialPatcher.split`; a
            matched patch is sized as the sum of its members' bytes.
    """
    _validate_aggregator_names(
        self.secondary_aggregators, mfield, type(self).__name__
    )
    source: Any = mfield if cache is None else _CachedSourceReads(mfield, cache)
    outers = self.primary.split(
        source,
        hooks=hooks,
        prefetch=prefetch,
        journal=journal,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
    )
    cls_name = type(self).__name__
    for outer in outers:
        data_by_name, masked = _unpack_matched(
            outer, mfield, cls_name, "each Patch.data to be"
        )
        members = {
            name: outer.with_data(data) for name, data in data_by_name.items()
        }
        matched = MatchedPatch(
            anchor=outer.anchor,
            members=members,
            valid_mask=_compute_member_masks(members, mfield, masked=masked),
            weights=_member_weights(members),
        )
        _hand_over_release(outer, matched)
        yield matched

geopatcher.matched.MatchedTemporalPatcher dataclass

Bases: _MatchedConfigMixin

Temporal patcher that yields MatchedTemporalPatches and merges per-source.

Mirror of MatchedSpatialPatcher over the time axis. The TemporalPatcher slices a numpy array directly (it does not call Field.select per anchor the way SpatialPatcher does), so the matched-temporal split first reads every source's full series once — mfield.select(indexer), with an indexer covering the primary's whole extent (see split) — then drives the primary patcher on the primary's series and slices each secondary's array in lockstep.

Parameters:

Name Type Description Default
primary TemporalPatcher

A regular TemporalPatcher configured for the primary series. Drives anchor placement, geometry, window, and primary aggregation.

required
secondary_aggregators Mapping[str, Aggregation]

{name: temporal.aggregation.Aggregation} — one aggregator per secondary. Names that don't match any entry in mfield.secondaries raise on split / merge rather than silently skipping (typo guard). Omitting a secondary from this mapping is the documented opt-out for "don't reconstruct this source".

dict()
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
@dataclass(eq=False)
class MatchedTemporalPatcher(_MatchedConfigMixin):
    """Temporal patcher that yields `MatchedTemporalPatch`es and merges per-source.

    Mirror of `MatchedSpatialPatcher` over the time axis. The
    `TemporalPatcher` slices a numpy array directly (it does not call
    `Field.select` per anchor the way `SpatialPatcher` does), so the
    matched-temporal split first reads every source's full series once
    — ``mfield.select(indexer)``, with an indexer covering the primary's
    whole extent (see `split`) — then drives the primary patcher on the
    primary's series and slices each secondary's array in lockstep.

    Args:
        primary: A regular `TemporalPatcher` configured for the
            primary series. Drives anchor placement, geometry,
            window, and primary aggregation.
        secondary_aggregators: ``{name: temporal.aggregation.Aggregation}`` — one
            aggregator per secondary. Names that don't match any
            entry in ``mfield.secondaries`` raise on ``split`` /
            ``merge`` rather than silently skipping (typo guard).
            Omitting a secondary from this mapping is the documented
            opt-out for "don't reconstruct this source".
    """

    primary: TemporalPatcher
    secondary_aggregators: Mapping[str, TemporalAggregation] = field(
        default_factory=dict
    )

    def split(
        self,
        mfield: MatchedField,
        time_axis: int = 0,
        hooks: Iterable[PatcherHook] | None = None,
        *,
        indexer: Any | None = None,
        coord: np.ndarray | None = None,
        prefetch: int = 0,
    ) -> Iterator[MatchedTemporalPatch]:
        """Yield `MatchedTemporalPatch`es by driving the primary on each anchor.

        Reads every source's series once via ``mfield.select(indexer)``,
        then drives the primary `TemporalPatcher` on the primary's array.
        For each yielded `TemporalPatch`, each secondary's array is sliced
        with the same ``indices`` and packaged into the matched carrier.

        Per-source ``valid_mask`` arrays are computed when
        ``mfield.valid_mask`` is True (the default): a cell is invalid
        where it equals the source carrier's declared nodata or, for
        float data, is NaN / ±inf.

        Args:
            mfield: A `MatchedField` whose ``select`` returns the
                per-source series as a dict keyed by source name.
            time_axis: Which axis of each source's array is the time
                axis. Default 0. Must be the same across sources.
            hooks: Optional observability hooks, dispatched once per
                matched patch (``on_patch_done`` bytes sum every member,
                ``coord_value`` as `TemporalPatcher` reports it).
            indexer: The indexer that reads the whole series. ``None``
                (default) derives it from the primary's domain: the full
                pixel ``Window`` of a raster domain (`RasterField`,
                `RioXarrayField`, …), ``{}`` for a `GridDomain`
                (`XarrayField`, `DaskField`), ``slice(None)`` for other
                duck-typed fields.
            coord: 1-D coordinate vector along ``time_axis``, forwarded to
                the primary — required by coordinate-aware (stencil)
                geometries / samplers.
            prefetch: If positive, read ahead up to ``prefetch`` matched
                patches on a background thread.

        Raises:
            ValueError: A secondary's length along ``time_axis`` differs
                from the primary's (a cadence the coreg did not resample).
        """
        return prefetch_iterable(
            self._split(mfield, time_axis, hooks, indexer=indexer, coord=coord),
            prefetch,
        )

    def _split(
        self,
        mfield: MatchedField,
        time_axis: int,
        hooks: Iterable[PatcherHook] | None,
        *,
        indexer: Any | None,
        coord: np.ndarray | None,
    ) -> Iterator[MatchedTemporalPatch]:
        cls_name = type(self).__name__
        _validate_aggregator_names(self.secondary_aggregators, mfield, cls_name)
        if indexer is None:
            indexer = _full_indexer(mfield.domain)
        data_by_name = mfield.select(indexer)
        _check_matched_dict(data_by_name, cls_name, "mfield.select to return")

        arrays = {name: np.asarray(data) for name, data in data_by_name.items()}
        nodata = {name: _declared_nodata(d) for name, d in data_by_name.items()}
        primary_arr = arrays[PRIMARY_KEY]
        _check_time_lengths(arrays, time_axis, cls_name)

        hook_list = _as_hooks(hooks)
        if hook_list:
            n = len(self.primary.anchors(primary_arr, time_axis=time_axis, coord=coord))
            _dispatch(hook_list, "on_split_start", n)
        try:
            for primary_patch in self.primary.split(
                primary_arr, time_axis=time_axis, coord=coord
            ):
                anchor = primary_patch.anchor
                coord_value = coord[int(anchor)] if coord is not None else None
                _dispatch(hook_list, "on_patch_start", anchor, coord_value)
                start = perf_counter()
                try:
                    idx: list[Any] = [slice(None)] * primary_arr.ndim
                    idx[time_axis] = primary_patch.indices
                    tup = tuple(idx)
                    members = {
                        name: primary_patch.with_data(arr[tup])
                        for name, arr in arrays.items()
                    }
                    matched = MatchedTemporalPatch(
                        anchor=anchor,
                        members=members,
                        valid_mask=_compute_member_masks(members, mfield, nodata),
                        weights=_member_weights(members),
                    )
                except Exception as exc:
                    _dispatch(hook_list, "on_error", anchor, exc)
                    raise
                _dispatch(
                    hook_list,
                    "on_patch_done",
                    anchor,
                    perf_counter() - start,
                    _members_nbytes(members),
                    coord_value,
                )
                yield matched
        finally:
            if hook_list:
                _dispatch(hook_list, "on_split_end")

    def _primary_series(self, mfield: MatchedField, indexer: Any | None) -> Any:
        """A shape-carrying stand-in for the primary's series.

        Neither a secondary read nor a coregistration runs — counting
        anchors needs only the primary's time length. With the default
        indexer the primary's domain shape answers without any I/O (a
        raster / grid domain's shape is the full read's shape); otherwise
        the primary alone is read.
        """
        domain_shape = getattr(mfield.domain, "shape", None)
        if indexer is None and domain_shape is not None:
            return _Shaped(tuple(int(n) for n in domain_shape))
        if indexer is None:
            indexer = _full_indexer(mfield.domain)
        return _Shaped(tuple(np.shape(mfield.primary.select(indexer))))

    def n_anchors(
        self,
        mfield: MatchedField,
        time_axis: int = 0,
        *,
        indexer: Any | None = None,
        coord: np.ndarray | None = None,
    ) -> int:
        """Number of `MatchedTemporalPatch`es ``split`` will yield.

        Reads the primary only (no secondary read, no coregistration).
        """
        series = self._primary_series(mfield, indexer)
        return self.primary.n_anchors(series, time_axis=time_axis, coord=coord)

    def anchors(
        self,
        mfield: MatchedField,
        time_axis: int = 0,
        *,
        indexer: Any | None = None,
        coord: np.ndarray | None = None,
    ) -> list[int]:
        """Materialise the sampler's anchor sequence for ``mfield``.

        Reads the primary only (no secondary read, no coregistration).
        """
        series = self._primary_series(mfield, indexer)
        return self.primary.anchors(series, time_axis=time_axis, coord=coord)

    def merge(
        self,
        patches: Iterable[MatchedTemporalPatch],
        mfield: MatchedField,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> dict[str, Any]:
        """Per-source merge: dict of ``name -> aggregation result``.

        Returns the primary under ``MatchedTemporalPatch.PRIMARY_KEY``;
        secondaries appear under the names supplied to
        ``MatchedField.secondaries``. Names whose
        ``secondary_aggregators`` entry is missing are skipped (the
        user opted out for that source). Names that *are* in
        ``secondary_aggregators`` but not in ``mfield.secondaries``
        raise — typo guard.

        Unlike the spatial path, `temporal.aggregation.Aggregation.merge` takes
        only the patches (no domain argument), so ``mfield`` is used
        solely for the typo-guard check. ``patches`` is consumed once,
        streamed to every source's aggregation as in
        `MatchedSpatialPatcher.merge`.

        Args:
            patches: Iterable of `MatchedTemporalPatch` instances.
            mfield: Original `MatchedField` (used for the typo-guard).
            hooks: Optional observability hooks, dispatched once at the
                matched level (one ``on_merge_start`` / ``on_merge_end``
                per call; the output bytes sum every source).
        """
        _validate_aggregator_names(
            self.secondary_aggregators, mfield, type(self).__name__
        )
        aggregations = {
            PRIMARY_KEY: self.primary.aggregation,
            **self.secondary_aggregators,
        }

        def consumer(agg: Any) -> Callable[[Iterator[Any]], Any]:
            return lambda members: agg.merge(members)

        return _merge_per_source(
            patches,
            {name: consumer(agg) for name, agg in aggregations.items()},
            hooks,
        )

anchors(mfield, time_axis=0, *, indexer=None, coord=None)

Materialise the sampler's anchor sequence for mfield.

Reads the primary only (no secondary read, no coregistration).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def anchors(
    self,
    mfield: MatchedField,
    time_axis: int = 0,
    *,
    indexer: Any | None = None,
    coord: np.ndarray | None = None,
) -> list[int]:
    """Materialise the sampler's anchor sequence for ``mfield``.

    Reads the primary only (no secondary read, no coregistration).
    """
    series = self._primary_series(mfield, indexer)
    return self.primary.anchors(series, time_axis=time_axis, coord=coord)

merge(patches, mfield, hooks=None)

Per-source merge: dict of name -> aggregation result.

Returns the primary under MatchedTemporalPatch.PRIMARY_KEY; secondaries appear under the names supplied to MatchedField.secondaries. Names whose secondary_aggregators entry is missing are skipped (the user opted out for that source). Names that are in secondary_aggregators but not in mfield.secondaries raise — typo guard.

Unlike the spatial path, temporal.aggregation.Aggregation.merge takes only the patches (no domain argument), so mfield is used solely for the typo-guard check. patches is consumed once, streamed to every source's aggregation as in MatchedSpatialPatcher.merge.

Parameters:

Name Type Description Default
patches Iterable[MatchedTemporalPatch]

Iterable of MatchedTemporalPatch instances.

required
mfield MatchedField

Original MatchedField (used for the typo-guard).

required
hooks Iterable[PatcherHook] | None

Optional observability hooks, dispatched once at the matched level (one on_merge_start / on_merge_end per call; the output bytes sum every source).

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def merge(
    self,
    patches: Iterable[MatchedTemporalPatch],
    mfield: MatchedField,
    hooks: Iterable[PatcherHook] | None = None,
) -> dict[str, Any]:
    """Per-source merge: dict of ``name -> aggregation result``.

    Returns the primary under ``MatchedTemporalPatch.PRIMARY_KEY``;
    secondaries appear under the names supplied to
    ``MatchedField.secondaries``. Names whose
    ``secondary_aggregators`` entry is missing are skipped (the
    user opted out for that source). Names that *are* in
    ``secondary_aggregators`` but not in ``mfield.secondaries``
    raise — typo guard.

    Unlike the spatial path, `temporal.aggregation.Aggregation.merge` takes
    only the patches (no domain argument), so ``mfield`` is used
    solely for the typo-guard check. ``patches`` is consumed once,
    streamed to every source's aggregation as in
    `MatchedSpatialPatcher.merge`.

    Args:
        patches: Iterable of `MatchedTemporalPatch` instances.
        mfield: Original `MatchedField` (used for the typo-guard).
        hooks: Optional observability hooks, dispatched once at the
            matched level (one ``on_merge_start`` / ``on_merge_end``
            per call; the output bytes sum every source).
    """
    _validate_aggregator_names(
        self.secondary_aggregators, mfield, type(self).__name__
    )
    aggregations = {
        PRIMARY_KEY: self.primary.aggregation,
        **self.secondary_aggregators,
    }

    def consumer(agg: Any) -> Callable[[Iterator[Any]], Any]:
        return lambda members: agg.merge(members)

    return _merge_per_source(
        patches,
        {name: consumer(agg) for name, agg in aggregations.items()},
        hooks,
    )

n_anchors(mfield, time_axis=0, *, indexer=None, coord=None)

Number of MatchedTemporalPatches split will yield.

Reads the primary only (no secondary read, no coregistration).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def n_anchors(
    self,
    mfield: MatchedField,
    time_axis: int = 0,
    *,
    indexer: Any | None = None,
    coord: np.ndarray | None = None,
) -> int:
    """Number of `MatchedTemporalPatch`es ``split`` will yield.

    Reads the primary only (no secondary read, no coregistration).
    """
    series = self._primary_series(mfield, indexer)
    return self.primary.n_anchors(series, time_axis=time_axis, coord=coord)

split(mfield, time_axis=0, hooks=None, *, indexer=None, coord=None, prefetch=0)

Yield MatchedTemporalPatches by driving the primary on each anchor.

Reads every source's series once via mfield.select(indexer), then drives the primary TemporalPatcher on the primary's array. For each yielded TemporalPatch, each secondary's array is sliced with the same indices and packaged into the matched carrier.

Per-source valid_mask arrays are computed when mfield.valid_mask is True (the default): a cell is invalid where it equals the source carrier's declared nodata or, for float data, is NaN / ±inf.

Parameters:

Name Type Description Default
mfield MatchedField

A MatchedField whose select returns the per-source series as a dict keyed by source name.

required
time_axis int

Which axis of each source's array is the time axis. Default 0. Must be the same across sources.

0
hooks Iterable[PatcherHook] | None

Optional observability hooks, dispatched once per matched patch (on_patch_done bytes sum every member, coord_value as TemporalPatcher reports it).

None
indexer Any | None

The indexer that reads the whole series. None (default) derives it from the primary's domain: the full pixel Window of a raster domain (RasterField, RioXarrayField, …), {} for a GridDomain (XarrayField, DaskField), slice(None) for other duck-typed fields.

None
coord ndarray | None

1-D coordinate vector along time_axis, forwarded to the primary — required by coordinate-aware (stencil) geometries / samplers.

None
prefetch int

If positive, read ahead up to prefetch matched patches on a background thread.

0

Raises:

Type Description
ValueError

A secondary's length along time_axis differs from the primary's (a cadence the coreg did not resample).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def split(
    self,
    mfield: MatchedField,
    time_axis: int = 0,
    hooks: Iterable[PatcherHook] | None = None,
    *,
    indexer: Any | None = None,
    coord: np.ndarray | None = None,
    prefetch: int = 0,
) -> Iterator[MatchedTemporalPatch]:
    """Yield `MatchedTemporalPatch`es by driving the primary on each anchor.

    Reads every source's series once via ``mfield.select(indexer)``,
    then drives the primary `TemporalPatcher` on the primary's array.
    For each yielded `TemporalPatch`, each secondary's array is sliced
    with the same ``indices`` and packaged into the matched carrier.

    Per-source ``valid_mask`` arrays are computed when
    ``mfield.valid_mask`` is True (the default): a cell is invalid
    where it equals the source carrier's declared nodata or, for
    float data, is NaN / ±inf.

    Args:
        mfield: A `MatchedField` whose ``select`` returns the
            per-source series as a dict keyed by source name.
        time_axis: Which axis of each source's array is the time
            axis. Default 0. Must be the same across sources.
        hooks: Optional observability hooks, dispatched once per
            matched patch (``on_patch_done`` bytes sum every member,
            ``coord_value`` as `TemporalPatcher` reports it).
        indexer: The indexer that reads the whole series. ``None``
            (default) derives it from the primary's domain: the full
            pixel ``Window`` of a raster domain (`RasterField`,
            `RioXarrayField`, …), ``{}`` for a `GridDomain`
            (`XarrayField`, `DaskField`), ``slice(None)`` for other
            duck-typed fields.
        coord: 1-D coordinate vector along ``time_axis``, forwarded to
            the primary — required by coordinate-aware (stencil)
            geometries / samplers.
        prefetch: If positive, read ahead up to ``prefetch`` matched
            patches on a background thread.

    Raises:
        ValueError: A secondary's length along ``time_axis`` differs
            from the primary's (a cadence the coreg did not resample).
    """
    return prefetch_iterable(
        self._split(mfield, time_axis, hooks, indexer=indexer, coord=coord),
        prefetch,
    )

geopatcher.matched.MatchedSpatioTemporalPatcher dataclass

Bases: _MatchedConfigMixin

Spatio-temporal matched patcher — yields MatchedSpatioTemporalPatches.

Mirror of MatchedSpatialPatcher over the spatio-temporal axis: it drives the primary SpatioTemporalPatcher over the MatchedField and turns each yielded patch into a matched carrier, so the coupling mode ("product" or "coupled", from primary.coupling), the chip reads, the on_error policy, hooks, journal and backpressure are the primary's own.

Parameters:

Name Type Description Default
primary SpatioTemporalPatcher

A regular SpatioTemporalPatcher configured for the primary field. Drives both spatial anchor placement and temporal windowing.

required
secondary_aggregators Mapping[str, Aggregation]

{name: temporal.aggregation.Aggregation} — one temporal aggregator per secondary, matching the per-anchor temporal merge shape of SpatioTemporalPatcher.merge. Names that don't match any entry in mfield.secondaries raise on split / merge (typo guard).

dict()
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
@dataclass(eq=False)
class MatchedSpatioTemporalPatcher(_MatchedConfigMixin):
    """Spatio-temporal matched patcher — yields `MatchedSpatioTemporalPatch`es.

    Mirror of `MatchedSpatialPatcher` over the spatio-temporal axis: it
    drives the primary `SpatioTemporalPatcher` over the `MatchedField`
    and turns each yielded patch into a matched carrier, so the coupling
    mode (``"product"`` or ``"coupled"``, from ``primary.coupling``), the
    chip reads, the ``on_error`` policy, hooks, journal and backpressure
    are the primary's own.

    Args:
        primary: A regular `SpatioTemporalPatcher` configured for the
            primary field. Drives both spatial anchor placement and
            temporal windowing.
        secondary_aggregators: ``{name: temporal.aggregation.Aggregation}`` — one
            temporal aggregator per secondary, matching the per-anchor
            temporal merge shape of `SpatioTemporalPatcher.merge`.
            Names that don't match any entry in ``mfield.secondaries``
            raise on ``split`` / ``merge`` (typo guard).
    """

    primary: SpatioTemporalPatcher
    secondary_aggregators: Mapping[str, TemporalAggregation] = field(
        default_factory=dict
    )

    def split(
        self,
        mfield: MatchedField,
        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[MatchedSpatioTemporalPatch]:
        """Yield `MatchedSpatioTemporalPatch`es lazily.

        Runs ``self.primary.split`` over ``mfield``: each spatial chip is
        one `MatchedField` read (every source over the primary chip's
        footprint, coregistered onto it) checked to hold the primary and
        to share its time length, and every source is sliced to the same
        time window. Each yielded patch is unpacked into a matched carrier
        whose ``members`` are per-source `SpatioTemporalPatch`es.

        The spatial patcher's ``on_error`` policy covers every source's
        read and coregistration; under ``"mask"`` a failed chip yields
        all-NaN members with an all-False ``valid_mask``. Per-source
        ``valid_mask`` arrays are otherwise computed when
        ``mfield.valid_mask`` is True (the default).

        Args:
            mfield: A `MatchedField` to walk with the primary
                spatio-temporal patcher.
            hooks: Optional observability hooks, dispatched by the
                primary's split once per matched patch — ``(space, time)``
                anchors, ``coord_value``, and ``on_patch_done`` bytes summed
                over every member.
            coord: 1-D coordinate vector along the time axis, as
                `SpatioTemporalPatcher.split` takes it — required by
                coordinate-aware (stencil) temporal geometries / samplers.
            prefetch: If positive, read ahead up to ``prefetch`` matched
                patches on a background thread.
            journal: Forwarded to `SpatioTemporalPatcher.split` — the
                ``(space, time_key)`` keys it holds are skipped.
            cache: A `PatchCache` consulted per source, as in
                `MatchedSpatialPatcher.split` (the coregistration still
                runs).
            max_in_flight: Forwarded to `SpatioTemporalPatcher.split`;
                each yielded matched patch owns the slot — release it with
                ``mp.close()`` or ``with mp: ...``.
            max_in_flight_bytes: Forwarded; a matched patch is sized as
                the sum of its members' bytes.

        Raises:
            ValueError: A secondary's length along the time axis differs
                from the primary's.
        """
        _validate_aggregator_names(
            self.secondary_aggregators, mfield, type(self).__name__
        )
        source: Any = mfield if cache is None else _CachedSourceReads(mfield, cache)
        outers = self.primary._split(
            source,
            hooks,
            coord=coord,
            prefetch=prefetch,
            journal=journal,
            cache=None,
            max_in_flight=max_in_flight,
            max_in_flight_bytes=max_in_flight_bytes,
            unpack=partial(self._unpack, mfield),
        )
        return self._matched(outers, mfield)

    def _unpack(self, mfield: MatchedField, chip: Any) -> dict[str, Any]:
        """One chip read (a `Patch`) → its checked ``{source: data}`` dict.

        A mask placeholder fans out to one all-NaN copy per source, marked
        `_MaskedMembers` so `_matched` gives it an all-False mask.
        """
        cls_name = type(self).__name__
        data_by_name, masked = _unpack_matched(
            chip, mfield, cls_name, "each spatial Patch.data to be"
        )
        _check_time_lengths(data_by_name, self.primary.time_axis, cls_name)
        return _MaskedMembers(data_by_name) if masked else data_by_name

    def _matched(
        self, outers: Iterator[SpatioTemporalPatch], mfield: MatchedField
    ) -> Iterator[MatchedSpatioTemporalPatch]:
        try:
            for outer in outers:
                members = {
                    name: outer.with_data(data) for name, data in outer.data.items()
                }
                matched = MatchedSpatioTemporalPatch(
                    space=outer.space,
                    time=outer.time,
                    members=members,
                    valid_mask=_compute_member_masks(
                        members, mfield, masked=isinstance(outer.data, _MaskedMembers)
                    ),
                    weights=_member_weights(members),
                )
                _hand_over_release(outer, matched)
                yield matched
        finally:
            _close(outers)

    def merge(
        self,
        patches: Iterable[MatchedSpatioTemporalPatch],
        mfield: MatchedField,
        hooks: Iterable[PatcherHook] | None = None,
    ) -> dict[str, list[tuple[Any, Any]]]:
        """Per-source merge: dict of ``name -> [(spatial_anchor, temporal_merge), …]``.

        Each source's value is what `SpatioTemporalPatcher.merge` returns
        for that source's members: ``(spatial_anchor,
        temporal_aggregation_result)`` pairs grouped by spatial anchor
        (first-seen order). Secondaries use their `temporal.aggregation.Aggregation`;
        the primary uses ``self.primary.temporal.aggregation``.
        ``patches`` is consumed once and fanned out to every source as in
        `MatchedSpatialPatcher.merge`; each source's grouping still holds
        its groups until the pass ends.

        Args:
            patches: Iterable of `MatchedSpatioTemporalPatch` instances.
            mfield: Original `MatchedField` (used for the typo-guard).
            hooks: Optional observability hooks. Dispatched at the
                matched layer (one ``merge_start`` / ``merge_end`` per
                call; the output bytes sum every source).
        """
        _validate_aggregator_names(
            self.secondary_aggregators, mfield, type(self).__name__
        )
        aggregations = {
            PRIMARY_KEY: self.primary.temporal.aggregation,
            **self.secondary_aggregators,
        }

        def consumer(agg: Any) -> Callable[[Iterator[Any]], Any]:
            return lambda members: _merge_by_space(members, agg)

        return _merge_per_source(
            patches,
            {name: consumer(agg) for name, agg in aggregations.items()},
            hooks,
        )

merge(patches, mfield, hooks=None)

Per-source merge: dict of name -> [(spatial_anchor, temporal_merge), …].

Each source's value is what SpatioTemporalPatcher.merge returns for that source's members: (spatial_anchor, temporal_aggregation_result) pairs grouped by spatial anchor (first-seen order). Secondaries use their temporal.aggregation.Aggregation; the primary uses self.primary.temporal.aggregation. patches is consumed once and fanned out to every source as in MatchedSpatialPatcher.merge; each source's grouping still holds its groups until the pass ends.

Parameters:

Name Type Description Default
patches Iterable[MatchedSpatioTemporalPatch]

Iterable of MatchedSpatioTemporalPatch instances.

required
mfield MatchedField

Original MatchedField (used for the typo-guard).

required
hooks Iterable[PatcherHook] | None

Optional observability hooks. Dispatched at the matched layer (one merge_start / merge_end per call; the output bytes sum every source).

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def merge(
    self,
    patches: Iterable[MatchedSpatioTemporalPatch],
    mfield: MatchedField,
    hooks: Iterable[PatcherHook] | None = None,
) -> dict[str, list[tuple[Any, Any]]]:
    """Per-source merge: dict of ``name -> [(spatial_anchor, temporal_merge), …]``.

    Each source's value is what `SpatioTemporalPatcher.merge` returns
    for that source's members: ``(spatial_anchor,
    temporal_aggregation_result)`` pairs grouped by spatial anchor
    (first-seen order). Secondaries use their `temporal.aggregation.Aggregation`;
    the primary uses ``self.primary.temporal.aggregation``.
    ``patches`` is consumed once and fanned out to every source as in
    `MatchedSpatialPatcher.merge`; each source's grouping still holds
    its groups until the pass ends.

    Args:
        patches: Iterable of `MatchedSpatioTemporalPatch` instances.
        mfield: Original `MatchedField` (used for the typo-guard).
        hooks: Optional observability hooks. Dispatched at the
            matched layer (one ``merge_start`` / ``merge_end`` per
            call; the output bytes sum every source).
    """
    _validate_aggregator_names(
        self.secondary_aggregators, mfield, type(self).__name__
    )
    aggregations = {
        PRIMARY_KEY: self.primary.temporal.aggregation,
        **self.secondary_aggregators,
    }

    def consumer(agg: Any) -> Callable[[Iterator[Any]], Any]:
        return lambda members: _merge_by_space(members, agg)

    return _merge_per_source(
        patches,
        {name: consumer(agg) for name, agg in aggregations.items()},
        hooks,
    )

split(mfield, hooks=None, *, coord=None, prefetch=0, journal=None, cache=None, max_in_flight=None, max_in_flight_bytes=None)

Yield MatchedSpatioTemporalPatches lazily.

Runs self.primary.split over mfield: each spatial chip is one MatchedField read (every source over the primary chip's footprint, coregistered onto it) checked to hold the primary and to share its time length, and every source is sliced to the same time window. Each yielded patch is unpacked into a matched carrier whose members are per-source SpatioTemporalPatches.

The spatial patcher's on_error policy covers every source's read and coregistration; under "mask" a failed chip yields all-NaN members with an all-False valid_mask. Per-source valid_mask arrays are otherwise computed when mfield.valid_mask is True (the default).

Parameters:

Name Type Description Default
mfield MatchedField

A MatchedField to walk with the primary spatio-temporal patcher.

required
hooks Iterable[PatcherHook] | None

Optional observability hooks, dispatched by the primary's split once per matched patch — (space, time) anchors, coord_value, and on_patch_done bytes summed over every member.

None
coord ndarray | None

1-D coordinate vector along the time axis, as SpatioTemporalPatcher.split takes it — required by coordinate-aware (stencil) temporal geometries / samplers.

None
prefetch int

If positive, read ahead up to prefetch matched patches on a background thread.

0
journal Any | None

Forwarded to SpatioTemporalPatcher.split — the (space, time_key) keys it holds are skipped.

None
cache Any | None

A PatchCache consulted per source, as in MatchedSpatialPatcher.split (the coregistration still runs).

None
max_in_flight int | None

Forwarded to SpatioTemporalPatcher.split; each yielded matched patch owns the slot — release it with mp.close() or with mp: ....

None
max_in_flight_bytes int | None

Forwarded; a matched patch is sized as the sum of its members' bytes.

None

Raises:

Type Description
ValueError

A secondary's length along the time axis differs from the primary's.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/matched/patcher.py
def split(
    self,
    mfield: MatchedField,
    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[MatchedSpatioTemporalPatch]:
    """Yield `MatchedSpatioTemporalPatch`es lazily.

    Runs ``self.primary.split`` over ``mfield``: each spatial chip is
    one `MatchedField` read (every source over the primary chip's
    footprint, coregistered onto it) checked to hold the primary and
    to share its time length, and every source is sliced to the same
    time window. Each yielded patch is unpacked into a matched carrier
    whose ``members`` are per-source `SpatioTemporalPatch`es.

    The spatial patcher's ``on_error`` policy covers every source's
    read and coregistration; under ``"mask"`` a failed chip yields
    all-NaN members with an all-False ``valid_mask``. Per-source
    ``valid_mask`` arrays are otherwise computed when
    ``mfield.valid_mask`` is True (the default).

    Args:
        mfield: A `MatchedField` to walk with the primary
            spatio-temporal patcher.
        hooks: Optional observability hooks, dispatched by the
            primary's split once per matched patch — ``(space, time)``
            anchors, ``coord_value``, and ``on_patch_done`` bytes summed
            over every member.
        coord: 1-D coordinate vector along the time axis, as
            `SpatioTemporalPatcher.split` takes it — required by
            coordinate-aware (stencil) temporal geometries / samplers.
        prefetch: If positive, read ahead up to ``prefetch`` matched
            patches on a background thread.
        journal: Forwarded to `SpatioTemporalPatcher.split` — the
            ``(space, time_key)`` keys it holds are skipped.
        cache: A `PatchCache` consulted per source, as in
            `MatchedSpatialPatcher.split` (the coregistration still
            runs).
        max_in_flight: Forwarded to `SpatioTemporalPatcher.split`;
            each yielded matched patch owns the slot — release it with
            ``mp.close()`` or ``with mp: ...``.
        max_in_flight_bytes: Forwarded; a matched patch is sized as
            the sum of its members' bytes.

    Raises:
        ValueError: A secondary's length along the time axis differs
            from the primary's.
    """
    _validate_aggregator_names(
        self.secondary_aggregators, mfield, type(self).__name__
    )
    source: Any = mfield if cache is None else _CachedSourceReads(mfield, cache)
    outers = self.primary._split(
        source,
        hooks,
        coord=coord,
        prefetch=prefetch,
        journal=journal,
        cache=None,
        max_in_flight=max_in_flight,
        max_in_flight_bytes=max_in_flight_bytes,
        unpack=partial(self._unpack, mfield),
    )
    return self._matched(outers, mfield)