envlib-ingest-base 0.1.4__tar.gz → 0.2.0__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,3 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: envlib-ingest-base
3
+ Version: 0.2.0
4
+ Summary: Shared toolkit for envlib data-ingest repos: source-agnostic time-series resampling and ts_ortho (station) dataset build + idempotent commons update.
5
+ Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
+ Author-email: mullenkamp <mullenkamp1@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: cfdb>=0.9.4
12
+ Requires-Dist: ebooklet>=0.10.3
13
+ Requires-Dist: envlib>=0.1.3
14
+ Requires-Dist: numpy
15
+ Requires-Dist: sentry-sdk
16
+ Requires-Dist: shapely>=2.0
17
+ Description-Content-Type: text/markdown
18
+
1
19
  # envlib-ingest-base
2
20
 
3
21
  Shared, tested toolkit for the envlib data-ingest family — and the Docker base image that carries
@@ -236,7 +254,7 @@ meta = envlib.Metadata(
236
254
  )
237
255
  ```
238
256
 
239
- ### `build_local(path, meta, stations, series, *, variable, units, precision, min_value, max_value, chunk_shape=None, standard_name=None, extra_var_attrs=None)`
257
+ ### `build_local(path, meta, stations, series, *, variable, units, precision, min_value, max_value, chunk_shape=None, standard_name=None, extra_var_attrs=None, ancillary=None)`
240
258
 
241
259
  Create a fresh local ts_ortho cfdb at the cadence of `meta.frequency_interval`. **Requires
242
260
  cfdb >= 0.9.4** (older versions fabricate values when the packed encoder meets NaN or
@@ -262,6 +280,37 @@ from envlib import Catalogue
262
280
  Catalogue(remotes=[]).validate('flow.cfdb') # {'metadata', 'dataset_version_id', 'state', ...}
263
281
  ```
264
282
 
283
+ #### Ancillary variables — per-timestep metadata *about* each value
284
+
285
+ `ancillary` declares companion `(point, time)` planes carrying information about each value rather
286
+ than more values — a per-observation quality grade on a quality-controlled product being the
287
+ motivating case. Their data rides along in each series entry as a third tuple slot:
288
+
289
+ ```python
290
+ QC = {'quality_code': {'units': '1', 'precision': 0, 'min_value': 0, 'max_value': 1000,
291
+ 'attrs': {'standard_name': 'quality_flag',
292
+ 'long_name': 'NEMS quality code'}}}
293
+
294
+ series = {'68801': (times, values, {'quality_code': codes})} # extras paired 1:1 with values
295
+
296
+ build_local('flow.cfdb', meta, stations, series, variable='streamflow', units='m^3/s',
297
+ precision=4, min_value=0, max_value=20_000, ancillary=QC)
298
+ ```
299
+
300
+ The pairing is **positional and structural** — same length, same timestamps — so a value and its
301
+ grade cannot desynchronize; a ragged extras array raises before anything is written. The primary
302
+ variable gets a CF `ancillary_variables` attr naming the companions, and that attr is the roster
303
+ `merge_dataset` reads back: the stored dataset, never a caller argument, is the source of truth on
304
+ update. Incoming extras naming an undeclared variable **raise** — silently dropping per-timestep
305
+ quality data is unrecoverable without re-running the whole extraction.
306
+
307
+ Ancillaries are stored as **packed floats, not integers**: the entire merge/QC machinery is
308
+ NaN-based, and an integer plane cannot express "no incoming code" at all. `precision=0` with bounds
309
+ `0–1000` gives uint16 storage and a reserved fill that decodes to NaN. Their `valid_min`/`valid_max`
310
+ attrs are load-bearing rather than decorative — the encoder rejects below-min and non-finite values
311
+ but **passes above-max straight through**, so without them a merge falls back to the far wider
312
+ encodable range and a junk high code would persist silently.
313
+
265
314
  ### `merge_dataset(ds, stations, series, *, variable)`
266
315
 
267
316
  Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
@@ -279,12 +328,30 @@ from envlib_ingest_base import merge_dataset
279
328
  with open_dataset('flow.cfdb', flag='w') as ds:
280
329
  merge_dataset(ds, stations, series_recent, variable='streamflow')
281
330
  # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 72, 'gap_steps': 0,
282
- # 'qc_rejected': 0, 'dropped_before_axis': 0}
331
+ # 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
283
332
  # gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
284
333
  # so refetching a wider window and re-merging heals them
285
334
  # qc_rejected: values outside the encodable range set to NaN by the min/max QC
