Skip to content

Temporal axes — geopatcher.temporal

The four temporal axes composed by TemporalPatcher, plus the coordinate-aware TimeStencil machinery.

Temporal axes

Geometry

geopatcher.temporal.geometry.Geometry

Base for time-window shapes.

Subclasses implement window(time_len, anchor) -> slice | list[slice] | None. A list is returned by multi-window geometries (temporal.geometry.MultiScale, temporal.geometry.PhaseWindow); None means the anchor yields no patch (its window was dropped under boundary="drop").

Coordinate-aware subclasses (e.g. temporal.geometry.StencilGeometry) set needs_coord = True and implement window_coord(coord, anchor_idx) -> slice. TemporalPatcher dispatches on the flag and requires a coord= argument when it is True. See ADR-004 in docs/patcher/decisions.md.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
class Geometry:
    """Base for time-window shapes.

    Subclasses implement
    ``window(time_len, anchor) -> slice | list[slice] | None``. A list is
    returned by multi-window geometries (`temporal.geometry.MultiScale`,
    `temporal.geometry.PhaseWindow`); ``None`` means the anchor yields no patch
    (its window was dropped under ``boundary="drop"``).

    Coordinate-aware subclasses (e.g. `temporal.geometry.StencilGeometry`) set
    ``needs_coord = True`` and implement
    ``window_coord(coord, anchor_idx) -> slice``. `TemporalPatcher` dispatches
    on the flag and requires a ``coord=`` argument when it is `True`. See
    ADR-004 in ``docs/patcher/decisions.md``.
    """

    forbid_in_yaml: ClassVar[bool] = False
    needs_coord: ClassVar[bool] = False

    def window(self, time_len: int, anchor: int) -> slice | list[slice] | None:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.temporal.geometry.FixedLookback dataclass

Bases: Geometry

Causal lookback of fixed length time steps.

The returned slice is [t - length + 1, t + 1) — i.e. length steps ending at t inclusive.

Parameters:

Name Type Description Default
length int

Number of steps in the lookback (>= 1).

required
boundary TemporalBoundary

What to do with an anchor whose lookback starts before the axis (t < length - 1): "drop" it (default), "shrink" the window to [0, t + 1), or "raise".

'drop'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
@dataclass(eq=False)
class FixedLookback(Geometry):
    """Causal lookback of fixed ``length`` time steps.

    The returned slice is ``[t - length + 1, t + 1)`` — i.e. ``length``
    steps ending at ``t`` inclusive.

    Args:
        length: Number of steps in the lookback (``>= 1``).
        boundary: What to do with an anchor whose lookback starts before
            the axis (``t < length - 1``): ``"drop"`` it (default),
            ``"shrink"`` the window to ``[0, t + 1)``, or ``"raise"``.
    """

    length: int
    boundary: TemporalBoundary = "drop"

    def __post_init__(self) -> None:
        _check_boundary(self.boundary)
        if int(self.length) < 1:
            raise ValueError(f"length must be >= 1; got {self.length}")

    def window(self, time_len: int, anchor: int) -> slice | None:
        end = int(anchor) + 1
        start = end - int(self.length)
        return _resolve(self, int(anchor), start, end, int(time_len), self.boundary)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.geometry.LookbackHorizon dataclass

Bases: Geometry

Lookback + horizon — the canonical forecasting window shape.

Returns [t - lookback + 1, t + horizon + 1). Operators consuming this typically split the window into past (lookback) and future (horizon) at index lookback.

Parameters:

Name Type Description Default
lookback int

Steps up to and including the anchor (>= 1).

required
horizon int

Steps after the anchor (>= 0).

required
boundary TemporalBoundary

What to do with an anchor whose window overflows either end of the axis: "drop" it (default — so the horizon of every emitted window is real data), "shrink" the window to the axis, or "raise".

'drop'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
@dataclass(eq=False)
class LookbackHorizon(Geometry):
    """Lookback + horizon — the canonical forecasting window shape.

    Returns ``[t - lookback + 1, t + horizon + 1)``. Operators consuming
    this typically split the window into past (``lookback``) and future
    (``horizon``) at index ``lookback``.

    Args:
        lookback: Steps up to and including the anchor (``>= 1``).
        horizon: Steps after the anchor (``>= 0``).
        boundary: What to do with an anchor whose window overflows either
            end of the axis: ``"drop"`` it (default — so the horizon of
            every emitted window is real data), ``"shrink"`` the window to
            the axis, or ``"raise"``.
    """

    lookback: int
    horizon: int
    boundary: TemporalBoundary = "drop"

    def __post_init__(self) -> None:
        _check_boundary(self.boundary)
        if int(self.lookback) < 1:
            raise ValueError(f"lookback must be >= 1; got {self.lookback}")
        if int(self.horizon) < 0:
            raise ValueError(f"horizon must be >= 0; got {self.horizon}")

    def window(self, time_len: int, anchor: int) -> slice | None:
        a = int(anchor)
        start = a - int(self.lookback) + 1
        stop = a + int(self.horizon) + 1
        return _resolve(self, a, start, stop, int(time_len), self.boundary)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.geometry.MultiScale dataclass

Bases: Geometry

One lookback per scale — for combining hourly + daily + annual context.

Emits one window per scale, in scales order, so the k-th patch of an anchor (TemporalPatch.window_index k) is scale scales[k].

Parameters:

Name Type Description Default
scales list[int]

List of lookback lengths (in time-axis steps, each >= 1).

required
boundary TemporalBoundary

What to do with an anchor whose longest lookback starts before the axis: "drop" the whole anchor (default — every emitted anchor carries every scale at full length), "shrink" each overflowing scale to [0, t + 1), or "raise".

'drop'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
@dataclass(eq=False)
class MultiScale(Geometry):
    """One lookback per scale — for combining hourly + daily + annual context.

    Emits one window per scale, in ``scales`` order, so the ``k``-th
    patch of an anchor (`TemporalPatch.window_index` ``k``) is scale
    ``scales[k]``.

    Args:
        scales: List of lookback lengths (in time-axis steps, each ``>= 1``).
        boundary: What to do with an anchor whose *longest* lookback starts
            before the axis: ``"drop"`` the whole anchor (default — every
            emitted anchor carries every scale at full length), ``"shrink"``
            each overflowing scale to ``[0, t + 1)``, or ``"raise"``.
    """

    scales: list[int]
    boundary: TemporalBoundary = "drop"

    def __post_init__(self) -> None:
        _check_boundary(self.boundary)
        self.scales = [int(s) for s in self.scales]
        if not self.scales or min(self.scales) < 1:
            raise ValueError(
                f"scales must be a non-empty list of lengths >= 1; got {self.scales}"
            )

    def window(self, time_len: int, anchor: int) -> list[slice] | None:
        end = int(anchor) + 1
        out: list[slice] = []
        for length in self.scales:
            s = _resolve(
                self, int(anchor), end - length, end, int(time_len), self.boundary
            )
            if s is None:
                # "drop": one overflowing scale drops the anchor, so the
                # surviving anchors always carry the full scale set.
                return None
            out.append(s)
        return out

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.geometry.PhaseWindow dataclass

Bases: Geometry

Periodic phase slots — every cycle's steps near the anchor's phase.

For anchor t with phase = t % period the geometry returns one slot per cycle, [k * period + phase - phase_width, k * period + phase + phase_width + 1) for every k whose slot touches the axis, in time order. E.g. with hourly data, period=24, phase_width=1 at a 14:00 anchor yields the 13:00-15:00 slot of every day — the diurnal-composite shape.

Parameters:

Name Type Description Default
period int

Cycle length in time-axis steps (e.g. 24 for hourly diurnal).

required
phase_width int

Half-width of each slot in steps; slots must not overlap, so 2 * phase_width + 1 <= period.

required
boundary TemporalBoundary

What to do with a slot that overflows the axis (only the first / last cycle can): "drop" that slot (default — an anchor whose every slot is dropped yields no patch), "shrink" it to the axis, or "raise".

