envlib 0.1.8__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.
- {envlib-0.1.8 → envlib-0.1.9}/PKG-INFO +23 -22
- {envlib-0.1.8 → envlib-0.1.9}/README.md +22 -21
- envlib-0.1.9/envlib/__init__.py +39 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/catalogue.py +333 -79
- {envlib-0.1.8 → envlib-0.1.9}/pyproject.toml +4 -1
- envlib-0.1.8/envlib/__init__.py +0 -18
- {envlib-0.1.8 → envlib-0.1.9}/.gitignore +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/LICENSE +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/metadata.py +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/__init__.py +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/aggregation_statistic.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/feature.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/frequency_interval.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/license.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/method.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/processing_level.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/standard_name.json +0 -0
- {envlib-0.1.8 → envlib-0.1.9}/envlib/vocabularies/variable.json +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: envlib
|
|
3
|
-
Version: 0.1.
|
|
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
|
|
@@ -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
|
-
#
|
|
62
|
-
#
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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
|
-
#
|
|
44
|
-
#
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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 (
|
|
@@ -56,10 +58,13 @@ FORECAST_REF_COORD = 'forecast_reference_time'
|
|
|
56
58
|
FORECAST_PERIOD_COORD = 'forecast_period'
|
|
57
59
|
|
|
58
60
|
_HEX24_RE = re.compile(r'[0-9a-f]{24}')
|
|
61
|
+
_FRACTION_RE = re.compile(r'(?<=:\d\d)\.(\d{1,5})(?!\d)')
|
|
59
62
|
_EPSG_4326 = pyproj.CRS.from_epsg(4326)
|
|
60
63
|
_FULL_CIRCLE_DEG = 360.0
|
|
64
|
+
_BBOX_LEN = 4 # w, s, e, n
|
|
65
|
+
_MAX_LAT = 90.0
|
|
61
66
|
|
|
62
|
-
|
|
67
|
+
QUERYABLE_FIELDS = frozenset(IDENTITY_FIELDS) | {'license', 'dataset_type', 'dataset_version_id', 'dataset_id'}
|
|
63
68
|
|
|
64
69
|
|
|
65
70
|
def _raise_on_push_failure(result, context: str):
|
|
@@ -127,12 +132,21 @@ def _dt64_to_iso(value) -> str:
|
|
|
127
132
|
return dt.strftime('%Y-%m-%dT%H:%M:%S') + f'.{frac}Z'
|
|
128
133
|
|
|
129
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
|
+
|
|
130
144
|
def _parse_iso(value) -> datetime.datetime:
|
|
131
145
|
"""Parse an ISO8601 string (Z-suffixed or naive-as-UTC) or pass a datetime through."""
|
|
132
146
|
if isinstance(value, datetime.datetime):
|
|
133
147
|
dt = value
|
|
134
148
|
else:
|
|
135
|
-
dt = datetime.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
|
149
|
+
dt = datetime.datetime.fromisoformat(_pad_fraction(str(value).replace('Z', '+00:00')))
|
|
136
150
|
if dt.tzinfo is None:
|
|
137
151
|
dt = dt.replace(tzinfo=datetime.timezone.utc)
|
|
138
152
|
return dt
|
|
@@ -208,6 +222,61 @@ def _wrap_lon_extent(west: float, east: float, x_step: float | None) -> tuple:
|
|
|
208
222
|
return w, e
|
|
209
223
|
|
|
210
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
|
+
|
|
211
280
|
def _split_bbox(bbox) -> list:
|
|
212
281
|
"""Split an antimeridian-crossing bbox into 1-2 conventional boxes."""
|
|
213
282
|
min_lon, min_lat, max_lon, max_lat = bbox
|
|
@@ -224,8 +293,15 @@ def _bbox_intersects(stored, query) -> bool:
|
|
|
224
293
|
return any(_boxes_intersect(s, q) for s in _split_bbox(stored) for q in _split_bbox(query))
|
|
225
294
|
|
|
226
295
|
|
|
227
|
-
def
|
|
228
|
-
|
|
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)
|
|
229
305
|
|
|
230
306
|
|
|
231
307
|
_GEOD = pyproj.Geod(ellps='WGS84')
|
|
@@ -403,6 +479,7 @@ def _extract_state(ds, meta: Metadata) -> dict:
|
|
|
403
479
|
}
|
|
404
480
|
|
|
405
481
|
x_step = y_step = None
|
|
482
|
+
bounds_crs = crs # the CRS of west/south/east/north below (stations are reprojected first)
|
|
406
483
|
## Both grid types: the else-branch below assumes a station geometry coordinate, so exact
|
|
407
484
|
## equality here would route grid_forecast into it and fail with a message about ts_ortho.
|
|
408
485
|
if dataset_type in GRID_TYPES:
|
|
@@ -428,16 +505,21 @@ def _extract_state(ds, meta: Metadata) -> dict:
|
|
|
428
505
|
if len(points) == 0:
|
|
429
506
|
msg = f'{dataset_type} datasets must have at least one station point.'
|
|
430
507
|
raise ValidationError(msg)
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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]
|
|
434
515
|
south, north = float(min(ys)), float(max(ys))
|
|
516
|
+
bounds_crs = _EPSG_4326
|
|
435
517
|
|
|
436
|
-
if
|
|
518
|
+
if bounds_crs.is_geographic:
|
|
437
519
|
# native-geographic source: transform_bounds is an identity no-op for
|
|
438
520
|
# longitude conventions, so apply envlib's own structure-preserving
|
|
439
521
|
# wrap (0-360 grids -> [-180, 180] / the crossing convention).
|
|
440
|
-
if not
|
|
522
|
+
if not bounds_crs.equals(_EPSG_4326):
|
|
441
523
|
transformer = pyproj.Transformer.from_crs(crs, _EPSG_4326, always_xy=True)
|
|
442
524
|
west, south, east, north = transformer.transform_bounds(west, south, east, north, densify_pts=21)
|
|
443
525
|
min_lon, max_lon = _wrap_lon_extent(west, east, x_step)
|
|
@@ -640,7 +722,8 @@ def validate_dataset(dataset, *, validate_cv: bool = True) -> dict:
|
|
|
640
722
|
network refresh, neither of which a local build has or wants.
|
|
641
723
|
|
|
642
724
|
Args:
|
|
643
|
-
dataset: a path to a local cfdb file,
|
|
725
|
+
dataset (str | pathlib.Path | cfdb.Dataset | cfdb.EDataset): a path to a local cfdb file,
|
|
726
|
+
or an ALREADY-OPEN cfdb ``Dataset``/``EDataset``.
|
|
644
727
|
Prefer passing the open object when you have one -- reopening a file that is linked
|
|
645
728
|
to a remote starts a second session against it, and for an ``EDataset`` the open
|
|
646
729
|
object also pulls transparently, so extents are read from the whole dataset rather
|
|
@@ -826,6 +909,10 @@ class Catalogue:
|
|
|
826
909
|
"""All catalogue entries as DatasetRef objects."""
|
|
827
910
|
return [DatasetRef(key, entry, self._cache_dir) for key, entry in self._entries.items()]
|
|
828
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
|
+
|
|
829
916
|
# -- value discovery -------------------------------------------------------
|
|
830
917
|
|
|
831
918
|
def distinct(self, field: str, *, counts: bool = False):
|
|
@@ -843,17 +930,10 @@ class Catalogue:
|
|
|
843
930
|
values, excluding None. When True, return a ``{value: count}``
|
|
844
931
|
dict that DOES include a None key when some entries lack the
|
|
845
932
|
field (e.g. datasets with no ``product_code``).
|
|
933
|
+
|
|
934
|
+
Every version is counted. The rules are :func:`distinct_values`'.
|
|
846
935
|
"""
|
|
847
|
-
|
|
848
|
-
msg = f'unknown field {field!r}; queryable fields are {sorted(_QUERYABLE_FIELDS)}.'
|
|
849
|
-
raise ValueError(msg)
|
|
850
|
-
tally: dict = {}
|
|
851
|
-
for entry in self._entries.values():
|
|
852
|
-
value = (entry.get('user_meta') or {}).get(field)
|
|
853
|
-
tally[value] = tally.get(value, 0) + 1
|
|
854
|
-
if counts:
|
|
855
|
-
return dict(sorted(tally.items(), key=lambda kv: (kv[0] is None, str(kv[0]))))
|
|
856
|
-
return sorted(v for v in tally if v is not None)
|
|
936
|
+
return distinct_values(self._metas(), field, counts=counts)
|
|
857
937
|
|
|
858
938
|
@property
|
|
859
939
|
def features(self) -> list:
|
|
@@ -934,50 +1014,34 @@ class Catalogue:
|
|
|
934
1014
|
geometry=None,
|
|
935
1015
|
start_date=None,
|
|
936
1016
|
end_date=None,
|
|
1017
|
+
all_versions: bool = False,
|
|
937
1018
|
**fields,
|
|
938
1019
|
) -> list:
|
|
939
1020
|
"""Filter the catalogue; kwargs are AND'd, a list value means any-of.
|
|
940
1021
|
|
|
941
1022
|
Spatial filters (mutually exclusive, EPSG:4326): ``bbox`` (intersects),
|
|
942
1023
|
``within_radius`` (((lon, lat), km) great-circle), ``geometry``
|
|
943
|
-
(shapely, intersects). Temporal:
|
|
944
|
-
the dataset's time range. Without an
|
|
945
|
-
|
|
946
|
-
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.
|
|
947
1032
|
"""
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
for
|
|
960
|
-
user_meta = ref.metadata
|
|
961
|
-
if not all(_field_matches(user_meta.get(name), wanted) for name, wanted in fields.items()):
|
|
962
|
-
continue
|
|
963
|
-
stored_bbox = user_meta.get('bbox')
|
|
964
|
-
if bbox is not None and (stored_bbox is None or not _bbox_intersects(stored_bbox, bbox)):
|
|
965
|
-
continue
|
|
966
|
-
if geometry is not None and (stored_bbox is None or not _geometry_intersects(stored_bbox, geometry)):
|
|
967
|
-
continue
|
|
968
|
-
if within_radius is not None:
|
|
969
|
-
(lon, lat), radius_km = within_radius
|
|
970
|
-
if stored_bbox is None or not _bbox_within_radius(stored_bbox, lon, lat, radius_km):
|
|
971
|
-
continue
|
|
972
|
-
if (start_date is not None or end_date is not None) and not _time_overlaps(
|
|
973
|
-
user_meta.get('time_start'), user_meta.get('time_end'), start_date, end_date
|
|
974
|
-
):
|
|
975
|
-
continue
|
|
976
|
-
results.append(ref)
|
|
977
|
-
|
|
978
|
-
if 'version' not in fields:
|
|
979
|
-
results = _latest_per_dataset(results)
|
|
980
|
-
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]
|
|
981
1045
|
|
|
982
1046
|
# -- validate / publish / register / deregister ---------------------------
|
|
983
1047
|
|
|
@@ -1002,7 +1066,11 @@ class Catalogue:
|
|
|
1002
1066
|
int packs chunks into write-order groups of up to that many bytes, None
|
|
1003
1067
|
stores one object per chunk. Omitted, an existing remote keeps its mode
|
|
1004
1068
|
and recorded group_bytes, and a new one is grouped (ebooklet's
|
|
1005
|
-
default, 32 MiB).
|
|
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.
|
|
1006
1074
|
|
|
1007
1075
|
The cfdb data is pushed BEFORE the RCG entry so the catalogue never
|
|
1008
1076
|
references incomplete remote data. With ``verify_objects`` (default True),
|
|
@@ -1185,33 +1253,219 @@ def _field_matches(stored, wanted) -> bool:
|
|
|
1185
1253
|
return str(stored).lower() == str(wanted).strip().lower()
|
|
1186
1254
|
|
|
1187
1255
|
|
|
1188
|
-
def
|
|
1189
|
-
|
|
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:
|
|
1190
1292
|
return False
|
|
1191
|
-
|
|
1192
|
-
t1 = _parse_iso(time_end)
|
|
1193
|
-
if start_date is not None and t1 < _parse_iso(start_date):
|
|
1293
|
+
if start is not None and t1 < start:
|
|
1194
1294
|
return False
|
|
1195
|
-
return not (
|
|
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)
|
|
1308
|
+
|
|
1196
1309
|
|
|
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 '')
|
|
1197
1314
|
|
|
1198
|
-
|
|
1199
|
-
|
|
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 = {}
|
|
1200
1320
|
no_dataset_id = []
|
|
1201
|
-
for
|
|
1202
|
-
|
|
1203
|
-
dataset_id =
|
|
1321
|
+
for i in indices:
|
|
1322
|
+
meta = metas[i] or {}
|
|
1323
|
+
dataset_id = meta.get('dataset_id')
|
|
1204
1324
|
if dataset_id is None:
|
|
1205
|
-
no_dataset_id.append(
|
|
1325
|
+
no_dataset_id.append(i)
|
|
1206
1326
|
continue
|
|
1207
|
-
current =
|
|
1208
|
-
if current is None or
|
|
1209
|
-
|
|
1210
|
-
return list(
|
|
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
|
|
1211
1331
|
|
|
1212
1332
|
|
|
1213
|
-
def
|
|
1214
|
-
|
|
1215
|
-
if
|
|
1216
|
-
|
|
1217
|
-
|
|
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)
|
|
@@ -22,7 +22,7 @@ dependencies = [
|
|
|
22
22
|
# version that can.
|
|
23
23
|
# >=0.11 (cfdb and ebooklet): ebooklet 0.11's write-order groups are remote format 3, which
|
|
24
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
|
|
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
26
|
"cfdb>=0.11.0",
|
|
27
27
|
"ebooklet>=0.11.0",
|
|
28
28
|
"booklet>=0.12.6",
|
|
@@ -44,6 +44,9 @@ dev = [
|
|
|
44
44
|
"types-shapely>=2.1.0.20260630",
|
|
45
45
|
"numpy>=2.2.6",
|
|
46
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",
|
|
47
50
|
]
|
|
48
51
|
|
|
49
52
|
[tool.pytest.ini_options]
|
envlib-0.1.8/envlib/__init__.py
DELETED
|
@@ -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.8'
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|