335
+ # anc_qc_rejected: ancillary values outside their own declared bounds, set to NaN
286
336
  ```
287
337
 
338
+ When the dataset carries ancillary variables, the write is governed by a single **union mask**: a
339
+ slot counts as "supplied by this run" when the primary *or* any ancillary is non-NaN there, and
340
+ every plane is then taken from that run. So a stored (value, grade) pair always originates from one
341
+ run — a later run can never leave its value beside an earlier run's grade — and a grade whose whole
342
+ job is to explain an absence (NEMS 100, "missing record") is representable rather than dropped. A
343
+ value rejected by the primary QC bounds takes its grade with it.
344
+
345
+ Note the deliberate asymmetry: an all-NaN incoming slot leaves the stored pair untouched. That is
346
+ what protects an offline station's history, and it is also why this merge **cannot express a
347
+ retraction** — a source that revises a reading *to* missing has no way to say so. That needs an
348
+ explicit deletion path the toolkit does not currently have.
349
+
350
+ The primary and each ancillary are separate block writes, so an interruption between them can leave
351
+ new values beside old grades for one block. Re-running heals it, but only if a later window actually
352
+ covers the crashed block — the horizon guard forbids reaching arbitrarily far back, so a crash
353
+ outside every later window needs a supervised re-merge over that range.
354
+
288
355
  ### `build_and_publish(...)` / `update_and_publish(...)` — publish to the commons
289
356
 
290
357
  Wrap the above with `envlib.Catalogue` + the ebooklet member/RCG connections.
@@ -1,20 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: envlib-ingest-base
3
- Version: 0.1.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
- Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
- Author-email: mullenkamp <mullenkamp1@gmail.com>
7
- License-Expression: Apache-2.0
8
- License-File: LICENSE
9
- Classifier: Programming Language :: Python :: 3 :: Only
10
- Requires-Python: >=3.10
11
- Requires-Dist: cfdb>=0.9.4
12
- Requires-Dist: ebooklet>=0.10.2
13
- Requires-Dist: envlib>=0.1.2
14
- Requires-Dist: numpy
15
- Requires-Dist: shapely>=2.0
16
- Description-Content-Type: text/markdown
17
-
18
1
  # envlib-ingest-base
19
2
 
20
3
  Shared, tested toolkit for the envlib data-ingest family — and the Docker base image that carries
@@ -253,7 +236,7 @@ meta = envlib.Metadata(
253
236
  )
254
237
  ```
255
238
 
256
- ### `build_local(path, meta, stations, series, *, variable, units, precision, min_value, max_value, chunk_shape=None, standard_name=None, extra_var_attrs=None)`
239
+ ### `build_local(path, meta, stations, series, *, variable, units, precision, min_value, max_value, chunk_shape=None, standard_name=None, extra_var_attrs=None, ancillary=None)`
257
240
 
258
241
  Create a fresh local ts_ortho cfdb at the cadence of `meta.frequency_interval`. **Requires
