envlib 0.1.3__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
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: envlib
3
- Version: 0.1.3
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
@@ -0,0 +1,17 @@
1
+ """envlib: a distributed database and catalogue for environmental data."""
2
+
3
+ from envlib import vocabularies
4
+ from envlib.catalogue import Catalogue, DatasetRef
5
+ from envlib.metadata import Metadata, ValidationError, canonical_station_point, compute_station_id
6
+
7
+ __version__ = '0.1.5'
8
+
9
+ __all__ = [
10
+ 'Catalogue',
11
+ 'DatasetRef',
12
+ 'Metadata',
13
+ 'ValidationError',
14
+ 'canonical_station_point',
15
+ 'compute_station_id',
16
+ 'vocabularies',
17
+ ]
@@ -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,):
@@ -362,10 +501,16 @@ def _check_stations(ds):
362
501
  stored = [str(v) for v in sid_var.data]
363
502
  if stored != expected:
364
503
  first_bad = next(i for i, (s, e) in enumerate(zip(stored, expected, strict=True)) if s != e)
504
+ bad_point = points[first_bad]
365
505
  msg = (
366
506
  f'{STATION_ID_VAR!r} values do not match the envlib derivation (first mismatch at index '
367
- f'{first_bad}: stored {stored[first_bad]!r}, derived {expected[first_bad]!r}). '
368
- f'Use envlib.compute_station_id on the EPSG:4326 station points.'
507
+ f'{first_bad}: stored {stored[first_bad]!r}, derived {expected[first_bad]!r} from the '
508
+ f'STORED geometry ({bad_point.x}, {bad_point.y})). The stored GEOMETRY is the usual '
509
+ f'culprit here, not the id: a store may re-round a point as it writes it (cfdb encodes '
510
+ f'point coordinates at 5 decimal places), so a point that derived the stored id before '
511
+ f'the write no longer derives it after. Pass station points through '
512
+ f'envlib.canonical_station_point BEFORE writing them to the geometry coordinate, so '
513
+ f'what is stored is already canonical and the round-trip is stable.'
369
514
  )
370
515
  raise ValidationError(msg)
371
516
 
@@ -433,7 +578,10 @@ def _validate_dataset(ds, *, validate_cv: bool) -> dict:
433
578
  msg = f'declared ancillary variable {name!r} is not a data variable in the dataset.'
434
579
  raise ValidationError(msg)
435
580
 
436
- 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:
437
585
  _check_stations(ds)
438
586
 
439
587
  state = _extract_state(ds, meta)
@@ -917,6 +1065,23 @@ class Catalogue:
917
1065
  with ebooklet.open_rcg(rcg_conn, self._rcg_cache_path(rcg_conn), flag='c') as rcg:
918
1066
  existing = rcg.get(dataset_version_id)
919
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
+
920
1085
  now = _utc_now_iso()
921
1086
  user_meta = _build_user_meta(result, member_conn)
922
1087
  user_meta['created_at'] = existing_meta.get('created_at') or now
@@ -250,13 +250,30 @@ def _hash_fields(field_values) -> str:
250
250
  return blake2b(joined.encode('utf-8'), digest_size=12).hexdigest()
251
251
 
252
252
 
253
- def compute_station_id(geometry) -> str:
254
- """Deterministic station id from a shapely Point in EPSG:4326.
255
-
256
- tethys-compatible derivation: z stripped if present; WKT round-trip with
257
- ``rounding_precision=5`` (~1 m at the equator); signed zero collapsed
258
- (``-0.0`` -> ``0.0``, reachable after reprojection); explicit little-endian
259
- WKB; keyless blake2b-12 hex. Same x/y at different z share a station_id.
253
+ def canonical_station_point(geometry) -> shapely.Point:
254
+ """The canonical EPSG:4326 Point whose WKB :func:`compute_station_id` hashes.
255
+
256
+ z stripped if present; WKT round-trip with ``rounding_precision=5`` (~1 m at
257
+ the equator); signed zero collapsed (``-0.0`` -> ``0.0``, reachable after
258
+ reprojection). Same validation, and the same ``ValidationError``, as
259
+ :func:`compute_station_id` — a producer wants a bad geometry rejected here
260
+ rather than one step later.
261
+
262
+ **Producers must STORE this point, not the raw one.** A store that re-rounds
263
+ the geometry its own way will otherwise hold a point that no longer derives
264
+ the ``station_id`` stored beside it, and the dataset becomes unpublishable.
265
+ cfdb is exactly such a store: it encodes point coordinates with
266
+ ``shapely.to_wkt(..., rounding_precision=5)``, whose ``trim=True`` default
267
+ rounds the shortest decimal *string* half-to-even, while the derivation here
268
+ uses ``wkt.dumps`` (``trim=False``), which rounds the underlying *binary*
269
+ value. The two disagree on roughly 9% of coordinates given to 6 decimal
270
+ places — every case being an ordinate whose shortest representation ends in
271
+ a trailing '5' past the 5th decimal. Passing a point through this function
272
+ first makes the round-trip a fixed point, because a canonical point has no
273
+ 6th decimal left to round. (envlib 0.1.4; found on a live publish failure,
274
+ 2026-08-24.)
275
+
276
+ Idempotent: ``canonical_station_point(canonical_station_point(p))`` is ``p``.
260
277
  """
261
278
  if not isinstance(geometry, shapely.Point):
262
279
  msg = f'station geometry must be a shapely Point (v1 supports Points only), not {type(geometry).__name__}.'
@@ -272,7 +289,22 @@ def compute_station_id(geometry) -> str:
272
289
  if geometry.has_z:
273
290
  geometry = shapely.Point(geometry.x, geometry.y)
274
291
  rounded = cast('shapely.Point', wkt.loads(wkt.dumps(geometry, rounding_precision=5)))
275
- canonical_point = shapely.Point(rounded.x + 0.0, rounded.y + 0.0)
292
+ return shapely.Point(rounded.x + 0.0, rounded.y + 0.0)
293
+
294
+
295
+ def compute_station_id(geometry) -> str:
296
+ """Deterministic station id from a shapely Point in EPSG:4326.
297
+
298
+ tethys-compatible derivation: z stripped if present; WKT round-trip with
299
+ ``rounding_precision=5`` (~1 m at the equator); signed zero collapsed
300
+ (``-0.0`` -> ``0.0``, reachable after reprojection); explicit little-endian
301
+ WKB; keyless blake2b-12 hex. Same x/y at different z share a station_id.
302
+
303
+ The canonicalization is :func:`canonical_station_point`; this hashes its WKB.
304
+ Splitting the two moved no id (verified against 0.1.3 over ~143,000 points
305
+ in review round ``envlib-stationid-1``, including exception parity).
306
+ """
307
+ canonical_point = canonical_station_point(geometry)
276
308
  return blake2b(shapely.to_wkb(canonical_point, byte_order=1), digest_size=12).hexdigest()
277
309
 
278
310
 
@@ -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",
@@ -1,9 +0,0 @@
1
- """envlib: a distributed database and catalogue for environmental data."""
2
-
3
- from envlib import vocabularies
4
- from envlib.catalogue import Catalogue, DatasetRef
5
- from envlib.metadata import Metadata, ValidationError, compute_station_id
6
-
7
- __version__ = '0.1.3'
8
-
9
- __all__ = ['Catalogue', 'DatasetRef', 'Metadata', 'ValidationError', 'compute_station_id', 'vocabularies']
File without changes
File without changes
File without changes