'drop'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
@dataclass(eq=False)
class PhaseWindow(Geometry):
    """Periodic phase slots — every cycle's steps near the anchor's phase.

    For anchor ``t`` with ``phase = t % period`` the geometry returns one
    slot per cycle,
    ``[k * period + phase - phase_width, k * period + phase + phase_width + 1)`` for
    every ``k`` whose slot touches the axis, in time order. E.g. with
    hourly data, ``period=24, phase_width=1`` at a 14:00 anchor yields the
    13:00-15:00 slot of every day — the diurnal-composite shape.

    Args:
        period: Cycle length in time-axis steps (e.g. 24 for hourly diurnal).
        phase_width: Half-width of each slot in steps; slots must not
            overlap, so ``2 * phase_width + 1 <= period``.
        boundary: What to do with a slot that overflows the axis (only the
            first / last cycle can): ``"drop"`` that slot (default — an
            anchor whose every slot is dropped yields no patch),
            ``"shrink"`` it to the axis, or ``"raise"``.
    """

    period: int
    phase_width: int
    boundary: TemporalBoundary = "drop"

    def __post_init__(self) -> None:
        _check_boundary(self.boundary)
        period, w = int(self.period), int(self.phase_width)
        if period < 1:
            raise ValueError(f"period must be >= 1; got {self.period}")
        if w < 0 or 2 * w + 1 > period:
            raise ValueError(
                "phase_width must satisfy 0 <= 2 * phase_width + 1 <= period; "
                f"got phase_width={self.phase_width}, period={self.period}"
            )

    def window(self, time_len: int, anchor: int) -> list[slice] | None:
        period, w, n = int(self.period), int(self.phase_width), int(time_len)
        phase = int(anchor) % period
        out: list[slice] = []
        # Start one cycle early: for a phase within ``w`` of the cycle end
        # the slot centred at ``phase - period`` still reaches into the axis.
        for centre in range(phase - period, n + w, period):
            start, stop = centre - w, centre + w + 1
            if stop <= 0 or start >= n:
                continue
            s = _resolve(self, int(anchor), start, stop, n, self.boundary)
            if s is not None:
                out.append(s)
        return out or None

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

Sampler

geopatcher.temporal.sampler.Sampler

Base for temporal anchor placement.

Subclasses implement anchors(time_len) -> Iterable[int]. The base signature is integer-only; coordinate-aware subclasses (e.g. temporal.sampler.StencilSampler) set needs_coord = True and accept a coord= keyword in anchors. TemporalPatcher passes the coord vector through when the flag is True. See ADR-004 in docs/patcher/decisions.md.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
class Sampler:
    """Base for temporal anchor placement.

    Subclasses implement `anchors(time_len) -> Iterable[int]`. The base
    signature is integer-only; coordinate-aware subclasses (e.g.
    `temporal.sampler.StencilSampler`) set ``needs_coord = True`` and accept a
    ``coord=`` keyword in `anchors`. `TemporalPatcher` passes the coord
    vector through when the flag is `True`. See ADR-004 in
    ``docs/patcher/decisions.md``.
    """

    forbid_in_yaml: ClassVar[bool] = False
    needs_coord: ClassVar[bool] = False

    def anchors(self, time_len: int) -> Iterable[int]:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.temporal.sampler.RegularStride dataclass

Bases: Sampler

Every step steps along the time axis, starting at start.

Parameters:

Name Type Description Default
step int

Stride between anchors (>= 1).

1
start int

First anchor index (>= 0). With a causal lookback of L steps, start=L - 1 is the first anchor whose window fits under boundary="drop".

0
check_full_scan bool

If True, TemporalPatcher raises IncompleteScanConfiguration before the first patch when the windows of the placed anchors leave any time step uncovered (a stride longer than the window, a dropped head / tail) — the temporal twin of spatial.sampler.RegularStride.check_full_scan.

False
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
@dataclass(eq=False)
class RegularStride(Sampler):
    """Every ``step`` steps along the time axis, starting at ``start``.

    Args:
        step: Stride between anchors (``>= 1``).
        start: First anchor index (``>= 0``). With a causal lookback of
            ``L`` steps, ``start=L - 1`` is the first anchor whose window
            fits under ``boundary="drop"``.
        check_full_scan: If ``True``, `TemporalPatcher` raises
            `IncompleteScanConfiguration` before the first patch when the
            windows of the placed anchors leave any time step uncovered
            (a stride longer than the window, a dropped head / tail) —
            the temporal twin of `spatial.sampler.RegularStride.check_full_scan`.
    """

    step: int = 1
    start: int = 0
    check_full_scan: bool = False

    def __post_init__(self) -> None:
        if int(self.step) != self.step or self.step < 1:
            raise ValueError(f"step must be an integer >= 1, got {self.step!r}")
        if int(self.start) != self.start or self.start < 0:
            raise ValueError(f"start must be an integer >= 0, got {self.start!r}")

    def anchors(self, time_len: int) -> Iterator[int]:
        yield from range(int(self.start), int(time_len), int(self.step))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.sampler.Random dataclass

Bases: Sampler

n_samples uniform-random anchors along the time axis.

Draws are independent — with replacement, so an index can repeat — and are yielded in draw order, not sorted, exactly like spatial.sampler.Random.

Parameters:

Name Type Description Default
n_samples int

Number of anchors to draw (>= 0).

1
seed int | None

Integer seed for reproducible draws — same contract as spatial.sampler.Random.seed. None re-seeds each call.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
@dataclass(eq=False)
class Random(Sampler):
    """``n_samples`` uniform-random anchors along the time axis.

    Draws are independent — *with replacement*, so an index can repeat —
    and are yielded in draw order, not sorted, exactly like
    `spatial.sampler.Random`.

    Args:
        n_samples: Number of anchors to draw (``>= 0``).
        seed: Integer seed for reproducible draws — same contract as
            `spatial.sampler.Random.seed`. ``None`` re-seeds each call.
    """

    n_samples: int = 1
    seed: int | None = None

    def __post_init__(self) -> None:
        if int(self.n_samples) != self.n_samples or self.n_samples < 0:
            raise ValueError(
                f"n_samples must be a non-negative integer, got {self.n_samples!r}"
            )

    def anchors(self, time_len: int) -> Iterator[int]:
        if int(time_len) <= 0:
            return
        rng = np.random.default_rng(self.seed)
        idx = rng.integers(0, int(time_len), size=int(self.n_samples))
        for t in idx:
            yield int(t)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.sampler.Explicit dataclass

Bases: Sampler

Caller-supplied anchor indices — the universal escape hatch.

Yields the in-range indices (0 <= t < time_len) in the given order; out-of-range ones are skipped. Use it for event-aligned patching (storm tracks, plume detections — the natural partner of coupling="coupled" in SpatioTemporalPatcher).

Parameters:

Name Type Description Default
times list[int]

Iterable of integer time indices. Coerced to a list at construction so get_config() doesn't accidentally exhaust a user-supplied generator.

list()
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
@dataclass(eq=False)
class Explicit(Sampler):
    """Caller-supplied anchor indices — the universal escape hatch.

    Yields the in-range indices (``0 <= t < time_len``) in the given
    order; out-of-range ones are skipped. Use it for event-aligned
    patching (storm tracks, plume detections — the natural partner of
    ``coupling="coupled"`` in `SpatioTemporalPatcher`).

    Args:
        times: Iterable of integer time indices. Coerced to a list at
            construction so `get_config()` doesn't accidentally exhaust a
            user-supplied generator.
    """

    times: list[int] = field(default_factory=list)

    def __post_init__(self) -> None:
        self.times = [int(t) for t in self.times]

    def anchors(self, time_len: int) -> Iterator[int]:
        for t in self.times:
            if 0 <= t < int(time_len):
                yield t

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

Window

geopatcher.temporal.window.Window

Base for temporal window functions.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
class Window:
    """Base for temporal window functions."""

    forbid_in_yaml: ClassVar[bool] = False

    def weights(self, geometry: TemporalGeometry, length: int) -> np.ndarray:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.temporal.window.CausalBoxcar dataclass

Bases: Window

