envlib 0.1.7__tar.gz → 0.1.9__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.7
3
+ Version: 0.1.9
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,8 +9,8 @@ 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.10.0
13
- Requires-Dist: ebooklet>=0.10.5
12
+ Requires-Dist: cfdb>=0.11.0
13
+ Requires-Dist: ebooklet>=0.11.0
14
14
  Requires-Dist: pyproj
15
15
  Requires-Dist: shapely>=2.0
16
16
  Requires-Dist: urllib3
@@ -55,30 +55,31 @@ pip install envlib
55
55
 
56
56
  ## Quick example
57
57
 
58
+ <!-- skip: start if(not docs_live, reason="reads the live public commons") -->
59
+
58
60
  ```python
59
- import envlib
60
-
61
- # The public envlib catalogue — zero config, no credentials
62
- # (until it's hosted: Catalogue(remotes=['https://.../catalogue.rcg']))
63
- cat = envlib.Catalogue()
64
-
65
- # What's in it?
66
- cat.variables # ['precipitation', 'streamflow', 'temperature']
67
- cat.owners # ['ecan', 'ecmwf', 'niwa']
68
-
69
- # Find the latest version of each matching dataset
70
- results = cat.query(
71
- variable='temperature',
72
- feature='atmosphere',
73
- bbox=[166, -47, 179, -34],
74
- start_date='2020-01-01',
75
- )
76
-
77
- # Open one as a cfdb dataset and read it
78
- ds = results[0].open()
79
- temp = ds['temperature']
61
+ >>> import envlib
62
+ >>> cat = envlib.Catalogue() # the public envlib catalogue: zero config, no credentials
63
+ >>> # What's in it? (the public commons in November 2026; it grows)
64
+ >>> cat.variables # doctest: +ELLIPSIS
65
+ ['altitude', 'barometric_pressure', ..., 'temperature', ..., 'wind_speed']
66
+ >>> cat.owners
67
+ ['ecan', 'esa', 'uc']
68
+ >>> # Find the latest version of each matching dataset
69
+ >>> results = cat.query(
70
+ ... variable='temperature',
71
+ ... feature='atmosphere',
72
+ ... bbox=[166, -47, 179, -34],
73
+ ... start_date='2020-01-01',
74
+ ... )
75
+ >>> # Open one as a cfdb dataset and read the last day of it
76
+ >>> ds = results[0].open()
77
+ >>> last_day = ds['temperature'][-24:].data
78
+ >>> ds.close()
80
79
  ```
81
80
 
