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
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 ( |
required |
boundary
|
TemporalBoundary
|
What to do with an anchor whose lookback starts before
the axis ( |
'drop'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
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 ( |
required |
horizon
|
int
|
Steps after the anchor ( |
required |
boundary
|
TemporalBoundary
|
What to do with an anchor whose window overflows either
end of the axis: |
'drop'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
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 |
required |
boundary
|
TemporalBoundary
|
What to do with an anchor whose longest lookback starts
before the axis: |
'drop'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
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 |
required |
boundary
|
TemporalBoundary
|
What to do with a slot that overflows the axis (only the
first / last cycle can): |
'drop'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
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
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
|
start
|
int
|
First anchor index ( |
0
|
check_full_scan
|
bool
|
If |
False
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
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 ( |
1
|
seed
|
int | None
|
Integer seed for reproducible draws — same contract as
|
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
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 |
list()
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/sampler.py
Window¶
geopatcher.temporal.window.Window
¶
Base for temporal window functions.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
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
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 ( |
required |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
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.5
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
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 ( |
required |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/window.py
Aggregation¶
geopatcher.temporal.aggregation.Aggregation
¶
Base for time-axis merge strategies.
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
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]
|
|
required |
initial_state
|
Any
|
Starting accumulator (default |
None
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
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 |
0
|
time_len
|
int | None
|
Length of the output time axis. |
None
|
fill_value
|
float
|
Written into steps with no valid sample. Default NaN. |
nan
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On an empty patch stream without |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
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 |
list()
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
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 |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A patch whose |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/aggregation.py
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 |
required |
step
|
Any
|
Spacing between sample points in coordinate units. Must be
strictly positive and evenly divide |
required |
closed
|
Closed
|
Which endpoints are included. One of |
'left'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
On an invalid |
TypeError
|
If the three fields mix |
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
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
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
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
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 |
required |
stencil
|
Stencil
|
The stencil shape to apply at each origin. |
required |
Returns:
| Type | Description |
|---|---|
list[slice]
|
|
list[slice]
|
|
list[slice]
|
source step. Strides > 1 are valid stencil output but rejected by |
list[slice]
|
the v0.1 |
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 code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | |
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
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 code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
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 |
required |
label
|
str
|
Short noun describing what |
'value'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The integer quotient as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If either operand is a |
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
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 |
ndarray
|
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/stencils.py
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 |
required |
source_step
|
Any
|
Optional cadence of the source grid (same units as
|
None
|
boundary
|
TemporalBoundary
|
What to do with an origin whose stencil overflows the
coordinate: |
'drop'
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
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. |
required |
anchor_idx
|
int
|
Integer index into |
required |
Returns:
| Type | Description |
|---|---|
slice | None
|
|
slice | None
|
integer index space, or |
slice | None
|
an overflowing origin. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For an invalid coordinate, a stride > 1, or (under
|
Source code in packages/geotoolz-patcher/src/geopatcher/_src/temporal/geometry.py
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 |
required |
every
|
int
|
Thin the valid-origin set in valid-anchor space
( |
1
|
shuffle
|
bool
|
If true, shuffle the kept anchors before emitting. Useful for training-time data loaders. |
False
|
seed
|
int | None
|
Reproducibility seed for |
None
|