Constant 1.0 — no recency weighting, hard past cutoff at the lookback.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
@dataclass(eq=False)
class CausalBoxcar(Window):
    """Constant 1.0 — no recency weighting, hard past cutoff at the lookback."""

    def weights(self, geometry: TemporalGeometry, length: int) -> np.ndarray:
        return np.ones(int(length), dtype=np.float64)

geopatcher.temporal.window.ExponentialDecay dataclass

Bases: Window

Geometric recency weighting — w[k] = exp(-k / tau) for past-to-present.

The latest step (largest index) gets weight 1.0; earlier steps decay.

Parameters:

Name Type Description Default
tau float

Decay constant in time-axis steps (> 0).

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
@dataclass(eq=False)
class ExponentialDecay(Window):
    """Geometric recency weighting — ``w[k] = exp(-k / tau)`` for past-to-present.

    The latest step (largest index) gets weight 1.0; earlier steps decay.

    Args:
        tau: Decay constant in time-axis steps (``> 0``).
    """

    tau: float

    def __post_init__(self) -> None:
        if not self.tau > 0:
            raise ValueError(f"tau must be > 0, got {self.tau!r}")

    def weights(self, geometry: TemporalGeometry, length: int) -> np.ndarray:
        n = int(length)
        if n <= 0:
            return np.array([], dtype=np.float64)
        # ages: n-1 at the oldest step, 0 at the most recent
        ages = np.arange(n - 1, -1, -1, dtype=np.float64)
        return np.exp(-ages / float(self.tau))

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.window.TaperedTukey dataclass

Bases: Window

One-sided (causal) Tukey taper — the oldest steps fade in.

The first alpha fraction of the window, counted from the oldest step, rises along a raised cosine; the rest — always including the newest step — is 1.0. With n steps, step k (oldest k = 0) sits at x = (k + 1) / n and weighs 0.5 * (1 - cos(pi * x / alpha)) for x < alpha, else 1.0. A symmetric taper would zero the newest observation, which is the one a causal window exists to keep.

Parameters:

Name Type Description Default
alpha float

Taper fraction in [0, 1] (0 = boxcar, 1 = a raised cosine over the whole window).

0.5
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
@dataclass(eq=False)
class TaperedTukey(Window):
    """One-sided (causal) Tukey taper — the oldest steps fade in.

    The first ``alpha`` fraction of the window, counted from the oldest
    step, rises along a raised cosine; the rest — always including the
    newest step — is 1.0. With ``n`` steps, step ``k`` (oldest ``k = 0``)
    sits at ``x = (k + 1) / n`` and weighs
    ``0.5 * (1 - cos(pi * x / alpha))`` for ``x < alpha``, else 1.0. A
    symmetric taper would zero the newest observation, which is the one a
    causal window exists to keep.

    Args:
        alpha: Taper fraction in ``[0, 1]`` (0 = boxcar, 1 = a raised
            cosine over the whole window).
    """

    alpha: float = 0.5

    def __post_init__(self) -> None:
        if not 0.0 <= float(self.alpha) <= 1.0:
            raise ValueError(f"alpha must be in [0, 1], got {self.alpha!r}")

    def weights(self, geometry: TemporalGeometry, length: int) -> np.ndarray:
        n = int(length)
        if n <= 0:
            return np.array([], dtype=np.float64)
        alpha = float(self.alpha)
        x = np.arange(1, n + 1, dtype=np.float64) / n
        if alpha == 0.0:
            return np.ones(n, dtype=np.float64)
        ramp = 0.5 * (1.0 - np.cos(np.pi * np.minimum(x / alpha, 1.0)))
        return np.where(x < alpha, ramp, 1.0)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.window.Periodic dataclass

Bases: CausalBoxcar

temporal.window.CausalBoxcar weights tagged with a cycle length.

The weights are the boxcar's (it inherits them); the period only records the cycle the configuration is built around — pair it with a temporal.geometry.PhaseWindow of the same period — so YAML configs keep the intent.

Parameters:

Name Type Description Default
period int

Cycle length in time-axis steps (>= 1).

required
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
@dataclass(eq=False)
class Periodic(CausalBoxcar):
    """`temporal.window.CausalBoxcar` weights tagged with a cycle length.

    The weights *are* the boxcar's (it inherits them); the ``period`` only
    records the cycle the configuration is built around — pair it with a
    `temporal.geometry.PhaseWindow` of the same period — so YAML configs keep the
    intent.

    Args:
        period: Cycle length in time-axis steps (``>= 1``).
    """

    period: int

    def __post_init__(self) -> None:
        if int(self.period) < 1:
            raise ValueError(f"period must be >= 1, got {self.period!r}")

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

Aggregation

geopatcher.temporal.aggregation.Aggregation

Base for time-axis merge strategies.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
class Aggregation:
    """Base for time-axis merge strategies."""

    streaming_safe: ClassVar[bool] = False
    forbid_in_yaml: ClassVar[bool] = False

    def merge(self, patches: Iterable[Any]) -> Any:
        raise NotImplementedError

    def get_config(self) -> dict[str, Any]:
        return {}

geopatcher.temporal.aggregation.Fold dataclass

Bases: Aggregation

Stateful left-fold across patches — the RNN / state-space shape.

Parameters:

Name Type Description Default
fold_fn Callable[[Any, Any], Any]

(state, patch) -> state. Carries closures, so forbid_in_yaml = True.

required
initial_state Any

Starting accumulator (default None).

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
@dataclass(eq=False)
class Fold(Aggregation):
    """Stateful left-fold across patches — the RNN / state-space shape.

    Args:
        fold_fn: ``(state, patch) -> state``. Carries closures, so
            ``forbid_in_yaml = True``.
        initial_state: Starting accumulator (default ``None``).
    """

    fold_fn: Callable[[Any, Any], Any]
    initial_state: Any = None

    streaming_safe: ClassVar[bool] = True
    forbid_in_yaml: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any]) -> Any:
        state = self.initial_state
        for p in patches:
            state = self.fold_fn(state, p)
        return state

geopatcher.temporal.aggregation.Mean dataclass

Bases: Aggregation

Per-time-step mean of the overlapping patches — the spatial.aggregation.Mean of time.

Each patch is placed at its indices (a slice along the time axis) and accumulated into a running per-step sum and count, so the merge holds one output-sized buffer, never the patch stream, and shrunk edge windows (boundary="shrink") of different lengths merge fine. NaN samples are not counted; steps no patch reached get fill_value.

Parameters:

Name Type Description Default
time_axis int

Which axis of patch.data is the time axis. Must match the patcher's time_axis. Default 0.

0
time_len int | None

Length of the output time axis. None (default) uses the furthest patch indices.stop; pass the series length to cover trailing steps no patch reached (they get fill_value).

None
fill_value float

Written into steps with no valid sample. Default NaN.

nan

Raises:

Type Description
ValueError

