envlib-ingest-base
Shared, tested toolkit for the envlib data-ingest family — and the Docker base image that carries
the envlib stack pre-installed. Ingest repos depend on this package and build FROM its image, so
the tricky, reusable machinery is written and tested once instead of copied per repo.
Two modules:
resample — source-agnostic resampling of irregular / gappy station telemetry to a fixed cadence.
tsortho — build + idempotent commons-update of station (ts_ortho) datasets.
The package is deliberately pandas-free (numpy + shapely + the envlib stack only). Data flows
through it as plain numpy arrays and dicts — the same shapes cfdb ingests — while pandas objects
still work as inputs by duck-typing (see below).
Install / use from an ingest repo
# pyproject.toml
dependencies = ["envlib-ingest-base", ...]
# for local dev against a sibling checkout (drop once it's on PyPI):
[tool.uv.sources]
envlib-ingest-base = { path = "../envlib-ingest-base", editable = true }
from envlib_ingest_base import (
resample, # resampling (statistic keyed to envlib metadata)
build_local, merge_dataset, # ts_ortho (cfdb-level)
build_and_publish, update_and_publish, # ts_ortho + commons publish
)
Resampling (resample)
Turn a single station's raw (times, values) into a fixed-cadence series, returned as a plain
(times, values) tuple: ascending datetime64[us] interval-start labels (envlib
convention; pass UTC in, get UTC out) + float64 values. Unpack immediately —
t, v = resample(...) — and test emptiness as t.size == 0 (never len()/truthiness on
the pair itself, which is always 2/truthy).
Inputs are anything convertible to datetime64: ISO-format strings, datetime64 arrays of
any unit, python datetime objects, or pandas DatetimeIndex/Series (tz-aware converts to
UTC-naive) — no pandas required by the toolkit itself. Time is handled in microseconds
(python datetime's native resolution; ±290k-year range, so overflow is a non-issue in
practice). None/NaT/NaN entries are dropped; non-numeric values raise rather than
coercing silently.
Two kinds, matching the two physical measurement types. Both are epoch-anchored (labels are
multiples of freq since 1970-01-01) — identical to pandas for any freq that divides 24 h.
Missing data and aggregation rules
These rules are the core of the toolkit and deliberate (design rulings 2026-07-17/18); read
them before producing a dataset.
The estimator spans beyond the aggregation interval and must be told where to stop
(max_gap); once stopped, each interval is judged by how much of it remains covered
(min_coverage). The two rules are anchored to two different clocks and are NOT derivable
from each other:
- The gap rule — the data's clock. The mean treats the signal as piecewise-linear
between consecutive readings, regardless of interval boundaries — so it needs a rule for
when interpolation stops being honest. That rule is a property of the source's sampling
design, never of the output frequency: by default, a segment longer than
gap_multiplier × the local median native interval is a hole that is never
interpolated across. The median is local (a rolling window of segments), so a station
that logged 30-min data twenty years ago and 5-min data today is judged by each era's own
cadence — a global median would misclassify one era wholesale. A 5-min site therefore
gets a ~15-min threshold and a 60-min site ~3 h, at any output freq.
- The coverage rule — the output's clock. After holes are excluded, an interval covered
below
min_coverage is absent rather than summarized from too little data. The
default 0.75 follows common climatological completeness practice and is deliberately
conservative: telemetry missingness is not random — outages correlate with the extreme
events you most want recorded. For the mean, coverage is the non-hole time fraction; for
the sum, each reading covers its accumulation slot, capped at one local native
interval — a reading after skipped slots covers only its own slot, so losses are never
credited as measured. An hour holding 8 of its 12 five-minute rain slots is missing,
never published as a silent undercount, and a single-reading series has an unknowable
slot and contributes no coverage (kept only when min_coverage=0).
Sums assume per-slot totals (each reading is the accumulation over its own reporting
slot). Feeds from totalizing gauges (since-last-report accumulations) must be differenced
upstream, and resampling accumulations finer than their native interval is not meaningful.
Common parameters:
| param |
default |
meaning |
freq |
'1h' |
output cadence: '<n><unit>' with unit in h, min, s, D (e.g. '1h', '15min'), the envlib CV code 'day', or a np.timedelta64 / datetime.timedelta. Anything else — including '0min', negative/NaT/calendar timedeltas — raises. |
max_gap |
None |
absolute hole threshold (same forms as freq, e.g. '2h'); None ⇒ adaptive (the local-median rule above). |
gap_multiplier |
3.0 |
adaptive threshold = gap_multiplier × local median(native interval). |
min_coverage |
0.75 |
both kinds: an interval covered below this fraction is absent. 0 disables. Float comparison at the boundary — prefer binary-friendly fractions (0.75, 0.5). |
round_to |
None |
the source's true timestamp precision (same forms as freq, e.g. '1min'). Timestamps are rounded to the nearest multiple before binning — a boundary reading jittered to 11:00:01 bins into the correct hour, and two jittery renderings of one reading collide and merge via the duplicate collapse instead of double-counting. |
resample(times, values, *, statistic='mean', freq='1h', max_gap=None, gap_multiplier=3.0, min_coverage=0.75, round_to=None)
One entry point; statistic selects both the aggregation and the signal model behind it — pass
the dataset's envlib aggregation_statistic metadata value, so the declared identity and the
computation can never drift (the same single-source-of-truth pattern tsortho uses for
frequency_interval). Future statistics of the instantaneous signal (median/min/max share its
segment machinery, differing only in the final reduction) will slot in without an API change;
unknown values raise.
statistic='mean' — instantaneous signals
Exact trapezoidal time-weighted mean for an instantaneous signal (river stage, flow). The signal
is treated as piecewise-linear between observations and integrated over each interval — exact for any
spacing. For grid-aligned regular data this is the trapezoid-rule mean (interval endpoints carry
half-weight): it coincides with the plain arithmetic mean for linear ramps but is NOT pandas'
left-closed .resample().mean().
from envlib_ingest_base import resample
# irregular spacing: 10 @ 00:00, 20 @ 00:15, 100 @ 01:00
times = ['2024-06-01 00:00', '2024-06-01 00:15', '2024-06-01 01:00']
t, v = resample(times, [10.0, 20.0, 100.0])
# t -> ['2024-06-01T00:00'] (datetime64[us])
# v -> [48.75] # time-weighted (the 45-min stretch near 100 dominates),
# # NOT the equal-weight 37.5 a naive .resample().mean() gives
Gaps are dropped, never ramped across:
times = ['2024-06-01 00:00', '2024-06-01 01:00', '2024-06-01 02:00',
'2024-06-01 12:00', '2024-06-01 13:00']
t, v = resample(times, [0.0, 0.0, 0.0, 120.0, 120.0])
# t -> ['2024-06-01T00:00', '2024-06-01T01:00', '2024-06-01T12:00']
# v -> [0.0, 0.0, 120.0] # hours 02:00–11:00 are ABSENT (outage), not contaminated by 120
statistic='sum' — accumulations
Right-closed interval sum for an accumulation signal (rainfall): an interval with no
reading is missing (absent from the output), never a fabricated 0, while a genuinely reported
0.0 is kept. A reading is attributed to the interval it closes (interval-start label).
Duplicate timestamps collapse by mean before summing (the same reading served twice must not
double-count).
# hourly rain totals; note the 03:00–06:00 outage
times = ['2024-06-01 01:00', '2024-06-01 02:00', '2024-06-01 07:00']
t, v = resample(times, [0.0, 0.5, 1.0], statistic='sum')
# t -> ['2024-06-01T00:00', '2024-06-01T01:00', '2024-06-01T06:00']
# v -> [0.0, 0.5, 1.0] # reported 0.0 kept (a confirmed dry hour);
# # hours 02:00–05:00 ABSENT (no reading) — never fabricated as 0
statistic='point' — instantaneous samples published as-is
Identity pass-through for a dataset that publishes readings at their native cadence (a 15-min
flow record published as 15-min points). After rounding to round_to, a reading exactly on the
epoch-anchored freq grid is kept with its value untouched. An off-grid reading is absent, and an
absent stamp stays absent: nothing is interpolated. Two readings on one stamp raise instead of
merging, since averaging them would publish a value nobody measured. A producer that wants jittered
stamps snapped onto the grid passes round_to=freq. max_gap, gap_multiplier and
min_coverage are accepted and unused, because no interval is estimated.
times = ['2024-06-01 00:00', '2024-06-01 00:07', '2024-06-01 00:15', '2024-06-01 00:45']
t, v = resample(times, [1.0, 2.0, 1000.0, 3.0], statistic='point', freq='15min')
# t -> ['2024-06-01T00:00', '2024-06-01T00:15', '2024-06-01T00:45']
# v -> [1.0, 1000.0, 3.0] # values untouched; 00:07 is off-grid and absent; 00:30 stays absent
Not to be confused with statistic='mean' at the source's own cadence: that one returns interval
means (averages of neighbouring readings), as its declaration says.
resample returns (times, values) only. A producer carrying an ancillary per reading (such as a
quality code) re-joins it to the returned stamps by exact match.
Config-driven pipelines key both statistic and freq straight off the dataset's metadata:
t, v = resample(times, values,
statistic=cfg['metadata']['aggregation_statistic'],
freq=cfg['metadata']['frequency_interval'])
Station datasets (tsortho)
Build and update envlib ts_ortho datasets — an orthogonal (point, time) layout: a geometry
coordinate of shapely Points (one per station), a shared dense fixed-step time axis at the
cadence declared by meta.frequency_interval, one data variable named after meta.variable,
and per-station metadata as auxiliary (point,) variables — the established nomenclature for
station data in envlib ts_ortho datasets:
station_id — envlib's deterministic geometry hash (compute_station_id); changes if the
provider corrects a site's coordinates. Carries the CF cf_role = "timeseries_id" marking it as
the timeseries instance identifier (cfdb writes the global featureType = "timeSeries").
station_name — the human-readable name.
station_ref — the source's native identifier (the stations-dict key, e.g. an ECan site
number): the stable join key back to the provider's own records.
station_altitude — station elevation in metres (CF standard_name = "altitude"). Optional:
created only when a source supplies a non-null 'altitude' value in the stations dict (a source
with none, e.g. ECan — or one whose altitude column is all-null — gets no such variable); NaN for
any individual station lacking a value. Stored as-reported (unpacked float32, no declared
precision — survey accuracy varies station-to-station and isn't characterised), and QC'd against
a universal plausibility band (valid_min = -500, valid_max = 9000 m, persisted as attrs);
out-of-range values (incl -9999-type sentinels, ±inf) become missing with a warning, while a
non-coercible value raises (that's an adapter bug, not a sentinel).
Each station var carries a CF long_name (and station_id/station_ref a comment); these
back-fill onto pre-existing datasets on the next update run. Station metadata is written once,
when a station first appears — it is not revised on later merges (correcting it needs a rebuild).
Version notes: station_ref exists in datasets built by toolkit >= 0.1.2 (merging new stations
into an older dataset raises — rebuild it — while revise-only merges keep working); the CF attrs
and station_altitude land from toolkit >= 0.1.4.
Station geometry is canonicalized through envlib.canonical_station_point before it is
stored, from toolkit >= 0.3.1 (which is why that release floors envlib>=0.1.4). Without it, a
source supplying more than 5 decimal places of longitude/latitude could write a point that cfdb
re-rounds on the way in, leaving a stored geometry that no longer derives the stored station_id
— a dataset that then fails publish() forever. Ids are unaffected, so this changed nothing for
stations already stored; datasets built by earlier toolkits need no rebuild. Two stations that
round to the same point (within ~1 m) are now rejected at build with both refs named, instead of
dying inside cfdb's coordinate-uniqueness check.
The envlib metadata is the single source of truth for the cadence — there is no freq
parameter. frequency_interval is a closed envlib vocabulary; only fixed codes work here
(1min…30min, 1h…12h, day — month/year/None raise, a dense axis needs a fixed
duration). The time coordinate is stored in the cadence's natural datetime64 unit — a daily
dataset reads as datetime64[D], hourly as [h], 15-min as [m] — with an explicit step, so
the axis itself tells the reader the data's precision.
Two guards keep declared and actual cadence honest (both fail loud):
- alignment — every incoming timestamp must be an exact multiple of the declared step (the
resample_* labels are, by construction, when resampled at the same freq the metadata declares);
- phase — a fixed cadence with a (reduced)
utc_offset other than +00:00 declares
phase-anchored binning (e.g. local-midnight days) that the epoch-anchored resampler can't
produce, and is rejected. Phase-anchored datasets are a planned follow-up (resampler origin).