259
242
  cfdb >= 0.9.4** (older versions fabricate values when the packed encoder meets NaN or
@@ -279,6 +262,37 @@ from envlib import Catalogue
279
262
  Catalogue(remotes=[]).validate('flow.cfdb') # {'metadata', 'dataset_version_id', 'state', ...}
280
263
  ```
281
264
 
265
+ #### Ancillary variables — per-timestep metadata *about* each value
266
+
267
+ `ancillary` declares companion `(point, time)` planes carrying information about each value rather
268
+ than more values — a per-observation quality grade on a quality-controlled product being the
269
+ motivating case. Their data rides along in each series entry as a third tuple slot:
270
+
271
+ ```python
272
+ QC = {'quality_code': {'units': '1', 'precision': 0, 'min_value': 0, 'max_value': 1000,
273
+ 'attrs': {'standard_name': 'quality_flag',
274
+ 'long_name': 'NEMS quality code'}}}
275
+
276
+ series = {'68801': (times, values, {'quality_code': codes})} # extras paired 1:1 with values
277
+
278
+ build_local('flow.cfdb', meta, stations, series, variable='streamflow', units='m^3/s',
279
+ precision=4, min_value=0, max_value=20_000, ancillary=QC)
280
+ ```
281
+
282
+ The pairing is **positional and structural** — same length, same timestamps — so a value and its
283
+ grade cannot desynchronize; a ragged extras array raises before anything is written. The primary
284
+ variable gets a CF `ancillary_variables` attr naming the companions, and that attr is the roster
285
+ `merge_dataset` reads back: the stored dataset, never a caller argument, is the source of truth on
286
+ update. Incoming extras naming an undeclared variable **raise** — silently dropping per-timestep
287
+ quality data is unrecoverable without re-running the whole extraction.
288
+
289
+ Ancillaries are stored as **packed floats, not integers**: the entire merge/QC machinery is
290
+ NaN-based, and an integer plane cannot express "no incoming code" at all. `precision=0` with bounds
291
+ `0–1000` gives uint16 storage and a reserved fill that decodes to NaN. Their `valid_min`/`valid_max`
292
+ attrs are load-bearing rather than decorative — the encoder rejects below-min and non-finite values
293
+ but **passes above-max straight through**, so without them a merge falls back to the far wider
294
+ encodable range and a junk high code would persist silently.
295
+
282
296
  ### `merge_dataset(ds, stations, series, *, variable)`
283
297
 
284
298
  Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
@@ -296,12 +310,30 @@ from envlib_ingest_base import merge_dataset
296
310
  with open_dataset('flow.cfdb', flag='w') as ds:
297
311
  merge_dataset(ds, stations, series_recent, variable='streamflow')
298
312
  # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 72, 'gap_steps': 0,
299
- # 'qc_rejected': 0, 'dropped_before_axis': 0}
313
+ # 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
300
314
  # gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
301
315
  # so refetching a wider window and re-merging heals them
302
316
  # qc_rejected: values outside the encodable range set to NaN by the min/max QC
317
+ # anc_qc_rejected: ancillary values outside their own declared bounds, set to NaN
303
318
  ```
304
319
 
320
+ When the dataset carries ancillary variables, the write is governed by a single **union mask**: a
321
+ slot counts as "supplied by this run" when the primary *or* any ancillary is non-NaN there, and
322
+ every plane is then taken from that run. So a stored (value, grade) pair always originates from one
323
+ run — a later run can never leave its value beside an earlier run's grade — and a grade whose whole
324
+ job is to explain an absence (NEMS 100, "missing record") is representable rather than dropped. A
325
+ value rejected by the primary QC bounds takes its grade with it.
326
+
327
+ Note the deliberate asymmetry: an all-NaN incoming slot leaves the stored pair untouched. That is
328
+ what protects an offline station's history, and it is also why this merge **cannot express a
329
+ retraction** — a source that revises a reading *to* missing has no way to say so. That needs an
330
+ explicit deletion path the toolkit does not currently have.
331
+
332
+ The primary and each ancillary are separate block writes, so an interruption between them can leave
333
+ new values beside old grades for one block. Re-running heals it, but only if a later window actually
334
+ covers the crashed block — the horizon guard forbids reaching arbitrarily far back, so a crash
335
+ outside every later window needs a supervised re-merge over that range.
336
+
305
337
  ### `build_and_publish(...)` / `update_and_publish(...)` — publish to the commons
306
338
 
307
339
  Wrap the above with `envlib.Catalogue` + the ebooklet member/RCG connections.
@@ -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.4'
10
+ __version__ = '0.2.0'
11
11
  __all__ = [
12
12
  'build_and_publish',
13
13
  'build_local',
@@ -34,6 +34,17 @@ Two inputs recur:
34
34
  ``resample_*`` at the SAME freq the metadata declares): ascending interval-start
35
35
  ``datetime64`` times + ``float64`` values. An entry that is ``None`` or has
36
36
  ``times.size == 0`` is simply skipped — never test the tuple itself with ``len()``/truthiness.
37
+ An entry may instead be the 3-tuple ``(times, values, extras)``, where ``extras`` is
38
+ ``{ancillary_name: array}`` positionally paired with ``values`` — see below.
39
+
40
+ Optionally a dataset carries **ancillary variables**: companion ``(point, time)`` planes holding
41
+ per-timestep metadata about each value, declared via ``build_local(..., ancillary=...)`` and named
42
+ on the primary by the CF ``ancillary_variables`` attr. The motivating case is a per-observation
43
+ quality grade (e.g. NEMS) on a quality-controlled product. They are stored as packed floats rather
44
+ than integers because the whole merge/QC machinery is NaN-based, and they are governed on update by
45
+ a single union mask so a stored (value, grade) pair always comes from one run (see
46
+ ``merge_dataset``). There is deliberately NO deletion path: the merge cannot express "this reading
47
+ is now missing", which is what protects an offline station's history from being erased.
37
48
 
38
49
  Two guards enforce a strict **epoch-anchored phase contract** (phase-anchored binning — e.g. a
39
50
  local-midnight or 9am-rain-day daily product — is deliberately unsupported until the resampler
@@ -140,6 +151,8 @@ _STATION_VAR_ATTRS = {
140
151
  },
141
152
  }
142
153
  _DEFAULT_TIME_CHUNK = 25_000 # steps; see the chunk_shape default rationale in build_local
154
+ # a series entry is (times, values) or (times, values, extras) — the 3rd slot carries ancillary data
155
+ _SERIES_WITH_EXTRAS = 3
143
156
  # natural-unit ladder: the largest unit that divides the step becomes the stored coord unit
144
157
  _UNIT_US = (('D', 86_400_000_000), ('h', 3_600_000_000), ('m', 60_000_000), ('s', 1_000_000))
145
158
 
@@ -179,7 +192,7 @@ def _step_index(times, t0_us: int, step_us: int) -> np.ndarray:
179
192
 
180
193
  def _check_aligned(non_empty: dict, step_us: int, code) -> None:
181
194
  """Every incoming timestamp must sit on the epoch-anchored step grid (module docstring)."""
182
- for ref, (t, _v) in non_empty.items():
195
+ for ref, (t, *_rest) in non_empty.items():
183
196
  res = t.astype('int64') % step_us
184
197
  bad = np.nonzero(res)[0]
185
198
  if bad.size:
@@ -222,20 +235,37 @@ def _encodable_range(dt) -> tuple:
222
235
  return (1 / factor) + dt.offset, (info.max / factor) + dt.offset
223
236
 
224
237
 
225
- def _qc_filter(non_empty: dict, lo, hi) -> tuple[dict, int]:
238
+ def _qc_filter(non_empty: dict, lo, hi, anc_bounds: dict | None = None) -> tuple[dict, int, int]:
226
239
  """min/max QC (ruling 2026-07-17): the DECLARED min/max double as plausibility bounds,
227
240
  so values outside them — including ±inf — become NaN (missing). Runs BEFORE the merge
228
- combine, so a rejected incoming value can never displace a stored valid one."""
229
- if lo is None:
230
- return non_empty, 0
231
- out, n = {}, 0
232
- for ref, (t, v) in non_empty.items():
233
- bad = ~np.isnan(v) & ((v < lo) | (v > hi))
241
+ combine, so a rejected incoming value can never displace a stored valid one.
242
+
243
+ Ancillary planes are filtered against their OWN declared bounds, and a value rejected by
244
+ the PRIMARY filter takes its ancillary entries with it: a quality grade attached to a
245
+ measurement we refused to store describes nothing.
246
+ """
247
+ anc_bounds = anc_bounds or {}
248
+ out, n, n_anc = {}, 0, 0
249
+ for ref, (t, v, ex) in non_empty.items():
250
+ if lo is None:
251
+ bad = np.zeros(v.shape, dtype=bool)
252
+ else:
253
+ bad = ~np.isnan(v) & ((v < lo) | (v > hi))
234
254
  nbad = int(bad.sum())
235
255
  vv = np.where(bad, np.nan, v) if nbad else v
236
256
  n += nbad
237
- out[ref] = (t, vv)
238
- return out, n
257
+ ee = {}
258
+ for k, a in ex.items():
259
+ b = anc_bounds.get(k)
260
+ if b is None or b[0] is None:
261
+ abad = np.zeros(a.shape, dtype=bool)
262
+ else:
263
+ abad = ~np.isnan(a) & ((a < b[0]) | (a > b[1]))
264
+ n_anc += int(abad.sum())
265
+ drop = abad | bad
266
+ ee[k] = np.where(drop, np.nan, a) if drop.any() else a
267
+ out[ref] = (t, vv, ee)
268
+ return out, n, n_anc
239
269
 
240
270
 
241
271
  def _qc_bounds(dv) -> tuple:
@@ -261,29 +291,77 @@ def _nan_safe(data: np.ndarray, dt) -> np.ndarray:
261
291
 
262
292
 
263
293
  def _non_empty(series: dict) -> dict:
264
- """Entries that actually carry data, normalized to (datetime64[us] times, float64 values)."""
294
+ """Entries that actually carry data, normalized to ``(times, values, extras)``.
295
+
296
+ Accepts both the 2-tuple ``(times, values)`` and the 3-tuple ``(times, values, extras)``
297
+ where ``extras`` is ``{ancillary_name: array}`` **positionally paired with values** — same
298
+ length, same timestamps. The pairing is structural precisely so a value and its ancillary
299
+ entry can never desynchronize; a ragged extras array is a producer bug and raises here,
300
+ before anything is written.
301
+ """
265
302
  out = {}
266
303
  for ref, s in series.items():
267
304
  if s is None:
268
305
  continue
269
- t, v = s
306
+ if len(s) == _SERIES_WITH_EXTRAS:
307
+ t, v, extras = s
308
+ else:
309
+ t, v = s
310
+ extras = None
270
311
  t = np.asarray(t, dtype='datetime64[us]')
312
+ v = np.asarray(v, dtype='float64')
313
+ ex = {}
314
+ for k, arr in (extras or {}).items():
315
+ a = np.asarray(arr, dtype='float64')
316
+ if a.shape != v.shape:
317
+ msg = (
318
+ f'station {ref!r}: ancillary {k!r} has shape {a.shape} but values have '
319
+ f'{v.shape} — extras must be positionally paired with values'
320
+ )
321
+ raise ValueError(msg)
322
+ ex[k] = a
271
323
  if t.size:
272
- out[ref] = (t, np.asarray(v, dtype='float64'))
324
+ out[ref] = (t, v, ex)
273
325
  return out
274
326
 
275
327
 
276
- def _assemble(stations: dict, series: dict, t0_us: int, n_times: int, step_us: int) -> np.ndarray:
277
- """Dense (n_point, n_time) float array; NaN where a station has no value at a step."""
328
+ def _check_extras(non_empty: dict, roster) -> None:
329
+ """Incoming ancillary data naming a variable the dataset does not declare RAISES.
330
+
331
+ Deliberately louder than the altitude warn-and-continue: silently dropping per-timestep
332
+ quality information from a QC'd product is data loss with no later recovery path (there is
333
+ no rebuild that puts it back without re-running the whole extraction).
334
+ """
335
+ known = set(roster)
336
+ for ref, (_t, _v, ex) in non_empty.items():
337
+ unknown = sorted(set(ex) - known)
338
+ if unknown:
339
+ msg = (
340
+ f'station {ref!r}: ancillary {unknown} not declared by this dataset '
341
+ f'(declared: {sorted(known)})'
342
+ )
343
+ raise ValueError(msg)
344
+
345
+
346
+ def _assemble(stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, plane=None) -> np.ndarray:
347
+ """Dense (n_point, n_time) float array; NaN where a station has no value at a step.
348
+
349
+ ``plane=None`` assembles the primary values; a string assembles that named ancillary
350
+ (stations lacking it stay NaN), so both planes share this one code path and land on
351
+ identical geometry.
352
+ """
278
353
  data = np.full((len(stations), n_times), np.nan, dtype='float64')
279
354
  for i, ref in enumerate(stations):
280
355
  s = series.get(ref)
281
356
  if s is None:
282
357
  continue
283
- t, v = s
358
+ t, v, ex = s
359
+ arr = v if plane is None else ex.get(plane)
360
+ if arr is None:
361
+ continue
284
362
  col = _step_index(t, t0_us, step_us)
285
363
  ok = (col >= 0) & (col < n_times)
286
- data[i, col[ok]] = v[ok]
364
+ data[i, col[ok]] = arr[ok]
287
365
  return data
288
366
 
289
367
 
@@ -355,6 +433,7 @@ def build_local(
355
433
  chunk_shape=None,
356
434
  standard_name=None,
357
435
  extra_var_attrs=None,
436
+ ancillary=None,
358
437
  ):
359
438
  """Create a fresh local ts_ortho cfdb from all stations + their resampled series.