81
+ <!-- skip: end -->
82
+
82
83
  Producing data is the same library in the other direction: build a cfdb file, attach `envlib.Metadata`, and `cat.publish(...)` it — see the [documentation](https://envlib.github.io/envlib/) for the full guide.
83
84
 
84
85
  Changes between releases are tracked in the [changelog](https://envlib.github.io/envlib/changelog/).
@@ -37,30 +37,31 @@ pip install envlib
37
37
 
38
38
  ## Quick example
39
39
 
40
+ <!-- skip: start if(not docs_live, reason="reads the live public commons") -->
41
+
40
42
  ```python
41
- import envlib
42
-
43
- # The public envlib catalogue — zero config, no credentials
44
- # (until it's hosted: Catalogue(remotes=['https://.../catalogue.rcg']))
45
- cat = envlib.Catalogue()
46
-
47
- # What's in it?
48
- cat.variables # ['precipitation', 'streamflow', 'temperature']
49
- cat.owners # ['ecan', 'ecmwf', 'niwa']
50
-
51
- # Find the latest version of each matching dataset
52
- results = cat.query(
53
- variable='temperature',
54
- feature='atmosphere',
55
- bbox=[166, -47, 179, -34],
56
- start_date='2020-01-01',
57
- )
58
-
59
- # Open one as a cfdb dataset and read it
60
- ds = results[0].open()
61
- temp = ds['temperature']
43
+ >>> import envlib
44
+ >>> cat = envlib.Catalogue() # the public envlib catalogue: zero config, no credentials
45
+ >>> # What's in it? (the public commons in November 2026; it grows)
46
+ >>> cat.variables # doctest: +ELLIPSIS
47
+ ['altitude', 'barometric_pressure', ..., 'temperature', ..., 'wind_speed']
48
+ >>> cat.owners
49
+ ['ecan', 'esa', 'uc']
50
+ >>> # Find the latest version of each matching dataset
51
+ >>> results = cat.query(
52
+ ... variable='temperature',
53
+ ... feature='atmosphere',
54
+ ... bbox=[166, -47, 179, -34],
55
+ ... start_date='2020-01-01',
56
+ ... )
57
+ >>> # Open one as a cfdb dataset and read the last day of it
58
+ >>> ds = results[0].open()
59
+ >>> last_day = ds['temperature'][-24:].data
60
+ >>> ds.close()
62
61
  ```
63
62
 
63
+ <!-- skip: end -->
64
+
64
65
  Producing data is the same library in the other direction: build a cfdb file, attach `envlib.Metadata`, and `cat.publish(...)` it — see the [documentation](https://envlib.github.io/envlib/) for the full guide.
65
66
 
66
67
  Changes between releases are tracked in the [changelog](https://envlib.github.io/envlib/changelog/).
@@ -0,0 +1,39 @@
1
+ """envlib: a distributed database and catalogue for environmental data."""
2
+
3
+ from envlib import vocabularies
4
+ from envlib.catalogue import (
5
+ QUERYABLE_FIELDS,
6
+ Catalogue,
7
+ DatasetRef,
8
+ distinct_values,
9
+ latest_per_dataset,
10
+ match_entries,
11
+ validate_dataset,
12
+ version_key,
13
+ )
14
+ from envlib.metadata import (
15
+ Metadata,
16
+ PublishIntegrityError,
17
+ ValidationError,
18
+ canonical_station_point,
19
+ compute_station_id,
20
+ )
21
+
22
+ __version__ = '0.1.9'
23
+
24
+ __all__ = [
25
+ 'QUERYABLE_FIELDS',
26
+ 'Catalogue',
27
+ 'DatasetRef',
28
+ 'Metadata',
29
+ 'PublishIntegrityError',
30
+ 'ValidationError',
31
+ 'canonical_station_point',
32
+ 'compute_station_id',
33
+ 'distinct_values',
34
+ 'latest_per_dataset',
35
+ 'match_entries',
36
+ 'validate_dataset',
37
+ 'version_key',
38
+ 'vocabularies',
39
+ ]
@@ -15,6 +15,7 @@ import pathlib
15
15
  import re
16
16
  import urllib.parse
17
17
  import warnings
18
+ from collections.abc import Iterable
18
19
  from hashlib import blake2b
19
20
 
20
21
  import cfdb
@@ -22,6 +23,7 @@ import ebooklet
22
23
  import numpy as np
23
24
  import pyproj
24
25
  import shapely
26
+ import shapely.affinity
25
27
 
26
28
  from envlib import vocabularies
27
29
  from envlib.metadata import (
@@ -42,6 +44,10 @@ DEFAULT_CACHE_DIR = '~/.envlib/cache'
42
44
 
43
45
  STATION_ID_VAR = 'station_id'
44
46
 
47
+ # "Argument not given" for publish()'s group_bytes: only a given value is
48
+ # forwarded, so ebooklet's own default applies otherwise.
49
+ _NOT_GIVEN = object()
50
+
45
51
  # cfdb dataset types, grouped by the structure envlib cares about. Defined once because every
46
52
  # check below used exact string equality against a single value, which is how a new dataset type
47
53
  # silently skips a guard -- most dangerously _check_stations.
@@ -52,10 +58,13 @@ FORECAST_REF_COORD = 'forecast_reference_time'
52
58
  FORECAST_PERIOD_COORD = 'forecast_period'
53
59
 
54
60
  _HEX24_RE = re.compile(r'[0-9a-f]{24}')
61
+ _FRACTION_RE = re.compile(r'(?<=:\d\d)\.(\d{1,5})(?!\d)')
55
62
  _EPSG_4326 = pyproj.CRS.from_epsg(4326)
56
63
  _FULL_CIRCLE_DEG = 360.0
64
+ _BBOX_LEN = 4 # w, s, e, n
65
+ _MAX_LAT = 90.0
57
66
 
58
- _QUERYABLE_FIELDS = frozenset(IDENTITY_FIELDS) | {'license', 'dataset_type', 'dataset_version_id', 'dataset_id'}
67
+ QUERYABLE_FIELDS = frozenset(IDENTITY_FIELDS) | {'license', 'dataset_type', 'dataset_version_id', 'dataset_id'}
59
68
 
60
69
 
61
70
  def _raise_on_push_failure(result, context: str):
@@ -123,12 +132,21 @@ def _dt64_to_iso(value) -> str:
123
132
  return dt.strftime('%Y-%m-%dT%H:%M:%S') + f'.{frac}Z'
124
133
 
125
134
 
135
+ def _pad_fraction(text: str) -> str:
136
+ """Pad a 1-5 digit fractional second to 6 digits.
137
+
138
+ `_dt64_to_iso` strips trailing zeros ('...00.5Z'), and Python 3.10's fromisoformat accepts
139
+ only 3 or 6 fractional digits (plan review edr-api-plan-5).
140
+ """
141
+ return _FRACTION_RE.sub(lambda m: '.' + m.group(1).ljust(6, '0'), text, count=1)
142
+
143
+
126
144
  def _parse_iso(value) -> datetime.datetime:
127
145
  """Parse an ISO8601 string (Z-suffixed or naive-as-UTC) or pass a datetime through."""
128
146
  if isinstance(value, datetime.datetime):
129
147
  dt = value
130
148
  else:
131
- dt = datetime.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
149
+ dt = datetime.datetime.fromisoformat(_pad_fraction(str(value).replace('Z', '+00:00')))
132
150
  if dt.tzinfo is None:
133
151
  dt = dt.replace(tzinfo=datetime.timezone.utc)
134
152
  return dt
@@ -204,6 +222,61 @@ def _wrap_lon_extent(west: float, east: float, x_step: float | None) -> tuple:
204
222
  return w, e
205
223
 
206
224
 
225
+ def _smallest_lon_arc(lons) -> tuple:
226
+ """(west, east) of the shortest arc of longitude holding every value in `lons`.
227
+
228
+ The arc is the circle minus its largest gap between neighbouring longitudes, taken on the
229
+ longitudes normalised to [-180, 180), so 0..360 input and a station at exactly 180 are placed
230
+ correctly. Each end comes back as the value given (a longitude within [-180, 180] unchanged).
231
+ When the largest gap is the one across 180 (or ties with it), west <= east after the wrap;
232
+ otherwise the arc crosses 180 (west > east, the GeoJSON convention).
233
+ """
234
+ normalised = {}
235
+ for lon in lons:
236
+ normalised.setdefault((float(lon) + 180.0) % 360.0 - 180.0, float(lon))
237
+ ordered = sorted(normalised)
238
+ if len(ordered) == 1:
239
+ lon = normalised[ordered[0]]
240
+ return lon, lon
241
+ gap, i = max((ordered[k + 1] - ordered[k], k) for k in range(len(ordered) - 1))
242
+ across_180 = ordered[0] + _FULL_CIRCLE_DEG - ordered[-1]
243
+ if across_180 >= gap:
244
+ return normalised[ordered[0]], normalised[ordered[-1]]
245
+ return normalised[ordered[i + 1]], normalised[ordered[i]]
246
+
247
+
248
+ def _query_bbox(bbox) -> list:
249
+ """A query bbox in envlib's convention, or ValueError.
250
+
251
+ Accepts (west, south, east, north) with longitudes in -360..360, so 0..360 boxes work as they do
252
+ in a ``geometry`` (code review edr-api-code-5): a box whose east lies up to 360 degrees east of
253
+ its west, taken mod 360. A full-width box becomes -180..180; otherwise an edge outside
254
+ [-180, 180] is wrapped into it, so west > east means the box crosses 180.
255
+ """
256
+ try:
257
+ w, s, e, n = (float(v) for v in bbox)
258
+ except (TypeError, ValueError) as err:
259
+ msg = f'bbox must be four numbers (west, south, east, north); got {bbox!r}.'
260
+ raise ValueError(msg) from err
261
+ if not all(np.isfinite((w, s, e, n))):
262
+ msg = f'bbox values must be finite; got {bbox!r}.'
263
+ raise ValueError(msg)
264
+ if not (-_MAX_LAT <= s <= n <= _MAX_LAT):
265
+ msg = f'bbox latitudes must satisfy -90 <= south <= north <= 90; got {bbox!r}.'
266
+ raise ValueError(msg)
267
+ if abs(w) > _FULL_CIRCLE_DEG or abs(e) > _FULL_CIRCLE_DEG:
268
+ msg = f'bbox longitudes must be within -360..360; got {bbox!r}.'
269
+ raise ValueError(msg)
270
+ width = e - w if w <= e else e - w + _FULL_CIRCLE_DEG
271
+ if not (0.0 <= width <= _FULL_CIRCLE_DEG):
272
+ msg = f'bbox: east must lie 0 to 360 degrees east of west; got {bbox!r}.'
273
+ raise ValueError(msg)
274
+ if width == _FULL_CIRCLE_DEG:
275
+ return [-180.0, s, 180.0, n]
276
+ half = _FULL_CIRCLE_DEG / 2
277
+ return [_wrap_lon(w) if abs(w) > half else w, s, _wrap_lon(e) if abs(e) > half else e, n]
278
+
279
+
207
280
  def _split_bbox(bbox) -> list:
208
281
  """Split an antimeridian-crossing bbox into 1-2 conventional boxes."""
209
282
  min_lon, min_lat, max_lon, max_lat = bbox
@@ -220,8 +293,15 @@ def _bbox_intersects(stored, query) -> bool:
220
293
  return any(_boxes_intersect(s, q) for s in _split_bbox(stored) for q in _split_bbox(query))
221
294
 
222
295
 
223
- def _geometry_intersects(stored, geometry) -> bool:
224
- return any(shapely.box(*part).intersects(geometry) for part in _split_bbox(stored))
296
+ def _geometry_shifts(geometry) -> list:
297
+ """The geometry and its copies 360 degrees east and west, so a geometry drawn in 0..360 (or
298
+ -360..0) longitudes finds what its -180..180 twin finds (plan review edr-api-plan-5)."""
299
+ return [geometry, *(shapely.affinity.translate(geometry, xoff=shift) for shift in (360.0, -360.0))]
300
+
301
+
302
+ def _geometry_intersects(stored, geometries) -> bool:
303
+ """Whether a stored bbox intersects any of `geometries` (from _geometry_shifts)."""
304
+ return any(shapely.box(*part).intersects(g) for part in _split_bbox(stored) for g in geometries)
225
305
 
226
306
 
227
307
  _GEOD = pyproj.Geod(ellps='WGS84')
@@ -399,6 +479,7 @@ def _extract_state(ds, meta: Metadata) -> dict:
399
479
  }
400
480
 
401
481
  x_step = y_step = None
482
+ bounds_crs = crs # the CRS of west/south/east/north below (stations are reprojected first)
402
483
  ## Both grid types: the else-branch below assumes a station geometry coordinate, so exact
403
484
  ## equality here would route grid_forecast into it and fail with a message about ts_ortho.
404
485
  if dataset_type in GRID_TYPES:
@@ -424,16 +505,21 @@ def _extract_state(ds, meta: Metadata) -> dict:
424
505
  if len(points) == 0:
425
506
  msg = f'{dataset_type} datasets must have at least one station point.'
426
507
  raise ValidationError(msg)
427
- xs = [p.x for p in points]
428
- ys = [p.y for p in points]
429
- west, east = float(min(xs)), float(max(xs))
508
+ ## The stations in EPSG:4326 whatever their CRS (as their ids are derived), then the
509
+ ## shortest arc of longitude holding them, crossing 180 when that is shorter: min/max gave a
510
+ ## 350-degree box for Canterbury plus the Chathams (plan review edr-api-plan-5), and the
511
+ ## arc must not depend on the CRS (code review edr-api-code-5).
512
+ stations_4326 = _reproject_points(points, crs)
513
+ west, east = _smallest_lon_arc([p.x for p in stations_4326])
514
+ ys = [p.y for p in stations_4326]
430
515
  south, north = float(min(ys)), float(max(ys))
516
+ bounds_crs = _EPSG_4326
431
517
 
432
- if crs.is_geographic:
518
+ if bounds_crs.is_geographic:
433
519
  # native-geographic source: transform_bounds is an identity no-op for
434
520
  # longitude conventions, so apply envlib's own structure-preserving
435
521
  # wrap (0-360 grids -> [-180, 180] / the crossing convention).
436
- if not crs.equals(_EPSG_4326):
522
+ if not bounds_crs.equals(_EPSG_4326):
437
523
  transformer = pyproj.Transformer.from_crs(crs, _EPSG_4326, always_xy=True)
438
524
  west, south, east, north = transformer.transform_bounds(west, south, east, north, densify_pts=21)
439
525
  min_lon, max_lon = _wrap_lon_extent(west, east, x_step)
@@ -636,7 +722,8 @@ def validate_dataset(dataset, *, validate_cv: bool = True) -> dict:
636
722
  network refresh, neither of which a local build has or wants.
637
723
 
638
724
  Args:
639
- dataset: a path to a local cfdb file, or an ALREADY-OPEN cfdb ``Dataset``/``EDataset``.
725
+ dataset (str | pathlib.Path | cfdb.Dataset | cfdb.EDataset): a path to a local cfdb file,
726
+ or an ALREADY-OPEN cfdb ``Dataset``/``EDataset``.
640
727
  Prefer passing the open object when you have one -- reopening a file that is linked
641
728
  to a remote starts a second session against it, and for an ``EDataset`` the open
642
729
  object also pulls transparently, so extents are read from the whole dataset rather
@@ -822,6 +909,10 @@ class Catalogue:
822
909
  """All catalogue entries as DatasetRef objects."""
823
910
  return [DatasetRef(key, entry, self._cache_dir) for key, entry in self._entries.items()]
824
911
 
912
+ def _metas(self) -> list:
913
+ """Every entry's ``user_meta``, in catalogue order (the same order as :attr:`datasets`)."""
914
+ return [entry.get('user_meta') or {} for entry in self._entries.values()]
915
+
825
916
  # -- value discovery -------------------------------------------------------
826
917
 
827
918
  def distinct(self, field: str, *, counts: bool = False):
@@ -839,17 +930,10 @@ class Catalogue:
839
930
  values, excluding None. When True, return a ``{value: count}``
840
931
  dict that DOES include a None key when some entries lack the
841
932
  field (e.g. datasets with no ``product_code``).
933
+
934
+ Every version is counted. The rules are :func:`distinct_values`'.
842
935
  """
843
- if field not in _QUERYABLE_FIELDS:
844
- msg = f'unknown field {field!r}; queryable fields are {sorted(_QUERYABLE_FIELDS)}.'
845
- raise ValueError(msg)
846
- tally: dict = {}
847
- for entry in self._entries.values():
848
- value = (entry.get('user_meta') or {}).get(field)
849
- tally[value] = tally.get(value, 0) + 1
850
- if counts:
851
- return dict(sorted(tally.items(), key=lambda kv: (kv[0] is None, str(kv[0]))))
852
- return sorted(v for v in tally if v is not None)
936
+ return distinct_values(self._metas(), field, counts=counts)
853
937
 
854
938
  @property
855
939
  def features(self) -> list:
@@ -930,50 +1014,34 @@ class Catalogue:
930
1014
  geometry=None,
931
1015
  start_date=None,
932
1016
  end_date=None,
1017
+ all_versions: bool = False,
933
1018
  **fields,
934
1019
  ) -> list:
935
1020
  """Filter the catalogue; kwargs are AND'd, a list value means any-of.
936
1021
 
937
1022
  Spatial filters (mutually exclusive, EPSG:4326): ``bbox`` (intersects),
938
1023
  ``within_radius`` (((lon, lat), km) great-circle), ``geometry``
939
- (shapely, intersects). Temporal: ``start_date``/``end_date`` overlap
940
- the dataset's time range. Without an explicit ``version=`` kwarg the
941
- latest version (greatest created_at) of each matching dataset is
942
- returned.
1024
+ (shapely, intersects; also tried 360 degrees east and west). Temporal:
1025
+ ``start_date``/``end_date`` overlap the dataset's time range. Without an
1026
+ explicit ``version=`` kwarg, or ``all_versions=True``, the latest version
1027
+ of each matching dataset is returned: the greatest created_at, and on a
1028
+ tie the greater dataset_version_id.
1029
+
1030
+ The rules are :func:`match_entries`'; the results are DatasetRefs in
1031
+ catalogue order.
943
1032
  """
944
- unknown = set(fields) - _QUERYABLE_FIELDS
945
- if unknown:
946
- msg = f'unknown query fields: {sorted(unknown)}; queryable fields are {sorted(_QUERYABLE_FIELDS)}.'
947
- raise ValueError(msg)
948
- spatial_kwargs = (('bbox', bbox), ('within_radius', within_radius), ('geometry', geometry))
949
- spatial = [kw for kw, v in spatial_kwargs if v is not None]
950
- if len(spatial) > 1:
951
- msg = f'spatial filters are mutually exclusive; got {spatial}.'
952
- raise ValueError(msg)
953
-
954
- results = []
955
- for ref in self.datasets:
956
- user_meta = ref.metadata
957
- if not all(_field_matches(user_meta.get(name), wanted) for name, wanted in fields.items()):
958
- continue
959
- stored_bbox = user_meta.get('bbox')
960
- if bbox is not None and (stored_bbox is None or not _bbox_intersects(stored_bbox, bbox)):
961
- continue
962
- if geometry is not None and (stored_bbox is None or not _geometry_intersects(stored_bbox, geometry)):
963
- continue
964
- if within_radius is not None:
965
- (lon, lat), radius_km = within_radius
966
- if stored_bbox is None or not _bbox_within_radius(stored_bbox, lon, lat, radius_km):
967
- continue
968
- if (start_date is not None or end_date is not None) and not _time_overlaps(
969
- user_meta.get('time_start'), user_meta.get('time_end'), start_date, end_date
970
- ):
971
- continue
972
- results.append(ref)
973
-
974
- if 'version' not in fields:
975
- results = _latest_per_dataset(results)
976
- return results
1033
+ refs = self.datasets
1034
+ hits = _match_indices(
1035
+ [ref.metadata for ref in refs],
1036
+ bbox=bbox,
1037
+ within_radius=within_radius,
1038
+ geometry=geometry,
1039
+ start_date=start_date,
1040
+ end_date=end_date,
1041
+ all_versions=all_versions,
1042
+ fields=fields,
1043
+ )
1044
+ return [refs[i] for i in hits]
977
1045
 
978
1046
  # -- validate / publish / register / deregister ---------------------------
979
1047
 
@@ -989,10 +1057,21 @@ class Catalogue:
989
1057
  return validate_dataset(local_cfdb_path)
990
1058
 
991
1059
  def publish(
992
- self, local_cfdb_path, remote_conn, rcg_remote_conn, num_groups=None, verify_objects: bool = True, **open_kwargs
1060
+ self, local_cfdb_path, remote_conn, rcg_remote_conn, *, group_bytes=_NOT_GIVEN, verify_objects: bool = True,
1061
+ **open_kwargs
993
1062
  ) -> dict:
994
1063
  """Validate, push the cfdb data to its S3 remote, verify it, then register it in the RCG.
995
1064
 
1065
+ ``group_bytes`` sets how the remote stores chunks (ebooklet >= 0.11): an
1066
+ int packs chunks into write-order groups of up to that many bytes, None
1067
+ stores one object per chunk. Omitted, an existing remote keeps its mode
1068
+ and recorded group_bytes, and a new one is grouped (ebooklet's
1069
+ default, 32 MiB). The mode (grouped or per-key) is fixed per remote:
1070
+ asking an existing remote for the other mode is ignored with a warning.
1071
+ A remote hash-grouped by envlib <= 0.1.7 (``num_groups``) cannot be
1072
+ opened at all (ebooklet raises ``UnsupportedFormatError``); see the
1073
+ changelog for how to move one.
1074
+
996
1075
  The cfdb data is pushed BEFORE the RCG entry so the catalogue never
997
1076
  references incomplete remote data. With ``verify_objects`` (default True),
998
1077
  after the push and before the entry is written the remote is fsck'd, and a
@@ -1004,8 +1083,8 @@ class Catalogue:
1004
1083
  """
1005
1084
  member_conn = _as_connection(remote_conn)
1006
1085
  edataset_kwargs = dict(open_kwargs)
1007
- if num_groups is not None:
1008
- edataset_kwargs['num_groups'] = num_groups
1086
+ if group_bytes is not _NOT_GIVEN:
1087
+ edataset_kwargs['group_bytes'] = group_bytes
1009
1088
  # validate INSIDE the edataset session: for a re-publish of an
1010
1089
  # already-pushed (possibly partially materialized) local file, plain
1011
1090
  # open_dataset would read local chunks only and could extract wrong
@@ -1174,33 +1253,219 @@ def _field_matches(stored, wanted) -> bool:
1174
1253
  return str(stored).lower() == str(wanted).strip().lower()
1175
1254
 
1176
1255
 
1177
- def _time_overlaps(time_start, time_end, start_date, end_date) -> bool:
1178
- if time_start is None or time_end is None:
1256
+ def _entry_name(meta: dict) -> str:
1257
+ return str(meta.get('dataset_version_id') or meta.get('dataset_id') or '<an entry>')
1258
+
1259
+
1260
+ def _stored_time(meta: dict, field: str):
1261
+ """A stored time as an aware datetime; None when missing, or (with a warning) unparsable."""
1262
+ value = meta.get(field)
1263
+ if value is None:
1264
+ return None
1265
+ try:
1266
+ return _parse_iso(value)
1267
+ except (ValueError, TypeError, OverflowError):
1268
+ warnings.warn(f'{_entry_name(meta)}: unparsable {field} {value!r}; it matches no time filter.', stacklevel=2)
1269
+ return None
1270
+
1271
+
1272
+ def _stored_bbox(meta: dict):
1273
+ """The stored bbox as four floats; None when missing, or (with a warning) malformed."""
1274
+ value = meta.get('bbox')
1275
+ if value is None:
1276
+ return None
1277
+ try:
1278
+ vals = [float(v) for v in value]
1279
+ except (TypeError, ValueError):
1280
+ vals = []
1281
+ if len(vals) != _BBOX_LEN or not all(np.isfinite(vals)):
1282
+ warnings.warn(f'{_entry_name(meta)}: malformed bbox {value!r}; it matches no spatial filter.', stacklevel=2)
1283
+ return None
1284
+ return vals
1285
+
1286
+
1287
+ def _time_overlaps(meta: dict, start, end) -> bool:
1288
+ """Whether the entry's stored time range overlaps [start, end] (aware datetimes or None)."""
1289
+ t0 = _stored_time(meta, 'time_start')
1290
+ t1 = _stored_time(meta, 'time_end')
1291
+ if t0 is None or t1 is None:
1179
1292
  return False
1180
- t0 = _parse_iso(time_start)
1181
- t1 = _parse_iso(time_end)
1182
- if start_date is not None and t1 < _parse_iso(start_date):
1293
+ if start is not None and t1 < start:
1183
1294
  return False
1184
- return not (end_date is not None and t0 > _parse_iso(end_date))
1295
+ return not (end is not None and t0 > end)
1296
+
1297
+
1298
+ def _created_at(meta: dict) -> datetime.datetime:
1299
+ """`created_at` as an aware datetime. Missing is the oldest; unparsable is the oldest too, with a
1300
+ warning, so one damaged entry cannot fail every query (code review edr-api-code-3)."""
1301
+ value = meta.get('created_at')
1302
+ if value is not None:
1303
+ try:
1304
+ return _parse_iso(value)
1305
+ except (ValueError, TypeError, OverflowError):
1306
+ warnings.warn(f'{_entry_name(meta)}: unparsable created_at {value!r}; treated as the oldest.', stacklevel=2)
1307
+ return datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)
1185
1308
 
1186
1309
 
1187
- def _latest_per_dataset(refs: list) -> list:
1188
- by_dataset: dict = {}
1310
+ def _version_key(meta: dict) -> tuple:
1311
+ """The order of versions: created_at, then dataset_version_id, so a tie never depends on the
1312
+ order the entries were read in (plan review edr-api-plan-3)."""
1313
+ return _created_at(meta), str(meta.get('dataset_version_id') or '')
1314
+
1315
+
1316
+ def _latest_indices(metas: list, indices) -> list:
1317
+ """Of `indices` into `metas`, the latest version of each dataset_id, in order of each dataset's
1318
+ first appearance; entries with no dataset_id follow, in their own order."""
1319
+ best: dict = {}
1189
1320
  no_dataset_id = []
1190
- for ref in refs:
1191
- user_meta = ref.metadata
1192
- dataset_id = user_meta.get('dataset_id')
1321
+ for i in indices:
1322
+ meta = metas[i] or {}
1323
+ dataset_id = meta.get('dataset_id')
1193
1324
  if dataset_id is None:
1194
- no_dataset_id.append(ref)
1325
+ no_dataset_id.append(i)
1195
1326
  continue
1196
- current = by_dataset.get(dataset_id)
1197
- if current is None or _created_at(ref) > _created_at(current):
1198
- by_dataset[dataset_id] = ref
1199
- return list(by_dataset.values()) + no_dataset_id
1327
+ current = best.get(dataset_id)
1328
+ if current is None or _version_key(meta) > _version_key(metas[current] or {}):
1329
+ best[dataset_id] = i
1330
+ return list(best.values()) + no_dataset_id
1200
1331
 
1201
1332
 
1202
- def _created_at(ref: DatasetRef) -> datetime.datetime:
1203
- value = ref.metadata.get('created_at')
1204
- if value is None:
1205
- return datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)
1206
- return _parse_iso(value)
1333
+ def _match_indices(metas, *, bbox, within_radius, geometry, start_date, end_date, all_versions, fields) -> list:
1334
+ unknown = set(fields) - QUERYABLE_FIELDS
1335
+ if unknown:
1336
+ msg = f'unknown query fields: {sorted(unknown)}; queryable fields are {sorted(QUERYABLE_FIELDS)}.'
1337
+ raise ValueError(msg)
1338
+ spatial_kwargs = (('bbox', bbox), ('within_radius', within_radius), ('geometry', geometry))
1339
+ spatial = [kw for kw, v in spatial_kwargs if v is not None]
1340
+ if len(spatial) > 1:
1341
+ msg = f'spatial filters are mutually exclusive; got {spatial}.'
1342
+ raise ValueError(msg)
1343
+ start = None if start_date is None else _parse_iso(start_date)
1344
+ end = None if end_date is None else _parse_iso(end_date)
1345
+ if bbox is not None:
1346
+ bbox = _query_bbox(bbox)
1347
+ if geometry is not None and not np.all(np.isfinite(shapely.get_coordinates(geometry))):
1348
+ ## shapely cannot translate it (GEOSException), and it is no place (code review edr-api-code-5)
1349
+ msg = 'geometry coordinates must be finite.'
1350
+ raise ValueError(msg)
1351
+ shifted = None if geometry is None else _geometry_shifts(geometry)
1352
+
1353
+ hits = []
1354
+ for i, entry_meta in enumerate(metas):
1355
+ meta = entry_meta or {}
1356
+ if not all(_field_matches(meta.get(name), wanted) for name, wanted in fields.items()):
1357
+ continue
1358
+ if spatial:
1359
+ stored = _stored_bbox(meta)
1360
+ if stored is None:
1361
+ continue
1362
+ if bbox is not None and not _bbox_intersects(stored, bbox):
1363
+ continue
1364
+ if shifted is not None and not _geometry_intersects(stored, shifted):
1365
+ continue
1366
+ if within_radius is not None:
1367
+ (lon, lat), radius_km = within_radius
1368
+ if not _bbox_within_radius(stored, lon, lat, radius_km):
1369
+ continue
1370
+ if (start is not None or end is not None) and not _time_overlaps(meta, start, end):
1371
+ continue
1372
+ hits.append(i)
1373
+
1374
+ if not all_versions and 'version' not in fields:
1375
+ hits = _latest_indices(metas, hits)
1376
+ return hits
1377
+
1378
+
1379
+ ###################################################
1380
+ # catalogue matching: the public, plain-data form of query() and distinct()
1381
+
1382
+
1383
+ def match_entries(
1384
+ metas: Iterable[dict],
1385
+ *,
1386
+ bbox=None,
1387
+ within_radius=None,
1388
+ geometry=None,
1389
+ start_date=None,
1390
+ end_date=None,
1391
+ all_versions: bool = False,
1392
+ **fields,
1393
+ ) -> list:
1394
+ """The catalogue entries that match, by the rules of :meth:`Catalogue.query`.
1395
+
1396
+ The one definition of catalogue matching: ``Catalogue.query`` and the envlib EDR API both call
1397
+ it, so a Python query and an HTTP query of the same catalogue give the same entries.
1398
+
1399
+ Args:
1400
+ metas: Catalogue ``user_meta`` dicts (``DatasetRef.metadata``).
1401
+ all_versions: Return every matching version, not only the latest of each dataset.
1402
+
1403
+ ``bbox``, ``within_radius``, ``geometry``, ``start_date``, ``end_date`` and the field filters are
1404
+ as for :meth:`Catalogue.query`.
1405
+
1406
+ Returns:
1407
+ The matching dicts themselves (not copies). Without ``version=`` or ``all_versions``, the
1408
+ latest of each dataset_id, in order of each dataset's first appearance, then any entries
1409
+ without a dataset_id.
1410
+
1411
+ A stored value that cannot be read never fails the call: an unparsable ``created_at`` is the
1412
+ oldest, and an unparsable time or bbox matches no filter on it. Each warns.
1413
+ """
1414
+ metas = list(metas)
1415
+ hits = _match_indices(
1416
+ metas,
1417
+ bbox=bbox,
1418
+ within_radius=within_radius,
1419
+ geometry=geometry,
1420
+ start_date=start_date,
1421
+ end_date=end_date,
1422
+ all_versions=all_versions,
1423
+ fields=fields,
1424
+ )
1425
+ return [metas[i] for i in hits]
1426
+
1427
+
1428
+ def version_key(meta: dict) -> tuple:
1429
+ """The order of a dataset's versions, as :func:`latest_per_dataset` ranks them.
1430
+
1431
+ ``(created_at, dataset_version_id)``: the greater key is the later version. A missing or
1432
+ unparsable ``created_at`` is the oldest (an unparsable one warns). Sorting a dataset's entries by
1433
+ this key, descending, puts the version a collection serves first.
1434
+ """
1435
+ return _version_key(meta or {})
1436
+
1437
+
1438
+ def latest_per_dataset(metas: Iterable[dict]) -> list:
1439
+ """The latest version of each dataset_id among ``metas`` (catalogue ``user_meta`` dicts).
1440
+
1441
+ Latest is the greatest ``created_at``; on a tie, the greater ``dataset_version_id``, whatever
1442
+ the order of ``metas``. Returns the dicts themselves, in order of each dataset's first
1443
+ appearance, then any entries without a dataset_id.
1444
+ """
1445
+ metas = list(metas)
1446
+ return [metas[i] for i in _latest_indices(metas, range(len(metas)))]
1447
+
1448
+
1449
+ def distinct_values(metas: Iterable[dict], field: str, *, counts: bool = False):
1450
+ """The distinct stored values of a queryable field, by the rules of :meth:`Catalogue.distinct`.
1451
+
1452
+ Args:
1453
+ metas: Catalogue ``user_meta`` dicts; every one is counted, all versions included.
1454
+ field: Any field in :data:`QUERYABLE_FIELDS`.
1455
+ counts: When False, a sorted list of the values, excluding None. When True, a
1456
+ ``{value: count}`` dict, None last.
1457
+ """
1458
+ if field not in QUERYABLE_FIELDS:
1459
+ msg = f'unknown field {field!r}; queryable fields are {sorted(QUERYABLE_FIELDS)}.'
1460
+ raise ValueError(msg)
1461
+ tally: dict = {}
1462
+ for meta in metas:
1463
+ value = (meta or {}).get(field)
1464
+ tally[value] = tally.get(value, 0) + 1
1465
+ if counts:
1466
+ return dict(sorted(tally.items(), key=lambda kv: (kv[0] is None, str(kv[0]))))
1467
+ values = [v for v in tally if v is not None]
1468
+ try:
1469
+ return sorted(values)
1470
+ except TypeError: # mixed types (e.g. an int beside strings): sort by text rather than fail
1471
+ return sorted(values, key=str)
@@ -19,9 +19,12 @@ dependencies = [
19
19
  # >=0.10.0: cfdb 0.10 writes new datasets with byte-shuffled compression (zstd_shuffle), which an
20
20
  # older cfdb refuses at open with a bare "Invalid enum value 'zstd_shuffle'" naming no remedy.
21
21
  # Readers must be able to open anything a current producer publishes, so envlib floors the
22
- # version that can. (It needs no other 0.10 feature.)
23
- "cfdb>=0.10.0",
24
- "ebooklet>=0.10.5",
22
+ # version that can.
23
+ # >=0.11 (cfdb and ebooklet): ebooklet 0.11's write-order groups are remote format 3, which
24
+ # 0.10 clients refuse ("upgrade ebooklet"), and publish() forwards group_bytes, which only
25
+ # cfdb 0.11's open_edataset accepts. The commons catalogue is republished per-key (format 2), which both 0.10 and 0.11 read.
26
+ "cfdb>=0.11.0",
27
+ "ebooklet>=0.11.0",
25
28
  "booklet>=0.12.6",
26
29
  "pyproj",
27
30
  "shapely>=2.0",
@@ -41,6 +44,9 @@ dev = [
41
44
  "types-shapely>=2.1.0.20260630",
42
45
  "numpy>=2.2.6",
43
46
  "tomli>=2.4.1 ; python_full_version < '3.11'",
47
+ "sybil[pytest]>=9.3.0",
48
+ "pytest-timeout>=2.4.0",
49
+ "moto[server]>=5.2.5",
44
50
  ]
45
51
 
46
52
  [tool.pytest.ini_options]
@@ -1,18 +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, validate_dataset
5
- from envlib.metadata import Metadata, ValidationError, canonical_station_point, compute_station_id
6
-
7
- __version__ = '0.1.7'
8
-
9
- __all__ = [
10
- 'Catalogue',
11
- 'DatasetRef',
12
- 'Metadata',
13
- 'ValidationError',
14
- 'canonical_station_point',
15
- 'compute_station_id',
16
- 'validate_dataset',
17
- 'vocabularies',
18
- ]
File without changes
File without changes
File without changes