envlib-ingest-base 0.2.0__tar.gz → 0.3.1__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.
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/PKG-INFO +41 -8
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/README.md +38 -5
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/envlib_ingest_base/__init__.py +1 -1
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/envlib_ingest_base/tsortho.py +162 -57
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/pyproject.toml +4 -1
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/.gitignore +0 -0
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/LICENSE +0 -0
- {envlib_ingest_base-0.2.0 → envlib_ingest_base-0.3.1}/envlib_ingest_base/resample.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: envlib-ingest-base
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.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
5
|
Project-URL: Source, https://github.com/envlib/envlib-ingest-base
|
|
6
6
|
Author-email: mullenkamp <mullenkamp1@gmail.com>
|
|
@@ -10,7 +10,7 @@ Classifier: Programming Language :: Python :: 3 :: Only
|
|
|
10
10
|
Requires-Python: >=3.10
|
|
11
11
|
Requires-Dist: cfdb>=0.9.4
|
|
12
12
|
Requires-Dist: ebooklet>=0.10.3
|
|
13
|
-
Requires-Dist: envlib>=0.1.
|
|
13
|
+
Requires-Dist: envlib>=0.1.4
|
|
14
14
|
Requires-Dist: numpy
|
|
15
15
|
Requires-Dist: sentry-sdk
|
|
16
16
|
Requires-Dist: shapely>=2.0
|
|
@@ -208,6 +208,15 @@ Version notes: `station_ref` exists in datasets built by toolkit >= 0.1.2 (mergi
|
|
|
208
208
|
into an older dataset raises — rebuild it — while revise-only merges keep working); the CF attrs
|
|
209
209
|
and `station_altitude` land from toolkit >= 0.1.4.
|
|
210
210
|
|
|
211
|
+
Station **geometry** is canonicalized through `envlib.canonical_station_point` before it is
|
|
212
|
+
stored, from toolkit >= 0.3.1 (which is why that release floors `envlib>=0.1.4`). Without it, a
|
|
213
|
+
source supplying more than 5 decimal places of longitude/latitude could write a point that cfdb
|
|
214
|
+
re-rounds on the way in, leaving a stored geometry that no longer derives the stored `station_id`
|
|
215
|
+
— a dataset that then fails `publish()` forever. Ids are unaffected, so this changed nothing for
|
|
216
|
+
stations already stored; datasets built by earlier toolkits need no rebuild. Two stations that
|
|
217
|
+
round to the same point (within ~1 m) are now rejected at build with both refs named, instead of
|
|
218
|
+
dying inside cfdb's coordinate-uniqueness check.
|
|
219
|
+
|
|
211
220
|
**The envlib metadata is the single source of truth for the cadence** — there is no `freq`
|
|
212
221
|
parameter. `frequency_interval` is a closed envlib vocabulary; only *fixed* codes work here
|
|
213
222
|
(`1min`…`30min`, `1h`…`12h`, `day` — `month`/`year`/`None` raise, a dense axis needs a fixed
|
|
@@ -265,6 +274,15 @@ attrs so merges apply the same filter). `precision` is
|
|
|
265
274
|
**decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
|
|
266
275
|
pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
|
|
267
276
|
|
|
277
|
+
**Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
|
|
278
|
+
(`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
|
|
279
|
+
tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
|
|
280
|
+
~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
|
|
281
|
+
write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
|
|
282
|
+
still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
|
|
283
|
+
for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
|
|
284
|
+
write — is the ceiling.
|
|
285
|
+
|
|
268
286
|
```python
|
|
269
287
|
from envlib_ingest_base import build_local
|
|
270
288
|
|
|
@@ -316,10 +334,22 @@ encodable range and a junk high code would persist silently.
|
|
|
316
334
|
Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
|
|
317
335
|
The cadence is read back from the dataset's own envlib attrs and cross-checked against the stored
|
|
318
336
|
axis (epoch-aligned origin, dense constant step — mismatches raise). Appends genuinely-new stations
|
|
319
|
-
and new steps, then
|
|
320
|
-
values **only where they are non-NaN** — so a station that is offline this window (or an
|
|
321
|
-
that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
|
|
322
|
-
before the axis start raises (no history prepending). Returns a small report dict.
|
|
337
|
+
and new steps, then read-modify-writes **one station at a time, each over its own window**, writing
|
|
338
|
+
incoming values **only where they are non-NaN** — so a station that is offline this window (or an
|
|
339
|
+
interval that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
|
|
340
|
+
entirely before the axis start raises (no history prepending). Returns a small report dict.
|
|
341
|
+
|
|
342
|
+
**Memory is bounded by one station's window, not by the point dimension.** This previously read one
|
|
343
|
+
contiguous block spanning *every* station, sized from the global min/max incoming timestamp — so a
|
|
344
|
+
single station reporting one backdated value widened the read for all of them (measured: a routine
|
|
345
|
+
48-step merge went from 6 MB to 552 MB from one stale value). Per-station, a backdated value widens
|
|
346
|
+
only its own row. **Stations that supply nothing this run are not touched at all**, which also means
|
|
347
|
+
they are no longer rewritten — relevant to an `EDataset`, where a rewritten chunk is a pushed chunk.
|
|
348
|
+
|
|
349
|
+
⚠️ **The store is log-structured, so every merge grows the file** (each reporting station's tail
|
|
350
|
+
chunk is rewritten and the old block orphaned). A continuously-merged dataset needs `ds.prune()` to
|
|
351
|
+
reclaim it — cheap, local-only, and it preserves per-key timestamps so it cannot inflate the next
|
|
352
|
+
push. Prune after publishing.
|
|
323
353
|
|
|
324
354
|
```python
|
|
325
355
|
from cfdb import open_dataset
|
|
@@ -327,8 +357,11 @@ from envlib_ingest_base import merge_dataset
|
|
|
327
357
|
|
|
328
358
|
with open_dataset('flow.cfdb', flag='w') as ds:
|
|
329
359
|
merge_dataset(ds, stations, series_recent, variable='streamflow')
|
|
330
|
-
# -> {'new_stations': 0, 'new_steps': 24, 'written_block':
|
|
360
|
+
# -> {'new_stations': 0, 'new_steps': 24, 'written_block': 48, 'gap_steps': 0,
|
|
331
361
|
# 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
|
|
362
|
+
# written_block: the WIDEST single station's window (the merge no longer has one global
|
|
363
|
+
# block). A large value now means one station genuinely carried a wide window,
|
|
364
|
+
# not that one stale timestamp stretched the block across every station.
|
|
332
365
|
# gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
|
|
333
366
|
# so refetching a wider window and re-merging heals them
|
|
334
367
|
# qc_rejected: values outside the encodable range set to NaN by the min/max QC
|
|
@@ -190,6 +190,15 @@ Version notes: `station_ref` exists in datasets built by toolkit >= 0.1.2 (mergi
|
|
|
190
190
|
into an older dataset raises — rebuild it — while revise-only merges keep working); the CF attrs
|
|
191
191
|
and `station_altitude` land from toolkit >= 0.1.4.
|
|
192
192
|
|
|
193
|
+
Station **geometry** is canonicalized through `envlib.canonical_station_point` before it is
|
|
194
|
+
stored, from toolkit >= 0.3.1 (which is why that release floors `envlib>=0.1.4`). Without it, a
|
|
195
|
+
source supplying more than 5 decimal places of longitude/latitude could write a point that cfdb
|
|
196
|
+
re-rounds on the way in, leaving a stored geometry that no longer derives the stored `station_id`
|
|
197
|
+
— a dataset that then fails `publish()` forever. Ids are unaffected, so this changed nothing for
|
|
198
|
+
stations already stored; datasets built by earlier toolkits need no rebuild. Two stations that
|
|
199
|
+
round to the same point (within ~1 m) are now rejected at build with both refs named, instead of
|
|
200
|
+
dying inside cfdb's coordinate-uniqueness check.
|
|
201
|
+
|
|
193
202
|
**The envlib metadata is the single source of truth for the cadence** — there is no `freq`
|
|
194
203
|
parameter. `frequency_interval` is a closed envlib vocabulary; only *fixed* codes work here
|
|
195
204
|
(`1min`…`30min`, `1h`…`12h`, `day` — `month`/`year`/`None` raise, a dense axis needs a fixed
|
|
@@ -247,6 +256,15 @@ attrs so merges apply the same filter). `precision` is
|
|
|
247
256
|
**decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
|
|
248
257
|
pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
|
|
249
258
|
|
|
259
|
+
**Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
|
|
260
|
+
(`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
|
|
261
|
+
tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
|
|
262
|
+
~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
|
|
263
|
+
write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
|
|
264
|
+
still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
|
|
265
|
+
for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
|
|
266
|
+
write — is the ceiling.
|
|
267
|
+
|
|
250
268
|
```python
|
|
251
269
|
from envlib_ingest_base import build_local
|
|
252
270
|
|
|
@@ -298,10 +316,22 @@ encodable range and a junk high code would persist silently.
|
|
|
298
316
|
Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
|
|
299
317
|
The cadence is read back from the dataset's own envlib attrs and cross-checked against the stored
|
|
300
318
|
axis (epoch-aligned origin, dense constant step — mismatches raise). Appends genuinely-new stations
|
|
301
|
-
and new steps, then
|
|
302
|
-
values **only where they are non-NaN** — so a station that is offline this window (or an
|
|
303
|
-
that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
|
|
304
|
-
before the axis start raises (no history prepending). Returns a small report dict.
|
|
319
|
+
and new steps, then read-modify-writes **one station at a time, each over its own window**, writing
|
|
320
|
+
incoming values **only where they are non-NaN** — so a station that is offline this window (or an
|
|
321
|
+
interval that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
|
|
322
|
+
entirely before the axis start raises (no history prepending). Returns a small report dict.
|
|
323
|
+
|
|
324
|
+
**Memory is bounded by one station's window, not by the point dimension.** This previously read one
|
|
325
|
+
contiguous block spanning *every* station, sized from the global min/max incoming timestamp — so a
|
|
326
|
+
single station reporting one backdated value widened the read for all of them (measured: a routine
|
|
327
|
+
48-step merge went from 6 MB to 552 MB from one stale value). Per-station, a backdated value widens
|
|
328
|
+
only its own row. **Stations that supply nothing this run are not touched at all**, which also means
|
|
329
|
+
they are no longer rewritten — relevant to an `EDataset`, where a rewritten chunk is a pushed chunk.
|
|
330
|
+
|
|
331
|
+
⚠️ **The store is log-structured, so every merge grows the file** (each reporting station's tail
|
|
332
|
+
chunk is rewritten and the old block orphaned). A continuously-merged dataset needs `ds.prune()` to
|
|
333
|
+
reclaim it — cheap, local-only, and it preserves per-key timestamps so it cannot inflate the next
|
|
334
|
+
push. Prune after publishing.
|
|
305
335
|
|
|
306
336
|
```python
|
|
307
337
|
from cfdb import open_dataset
|
|
@@ -309,8 +339,11 @@ from envlib_ingest_base import merge_dataset
|
|
|
309
339
|
|
|
310
340
|
with open_dataset('flow.cfdb', flag='w') as ds:
|
|
311
341
|
merge_dataset(ds, stations, series_recent, variable='streamflow')
|
|
312
|
-
# -> {'new_stations': 0, 'new_steps': 24, 'written_block':
|
|
342
|
+
# -> {'new_stations': 0, 'new_steps': 24, 'written_block': 48, 'gap_steps': 0,
|
|
313
343
|
# 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
|
|
344
|
+
# written_block: the WIDEST single station's window (the merge no longer has one global
|
|
345
|
+
# block). A large value now means one station genuinely carried a wide window,
|
|
346
|
+
# not that one stale timestamp stretched the block across every station.
|
|
314
347
|
# gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
|
|
315
348
|
# so refetching a wider window and re-merging heals them
|
|
316
349
|
# qc_rejected: values outside the encodable range set to NaN by the min/max QC
|
|
@@ -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.
|
|
10
|
+
__version__ = '0.3.1'
|
|
11
11
|
__all__ = [
|
|
12
12
|
'build_and_publish',
|
|
13
13
|
'build_local',
|
|
@@ -60,11 +60,17 @@ grows an ``origin`` feature; see the OPEN_WORK follow-up):
|
|
|
60
60
|
Known one-directional limit: data resampled *coarser* than declared (daily labels are valid
|
|
61
61
|
hour multiples) builds a sparse-but-aligned axis the guards cannot detect.
|
|
62
62
|
|
|
63
|
-
The **merge** is the operational core: each run resamples a recent window and folds it in
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
63
|
+
The **merge** is the operational core: each run resamples a recent window and folds it in with a
|
|
64
|
+
read-modify-write **per station, each over its own window**, writing incoming values only where
|
|
65
|
+
they are non-NaN (so a station that is briefly offline, or an interval that resamples to NaN,
|
|
66
|
+
never clobbers good stored data). New stations append to the point axis; new steps extend the
|
|
67
|
+
time axis (in the coord's own stored dtype). A re-run over the same window is a no-op.
|
|
68
|
+
|
|
69
|
+
Both write paths — build and merge — iterate BY STATION, matching the ts_ortho chunk shape of
|
|
70
|
+
`(1, time_chunk)`. Peak memory therefore tracks one station's row, never the point dimension.
|
|
71
|
+
Note the store is log-structured, so each merge orphans the chunks it rewrites: a continuously
|
|
72
|
+
merged dataset grows every run and wants a periodic `ds.prune()` (local-only, timestamp-preserving,
|
|
73
|
+
so it cannot inflate a push).
|
|
68
74
|
|
|
69
75
|
The cfdb-level functions (``build_local``, ``merge_dataset``) take an open dataset / path and
|
|
70
76
|
are unit-tested without any remote. ``build_and_publish`` / ``update_and_publish`` wrap them
|
|
@@ -343,33 +349,92 @@ def _check_extras(non_empty: dict, roster) -> None:
|
|
|
343
349
|
raise ValueError(msg)
|
|
344
350
|
|
|
345
351
|
|
|
346
|
-
def
|
|
347
|
-
"""
|
|
352
|
+
def _write_rows(var, stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, dt, plane=None) -> None:
|
|
353
|
+
"""Write the dense ``(n_point, n_time)`` plane ONE STATION ROW AT A TIME.
|
|
348
354
|
|
|
349
|
-
``
|
|
350
|
-
|
|
351
|
-
|
|
355
|
+
This replaces an earlier ``_assemble`` that built the whole dense plane in memory and
|
|
356
|
+
returned it for a single ``var[:] = ...`` assignment. **That defeated the main reason to use
|
|
357
|
+
cfdb.** cfdb reads and writes in chunks, and the ts_ortho chunk shape is ``(1, time_chunk)``
|
|
358
|
+
— *one station row* — so the whole-plane approach allocated a station-count multiple of what
|
|
359
|
+
a write actually needs. Measured on a 606-station by 620,771-step dataset: 3.01 GB per plane,
|
|
360
|
+
two planes, and roughly double again for ``_nan_safe``'s mask and copy. Per row it is ~5 MB.
|
|
361
|
+
|
|
362
|
+
``plane=None`` writes the primary values; a string writes that named ancillary (stations
|
|
363
|
+
lacking it stay NaN), so both share one code path and land on identical geometry.
|
|
364
|
+
|
|
365
|
+
⚠️ **Iterate ``stations``, never ``series``.** The point coordinate and the
|
|
366
|
+
``station_id``/``station_ref``/``station_name`` arrays are built in ``stations`` order, so row
|
|
367
|
+
``i`` MUST be the ``i``-th entry of ``stations``. Driving the loop from ``series`` instead
|
|
368
|
+
would map the *i*-th station-that-has-data to point *i* and silently mislabel every station
|
|
369
|
+
after the first data-less one — a file that validates cleanly and is wrong.
|
|
370
|
+
|
|
371
|
+
A station with no data still gets an explicitly written all-NaN row, exactly as before: an
|
|
372
|
+
unwritten chunk also reads as NaN, but it would change which chunks exist and the file size.
|
|
373
|
+
|
|
374
|
+
Each row is written in ONE call, and each chunk therefore exactly once. Revisiting a chunk
|
|
375
|
+
costs a full decompress+recompress, orphans the previous block (the store is log-structured,
|
|
376
|
+
so the file grows until pruned), and can force a synchronous buffer flush.
|
|
352
377
|
"""
|
|
353
|
-
data = np.full((len(stations), n_times), np.nan, dtype='float64')
|
|
354
378
|
for i, ref in enumerate(stations):
|
|
379
|
+
# a fresh row per station: nothing is ever aliased into cfdb's chunk buffer, and the
|
|
380
|
+
# peak is one row regardless of station count
|
|
381
|
+
row = np.full(n_times, np.nan, dtype='float64')
|
|
355
382
|
s = series.get(ref)
|
|
356
|
-
if s is None:
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
data[i, col[ok]] = arr[ok]
|
|
365
|
-
return data
|
|
383
|
+
if s is not None:
|
|
384
|
+
t, v, ex = s
|
|
385
|
+
arr = v if plane is None else ex.get(plane)
|
|
386
|
+
if arr is not None:
|
|
387
|
+
col = _step_index(t, t0_us, step_us)
|
|
388
|
+
ok = (col >= 0) & (col < n_times)
|
|
389
|
+
row[col[ok]] = arr[ok]
|
|
390
|
+
var[i, :] = _nan_safe(row, dt)
|
|
366
391
|
|
|
367
392
|
|
|
368
393
|
def _points_ids_names(stations: dict):
|
|
369
|
-
|
|
394
|
+
"""Station geometry + labels, in ``stations`` order.
|
|
395
|
+
|
|
396
|
+
The points are CANONICALISED (``envlib.canonical_station_point``) before they leave this
|
|
397
|
+
function, and that is not cosmetic: cfdb stores a point coordinate by encoding it with
|
|
398
|
+
``shapely.to_wkt(..., rounding_precision=5)``, whose ``trim=True`` default rounds the
|
|
399
|
+
shortest decimal string half-to-even, while ``compute_station_id`` rounds the binary value
|
|
400
|
+
via ``wkt.dumps`` (``trim=False``). They disagree on ~9% of coordinates supplied to 6
|
|
401
|
+
decimal places, so writing the RAW point stores a geometry that no longer derives the
|
|
402
|
+
``station_id`` written beside it and the dataset can never be published — which is exactly
|
|
403
|
+
how a live ECan publish failed on 2026-08-24. Canonicalising first makes the store's
|
|
404
|
+
round-trip a fixed point. Ids are unaffected (the canonical point is what they already
|
|
405
|
+
hashed), so this changes nothing for any station already stored.
|
|
406
|
+
"""
|
|
407
|
+
points = [
|
|
408
|
+
envlib.canonical_station_point(shapely.Point(float(d['lon']), float(d['lat'])))
|
|
409
|
+
for d in stations.values()
|
|
410
|
+
]
|
|
370
411
|
ids = np.array([envlib.compute_station_id(p) for p in points], dtype=object)
|
|
371
412
|
names = np.array([str(d['name']) for d in stations.values()], dtype=object)
|
|
372
413
|
refs = np.array([str(r) for r in stations], dtype=object)
|
|
414
|
+
|
|
415
|
+
# Two stations inside the same ~1 m 5-dp cell collapse to ONE station_id. That is the
|
|
416
|
+
# id contract, not a defect here — but it must be said out loud. Without this, the build
|
|
417
|
+
# dies in cfdb's coord-uniqueness check ('The data for coords must be unique.'), which
|
|
418
|
+
# names neither station, and before canonicalisation it did something worse: wrote two
|
|
419
|
+
# rows carrying the same id and failed much later inside catalogue validation.
|
|
420
|
+
if len(set(ids)) != len(ids):
|
|
421
|
+
seen: dict = {}
|
|
422
|
+
clashes = []
|
|
423
|
+
for ref, sid, p in zip(refs, ids, points, strict=True):
|
|
424
|
+
if sid in seen:
|
|
425
|
+
first_ref, first_p = seen[sid]
|
|
426
|
+
clashes.append(
|
|
427
|
+
f'{first_ref!r} ({first_p.x}, {first_p.y}) and {ref!r} ({p.x}, {p.y}) -> {sid}'
|
|
428
|
+
)
|
|
429
|
+
else:
|
|
430
|
+
seen[sid] = (ref, p)
|
|
431
|
+
msg = (
|
|
432
|
+
'stations collapse to the same station_id (identical to 5 decimal places, ~1 m): '
|
|
433
|
+
+ '; '.join(clashes)
|
|
434
|
+
+ '. A station_id IS its rounded location, so these are one station to envlib — '
|
|
435
|
+
'drop one, or correct the coordinates if they are wrong.'
|
|
436
|
+
)
|
|
437
|
+
raise ValueError(msg)
|
|
373
438
|
return points, ids, names, refs
|
|
374
439
|
|
|
375
440
|
|
|
@@ -487,7 +552,8 @@ def build_local(
|
|
|
487
552
|
tmin = _floor_step(min(int(t.astype('int64').min()) for t, *_ in non_empty.values()), step_us)
|
|
488
553
|
tmax = _floor_step(max(int(t.astype('int64').max()) for t, *_ in non_empty.values()), step_us)
|
|
489
554
|
times_us = np.arange(tmin, tmax + 1, step_us)
|
|
490
|
-
|
|
555
|
+
# NOTE: the dense plane is NOT assembled here. Rows are written individually inside the
|
|
556
|
+
# dataset context below (see _write_rows) so peak memory is one row, not one plane.
|
|
491
557
|
points, ids, names, refs = _points_ids_names(stations)
|
|
492
558
|
|
|
493
559
|
if chunk_shape is None:
|
|
@@ -521,7 +587,7 @@ def build_local(
|
|
|
521
587
|
# merge_dataset reads back, so the stored dataset stays the source of truth on update.
|
|
522
588
|
if ancillary:
|
|
523
589
|
dv.attrs['ancillary_variables'] = ' '.join(ancillary)
|
|
524
|
-
dv
|
|
590
|
+
_write_rows(dv, stations, non_empty, tmin, times_us.size, step_us, dt)
|
|
525
591
|
|
|
526
592
|
for aname, spec in ancillary.items():
|
|
527
593
|
adt = dtypes.dtype(
|
|
@@ -537,9 +603,10 @@ def build_local(
|
|
|
537
603
|
# written LAST so a caller-supplied attrs dict can never weaken the QC bounds
|
|
538
604
|
av.attrs['valid_min'] = float(spec['min_value'])
|
|
539
605
|
av.attrs['valid_max'] = float(spec['max_value'])
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
606
|
+
# Previously this nested a whole-plane _assemble INSIDE _nan_safe while the primary
|
|
607
|
+
# plane was still resident — three full planes plus a mask live at once, the worst
|
|
608
|
+
# single moment in the build. Now one row at a time, like the primary.
|
|
609
|
+
_write_rows(av, stations, non_empty, tmin, times_us.size, step_us, adt, plane=aname)
|
|
543
610
|
|
|
544
611
|
sid = ds.create.data_var.generic(STATION_ID_VAR, ('point',), dtype=dtypes.dtype('str'))
|
|
545
612
|
sid[:] = ids
|
|
@@ -569,9 +636,10 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
|
|
|
569
636
|
|
|
570
637
|
The cadence comes from the dataset's own ``envlib_frequency_interval`` attr (written at
|
|
571
638
|
build), cross-checked against the actual axis (origin on the epoch grid, dense constant
|
|
572
|
-
step). Appends new stations and new steps (in the coord's stored dtype), then
|
|
573
|
-
|
|
574
|
-
|
|
639
|
+
step). Appends new stations and new steps (in the coord's stored dtype), then read-modify-writes
|
|
640
|
+
ONE STATION AT A TIME, each over its own window, keeping existing values where the incoming
|
|
641
|
+
value is NaN. Idempotent for a fixed input window. Stations that supply nothing this run are
|
|
642
|
+
not read or written at all.
|
|
575
643
|
|
|
576
644
|
Requires a writable dataset: the station-attr heal runs on every call (even an empty window,
|
|
577
645
|
before the early return), so calling this on a read-only dataset raises rather than no-opping.
|
|
@@ -655,6 +723,11 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
|
|
|
655
723
|
active = list(non_empty)
|
|
656
724
|
sub = {r: stations[r] for r in active}
|
|
657
725
|
points, ids, names, refs = _points_ids_names(sub)
|
|
726
|
+
# ONE derivation per station per merge, reused by the write loop below. That loop used to
|
|
727
|
+
# recompute the id from stations[ref] independently, which meant the store path and the
|
|
728
|
+
# row-lookup path each had their own spelling of "the id for this station" and nothing
|
|
729
|
+
# forced them to agree.
|
|
730
|
+
ref_to_sid = dict(zip(refs, ids, strict=True))
|
|
658
731
|
# validated up front, BEFORE any row mutation: a junk/non-finite altitude then raises
|
|
659
732
|
# pre-append (never leaving a half-written station row), and the check is uniform — merge
|
|
660
733
|
# is as loud on bad altitude as build, regardless of new-vs-existing or var presence.
|
|
@@ -701,43 +774,75 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
|
|
|
701
774
|
if w_hi < 0:
|
|
702
775
|
msg = f'incoming window ends before the axis start ({tdata[0]}) — refusing to prepend history'
|
|
703
776
|
raise ValueError(msg)
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
incoming
|
|
708
|
-
|
|
709
|
-
|
|
777
|
+
# ONE STATION AT A TIME, each over ITS OWN window — never one block spanning every point.
|
|
778
|
+
#
|
|
779
|
+
# This previously read `dv[:, w_lo:w_hi+1]` across the FULL point dimension, where w_lo/w_hi
|
|
780
|
+
# came from the GLOBAL min/max incoming timestamp. Two consequences, both bad:
|
|
781
|
+
#
|
|
782
|
+
# * MEMORY: ~6-7 float64 blocks of (n_point x global_width) live at once. One station
|
|
783
|
+
# reporting a backdated timestamp widened the block for EVERY station — measured, a
|
|
784
|
+
# single stale value took a 48-step merge from 9 MB to 228 MB, and at production scale
|
|
785
|
+
# that is gigabytes inside an hourly cron.
|
|
786
|
+
# * WRITE AMPLIFICATION: every station's chunks in the block were rewritten even when that
|
|
787
|
+
# station supplied nothing this run (its slots merged to `existing`, i.e. back to
|
|
788
|
+
# themselves). Since the store is log-structured and the remote pushes changed keys,
|
|
789
|
+
# that is an upload of the whole block's chunks on every single run.
|
|
790
|
+
#
|
|
791
|
+
# Per-station is simply correct here: the union mask is elementwise and `incoming[row]` only
|
|
792
|
+
# ever carries data for the station at `row`, so there is NO cross-station dependency to
|
|
793
|
+
# preserve. Each station's window is its own, so a backdated value widens only its own read,
|
|
794
|
+
# and stations that reported nothing are not touched at all.
|
|
795
|
+
#
|
|
796
|
+
# chunk_shape is (1, time_chunk), so a row IS the chunk row: this reads and writes exactly
|
|
797
|
+
# the chunks it must, one station's worth at a time.
|
|
710
798
|
n_before = 0
|
|
799
|
+
widest = 0
|
|
711
800
|
for ref, (t, v, ex) in non_empty.items():
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
801
|
+
row = id_to_row[ref_to_sid[ref]]
|
|
802
|
+
col_abs = _step_index(t, t0, step_us)
|
|
803
|
+
n_before += int((col_abs < 0).sum()) # window straddles the axis start: pre-axis values
|
|
804
|
+
keep = col_abs >= 0
|
|
805
|
+
if not keep.any():
|
|
806
|
+
continue
|
|
807
|
+
lo, hi = int(col_abs[keep].min()), int(col_abs[keep].max())
|
|
808
|
+
width = hi - lo + 1
|
|
809
|
+
widest = max(widest, width)
|
|
810
|
+
col = col_abs[keep] - lo
|
|
811
|
+
|
|
812
|
+
existing = np.asarray(dv[row, lo : hi + 1].data, dtype='float64').ravel()
|
|
813
|
+
incoming = np.full(width, np.nan)
|
|
814
|
+
incoming[col] = v[keep]
|
|
815
|
+
existing_a, incoming_a = {}, {}
|
|
719
816
|
for n in anc_names:
|
|
817
|
+
existing_a[n] = np.asarray(anc_vars[n][row, lo : hi + 1].data, dtype='float64').ravel()
|
|
818
|
+
inc = np.full(width, np.nan)
|
|
720
819
|
a = ex.get(n)
|
|
721
820
|
if a is not None:
|
|
722
|
-
|
|
821
|
+
inc[col] = a[keep]
|
|
822
|
+
incoming_a[n] = inc
|
|
823
|
+
|
|
824
|
+
# UNION mask: a slot is "supplied by this run" if the primary OR any ancillary has data
|
|
825
|
+
# there. One mask drives every plane, so a stored (value, code) pair can never be
|
|
826
|
+
# assembled from two different runs — and a code that explains an absent value survives.
|
|
827
|
+
mask = ~np.isnan(incoming)
|
|
828
|
+
for n in anc_names:
|
|
829
|
+
mask |= ~np.isnan(incoming_a[n])
|
|
830
|
+
dv[row, lo : hi + 1] = _nan_safe(np.where(mask, incoming, existing), dv.dtype)
|
|
831
|
+
for n in anc_names:
|
|
832
|
+
merged_a = np.where(mask, incoming_a[n], existing_a[n])
|
|
833
|
+
anc_vars[n][row, lo : hi + 1] = _nan_safe(merged_a, anc_vars[n].dtype)
|
|
834
|
+
|
|
723
835
|
if n_before:
|
|
724
836
|
logger.warning('merge %s: %d incoming value(s) predate the axis start and were dropped', variable, n_before)
|
|
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)
|
|
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)
|
|
737
837
|
return {
|
|
738
838
|
'new_stations': n_new,
|
|
739
839
|
'new_steps': int(n_new_steps),
|
|
740
|
-
'
|
|
840
|
+
# WIDEST single station's window, not one global block — the merge no longer has a
|
|
841
|
+
# single block width. Nothing consumes this field (ingest.py reads only gap_steps); it
|
|
842
|
+
# is a diagnostic, and per-station is the more useful reading of it anyway: a large
|
|
843
|
+
# value now means one station genuinely carried a wide window, not that one stale
|
|
844
|
+
# timestamp stretched the block across every station.
|
|
845
|
+
'written_block': int(widest),
|
|
741
846
|
'gap_steps': int(gap_steps),
|
|
742
847
|
'qc_rejected': int(n_qc),
|
|
743
848
|
'anc_qc_rejected': int(n_anc_qc),
|
|
@@ -13,7 +13,10 @@ 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
|
-
|
|
16
|
+
# >=0.1.4 is a HARD floor, not hygiene: tsortho calls envlib.canonical_station_point,
|
|
17
|
+
# which does not exist before 0.1.4 — an older envlib makes EVERY ts_ortho build and
|
|
18
|
+
# merge die with AttributeError in _points_ids_names.
|
|
19
|
+
"envlib>=0.1.4",
|
|
17
20
|
# >=0.9.4 is a HARD floor: older cfdb fabricates values when its packed encoder meets
|
|
18
21
|
# NaN/out-of-range data (cfdb changelog 0.9.4); tsortho also enforces this at runtime.
|
|
19
22
|
"cfdb>=0.9.4",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|