360
439
 
@@ -362,26 +441,51 @@ def build_local(
362
441
  coordinate is stored in the cadence's natural unit with an explicit step.
363
442
  ``stations``: dict ``{ref: {'lon', 'lat', 'name'[, 'altitude']}}`` (``altitude`` optional, metres —
364
443
  the ``station_altitude`` var is created only if at least one station has it); ``series``:
365
- ``{ref -> (times, values)}``.
444
+ ``{ref -> (times, values)}`` or ``{ref -> (times, values, extras)}``.
445
+
446
+ ``ancillary`` declares optional companion ``(point, time)`` variables carrying per-timestep
447
+ metadata about each value — a NEMS/quality grade being the motivating case::
448
+
449
+ ancillary={'quality_code': {'units': '1', 'precision': 0,
450
+ 'min_value': 0, 'max_value': 1000,
451
+ 'attrs': {'standard_name': 'quality_flag', ...}}}
452
+
453
+ Their data arrives in each series entry's ``extras`` dict. The primary variable gets a CF
454
+ ``ancillary_variables`` attr naming them, which is also the roster ``merge_dataset`` reads
455
+ back — the stored dataset, not a caller argument, is the single source of truth on update.
456
+
457
+ Each ancillary is stored as a PACKED FLOAT (not an integer dtype): the whole merge/QC
458
+ machinery is NaN-based, and an integer plane cannot express "no incoming code" at all.
459
+ ``valid_min``/``valid_max`` are written from the declared bounds and are load-bearing, not
460
+ decorative — the encoder rejects below-min and non-finite but passes ABOVE-max values
461
+ straight through, so without those attrs a merge falls back to the far wider encodable
462
+ range and a junk high code would persist silently.
366
463
  """
367
464
  _require_fixed_cfdb()
368
465
  step_us, unit = _freq_step(meta.frequency_interval)
369
466
  attrs = meta.to_dict()
370
467
  _check_phase(attrs.get('envlib_utc_offset'), meta.frequency_interval)
468
+ ancillary = ancillary or {}
371
469
  non_empty = _non_empty(series)
372
470
  if not non_empty:
373
471
  msg = 'no series data to build from'
374
472
  raise ValueError(msg)
375
473
  _check_refs(non_empty, stations)
474
+ _check_extras(non_empty, ancillary)
376
475
  _check_aligned(non_empty, step_us, meta.frequency_interval)
377
476
 
378
477
  dt = dtypes.dtype('float32', precision=precision, min_value=min_value, max_value=max_value)
379
- non_empty, n_qc = _qc_filter(non_empty, float(min_value), float(max_value))
478
+ anc_bounds = {k: (float(s['min_value']), float(s['max_value'])) for k, s in ancillary.items()}
479
+ non_empty, n_qc, n_anc_qc = _qc_filter(non_empty, float(min_value), float(max_value), anc_bounds)
380
480
  if n_qc:
381
481
  logger.warning('build %s: %d value(s) outside [%s, %s] set to NaN (QC)', variable, n_qc, min_value, max_value)
482
+ if n_anc_qc:
483
+ logger.warning(
484
+ 'build %s: %d ancillary value(s) outside their declared bounds set to NaN (QC)', variable, n_anc_qc
485
+ )
382
486
 
383
- tmin = _floor_step(min(int(t.astype('int64').min()) for t, _ in non_empty.values()), step_us)
384
- tmax = _floor_step(max(int(t.astype('int64').max()) for t, _ in non_empty.values()), step_us)
487
+ tmin = _floor_step(min(int(t.astype('int64').min()) for t, *_ in non_empty.values()), step_us)
488
+ tmax = _floor_step(max(int(t.astype('int64').max()) for t, *_ in non_empty.values()), step_us)
385
489
  times_us = np.arange(tmin, tmax + 1, step_us)
386
490
  data = _assemble(stations, non_empty, tmin, times_us.size, step_us)
387
491
  points, ids, names, refs = _points_ids_names(stations)
@@ -413,8 +517,30 @@ def build_local(
413
517
  dv.attrs['standard_name'] = standard_name
414
518
  if extra_var_attrs:
415
519
  dv.attrs.update(extra_var_attrs)
520
+ # CF: name the companion variables on the primary. This attr is also the roster
521
+ # merge_dataset reads back, so the stored dataset stays the source of truth on update.
522
+ if ancillary:
523
+ dv.attrs['ancillary_variables'] = ' '.join(ancillary)
416
524
  dv[:] = _nan_safe(data, dt)
417
525
 
526
+ for aname, spec in ancillary.items():
527
+ adt = dtypes.dtype(
528
+ 'float32',
529
+ precision=spec['precision'],
530
+ min_value=spec['min_value'],
531
+ max_value=spec['max_value'],
532
+ )
533
+ av = ds.create.data_var.generic(aname, ('point', 'time'), dtype=adt, chunk_shape=chunk_shape)
534
+ av.attrs['units'] = spec.get('units', '1')
535
+ if spec.get('attrs'):
536
+ av.attrs.update(spec['attrs'])
537
+ # written LAST so a caller-supplied attrs dict can never weaken the QC bounds
538
+ av.attrs['valid_min'] = float(spec['min_value'])
539
+ av.attrs['valid_max'] = float(spec['max_value'])
540
+ av[:] = _nan_safe(
541
+ _assemble(stations, non_empty, tmin, times_us.size, step_us, plane=aname), adt
542
+ )
543
+
418
544
  sid = ds.create.data_var.generic(STATION_ID_VAR, ('point',), dtype=dtypes.dtype('str'))
419
545
  sid[:] = ids
420
546
  snm = ds.create.data_var.generic(STATION_NAME_VAR, ('point',), dtype=dtypes.dtype('str'))
@@ -449,6 +575,25 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
449
575
 
450
576
  Requires a writable dataset: the station-attr heal runs on every call (even an empty window,
451
577
  before the early return), so calling this on a read-only dataset raises rather than no-opping.
578
+
579
+ **Ancillary variables.** The roster is read from the primary's ``ancillary_variables`` attr
580
+ (never a caller argument), and the write is governed by a single UNION mask: a slot counts as
581
+ "supplied by this run" when the primary OR any ancillary is non-NaN there, and every plane is
582
+ then taken from that run. Two properties follow. A stored (value, code) pair always originates
583
+ from one run — a later run can never leave its value sitting beside an earlier run's grade. And
584
+ a grade can exist without a value, so a code whose entire job is to explain an absence (NEMS
585
+ 100, "missing record") is representable rather than silently dropped.
586
+
587
+ Note the deliberate asymmetry with deletion: an all-NaN incoming slot leaves the stored pair
588
+ untouched, which is what stops a briefly-offline station from erasing good history — and is
589
+ also why this merge cannot express a genuine retraction. A source that revises a reading *to*
590
+ missing has no way to say so; that needs an explicit deletion path this toolkit does not have.
591
+
592
+ **Crash window.** The primary and each ancillary are separate block writes, so an interruption
593
+ between them can leave new values beside old grades for one block. Re-running heals it — but
594
+ only if a subsequent window actually covers the crashed block; the horizon guard forbids
595
+ reaching arbitrarily far back, so a crash outside every later window needs a supervised
596
+ re-merge over that range.
452
597
  """
453
598
  _require_fixed_cfdb()
454
599
  dsattrs = ds.attrs.data
@@ -471,16 +616,25 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
471
616
  'written_block': 0,
472
617
  'gap_steps': 0,
473
618
  'qc_rejected': 0,
619
+ 'anc_qc_rejected': 0,
474
620
  'dropped_before_axis': 0,
475
621
  }
