envlib-ingest-base 0.3.2__tar.gz → 0.4.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.3.2 → envlib_ingest_base-0.4.1}/PKG-INFO +4 -4
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/envlib_ingest_base/__init__.py +9 -1
- envlib_ingest_base-0.4.1/envlib_ingest_base/stations.py +228 -0
- envlib_ingest_base-0.4.1/envlib_ingest_base/tsforecast.py +490 -0
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/envlib_ingest_base/tsortho.py +14 -204
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/pyproject.toml +7 -3
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/.gitignore +0 -0
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/LICENSE +0 -0
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/README.md +0 -0
- {envlib_ingest_base-0.3.2 → envlib_ingest_base-0.4.1}/envlib_ingest_base/resample.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: envlib-ingest-base
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.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>
|
|
@@ -9,9 +9,9 @@ License-File: LICENSE
|
|
|
9
9
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
10
|
Requires-Python: >=3.10
|
|
11
11
|
Requires-Dist: booklet>=0.12.10
|
|
12
|
-
Requires-Dist: cfdb>=0.9.
|
|
13
|
-
Requires-Dist: ebooklet>=0.10.
|
|
14
|
-
Requires-Dist: envlib>=0.1.
|
|
12
|
+
Requires-Dist: cfdb>=0.9.5
|
|
13
|
+
Requires-Dist: ebooklet>=0.10.5
|
|
14
|
+
Requires-Dist: envlib>=0.1.6
|
|
15
15
|
Requires-Dist: numpy
|
|
16
16
|
Requires-Dist: sentry-sdk
|
|
17
17
|
Requires-Dist: shapely>=2.0
|
|
@@ -2,16 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
- ``resample``: source-agnostic time-series resampling (exact trapezoidal mean; accumulation sum).
|
|
4
4
|
- ``tsortho``: build + idempotent commons-update of station (ts_ortho) datasets.
|
|
5
|
+
- ``tsforecast``: build + append of point-forecast (ts_forecast) datasets, one run at a time.
|
|
6
|
+
- ``stations``: station identity/altitude helpers shared by both builders.
|
|
5
7
|
"""
|
|
6
8
|
|
|
7
9
|
from envlib_ingest_base.resample import resample
|
|
10
|
+
from envlib_ingest_base.tsforecast import build_and_push, merge_run, update_and_push
|
|
11
|
+
from envlib_ingest_base.tsforecast import build_local as build_forecast_local
|
|
8
12
|
from envlib_ingest_base.tsortho import build_and_publish, build_local, merge_dataset, update_and_publish
|
|
9
13
|
|
|
10
|
-
__version__ = '0.
|
|
14
|
+
__version__ = '0.4.1'
|
|
11
15
|
__all__ = [
|
|
12
16
|
'build_and_publish',
|
|
17
|
+
'build_and_push',
|
|
18
|
+
'build_forecast_local',
|
|
13
19
|
'build_local',
|
|
14
20
|
'merge_dataset',
|
|
21
|
+
'merge_run',
|
|
15
22
|
'resample',
|
|
16
23
|
'update_and_publish',
|
|
24
|
+
'update_and_push',
|
|
17
25
|
]
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Station identity, altitude and encoding helpers shared by every dataset builder.
|
|
2
|
+
|
|
3
|
+
Extracted from ``tsortho`` when the forecast builder arrived, because the two must not fork.
|
|
4
|
+
``_points_ids_names`` in particular is the reason this module exists: it canonicalises each point
|
|
5
|
+
with ``envlib.canonical_station_point`` BEFORE the geometry is written, and a second copy of that
|
|
6
|
+
logic is a second chance to get the 5-decimal-place rounding wrong. A live ECan publish already
|
|
7
|
+
failed exactly that way on 2026-08-24 -- the stored geometry no longer derived the ``station_id``
|
|
8
|
+
stored beside it, and the dataset could never be published.
|
|
9
|
+
|
|
10
|
+
Nothing here knows about time, cadence, leads or runs. That is the dividing line: a helper belongs
|
|
11
|
+
in this module when it concerns WHICH STATION a row is, and in the builder when it concerns WHEN.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
|
|
18
|
+
import cfdb
|
|
19
|
+
import envlib
|
|
20
|
+
import numpy as np
|
|
21
|
+
import shapely
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
_MIN_CFDB = (0, 9, 4)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _require_fixed_cfdb() -> None:
|
|
29
|
+
"""cfdb < 0.9.4 fabricates values when its packed encoder meets NaN/out-of-range data —
|
|
30
|
+
and cfdb's own partial-chunk read-modify-write re-encodes STORED holes on every merge,
|
|
31
|
+
so no toolkit-side substitution can make older versions safe. Refuse to write."""
|
|
32
|
+
ver = tuple(int(x) for x in cfdb.__version__.split('.')[:3])
|
|
33
|
+
if ver < _MIN_CFDB:
|
|
34
|
+
msg = (
|
|
35
|
+
f'cfdb >= 0.9.4 required (installed: {cfdb.__version__}): older versions fabricate '
|
|
36
|
+
f'values when encoding NaN/out-of-range data through packed dtypes (cfdb changelog 0.9.4)'
|
|
37
|
+
)
|
|
38
|
+
raise RuntimeError(msg)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
STATION_ID_VAR = 'station_id'
|
|
42
|
+
|
|
43
|
+
STATION_NAME_VAR = 'station_name'
|
|
44
|
+
|
|
45
|
+
STATION_REF_VAR = 'station_ref'
|
|
46
|
+
|
|
47
|
+
STATION_ALTITUDE_VAR = 'station_altitude'
|
|
48
|
+
|
|
49
|
+
# station_altitude plausibility band (metres): a UNIVERSAL physical range for a station's
|
|
50
|
+
# elevation — above every surface station on Earth (highest AWS ~8,810 m; Everest summit 8,849)
|
|
51
|
+
# down through the deepest dry-land depressions (Dead Sea shore ~-430 m). Numeric values outside
|
|
52
|
+
# it (incl ±inf, float32 overflow, and the classic -9999/-999 sentinels) are treated as MISSING,
|
|
53
|
+
# not real. Precision is deliberately NOT declared: a station's survey accuracy varies
|
|
54
|
+
# station-to-station, is rarely documented, and would be dishonest to assert — altitude is stored
|
|
55
|
+
# as-reported (unpacked float32), and the comment attr says so.
|
|
56
|
+
_ALTITUDE_MIN = -500.0
|
|
57
|
+
|
|
58
|
+
_ALTITUDE_MAX = 9000.0
|
|
59
|
+
|
|
60
|
+
_MAX_WARN_REFS = 10 # cap the station list shown in the out-of-range altitude warning
|
|
61
|
+
|
|
62
|
+
# CF attributes for the auxiliary station-metadata variables. cfdb already writes the global
|
|
63
|
+
# featureType='timeSeries' for ts_ortho; per CF discrete-sampling-geometry conventions (§9.5)
|
|
64
|
+
# exactly one variable carries cf_role to mark the timeseries instance identifier — station_id
|
|
65
|
+
# (envlib's canonical geometry-derived station identity). station_altitude is optional (created
|
|
66
|
+
# only when a source supplies it; see build_local), so its attrs apply only where the var exists.
|
|
67
|
+
_STATION_VAR_ATTRS = {
|
|
68
|
+
STATION_ID_VAR: {
|
|
69
|
+
'long_name': 'envlib station identifier',
|
|
70
|
+
'cf_role': 'timeseries_id',
|
|
71
|
+
'comment': (
|
|
72
|
+
'Deterministic hash of the station geometry (envlib.compute_station_id); envlib '
|
|
73
|
+
'canonical station identity. Changes if the source corrects the coordinates.'
|
|
74
|
+
),
|
|
75
|
+
},
|
|
76
|
+
STATION_NAME_VAR: {'long_name': 'station name'},
|
|
77
|
+
STATION_REF_VAR: {
|
|
78
|
+
'long_name': 'source station reference identifier',
|
|
79
|
+
'comment': (
|
|
80
|
+
"The data provider's own native station id (the source's site key); the stable "
|
|
81
|
+
'join key back to the provider records.'
|
|
82
|
+
),
|
|
83
|
+
},
|
|
84
|
+
STATION_ALTITUDE_VAR: {
|
|
85
|
+
'long_name': 'station altitude',
|
|
86
|
+
'standard_name': 'altitude',
|
|
87
|
+
'units': 'm',
|
|
88
|
+
'valid_min': _ALTITUDE_MIN,
|
|
89
|
+
'valid_max': _ALTITUDE_MAX,
|
|
90
|
+
'comment': (
|
|
91
|
+
'Station elevation as reported by the source; survey method and precision vary between '
|
|
92
|
+
'stations and are not characterised. Values outside the valid range are treated as missing.'
|
|
93
|
+
),
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _encodable_range(dt) -> tuple:
|
|
99
|
+
"""The decodable value interval of a packed dtype; (None, None) when unpacked."""
|
|
100
|
+
enc = getattr(dt, 'dtype_encoded', None)
|
|
101
|
+
if enc is None or dt.precision is None or dt.offset is None:
|
|
102
|
+
return None, None
|
|
103
|
+
factor = 10**dt.precision
|
|
104
|
+
info = np.iinfo(enc)
|
|
105
|
+
return (1 / factor) + dt.offset, (info.max / factor) + dt.offset
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _qc_bounds(dv) -> tuple:
|
|
109
|
+
"""The QC bounds for an existing data var: the DECLARED ``valid_min``/``valid_max`` attrs
|
|
110
|
+
(written at build), falling back to the encodable range for datasets built before the
|
|
111
|
+
attrs existed (wider — encodability only)."""
|
|
112
|
+
attrs = dv.attrs.data
|
|
113
|
+
if 'valid_min' in attrs and 'valid_max' in attrs:
|
|
114
|
+
return float(attrs['valid_min']), float(attrs['valid_max'])
|
|
115
|
+
return _encodable_range(dv.dtype)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _nan_safe(data: np.ndarray, dt) -> np.ndarray:
|
|
119
|
+
"""Substitute NaN with the dtype's ``offset`` value, which encodes to the reserved
|
|
120
|
+
fillvalue exactly (decoding back to NaN). NOTE: this shields only the toolkit's own
|
|
121
|
+
writes — cfdb's partial-chunk read-modify-write re-encodes STORED holes internally, so
|
|
122
|
+
this is belt-and-braces on top of ``_require_fixed_cfdb``, NOT a substitute for it.
|
|
123
|
+
A no-op for unpacked dtypes."""
|
|
124
|
+
off = getattr(dt, 'offset', None)
|
|
125
|
+
if off is None:
|
|
126
|
+
return data
|
|
127
|
+
return np.where(np.isnan(data), float(off), data)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _points_ids_names(stations: dict):
|
|
131
|
+
"""Station geometry + labels, in ``stations`` order.
|
|
132
|
+
|
|
133
|
+
The points are CANONICALISED (``envlib.canonical_station_point``) before they leave this
|
|
134
|
+
function, and that is not cosmetic: cfdb stores a point coordinate by encoding it with
|
|
135
|
+
``shapely.to_wkt(..., rounding_precision=5)``, whose ``trim=True`` default rounds the
|
|
136
|
+
shortest decimal string half-to-even, while ``compute_station_id`` rounds the binary value
|
|
137
|
+
via ``wkt.dumps`` (``trim=False``). They disagree on ~9% of coordinates supplied to 6
|
|
138
|
+
decimal places, so writing the RAW point stores a geometry that no longer derives the
|
|
139
|
+
``station_id`` written beside it and the dataset can never be published — which is exactly
|
|
140
|
+
how a live ECan publish failed on 2026-08-24. Canonicalising first makes the store's
|
|
141
|
+
round-trip a fixed point. Ids are unaffected (the canonical point is what they already
|
|
142
|
+
hashed), so this changes nothing for any station already stored.
|
|
143
|
+
"""
|
|
144
|
+
points = [
|
|
145
|
+
envlib.canonical_station_point(shapely.Point(float(d['lon']), float(d['lat']))) for d in stations.values()
|
|
146
|
+
]
|
|
147
|
+
ids = np.array([envlib.compute_station_id(p) for p in points], dtype=object)
|
|
148
|
+
names = np.array([str(d['name']) for d in stations.values()], dtype=object)
|
|
149
|
+
refs = np.array([str(r) for r in stations], dtype=object)
|
|
150
|
+
|
|
151
|
+
# Two stations inside the same ~1 m 5-dp cell collapse to ONE station_id. That is the
|
|
152
|
+
# id contract, not a defect here — but it must be said out loud. Without this, the build
|
|
153
|
+
# dies in cfdb's coord-uniqueness check ('The data for coords must be unique.'), which
|
|
154
|
+
# names neither station, and before canonicalisation it did something worse: wrote two
|
|
155
|
+
# rows carrying the same id and failed much later inside catalogue validation.
|
|
156
|
+
if len(set(ids)) != len(ids):
|
|
157
|
+
seen: dict = {}
|
|
158
|
+
clashes = []
|
|
159
|
+
for ref, sid, p in zip(refs, ids, points, strict=True):
|
|
160
|
+
if sid in seen:
|
|
161
|
+
first_ref, first_p = seen[sid]
|
|
162
|
+
clashes.append(f'{first_ref!r} ({first_p.x}, {first_p.y}) and {ref!r} ({p.x}, {p.y}) -> {sid}')
|
|
163
|
+
else:
|
|
164
|
+
seen[sid] = (ref, p)
|
|
165
|
+
msg = (
|
|
166
|
+
'stations collapse to the same station_id (identical to 5 decimal places, ~1 m): '
|
|
167
|
+
+ '; '.join(clashes)
|
|
168
|
+
+ '. A station_id IS its rounded location, so these are one station to envlib — '
|
|
169
|
+
'drop one, or correct the coordinates if they are wrong.'
|
|
170
|
+
)
|
|
171
|
+
raise ValueError(msg)
|
|
172
|
+
return points, ids, names, refs
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _altitudes(stations: dict) -> np.ndarray:
|
|
176
|
+
"""Per-station altitude in metres (unpacked float32), NaN where a station lacks one; order
|
|
177
|
+
matches the dict. A missing/None/NaN value -> NaN. A numeric value outside the plausibility
|
|
178
|
+
band ``[_ALTITUDE_MIN, _ALTITUDE_MAX]`` (incl ±inf, float32 overflow, and sentinels like
|
|
179
|
+
-9999) is treated as MISSING -> NaN with a station-naming warning — the same "the declared
|
|
180
|
+
range doubles as QC" rule the data var uses. A NON-coercible / wrong-type value RAISES naming
|
|
181
|
+
the station: that is an adapter bug (clean floats/None are expected), not a sensor sentinel."""
|
|
182
|
+
out, rejected = [], []
|
|
183
|
+
for ref, d in stations.items():
|
|
184
|
+
v = d.get('altitude')
|
|
185
|
+
if v is None:
|
|
186
|
+
out.append(np.nan)
|
|
187
|
+
continue
|
|
188
|
+
try:
|
|
189
|
+
f = float(v)
|
|
190
|
+
except (TypeError, ValueError) as e:
|
|
191
|
+
msg = f'station {ref!r}: invalid altitude {v!r}'
|
|
192
|
+
raise ValueError(msg) from e
|
|
193
|
+
if np.isnan(f):
|
|
194
|
+
out.append(np.nan)
|
|
195
|
+
elif _ALTITUDE_MIN <= f <= _ALTITUDE_MAX:
|
|
196
|
+
out.append(f)
|
|
197
|
+
else: # sentinel / ±inf / float32 overflow -> missing (not real)
|
|
198
|
+
rejected.append(ref)
|
|
199
|
+
out.append(np.nan)
|
|
200
|
+
if rejected:
|
|
201
|
+
shown = rejected if len(rejected) <= _MAX_WARN_REFS else [*rejected[:_MAX_WARN_REFS], '...']
|
|
202
|
+
logger.warning(
|
|
203
|
+
'altitude: %d station(s) with out-of-range altitude set to NaN (outside [%g, %g] m): %s',
|
|
204
|
+
len(rejected),
|
|
205
|
+
_ALTITUDE_MIN,
|
|
206
|
+
_ALTITUDE_MAX,
|
|
207
|
+
shown,
|
|
208
|
+
)
|
|
209
|
+
return np.array(out, dtype='float32')
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _apply_station_attrs(ds) -> None:
|
|
213
|
+
"""Idempotently stamp the canonical CF attrs onto whatever station vars exist in ``ds``.
|
|
214
|
+
Unconditional ``update`` is safe: cfdb's attrs finalizer writes to the store only when the
|
|
215
|
+
attrs actually change, so re-running on every merge dirties nothing and re-uploads nothing."""
|
|
216
|
+
for var, attrs in _STATION_VAR_ATTRS.items():
|
|
217
|
+
if var in ds:
|
|
218
|
+
ds[var].attrs.update(attrs)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _check_refs(non_empty: dict, stations: dict) -> None:
|
|
222
|
+
"""A series ref absent from stations is a broken premise, not an operational hiccup:
|
|
223
|
+
extraction is station-list-driven, and without metadata there is no geometry, no
|
|
224
|
+
station_id, and no row to put the data in. Raise — never silently drop or skip."""
|
|
225
|
+
missing = sorted(set(non_empty) - set(stations))
|
|
226
|
+
if missing:
|
|
227
|
+
msg = f'series refs missing from stations: {missing} — station metadata is required'
|
|
228
|
+
raise ValueError(msg)
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
"""Build and incrementally extend envlib ``ts_forecast`` (point forecast) datasets.
|
|
2
|
+
|
|
3
|
+
A forecast archive is a sequence of **runs**. Each run is issued at an *init* time
|
|
4
|
+
(CF ``forecast_reference_time``) and predicts a series of future steps at fixed *leads*
|
|
5
|
+
(CF ``forecast_period``). Valid time is ``init + lead``. The layout is
|
|
6
|
+
``(point, forecast_reference_time, forecast_period)`` -- a LEAD axis, not a valid-time axis,
|
|
7
|
+
because ``(point, init, valid_time)`` is ~97 % empty while ``(point, init, lead)`` is dense.
|
|
8
|
+
|
|
9
|
+
**The write unit is one RUN, not one station** -- and that is the whole difference from
|
|
10
|
+
``tsortho``. Each run is a dense ``(all points, 1 init, all leads)`` slab, which is exactly one
|
|
11
|
+
chunk, so a run is appended in a single write with no read-modify-write::
|
|
12
|
+
|
|
13
|
+
ds['forecast_reference_time'].append([init]) # explicit step -> a missed run auto-fills
|
|
14
|
+
dv[:, frt_index, :] = slab # (n_points, n_leads); one chunk, one write
|
|
15
|
+
|
|
16
|
+
Everything else in this module is a guard, and they exist because every failure mode here is
|
|
17
|
+
SILENT -- each produces a file that validates, reads back cleanly, and answers wrongly.
|
|
18
|
+
|
|
19
|
+
Three inputs recur:
|
|
20
|
+
|
|
21
|
+
- ``stations``: ``{ref: {'lon': float, 'lat': float, 'name': str[, 'altitude': float]}}``,
|
|
22
|
+
identical to ``tsortho``. Station identity comes from :mod:`envlib_ingest_base.stations`, so the
|
|
23
|
+
two builders cannot fork on the 5-decimal-place geometry canonicalisation.
|
|
24
|
+
- ``run``: ``{'reference_time': datetime64, 'leads': int array, 'values': {ref: float array}}``.
|
|
25
|
+
``leads`` and each ``values`` array are POSITIONALLY PAIRED -- same length, same order. The
|
|
26
|
+
pairing is structural precisely so a value and its lead cannot desynchronise.
|
|
27
|
+
- ``variable``: the primary data variable's name, which must equal ``meta.variable``.
|
|
28
|
+
|
|
29
|
+
Four things this module refuses, each of which the storage layer will otherwise accept quietly:
|
|
30
|
+
|
|
31
|
+
*An OFF-GRID init.* ``forecast_reference_time`` declares an explicit step, and a step is the only
|
|
32
|
+
thing that makes a *missed* run recoverable: it auto-fills the skipped slot, and a later merge
|
|
33
|
+
writes into that slot rather than attempting a middle insertion. But **cfdb does not enforce its
|
|
34
|
+
own step for datetime coordinates** -- ``utils._generate_step_fill``'s datetime branch truncates
|
|
35
|
+
the gap to an int and then tests ``isclose`` against that int's own rounding, which is true for
|
|
36
|
+
every input (fixed in cfdb 0.9.7; this guard does NOT assume that fix is present). An off-grid
|
|
37
|
+
init is therefore appended silently onto an axis that goes on reporting its declared step, and
|
|
38
|
+
envlib's validation does not check axis uniformity either. So this module is the only thing
|
|
39
|
+
between a mislabelled init and the archive -- the same role ``tsortho._check_aligned`` plays for
|
|
40
|
+
a dense time axis. It refuses rather than snapping: flooring an init onto the declared cadence
|
|
41
|
+
would silently label a run with an init it does not have, and a loud refusal is recoverable while
|
|
42
|
+
a mislabelled init is not.
|
|
43
|
+
|
|
44
|
+
*A duplicate init.* A forecast run is immutable. Re-ingesting an init raises unless the caller
|
|
45
|
+
passes ``overwrite=True``, which is logged loudly. Callers should not rely on the raise for
|
|
46
|
+
idempotence -- check ``init in ds['forecast_reference_time']`` and skip, so a routine re-read of
|
|
47
|
+
an unchanged source file is a quiet no-op rather than an alert.
|
|
48
|
+
|
|
49
|
+
*A non-integer lead.* cfdb has no timedelta dtype, so a lead is a bare integer carrying a CF
|
|
50
|
+
``units`` attribute, and a float lead would be silently truncated by the encoder.
|
|
51
|
+
|
|
52
|
+
*A lead vector that is neither the stored one, a prefix of it, nor an extension of it.* Anything
|
|
53
|
+
else -- a different step, a different first lead, a gap -- is a source change that needs a human.
|
|
54
|
+
|
|
55
|
+
Chunking: the point dimension of a chunk is **locked at creation**. Sizing it from the station
|
|
56
|
+
count means every later station lands in a second, mostly-padding partial chunk forever, so
|
|
57
|
+
``point_headroom`` deliberately over-sizes it. This matters in practice, not in theory: a forecast
|
|
58
|
+
provider's station roster changes whenever someone asks them to move a site.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
from __future__ import annotations
|
|
62
|
+
|
|
63
|
+
import logging
|
|
64
|
+
|
|
65
|
+
import envlib
|
|
66
|
+
import numpy as np
|
|
67
|
+
from cfdb import dtypes, open_dataset, open_edataset
|
|
68
|
+
|
|
69
|
+
from envlib_ingest_base.stations import (
|
|
70
|
+
STATION_ALTITUDE_VAR,
|
|
71
|
+
STATION_ID_VAR,
|
|
72
|
+
STATION_NAME_VAR,
|
|
73
|
+
STATION_REF_VAR,
|
|
74
|
+
_altitudes,
|
|
75
|
+
_apply_station_attrs,
|
|
76
|
+
_check_refs,
|
|
77
|
+
_nan_safe,
|
|
78
|
+
_points_ids_names,
|
|
79
|
+
_qc_bounds,
|
|
80
|
+
_require_fixed_cfdb,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
logger = logging.getLogger(__name__)
|
|
84
|
+
|
|
85
|
+
FRT_COORD = 'forecast_reference_time'
|
|
86
|
+
PERIOD_COORD = 'forecast_period'
|
|
87
|
+
|
|
88
|
+
# The forecast_reference_time coordinate is stored as datetime64[m] (cfdb-vars' definition), so
|
|
89
|
+
# its declared step is an integer number of MINUTES.
|
|
90
|
+
_MINUTES_PER_HOUR = 60
|
|
91
|
+
|
|
92
|
+
# Over-size the chunk's point dimension so a station added later still lands in the same chunk.
|
|
93
|
+
# 8 covers every point-forecast roster this toolkit has seen; the cost is padding in a ~1 KB chunk.
|
|
94
|
+
DEFAULT_POINT_HEADROOM = 8
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _normalise_run(run: dict, stations: dict) -> tuple:
|
|
98
|
+
"""``run`` -> ``(init, leads, values)`` with every structural guard applied.
|
|
99
|
+
|
|
100
|
+
Returns ``init`` as ``datetime64[m]`` (the storage unit of the init axis), ``leads`` as an
|
|
101
|
+
ascending int64 array, and ``values`` as ``{ref: float64 array}`` aligned to ``leads``.
|
|
102
|
+
"""
|
|
103
|
+
for key in ('reference_time', 'leads', 'values'):
|
|
104
|
+
if key not in run:
|
|
105
|
+
msg = f'run is missing {key!r}; expected keys reference_time, leads, values'
|
|
106
|
+
raise ValueError(msg)
|
|
107
|
+
|
|
108
|
+
init = np.asarray(run['reference_time'], dtype='datetime64[m]').reshape(())
|
|
109
|
+
raw_leads = np.asarray(run['leads'])
|
|
110
|
+
if raw_leads.ndim != 1 or raw_leads.size == 0:
|
|
111
|
+
msg = f'run leads must be a non-empty 1-D array; got shape {raw_leads.shape}'
|
|
112
|
+
raise ValueError(msg)
|
|
113
|
+
# A float lead is REFUSED rather than cast: forecast_period is a bare integer coordinate
|
|
114
|
+
# (cfdb has no timedelta dtype), so 1.5 would encode as 1 and shift the valid time of every
|
|
115
|
+
# value beneath it by half a step, with no error anywhere.
|
|
116
|
+
if raw_leads.dtype.kind not in ('i', 'u'):
|
|
117
|
+
msg = (
|
|
118
|
+
f'run leads must be an integer dtype, not {raw_leads.dtype!r} -- {PERIOD_COORD} is a '
|
|
119
|
+
f'bare integer coordinate and a fractional lead would be silently truncated'
|
|
120
|
+
)
|
|
121
|
+
raise ValueError(msg)
|
|
122
|
+
leads = raw_leads.astype('int64')
|
|
123
|
+
if leads.size > 1:
|
|
124
|
+
gaps = np.unique(np.diff(leads))
|
|
125
|
+
if gaps.size != 1 or gaps[0] <= 0:
|
|
126
|
+
msg = f'run leads must be strictly ascending with one uniform step; got diffs {gaps.tolist()}'
|
|
127
|
+
raise ValueError(msg)
|
|
128
|
+
|
|
129
|
+
values = {}
|
|
130
|
+
for ref, arr in run['values'].items():
|
|
131
|
+
a = np.asarray(arr, dtype='float64')
|
|
132
|
+
if a.shape != leads.shape:
|
|
133
|
+
msg = (
|
|
134
|
+
f'station {ref!r}: values have shape {a.shape} but leads have {leads.shape} -- '
|
|
135
|
+
f'values must be positionally paired with leads'
|
|
136
|
+
)
|
|
137
|
+
raise ValueError(msg)
|
|
138
|
+
values[ref] = a
|
|
139
|
+
if not values:
|
|
140
|
+
msg = 'run carries no station values'
|
|
141
|
+
raise ValueError(msg)
|
|
142
|
+
_check_refs(values, stations)
|
|
143
|
+
return init, leads, values
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _lead_step(leads: np.ndarray) -> int:
|
|
147
|
+
return int(leads[1] - leads[0]) if leads.size > 1 else 1
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _check_init_on_grid(init, origin, step_minutes: int) -> None:
|
|
151
|
+
"""THE guard this module exists for -- see the module docstring.
|
|
152
|
+
|
|
153
|
+
The incoming init must sit exactly on the axis's own grid. cfdb will not check this for a
|
|
154
|
+
datetime coordinate, and nothing downstream re-derives an axis from its declared step, so a
|
|
155
|
+
mislabelled init is invisible at every layer once written.
|
|
156
|
+
"""
|
|
157
|
+
delta = (init.astype('datetime64[m]') - origin.astype('datetime64[m]')).astype('int64')
|
|
158
|
+
if delta % step_minutes:
|
|
159
|
+
msg = (
|
|
160
|
+
f'{FRT_COORD} {init} is not on the declared grid: it is {delta} min from the axis '
|
|
161
|
+
f'origin {origin}, which is not a multiple of the {step_minutes} min step. Refusing '
|
|
162
|
+
f'rather than snapping -- a snapped init would label this run with a time it does not '
|
|
163
|
+
f'have. Check the source file, or the declared run cadence.'
|
|
164
|
+
)
|
|
165
|
+
raise ValueError(msg)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _resolve_lead_block(stored: np.ndarray, leads: np.ndarray) -> tuple:
|
|
169
|
+
"""Reconcile a run's leads against the stored ``forecast_period`` axis.
|
|
170
|
+
|
|
171
|
+
Returns ``(n_write, extension)``: how many leads of the slab to write, and any new lead
|
|
172
|
+
values to append to the coordinate first. Accepts exactly three shapes -- identical, a
|
|
173
|
+
prefix of the stored axis (a short run; the tail stays missing), or an extension of it (a
|
|
174
|
+
longer product). Anything else is a source change a human should look at.
|
|
175
|
+
"""
|
|
176
|
+
stored = np.asarray(stored, dtype='int64')
|
|
177
|
+
n = min(stored.size, leads.size)
|
|
178
|
+
if not np.array_equal(stored[:n], leads[:n]):
|
|
179
|
+
msg = (
|
|
180
|
+
f'run leads are not compatible with the stored {PERIOD_COORD} axis: stored starts '
|
|
181
|
+
f'{stored[:5].tolist()}, run starts {leads[:5].tolist()}. A run must match the stored '
|
|
182
|
+
f'leads, be a prefix of them (a short run), or extend them (a longer product).'
|
|
183
|
+
)
|
|
184
|
+
raise ValueError(msg)
|
|
185
|
+
if leads.size <= stored.size:
|
|
186
|
+
return int(leads.size), None
|
|
187
|
+
return int(leads.size), leads[stored.size :]
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _slab(stations: dict, values: dict, n_leads: int, dt) -> np.ndarray:
|
|
191
|
+
"""The run's dense ``(n_point, n_leads)`` plane, in ``stations`` order.
|
|
192
|
+
|
|
193
|
+
⚠️ Iterate ``stations``, never ``values``. The point coordinate and the station_id/ref/name
|
|
194
|
+
arrays are built in ``stations`` order, so row *i* MUST be the *i*-th entry of ``stations``.
|
|
195
|
+
Driving the loop from ``values`` would map the *i*-th station-that-reported to point *i* and
|
|
196
|
+
silently mislabel every station after the first absent one -- a file that validates and is
|
|
197
|
+
wrong. (``tsortho._write_rows`` carries the same warning for the same reason.)
|
|
198
|
+
|
|
199
|
+
A station absent from this run keeps an all-NaN row: a run is written once, into a slot that
|
|
200
|
+
was empty, so there is nothing to clobber.
|
|
201
|
+
"""
|
|
202
|
+
plane = np.full((len(stations), n_leads), np.nan, dtype='float64')
|
|
203
|
+
for i, ref in enumerate(stations):
|
|
204
|
+
arr = values.get(ref)
|
|
205
|
+
if arr is not None:
|
|
206
|
+
plane[i, :] = arr[:n_leads]
|
|
207
|
+
return _nan_safe(plane, dt)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _qc(values: dict, lo, hi, variable: str) -> dict:
|
|
211
|
+
"""The declared min/max double as plausibility bounds (the toolkit-wide ruling): values
|
|
212
|
+
outside them -- including infinities -- become missing rather than being stored."""
|
|
213
|
+
if lo is None:
|
|
214
|
+
return values
|
|
215
|
+
out, n = {}, 0
|
|
216
|
+
for ref, v in values.items():
|
|
217
|
+
bad = ~np.isnan(v) & ((v < lo) | (v > hi))
|
|
218
|
+
n += int(bad.sum())
|
|
219
|
+
out[ref] = np.where(bad, np.nan, v) if bad.any() else v
|
|
220
|
+
if n:
|
|
221
|
+
logger.warning('%s: %d value(s) outside [%s, %s] set to NaN (QC)', variable, n, lo, hi)
|
|
222
|
+
return out
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def build_local(
|
|
226
|
+
path,
|
|
227
|
+
meta,
|
|
228
|
+
stations: dict,
|
|
229
|
+
run: dict,
|
|
230
|
+
*,
|
|
231
|
+
variable: str,
|
|
232
|
+
units: str,
|
|
233
|
+
precision,
|
|
234
|
+
min_value,
|
|
235
|
+
max_value,
|
|
236
|
+
frt_step_hours,
|
|
237
|
+
lead_units: str = 'h',
|
|
238
|
+
point_headroom: int = DEFAULT_POINT_HEADROOM,
|
|
239
|
+
chunk_shape=None,
|
|
240
|
+
standard_name=None,
|
|
241
|
+
extra_var_attrs=None,
|
|
242
|
+
validate: bool = True,
|
|
243
|
+
):
|
|
244
|
+
"""Create a fresh local ``ts_forecast`` cfdb from all stations and the FIRST run.
|
|
245
|
+
|
|
246
|
+
``frt_step_hours`` is the provider's run cadence and becomes the init axis's explicit step.
|
|
247
|
+
Declaring it is what makes a *missed* run recoverable later, and ``step=True`` is not a
|
|
248
|
+
substitute: auto-detect infers nothing from the single-value axis a first run creates.
|
|
249
|
+
|
|
250
|
+
``lead_units`` is written to ``forecast_period``'s CF ``units`` attribute and is load-bearing,
|
|
251
|
+
not decoration -- cfdb-vars deliberately supplies no default, because a consumer adding a bare
|
|
252
|
+
integer lead to the ``datetime64[m]`` init axis would otherwise add MINUTES.
|
|
253
|
+
|
|
254
|
+
``validate=True`` runs envlib's full dataset validation on the finished file. Leave it on: this
|
|
255
|
+
archive is not published to a catalogue, so this is the only place the guards that catalogue
|
|
256
|
+
publication would apply -- above all the ``station_id`` recomputation from the stored geometry
|
|
257
|
+
-- ever run.
|
|
258
|
+
"""
|
|
259
|
+
_require_fixed_cfdb()
|
|
260
|
+
init, leads, values = _normalise_run(run, stations)
|
|
261
|
+
# The init axis is datetime64[m], so the cadence must land on a whole minute. A fractional
|
|
262
|
+
# one is REFUSED rather than rounded: rounding would declare a step the provider does not
|
|
263
|
+
# keep, and every later on-grid check would then be measured against the wrong grid.
|
|
264
|
+
step_exact = float(frt_step_hours) * _MINUTES_PER_HOUR
|
|
265
|
+
step_minutes = round(step_exact)
|
|
266
|
+
if step_minutes <= 0 or step_minutes != step_exact:
|
|
267
|
+
msg = (
|
|
268
|
+
f'frt_step_hours must be positive and a whole number of minutes; got '
|
|
269
|
+
f'{frt_step_hours!r} ({step_exact} min)'
|
|
270
|
+
)
|
|
271
|
+
raise ValueError(msg)
|
|
272
|
+
if not lead_units:
|
|
273
|
+
msg = f'lead_units is required -- {PERIOD_COORD} carries no default units by design'
|
|
274
|
+
raise ValueError(msg)
|
|
275
|
+
|
|
276
|
+
dt = dtypes.dtype('float32', precision=precision, min_value=min_value, max_value=max_value)
|
|
277
|
+
values = _qc(values, float(min_value), float(max_value), variable)
|
|
278
|
+
points, ids, names, refs = _points_ids_names(stations)
|
|
279
|
+
alts = _altitudes(stations)
|
|
280
|
+
if chunk_shape is None:
|
|
281
|
+
chunk_shape = (max(int(point_headroom), len(stations)), 1, int(leads.size))
|
|
282
|
+
|
|
283
|
+
with open_dataset(str(path), flag='n', dataset_type='ts_forecast') as ds:
|
|
284
|
+
ds.create.coord.point()
|
|
285
|
+
ds['point'].append(points)
|
|
286
|
+
ds.create.coord.forecast_reference_time(data=np.array([init]), step=step_minutes)
|
|
287
|
+
ds.create.coord.forecast_period(data=leads.astype('int32'), step=_lead_step(leads))
|
|
288
|
+
ds[PERIOD_COORD].attrs['units'] = lead_units
|
|
289
|
+
ds.create.crs.from_user_input(4326, xy_coord='point')
|
|
290
|
+
|
|
291
|
+
dv = ds.create.data_var.generic(variable, ('point', FRT_COORD, PERIOD_COORD), dtype=dt, chunk_shape=chunk_shape)
|
|
292
|
+
dv.attrs['units'] = units
|
|
293
|
+
# persisted so every later merge applies the SAME plausibility filter
|
|
294
|
+
dv.attrs['valid_min'] = float(min_value)
|
|
295
|
+
dv.attrs['valid_max'] = float(max_value)
|
|
296
|
+
if standard_name is not None:
|
|
297
|
+
dv.attrs['standard_name'] = standard_name
|
|
298
|
+
if extra_var_attrs:
|
|
299
|
+
dv.attrs.update(extra_var_attrs)
|
|
300
|
+
dv[:, 0, :] = _slab(stations, values, int(leads.size), dt)
|
|
301
|
+
|
|
302
|
+
sid = ds.create.data_var.generic(STATION_ID_VAR, ('point',), dtype=dtypes.dtype('str'))
|
|
303
|
+
sid[:] = ids
|
|
304
|
+
snm = ds.create.data_var.generic(STATION_NAME_VAR, ('point',), dtype=dtypes.dtype('str'))
|
|
305
|
+
snm[:] = names
|
|
306
|
+
srf = ds.create.data_var.generic(STATION_REF_VAR, ('point',), dtype=dtypes.dtype('str'))
|
|
307
|
+
srf[:] = refs
|
|
308
|
+
if bool((~np.isnan(alts)).any()):
|
|
309
|
+
salt = ds.create.data_var.generic(STATION_ALTITUDE_VAR, ('point',), dtype=dtypes.dtype('float32'))
|
|
310
|
+
salt[:] = alts
|
|
311
|
+
|
|
312
|
+
_apply_station_attrs(ds)
|
|
313
|
+
ds.attrs.update(meta.to_dict())
|
|
314
|
+
if validate:
|
|
315
|
+
_validate(ds)
|
|
316
|
+
return str(path)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _validate(ds) -> None:
|
|
320
|
+
"""Run envlib's dataset validation against the OPEN dataset.
|
|
321
|
+
|
|
322
|
+
Deliberately against the open object rather than the path: reopening a file that is linked to
|
|
323
|
+
a remote starts a second session against it, and an open ``EDataset`` pulls transparently, so
|
|
324
|
+
extents come from the whole dataset rather than whichever chunks happen to be local.
|
|
325
|
+
"""
|
|
326
|
+
envlib.validate_dataset(ds)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def merge_run(ds, stations: dict, run: dict, *, variable: str, overwrite: bool = False) -> dict:
|
|
330
|
+
"""Fold ONE run into an open ``ts_forecast`` dataset (cfdb Dataset or EDataset, ``flag='w'``).
|
|
331
|
+
|
|
332
|
+
Appends any station that is new, reconciles the lead axis, places the init on the declared
|
|
333
|
+
grid, and writes the run's slab in a single call. Returns a report dict.
|
|
334
|
+
|
|
335
|
+
``overwrite=True`` replaces an init that is already present -- the whole slab, since a run is
|
|
336
|
+
atomic. It is logged at WARNING because overwriting a stored forecast is a recovery action,
|
|
337
|
+
not routine.
|
|
338
|
+
"""
|
|
339
|
+
_require_fixed_cfdb()
|
|
340
|
+
_apply_station_attrs(ds) # heal the canonical CF attrs on pre-existing datasets, idempotently
|
|
341
|
+
init, leads, values = _normalise_run(run, stations)
|
|
342
|
+
|
|
343
|
+
frt = ds[FRT_COORD]
|
|
344
|
+
step_minutes = frt.step
|
|
345
|
+
if not step_minutes:
|
|
346
|
+
msg = (
|
|
347
|
+
f'{FRT_COORD} has no declared step, so a missed run could never be back-filled '
|
|
348
|
+
f'(cfdb cannot insert into the middle of a coordinate). Rebuild with frt_step_hours.'
|
|
349
|
+
)
|
|
350
|
+
raise ValueError(msg)
|
|
351
|
+
stored_frt = np.asarray(frt.data).astype('datetime64[m]')
|
|
352
|
+
_check_init_on_grid(init, stored_frt[0], int(step_minutes))
|
|
353
|
+
|
|
354
|
+
dv = ds[variable]
|
|
355
|
+
lo, hi = _qc_bounds(dv)
|
|
356
|
+
values = _qc(values, lo, hi, variable)
|
|
357
|
+
|
|
358
|
+
# --- lead axis -------------------------------------------------------------------------
|
|
359
|
+
stored_leads = np.asarray(ds[PERIOD_COORD].data, dtype='int64')
|
|
360
|
+
n_write, extension = _resolve_lead_block(stored_leads, leads)
|
|
361
|
+
n_new_leads = 0
|
|
362
|
+
if extension is not None:
|
|
363
|
+
ds[PERIOD_COORD].append(extension.astype(np.asarray(ds[PERIOD_COORD].data).dtype))
|
|
364
|
+
n_new_leads = int(extension.size)
|
|
365
|
+
|
|
366
|
+
# --- new stations ----------------------------------------------------------------------
|
|
367
|
+
points, ids, names, refs = _points_ids_names(stations)
|
|
368
|
+
alts = _altitudes(stations)
|
|
369
|
+
stored_ids = [str(v) for v in ds[STATION_ID_VAR].data]
|
|
370
|
+
id_to_row = {sid: i for i, sid in enumerate(stored_ids)}
|
|
371
|
+
new_mask = np.array([sid not in id_to_row for sid in ids])
|
|
372
|
+
n_new = int(new_mask.sum())
|
|
373
|
+
if n_new:
|
|
374
|
+
base = len(stored_ids)
|
|
375
|
+
ds['point'].append([p for p, m in zip(points, new_mask, strict=True) if m])
|
|
376
|
+
ds[STATION_ID_VAR][base : base + n_new] = ids[new_mask]
|
|
377
|
+
ds[STATION_NAME_VAR][base : base + n_new] = names[new_mask]
|
|
378
|
+
ds[STATION_REF_VAR][base : base + n_new] = refs[new_mask]
|
|
379
|
+
if STATION_ALTITUDE_VAR in ds:
|
|
380
|
+
ds[STATION_ALTITUDE_VAR][base : base + n_new] = alts[new_mask]
|
|
381
|
+
for k, sid in enumerate(ids[new_mask]):
|
|
382
|
+
id_to_row[sid] = base + k
|
|
383
|
+
if STATION_ALTITUDE_VAR not in ds and bool((~np.isnan(alts)).any()):
|
|
384
|
+
logger.warning(
|
|
385
|
+
'merge %s: incoming stations carry altitude but the dataset has no %s var; rebuild to add it',
|
|
386
|
+
variable,
|
|
387
|
+
STATION_ALTITUDE_VAR,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
# --- place the init --------------------------------------------------------------------
|
|
391
|
+
existing = np.flatnonzero(stored_frt == init)
|
|
392
|
+
replaced = False
|
|
393
|
+
if existing.size:
|
|
394
|
+
# An init being ON THE AXIS does not mean a run was ever written there. A declared step
|
|
395
|
+
# AUTO-FILLS the slots of missed runs, and those placeholders are exactly what a later
|
|
396
|
+
# back-fill is supposed to write into -- so testing membership alone would make the
|
|
397
|
+
# immutability rule forbid the recovery the step exists to enable. Distinguish the two by
|
|
398
|
+
# the DATA: an all-missing slab is a placeholder, anything else is a stored run.
|
|
399
|
+
# (A real run in which every station was absent is indistinguishable from a placeholder,
|
|
400
|
+
# and is correctly treated as one -- it carries nothing to protect.)
|
|
401
|
+
idx = int(existing[0])
|
|
402
|
+
stored_slab = np.asarray(ds[variable][:, idx, :].data, dtype='float64')
|
|
403
|
+
replaced = bool(np.isfinite(stored_slab).any())
|
|
404
|
+
if replaced and not overwrite:
|
|
405
|
+
msg = (
|
|
406
|
+
f'{FRT_COORD} {init} already holds a stored run -- a forecast run is immutable. '
|
|
407
|
+
f'Pass overwrite=True to replace it deliberately, or skip this run (checking '
|
|
408
|
+
f'whether the init is already on the axis is the right idempotence test for a '
|
|
409
|
+
f're-read of an unchanged source file).'
|
|
410
|
+
)
|
|
411
|
+
raise ValueError(msg)
|
|
412
|
+
if replaced:
|
|
413
|
+
logger.warning('merge %s: OVERWRITING stored run %s', variable, init)
|
|
414
|
+
else:
|
|
415
|
+
logger.info('merge %s: back-filling the auto-filled slot at %s', variable, init)
|
|
416
|
+
elif init < stored_frt[0]:
|
|
417
|
+
msg = f'{FRT_COORD} {init} predates the axis start {stored_frt[0]}; refusing to prepend history'
|
|
418
|
+
raise ValueError(msg)
|
|
419
|
+
else:
|
|
420
|
+
# the declared step auto-fills any skipped inits; those slots read missing until a later
|
|
421
|
+
# merge writes into them, which is exactly what makes a missed run recoverable
|
|
422
|
+
frt.append(np.array([init]))
|
|
423
|
+
idx = int(np.flatnonzero(np.asarray(frt.data).astype('datetime64[m]') == init)[0])
|
|
424
|
+
filled = 0 if existing.size else max(idx - (stored_frt.size - 1) - 1, 0)
|
|
425
|
+
|
|
426
|
+
# --- one run, one slab, one write ------------------------------------------------------
|
|
427
|
+
# The plane is sized to the DATASET's point count and addressed BY ROW INDEX, not built in
|
|
428
|
+
# `stations` order. Those two coincide on a fresh build and stop coinciding the moment the
|
|
429
|
+
# roster changes -- a station retired from the config still occupies its row, and a station
|
|
430
|
+
# added later sits past the end of the config's ordering. Deriving each row from the stored
|
|
431
|
+
# station_id is the only thing that keeps a value attached to the station it belongs to.
|
|
432
|
+
dv = ds[variable]
|
|
433
|
+
ref_to_sid = dict(zip(refs, ids, strict=True))
|
|
434
|
+
n_points = int(np.asarray(ds['point'].data).size)
|
|
435
|
+
plane = np.full((n_points, n_write), np.nan, dtype='float64')
|
|
436
|
+
for ref, arr in values.items():
|
|
437
|
+
plane[id_to_row[ref_to_sid[str(ref)]], :] = arr[:n_write]
|
|
438
|
+
dv[:, idx, :n_write] = _nan_safe(plane, dv.dtype)
|
|
439
|
+
|
|
440
|
+
if filled:
|
|
441
|
+
logger.warning(
|
|
442
|
+
'merge %s: %d missed run slot(s) auto-filled before %s; they read missing until back-filled',
|
|
443
|
+
variable,
|
|
444
|
+
filled,
|
|
445
|
+
init,
|
|
446
|
+
)
|
|
447
|
+
return {
|
|
448
|
+
'init': str(init),
|
|
449
|
+
'init_index': idx,
|
|
450
|
+
'new_stations': n_new,
|
|
451
|
+
'new_leads': n_new_leads,
|
|
452
|
+
'autofilled_slots': int(filled),
|
|
453
|
+
'overwritten': replaced,
|
|
454
|
+
'backfilled': bool(existing.size) and not replaced,
|
|
455
|
+
'stations_reporting': len(values),
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def build_and_push(member_conn, path, meta, stations: dict, run: dict, *, num_groups=None, **build_kwargs):
|
|
460
|
+
"""First run: build the local ``ts_forecast`` and push it to its S3 remote.
|
|
461
|
+
|
|
462
|
+
There is deliberately **no catalogue here**. A forecast archive of a commercial provider's
|
|
463
|
+
product is not published to a public commons, so ``envlib.Catalogue`` contributes nothing --
|
|
464
|
+
but the metadata is still generated by ``envlib.Metadata`` and the file still passes the full
|
|
465
|
+
``envlib.validate_dataset`` in ``build_local``, so the dataset carries CV-validated identity
|
|
466
|
+
fields and is trivially promotable later if that ever changes.
|
|
467
|
+
|
|
468
|
+
``num_groups=None`` (per-key objects) is right for a continuously-appended archive: each run
|
|
469
|
+
is one small chunk, and every push moves exactly the run that changed.
|
|
470
|
+
"""
|
|
471
|
+
build_local(path, meta, stations, run, **build_kwargs)
|
|
472
|
+
with open_edataset(member_conn, str(path), flag='w', num_groups=num_groups) as eds:
|
|
473
|
+
result = eds.push()
|
|
474
|
+
return {'path': str(path), 'push': result}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def update_and_push(
|
|
478
|
+
member_conn, path, stations: dict, run: dict, *, variable: str, overwrite: bool = False, num_groups=None
|
|
479
|
+
):
|
|
480
|
+
"""Incremental run: pull the remote, merge one run, push.
|
|
481
|
+
|
|
482
|
+
``path`` is a local working cache linked to ``member_conn``. Note the store is log-structured,
|
|
483
|
+
so every run rewrites the init coordinate and orphans the previous copy -- the local file grows
|
|
484
|
+
on every run and wants a periodic ``ds.prune()``, AFTER the push (pruning is local-only and
|
|
485
|
+
preserves key timestamps, so it cannot inflate the next push).
|
|
486
|
+
"""
|
|
487
|
+
with open_edataset(member_conn, str(path), flag='w', num_groups=num_groups) as ds:
|
|
488
|
+
report = merge_run(ds, stations, run, variable=variable, overwrite=overwrite)
|
|
489
|
+
result = ds.push()
|
|
490
|
+
return {'merge': report, 'push': result}
|
|
@@ -81,81 +81,27 @@ from __future__ import annotations
|
|
|
81
81
|
|
|
82
82
|
import logging
|
|
83
83
|
|
|
84
|
-
import cfdb
|
|
85
|
-
import envlib
|
|
86
84
|
import numpy as np
|
|
87
|
-
import shapely
|
|
88
85
|
from cfdb import dtypes, open_dataset, open_edataset
|
|
89
86
|
from envlib.vocabularies import frequency_entry
|
|
90
87
|
|
|
91
|
-
|
|
88
|
+
from envlib_ingest_base.stations import (
|
|
89
|
+
STATION_ALTITUDE_VAR,
|
|
90
|
+
STATION_ID_VAR,
|
|
91
|
+
STATION_NAME_VAR,
|
|
92
|
+
STATION_REF_VAR,
|
|
93
|
+
_altitudes,
|
|
94
|
+
_apply_station_attrs,
|
|
95
|
+
_check_refs,
|
|
96
|
+
_nan_safe,
|
|
97
|
+
_points_ids_names,
|
|
98
|
+
_qc_bounds,
|
|
99
|
+
_require_fixed_cfdb,
|
|
100
|
+
)
|
|
92
101
|
|
|
93
|
-
|
|
102
|
+
logger = logging.getLogger(__name__)
|
|
94
103
|
|
|
95
104
|
|
|
96
|
-
def _require_fixed_cfdb() -> None:
|
|
97
|
-
"""cfdb < 0.9.4 fabricates values when its packed encoder meets NaN/out-of-range data —
|
|
98
|
-
and cfdb's own partial-chunk read-modify-write re-encodes STORED holes on every merge,
|
|
99
|
-
so no toolkit-side substitution can make older versions safe. Refuse to write."""
|
|
100
|
-
ver = tuple(int(x) for x in cfdb.__version__.split('.')[:3])
|
|
101
|
-
if ver < _MIN_CFDB:
|
|
102
|
-
msg = (
|
|
103
|
-
f'cfdb >= 0.9.4 required (installed: {cfdb.__version__}): older versions fabricate '
|
|
104
|
-
f'values when encoding NaN/out-of-range data through packed dtypes (cfdb changelog 0.9.4)'
|
|
105
|
-
)
|
|
106
|
-
raise RuntimeError(msg)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
STATION_ID_VAR = 'station_id'
|
|
110
|
-
STATION_NAME_VAR = 'station_name'
|
|
111
|
-
STATION_REF_VAR = 'station_ref'
|
|
112
|
-
STATION_ALTITUDE_VAR = 'station_altitude'
|
|
113
|
-
|
|
114
|
-
# station_altitude plausibility band (metres): a UNIVERSAL physical range for a station's
|
|
115
|
-
# elevation — above every surface station on Earth (highest AWS ~8,810 m; Everest summit 8,849)
|
|
116
|
-
# down through the deepest dry-land depressions (Dead Sea shore ~-430 m). Numeric values outside
|
|
117
|
-
# it (incl ±inf, float32 overflow, and the classic -9999/-999 sentinels) are treated as MISSING,
|
|
118
|
-
# not real. Precision is deliberately NOT declared: a station's survey accuracy varies
|
|
119
|
-
# station-to-station, is rarely documented, and would be dishonest to assert — altitude is stored
|
|
120
|
-
# as-reported (unpacked float32), and the comment attr says so.
|
|
121
|
-
_ALTITUDE_MIN = -500.0
|
|
122
|
-
_ALTITUDE_MAX = 9000.0
|
|
123
|
-
_MAX_WARN_REFS = 10 # cap the station list shown in the out-of-range altitude warning
|
|
124
|
-
|
|
125
|
-
# CF attributes for the auxiliary station-metadata variables. cfdb already writes the global
|
|
126
|
-
# featureType='timeSeries' for ts_ortho; per CF discrete-sampling-geometry conventions (§9.5)
|
|
127
|
-
# exactly one variable carries cf_role to mark the timeseries instance identifier — station_id
|
|
128
|
-
# (envlib's canonical geometry-derived station identity). station_altitude is optional (created
|
|
129
|
-
# only when a source supplies it; see build_local), so its attrs apply only where the var exists.
|
|
130
|
-
_STATION_VAR_ATTRS = {
|
|
131
|
-
STATION_ID_VAR: {
|
|
132
|
-
'long_name': 'envlib station identifier',
|
|
133
|
-
'cf_role': 'timeseries_id',
|
|
134
|
-
'comment': (
|
|
135
|
-
'Deterministic hash of the station geometry (envlib.compute_station_id); envlib '
|
|
136
|
-
'canonical station identity. Changes if the source corrects the coordinates.'
|
|
137
|
-
),
|
|
138
|
-
},
|
|
139
|
-
STATION_NAME_VAR: {'long_name': 'station name'},
|
|
140
|
-
STATION_REF_VAR: {
|
|
141
|
-
'long_name': 'source station reference identifier',
|
|
142
|
-
'comment': (
|
|
143
|
-
"The data provider's own native station id (the source's site key); the stable "
|
|
144
|
-
'join key back to the provider records.'
|
|
145
|
-
),
|
|
146
|
-
},
|
|
147
|
-
STATION_ALTITUDE_VAR: {
|
|
148
|
-
'long_name': 'station altitude',
|
|
149
|
-
'standard_name': 'altitude',
|
|
150
|
-
'units': 'm',
|
|
151
|
-
'valid_min': _ALTITUDE_MIN,
|
|
152
|
-
'valid_max': _ALTITUDE_MAX,
|
|
153
|
-
'comment': (
|
|
154
|
-
'Station elevation as reported by the source; survey method and precision vary between '
|
|
155
|
-
'stations and are not characterised. Values outside the valid range are treated as missing.'
|
|
156
|
-
),
|
|
157
|
-
},
|
|
158
|
-
}
|
|
159
105
|
_DEFAULT_TIME_CHUNK = 25_000 # steps; see the chunk_shape default rationale in build_local
|
|
160
106
|
# a series entry is (times, values) or (times, values, extras) — the 3rd slot carries ancillary data
|
|
161
107
|
_SERIES_WITH_EXTRAS = 3
|
|
@@ -221,26 +167,6 @@ def _check_phase(utc_offset, code) -> None:
|
|
|
221
167
|
raise ValueError(msg)
|
|
222
168
|
|
|
223
169
|
|
|
224
|
-
def _check_refs(non_empty: dict, stations: dict) -> None:
|
|
225
|
-
"""A series ref absent from stations is a broken premise, not an operational hiccup:
|
|
226
|
-
extraction is station-list-driven, and without metadata there is no geometry, no
|
|
227
|
-
station_id, and no row to put the data in. Raise — never silently drop or skip."""
|
|
228
|
-
missing = sorted(set(non_empty) - set(stations))
|
|
229
|
-
if missing:
|
|
230
|
-
msg = f'series refs missing from stations: {missing} — station metadata is required'
|
|
231
|
-
raise ValueError(msg)
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
def _encodable_range(dt) -> tuple:
|
|
235
|
-
"""The decodable value interval of a packed dtype; (None, None) when unpacked."""
|
|
236
|
-
enc = getattr(dt, 'dtype_encoded', None)
|
|
237
|
-
if enc is None or dt.precision is None or dt.offset is None:
|
|
238
|
-
return None, None
|
|
239
|
-
factor = 10**dt.precision
|
|
240
|
-
info = np.iinfo(enc)
|
|
241
|
-
return (1 / factor) + dt.offset, (info.max / factor) + dt.offset
|
|
242
|
-
|
|
243
|
-
|
|
244
170
|
def _qc_filter(non_empty: dict, lo, hi, anc_bounds: dict | None = None) -> tuple[dict, int, int]:
|
|
245
171
|
"""min/max QC (ruling 2026-07-17): the DECLARED min/max double as plausibility bounds,
|
|
246
172
|
so values outside them — including ±inf — become NaN (missing). Runs BEFORE the merge
|
|
@@ -274,28 +200,6 @@ def _qc_filter(non_empty: dict, lo, hi, anc_bounds: dict | None = None) -> tuple
|
|
|
274
200
|
return out, n, n_anc
|
|
275
201
|
|
|
276
202
|
|
|
277
|
-
def _qc_bounds(dv) -> tuple:
|
|
278
|
-
"""The QC bounds for an existing data var: the DECLARED ``valid_min``/``valid_max`` attrs
|
|
279
|
-
(written at build), falling back to the encodable range for datasets built before the
|
|
280
|
-
attrs existed (wider — encodability only)."""
|
|
281
|
-
attrs = dv.attrs.data
|
|
282
|
-
if 'valid_min' in attrs and 'valid_max' in attrs:
|
|
283
|
-
return float(attrs['valid_min']), float(attrs['valid_max'])
|
|
284
|
-
return _encodable_range(dv.dtype)
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
def _nan_safe(data: np.ndarray, dt) -> np.ndarray:
|
|
288
|
-
"""Substitute NaN with the dtype's ``offset`` value, which encodes to the reserved
|
|
289
|
-
fillvalue exactly (decoding back to NaN). NOTE: this shields only the toolkit's own
|
|
290
|
-
writes — cfdb's partial-chunk read-modify-write re-encodes STORED holes internally, so
|
|
291
|
-
this is belt-and-braces on top of ``_require_fixed_cfdb``, NOT a substitute for it.
|
|
292
|
-
A no-op for unpacked dtypes."""
|
|
293
|
-
off = getattr(dt, 'offset', None)
|
|
294
|
-
if off is None:
|
|
295
|
-
return data
|
|
296
|
-
return np.where(np.isnan(data), float(off), data)
|
|
297
|
-
|
|
298
|
-
|
|
299
203
|
def _non_empty(series: dict) -> dict:
|
|
300
204
|
"""Entries that actually carry data, normalized to ``(times, values, extras)``.
|
|
301
205
|
|
|
@@ -390,100 +294,6 @@ def _write_rows(var, stations: dict, series: dict, t0_us: int, n_times: int, ste
|
|
|
390
294
|
var[i, :] = _nan_safe(row, dt)
|
|
391
295
|
|
|
392
296
|
|
|
393
|
-
def _points_ids_names(stations: dict):
|
|
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
|
-
]
|
|
411
|
-
ids = np.array([envlib.compute_station_id(p) for p in points], dtype=object)
|
|
412
|
-
names = np.array([str(d['name']) for d in stations.values()], dtype=object)
|
|
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)
|
|
438
|
-
return points, ids, names, refs
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
def _altitudes(stations: dict) -> np.ndarray:
|
|
442
|
-
"""Per-station altitude in metres (unpacked float32), NaN where a station lacks one; order
|
|
443
|
-
matches the dict. A missing/None/NaN value -> NaN. A numeric value outside the plausibility
|
|
444
|
-
band ``[_ALTITUDE_MIN, _ALTITUDE_MAX]`` (incl ±inf, float32 overflow, and sentinels like
|
|
445
|
-
-9999) is treated as MISSING -> NaN with a station-naming warning — the same "the declared
|
|
446
|
-
range doubles as QC" rule the data var uses. A NON-coercible / wrong-type value RAISES naming
|
|
447
|
-
the station: that is an adapter bug (clean floats/None are expected), not a sensor sentinel."""
|
|
448
|
-
out, rejected = [], []
|
|
449
|
-
for ref, d in stations.items():
|
|
450
|
-
v = d.get('altitude')
|
|
451
|
-
if v is None:
|
|
452
|
-
out.append(np.nan)
|
|
453
|
-
continue
|
|
454
|
-
try:
|
|
455
|
-
f = float(v)
|
|
456
|
-
except (TypeError, ValueError) as e:
|
|
457
|
-
msg = f'station {ref!r}: invalid altitude {v!r}'
|
|
458
|
-
raise ValueError(msg) from e
|
|
459
|
-
if np.isnan(f):
|
|
460
|
-
out.append(np.nan)
|
|
461
|
-
elif _ALTITUDE_MIN <= f <= _ALTITUDE_MAX:
|
|
462
|
-
out.append(f)
|
|
463
|
-
else: # sentinel / ±inf / float32 overflow -> missing (not real)
|
|
464
|
-
rejected.append(ref)
|
|
465
|
-
out.append(np.nan)
|
|
466
|
-
if rejected:
|
|
467
|
-
shown = rejected if len(rejected) <= _MAX_WARN_REFS else [*rejected[:_MAX_WARN_REFS], '...']
|
|
468
|
-
logger.warning(
|
|
469
|
-
'altitude: %d station(s) with out-of-range altitude set to NaN (outside [%g, %g] m): %s',
|
|
470
|
-
len(rejected),
|
|
471
|
-
_ALTITUDE_MIN,
|
|
472
|
-
_ALTITUDE_MAX,
|
|
473
|
-
shown,
|
|
474
|
-
)
|
|
475
|
-
return np.array(out, dtype='float32')
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
def _apply_station_attrs(ds) -> None:
|
|
479
|
-
"""Idempotently stamp the canonical CF attrs onto whatever station vars exist in ``ds``.
|
|
480
|
-
Unconditional ``update`` is safe: cfdb's attrs finalizer writes to the store only when the
|
|
481
|
-
attrs actually change, so re-running on every merge dirties nothing and re-uploads nothing."""
|
|
482
|
-
for var, attrs in _STATION_VAR_ATTRS.items():
|
|
483
|
-
if var in ds:
|
|
484
|
-
ds[var].attrs.update(attrs)
|
|
485
|
-
|
|
486
|
-
|
|
487
297
|
def build_local(
|
|
488
298
|
path,
|
|
489
299
|
meta,
|
|
@@ -16,11 +16,15 @@ dependencies = [
|
|
|
16
16
|
# >=0.1.4 is a HARD floor, not hygiene: tsortho calls envlib.canonical_station_point,
|
|
17
17
|
# which does not exist before 0.1.4 — an older envlib makes EVERY ts_ortho build and
|
|
18
18
|
# merge die with AttributeError in _points_ids_names.
|
|
19
|
-
|
|
19
|
+
# >=0.1.6 is a HARD floor: tsforecast calls envlib.validate_dataset, the public catalogue-free
|
|
20
|
+
# validation entry point, which does not exist before it. Raised in the SAME commit as the code
|
|
21
|
+
# that needs it -- 0.1.5 satisfies the old ">=0.1.5" floor, so an in-place upgrade would keep it
|
|
22
|
+
# and the failure would surface as an AttributeError far from its cause.
|
|
23
|
+
"envlib>=0.1.6",
|
|
20
24
|
# >=0.9.4 is a HARD floor: older cfdb fabricates values when its packed encoder meets
|
|
21
25
|
# NaN/out-of-range data (cfdb changelog 0.9.4); tsortho also enforces this at runtime.
|
|
22
|
-
"cfdb>=0.9.
|
|
23
|
-
"ebooklet>=0.10.
|
|
26
|
+
"cfdb>=0.9.5",
|
|
27
|
+
"ebooklet>=0.10.5",
|
|
24
28
|
"numpy",
|
|
25
29
|
"shapely>=2.0",
|
|
26
30
|
"sentry-sdk",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|