envlib 0.1.4__tar.gz → 0.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: envlib
3
- Version: 0.1.4
3
+ Version: 0.1.5
4
4
  Summary: The environmental library
5
5
  Project-URL: Documentation, https://envlib.github.io/envlib/
6
6
  Project-URL: Source, https://github.com/envlib/envlib
@@ -9,7 +9,7 @@ License-File: LICENSE
9
9
  Classifier: Programming Language :: Python :: 3 :: Only
10
10
  Requires-Python: >=3.10
11
11
  Requires-Dist: booklet>=0.12.6
12
- Requires-Dist: cfdb>=0.9.1
12
+ Requires-Dist: cfdb>=0.9.6
13
13
  Requires-Dist: ebooklet>=0.10.3
14
14
  Requires-Dist: pyproj
15
15
  Requires-Dist: shapely>=2.0
@@ -4,7 +4,7 @@ from envlib import vocabularies
4
4
  from envlib.catalogue import Catalogue, DatasetRef
5
5
  from envlib.metadata import Metadata, ValidationError, canonical_station_point, compute_station_id
6
6
 
7
- __version__ = '0.1.4'
7
+ __version__ = '0.1.5'
8
8
 
9
9
  __all__ = [
10
10
  'Catalogue',
@@ -19,6 +19,7 @@ from hashlib import blake2b
19
19
 
20
20
  import cfdb
21
21
  import ebooklet
22
+ import numpy as np
22
23
  import pyproj
23
24
  import shapely
24
25
 
@@ -41,6 +42,15 @@ DEFAULT_CACHE_DIR = '~/.envlib/cache'
41
42
 
42
43
  STATION_ID_VAR = 'station_id'
43
44
 
45
+ # cfdb dataset types, grouped by the structure envlib cares about. Defined once because every
46
+ # check below used exact string equality against a single value, which is how a new dataset type
47
+ # silently skips a guard -- most dangerously _check_stations.
48
+ GRID_TYPES = ('grid', 'grid_forecast')
49
+ TS_TYPES = ('ts_ortho', 'ts_forecast')
50
+ FORECAST_TYPES = ('ts_forecast', 'grid_forecast')
51
+ FORECAST_REF_COORD = 'forecast_reference_time'
52
+ FORECAST_PERIOD_COORD = 'forecast_period'
53
+
44
54
  _HEX24_RE = re.compile(r'[0-9a-f]{24}')
45
55
  _EPSG_4326 = pyproj.CRS.from_epsg(4326)
46
56
  _FULL_CIRCLE_DEG = 360.0
@@ -256,27 +266,142 @@ def _reproject_points(points, crs) -> list:
256
266
  return out
257
267
 
258
268
 
269
+ # CF time-unit names -> numpy datetime64/timedelta64 unit codes. CF's canonical unit for
270
+ # forecast_period is seconds, but any of these is legal and producers use whatever matches
271
+ # their lead resolution.
272
+ #
273
+ # Bare 'm' is deliberately ABSENT: in CF/udunits it means metres, so accepting it as minutes
274
+ # would silently misread a lead by 60x. Producers must write 'min'.
275
+ #
276
+ # Month and year are absent because numpy refuses to add them to a datetime64[m] at all
277
+ # (UFuncTypeError) -- they are not fixed-length. Week IS fixed-length and numpy supports it;
278
+ # it is omitted only because no forecast product uses weekly leads, and the refusal is loud.
279
+ _CF_TIME_UNITS = {
280
+ 'second': 's', 'seconds': 's', 'sec': 's', 'secs': 's', 's': 's',
281
+ 'minute': 'm', 'minutes': 'm', 'min': 'm', 'mins': 'm',
282
+ 'hour': 'h', 'hours': 'h', 'hr': 'h', 'hrs': 'h', 'h': 'h',
283
+ 'day': 'D', 'days': 'D', 'd': 'D',
284
+ }
285
+
286
+
287
+ def _cf_unit_to_np(units: str) -> str:
288
+ """Map a CF time-unit name to a numpy timedelta64 unit code."""
289
+ key = str(units).strip().lower()
290
+ if key not in _CF_TIME_UNITS:
291
+ msg = (
292
+ f'unsupported time unit {units!r}; expected one of '
293
+ f'{sorted(set(_CF_TIME_UNITS))}.'
294
+ )
295
+ raise ValueError(msg)
296
+ return _CF_TIME_UNITS[key]
297
+
298
+
299
+ def _forecast_time_range(ds) -> tuple:
300
+ """
301
+ VALID-time bounds for a forecast dataset: first init -> last init + longest lead.
302
+
303
+ Valid rather than init range because these two fields feed exactly one consumer --
304
+ _time_overlaps, behind Catalogue.query(start_date=, end_date=) -- and a user asking "does
305
+ this cover my period?" means valid time. For measured data valid time IS observation time,
306
+ so the catalogue stays semantically uniform. (Consequence: time_end sits in the future and
307
+ corresponds to no coordinate value in the file; it is a bound, not an index.)
308
+
309
+ WARNING -- the arithmetic below must NOT be written as `frt[-1] + lead.max()`. cfdb has no
310
+ timedelta dtype, so forecast_period is a bare integer and numpy evaluates the sum in the
311
+ DATETIME's storage unit: against a datetime64[m] axis that silently adds minutes instead of
312
+ hours. The units attr is the only thing that says what a lead value means.
313
+ """
314
+ for name in (FORECAST_REF_COORD, FORECAST_PERIOD_COORD):
315
+ if name not in ds.coord_names:
316
+ msg = (
317
+ f'{ds.dataset_type!r} datasets must have a {name!r} coordinate; '
318
+ f'got {tuple(ds.coord_names)}.'
319
+ )
320
+ raise ValidationError(msg)
321
+
322
+ frt = ds[FORECAST_REF_COORD]
323
+ if frt.dtype.kind != 'M':
324
+ msg = f'{FORECAST_REF_COORD!r} must be datetime64, not {frt.dtype.name!r}.'
325
+ raise ValidationError(msg)
326
+ frt_values = frt.data
327
+ if len(frt_values) == 0:
328
+ msg = f'{FORECAST_REF_COORD!r} must have at least one value.'
329
+ raise ValidationError(msg)
330
+
331
+ period = ds[FORECAST_PERIOD_COORD]
332
+ period_values = period.data
333
+ if len(period_values) == 0:
334
+ msg = f'{FORECAST_PERIOD_COORD!r} must have at least one value.'
335
+ raise ValidationError(msg)
336
+
337
+ units = period.attrs.get('units')
338
+ if not units:
339
+ msg = (
340
+ f'{FORECAST_PERIOD_COORD!r} must declare a CF "units" attribute (e.g. "h"). '
341
+ f'Without it the lead time is a dimensionless integer and the valid-time range '
342
+ f'cannot be computed.'
343
+ )
344
+ raise ValidationError(msg)
345
+
346
+ ## Integer only. A float lead silently truncates through int() -- a 1.5 h lead becomes
347
+ ## 1 h and the catalogue understates the range by 30 minutes with no warning. cfdb-vars
348
+ ## declares this coordinate int32; a producer using the generic constructor can still
349
+ ## make it float, so refuse loudly rather than round.
350
+ if period_values.dtype.kind not in ('i', 'u'):
351
+ msg = (
352
+ f'{FORECAST_PERIOD_COORD!r} must be an integer dtype, not '
353
+ f'{period_values.dtype.name!r}. A fractional lead cannot be represented exactly '
354
+ f'against the {FORECAST_REF_COORD!r} axis and would be silently truncated.'
355
+ )
356
+ raise ValidationError(msg)
357
+
358
+ try:
359
+ np_unit = _cf_unit_to_np(units)
360
+ min_lead = np.timedelta64(int(np.min(period_values)), np_unit)
361
+ max_lead = np.timedelta64(int(np.max(period_values)), np_unit)
362
+ except (TypeError, ValueError) as err:
363
+ msg = f'could not interpret {FORECAST_PERIOD_COORD!r} units {units!r}: {err}'
364
+ raise ValidationError(msg) from err
365
+
366
+ ## BOTH ends come from the leads, not just the end. Using frt[0] alone was wrong in two
367
+ ## ways: a negative lead (an assimilation window) INVERTED the range -- start > end, which
368
+ ## _time_overlaps then answers nonsensically -- and a day-2-only product (leads 24-48 h)
369
+ ## claimed a full extra day of coverage that does not exist in the file.
370
+ return (
371
+ _dt64_to_iso(frt_values[0] + min_lead),
372
+ _dt64_to_iso(frt_values[-1] + max_lead),
373
+ )
374
+
375
+
259
376
  def _extract_state(ds, meta: Metadata) -> dict:
260
377
  """Extract State Metadata (bbox, time range, steps, dataset_type) from an open dataset."""
261
378
  dataset_type = ds.dataset_type
262
379
  crs = ds.crs
263
380
 
264
- time_coord = ds.get('time') if 'time' in ds.coord_names else None
265
- if time_coord is None or len(time_coord.data) == 0:
266
- msg = 'every envlib dataset must have a time coordinate with at least one value.'
267
- raise ValidationError(msg)
268
- if time_coord.dtype.kind != 'M':
269
- msg = f'the time coordinate must be datetime64, not {time_coord.dtype.name!r}.'
270
- raise ValidationError(msg)
271
- time_values = time_coord.data
381
+ if dataset_type in FORECAST_TYPES:
382
+ time_start, time_end = _forecast_time_range(ds)
383
+ else:
384
+ time_coord = ds.get('time') if 'time' in ds.coord_names else None
385
+ if time_coord is None or len(time_coord.data) == 0:
386
+ msg = 'every envlib dataset must have a time coordinate with at least one value.'
387
+ raise ValidationError(msg)
388
+ if time_coord.dtype.kind != 'M':
389
+ msg = f'the time coordinate must be datetime64, not {time_coord.dtype.name!r}.'
390
+ raise ValidationError(msg)
391
+ time_values = time_coord.data
392
+ time_start = _dt64_to_iso(time_values[0])
393
+ time_end = _dt64_to_iso(time_values[-1])
394
+
272
395
  state: dict = {
273
396
  'dataset_type': dataset_type,
274
- 'time_start': _dt64_to_iso(time_values[0]),
275
- 'time_end': _dt64_to_iso(time_values[-1]),
397
+ 'time_start': time_start,
398
+ 'time_end': time_end,
276
399
  }
277
400
 
278
401
  x_step = y_step = None
279
- if dataset_type == 'grid':
402
+ ## Both grid types: the else-branch below assumes a station geometry coordinate, so exact
403
+ ## equality here would route grid_forecast into it and fail with a message about ts_ortho.
404
+ if dataset_type in GRID_TYPES:
280
405
  x_coord = _coord_by_axis(ds, 'x')
281
406
  y_coord = _coord_by_axis(ds, 'y')
282
407
  if x_coord is None or y_coord is None:
@@ -297,7 +422,7 @@ def _extract_state(ds, meta: Metadata) -> dict:
297
422
  geom_coord = _geometry_coord(ds)
298
423
  points = geom_coord.data
299
424
  if len(points) == 0:
300
- msg = 'ts_ortho datasets must have at least one station point.'
425
+ msg = f'{dataset_type} datasets must have at least one station point.'
301
426
  raise ValidationError(msg)
302
427
  xs = [p.x for p in points]
303
428
  ys = [p.y for p in points]
@@ -324,8 +449,22 @@ def _extract_state(ds, meta: Metadata) -> dict:
324
449
  state['y_step'] = y_step
325
450
 
326
451
  # identity cross-checks that involve state
327
- if dataset_type == 'ts_ortho' and meta.spatial_resolution != 'point':
328
- msg = "ts_ortho datasets must use spatial_resolution='point'."
452
+ if dataset_type in TS_TYPES and meta.spatial_resolution != 'point':
453
+ msg = f"{dataset_type} datasets must use spatial_resolution='point'."
454
+ raise ValidationError(msg)
455
+
456
+ ## dataset_type is STATE metadata, not identity -- it is not one of the 11 hashed fields,
457
+ ## so it cannot distinguish two datasets on its own. method IS an identity field and the
458
+ ## vocabulary already carries 'forecast', so requiring it here is what stops a forecast
459
+ ## dataset from hashing to the same dataset_version_id as its measured counterpart.
460
+ ## (It does NOT separate ts_forecast from grid_forecast -- that is handled at the write
461
+ ## path, in Catalogue._upsert_entry.)
462
+ if dataset_type in FORECAST_TYPES and meta.method != 'forecast':
463
+ msg = (
464
+ f"{dataset_type} datasets must use method='forecast' (got {meta.method!r}); "
465
+ f"otherwise a forecast dataset and its measured counterpart collide on "
466
+ f"dataset_version_id."
467
+ )
329
468
  raise ValidationError(msg)
330
469
  return state
331
470
 
@@ -334,8 +473,8 @@ def _geometry_coord(ds):
334
473
  coord = _coord_by_axis(ds, 'xy')
335
474
  if coord is None:
336
475
  msg = (
337
- "ts_ortho datasets must have a point geometry coordinate with the 'xy' axis "
338
- '(create.coord.point + create.crs.from_user_input(xy_coord=...)).'
476
+ f"{ds.dataset_type} datasets must have a point geometry coordinate with the 'xy' "
477
+ 'axis (create.coord.point + create.crs.from_user_input(xy_coord=...)).'
339
478
  )
340
479
  raise ValidationError(msg)
341
480
  if coord.dtype.kind != 'G':
@@ -345,10 +484,10 @@ def _geometry_coord(ds):
345
484
 
346
485
 
347
486
  def _check_stations(ds):
348
- """ts_ortho: station_id attribute variable must exist and match recomputation."""
487
+ """ts_ortho / ts_forecast: station_id must exist and match recomputation from the stored geometry."""
349
488
  geom_coord = _geometry_coord(ds)
350
489
  if STATION_ID_VAR not in ds.data_var_names:
351
- msg = f'ts_ortho datasets must carry a {STATION_ID_VAR!r} station attribute variable (shape (geometry,)).'
490
+ msg = f'{ds.dataset_type} datasets must carry a {STATION_ID_VAR!r} station attribute variable (shape (geometry,)).'
352
491
  raise ValidationError(msg)
353
492
  sid_var = ds[STATION_ID_VAR]
354
493
  if tuple(sid_var.coord_names) != (geom_coord.name,):
@@ -439,7 +578,10 @@ def _validate_dataset(ds, *, validate_cv: bool) -> dict:
439
578
  msg = f'declared ancillary variable {name!r} is not a data variable in the dataset.'
440
579
  raise ValidationError(msg)
441
580
 
442
- if ds.dataset_type == 'ts_ortho':
581
+ ## Both ts types. This is the guard the forecast<->measured join depends on: it verifies
582
+ ## each station_id is reproducible from the geometry stored beside it, and that join is
583
+ ## nothing but those two hashes colliding at 5 dp.
584
+ if ds.dataset_type in TS_TYPES:
443
585
  _check_stations(ds)
444
586
 
445
587
  state = _extract_state(ds, meta)
@@ -923,6 +1065,23 @@ class Catalogue:
923
1065
  with ebooklet.open_rcg(rcg_conn, self._rcg_cache_path(rcg_conn), flag='c') as rcg:
924
1066
  existing = rcg.get(dataset_version_id)
925
1067
  existing_meta = (existing or {}).get('user_meta') or {}
1068
+ ## dataset_type is not an identity field, so two datasets differing ONLY by type
1069
+ ## hash to the same key and this upsert would silently replace one with the other
1070
+ ## -- bbox, time range and all. Reachable today with a plain grid and ts_ortho
1071
+ ## pair, not just with the forecast types. Refuse instead: a genuine type change
1072
+ ## is a different dataset and should be deregistered first.
1073
+ existing_type = existing_meta.get('dataset_type')
1074
+ incoming_type = result['state'].get('dataset_type')
1075
+ if existing is not None and existing_type and existing_type != incoming_type:
1076
+ msg = (
1077
+ f'catalogue entry {dataset_version_id} is already registered with '
1078
+ f'dataset_type {existing_type!r}, but this dataset is {incoming_type!r}. '
1079
+ f'These share a dataset_version_id because dataset_type is not an identity '
1080
+ f'field. Deregister the existing entry first, or change an identity field '
1081
+ f'(method, product_code or version) so the two are distinct.'
1082
+ )
1083
+ raise ValidationError(msg)
1084
+
926
1085
  now = _utc_now_iso()
927
1086
  user_meta = _build_user_meta(result, member_conn)
928
1087
  user_meta['created_at'] = existing_meta.get('created_at') or now
@@ -11,7 +11,12 @@ classifiers = [
11
11
  ]
12
12
  requires-python = ">=3.10"
13
13
  dependencies = [
14
- "cfdb>=0.9.1",
14
+ # HARD floor, not hygiene: the forecast dataset types (ts_forecast / grid_forecast) do not
15
+ # exist before cfdb 0.9.6, so _extract_state's forecast branch is unreachable and any such
16
+ # file fails to open at all. No runtime guard accompanies this one, deliberately -- unlike
17
+ # the packed-encoder floor in envlib-ingest-base, an older cfdb cannot silently mis-handle a
18
+ # forecast dataset; it raises TypeError before touching data.
19
+ "cfdb>=0.9.6",
15
20
  "ebooklet>=0.10.3",
16
21
  "booklet>=0.12.6",
17
22
  "pyproj",
File without changes
File without changes
File without changes
File without changes