476
622
  _check_refs(non_empty, stations)
477
623
  _check_aligned(non_empty, step_us, code)
478
624
 
479
625
  dv = ds[variable]
626
+ # the ancillary roster comes from the STORED dataset, never from a caller argument
627
+ anc_names = [n for n in str(dv.attrs.data.get('ancillary_variables', '')).split() if n in ds]
628
+ anc_vars = {n: ds[n] for n in anc_names}
629
+ _check_extras(non_empty, anc_names)
630
+
480
631
  lo, hi = _qc_bounds(dv)
481
- non_empty, n_qc = _qc_filter(non_empty, lo, hi)
632
+ anc_bounds = {n: _qc_bounds(av) for n, av in anc_vars.items()}
633
+ non_empty, n_qc, n_anc_qc = _qc_filter(non_empty, lo, hi, anc_bounds)
482
634
  if n_qc:
483
635
  logger.warning('merge %s: %d value(s) outside [%s, %s] set to NaN (min/max QC)', variable, n_qc, lo, hi)
636
+ if n_anc_qc:
637
+ logger.warning('merge %s: %d ancillary value(s) outside declared bounds set to NaN (QC)', variable, n_anc_qc)
484
638
 
485
639
  cur_ids = list(ds[STATION_ID_VAR].data)
