envlib-api 0.3.0__py3-none-any.whl

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.
Files changed (116) hide show
  1. envlib_api/__init__.py +3 -0
  2. envlib_api/__main__.py +3 -0
  3. envlib_api/api/__init__.py +7 -0
  4. envlib_api/api/app.py +435 -0
  5. envlib_api/api/compress.py +52 -0
  6. envlib_api/api/cost.py +107 -0
  7. envlib_api/api/edr.py +343 -0
  8. envlib_api/api/encode.py +285 -0
  9. envlib_api/api/errors.py +23 -0
  10. envlib_api/api/grid.py +317 -0
  11. envlib_api/api/params.py +71 -0
  12. envlib_api/api/read.py +65 -0
  13. envlib_api/api/resolve.py +191 -0
  14. envlib_api/api/server.py +35 -0
  15. envlib_api/api/stations.py +96 -0
  16. envlib_api/api/timesel.py +97 -0
  17. envlib_api/cli.py +179 -0
  18. envlib_api/config.py +158 -0
  19. envlib_api/healthcheck.py +38 -0
  20. envlib_api/mirror.py +353 -0
  21. envlib_api/refresher.py +265 -0
  22. envlib_api/tests/__init__.py +0 -0
  23. envlib_api/tests/api_support.py +307 -0
  24. envlib_api/tests/conftest.py +12 -0
  25. envlib_api/tests/grid_support.py +217 -0
  26. envlib_api/tests/schemas/README.md +12 -0
  27. envlib_api/tests/schemas/coveragejson/coveragejson.json +1794 -0
  28. envlib_api/tests/schemas/edr/schemas/collections/DataQuery.yaml +38 -0
  29. envlib_api/tests/schemas/edr/schemas/collections/areaDataQuery.yaml +10 -0
  30. envlib_api/tests/schemas/edr/schemas/collections/areaLink.yaml +9 -0
  31. envlib_api/tests/schemas/edr/schemas/collections/collection.yaml +137 -0
  32. envlib_api/tests/schemas/edr/schemas/collections/collections.yaml +26 -0
  33. envlib_api/tests/schemas/edr/schemas/collections/corridorDataQuery.yaml +29 -0
  34. envlib_api/tests/schemas/edr/schemas/collections/corridorLink.yaml +9 -0
  35. envlib_api/tests/schemas/edr/schemas/collections/crsObject.yaml +15 -0
  36. envlib_api/tests/schemas/edr/schemas/collections/cubeDataQuery.yaml +20 -0
  37. envlib_api/tests/schemas/edr/schemas/collections/cubeLink.yaml +9 -0
  38. envlib_api/tests/schemas/edr/schemas/collections/extent.yaml +311 -0
  39. envlib_api/tests/schemas/edr/schemas/collections/instancesDataQuery.yaml +21 -0
  40. envlib_api/tests/schemas/edr/schemas/collections/instancesLink.yaml +9 -0
  41. envlib_api/tests/schemas/edr/schemas/collections/itemsDataQuery.yaml +21 -0
  42. envlib_api/tests/schemas/edr/schemas/collections/itemsLink.yaml +9 -0
  43. envlib_api/tests/schemas/edr/schemas/collections/locationsDataQuery.yaml +10 -0
  44. envlib_api/tests/schemas/edr/schemas/collections/locationsLink.yaml +9 -0
  45. envlib_api/tests/schemas/edr/schemas/collections/observedPropertyCollection.yaml +51 -0
  46. envlib_api/tests/schemas/edr/schemas/collections/parameterNames.yaml +70 -0
  47. envlib_api/tests/schemas/edr/schemas/collections/positionDataQuery.yaml +12 -0
  48. envlib_api/tests/schemas/edr/schemas/collections/positionLink.yaml +9 -0
  49. envlib_api/tests/schemas/edr/schemas/collections/radiusDataQuery.yaml +18 -0
  50. envlib_api/tests/schemas/edr/schemas/collections/radiusLink.yaml +9 -0
  51. envlib_api/tests/schemas/edr/schemas/collections/trajectoryDataQuery.yaml +10 -0
  52. envlib_api/tests/schemas/edr/schemas/collections/trajectoryLink.yaml +9 -0
  53. envlib_api/tests/schemas/edr/schemas/collections/units.yaml +42 -0
  54. envlib_api/tests/schemas/edr/schemas/core/confClasses.yaml +8 -0
  55. envlib_api/tests/schemas/edr/schemas/core/exception.yaml +8 -0
  56. envlib_api/tests/schemas/edr/schemas/core/landingPage.yaml +76 -0
  57. envlib_api/tests/schemas/edr/schemas/core/link.yaml +31 -0
  58. envlib_api/tests/schemas/edr/schemas/covjson/anyAxis.yaml +11 -0
  59. envlib_api/tests/schemas/edr/schemas/covjson/coverage.yaml +14 -0
  60. envlib_api/tests/schemas/edr/schemas/covjson/coverageBase.yaml +68 -0
  61. envlib_api/tests/schemas/edr/schemas/covjson/coverageCollection.yaml +58 -0
  62. envlib_api/tests/schemas/edr/schemas/covjson/coverageJSON.yaml +46 -0
  63. envlib_api/tests/schemas/edr/schemas/covjson/covjsonI18n.yaml +9 -0
  64. envlib_api/tests/schemas/edr/schemas/covjson/covjsonObservedProperty.yaml +29 -0
  65. envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameter.yaml +32 -0
  66. envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameterGroup.yaml +31 -0
  67. envlib_api/tests/schemas/edr/schemas/covjson/covjsonUnit.yaml +31 -0
  68. envlib_api/tests/schemas/edr/schemas/covjson/domain.yaml +7 -0
  69. envlib_api/tests/schemas/edr/schemas/covjson/domainBase.yaml +337 -0
  70. envlib_api/tests/schemas/edr/schemas/covjson/ndArray.yaml +88 -0
  71. envlib_api/tests/schemas/edr/schemas/covjson/numericAxis.yaml +11 -0
  72. envlib_api/tests/schemas/edr/schemas/covjson/numericRegularlySpacedAxis.yaml +17 -0
  73. envlib_api/tests/schemas/edr/schemas/covjson/numericSingleValueAxis.yaml +9 -0
  74. envlib_api/tests/schemas/edr/schemas/covjson/numericValuesAxis.yaml +14 -0
  75. envlib_api/tests/schemas/edr/schemas/covjson/polygonValuesAxis.yaml +29 -0
  76. envlib_api/tests/schemas/edr/schemas/covjson/primitiveValuesAxis.yaml +22 -0
  77. envlib_api/tests/schemas/edr/schemas/covjson/referenceSystem.yaml +48 -0
  78. envlib_api/tests/schemas/edr/schemas/covjson/referenceSystemConnection.yaml +16 -0
  79. envlib_api/tests/schemas/edr/schemas/covjson/stringSingleValueAxis.yaml +9 -0
  80. envlib_api/tests/schemas/edr/schemas/covjson/stringValuesAxis.yaml +14 -0
  81. envlib_api/tests/schemas/edr/schemas/covjson/targetConcept.yaml +13 -0
  82. envlib_api/tests/schemas/edr/schemas/covjson/tiledNdArray.yaml +50 -0
  83. envlib_api/tests/schemas/edr/schemas/covjson/tupleValuesAxis.yaml +24 -0
  84. envlib_api/tests/schemas/edr/schemas/covjson/valuesAxis.yaml +27 -0
  85. envlib_api/tests/schemas/edr/schemas/covjson/valuesAxisBase.yaml +24 -0
  86. envlib_api/tests/schemas/edr/schemas/edr-geojson/edrFeatureCollectionGeoJSON.yaml +32 -0
  87. envlib_api/tests/schemas/edr/schemas/edr-geojson/edrProperties.yaml +49 -0
  88. envlib_api/tests/schemas/edr/schemas/edr-geojson/observedProperty.yaml +26 -0
  89. envlib_api/tests/schemas/edr/schemas/edr-geojson/parameter.yaml +28 -0
  90. envlib_api/tests/schemas/edr/schemas/edr-geojson/unit.yaml +24 -0
  91. envlib_api/tests/schemas/edr/schemas/geojson/featureGeoJSON.yaml +29 -0
  92. envlib_api/tests/schemas/edr/schemas/geojson/geometrycollectionGeoJSON.yaml +19 -0
  93. envlib_api/tests/schemas/edr/schemas/geojson/linestringGeoJSON.yaml +23 -0
  94. envlib_api/tests/schemas/edr/schemas/geojson/multilinestringGeoJSON.yaml +19 -0
  95. envlib_api/tests/schemas/edr/schemas/geojson/multipointGeoJSON.yaml +16 -0
  96. envlib_api/tests/schemas/edr/schemas/geojson/multipolygonGeoJSON.yaml +21 -0
  97. envlib_api/tests/schemas/edr/schemas/geojson/pointGeoJSON.yaml +14 -0
  98. envlib_api/tests/schemas/edr/schemas/geojson/polygonGeoJSON.yaml +19 -0
  99. envlib_api/tests/schemas/edr/schemas/i18n.yaml +4 -0
  100. envlib_api/tests/schemas/edr/schemas/numberMatched.yaml +7 -0
  101. envlib_api/tests/schemas/edr/schemas/numberReturned.yaml +12 -0
  102. envlib_api/tests/schemas/edr/schemas/parameterGroup.yaml +30 -0
  103. envlib_api/tests/schemas/edr/schemas/queries/instances.yaml +26 -0
  104. envlib_api/tests/support.py +320 -0
  105. envlib_api/tests/test_alerting_and_guards.py +325 -0
  106. envlib_api/tests/test_api.py +808 -0
  107. envlib_api/tests/test_api_review.py +428 -0
  108. envlib_api/tests/test_grid.py +1075 -0
  109. envlib_api/tests/test_ops.py +358 -0
  110. envlib_api/tests/test_refresher.py +354 -0
  111. envlib_api/tests/test_schemas.py +91 -0
  112. envlib_api-0.3.0.dist-info/METADATA +408 -0
  113. envlib_api-0.3.0.dist-info/RECORD +116 -0
  114. envlib_api-0.3.0.dist-info/WHEEL +4 -0
  115. envlib_api-0.3.0.dist-info/entry_points.txt +3 -0
  116. envlib_api-0.3.0.dist-info/licenses/LICENSE +201 -0