On an empty patch stream without time_len (the output shape is unknown), a patch whose indices is not a unit-step slice matching its data, or patches whose non-time shapes differ.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
@dataclass(eq=False)
class Mean(Aggregation):
    """Per-time-step mean of the overlapping patches — the `spatial.aggregation.Mean` of
    time.

    Each patch is placed at its ``indices`` (a ``slice`` along the time
    axis) and accumulated into a running per-step sum and count, so the
    merge holds one output-sized buffer, never the patch stream, and
    shrunk edge windows (``boundary="shrink"``) of different lengths merge
    fine. NaN samples are not counted; steps no patch reached get
    ``fill_value``.

    Args:
        time_axis: Which axis of ``patch.data`` is the time axis. Must
            match the patcher's ``time_axis``. Default 0.
        time_len: Length of the output time axis. ``None`` (default) uses
            the furthest patch ``indices.stop``; pass the series length to
            cover trailing steps no patch reached (they get ``fill_value``).
        fill_value: Written into steps with no valid sample. Default NaN.

    Raises:
        ValueError: On an empty patch stream without ``time_len`` (the
            output shape is unknown), a patch whose ``indices`` is not a
            unit-step ``slice`` matching its data, or patches whose
            non-time shapes differ.
    """

    time_axis: int = 0
    time_len: int | None = None
    fill_value: float = math.nan

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any]) -> np.ndarray:
        ax = int(self.time_axis)
        total: np.ndarray | None = None
        count: np.ndarray | None = None
        for p in patches:
            x = np.moveaxis(np.asarray(p.data, dtype=np.float64), ax, 0)
            sl = _time_slice(p, x.shape[0], type(self).__name__)
            if total is None or count is None:
                n = self.time_len if self.time_len is not None else sl.stop
                total = np.zeros((max(int(n), sl.stop), *x.shape[1:]))
                count = np.zeros_like(total)
            elif x.shape[1:] != total.shape[1:]:
                raise ValueError(
                    f"temporal.aggregation.Mean: patch at anchor {p.anchor} has "
                    "non-time "
                    f"shape {x.shape[1:]}, expected {total.shape[1:]}"
                )
            if sl.stop > total.shape[0]:
                grow = [(0, sl.stop - total.shape[0])] + [(0, 0)] * (x.ndim - 1)
                total, count = np.pad(total, grow), np.pad(count, grow)
            valid = ~np.isnan(x)
            total[sl] += np.where(valid, x, 0.0)
            count[sl] += valid
        if total is None or count is None:
            if self.time_len is None:
                raise ValueError(
                    "temporal.aggregation.Mean.merge got no patches; pass time_len= to "
                    "get an all-fill output for an empty stream."
                )
            return np.full(int(self.time_len), self.fill_value, dtype=np.float64)
        with np.errstate(invalid="ignore", divide="ignore"):
            out = np.where(count > 0, total / count, self.fill_value)
        return np.moveaxis(out, 0, ax)

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.aggregation.HierarchicalCombine dataclass

Bases: Aggregation

Stitch multi-scale outputs — pairs with temporal.geometry.MultiScale geometry.

temporal.geometry.MultiScale.window emits one patch per (anchor, scale), so the aggregation keys on the (anchor, scale) pair rather than on the anchor alone. The scale is the patch's TemporalPatch.window_index (set by TemporalPatcher), never its realised slice — two scales shrunk to the same edge slice stay distinct. Hand-built patches with window_index=None are numbered in arrival order per anchor (the order split yields them).

Returns {anchor: {scale_key: data}}: scale_key is scales[k] when scales is supplied (it should equal temporal.geometry.MultiScale.scales), else the window index k.

Parameters:

Name Type Description Default
scales list[int]

List of lookback lengths matching temporal.geometry.MultiScale.scales. When supplied, the inner-dict keys become the scale lengths.

list()

Raises:

Type Description
ValueError

If scales is supplied and a window index has no matching entry, or two patches claim the same (anchor, scale).

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
@dataclass(eq=False)
class HierarchicalCombine(Aggregation):
    """Stitch multi-scale outputs — pairs with `temporal.geometry.MultiScale` geometry.

    `temporal.geometry.MultiScale.window` emits one patch per (anchor, scale), so the
    aggregation keys on the *(anchor, scale)* pair rather than on the
    anchor alone. The scale is the patch's `TemporalPatch.window_index`
    (set by `TemporalPatcher`), never its realised slice — two scales
    shrunk to the same edge slice stay distinct. Hand-built patches with
    ``window_index=None`` are numbered in arrival order per anchor (the
    order `split` yields them).

    Returns ``{anchor: {scale_key: data}}``: ``scale_key`` is
    ``scales[k]`` when ``scales`` is supplied (it should equal
    `temporal.geometry.MultiScale.scales`), else the window index ``k``.

    Args:
        scales: List of lookback lengths matching `temporal.geometry.MultiScale.scales`.
            When supplied, the inner-dict keys become the scale lengths.

    Raises:
        ValueError: If ``scales`` is supplied and a window index has no
            matching entry, or two patches claim the same (anchor, scale).
    """

    scales: list[int] = field(default_factory=list)

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any]) -> dict[int, dict[Any, Any]]:
        out: dict[int, dict[Any, Any]] = {}
        for p in patches:
            anchor = int(p.anchor)
            inner = out.setdefault(anchor, {})
            k = getattr(p, "window_index", None)
            k = len(inner) if k is None else int(k)
            if self.scales:
                if not 0 <= k < len(self.scales):
                    raise ValueError(
                        f"temporal.aggregation.HierarchicalCombine: window index {k} "
                        "at "
                        f"anchor {anchor} has no entry in scales={self.scales}"
                    )
                key: Any = int(self.scales[k])
            else:
                key = k
            if key in inner:
                raise ValueError(
                    f"temporal.aggregation.HierarchicalCombine: two patches for anchor "
                    f"{anchor}, scale {key!r}"
                )
            inner[key] = p.data
        return out

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

geopatcher.temporal.aggregation.Forecast dataclass

Bases: Aggregation

Keep only the horizon portion - pairs with temporal.geometry.LookbackHorizon.

The horizon is the horizon steps after the anchor, [anchor + 1, anchor + 1 + horizon), located from the anchor rather than taken as the patch's tail. A patch's data is either the whole lookback + horizon block covering patch.indices (the horizon is sliced out of it) or, for a model that predicts only the future, a horizon-step block (kept as is). Patches whose window does not contain the full horizon (a boundary="shrink" window at the end of the axis) are skipped, never mislabelled. The aggregation returns {anchor: horizon_block} so callers can align predictions back onto the time axis.

Parameters:

Name Type Description Default
horizon int

Number of steps after the anchor to keep.

1
time_axis int

Which axis of patch.data is the time axis. Must match the patcher's time_axis. Default 0.

0

Raises:

Type Description
ValueError

A patch whose indices is not a bounded slice, or whose time length is neither the window's nor horizon.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
@dataclass(eq=False)
class Forecast(Aggregation):
    """Keep only the horizon portion - pairs with `temporal.geometry.LookbackHorizon`.

    The horizon is the ``horizon`` steps *after the anchor*,
    ``[anchor + 1, anchor + 1 + horizon)``, located from the anchor rather
    than taken as the patch's tail. A patch's data is either the whole
    lookback + horizon block covering ``patch.indices`` (the horizon is
    sliced out of it) or, for a model that predicts only the future, a
    ``horizon``-step block (kept as is). Patches whose window does not
    contain the full horizon (a ``boundary="shrink"`` window at the end
    of the axis) are skipped, never mislabelled. The aggregation returns
    ``{anchor: horizon_block}`` so callers can align predictions back
    onto the time axis.

    Args:
        horizon: Number of steps after the anchor to keep.
        time_axis: Which axis of ``patch.data`` is the time axis. Must
            match the patcher's ``time_axis``. Default 0.

    Raises:
        ValueError: A patch whose ``indices`` is not a bounded slice, or
            whose time length is neither the window's nor ``horizon``.
    """

    horizon: int = 1
    time_axis: int = 0

    streaming_safe: ClassVar[bool] = True

    def merge(self, patches: Iterable[Any]) -> dict[int, Any]:
        out: dict[int, Any] = {}
        ax = int(self.time_axis)
        h = int(self.horizon)
        for p in patches:
            arr = np.asarray(p.data)
            n = arr.shape[ax]
            s = p.indices
            if not isinstance(s, slice) or s.start is None or s.stop is None:
                raise ValueError(
                    "temporal.aggregation.Forecast needs patch.indices to be a "
                    "bounded time "
                    f"slice; got {s!r} at anchor {p.anchor}"
                )
            first = int(p.anchor) + 1 - int(s.start)
            if first < 0 or first + h > int(s.stop) - int(s.start):
                continue  # the window does not hold the whole horizon
            if n == int(s.stop) - int(s.start):
                idx: list[Any] = [slice(None)] * arr.ndim
                idx[ax] = slice(first, first + h)
                out[int(p.anchor)] = arr[tuple(idx)]
            elif n == h:
                out[int(p.anchor)] = arr
            else:
                raise ValueError(
                    f"temporal.aggregation.Forecast: patch at anchor {p.anchor} has "
                    f"{n} "
                    f"steps along time_axis={ax}; expected the window's "
                    f"{int(s.stop) - int(s.start)} or horizon={h}"
                )
        return out

    def get_config(self) -> dict[str, Any]:
        return config_from_fields(self)