486
640
  tdata = np.asarray(ds['time'].data)
@@ -529,8 +683,8 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
529
683
  )
530
684
 
531
685
  # --- new steps (extend the dense axis, in the coord's own stored dtype) ---
532
- inc_min = _floor_step(min(int(t.astype('int64').min()) for t, _ in non_empty.values()), step_us)
533
- inc_max = _floor_step(max(int(t.astype('int64').max()) for t, _ in non_empty.values()), step_us)
686
+ inc_min = _floor_step(min(int(t.astype('int64').min()) for t, *_ in non_empty.values()), step_us)
687
+ inc_max = _floor_step(max(int(t.astype('int64').max()) for t, *_ in non_empty.values()), step_us)
534
688
  cur_max = int(cur_times[-1])
535
689
  # steps between the stored axis end and the incoming window start = a hole this window
536
690
  # cannot fill (pipeline downtime). The extension below NaN-fills it; report it so the
@@ -551,8 +705,10 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
551
705
  width = w_hi - w_lo + 1
552
706
  existing = np.asarray(dv[:, w_lo : w_hi + 1].data, dtype='float64') # (n_point_total, width)
553
707
  incoming = np.full_like(existing, np.nan)
708
+ existing_a = {n: np.asarray(anc_vars[n][:, w_lo : w_hi + 1].data, dtype='float64') for n in anc_names}
709
+ incoming_a = {n: np.full_like(existing, np.nan) for n in anc_names}
554
710
  n_before = 0