envlib_api/api/edr.py ADDED
@@ -0,0 +1,343 @@
1
+ """
2
+ EDR 1.2 metadata: the landing page, conformance, and collection objects built from the catalogue
3
+ entry (`user_meta`) and the dataset's attrs. The full `user_meta` rides in a namespaced `envlib`
4
+ object; the standard slots are derived from it and never edited separately (assessment §5).
5
+
6
+ Shapes follow EDR 1.2 and its master-branch schemas, as the plan review (edr-api-plan-3) read them:
7
+ - the collection's `crs` is a list of strings, and the {crs, wkt} objects go in each query's
8
+ `crs_details`;
9
+ - each `data_queries` link carries `variables` with title, description, query_type,
10
+ output_formats, default_output_format and crs_details; radius adds `within_units` (also at
11
+ collection level);
12
+ - the extent bbox is [[w, s, e, n]].
13
+ """
14
+
15
+ import functools
16
+ import importlib.resources
17
+ import json
18
+
19
+ import pyproj
20
+ from envlib.vocabularies import frequency_entry
21
+
22
+ CRS84_URI = 'http://www.opengis.net/def/crs/OGC/1.3/CRS84'
23
+ TRS_GREGORIAN = 'TIMECRS["DateTime",TDATUM["Gregorian Calendar"],CS[TemporalDateTime,1],AXIS["Time (T)",future]]'
24
+ DATA_FORMATS = ['CoverageJSON', 'CSV']
25
+ OUTPUT_FORMATS = ['CoverageJSON', 'CSV', 'GeoJSON']
26
+ WITHIN_UNITS = ['km', 'm']
27
+ NERC_STANDARD_NAME = 'http://vocab.nerc.ac.uk/standard_name/{}/'
28
+ _CONF = 'https://www.opengis.net/spec/ogcapi-edr-1/1.2/conf/'
29
+ CONFORMANCE = [
30
+ 'https://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core',
31
+ 'https://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections',
32
+ _CONF + 'core',
33
+ _CONF + 'collections',
34
+ _CONF + 'json',
35
+ _CONF + 'geojson',
36
+ _CONF + 'covjson',
37
+ ## oas31 is not claimed: /api is FastAPI's generated document, which does not describe the query
38
+ ## parameters yet (code review edr-api-code-3; plan 6).
39
+ _CONF + 'queries',
40
+ ]
41
+ ## EDR's recommended method names, where envlib's aggregation_statistic differs.
42
+ _METHODS = {'point': 'instantaneous'}
43
+ STATION_VARS = ('station_id', 'station_ref', 'station_name')
44
+ QUERIES = {
45
+ 'locations': ('Locations', 'Data for one station, by its station_id; the station list without one.'),
46
+ 'area': ('Area', 'Data for the stations inside a WKT POLYGON or MULTIPOLYGON (CRS84).'),
47
+ 'radius': ('Radius', 'Data for the stations within a great-circle distance of a WKT POINT (CRS84).'),
48
+ }
49
+ GRID_QUERIES = {
50
+ 'position': ('Position', 'The time series of the grid cell nearest a WKT POINT (CRS84).'),
51
+ 'cube': (
52
+ 'Cube',
53
+ 'The grid cells whose centres lie in a CRS84 bbox, as the smallest rectangle of the grid holding them '
54
+ '(cells outside the bbox in that rectangle are included).',
55
+ ),
56
+ }
57
+ ## The formats of each grid query: a cube is CoverageJSON only (Mike, 2026-11-25).
58
+ GRID_FORMATS = {'position': ('CoverageJSON', 'CSV'), 'cube': ('CoverageJSON',)}
59
+ ## The queries each served dataset type offers.
60
+ OFFERED = {'ts_ortho': tuple(QUERIES), 'grid': tuple(GRID_QUERIES)}
61
+
62
+
63
+ @functools.cache
64
+ def crs84_wkt():
65
+ return pyproj.CRS('OGC:CRS84').to_wkt()
66
+
67
+
68
+ @functools.cache
69
+ def _licences():
70
+ text = (importlib.resources.files('envlib.vocabularies') / 'license.json').read_text()
71
+ return {e['name']: e for e in json.loads(text)['entries']}
72
+
73
+
74
+ def iso_duration(frequency_interval):
75
+ """envlib's frequency code as an ISO 8601 duration ('1h' -> 'PT1H', 'day' -> 'P1D'), or None."""
76
+ if frequency_interval is None:
77
+ return None
78
+ entry = frequency_entry(frequency_interval)
79
+ if entry['kind'] == 'calendar':
80
+ return {'month': 'P1M', 'year': 'P1Y'}.get(entry['name'])
81
+ secs = int(entry['seconds'])
82
+ if secs % 86400 == 0:
83
+ return f'P{secs // 86400}D'
84
+ if secs % 3600 == 0:
85
+ return f'PT{secs // 3600}H'
86
+ if secs % 60 == 0:
87
+ return f'PT{secs // 60}M'
88
+ return f'PT{secs}S'
89
+
90
+
91
+ def measurement_type(meta):
92
+ stat = meta.get('aggregation_statistic')
93
+ if stat is None:
94
+ return None
95
+ method = _METHODS.get(stat, stat)
96
+ if method == 'instantaneous':
97
+ return {'method': method, 'duration': 'PT0S'}
98
+ mt = {'method': method}
99
+ duration = iso_duration(meta.get('frequency_interval'))
100
+ if duration is not None:
101
+ mt['duration'] = duration
102
+ return mt
103
+
104
+
105
+ def data_var_names(ds):
106
+ """The (point, time) data variables: the parameters a station collection serves."""
107
+ return [n for n in ds.data_var_names if ds[n].coord_names == ('point', 'time')]
108
+
109
+
110
+ def parameter_names(meta, attrs, names):
111
+ """EDR `parameter_names` (string labels)."""
112
+ out = {}
113
+ primary = meta.get('variable')
114
+ for name in names:
115
+ a = attrs[name]
116
+ units = a.get('units')
117
+ sn = a.get('standard_name')
118
+ p = {
119
+ 'type': 'Parameter',
120
+ 'id': name,
121
+ 'label': name,
122
+ 'unit': {'label': units, 'symbol': units},
123
+ 'observedProperty': {'id': NERC_STANDARD_NAME.format(sn) if sn else name, 'label': name},
124
+ }
125
+ if name == primary:
126
+ mt = measurement_type(meta)
127
+ if mt:
128
+ p['measurementType'] = mt
129
+ else:
130
+ p['description'] = f'Ancillary to {primary}.'
131
+ out[name] = p
132
+ return out
133
+
134
+
135
+ def covjson_parameters(attrs, names):
136
+ """CoverageJSON `parameters` (i18n-object labels, as CoverageJSON requires)."""
137
+ out = {}
138
+ for name in names:
139
+ a = attrs[name]
140
+ units = a.get('units')
141
+ sn = a.get('standard_name')
142
+ op = {'label': {'en': name}}
143
+ if sn:
144
+ op['id'] = NERC_STANDARD_NAME.format(sn)
145
+ out[name] = {'type': 'Parameter', 'observedProperty': op, 'unit': {'label': {'en': units}, 'symbol': units}}
146
+ return out
147
+
148
+
149
+ def title(meta):
150
+ parts = [meta.get('owner'), meta.get('variable'), meta.get('aggregation_statistic'), meta.get('frequency_interval')]
151
+ level = meta.get('processing_level')
152
+ text = ' '.join(str(p) for p in parts if p)
153
+ return f'{text} ({level}, version {meta.get("version")})' if level else text
154
+
155
+
156
+ def keywords(meta):
157
+ fields = ('feature', 'variable', 'method', 'owner', 'product_code', 'processing_level')
158
+ return [str(meta[f]) for f in fields if meta.get(f)]
159
+
160
+
161
+ def _query(base, cid, name):
162
+ qtitle, desc = QUERIES[name]
163
+ variables = {
164
+ 'title': f'{qtitle} query',
165
+ 'description': desc,
166
+ 'query_type': name,
167
+ 'output_formats': DATA_FORMATS,
168
+ 'default_output_format': 'CoverageJSON',
169
+ 'crs_details': [{'crs': 'CRS84', 'wkt': crs84_wkt()}],
170
+ }
171
+ if name == 'radius':
172
+ variables['within_units'] = WITHIN_UNITS
173
+ return {
174
+ 'link': {
175
+ 'href': f'{base}/collections/{cid}/{name}',
176
+ 'rel': 'data',
177
+ 'title': f'{qtitle} query',
178
+ 'variables': variables,
179
+ }
180
+ }
181
+
182
+
183
+ def collection(base, doc, attrs, names):
184
+ meta = doc['user_meta']
185
+ cid = doc['dataset_id']
186
+ links = [
187
+ {'href': f'{base}/collections/{cid}', 'rel': 'self', 'type': 'application/json', 'title': 'This collection'},
188
+ {
189
+ 'href': f'{base}/collections/{cid}/locations',
190
+ 'rel': 'data',
191
+ 'type': 'application/geo+json',
192
+ 'title': 'Stations',
193
+ },
194
+ ]
195
+ lic = _licences().get(meta.get('license'))
196
+ if lic and lic.get('url'):
197
+ links.append({'href': lic['url'], 'rel': 'license', 'title': lic.get('title', meta['license'])})
198
+ out = {
199
+ 'id': cid,
200
+ 'title': title(meta),
201
+ 'description': meta.get('description') or title(meta),
202
+ 'keywords': keywords(meta),
203
+ 'links': links,
204
+ 'extent': {
205
+ 'spatial': {'bbox': [list(meta['bbox'])], 'crs': CRS84_URI},
206
+ 'temporal': {'interval': [[meta.get('time_start'), meta.get('time_end')]], 'trs': TRS_GREGORIAN},
207
+ },
208
+ 'data_queries': {name: _query(base, cid, name) for name in QUERIES},
209
+ 'crs': ['CRS84'],
210
+ 'output_formats': OUTPUT_FORMATS,
211
+ 'parameter_names': parameter_names(meta, attrs, names),
212
+ 'within_units': WITHIN_UNITS,
213
+ 'envlib': meta,
214
+ }
215
+ return out
216
+
217
+
218
+ def _vrs(grid):
219
+ """A vertical CRS for the collection's `extent.vertical.vrs`, composed from the coordinate's CF attrs
220
+ (the datasets carry none)."""
221
+ a = grid.z_attrs
222
+ name = a.get('long_name') or a.get('standard_name') or grid.z_name
223
+ direction = 'down' if str(a.get('positive', '')).lower() == 'down' else 'up'
224
+ units = a.get('units') or ''
225
+ if units in ('m', 'metre', 'meter', 'metres', 'meters'):
226
+ return (
227
+ f'VERTCRS["{name}",VDATUM["{name}"],CS[vertical,1],'
228
+ f'AXIS["{grid.z_name} (Z)",{direction}],LENGTHUNIT["metre",1]]'
229
+ )
230
+ return f'{name} ({units}, positive {direction})'
231
+
232
+
233
+ def vertical_crs(grid):
234
+ """The CoverageJSON VerticalCRS of the z axis."""
235
+ a = grid.z_attrs
236
+ direction = 'down' if str(a.get('positive', '')).lower() == 'down' else 'up'
237
+ label = a.get('long_name') or a.get('standard_name') or grid.z_name
238
+ axis = {'name': {'en': label}, 'direction': direction}
239
+ if a.get('units'):
240
+ axis['unit'] = {'symbol': a['units']}
241
+ return {'type': 'VerticalCRS', 'cs': {'csAxes': [axis]}}
242
+
243
+
244
+ def grid_crs_details(grid):
245
+ """`crs` and `crs_details` of a grid collection. A projected grid's cube comes back in its own CRS
246
+ (`native`): a grid rotated against lon/lat cannot be a CRS84 Grid (Mike, D1)."""
247
+ details = [{'crs': 'CRS84', 'wkt': crs84_wkt()}]
248
+ if grid.geographic:
249
+ return ['CRS84'], details
250
+ return ['CRS84', 'native'], details + [{'crs': 'native', 'wkt': grid.wkt}]
251
+
252
+
253
+ def _grid_query(base, cid, name, grid):
254
+ qtitle, desc = GRID_QUERIES[name]
255
+ crs_list, details = grid_crs_details(grid)
256
+ variables = {
257
+ 'title': f'{qtitle} query',
258
+ 'description': desc,
259
+ 'query_type': name,
260
+ 'output_formats': list(GRID_FORMATS[name]),
261
+ 'default_output_format': 'CoverageJSON',
262
+ ## each query lists the output CRSs it accepts: a projected cube only `native`, everything else
263
+ ## CRS84 (code review edr-api-code-4: the cube link listed CRS84, which the route refuses)
264
+ 'crs_details': details[1:] if name == 'cube' and not grid.geographic else details[:1],
265
+ }
266
+ if name == 'cube':
267
+ units = grid.z_attrs.get('units') if grid.z_name else None
268
+ variables['height_units'] = [units] if units else []
269
+ return {
270
+ 'link': {
271
+ 'href': f'{base}/collections/{cid}/{name}',
272
+ 'rel': 'data',
273
+ 'title': f'{qtitle} query',
274
+ 'variables': variables,
275
+ }
276
+ }
277
+
278
+
279
+ def grid_collection(base, doc, attrs, grid):
280
+ meta = doc['user_meta']
281
+ cid = doc['dataset_id']
282
+ links = [
283
+ {'href': f'{base}/collections/{cid}', 'rel': 'self', 'type': 'application/json', 'title': 'This collection'},
284
+ ]
285
+ lic = _licences().get(meta.get('license'))
286
+ if lic and lic.get('url'):
287
+ links.append({'href': lic['url'], 'rel': 'license', 'title': lic.get('title', meta['license'])})
288
+ extent = {
289
+ 'spatial': {'bbox': [list(meta['bbox'])], 'crs': CRS84_URI},
290
+ 'temporal': {'interval': [[meta.get('time_start'), meta.get('time_end')]], 'trs': TRS_GREGORIAN},
291
+ }
292
+ if grid.z_name:
293
+ texts = grid.z_text(grid.z)
294
+ ordered = sorted(zip(grid.z_values(grid.z), texts, strict=True))
295
+ extent['vertical'] = {
296
+ 'interval': [[ordered[0][1], ordered[-1][1]]],
297
+ 'values': texts,
298
+ 'vrs': _vrs(grid),
299
+ }
300
+ crs_list, _ = grid_crs_details(grid)
301
+
302
+ def spacing(a):
303
+ return float((a[-1] - a[0]) / (len(a) - 1))
304
+
305
+ return {
306
+ 'id': cid,
307
+ 'title': title(meta),
308
+ 'description': meta.get('description') or title(meta),
309
+ 'keywords': keywords(meta),
310
+ 'links': links,
311
+ 'extent': extent,
312
+ 'data_queries': {name: _grid_query(base, cid, name, grid) for name in GRID_QUERIES},
313
+ 'crs': crs_list,
314
+ 'output_formats': DATA_FORMATS,
315
+ 'parameter_names': parameter_names(meta, attrs, grid.var_names),
316
+ 'envlib': meta,
317
+ 'envlib:grid': {
318
+ 'crs_wkt': grid.wkt,
319
+ 'x': grid.x_name,
320
+ 'y': grid.y_name,
321
+ 'z': grid.z_name,
322
+ 'shape': [len(grid.y), len(grid.x)],
323
+ 'spacing': {grid.x_name: spacing(grid.x), grid.y_name: spacing(grid.y)},
324
+ },
325
+ }
326
+
327
+
328
+ def landing(base):
329
+ return {
330
+ 'title': 'envlib EDR API',
331
+ 'description': 'OGC API - Environmental Data Retrieval for envlib datasets (station and grid collections).',
332
+ 'links': [
333
+ {'href': f'{base}/', 'rel': 'self', 'type': 'application/json', 'title': 'This document'},
334
+ {
335
+ 'href': f'{base}/api',
336
+ 'rel': 'service-desc',
337
+ 'type': 'application/vnd.oai.openapi+json;version=3.1',
338
+ 'title': 'The API definition',
339
+ },
340
+ {'href': f'{base}/conformance', 'rel': 'conformance', 'type': 'application/json', 'title': 'Conformance'},
341
+ {'href': f'{base}/collections', 'rel': 'data', 'type': 'application/json', 'title': 'Collections'},
342
+ ],
343
+ }
@@ -0,0 +1,285 @@
1
+ """
2
+ Response bodies: CoverageJSON and CSV for data, GeoJSON for the station list.
3
+
4
+ Values are printed at the variable's stored precision (plan review edr-api-plan-3). cfdb decodes a
5
+ packed value as (integer / 10**p) + offset in the decoded dtype. With a non-zero offset that is often
6
+ one ULP away from the stored decimal, so the shortest round-trip text would publish noise (1.3109999
7
+ for a gauge stored as 1.311). Rounding the decoded value to p decimals in float64 removes that noise,
8
+ and its shortest text has at most p decimals. NaN prints as null in JSON and as an empty cell in CSV.
9
+
10
+ What is printed always equals what a direct envlib read returns, rounded to p decimals. It is not
11
+ always the producer's decimal: a float32 variable cannot hold p decimals once |value| x 10**p passes
12
+ about 2**24 (streamflow at precision 4 above about 1,677). The producer's float32 step already lost
13
+ that digit (envlib-ingest-base's `tsortho.build_local` documents it), so the last printed decimal is
14
+ not significant there (code review edr-api-code-3; Mike, 2026-11-25: document it, do not trim it).
15
+ """
16
+
17
+ import csv
18
+ import io
19
+
20
+ import numpy as np
21
+ import orjson
22
+
23
+ from envlib_api.api import edr, timesel
24
+
25
+ COVJSON_TYPE = 'application/prs.coverage+json'
26
+ CSV_TYPE = 'text/csv; charset=utf-8'
27
+ GEOJSON_TYPE = 'application/geo+json'
28
+ JSON_TYPE = 'application/json'
29
+ _ORJSON = orjson.OPT_SERIALIZE_NUMPY
30
+
31
+
32
+ def at_precision(values, precision):
33
+ """float64 values rounded to `precision` decimals (NaN kept), or the decoded values if it is None."""
34
+ if precision is None:
35
+ return values
36
+ scale = 10.0**precision
37
+ return np.rint(values.astype('float64') * scale) / scale
38
+
39
+
40
+ def _referencing():
41
+ return [
42
+ {'coordinates': ['x', 'y'], 'system': {'type': 'GeographicCRS', 'id': edr.CRS84_URI}},
43
+ {'coordinates': ['t'], 'system': {'type': 'TemporalRS', 'calendar': 'Gregorian'}},
44
+ ]
45
+
46
+
47
+ def _coverage(stations, i, t_text, ranges):
48
+ return {
49
+ 'type': 'Coverage',
50
+ 'id': stations.ids[i],
51
+ 'domain': {
52
+ 'type': 'Domain',
53
+ 'domainType': 'PointSeries',
54
+ 'axes': {
55
+ 'x': {'values': [float(stations.lon[i])]},
56
+ 'y': {'values': [float(stations.lat[i])]},
57
+ 't': {'values': t_text},
58
+ },
59
+ },
60
+ 'ranges': ranges,
61
+ 'envlib:station_ref': stations.refs[i],
62
+ 'envlib:station_name': stations.names[i],
63
+ }
64
+
65
+
66
+ def _range(values):
67
+ return {'type': 'NdArray', 'dataType': 'float', 'axisNames': ['t'], 'shape': [len(values)], 'values': values}
68
+
69
+
70
+ def coverage_json(params, stations, positions, times, data, precisions, single):
71
+ """
72
+ One station (`single`): a PointSeries Coverage. Otherwise a CoverageCollection of PointSeries,
73
+ one per station, each with its `id` set to the station_id.
74
+ """
75
+ t_text = timesel.iso(times)
76
+ rounded = {name: at_precision(arr, precisions[name]) for name, arr in data.items()}
77
+ covs = []
78
+ for j, i in enumerate(positions):
79
+ covs.append(_coverage(stations, i, t_text, {name: _range(rounded[name][j]) for name in data}))
80
+ if single:
81
+ cov = covs[0]
82
+ cov['domain']['referencing'] = _referencing()
83
+ cov['parameters'] = params
84
+ return orjson.dumps(cov, option=_ORJSON)
85
+ return orjson.dumps(
86
+ {
87
+ 'type': 'CoverageCollection',
88
+ 'domainType': 'PointSeries',
89
+ 'parameters': params,
90
+ 'referencing': _referencing(),
91
+ 'coverages': covs,
92
+ },
93
+ option=_ORJSON,
94
+ )
95
+
96
+
97
+ def _text(v, precision):
98
+ if v != v: # NaN
99
+ return ''
100
+ if precision is None:
101
+ return repr(float(v))
102
+ return f'{v:.{max(precision, 0)}f}'
103
+
104
+
105
+ def csv_body(stations, positions, times, data, precisions):
106
+ """Long form: one row per station and time step."""
107
+ buf = io.StringIO()
108
+ w = csv.writer(buf, lineterminator='\n')
109
+ names = list(data)
110
+ w.writerow(['station_id', 'station_ref', 'station_name', 'lon', 'lat', 'time', *names])
111
+ t_text = timesel.iso(times)
112
+ rounded = {name: at_precision(arr, precisions[name]) for name, arr in data.items()}
113
+ for j, i in enumerate(positions):
114
+ head = [
115
+ stations.ids[i],
116
+ stations.refs[i],
117
+ stations.names[i],
118
+ repr(float(stations.lon[i])),
119
+ repr(float(stations.lat[i])),
120
+ ]
121
+ cols = [rounded[name][j] for name in names]
122
+ for k, t in enumerate(t_text):
123
+ w.writerow([*head, t, *(_text(col[k], precisions[name]) for col, name in zip(cols, names, strict=True))])
124
+ return buf.getvalue().encode()
125
+
126
+
127
+ def locations_geojson(stations, base, collection_id, time_interval, param_names):
128
+ """The station list as an EDR GeoJSON FeatureCollection, one Feature per station."""
129
+ feats = []
130
+ for i in range(len(stations)):
131
+ feats.append(
132
+ {
133
+ 'type': 'Feature',
134
+ 'id': stations.ids[i],
135
+ 'geometry': {'type': 'Point', 'coordinates': [float(stations.lon[i]), float(stations.lat[i])]},
136
+ 'properties': {
137
+ 'label': stations.names[i],
138
+ 'datetime': time_interval,
139
+ 'parameter-name': param_names,
140
+ 'edrqueryendpoint': f'{base}/collections/{collection_id}/locations/{stations.ids[i]}',
141
+ 'station_ref': stations.refs[i],
142
+ },
143
+ }
144
+ )
145
+ return orjson.dumps({'type': 'FeatureCollection', 'features': feats}, option=_ORJSON)
146
+
147
+
148
+ def json_body(obj):
149
+ return orjson.dumps(obj, option=_ORJSON)
150
+
151
+
152
+ # -- grids ----------------------------------------------------------------------------------------
153
+ #
154
+ # A cube is one CoverageJSON Grid: x and y as the dataset stores them (Lambert metres on WRF;
155
+ # longitudes past 180 on SST, which keeps the axis monotonic), z at its stored precision, t as text.
156
+ # Each range is an NdArray in row-major (t, z, y, x) order whose axisNames list only the axes with more
157
+ # than one value (CoverageJSON's SHOULD). A projected grid's ProjectedCRS carries its WKT as the custom
158
+ # member `envlib:wkt`, since CoverageJSON defines no WKT member (plan review edr-api-plan-4).
159
+
160
+
161
+ def _horizontal_system(grid):
162
+ if grid.geographic:
163
+ return {'type': 'GeographicCRS', 'id': edr.CRS84_URI}
164
+ return {'type': 'ProjectedCRS', 'envlib:wkt': grid.wkt}
165
+
166
+
167
+ def _grid_referencing(grid, horizontal):
168
+ refs = [{'coordinates': ['x', 'y'], 'system': horizontal}]
169
+ if grid.z_name:
170
+ refs.append({'coordinates': ['z'], 'system': edr.vertical_crs(grid)})
171
+ refs.append({'coordinates': ['t'], 'system': {'type': 'TemporalRS', 'calendar': 'Gregorian'}})
172
+ return refs
173
+
174
+
175
+ def _nd(values, names):
176
+ """An NdArray of `values` (axes `names`), leaving out single-valued axes."""
177
+ keep = [(n, s) for n, s in zip(names, values.shape, strict=True) if s > 1]
178
+ flat = np.ascontiguousarray(values).reshape(-1) # row-major (t, z, y, x)
179
+ if not keep:
180
+ return {'type': 'NdArray', 'dataType': 'float', 'values': flat}
181
+ return {
182
+ 'type': 'NdArray',
183
+ 'dataType': 'float',
184
+ 'axisNames': [n for n, _ in keep],
185
+ 'shape': [s for _, s in keep],
186
+ 'values': flat,
187
+ }
188
+
189
+
190
+ def cube_json(params, grid, sel, data, precisions):
191
+ """One Grid coverage for a cube selection (`sel`: the GridSelection of app.py)."""
192
+ names = ['t', 'z', 'y', 'x'] if grid.z_name else ['t', 'y', 'x']
193
+ axes = {
194
+ 'x': {'values': [float(v) for v in sel.xs]},
195
+ 'y': {'values': [float(v) for v in sel.ys]},
196
+ 't': {'values': timesel.iso(sel.times)},
197
+ }
198
+ if grid.z_name:
199
+ axes['z'] = {'values': grid.z_values(sel.zs)}
200
+ ranges = {name: _nd(at_precision(arr, precisions[name]), names) for name, arr in data.items()}
201
+ return orjson.dumps(
202
+ {
203
+ 'type': 'Coverage',
204
+ 'domain': {
205
+ 'type': 'Domain',
206
+ 'domainType': 'Grid',
207
+ 'axes': axes,
208
+ 'referencing': _grid_referencing(grid, _horizontal_system(grid)),
209
+ },
210
+ 'parameters': params,
211
+ 'ranges': ranges,
212
+ },
213
+ option=_ORJSON,
214
+ )
215
+
216
+
217
+ def position_json(params, grid, sel, data, precisions):
218
+ """
219
+ The cell's series: a PointSeries in CRS84 (the cell centre, lon in [-180, 180)). With several
220
+ levels selected, a CoverageCollection of PointSeries, one per level (a PointSeries' z is single-valued).
221
+ """
222
+ t_text = timesel.iso(sel.times)
223
+ rounded = {name: at_precision(arr, precisions[name]) for name, arr in data.items()}
224
+ cell = {
225
+ 'indices': {grid.y_name: sel.i, grid.x_name: sel.j},
226
+ 'native': {grid.y_name: float(sel.ys[0]), grid.x_name: float(sel.xs[0])},
227
+ }
228
+ levels = grid.z_values(sel.zs) if grid.z_name else [None]
229
+ covs = []
230
+ for k, level in enumerate(levels):
231
+ axes = {'x': {'values': [sel.lon]}, 'y': {'values': [sel.lat]}, 't': {'values': t_text}}
232
+ if level is not None:
233
+ axes['z'] = {'values': [level]}
234
+ ranges = {}
235
+ for name, arr in rounded.items():
236
+ series = arr[:, k, 0, 0] if grid.z_name else arr[:, 0, 0]
237
+ ranges[name] = _range(np.ascontiguousarray(series)) # orjson serialises contiguous arrays only
238
+ covs.append(
239
+ {
240
+ 'type': 'Coverage',
241
+ 'domain': {'type': 'Domain', 'domainType': 'PointSeries', 'axes': axes},
242
+ 'ranges': ranges,
243
+ 'envlib:cell': cell,
244
+ }
245
+ )
246
+ geographic = {'type': 'GeographicCRS', 'id': edr.CRS84_URI}
247
+ refs = _grid_referencing(grid, geographic)
248
+ if len(covs) == 1:
249
+ cov = covs[0]
250
+ cov['domain']['referencing'] = refs
251
+ cov['parameters'] = params
252
+ return orjson.dumps(cov, option=_ORJSON)
253
+ return orjson.dumps(
254
+ {
255
+ 'type': 'CoverageCollection',
256
+ 'domainType': 'PointSeries',
257
+ 'parameters': params,
258
+ 'referencing': refs,
259
+ 'coverages': covs,
260
+ },
261
+ option=_ORJSON,
262
+ )
263
+
264
+
265
+ def position_csv(grid, sel, data, precisions):
266
+ """
267
+ One cell's series, long form: one row per time step (and level), with the cell's native
268
+ coordinates and its centre in CRS84. A cube has no CSV (Mike, 2026-11-25).
269
+ """
270
+ buf = io.StringIO()
271
+ w = csv.writer(buf, lineterminator='\n')
272
+ names = list(data)
273
+ ## the native columns keep the grid's coordinate names, suffixed if one is 'lon', 'lat' or 'z'
274
+ taken = {'time', 'z', 'lon', 'lat', *names}
275
+ native = [f'{n}_native' if n in taken else n for n in (grid.x_name, grid.y_name)]
276
+ w.writerow(['time'] + (['z'] if grid.z_name else []) + [*native, 'lon', 'lat', *names])
277
+ cell = [repr(float(sel.xs[0])), repr(float(sel.ys[0])), repr(sel.lon), repr(sel.lat)]
278
+ z_text = grid.z_text(sel.zs) if grid.z_name else [None]
279
+ ## data arrays are (t, [z,] 1, 1): one cell
280
+ series = {n: at_precision(arr, precisions[n]).reshape(arr.shape[0], -1) for n, arr in data.items()}
281
+ for ti, t in enumerate(timesel.iso(sel.times)):
282
+ for zi, z in enumerate(z_text):
283
+ head = [t] + ([z] if grid.z_name else [])
284
+ w.writerow(head + cell + [_text(series[n][ti, zi], precisions[n]) for n in names])
285
+ return buf.getvalue().encode()
@@ -0,0 +1,23 @@
1
+ """The API's one exception type: an HTTP answer other than 200."""
2
+
3
+
4
+ class ApiError(Exception):
5
+ """
6
+ An HTTP error answer. The body follows OGC API - Common's exception shape (`code`,
7
+ `description`), plus any `extra` fields (the 413's limits and the direct-access snippet).
8
+ """
9
+
10
+ def __init__(self, status, code, description, *, headers=None, extra=None):
11
+ super().__init__(f'{status} {code}: {description}')
12
+ self.status = status
13
+ self.code = code
14
+ self.description = description
15
+ self.headers = headers or {}
16
+ self.extra = extra or {}
17
+
18
+ def body(self):
19
+ return {'code': self.code, 'description': self.description, **self.extra}
20
+
21
+
22
+ class NoContent(Exception):
23
+ """A valid query that selects no data: 204 (EDR 1.2, Requirement A.78 C)."""