Temporal stencils

Coordinate-aware time windows (see ADR-004 and the temporal stencils recipe). Closed is the Literal["left", "right", "both", "neither"] alias used by the stencil endpoints.

geopatcher.temporal.stencils.Stencil dataclass

Sample points relative to an origin, in coordinate units.

The three numeric fields are deliberately typed Any rather than a TypeVar: the runtime contract is "all three are the same orderable type, with +/-/* defined" (Python numerics, NumPy scalars, timedelta64), but a TypeVar[T] confuses static checkers' numeric overload resolution. TimeStencil is the typed specialisation.

Parameters:

Name Type Description Default
start Any

Left edge of the window in coordinate units (relative to the origin).

required
stop Any

Right edge in coordinate units. Must satisfy start <= stop; for the degenerate single-point stencil start == stop and step == 0 with closed="both".

required
step Any

Spacing between sample points in coordinate units. Must be strictly positive and evenly divide stop - start when start < stop.

required
closed Closed

Which endpoints are included. One of "left", "right", "both", "neither". Defaults to "left".

'left'

Raises:

Type Description
ValueError

On an invalid closed, start > stop, a non-positive or uneven step, or a stencil whose closedness trim leaves no sample point (Stencil(-1, 0, 1, closed="neither")).

TypeError

If the three fields mix timedelta64 and plain numbers.

Examples:

>>> Stencil(start=-2, stop=2, step=0.5, closed='both').points
array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
@dataclasses.dataclass(frozen=True)
class Stencil:
    """Sample points relative to an origin, in coordinate units.

    The three numeric fields are deliberately typed `Any` rather than a
    `TypeVar`: the runtime contract is "all three are the same orderable
    type, with `+`/`-`/`*` defined" (Python numerics, NumPy scalars,
    `timedelta64`), but a `TypeVar[T]` confuses static checkers' numeric
    overload resolution. `TimeStencil` is the typed specialisation.

    Args:
        start: Left edge of the window in coordinate units (relative to the
            origin).
        stop: Right edge in coordinate units. Must satisfy ``start <= stop``;
            for the degenerate single-point stencil ``start == stop`` and
            ``step == 0`` with ``closed="both"``.
        step: Spacing between sample points in coordinate units. Must be
            strictly positive and evenly divide ``stop - start`` when
            ``start < stop``.
        closed: Which endpoints are included. One of ``"left"``, ``"right"``,
            ``"both"``, ``"neither"``. Defaults to ``"left"``.

    Raises:
        ValueError: On an invalid ``closed``, ``start > stop``, a
            non-positive or uneven ``step``, or a stencil whose closedness
            trim leaves no sample point (``Stencil(-1, 0, 1, closed="neither")``).
        TypeError: If the three fields mix `timedelta64` and plain numbers.

    Examples:
        >>> Stencil(start=-2, stop=2, step=0.5, closed='both').points
        array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])
    """

    start: Any
    stop: Any
    step: Any
    closed: Closed = dataclasses.field(default="left", kw_only=True)

    def __post_init__(self) -> None:
        # A `{"value", "unit"}` mapping is the config form of a timedelta64
        # field (see `get_config`); coerce it so `Stencil(**cfg)` rebuilds.
        for name in ("start", "stop", "step"):
            value = getattr(self, name)
            if isinstance(value, Mapping):
                object.__setattr__(self, name, _to_timedelta64(value))
        if self.closed not in {"left", "right", "both", "neither"}:
            raise ValueError(f"invalid value for closed: {self.closed!r}")
        kinds = {
            np.asarray(v).dtype.kind == "m" for v in (self.start, self.stop, self.step)
        }
        if len(kinds) > 1:
            raise TypeError(
                "Stencil start / stop / step must all be timedelta64 or all "
                f"numbers; got {self.start!r}, {self.stop!r}, {self.step!r}"
            )
        if self.start == self.stop:
            if self.step != self.stop - self.start:
                raise ValueError(
                    "For single value stencil ``step`` must equal zero: "
                    f"{self.step=} vs {self.stop - self.start=}"
                )
            if self.closed != "both":
                raise ValueError(
                    'For single value stencil ``closed`` must be "both": '
                    f"{self.closed=}"
                )
        elif self.start > self.stop:
            raise ValueError(
                f"start must not be greater than stop: {self.start} vs {self.stop}"
            )
        else:
            # Non-degenerate window: step must be strictly positive, else
            # `points` produces an inconsistent / reversed grid and slices
            # become silently malformed. Caught here so the error names the
            # field directly.
            zero = self.stop - self.stop
            if self.step <= zero:
                raise ValueError(
                    f"step must be strictly positive when start < stop: {self.step=}"
                )
            if len(self.points) == 0:
                raise ValueError(
                    f"Stencil({self.start!r}, {self.stop!r}, {self.step!r}, "
                    f"closed={self.closed!r}) has no sample points after the "
                    "closedness trim; widen it or include an endpoint."
                )

    @property
    def includes_start(self) -> bool:
        return self.closed in _INCLUDE_START

    @property
    def includes_stop(self) -> bool:
        return self.closed in _INCLUDE_STOP

    @property
    def points(self) -> np.ndarray:
        """Realised sample points after the closedness trim."""
        if self.step:
            num = int(
                exact_quotient(self.stop - self.start, self.step, label="step").item()
            )
        else:
            num = 0
        result = self.start + self.step * np.arange(num + 1)
        if not self.includes_start and self.step:
            result = result[1:]
        if not self.includes_stop and self.step:
            result = result[:-1]
        return result

    def get_config(self) -> dict[str, Any]:
        """YAML-serialisable view of the stencil — geopatcher convention.

        Numeric fields dump as-is; `np.timedelta64` fields dump as
        ``{"value": int, "unit": str}`` (exact at every resolution), which
        both `Stencil` and `TimeStencil` accept back.
        """
        return {
            "start": delta_config(self.start),
            "stop": delta_config(self.stop),
            "step": delta_config(self.step),
            **config_from_fields(self, exclude=("start", "stop", "step")),
        }

points property

Realised sample points after the closedness trim.

get_config()

YAML-serialisable view of the stencil — geopatcher convention.

Numeric fields dump as-is; np.timedelta64 fields dump as {"value": int, "unit": str} (exact at every resolution), which both Stencil and TimeStencil accept back.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def get_config(self) -> dict[str, Any]:
    """YAML-serialisable view of the stencil — geopatcher convention.

    Numeric fields dump as-is; `np.timedelta64` fields dump as
    ``{"value": int, "unit": str}`` (exact at every resolution), which
    both `Stencil` and `TimeStencil` accept back.
    """
    return {
        "start": delta_config(self.start),
        "stop": delta_config(self.stop),
        "step": delta_config(self.step),
        **config_from_fields(self, exclude=("start", "stop", "step")),
    }

geopatcher.temporal.stencils.TimeStencil

Bases: Stencil

Stencil specialised to np.timedelta64.

Accepts NumPy timedelta strings ("-9h", "3h", "30min", "2D", "-1000 milliseconds"), {"value", "unit"} mappings (the get_config form), or pre-built np.timedelta64 instances.

Examples:

>>> TimeStencil(start='-9h', stop='3h', step='1h', closed='both')
TimeStencil(start='-9 hours', stop='3 hours', step='1 hours', closed='both')
>>> TimeStencil(**TimeStencil('-9h', '3h', '1h').get_config()).step
np.timedelta64(1,'h')
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
class TimeStencil(Stencil):
    """`Stencil` specialised to `np.timedelta64`.

    Accepts NumPy timedelta strings (``"-9h"``, ``"3h"``, ``"30min"``,
    ``"2D"``, ``"-1000 milliseconds"``), ``{"value", "unit"}`` mappings (the
    `get_config` form), or pre-built `np.timedelta64` instances.

    Examples:
        >>> TimeStencil(start='-9h', stop='3h', step='1h', closed='both')
        TimeStencil(start='-9 hours', stop='3 hours', step='1 hours', closed='both')
        >>> TimeStencil(**TimeStencil('-9h', '3h', '1h').get_config()).step
        np.timedelta64(1,'h')
    """

    def __init__(
        self,
        start: str | Mapping[str, Any] | np.timedelta64,
        stop: str | Mapping[str, Any] | np.timedelta64,
        step: str | Mapping[str, Any] | np.timedelta64,
        closed: Closed = "left",
    ) -> None:
        super().__init__(
            _to_timedelta64(start),
            _to_timedelta64(stop),
            _to_timedelta64(step),
            closed=closed,
        )

    def __repr__(self) -> str:
        return (
            f"TimeStencil(start='{self.start}', stop='{self.stop}',"
            f" step='{self.step}', closed='{self.closed}')"
        )

geopatcher.temporal.stencils.build_sampling_slices(source_points, sample_origins, stencil)

Resolve a stencil at each origin into slice objects.

Parameters:

Name Type Description Default
source_points ArrayLike

1-D, sorted-ascending, evenly-spaced data coordinates.

required
sample_origins ArrayLike

1-D, sorted-ascending origin coordinates. Each must be a value present in source_points (arbitrary gaps OK).

required
stencil Stencil

The stencil shape to apply at each origin.

required

Returns:

Type Description
list[slice]

list[slice], one per origin. Each slice has stride

list[slice]

max(stencil.step / source_step, 1) — at most one element per

list[slice]

source step. Strides > 1 are valid stencil output but rejected by

list[slice]

the v0.1 temporal.geometry.StencilGeometry wrapper.

Raises:

Type Description
ValueError

For non-1-D inputs, unsorted points, non-constant source step, uneven division of stencil.step by source_step, or any origin whose stencil falls outside source_points.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def build_sampling_slices(
    source_points: np.typing.ArrayLike,
    sample_origins: np.typing.ArrayLike,
    stencil: Stencil,
) -> list[slice]:
    """Resolve a stencil at each origin into `slice` objects.

    Args:
        source_points: 1-D, sorted-ascending, evenly-spaced data coordinates.
        sample_origins: 1-D, sorted-ascending origin coordinates. Each must
            be a value present in ``source_points`` (arbitrary gaps OK).
        stencil: The stencil shape to apply at each origin.

    Returns:
        ``list[slice]``, one per origin. Each slice has stride
        ``max(stencil.step / source_step, 1)`` — at most one element per
        source step. Strides > 1 are valid stencil output but rejected by
        the v0.1 `temporal.geometry.StencilGeometry` wrapper.

    Raises:
        ValueError: For non-1-D inputs, unsorted points, non-constant source
            step, uneven division of stencil.step by source_step, or any
            origin whose stencil falls outside ``source_points``.
    """
    source_points = np.asarray(source_points)
    sample_origins = np.asarray(sample_origins)

    if source_points.ndim != 1:
        raise ValueError(f"source_points must be 1D, got {source_points.shape=}")

    if sample_origins.ndim != 1:
        raise ValueError(f"sample_origins must be 1D, got {sample_origins.shape=}")

    source_steps = np.diff(source_points)
    if not np.all(source_steps > 0):
        raise ValueError(f"source_points must be sorted: {source_points=}")

    source_step = source_steps[0]
    if np.any(source_steps != source_step):
        raise ValueError(f"source_points must have constant step: {source_points=}")

    if not np.all(np.diff(sample_origins) > 0):
        raise ValueError(f"sample_origins must be sorted: {sample_origins=}")

    start_points = sample_origins + stencil.start
    starts = exact_quotient(
        start_points - source_points[0], source_step, label="source_step"
    )
    if sample_origins[0] + stencil.points[0] < source_points[0]:
        raise ValueError(
            "all points in the stencil centered on the first sample_origin must be "
            "at or after the first source point: "
            f"{sample_origins[0] + stencil.points} vs {source_points[0]}"
        )
    if not stencil.includes_start:
        starts += 1

    stop_points = sample_origins + stencil.stop
    stops = exact_quotient(
        stop_points - source_points[0], source_step, label="source_step"
    )
    if sample_origins[-1] + stencil.points[-1] > source_points[-1]:
        raise ValueError(
            "all points in the stencil centered on the last sample_origin must be"
            " at or before the last source point:"
            f" {sample_origins[-1] + stencil.points} vs {source_points[-1]}"
        )
    if stencil.includes_stop:
        stops += 1

    stride = max(
        exact_quotient(stencil.step, source_step, label="source_step").item(), 1
    )

    return [
        slice(int(start), int(stop), int(stride))
        for start, stop in zip(starts.tolist(), stops.tolist(), strict=True)
    ]

geopatcher.temporal.stencils.coord_step(source_points)

Validate a 1-D, strictly increasing, evenly spaced coord; return its step.

The one O(N) pass the stencil path needs per coordinate vector: with the step known, every window is resolved arithmetically by stencil_offsets instead of re-validating the coordinate per origin.

Raises:

Type Description
ValueError

For a non-1-D coordinate, fewer than two points, or points that are not strictly increasing or evenly spaced.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def coord_step(source_points: np.typing.ArrayLike) -> Any:
    """Validate a 1-D, strictly increasing, evenly spaced coord; return its step.

    The one O(N) pass the stencil path needs per coordinate vector: with
    the step known, every window is resolved arithmetically by
    `stencil_offsets` instead of re-validating the coordinate per origin.

    Raises:
        ValueError: For a non-1-D coordinate, fewer than two points, or
            points that are not strictly increasing or evenly spaced.
    """
    points = np.asarray(source_points)
    if points.ndim != 1:
        raise ValueError(f"coord must be 1-D; got shape {points.shape}.")
    if points.shape[0] < 2:
        raise ValueError(
            f"coord needs at least two points to define a step; got {points.shape[0]}."
        )
    steps = np.diff(points)
    if not np.all(steps > steps.dtype.type(0)):
        raise ValueError(
            "coord must be strictly increasing (sorted ascending, no "
            "duplicates); reverse a descending axis first."
        )
    step = steps[0]
    if np.any(steps != step):
        raise ValueError(
            f"coord must be evenly spaced; first step {step!r}, found "
            f"{np.unique(steps)[:5]!r}."
        )
    return step

geopatcher.temporal.stencils.stencil_offsets(stencil, source_step)

(lo, hi, stride) index offsets of stencil on a source_step grid.

The window at origin index i of an evenly spaced coordinate is slice(i + lo, i + hi, stride) — exactly what build_sampling_slices returns for that origin, computed in O(1).

Raises:

Type Description
ValueError

If source_step does not evenly divide the stencil's bounds or step.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def stencil_offsets(stencil: Stencil, source_step: Any) -> tuple[int, int, int]:
    """``(lo, hi, stride)`` index offsets of ``stencil`` on a ``source_step`` grid.

    The window at origin index ``i`` of an evenly spaced coordinate is
    ``slice(i + lo, i + hi, stride)`` — exactly what `build_sampling_slices`
    returns for that origin, computed in O(1).

    Raises:
        ValueError: If ``source_step`` does not evenly divide the stencil's
            bounds or step.
    """
    lo = int(exact_quotient(stencil.start, source_step, label="source_step").item())
    hi = int(exact_quotient(stencil.stop, source_step, label="source_step").item())
    if not stencil.includes_start:
        lo += 1
    if stencil.includes_stop:
        hi += 1
    stride = max(
        int(exact_quotient(stencil.step, source_step, label="source_step").item()), 1
    )
    return lo, hi, stride

geopatcher.temporal.stencils.exact_quotient(x, y, *, label='value')

Compute round(x / y) and verify the result is exact.

Operands are numbers or timedelta64 durations (both of the same kind). For timedelta64 operands the equality is exact (NumPy promotes both sides to a common resolution before the integer comparison). For float operands we allow 1e-6 slack. A datetime64 is a point in time, not a duration — subtract an origin first.

Parameters:

Name Type Description Default
x ArrayLike

Numerator. May be scalar or array-like.

required
y ArrayLike

Denominator. Scalar or broadcastable to x; must be non-zero.

required
label str

Short noun describing what y represents — used in the error message so callers see e.g. "step" rather than just the raw value. Defaults to "value".

'value'

Returns:

Type Description
ndarray

The integer quotient as np.ndarray of dtype int.

Raises:

Type Description
ValueError

If y is zero or does not evenly divide x. The message names both operands so unit mismatches are obvious from the traceback.

TypeError

If either operand is a datetime64, or one is a timedelta64 and the other is not.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def exact_quotient(
    x: np.typing.ArrayLike,
    y: np.typing.ArrayLike,
    *,
    label: str = "value",
) -> np.ndarray:
    """Compute ``round(x / y)`` and verify the result is exact.

    Operands are numbers or `timedelta64` durations (both of the same
    kind). For `timedelta64` operands the equality is exact (NumPy
    promotes both sides to a common resolution before the integer
    comparison). For float operands we allow ``1e-6`` slack. A
    `datetime64` is a point in time, not a duration — subtract an origin
    first.

    Args:
        x: Numerator. May be scalar or array-like.
        y: Denominator. Scalar or broadcastable to ``x``; must be non-zero.
        label: Short noun describing what ``y`` represents — used in the
            error message so callers see e.g. ``"step"`` rather than just
            the raw value. Defaults to ``"value"``.

    Returns:
        The integer quotient as ``np.ndarray`` of dtype ``int``.

    Raises:
        ValueError: If ``y`` is zero or does not evenly divide ``x``. The
            message names both operands so unit mismatches are obvious from
            the traceback.
        TypeError: If either operand is a `datetime64`, or one is a
            `timedelta64` and the other is not.
    """
    x = np.asarray(x)
    y = np.asarray(y)
    if x.dtype.kind == "M" or y.dtype.kind == "M":
        raise TypeError(
            f"exact_quotient takes durations, not datetime64 points in time: "
            f"{x!r} / {y!r}; subtract an origin first."
        )
    if (x.dtype.kind == "m") != (y.dtype.kind == "m"):
        raise TypeError(
            f"exact_quotient needs both operands to be timedelta64 or both "
            f"numeric; got {x.dtype} / {y.dtype} ({label})"
        )
    if np.any(y == y.dtype.type(0)):
        raise ValueError(f"{label} must be non-zero; got {y!r}")
    q = np.around(x / y).astype(int)
    if np.issubdtype(x.dtype, np.timedelta64):
        uneven = q * y != x
    else:
        epsilon = 1e-6
        uneven = abs(q * y - x) > epsilon
    if np.any(uneven):
        raise ValueError(f"{label} {y!r} must evenly divide {x!r}")
    return q

geopatcher.temporal.stencils.valid_origin_points(source_points, stencil)

Source points for which the full stencil fits in-record.

Trims both ends so every emitted window is full-length — the largest anchor set with no truncation.

Parameters:

Name Type Description Default
source_points ArrayLike

1-D, sorted-ascending, evenly-spaced data coordinates.

required
stencil Stencil

The stencil shape.

required

Returns:

Type Description
ndarray

Subset of source_points whose stencil fits entirely between

ndarray

source_points[0] and source_points[-1].

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
def valid_origin_points(
    source_points: np.typing.ArrayLike, stencil: Stencil
) -> np.ndarray:
    """Source points for which the full stencil fits in-record.

    Trims both ends so every emitted window is full-length — the largest
    anchor set with no truncation.

    Args:
        source_points: 1-D, sorted-ascending, evenly-spaced data coordinates.
        stencil: The stencil shape.

    Returns:
        Subset of ``source_points`` whose stencil fits entirely between
        ``source_points[0]`` and ``source_points[-1]``.
    """
    source_points = np.asarray(source_points)

    min_origin = source_points[0] - stencil.start
    if not stencil.includes_start:
        min_origin -= stencil.step

    max_origin = source_points[-1] - stencil.stop
    if not stencil.includes_stop:
        max_origin += stencil.step

    valid_origins = source_points[
        (source_points >= min_origin) & (source_points <= max_origin)
    ]
    return valid_origins

The four-axis integration points are documented with the other temporal axes above:

geopatcher.temporal.geometry.StencilGeometry dataclass

Bases: Geometry

Coordinate-aware geometry that resolves a Stencil against a coord.

Unlike the integer geometries above, the window is resolved in coordinate space via window_coord(coord, anchor_idx). TemporalPatcher dispatches on the needs_coord flag and supplies the coord vector through the split(..., coord=) argument. Calling the integer window is a TypeError so mis-wiring fails loudly.

v0.1 supports stride-1 stencils only (the temporal.window.Window.weights and temporal.aggregation.Aggregation.merge contracts assume contiguous index ranges). Pass source_step at construction to catch stride > 1 up front; the constructor also re-checks at window_coord time as a belt-and-braces guard for callers that didn't supply it. See ADR-004 in docs/patcher/decisions.md.

The coordinate is validated (1-D, strictly increasing, evenly spaced) once per coordinate array, not per anchor: windows are then resolved arithmetically from the source step (stencil_offsets), so a split over a 175 320-step (20-year hourly) axis costs O(N), not O(N²).

Parameters:

Name Type Description Default
stencil Stencil

The Stencil (or TimeStencil) describing the window shape in coordinate units.

required
source_step Any

Optional cadence of the source grid (same units as stencil.step; a string such as "1h" is parsed like a TimeStencil field, as is the {"value", "unit"} mapping get_config emits). If provided, the constructor raises immediately on stride > 1 or a unit mismatch instead of waiting for window_coord.

None
boundary TemporalBoundary

What to do with an origin whose stencil overflows the coordinate: "drop" it (default — temporal.sampler.StencilSampler only places origins that fit anyway), "shrink" the window to the axis, or "raise".