555
- for ref, (t, v) in non_empty.items():
711
+ for ref, (t, v, ex) in non_empty.items():
556
712
  d = stations[ref]
557
713
  sid = envlib.compute_station_id(shapely.Point(float(d['lon']), float(d['lat'])))
558
714
  row = id_to_row[sid]
@@ -560,16 +716,31 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
560
716
  ok = (col >= 0) & (col < width)
561
717
  n_before += int((col < 0).sum()) # window straddles the axis start: pre-axis values
562
718
  incoming[row, col[ok]] = v[ok]
719
+ for n in anc_names:
720
+ a = ex.get(n)
721
+ if a is not None:
722
+ incoming_a[n][row, col[ok]] = a[ok]
563
723
  if n_before:
564
724
  logger.warning('merge %s: %d incoming value(s) predate the axis start and were dropped', variable, n_before)
565
- merged = np.where(np.isnan(incoming), existing, incoming)
725
+
726
+ # UNION mask: a slot is "supplied by this run" if the primary OR any ancillary has data
727
+ # there. One mask drives every plane, so a stored (value, code) pair can never be assembled
728
+ # from two different runs — and a code that exists to explain an absent value survives.
729
+ mask = ~np.isnan(incoming)
730
+ for n in anc_names:
731
+ mask |= ~np.isnan(incoming_a[n])
732
+ merged = np.where(mask, incoming, existing)
566
733
  dv[:, w_lo : w_hi + 1] = _nan_safe(merged, dv.dtype)
