envlib-ingest-base 0.1.2__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: envlib-ingest-base
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: Shared toolkit for envlib data-ingest repos: source-agnostic time-series resampling and ts_ortho (station) dataset build + idempotent commons update.
5
5
  Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
6
  Author-email: mullenkamp <mullenkamp1@gmail.com>
@@ -182,7 +182,30 @@ t, v = resample(times, values,
182
182
  Build and update envlib `ts_ortho` datasets — an orthogonal `(point, time)` layout: a geometry
183
183
  coordinate of shapely Points (one per station), a shared **dense fixed-step time axis at the
184
184
  cadence declared by `meta.frequency_interval`**, one data variable named after `meta.variable`,
185
- and `station_id` (envlib's deterministic hash) + `station_name` per station.
185
+ and per-station metadata as auxiliary `(point,)` variables — the established nomenclature for
186
+ station data in envlib ts_ortho datasets:
187
+
188
+ - `station_id` — envlib's deterministic *geometry* hash (`compute_station_id`); changes if the
189
+ provider corrects a site's coordinates. Carries the CF `cf_role = "timeseries_id"` marking it as
190
+ the timeseries instance identifier (cfdb writes the global `featureType = "timeSeries"`).
191
+ - `station_name` — the human-readable name.
192
+ - `station_ref` — the **source's native identifier** (the stations-dict key, e.g. an ECan site
193
+ number): the stable join key back to the provider's own records.
194
+ - `station_altitude` — station elevation in metres (CF `standard_name = "altitude"`). **Optional**:
195
+ created only when a source supplies a non-null `'altitude'` value in the stations dict (a source
196
+ with none, e.g. ECan — or one whose altitude column is all-null — gets no such variable); NaN for
197
+ any individual station lacking a value. Stored **as-reported** (unpacked float32, **no declared
198
+ precision** — survey accuracy varies station-to-station and isn't characterised), and QC'd against
199
+ a universal plausibility band (`valid_min = -500`, `valid_max = 9000` m, persisted as attrs);
200
+ out-of-range values (incl `-9999`-type sentinels, ±inf) become missing with a warning, while a
201
+ non-coercible value raises (that's an adapter bug, not a sentinel).
202
+
203
+ Each station var carries a CF `long_name` (and `station_id`/`station_ref` a `comment`); these
204
+ back-fill onto pre-existing datasets on the next update run. Station metadata is **written once**,
205
+ when a station first appears — it is not revised on later merges (correcting it needs a rebuild).
206
+ Version notes: `station_ref` exists in datasets built by toolkit >= 0.1.2 (merging *new stations*
207
+ into an older dataset raises — rebuild it — while revise-only merges keep working); the CF attrs
208
+ and `station_altitude` land from toolkit >= 0.1.4.
186
209
 
187
210
  **The envlib metadata is the single source of truth for the cadence** — there is no `freq`
188
211
  parameter. `frequency_interval` is a closed envlib vocabulary; only *fixed* codes work here
@@ -206,8 +229,9 @@ axis widens back to midnight — normal numpy semantics, worth knowing as a read
206
229
 
207
230
  Two inputs recur:
208
231
 
209
- - **`stations`** — a dict `{ref: {'lon': float, 'lat': float, 'name': str}}`. From a pandas
210
- frame indexed by ref with those columns: `df.to_dict('index')`.
232
+ - **`stations`** — a dict `{ref: {'lon': float, 'lat': float, 'name': str[, 'altitude': float]}}`.
233
+ From a pandas frame indexed by ref with those columns: `df.to_dict('index')`. `altitude` is
234
+ optional (metres); include it and the `station_altitude` variable is created automatically.
211
235
  - **`series`** — a dict `{ref -> (times, values)}` of resampled tuples (the output of
212
236
  `resample_*` at the metadata's freq). Entries that are `None` or have `times.size == 0` are
213
237
  simply skipped.
@@ -165,7 +165,30 @@ t, v = resample(times, values,
165
165
  Build and update envlib `ts_ortho` datasets — an orthogonal `(point, time)` layout: a geometry
166
166
  coordinate of shapely Points (one per station), a shared **dense fixed-step time axis at the
167
167
  cadence declared by `meta.frequency_interval`**, one data variable named after `meta.variable`,
168
- and `station_id` (envlib's deterministic hash) + `station_name` per station.
168
+ and per-station metadata as auxiliary `(point,)` variables — the established nomenclature for
169
+ station data in envlib ts_ortho datasets:
170
+
171
+ - `station_id` — envlib's deterministic *geometry* hash (`compute_station_id`); changes if the
172
+ provider corrects a site's coordinates. Carries the CF `cf_role = "timeseries_id"` marking it as
173
+ the timeseries instance identifier (cfdb writes the global `featureType = "timeSeries"`).
174
+ - `station_name` — the human-readable name.
175
+ - `station_ref` — the **source's native identifier** (the stations-dict key, e.g. an ECan site
176
+ number): the stable join key back to the provider's own records.
177
+ - `station_altitude` — station elevation in metres (CF `standard_name = "altitude"`). **Optional**:
178
+ created only when a source supplies a non-null `'altitude'` value in the stations dict (a source
179
+ with none, e.g. ECan — or one whose altitude column is all-null — gets no such variable); NaN for
180
+ any individual station lacking a value. Stored **as-reported** (unpacked float32, **no declared
181
+ precision** — survey accuracy varies station-to-station and isn't characterised), and QC'd against
182
+ a universal plausibility band (`valid_min = -500`, `valid_max = 9000` m, persisted as attrs);
183
+ out-of-range values (incl `-9999`-type sentinels, ±inf) become missing with a warning, while a
184
+ non-coercible value raises (that's an adapter bug, not a sentinel).
185
+
186
+ Each station var carries a CF `long_name` (and `station_id`/`station_ref` a `comment`); these
187
+ back-fill onto pre-existing datasets on the next update run. Station metadata is **written once**,
188
+ when a station first appears — it is not revised on later merges (correcting it needs a rebuild).
189
+ Version notes: `station_ref` exists in datasets built by toolkit >= 0.1.2 (merging *new stations*
190
+ into an older dataset raises — rebuild it — while revise-only merges keep working); the CF attrs
191
+ and `station_altitude` land from toolkit >= 0.1.4.
169
192
 
170
193
  **The envlib metadata is the single source of truth for the cadence** — there is no `freq`
171
194
  parameter. `frequency_interval` is a closed envlib vocabulary; only *fixed* codes work here
@@ -189,8 +212,9 @@ axis widens back to midnight — normal numpy semantics, worth knowing as a read
189
212
 
190
213
  Two inputs recur:
191
214
 
192
- - **`stations`** — a dict `{ref: {'lon': float, 'lat': float, 'name': str}}`. From a pandas
193
- frame indexed by ref with those columns: `df.to_dict('index')`.
215
+ - **`stations`** — a dict `{ref: {'lon': float, 'lat': float, 'name': str[, 'altitude': float]}}`.
216
+ From a pandas frame indexed by ref with those columns: `df.to_dict('index')`. `altitude` is
217
+ optional (metres); include it and the `station_altitude` variable is created automatically.
194
218
  - **`series`** — a dict `{ref -> (times, values)}` of resampled tuples (the output of
195
219
  `resample_*` at the metadata's freq). Entries that are `None` or have `times.size == 0` are
196
220
  simply skipped.
@@ -7,7 +7,7 @@
7
7
  from envlib_ingest_base.resample import resample
8
8
  from envlib_ingest_base.tsortho import build_and_publish, build_local, merge_dataset, update_and_publish
9
9
 
10
- __version__ = '0.1.2'
10
+ __version__ = '0.1.4'
11
11
  __all__ = [
12
12
  'build_and_publish',
13
13
  'build_local',
@@ -3,8 +3,18 @@
3
3
  A ts_ortho dataset stores an orthogonal ``(point, time)`` layout: a geometry coordinate of
4
4
  shapely Points (one per station, order-free), a shared **dense fixed-step time axis at the
5
5
  cadence declared by ``meta.frequency_interval``**, one primary data variable named after
6
- ``meta.variable``, and a ``station_id`` (envlib's deterministic hash) + ``station_name``
7
- attribute variable per station.
6
+ ``meta.variable``, and per-station metadata as auxiliary ``(point,)`` variables — the
7
+ established nomenclature for station data in envlib/cfdb ts_ortho datasets:
8
+ ``station_id`` (envlib's deterministic geometry hash; carries the CF ``cf_role='timeseries_id'``
9
+ that marks it as the timeseries instance identifier), ``station_name``, and ``station_ref`` (the
10
+ SOURCE's native identifier = the stations-dict key, the stable join key back to the provider's
11
+ records) — each carrying CF ``long_name``/``comment`` attrs. ``station_altitude`` (metres, CF
12
+ ``standard_name='altitude'``, unpacked float32) is added when — and only when — a source supplies
13
+ a non-null ``'altitude'`` value in the stations dict; it is stored as-reported (no declared
14
+ precision — survey accuracy varies station-to-station and is not characterised) and QC'd against a
15
+ universal plausibility band (out-of-range values, incl -9999-type sentinels, become missing).
16
+ Further well-known fields join the same ``(point,)`` pattern. Station metadata is written once,
17
+ when a station first appears (not revised on later merges).
8
18
 
9
19
  **The envlib metadata is the single source of truth for the cadence** — there is no separate
10
20
  freq parameter. ``build_local`` reads ``meta.frequency_interval`` (a closed envlib controlled
@@ -18,8 +28,8 @@ by numpy to the axis unit (e.g. ``'...T06:00'`` on a daily axis widens back to m
18
28
 
19
29
  Two inputs recur:
20
30
 
21
- - ``stations``: a dict ``{ref: {'lon': float, 'lat': float, 'name': str}}`` (from a pandas
22
- frame: ``df.to_dict('index')``).
31
+ - ``stations``: a dict ``{ref: {'lon': float, 'lat': float, 'name': str[, 'altitude': float]}}``
32
+ (from a pandas frame: ``df.to_dict('index')``). ``altitude`` is optional (metres).
23
33
  - ``series``: a dict ``{ref -> (times, values)}`` of resampled tuples (the output of
24
34
  ``resample_*`` at the SAME freq the metadata declares): ascending interval-start
25
35
  ``datetime64`` times + ``float64`` values. An entry that is ``None`` or has
@@ -81,6 +91,54 @@ def _require_fixed_cfdb() -> None:
81
91
 
82
92
  STATION_ID_VAR = 'station_id'
83
93
  STATION_NAME_VAR = 'station_name'
94
+ STATION_REF_VAR = 'station_ref'
95
+ STATION_ALTITUDE_VAR = 'station_altitude'
96
+
97
+ # station_altitude plausibility band (metres): a UNIVERSAL physical range for a station's
98
+ # elevation — above every surface station on Earth (highest AWS ~8,810 m; Everest summit 8,849)
99
+ # down through the deepest dry-land depressions (Dead Sea shore ~-430 m). Numeric values outside
100
+ # it (incl ±inf, float32 overflow, and the classic -9999/-999 sentinels) are treated as MISSING,
101
+ # not real. Precision is deliberately NOT declared: a station's survey accuracy varies
102
+ # station-to-station, is rarely documented, and would be dishonest to assert — altitude is stored
103
+ # as-reported (unpacked float32), and the comment attr says so.
104
+ _ALTITUDE_MIN = -500.0
105
+ _ALTITUDE_MAX = 9000.0
106
+ _MAX_WARN_REFS = 10 # cap the station list shown in the out-of-range altitude warning
107
+
108
+ # CF attributes for the auxiliary station-metadata variables. cfdb already writes the global
109
+ # featureType='timeSeries' for ts_ortho; per CF discrete-sampling-geometry conventions (§9.5)
110
+ # exactly one variable carries cf_role to mark the timeseries instance identifier — station_id
111
+ # (envlib's canonical geometry-derived station identity). station_altitude is optional (created
112
+ # only when a source supplies it; see build_local), so its attrs apply only where the var exists.
113
+ _STATION_VAR_ATTRS = {
114
+ STATION_ID_VAR: {
115
+ 'long_name': 'envlib station identifier',
116
+ 'cf_role': 'timeseries_id',
117
+ 'comment': (
118
+ 'Deterministic hash of the station geometry (envlib.compute_station_id); envlib '
119
+ 'canonical station identity. Changes if the source corrects the coordinates.'
120
+ ),
121
+ },
122
+ STATION_NAME_VAR: {'long_name': 'station name'},
123
+ STATION_REF_VAR: {
124
+ 'long_name': 'source station reference identifier',
125
+ 'comment': (
126
+ "The data provider's own native station id (the source's site key); the stable "
127
+ 'join key back to the provider records.'
128
+ ),
129
+ },
130
+ STATION_ALTITUDE_VAR: {
131
+ 'long_name': 'station altitude',
132
+ 'standard_name': 'altitude',
133
+ 'units': 'm',
134
+ 'valid_min': _ALTITUDE_MIN,
135
+ 'valid_max': _ALTITUDE_MAX,
136
+ 'comment': (
137
+ 'Station elevation as reported by the source; survey method and precision vary between '
138
+ 'stations and are not characterised. Values outside the valid range are treated as missing.'
139
+ ),
140
+ },
141
+ }
84
142
  _DEFAULT_TIME_CHUNK = 25_000 # steps; see the chunk_shape default rationale in build_local
85
143
  # natural-unit ladder: the largest unit that divides the step becomes the stored coord unit
86
144
  _UNIT_US = (('D', 86_400_000_000), ('h', 3_600_000_000), ('m', 60_000_000), ('s', 1_000_000))
@@ -233,7 +291,54 @@ def _points_ids_names(stations: dict):
233
291
  points = [shapely.Point(float(d['lon']), float(d['lat'])) for d in stations.values()]
234
292
  ids = np.array([envlib.compute_station_id(p) for p in points], dtype=object)
235
293
  names = np.array([str(d['name']) for d in stations.values()], dtype=object)
236
- return points, ids, names
294
+ refs = np.array([str(r) for r in stations], dtype=object)
295
+ return points, ids, names, refs
296
+
297
+
298
+ def _altitudes(stations: dict) -> np.ndarray:
299
+ """Per-station altitude in metres (unpacked float32), NaN where a station lacks one; order
300
+ matches the dict. A missing/None/NaN value -> NaN. A numeric value outside the plausibility
301
+ band ``[_ALTITUDE_MIN, _ALTITUDE_MAX]`` (incl ±inf, float32 overflow, and sentinels like
302
+ -9999) is treated as MISSING -> NaN with a station-naming warning — the same "the declared
303
+ range doubles as QC" rule the data var uses. A NON-coercible / wrong-type value RAISES naming
304
+ the station: that is an adapter bug (clean floats/None are expected), not a sensor sentinel."""
305
+ out, rejected = [], []
306
+ for ref, d in stations.items():
307
+ v = d.get('altitude')
308
+ if v is None:
309
+ out.append(np.nan)
310
+ continue
311
+ try:
312
+ f = float(v)
313
+ except (TypeError, ValueError) as e:
314
+ msg = f'station {ref!r}: invalid altitude {v!r}'
315
+ raise ValueError(msg) from e
316
+ if np.isnan(f):
317
+ out.append(np.nan)
318
+ elif _ALTITUDE_MIN <= f <= _ALTITUDE_MAX:
319
+ out.append(f)
320
+ else: # sentinel / ±inf / float32 overflow -> missing (not real)
321
+ rejected.append(ref)
322
+ out.append(np.nan)
323
+ if rejected:
324
+ shown = rejected if len(rejected) <= _MAX_WARN_REFS else [*rejected[:_MAX_WARN_REFS], '...']
325
+ logger.warning(
326
+ 'altitude: %d station(s) with out-of-range altitude set to NaN (outside [%g, %g] m): %s',
327
+ len(rejected),
328
+ _ALTITUDE_MIN,
329
+ _ALTITUDE_MAX,
330
+ shown,
331
+ )
332
+ return np.array(out, dtype='float32')
333
+
334
+
335
+ def _apply_station_attrs(ds) -> None:
336
+ """Idempotently stamp the canonical CF attrs onto whatever station vars exist in ``ds``.
337
+ Unconditional ``update`` is safe: cfdb's attrs finalizer writes to the store only when the
338
+ attrs actually change, so re-running on every merge dirties nothing and re-uploads nothing."""
339
+ for var, attrs in _STATION_VAR_ATTRS.items():
340
+ if var in ds:
341
+ ds[var].attrs.update(attrs)
237
342
 
238
343
 
239
344
  def build_local(
@@ -255,7 +360,9 @@ def build_local(
255
360
 
256
361
  The axis cadence comes from ``meta.frequency_interval`` (fixed CV codes only); the time
257
362
  coordinate is stored in the cadence's natural unit with an explicit step.
258
- ``stations``: dict ``{ref: {'lon', 'lat', 'name'}}``; ``series``: ``{ref -> (times, values)}``.
363
+ ``stations``: dict ``{ref: {'lon', 'lat', 'name'[, 'altitude']}}`` (``altitude`` optional, metres —
364
+ the ``station_altitude`` var is created only if at least one station has it); ``series``:
365
+ ``{ref -> (times, values)}``.
259
366
  """
260
367
  _require_fixed_cfdb()
261
368
  step_us, unit = _freq_step(meta.frequency_interval)
@@ -277,7 +384,7 @@ def build_local(
277
384
  tmax = _floor_step(max(int(t.astype('int64').max()) for t, _ in non_empty.values()), step_us)
278
385
  times_us = np.arange(tmin, tmax + 1, step_us)
279
386
  data = _assemble(stations, non_empty, tmin, times_us.size, step_us)
280
- points, ids, names = _points_ids_names(stations)
387
+ points, ids, names, refs = _points_ids_names(stations)
281
388
 
282
389
  if chunk_shape is None:
283
390
  # ts_ortho default: point dim = 1 (ruling 2026-07-20). The dominant consumer read is
@@ -312,7 +419,21 @@ def build_local(
312
419
  sid[:] = ids
313
420
  snm = ds.create.data_var.generic(STATION_NAME_VAR, ('point',), dtype=dtypes.dtype('str'))
314
421
  snm[:] = names
315
-
422
+ # the SOURCE's native station identifier (the stations-dict key, e.g. an ECan site
423
+ # number) — the stable join key back to the provider's own records; station_id is
424
+ # geometry-derived and changes if the provider corrects coordinates
425
+ srf = ds.create.data_var.generic(STATION_REF_VAR, ('point',), dtype=dtypes.dtype('str'))
426
+ srf[:] = refs
427
+
428
+ # optional station altitude: create the var only when the source actually supplies it (a
429
+ # source with none, e.g. ECan, gets no empty var); NaN for any station that lacks a value.
430
+ # Created after ds['point'].append so the auto chunk_shape sees a non-empty coord.
431
+ alts = _altitudes(stations)
432
+ if bool((~np.isnan(alts)).any()):
433
+ salt = ds.create.data_var.generic(STATION_ALTITUDE_VAR, ('point',), dtype=dtypes.dtype('float32'))
434
+ salt[:] = alts
435
+
436
+ _apply_station_attrs(ds)
316
437
  ds.attrs.update(attrs)
317
438
  return str(path)
318
439
 
@@ -325,6 +446,9 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
325
446
  step). Appends new stations and new steps (in the coord's stored dtype), then does a single
326
447
  contiguous read-modify-write over the affected time block, keeping existing values where
327
448
  the incoming value is NaN. Idempotent for a fixed input window.
449
+
450
+ Requires a writable dataset: the station-attr heal runs on every call (even an empty window,
451
+ before the early return), so calling this on a read-only dataset raises rather than no-opping.
328
452
  """
329
453
  _require_fixed_cfdb()
330
454
  dsattrs = ds.attrs.data
@@ -335,6 +459,10 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
335
459
  step_us, _unit = _freq_step(code)
336
460
  _check_phase(dsattrs.get('envlib_utc_offset'), code)
337
461
 
462
+ # back-fill the canonical station-var CF attrs onto pre-existing datasets (idempotent, attrs
463
+ # only). Done here — before the empty-window early return — so even quiet update runs heal.
464
+ _apply_station_attrs(ds)
465
+
338
466
  non_empty = _non_empty(series)
339
467
  if not non_empty:
340
468
  return {
@@ -371,7 +499,12 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
371
499
  # --- new stations (only those that actually have data this window; `stations` may be the full
372
500
  # discovery dict, but a station with no incoming data must never be added) ---
373
501
  active = list(non_empty)
374
- points, ids, names = _points_ids_names({r: stations[r] for r in active})
502
+ sub = {r: stations[r] for r in active}
503
+ points, ids, names, refs = _points_ids_names(sub)
504
+ # validated up front, BEFORE any row mutation: a junk/non-finite altitude then raises
505
+ # pre-append (never leaving a half-written station row), and the check is uniform — merge
506
+ # is as loud on bad altitude as build, regardless of new-vs-existing or var presence.
507
+ alts = _altitudes(sub)
375
508
  id_to_row = {sid: i for i, sid in enumerate(cur_ids)}
376
509
  new_mask = np.array([sid not in id_to_row for sid in ids])
377
510
  n_new = int(new_mask.sum())
@@ -380,8 +513,20 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
380
513
  base = len(cur_ids)
381
514
  ds[STATION_ID_VAR][base : base + n_new] = ids[new_mask]
382
515
  ds[STATION_NAME_VAR][base : base + n_new] = names[new_mask]
516
+ ds[STATION_REF_VAR][base : base + n_new] = refs[new_mask]
517
+ if STATION_ALTITUDE_VAR in ds:
518
+ ds[STATION_ALTITUDE_VAR][base : base + n_new] = alts[new_mask]
383
519
  for k, sid in enumerate(ids[new_mask]):
384
520
  id_to_row[sid] = base + k
521
+ # incoming altitude with no var to hold it = silent omission until a rebuild. Warn once per
522
+ # merge, independent of n_new (a source may start supplying altitude for EXISTING stations).
523
+ # Station metadata is write-once: existing rows' altitude is not revised here (as with name/ref).
524
+ if STATION_ALTITUDE_VAR not in ds and bool((~np.isnan(alts)).any()):
525
+ logger.warning(
526
+ 'merge %s: incoming stations carry altitude but the dataset has no %s var; rebuild to add it',
527
+ variable,
528
+ STATION_ALTITUDE_VAR,
529
+ )
385
530
 
386
531
  # --- new steps (extend the dense axis, in the coord's own stored dtype) ---
387
532
  inc_min = _floor_step(min(int(t.astype('int64').min()) for t, _ in non_empty.values()), step_us)