'drop'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
@dataclass(eq=False)
class StencilGeometry(Geometry):
    """Coordinate-aware geometry that resolves a `Stencil` against a coord.

    Unlike the integer geometries above, the window is resolved in *coordinate*
    space via `window_coord(coord, anchor_idx)`. `TemporalPatcher` dispatches
    on the `needs_coord` flag and supplies the coord vector through the
    `split(..., coord=)` argument. Calling the integer `window` is a TypeError
    so mis-wiring fails loudly.

    v0.1 supports stride-1 stencils only (the `temporal.window.Window.weights` and
    `temporal.aggregation.Aggregation.merge` contracts assume contiguous index ranges).
    Pass ``source_step`` at construction to catch stride > 1 up front; the
    constructor also re-checks at `window_coord` time as a belt-and-braces
    guard for callers that didn't supply it. See ADR-004 in
    ``docs/patcher/decisions.md``.

    The coordinate is validated (1-D, strictly increasing, evenly spaced)
    once per coordinate array, not per anchor: windows are then resolved
    arithmetically from the source step (`stencil_offsets`), so a split
    over a 175 320-step (20-year hourly) axis costs O(N), not O(N²).

    Args:
        stencil: The `Stencil` (or `TimeStencil`) describing the window shape
            in coordinate units.
        source_step: Optional cadence of the source grid (same units as
            ``stencil.step``; a string such as ``"1h"`` is parsed like a
            `TimeStencil` field, as is the ``{"value", "unit"}`` mapping
            `get_config` emits). If provided, the constructor raises
            immediately on stride > 1 or a unit mismatch instead of waiting
            for `window_coord`.
        boundary: What to do with an origin whose stencil overflows the
            coordinate: ``"drop"`` it (default — `temporal.sampler.StencilSampler`
            only places origins that fit anyway), ``"shrink"`` the window
            to the axis, or ``"raise"``.
    """

    stencil: Stencil
    source_step: Any = None
    boundary: TemporalBoundary = "drop"
    needs_coord: ClassVar[bool] = True

    def __post_init__(self) -> None:
        _check_boundary(self.boundary)
        # Validated-coord memo: (weakref to the coord array, the stencil's
        # (lo, hi, stride) index offsets on its step).
        self._coord_memo: tuple[Any, tuple[int, int, int]] | None = None
        if isinstance(self.source_step, (str, Mapping)):
            self.source_step = _to_timedelta64(self.source_step)
        if self.source_step is not None:
            sigma = int(
                exact_quotient(
                    self.stencil.step,
                    self.source_step,
                    label="stencil step / source step",
                ).item()
            )
            if sigma != 1:
                raise ValueError(
                    "v0.1 supports stride-1 stencils only; got "
                    f"stride={sigma}. Use a stencil step equal to the source "
                    "cadence, or wait for v0.2."
                )
            # Also rejects a source_step that does not divide the bounds.
            stencil_offsets(self.stencil, self.source_step)

    def __getstate__(self) -> dict[str, Any]:
        state = self.__dict__.copy()
        state["_coord_memo"] = None  # weakrefs do not pickle
        return state

    def _offsets_for(self, coord: np.ndarray) -> tuple[int, int, int]:
        """Stencil offsets on ``coord``, validating each coord array only once."""
        memo = self._coord_memo
        if memo is not None and memo[0]() is coord:
            return memo[1]
        offsets = stencil_offsets(self.stencil, coord_step(coord))
        # A non-weak-referenceable coord is simply re-validated every call.
        with contextlib.suppress(TypeError):
            self._coord_memo = (weakref.ref(coord), offsets)
        return offsets

    def window_coord(self, coord: np.ndarray, anchor_idx: int) -> slice | None:
        """Resolve the stencil at the given anchor index → contiguous slice.

        Args:
            coord: 1-D, strictly increasing, evenly spaced coordinate array
                along the time axis (e.g. ``ds["time"].values``).
            anchor_idx: Integer index into ``coord`` marking the origin.

        Returns:
            ``slice(start, stop)`` covering the realised stencil window in
            integer index space, or ``None`` when ``boundary="drop"`` drops
            an overflowing origin.

        Raises:
            ValueError: For an invalid coordinate, a stride > 1, or (under
                ``boundary="raise"``) an overflowing origin.
        """
        coord = np.asarray(coord)
        lo, hi, stride = self._offsets_for(coord)
        if stride != 1:
            raise ValueError(
                f"v0.1 supports stride-1 stencils only; got stride={stride}."
            )
        i = int(anchor_idx)
        return _resolve(self, i, i + lo, i + hi, int(coord.shape[0]), self.boundary)

    def window(self, time_len: int, anchor: int) -> slice | list[slice] | None:
        raise TypeError(
            "temporal.geometry.StencilGeometry is coordinate-aware; call via "
            "TemporalPatcher.split(..., coord=time_coord) which dispatches to "
            "window_coord. Direct integer window() is not defined."
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "stencil": axis_envelope(self.stencil),
            "source_step": delta_config(self.source_step),
            "boundary": self.boundary,
        }

window_coord(coord, anchor_idx)

Resolve the stencil at the given anchor index → contiguous slice.

Parameters:

Name Type Description Default
coord ndarray

1-D, strictly increasing, evenly spaced coordinate array along the time axis (e.g. ds["time"].values).

required
anchor_idx int

Integer index into coord marking the origin.

required

Returns:

Type Description
slice | None

slice(start, stop) covering the realised stencil window in

slice | None

integer index space, or None when boundary="drop" drops

slice | None

an overflowing origin.

Raises:

Type Description
ValueError

For an invalid coordinate, a stride > 1, or (under boundary="raise") an overflowing origin.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
def window_coord(self, coord: np.ndarray, anchor_idx: int) -> slice | None:
    """Resolve the stencil at the given anchor index → contiguous slice.

    Args:
        coord: 1-D, strictly increasing, evenly spaced coordinate array
            along the time axis (e.g. ``ds["time"].values``).
        anchor_idx: Integer index into ``coord`` marking the origin.

    Returns:
        ``slice(start, stop)`` covering the realised stencil window in
        integer index space, or ``None`` when ``boundary="drop"`` drops
        an overflowing origin.

    Raises:
        ValueError: For an invalid coordinate, a stride > 1, or (under
            ``boundary="raise"``) an overflowing origin.
    """
    coord = np.asarray(coord)
    lo, hi, stride = self._offsets_for(coord)
    if stride != 1:
        raise ValueError(
            f"v0.1 supports stride-1 stencils only; got stride={stride}."
        )
    i = int(anchor_idx)
    return _resolve(self, i, i + lo, i + hi, int(coord.shape[0]), self.boundary)

geopatcher.temporal.sampler.StencilSampler dataclass

Bases: Sampler

Anchor sampler whose valid set is defined by a Stencil.

Yields integer indices into the coord vector — same return type as every other temporal.sampler.Sampler. The novelty is which integers count: only those whose stencil, when resolved against coord, fits entirely in-record (no truncation at either end).

Coordinate plumbing follows the needs_coord = True contract: TemporalPatcher forwards its coord= kwarg to anchors.

Parameters:

Name Type Description Default
stencil Stencil

The Stencil (or TimeStencil) used to compute the valid-origin set. Typically the same stencil as the paired temporal.geometry.StencilGeometry.

required
every int

Thin the valid-origin set in valid-anchor space (>= 1). every=2 keeps every other valid origin. Distinct from stencil.step, which is the within-window cadence.

1
shuffle bool

If true, shuffle the kept anchors before emitting. Useful for training-time data loaders.

False
seed int | None

Reproducibility seed for shuffle. Same contract as temporal.sampler.Random.seed.

None
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
@dataclass(eq=False)
class StencilSampler(Sampler):
    """Anchor sampler whose valid set is defined by a `Stencil`.

    Yields integer indices into the ``coord`` vector — same return type as
    every other `temporal.sampler.Sampler`. The novelty is *which* integers count:
    only those whose stencil, when resolved against ``coord``, fits entirely
    in-record (no truncation at either end).

    Coordinate plumbing follows the `needs_coord = True` contract:
    `TemporalPatcher` forwards its ``coord=`` kwarg to `anchors`.

    Args:
        stencil: The `Stencil` (or `TimeStencil`) used to compute the
            valid-origin set. Typically the same stencil as the paired
            `temporal.geometry.StencilGeometry`.
        every: Thin the valid-origin set in *valid-anchor* space
            (``>= 1``). ``every=2`` keeps every other valid origin.
            Distinct from ``stencil.step``, which is the within-window
            cadence.
        shuffle: If true, shuffle the kept anchors before emitting. Useful
            for training-time data loaders.
        seed: Reproducibility seed for ``shuffle``. Same contract as
            `temporal.sampler.Random.seed`.
    """

    stencil: Stencil
    every: int = 1
    shuffle: bool = False
    seed: int | None = None
    needs_coord: ClassVar[bool] = True

    def __post_init__(self) -> None:
        if int(self.every) != self.every or self.every < 1:
            raise ValueError(f"every must be an integer >= 1, got {self.every!r}")

    def anchors(
        self,
        time_len: int,
        coord: np.ndarray | None = None,
    ) -> Iterator[int]:
        if coord is None:
            raise ValueError(
                "temporal.sampler.StencilSampler requires coord=; supply it via "
                "TemporalPatcher.split(..., coord=time_coord)."
            )
        coord = np.asarray(coord)
        coord_step(coord)  # 1-D, strictly increasing, evenly spaced
        if int(time_len) != coord.shape[0]:
            raise ValueError(
                "coord length must equal time_len: "
                f"got coord.shape={coord.shape} vs time_len={time_len}."
            )
        valid = valid_origin_points(coord, self.stencil)
        # coord is monotonic-ascending (precondition of build_sampling_slices),
        # so searchsorted is O(log n) per origin.
        idx = np.searchsorted(coord, valid)[:: self.every]
        if self.shuffle:
            np.random.default_rng(self.seed).shuffle(idx)
        for i in idx:
            yield int(i)

    def get_config(self) -> dict[str, Any]:
        return {
            "stencil": axis_envelope(self.stencil),
            **config_from_fields(self, exclude=("stencil",)),
        }