734
+ for n in anc_names:
735
+ merged_a = np.where(mask, incoming_a[n], existing_a[n])
736
+ anc_vars[n][:, w_lo : w_hi + 1] = _nan_safe(merged_a, anc_vars[n].dtype)
567
737
  return {
568
738
  'new_stations': n_new,
569
739
  'new_steps': int(n_new_steps),
570
740
  'written_block': int(width),
571
741
  'gap_steps': int(gap_steps),
572
742
  'qc_rejected': int(n_qc),
743
+ 'anc_qc_rejected': int(n_anc_qc),
573
744
  'dropped_before_axis': int(n_before),
574
745
  }
575
746
 
@@ -583,6 +754,11 @@ def build_and_publish(cat, path, member_conn, rcg_conn, meta, stations, series,
583
754
  optimization for LARGE, rarely-updated archives (thousands of keys — see ebooklet's
584
755
  guidance of 10-100MB per group); pass a prime ``num_groups`` only for that shape.
585
756
  The choice is fixed at first publish.
757
+
758
+ ``**build_kwargs`` go straight to ``build_local`` — including ``ancillary=`` to declare
759
+ companion ``(point, time)`` planes (e.g. a per-timestep quality grade), whose data rides in
760
+ each ``series`` entry's third tuple slot. ``update_and_publish`` needs no equivalent argument:
761
+ the roster is read back from the stored dataset's ``ancillary_variables`` attr.
586
762
  """
587
763
  build_local(path, meta, stations, series, **build_kwargs)
588
764
  return cat.publish(str(path), member_conn, rcg_conn, num_groups=num_groups)
@@ -13,13 +13,14 @@ dependencies = [
13
13
  # Released PyPI stack only - ingest repos are arm's-length consumers.
14
14
  # Deliberately pandas-free: the API is numpy tuples/dicts (pandas objects still
15
15
  # work as *inputs* by duck-typing).
16
- "envlib>=0.1.2",
16
+ "envlib>=0.1.3",
17
17
  # >=0.9.4 is a HARD floor: older cfdb fabricates values when its packed encoder meets
18
18
  # NaN/out-of-range data (cfdb changelog 0.9.4); tsortho also enforces this at runtime.
19
19
  "cfdb>=0.9.4",
20
- "ebooklet>=0.10.2",
20
+ "ebooklet>=0.10.3",
21
21
  "numpy",
22
22
  "shapely>=2.0",
23
+ "sentry-sdk",
23
24
  ]
24
25
 
25
26
  [dependency-groups]