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.
- envlib_api/__init__.py +3 -0
- envlib_api/__main__.py +3 -0
- envlib_api/api/__init__.py +7 -0
- envlib_api/api/app.py +435 -0
- envlib_api/api/compress.py +52 -0
- envlib_api/api/cost.py +107 -0
- envlib_api/api/edr.py +343 -0
- envlib_api/api/encode.py +285 -0
- envlib_api/api/errors.py +23 -0
- envlib_api/api/grid.py +317 -0
- envlib_api/api/params.py +71 -0
- envlib_api/api/read.py +65 -0
- envlib_api/api/resolve.py +191 -0
- envlib_api/api/server.py +35 -0
- envlib_api/api/stations.py +96 -0
- envlib_api/api/timesel.py +97 -0
- envlib_api/cli.py +179 -0
- envlib_api/config.py +158 -0
- envlib_api/healthcheck.py +38 -0
- envlib_api/mirror.py +353 -0
- envlib_api/refresher.py +265 -0
- envlib_api/tests/__init__.py +0 -0
- envlib_api/tests/api_support.py +307 -0
- envlib_api/tests/conftest.py +12 -0
- envlib_api/tests/grid_support.py +217 -0
- envlib_api/tests/schemas/README.md +12 -0
- envlib_api/tests/schemas/coveragejson/coveragejson.json +1794 -0
- envlib_api/tests/schemas/edr/schemas/collections/DataQuery.yaml +38 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/areaLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/collection.yaml +137 -0
- envlib_api/tests/schemas/edr/schemas/collections/collections.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorDataQuery.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/collections/corridorLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/crsObject.yaml +15 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeDataQuery.yaml +20 -0
- envlib_api/tests/schemas/edr/schemas/collections/cubeLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/extent.yaml +311 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/instancesLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsDataQuery.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/collections/itemsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/locationsLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/observedPropertyCollection.yaml +51 -0
- envlib_api/tests/schemas/edr/schemas/collections/parameterNames.yaml +70 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionDataQuery.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/collections/positionLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusDataQuery.yaml +18 -0
- envlib_api/tests/schemas/edr/schemas/collections/radiusLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryDataQuery.yaml +10 -0
- envlib_api/tests/schemas/edr/schemas/collections/trajectoryLink.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/collections/units.yaml +42 -0
- envlib_api/tests/schemas/edr/schemas/core/confClasses.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/exception.yaml +8 -0
- envlib_api/tests/schemas/edr/schemas/core/landingPage.yaml +76 -0
- envlib_api/tests/schemas/edr/schemas/core/link.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/anyAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverage.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageBase.yaml +68 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageCollection.yaml +58 -0
- envlib_api/tests/schemas/edr/schemas/covjson/coverageJSON.yaml +46 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonI18n.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonObservedProperty.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameter.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonParameterGroup.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/covjsonUnit.yaml +31 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domain.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/covjson/domainBase.yaml +337 -0
- envlib_api/tests/schemas/edr/schemas/covjson/ndArray.yaml +88 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericAxis.yaml +11 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericRegularlySpacedAxis.yaml +17 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/numericValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/polygonValuesAxis.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/covjson/primitiveValuesAxis.yaml +22 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystem.yaml +48 -0
- envlib_api/tests/schemas/edr/schemas/covjson/referenceSystemConnection.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringSingleValueAxis.yaml +9 -0
- envlib_api/tests/schemas/edr/schemas/covjson/stringValuesAxis.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/covjson/targetConcept.yaml +13 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tiledNdArray.yaml +50 -0
- envlib_api/tests/schemas/edr/schemas/covjson/tupleValuesAxis.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxis.yaml +27 -0
- envlib_api/tests/schemas/edr/schemas/covjson/valuesAxisBase.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrFeatureCollectionGeoJSON.yaml +32 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/edrProperties.yaml +49 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/observedProperty.yaml +26 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/parameter.yaml +28 -0
- envlib_api/tests/schemas/edr/schemas/edr-geojson/unit.yaml +24 -0
- envlib_api/tests/schemas/edr/schemas/geojson/featureGeoJSON.yaml +29 -0
- envlib_api/tests/schemas/edr/schemas/geojson/geometrycollectionGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/linestringGeoJSON.yaml +23 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multilinestringGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipointGeoJSON.yaml +16 -0
- envlib_api/tests/schemas/edr/schemas/geojson/multipolygonGeoJSON.yaml +21 -0
- envlib_api/tests/schemas/edr/schemas/geojson/pointGeoJSON.yaml +14 -0
- envlib_api/tests/schemas/edr/schemas/geojson/polygonGeoJSON.yaml +19 -0
- envlib_api/tests/schemas/edr/schemas/i18n.yaml +4 -0
- envlib_api/tests/schemas/edr/schemas/numberMatched.yaml +7 -0
- envlib_api/tests/schemas/edr/schemas/numberReturned.yaml +12 -0
- envlib_api/tests/schemas/edr/schemas/parameterGroup.yaml +30 -0
- envlib_api/tests/schemas/edr/schemas/queries/instances.yaml +26 -0
- envlib_api/tests/support.py +320 -0
- envlib_api/tests/test_alerting_and_guards.py +325 -0
- envlib_api/tests/test_api.py +808 -0
- envlib_api/tests/test_api_review.py +428 -0
- envlib_api/tests/test_grid.py +1075 -0
- envlib_api/tests/test_ops.py +358 -0
- envlib_api/tests/test_refresher.py +354 -0
- envlib_api/tests/test_schemas.py +91 -0
- envlib_api-0.3.0.dist-info/METADATA +408 -0
- envlib_api-0.3.0.dist-info/RECORD +116 -0
- envlib_api-0.3.0.dist-info/WHEEL +4 -0
- envlib_api-0.3.0.dist-info/entry_points.txt +3 -0
- envlib_api-0.3.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,1075 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The grid routes (/position, /cube) against real grid datasets built by their real producers
|
|
3
|
+
(grid_support.py). Values are compared with direct cfdb reads of the same remote on the stored
|
|
4
|
+
quantity (round(x * 10**p)); CoverageJSON ranges are reshaped by the document's own axisNames and
|
|
5
|
+
shape, because the CoverageJSON schema checks neither (plan review edr-api-plan-4). The cell oracle
|
|
6
|
+
is independent of the API's CRS path: the wrfout's own XLAT/XLONG (WPS's formulas), nearest by
|
|
7
|
+
great-circle distance on WRF's 6,370 km sphere; on SST, the nearest stored centre by brute force.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import io
|
|
12
|
+
import math
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
import cfdb
|
|
17
|
+
import h5py
|
|
18
|
+
import numpy as np
|
|
19
|
+
import pyproj
|
|
20
|
+
import pytest
|
|
21
|
+
import s3func
|
|
22
|
+
from cfdb import dtypes
|
|
23
|
+
from ebooklet.mongo import MongoStore
|
|
24
|
+
from fastapi.testclient import TestClient
|
|
25
|
+
|
|
26
|
+
from envlib_api.api import cost, grid, read
|
|
27
|
+
from envlib_api.api.app import create_app
|
|
28
|
+
from envlib_api.tests.api_support import api_config
|
|
29
|
+
from envlib_api.tests.test_api import KeySpy
|
|
30
|
+
from envlib_api.tests.test_schemas import _errors, covjson_validator, edr_validator
|
|
31
|
+
|
|
32
|
+
IDENTITY = {'Accept-Encoding': 'identity'}
|
|
33
|
+
PRECISION = {
|
|
34
|
+
'wrf': {'temperature': 2},
|
|
35
|
+
'soil': {'volumetric_water_content': 3},
|
|
36
|
+
'static': {'altitude': 1},
|
|
37
|
+
'sst': {'temperature': 2, 'sea_ice_fraction': 2},
|
|
38
|
+
}
|
|
39
|
+
SPHERE = pyproj.Geod(a=6370000.0, f=0.0)
|
|
40
|
+
CELL_M = 3000.0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def client(gm, **cfg):
|
|
44
|
+
return TestClient(create_app(api_config(**cfg), db=gm.adb), headers=IDENTITY)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def gid(gm, name):
|
|
48
|
+
return gm.world.dataset_id[name]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def ints(a, p):
|
|
52
|
+
a = np.asarray(a, dtype='float64')
|
|
53
|
+
return np.where(np.isnan(a), np.nan, np.rint(a * 10.0**p))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def same(a, b, p):
|
|
57
|
+
a, b = np.asarray(a, dtype='float64'), np.asarray(b, dtype='float64')
|
|
58
|
+
return a.shape == b.shape and np.array_equal(ints(a, p), ints(b, p), equal_nan=True)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def nd(rng_obj, domain_axes, order):
|
|
62
|
+
"""A CoverageJSON NdArray as an array over `order` (every domain axis, single-valued ones included),
|
|
63
|
+
after checking its axisNames and shape against the domain."""
|
|
64
|
+
full = [len(domain_axes[n]['values']) for n in order]
|
|
65
|
+
keep = [n for n, s in zip(order, full, strict=True) if s > 1]
|
|
66
|
+
if keep:
|
|
67
|
+
assert rng_obj['axisNames'] == keep, (rng_obj['axisNames'], keep)
|
|
68
|
+
assert rng_obj['shape'] == [s for s in full if s > 1]
|
|
69
|
+
else:
|
|
70
|
+
assert 'axisNames' not in rng_obj and len(rng_obj['values']) == 1
|
|
71
|
+
vals = np.array([np.nan if v is None else v for v in rng_obj['values']], dtype='float64')
|
|
72
|
+
return vals.reshape(full)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Ref:
|
|
76
|
+
"""Direct reads of one remote (the oracle), read once: the fixtures are a few thousand values."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, ds):
|
|
79
|
+
self.crs = ds.crs
|
|
80
|
+
self.coords = {n: np.asarray(ds[n].data) for n in ds.coord_names}
|
|
81
|
+
self.vars = {n: np.asarray(ds[n].data, dtype='float64') for n in ds.data_var_names}
|
|
82
|
+
self.dims = {n: ds[n].coord_names for n in ds.data_var_names}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@pytest.fixture(scope='module')
|
|
86
|
+
def refs(grid_mirror):
|
|
87
|
+
out = {}
|
|
88
|
+
for name in ('wrf', 'soil', 'static', 'sst'):
|
|
89
|
+
with grid_mirror.world.direct(name) as ds:
|
|
90
|
+
out[name] = Ref(ds)
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@pytest.fixture(scope='module')
|
|
95
|
+
def wps(grid_mirror):
|
|
96
|
+
"""The WRF fixture's own cell centres, as WPS computed them (independent of any CRS)."""
|
|
97
|
+
with h5py.File(grid_mirror.world.wrfouts['wrf_b'], 'r') as h5:
|
|
98
|
+
return h5['XLAT'][0].astype('float64'), h5['XLONG'][0].astype('float64')
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def oracle_cell(xlat, xlong, lon, lat):
|
|
102
|
+
"""(i, j) nearest (lon, lat) on the sphere, and the gap (m) between the nearest and second-nearest centres."""
|
|
103
|
+
_, _, d = SPHERE.inv(np.full(xlat.size, lon), np.full(xlat.size, lat), xlong.ravel(), xlat.ravel())
|
|
104
|
+
order = np.argsort(d)
|
|
105
|
+
i, j = np.unravel_index(order[0], xlat.shape)
|
|
106
|
+
return (int(i), int(j)), float(d[order[1]] - d[order[0]])
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def open_grid(gm, name):
|
|
110
|
+
store = MongoStore(gm.adb, gm.world.dvid[name], http_session=s3func.HttpSession(stream=False))
|
|
111
|
+
return cfdb.open_store_dataset(store)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# -- the pure functions ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_nearest_index_edges_ties_and_direction():
|
|
118
|
+
"""The edge is half a cell out, plus EDGE_TOLERANCE (0.1%) of the edge spacing."""
|
|
119
|
+
assert grid.EDGE_TOLERANCE == 0.001
|
|
120
|
+
c = np.array([0.0, 1.0, 2.0])
|
|
121
|
+
assert grid.nearest_index(c, -0.5) == 0 # exactly half a cell out: inside
|
|
122
|
+
assert grid.nearest_index(c, -0.5009) == 0 # within the tolerance
|
|
123
|
+
edge = 0.5 + grid.EDGE_TOLERANCE
|
|
124
|
+
assert grid.nearest_index(c, -edge) == 0 and grid.nearest_index(c, 2 + edge) == 2 # the edge itself is in
|
|
125
|
+
assert grid.nearest_index(c, -0.5011) is None
|
|
126
|
+
assert grid.nearest_index(c, 2.5009) == 2 and grid.nearest_index(c, 2.5011) is None
|
|
127
|
+
assert grid.nearest_index(c, 0.5) == 0 # a midpoint: the lower cell
|
|
128
|
+
assert grid.nearest_index(c, 0.5000001) == 1
|
|
129
|
+
assert grid.nearest_index(c, float('nan')) is None and grid.nearest_index(c, float('inf')) is None
|
|
130
|
+
assert grid._strictly_increasing(c) and not grid._strictly_increasing(c[::-1])
|
|
131
|
+
assert not grid._strictly_increasing(np.array([0.0, 1.0, 1.0]))
|
|
132
|
+
irregular = np.array([0.0, 1.0, 3.0, 3.5]) # no step anywhere: midpoints 0.5, 2.0, 3.25
|
|
133
|
+
assert [grid.nearest_index(irregular, v) for v in (1.9, 2.1, 3.2, 3.3, 3.75, 3.76)] == [1, 2, 2, 3, 3, None]
|
|
134
|
+
# banker's rounding would put 533.5 at 534, outside a 534-cell axis
|
|
135
|
+
y = np.arange(534.0)
|
|
136
|
+
assert grid.nearest_index(y, 533.5) == 533 and grid.nearest_index(y, -0.5) == 0
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_the_round_number_edges_of_the_live_sst_axes_are_inside():
|
|
140
|
+
"""
|
|
141
|
+
On the live SST centres (float32 values), the cell edges fall 4.5e-6 deg inside the nominal
|
|
142
|
+
domain edges 120 and -60; the tolerance takes the round numbers in (Mike, 2026-11-25; code review
|
|
143
|
+
edr-api-code-4), and the far edges 200 and -10 were in already.
|
|
144
|
+
"""
|
|
145
|
+
lon = np.arange(120.025, 200.0, 0.05).astype('float32').astype('float64')
|
|
146
|
+
lat = np.arange(-59.975, -10.0, 0.05).astype('float32').astype('float64')
|
|
147
|
+
assert lon[0] - (lon[1] - lon[0]) / 2 > 120.0 and lat[0] - (lat[1] - lat[0]) / 2 > -60.0 # the premise
|
|
148
|
+
assert grid.nearest_index(lon, 120.0) == 0 and grid.nearest_index(lon, 200.0) == len(lon) - 1
|
|
149
|
+
assert grid.nearest_index(lat, -60.0) == 0 and grid.nearest_index(lat, -10.0) == len(lat) - 1
|
|
150
|
+
assert grid.nearest_index(lon, 119.999) is None and grid.nearest_index(lat, -60.001) is None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_the_lon_wrap_centres_on_the_axis():
|
|
154
|
+
"""On the live SST axis's float32 centres, whose west edge is 120.0000045, not 120.0."""
|
|
155
|
+
axis = np.arange(120.025, 200.0, 0.05).astype('float32').astype('float64')
|
|
156
|
+
assert len(axis) == 1600 and axis[0] - (axis[1] - axis[0]) / 2 > 120.0 # the premise: a noisy west edge
|
|
157
|
+
assert grid._wrap(-179.0, axis) == pytest.approx(181.0)
|
|
158
|
+
assert grid._wrap(181.0, axis) == pytest.approx(181.0)
|
|
159
|
+
assert grid._wrap(120.0, axis) == pytest.approx(120.0) # the west edge stays (a wrap from x0 would not)
|
|
160
|
+
assert grid._wrap(-160.0, axis) == pytest.approx(200.0)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@pytest.mark.parametrize(
|
|
164
|
+
'w,e,lon,inside',
|
|
165
|
+
[
|
|
166
|
+
(178, -178, 179.0, True),
|
|
167
|
+
(178, -178, -179.0, True),
|
|
168
|
+
(178, -178, 177.9, False),
|
|
169
|
+
(178, 182, -179.0, True), # 0-360 input
|
|
170
|
+
(178, 182, 181.0, True),
|
|
171
|
+
(-179, -170, 181.0, True), # SST's longitudes past 180
|
|
172
|
+
(-179, -170, -169.0, False),
|
|
173
|
+
(-180, 180, 0.0, True), # the whole globe
|
|
174
|
+
(10, 20, 15.0, True),
|
|
175
|
+
(10, 20, 375.0, True),
|
|
176
|
+
],
|
|
177
|
+
)
|
|
178
|
+
def test_the_mod_360_inside_rule(w, e, lon, inside):
|
|
179
|
+
assert bool(grid.lon_inside(np.array([lon]), w, grid.east_width(w, e))[0]) is inside
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@pytest.mark.parametrize('bbox', ['1,2,3', '1,2,3,4,5,6', 'a,b,c,d', '0,10,1,5', '0,-95,1,5', 'nan,0,1,1', '400,0,1,1'])
|
|
183
|
+
def test_malformed_bboxes_answer_400(bbox):
|
|
184
|
+
with pytest.raises(grid.ApiError) as e:
|
|
185
|
+
grid.parse_bbox(bbox)
|
|
186
|
+
assert e.value.status == 400
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_a_bbox_wider_than_360_degrees_answers_400():
|
|
190
|
+
with pytest.raises(grid.ApiError):
|
|
191
|
+
grid.parse_bbox('-200,0,200,1')
|
|
192
|
+
assert grid.parse_bbox('-180,-10,180,10') == (-180.0, -10.0, 180.0, 10.0)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@pytest.mark.parametrize(
|
|
196
|
+
'text,spec',
|
|
197
|
+
[
|
|
198
|
+
('1', ('level', 1.0)),
|
|
199
|
+
('1.0/2.0', ('interval', 1.0, 2.0)),
|
|
200
|
+
('../0.4', ('interval', None, 0.4)),
|
|
201
|
+
('0.4/..', ('interval', 0.4, None)),
|
|
202
|
+
],
|
|
203
|
+
)
|
|
204
|
+
def test_z_grammar(text, spec):
|
|
205
|
+
assert grid.parse_z(text) == spec
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@pytest.mark.parametrize('text', ['0.1,0.4', 'R2/0.1/0.3', '2/1', 'x', '1/2/3', 'inf'])
|
|
209
|
+
def test_unsupported_or_bad_z_answers_400(text):
|
|
210
|
+
with pytest.raises(grid.ApiError) as e:
|
|
211
|
+
grid.parse_z(text)
|
|
212
|
+
assert e.value.status == 400
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# -- the cell ---------------------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def test_the_nearest_cell_matches_the_wps_centres(grid_mirror, refs, wps):
|
|
219
|
+
"""
|
|
220
|
+
2,000 points around random cells. Only disagreements are excluded, and each must be a near-tie
|
|
221
|
+
(the two nearest centres within 0.005 cell of equidistant), under 0.5 % of points.
|
|
222
|
+
"""
|
|
223
|
+
xlat, xlong = wps
|
|
224
|
+
with grid_mirror.world.direct('wrf') as ds:
|
|
225
|
+
g = grid.Grid(ds, read.snapshot_attrs(ds))
|
|
226
|
+
rng = np.random.default_rng(3)
|
|
227
|
+
n, bad = 2000, []
|
|
228
|
+
for _ in range(n):
|
|
229
|
+
i, j = int(rng.integers(1, xlat.shape[0] - 1)), int(rng.integers(1, xlat.shape[1] - 1))
|
|
230
|
+
lat = xlat[i, j] + rng.uniform(-0.02, 0.02)
|
|
231
|
+
lon = xlong[i, j] + rng.uniform(-0.025, 0.025)
|
|
232
|
+
want, gap = oracle_cell(xlat, xlong, lon, lat)
|
|
233
|
+
got = g.nearest(lon, lat)
|
|
234
|
+
if got != want:
|
|
235
|
+
bad.append(gap)
|
|
236
|
+
assert len(bad) <= 0.005 * n, bad
|
|
237
|
+
assert all(gap < 0.005 * CELL_M for gap in bad), bad
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def test_the_wrf_fixture_straddles_the_antimeridian(wps):
|
|
241
|
+
"""The premise of the antimeridian tests: centres on both sides of 180."""
|
|
242
|
+
_, xlong = wps
|
|
243
|
+
assert (xlong < 0).sum() > 100 and (xlong > 0).sum() > 100
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def test_compared_neighbours_differ(refs):
|
|
247
|
+
"""The premise of every equality test here: a one-cell shift in x or y changes the values compared
|
|
248
|
+
(the raw synthetic T2 left 90 % of x-neighbours identical; plan review edr-api-plan-4)."""
|
|
249
|
+
for name, var in (('wrf', 'temperature'), ('sst', 'temperature'), ('static', 'altitude')):
|
|
250
|
+
a = refs[name].vars[var]
|
|
251
|
+
p = PRECISION[name][var]
|
|
252
|
+
dx = np.nanmean(ints(a[..., 1:], p) == ints(a[..., :-1], p))
|
|
253
|
+
dy = np.nanmean(ints(a[..., 1:, :], p) == ints(a[..., :-1, :], p))
|
|
254
|
+
assert dx < 0.05 and dy < 0.05, (name, dx, dy)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _position(c, gm, name, **params):
|
|
258
|
+
return c.get(f'/collections/{gid(gm, name)}/position', params=params)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def test_position_equals_a_direct_read_at_the_oracle_cell(grid_mirror, refs, wps):
|
|
262
|
+
xlat, xlong = wps
|
|
263
|
+
c = client(grid_mirror)
|
|
264
|
+
ref = refs['wrf']
|
|
265
|
+
for i, j in [(3, 4), (15, 20), (27, 37), (12, 30)]:
|
|
266
|
+
lat, lon = xlat[i, j] + 0.004, xlong[i, j] - 0.006
|
|
267
|
+
(oi, oj), _ = oracle_cell(xlat, xlong, lon, lat)
|
|
268
|
+
assert (oi, oj) == (i, j)
|
|
269
|
+
r = _position(c, grid_mirror, 'wrf', coords=f'POINT({lon} {lat})')
|
|
270
|
+
assert r.status_code == 200, r.text
|
|
271
|
+
cov = r.json()
|
|
272
|
+
assert cov['envlib:cell']['indices'] == {'y': i, 'x': j}
|
|
273
|
+
assert cov['envlib:cell']['native'] == {'y': float(ref.coords['y'][i]), 'x': float(ref.coords['x'][j])}
|
|
274
|
+
series = nd(cov['ranges']['temperature'], cov['domain']['axes'], ['t'])
|
|
275
|
+
assert same(series, ref.vars['temperature'][:, i, j], 2)
|
|
276
|
+
assert [t[:16] for t in cov['domain']['axes']['t']['values']] == [
|
|
277
|
+
str(t)[:16] for t in ref.coords['time'].astype('datetime64[m]')
|
|
278
|
+
]
|
|
279
|
+
clon, clat = cov['domain']['axes']['x']['values'][0], cov['domain']['axes']['y']['values'][0]
|
|
280
|
+
assert abs(clat - xlat[i, j]) < 1e-4 and abs(((clon - xlong[i, j] + 180) % 360) - 180) < 1e-4
|
|
281
|
+
assert -180 <= clon < 180
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def test_position_across_the_antimeridian_in_either_convention(grid_mirror, wps):
|
|
285
|
+
xlat, xlong = wps
|
|
286
|
+
c = client(grid_mirror)
|
|
287
|
+
east = np.argwhere(xlong < -179.7)[0] # a cell just east of 180
|
|
288
|
+
i, j = int(east[0]), int(east[1])
|
|
289
|
+
lat, lon = xlat[i, j], xlong[i, j]
|
|
290
|
+
a = _position(c, grid_mirror, 'wrf', coords=f'POINT({lon} {lat})').json()
|
|
291
|
+
b = _position(c, grid_mirror, 'wrf', coords=f'POINT({lon + 360} {lat})').json()
|
|
292
|
+
assert a['envlib:cell'] == b['envlib:cell'] and a['envlib:cell']['indices'] == {'y': i, 'x': j}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def test_position_outside_the_grid_answers_204(grid_mirror, refs):
|
|
296
|
+
c = client(grid_mirror)
|
|
297
|
+
r = _position(c, grid_mirror, 'wrf', coords='POINT(170 -45)')
|
|
298
|
+
assert r.status_code == 204 and r.headers['Vary'] == 'Accept-Encoding'
|
|
299
|
+
lon = refs['sst'].coords['longitude']
|
|
300
|
+
lat = refs['sst'].coords['latitude']
|
|
301
|
+
half_w = (lon[1] - lon[0]) / 2 # the tolerance is 0.1% of the spacing, so 0.2% of the half-cell
|
|
302
|
+
edge_in = lon[0] - half_w * 1.0019
|
|
303
|
+
edge_out = lon[0] - half_w * 1.0021
|
|
304
|
+
assert _position(c, grid_mirror, 'sst', coords=f'POINT({edge_in} {lat[3]})').status_code == 200
|
|
305
|
+
assert _position(c, grid_mirror, 'sst', coords=f'POINT({edge_out} {lat[3]})').status_code == 204
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def test_sst_position_wraps_and_matches_the_nearest_stored_centre(grid_mirror, refs):
|
|
309
|
+
ref = refs['sst']
|
|
310
|
+
lon, lat = ref.coords['longitude'], ref.coords['latitude']
|
|
311
|
+
c = client(grid_mirror)
|
|
312
|
+
rng = np.random.default_rng(5)
|
|
313
|
+
for _ in range(12):
|
|
314
|
+
qlon = rng.uniform(lon[0], lon[-1])
|
|
315
|
+
qlat = rng.uniform(lat[0], lat[-1])
|
|
316
|
+
j, i = int(np.argmin(np.abs(lon - qlon))), int(np.argmin(np.abs(lat - qlat)))
|
|
317
|
+
for given in (qlon, qlon - 360 if qlon > 180 else qlon):
|
|
318
|
+
r = _position(c, grid_mirror, 'sst', coords=f'POINT({given} {qlat})')
|
|
319
|
+
assert r.status_code == 200
|
|
320
|
+
cov = r.json()
|
|
321
|
+
assert cov['envlib:cell']['indices'] == {'latitude': i, 'longitude': j}
|
|
322
|
+
for var in ('temperature', 'sea_ice_fraction'):
|
|
323
|
+
assert same(nd(cov['ranges'][var], cov['domain']['axes'], ['t']), ref.vars[var][:, i, j], 2)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@pytest.mark.parametrize('coords', ['POINT(172 95)', 'POINT(1000 -40)', 'POINT(nan -40)', 'POINT(172 inf)'])
|
|
327
|
+
def test_position_with_an_impossible_point_answers_400(grid_mirror, coords):
|
|
328
|
+
assert _position(client(grid_mirror), grid_mirror, 'wrf', coords=coords).status_code == 400
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# -- z ----------------------------------------------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _soil_point(wps):
|
|
335
|
+
xlat, xlong = wps
|
|
336
|
+
return f'POINT({xlong[10, 12]} {xlat[10, 12]})', (10, 12)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def test_z_matches_the_stored_1_0_level_and_intervals_by_precision(grid_mirror, refs, wps):
|
|
340
|
+
ref = refs['soil']
|
|
341
|
+
assert repr(float(ref.coords['depth'][2])) == '0.9999999999999999' # the premise (as live)
|
|
342
|
+
c = client(grid_mirror)
|
|
343
|
+
coords, (i, j) = _soil_point(wps)
|
|
344
|
+
r = _position(c, grid_mirror, 'soil', coords=coords, z='1')
|
|
345
|
+
assert r.status_code == 200
|
|
346
|
+
cov = r.json()
|
|
347
|
+
assert cov['type'] == 'Coverage' and cov['domain']['axes']['z']['values'] == [1.0]
|
|
348
|
+
assert same(
|
|
349
|
+
nd(cov['ranges']['volumetric_water_content'], cov['domain']['axes'], ['t']),
|
|
350
|
+
ref.vars['volumetric_water_content'][:, 2, i, j],
|
|
351
|
+
3,
|
|
352
|
+
)
|
|
353
|
+
r = _position(c, grid_mirror, 'soil', coords=coords, z='1.0/2.0')
|
|
354
|
+
col = r.json()
|
|
355
|
+
assert col['type'] == 'CoverageCollection' and [x['domain']['axes']['z']['values'] for x in col['coverages']] == [
|
|
356
|
+
[1.0],
|
|
357
|
+
[2.0],
|
|
358
|
+
]
|
|
359
|
+
for k, cov in zip((2, 3), col['coverages'], strict=True):
|
|
360
|
+
vals = nd(cov['ranges']['volumetric_water_content'], cov['domain']['axes'], ['t'])
|
|
361
|
+
assert same(vals, ref.vars['volumetric_water_content'][:, k, i, j], 3)
|
|
362
|
+
assert any(r['coordinates'] == ['z'] and r['system']['type'] == 'VerticalCRS' for r in col['referencing'])
|
|
363
|
+
assert _position(c, grid_mirror, 'soil', coords=coords, z='0.5').status_code == 204
|
|
364
|
+
assert len(_position(c, grid_mirror, 'soil', coords=coords).json()['coverages']) == 4
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def test_z_on_a_grid_without_levels_is_ignored(grid_mirror, wps):
|
|
368
|
+
xlat, xlong = wps
|
|
369
|
+
c = client(grid_mirror)
|
|
370
|
+
coords = f'POINT({xlong[5, 5]} {xlat[5, 5]})'
|
|
371
|
+
a = _position(c, grid_mirror, 'wrf', coords=coords)
|
|
372
|
+
b = _position(c, grid_mirror, 'wrf', coords=coords, z='850')
|
|
373
|
+
assert a.status_code == b.status_code == 200 and a.content == b.content
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# -- the cube ---------------------------------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _wps_hull(xlat, xlong, bbox):
|
|
380
|
+
"""The hull by brute force on the WPS centres, with the margin of the nearest centre to an edge."""
|
|
381
|
+
w, s, e, n = bbox
|
|
382
|
+
width = e - w if w <= e else e - w + 360
|
|
383
|
+
rel = (xlong - w) % 360
|
|
384
|
+
inside = (xlat >= s) & (xlat <= n) & (rel <= width)
|
|
385
|
+
margin = min(np.abs(xlat - s).min(), np.abs(xlat - n).min(), np.abs(rel).min(), np.abs(rel - width).min())
|
|
386
|
+
rows, cols = np.nonzero(inside.any(axis=1))[0], np.nonzero(inside.any(axis=0))[0]
|
|
387
|
+
return ((int(rows[0]), int(rows[-1]) + 1), (int(cols[0]), int(cols[-1]) + 1)), margin
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
## Across 180 (w > e), chosen so no WPS centre lies within 0.0005 deg (about 50 m) of an edge: the WPS and
|
|
391
|
+
## pyproj centres agree to about 3 m (cfdb-ingest's test_wrf_crs), so the brute-force hull is unambiguous.
|
|
392
|
+
BBOX_180 = (179.67, -38.808, -179.78, -38.448)
|
|
393
|
+
DATA_VARS = {
|
|
394
|
+
'wrf': ('temperature',),
|
|
395
|
+
'sst': ('temperature', 'sea_ice_fraction'),
|
|
396
|
+
'soil': ('volumetric_water_content',),
|
|
397
|
+
'static': ('altitude',),
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _cube(c, gm, name, bbox, **params):
|
|
402
|
+
return c.get(f'/collections/{gid(gm, name)}/cube', params={'bbox': ','.join(map(str, bbox)), **params})
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def test_the_cube_is_the_hull_of_the_centres_and_equals_a_direct_read(grid_mirror, refs, wps):
|
|
406
|
+
xlat, xlong = wps
|
|
407
|
+
(rows, cols), margin = _wps_hull(xlat, xlong, BBOX_180)
|
|
408
|
+
assert margin > 0.0003 # no centre within ~30 m of an edge (10x the WPS/pyproj agreement)
|
|
409
|
+
assert rows[1] - rows[0] > 8 and cols[1] - cols[0] > 8 # crosses y and x chunk edges (8)
|
|
410
|
+
c = client(grid_mirror)
|
|
411
|
+
window = '2026-01-01T15:00Z/2026-01-02T03:00Z' # crosses time-chunk edges (6, origin -12)
|
|
412
|
+
r = _cube(c, grid_mirror, 'wrf', BBOX_180, datetime=window)
|
|
413
|
+
assert r.status_code == 200, r.text
|
|
414
|
+
cov = r.json()
|
|
415
|
+
ax = cov['domain']['axes']
|
|
416
|
+
ref = refs['wrf']
|
|
417
|
+
t = ref.coords['time']
|
|
418
|
+
tm = (t >= np.datetime64('2026-01-01T15:00')) & (t <= np.datetime64('2026-01-02T03:00'))
|
|
419
|
+
assert list(ax['y']['values']) == list(ref.coords['y'][rows[0] : rows[1]])
|
|
420
|
+
assert list(ax['x']['values']) == list(ref.coords['x'][cols[0] : cols[1]])
|
|
421
|
+
got = nd(cov['ranges']['temperature'], ax, ['t', 'y', 'x'])
|
|
422
|
+
assert same(got, ref.vars['temperature'][tm][:, rows[0] : rows[1], cols[0] : cols[1]], 2)
|
|
423
|
+
system = cov['domain']['referencing'][0]['system']
|
|
424
|
+
assert system['type'] == 'ProjectedCRS' and pyproj.CRS.from_wkt(system['envlib:wkt']) == ref.crs
|
|
425
|
+
# the same bbox in the 0-360 convention gives the same body
|
|
426
|
+
r2 = _cube(c, grid_mirror, 'wrf', (BBOX_180[0], BBOX_180[1], BBOX_180[2] + 360, BBOX_180[3]), datetime=window)
|
|
427
|
+
assert r2.content == r.content
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def test_the_hull_differs_from_the_corner_hull_here(grid_mirror, wps):
|
|
431
|
+
"""The premise of the corner-hull mutant: on this rotated grid the projected bbox corners give a
|
|
432
|
+
different rectangle from the centres."""
|
|
433
|
+
with grid_mirror.world.direct('wrf') as ds:
|
|
434
|
+
g = grid.Grid(ds, read.snapshot_attrs(ds))
|
|
435
|
+
w, s, e, n = BBOX_180
|
|
436
|
+
xs, ys = [], []
|
|
437
|
+
for lon, lat in ((w, s), (w, n), (e, s), (e, n)):
|
|
438
|
+
x, y = g.to_native(lon, lat)
|
|
439
|
+
xs.append(x)
|
|
440
|
+
ys.append(y)
|
|
441
|
+
corner = (
|
|
442
|
+
(grid.nearest_index(g.y, min(ys)), grid.nearest_index(g.y, max(ys)) + 1),
|
|
443
|
+
(grid.nearest_index(g.x, min(xs)), grid.nearest_index(g.x, max(xs)) + 1),
|
|
444
|
+
)
|
|
445
|
+
assert corner != g.hull(BBOX_180)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def test_an_sst_cube_across_180_in_both_notations(grid_mirror, refs):
|
|
449
|
+
ref = refs['sst']
|
|
450
|
+
lon, lat = ref.coords['longitude'], ref.coords['latitude']
|
|
451
|
+
c = client(grid_mirror)
|
|
452
|
+
a = _cube(c, grid_mirror, 'sst', (179.81, -40.31, -179.69, -39.81))
|
|
453
|
+
b = _cube(c, grid_mirror, 'sst', (179.81, -40.31, 180.31, -39.81))
|
|
454
|
+
assert a.status_code == 200 and a.content == b.content
|
|
455
|
+
cov = a.json()
|
|
456
|
+
ax = cov['domain']['axes']
|
|
457
|
+
cols = (lon >= 179.81) & (lon <= 180.31)
|
|
458
|
+
rows = (lat >= -40.31) & (lat <= -39.81)
|
|
459
|
+
assert ax['x']['values'] == list(lon[cols]) and max(ax['x']['values']) > 180
|
|
460
|
+
for var in ('temperature', 'sea_ice_fraction'):
|
|
461
|
+
assert same(nd(cov['ranges'][var], ax, ['t', 'y', 'x']), ref.vars[var][:, rows][:, :, cols], 2)
|
|
462
|
+
assert cov['domain']['referencing'][0]['system']['type'] == 'GeographicCRS'
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def test_a_soil_cube_carries_z_and_a_vertical_crs(grid_mirror, refs, wps):
|
|
466
|
+
xlat, xlong = wps
|
|
467
|
+
bbox = (xlong[8, 9] - 0.01, xlat[8, 9] - 0.01, xlong[11, 12] + 0.01, xlat[11, 12] + 0.01)
|
|
468
|
+
c = client(grid_mirror)
|
|
469
|
+
r = _cube(c, grid_mirror, 'soil', bbox, z='0.4/1')
|
|
470
|
+
assert r.status_code == 200
|
|
471
|
+
cov = r.json()
|
|
472
|
+
ax = cov['domain']['axes']
|
|
473
|
+
assert ax['z']['values'] == [0.4, 1.0]
|
|
474
|
+
rows, cols = grid_mirror_hull(grid_mirror, 'soil', bbox)
|
|
475
|
+
got = nd(cov['ranges']['volumetric_water_content'], ax, ['t', 'z', 'y', 'x'])
|
|
476
|
+
want = refs['soil'].vars['volumetric_water_content'][:, 1:3, rows[0] : rows[1], cols[0] : cols[1]]
|
|
477
|
+
assert same(got, want, 3)
|
|
478
|
+
assert [x['system']['type'] for x in cov['domain']['referencing']] == ['ProjectedCRS', 'VerticalCRS', 'TemporalRS']
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def grid_mirror_hull(gm, name, bbox):
|
|
482
|
+
with gm.world.direct(name) as ds:
|
|
483
|
+
return grid.Grid(ds, read.snapshot_attrs(ds)).hull(bbox)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def test_single_valued_axes_leave_axis_names(grid_mirror, refs, wps):
|
|
487
|
+
xlat, xlong = wps
|
|
488
|
+
bbox = (xlong[10, 10] - 0.03, xlat[10, 10] - 0.03, xlong[12, 12] + 0.03, xlat[12, 12] + 0.03)
|
|
489
|
+
cov = _cube(client(grid_mirror), grid_mirror, 'wrf', bbox, datetime='2026-01-01T13:00Z').json()
|
|
490
|
+
assert cov['ranges']['temperature']['axisNames'] == ['y', 'x']
|
|
491
|
+
cov = _cube(client(grid_mirror), grid_mirror, 'static', bbox).json()
|
|
492
|
+
assert cov['ranges']['altitude']['axisNames'] == ['y', 'x']
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def test_a_cube_outside_or_between_centres_answers_204(grid_mirror, wps):
|
|
496
|
+
xlat, xlong = wps
|
|
497
|
+
c = client(grid_mirror)
|
|
498
|
+
assert _cube(c, grid_mirror, 'wrf', (170, -45, 171, -44)).status_code == 204
|
|
499
|
+
# a bbox smaller than a cell, between centres
|
|
500
|
+
lat = (xlat[10, 10] + xlat[11, 10]) / 2
|
|
501
|
+
lon = (xlong[10, 10] + xlong[10, 11]) / 2
|
|
502
|
+
assert _cube(c, grid_mirror, 'wrf', (lon - 0.001, lat - 0.001, lon + 0.001, lat + 0.001)).status_code == 204
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def test_the_cube_crs_follows_the_collection(grid_mirror):
|
|
506
|
+
c = client(grid_mirror)
|
|
507
|
+
bbox = (179.62, -38.77, -179.83, -38.41)
|
|
508
|
+
assert _cube(c, grid_mirror, 'wrf', bbox, crs='CRS84').status_code == 400 # a rotated grid: native only
|
|
509
|
+
assert _cube(c, grid_mirror, 'wrf', bbox, crs='native').content == _cube(c, grid_mirror, 'wrf', bbox).content
|
|
510
|
+
sst = (179.81, -40.31, -179.69, -39.81)
|
|
511
|
+
assert _cube(c, grid_mirror, 'sst', sst, crs='native').status_code == 400
|
|
512
|
+
assert _cube(c, grid_mirror, 'sst', sst, crs='CRS84').status_code == 200
|
|
513
|
+
assert (
|
|
514
|
+
c.get(
|
|
515
|
+
f'/collections/{gid(grid_mirror, "wrf")}/cube', params={'bbox': '1,1,2,2', 'resolution-x': '2'}
|
|
516
|
+
).status_code
|
|
517
|
+
== 400
|
|
518
|
+
)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def test_position_csv_parses_back_to_the_same_values(grid_mirror, refs):
|
|
522
|
+
"""A cell east of 180 on SST (stored longitude past 180, lon in [-180, 180)), and soil at all levels."""
|
|
523
|
+
c = client(grid_mirror)
|
|
524
|
+
ref = refs['sst']
|
|
525
|
+
j = int(np.argmax(ref.coords['longitude'] > 180.5))
|
|
526
|
+
i = 40
|
|
527
|
+
qlon, qlat = float(ref.coords['longitude'][j]) - 360, float(ref.coords['latitude'][i])
|
|
528
|
+
params = {'coords': f'POINT({qlon} {qlat})'}
|
|
529
|
+
rows = list(csv.DictReader(io.StringIO(_position(c, grid_mirror, 'sst', f='CSV', **params).text)))
|
|
530
|
+
assert len(rows) == len(ref.coords['time'])
|
|
531
|
+
for k, row in enumerate(rows):
|
|
532
|
+
assert (
|
|
533
|
+
float(row['longitude']) == ref.coords['longitude'][j] > 180
|
|
534
|
+
and float(row['latitude']) == ref.coords['latitude'][i]
|
|
535
|
+
)
|
|
536
|
+
assert float(row['lon']) == pytest.approx(ref.coords['longitude'][j] - 360) and -180 <= float(row['lon']) < 180
|
|
537
|
+
assert row['time'] == str(ref.coords['time'][k]) + 'T00:00:00Z'
|
|
538
|
+
for var in ('temperature', 'sea_ice_fraction'):
|
|
539
|
+
v = ref.vars[var][k, i, j]
|
|
540
|
+
assert (row[var] == '') if np.isnan(v) else (row[var] == f'{np.rint(v * 100) / 100:.2f}')
|
|
541
|
+
soil = list(
|
|
542
|
+
csv.DictReader(io.StringIO(_position(c, grid_mirror, 'soil', coords='POINT(179.6 -38.6)', f='CSV').text))
|
|
543
|
+
)
|
|
544
|
+
assert [r['z'] for r in soil[:4]] == ['0.1', '0.4', '1', '2'] and len(soil) == 4 * len(refs['soil'].coords['time'])
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def test_a_cube_offers_no_csv(grid_mirror):
|
|
548
|
+
"""A cube is CoverageJSON only (Mike, 2026-11-25); asking for CSV fails loudly, naming what is offered."""
|
|
549
|
+
c = client(grid_mirror)
|
|
550
|
+
r = _cube(c, grid_mirror, 'sst', (179.81, -40.31, -179.69, -39.81), f='CSV')
|
|
551
|
+
assert r.status_code == 400 and 'CoverageJSON' in r.json()['description']
|
|
552
|
+
links = c.get(f'/collections/{gid(grid_mirror, "sst")}').json()['data_queries']
|
|
553
|
+
assert links['cube']['link']['variables']['output_formats'] == ['CoverageJSON']
|
|
554
|
+
assert links['position']['link']['variables']['output_formats'] == ['CoverageJSON', 'CSV']
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
# -- caps, keys and the batched read --------------------------------------------------------------
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _wrf_cube_chunks(gm, bbox, a, b):
|
|
561
|
+
with open_grid(gm, 'wrf') as ds:
|
|
562
|
+
(i0, i1), (j0, j1) = grid.Grid(ds, read.snapshot_attrs(ds)).hull(bbox)
|
|
563
|
+
return cost.count(ds, {'temperature': ((a, b), (i0, i1), (j0, j1))})
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def test_one_over_the_bytes_cap_on_a_cube_is_413_and_fetches_nothing(grid_mirror, monkeypatch):
|
|
567
|
+
window = '2026-01-01T15:00Z/2026-01-02T03:00Z'
|
|
568
|
+
nbytes, _ = _wrf_cube_chunks(grid_mirror, BBOX_180, 3, 16) # the window's positions: 15:00 is index 3
|
|
569
|
+
assert nbytes % (6 * 8 * 8 * 4) == 0 and nbytes // (6 * 8 * 8 * 4) > 8
|
|
570
|
+
ok = _cube(client(grid_mirror, max_decoded_bytes=nbytes), grid_mirror, 'wrf', BBOX_180, datetime=window)
|
|
571
|
+
assert ok.status_code == 200
|
|
572
|
+
spy = KeySpy(monkeypatch)
|
|
573
|
+
r = _cube(client(grid_mirror, max_decoded_bytes=nbytes - 1), grid_mirror, 'wrf', BBOX_180, datetime=window)
|
|
574
|
+
assert r.status_code == 413 and r.json()['limits'][0]['requested'] == nbytes
|
|
575
|
+
assert spy.data_keys('temperature') == [] and spy.data_fills('temperature') == []
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def test_the_values_cap_counts_the_levels(grid_mirror, wps):
|
|
579
|
+
"""A soil cube of all 4 levels, with the cap between t*y*x and t*z*y*x values."""
|
|
580
|
+
xlat, xlong = wps
|
|
581
|
+
bbox = (xlong[8, 9] - 0.01, xlat[8, 9] - 0.01, xlong[11, 12] + 0.01, xlat[11, 12] + 0.01)
|
|
582
|
+
(i0, i1), (j0, j1) = grid_mirror_hull(grid_mirror, 'soil', bbox)
|
|
583
|
+
flat = 8 * (i1 - i0) * (j1 - j0) # 8 time steps
|
|
584
|
+
c = client(grid_mirror, max_values=flat * 2)
|
|
585
|
+
r = _cube(c, grid_mirror, 'soil', bbox)
|
|
586
|
+
assert r.status_code == 413 and r.json()['limits'][0]['requested'] == flat * 4
|
|
587
|
+
assert _cube(client(grid_mirror, max_values=flat * 4), grid_mirror, 'soil', bbox).status_code == 200
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
@pytest.mark.parametrize('name', ['wrf', 'soil', 'static', 'sst'])
|
|
591
|
+
def test_the_key_list_equals_the_keys_cfdb_itself_asks_for(grid_mirror, monkeypatch, name):
|
|
592
|
+
"""Random selections, including the negative time origins, the 4-D soil and the one-chunk static map."""
|
|
593
|
+
spy = KeySpy(monkeypatch)
|
|
594
|
+
rng = np.random.default_rng(9)
|
|
595
|
+
with open_grid(grid_mirror, name) as ds:
|
|
596
|
+
for _ in range(25):
|
|
597
|
+
var = list(ds.data_var_names)[int(rng.integers(len(ds.data_var_names)))]
|
|
598
|
+
sel = []
|
|
599
|
+
for n in ds[var].shape:
|
|
600
|
+
lo = int(rng.integers(0, n))
|
|
601
|
+
sel.append((lo, int(rng.integers(lo + 1, n + 1))))
|
|
602
|
+
sel = tuple(sel)
|
|
603
|
+
mine = cost.chunk_keys(ds, {var: sel})[var]
|
|
604
|
+
spy.loaded.clear()
|
|
605
|
+
_ = ds[var][tuple(slice(lo, hi) for lo, hi in sel)].data
|
|
606
|
+
theirs = list(dict.fromkeys(spy.data_keys(var)))
|
|
607
|
+
assert sorted(mine) == sorted(theirs), (var, sel)
|
|
608
|
+
## the caps' counts against cfdb's own keys, not against chunk_keys (code review edr-api-code-4)
|
|
609
|
+
nbytes, nvalues = cost.count(ds, {var: sel})
|
|
610
|
+
dv = ds[var]
|
|
611
|
+
assert nbytes == len(theirs) * math.prod(dv.chunk_shape) * dv.dtype.dtype_decoded.itemsize
|
|
612
|
+
assert nvalues == math.prod(hi - lo for lo, hi in sel)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
@pytest.mark.parametrize(
|
|
616
|
+
'name,path,params',
|
|
617
|
+
[
|
|
618
|
+
('wrf', 'cube', {'bbox': ','.join(map(str, BBOX_180)), 'datetime': '2026-01-01T15:00Z/2026-01-02T03:00Z'}),
|
|
619
|
+
('sst', 'cube', {'bbox': '179.81,-40.31,-179.69,-39.81'}),
|
|
620
|
+
('soil', 'position', {'coords': 'POINT(179.6 -38.6)'}),
|
|
621
|
+
('static', 'cube', {'bbox': '179.5,-38.9,-179.5,-38.3'}),
|
|
622
|
+
],
|
|
623
|
+
)
|
|
624
|
+
def test_one_batched_fetch_and_nothing_after_it(grid_mirror, monkeypatch, name, path, params):
|
|
625
|
+
spy = KeySpy(monkeypatch)
|
|
626
|
+
r = client(grid_mirror).get(f'/collections/{gid(grid_mirror, name)}/{path}', params=params)
|
|
627
|
+
assert r.status_code == 200
|
|
628
|
+
prefixes = tuple(f'{v}!' for v in DATA_VARS[name])
|
|
629
|
+
data_fills = [ks for ks in spy.fills if any(k.startswith(prefixes) for k in ks)]
|
|
630
|
+
assert len(data_fills) == 1, data_fills # every data chunk came in the one batched load
|
|
631
|
+
assert {k.split('!')[0] for k in data_fills[0]} == set(DATA_VARS[name]) # all parameters in it
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def test_a_numpy_bound_is_refused_before_any_fetch(grid_mirror, monkeypatch):
|
|
635
|
+
"""cfdb reads a numpy-integer slice bound as the whole axis (plan review edr-api-plan-4)."""
|
|
636
|
+
from envlib_api.api import app as app_mod
|
|
637
|
+
|
|
638
|
+
real = app_mod.GridSelection.sel
|
|
639
|
+
monkeypatch.setattr(
|
|
640
|
+
app_mod.GridSelection, 'sel', lambda self, dims: tuple((np.int64(a), np.int64(b)) for a, b in real(self, dims))
|
|
641
|
+
)
|
|
642
|
+
spy = KeySpy(monkeypatch)
|
|
643
|
+
r = _cube(client(grid_mirror), grid_mirror, 'wrf', BBOX_180)
|
|
644
|
+
assert r.status_code == 500
|
|
645
|
+
assert spy.data_fills('temperature') == []
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def test_every_grid_answer_is_verified_and_nothing_is_read_after(grid_mirror, monkeypatch):
|
|
649
|
+
real_verify, real_fill, real_get = MongoStore.verify, MongoStore._fill, MongoStore.get
|
|
650
|
+
verified = []
|
|
651
|
+
|
|
652
|
+
def verify(store):
|
|
653
|
+
real_verify(store)
|
|
654
|
+
store._test_verified = True
|
|
655
|
+
verified.append(1)
|
|
656
|
+
|
|
657
|
+
def guard(real):
|
|
658
|
+
def inner(store, *a, **kw):
|
|
659
|
+
assert not getattr(store, '_test_verified', False), 'the store was read after verify()'
|
|
660
|
+
return real(store, *a, **kw)
|
|
661
|
+
|
|
662
|
+
return inner
|
|
663
|
+
|
|
664
|
+
monkeypatch.setattr(MongoStore, 'verify', verify)
|
|
665
|
+
monkeypatch.setattr(MongoStore, '_fill', guard(real_fill))
|
|
666
|
+
monkeypatch.setattr(MongoStore, 'get', guard(real_get))
|
|
667
|
+
c = client(grid_mirror)
|
|
668
|
+
for name, path, params, status in [
|
|
669
|
+
('wrf', 'cube', {'bbox': ','.join(map(str, BBOX_180))}, 200),
|
|
670
|
+
('wrf', 'position', {'coords': 'POINT(179.6 -38.6)', 'f': 'CSV'}, 200),
|
|
671
|
+
('soil', 'position', {'coords': 'POINT(179.6 -38.6)', 'z': '1'}, 200),
|
|
672
|
+
('soil', 'position', {'coords': 'POINT(179.6 -38.6)', 'z': '0.5'}, 204),
|
|
673
|
+
('sst', 'position', {'coords': 'POINT(170 -40)'}, 204),
|
|
674
|
+
('wrf', 'locations', {}, 404),
|
|
675
|
+
]:
|
|
676
|
+
before = len(verified)
|
|
677
|
+
assert c.get(f'/collections/{gid(grid_mirror, name)}/{path}', params=params).status_code == status
|
|
678
|
+
assert len(verified) > before, (name, path, params)
|
|
679
|
+
before = len(verified)
|
|
680
|
+
assert c.get(f'/collections/{gid(grid_mirror, "sst")}').status_code == 200 and len(verified) > before
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
# -- dispatch, collections and schemas ------------------------------------------------------------
|
|
684
|
+
|
|
685
|
+
|
|
686
|
+
def test_collections_list_every_grid_and_each_offers_its_queries(grid_mirror):
|
|
687
|
+
c = client(grid_mirror)
|
|
688
|
+
cols = {x['id']: x for x in c.get('/collections').json()['collections']}
|
|
689
|
+
assert set(cols) == {gid(grid_mirror, n) for n in ('wrf', 'soil', 'static', 'sst')}
|
|
690
|
+
for name in ('wrf', 'soil', 'static', 'sst'):
|
|
691
|
+
col = cols[gid(grid_mirror, name)]
|
|
692
|
+
assert set(col['data_queries']) == {'position', 'cube'}
|
|
693
|
+
assert col['crs'] == (['CRS84'] if name == 'sst' else ['CRS84', 'native'])
|
|
694
|
+
v = cols[gid(grid_mirror, 'soil')]['extent']['vertical']
|
|
695
|
+
assert v['values'] == ['0.1', '0.4', '1', '2'] and v['interval'] == [['0.1', '2']] and v['vrs']
|
|
696
|
+
assert c.get(f'/collections/{gid(grid_mirror, "wrf")}/locations').status_code == 404
|
|
697
|
+
assert (
|
|
698
|
+
c.get(
|
|
699
|
+
f'/collections/{gid(grid_mirror, "wrf")}/area', params={'coords': 'POLYGON((0 0,1 0,1 1,0 0))'}
|
|
700
|
+
).status_code
|
|
701
|
+
== 404
|
|
702
|
+
)
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def test_grid_queries_on_a_station_collection_answer_404(mirror):
|
|
706
|
+
from envlib_api.tests.test_api import cid as station_cid
|
|
707
|
+
from envlib_api.tests.test_api import client as station_client
|
|
708
|
+
|
|
709
|
+
c = station_client(mirror)
|
|
710
|
+
r = c.get(f'/collections/{station_cid(mirror, "sf")}/position', params={'coords': 'POINT(172 -43)'})
|
|
711
|
+
assert r.status_code == 404 and 'locations' in r.json()['description']
|
|
712
|
+
assert c.get(f'/collections/{station_cid(mirror, "sf")}/cube', params={'bbox': '1,1,2,2'}).status_code == 404
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def test_a_grid_without_a_crs_or_axes_is_not_served(grid_mirror, monkeypatch):
|
|
716
|
+
"""envlib refuses to publish a dataset without a CRS, so this is the convention check on its own."""
|
|
717
|
+
with grid_mirror.world.direct('sst') as ds:
|
|
718
|
+
attrs = read.snapshot_attrs(ds)
|
|
719
|
+
g = grid.Grid(ds, attrs)
|
|
720
|
+
assert g.geographic and g.x_name == 'longitude'
|
|
721
|
+
monkeypatch.setattr(type(ds), 'crs', property(lambda self: None), raising=False)
|
|
722
|
+
with pytest.raises(grid.ApiError) as e:
|
|
723
|
+
grid.Grid(ds, attrs)
|
|
724
|
+
assert e.value.status == 404 and e.value.code == 'NotServed'
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def test_grid_collections_and_coverages_validate(grid_mirror, wps):
|
|
728
|
+
c = client(grid_mirror)
|
|
729
|
+
v = edr_validator('collections/collection.yaml')
|
|
730
|
+
for name in ('wrf', 'soil', 'static', 'sst'):
|
|
731
|
+
assert _errors(v, c.get(f'/collections/{gid(grid_mirror, name)}').json()) == [], name
|
|
732
|
+
cv = covjson_validator()
|
|
733
|
+
bodies = [
|
|
734
|
+
_cube(c, grid_mirror, 'wrf', BBOX_180).json(),
|
|
735
|
+
_cube(c, grid_mirror, 'soil', BBOX_180).json(),
|
|
736
|
+
_cube(c, grid_mirror, 'sst', (179.81, -40.31, -179.69, -39.81)).json(),
|
|
737
|
+
_position(c, grid_mirror, 'wrf', coords='POINT(179.6 -38.6)').json(),
|
|
738
|
+
_position(c, grid_mirror, 'soil', coords='POINT(179.6 -38.6)').json(),
|
|
739
|
+
_position(c, grid_mirror, 'soil', coords='POINT(179.6 -38.6)', z='1').json(),
|
|
740
|
+
]
|
|
741
|
+
for body in bodies:
|
|
742
|
+
assert _errors(cv, body) == [], body.get('type')
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def test_the_validators_reject_a_broken_grid_collection(grid_mirror):
|
|
746
|
+
"""They must fail on purpose: numeric vertical values, and a cube link without height_units."""
|
|
747
|
+
v = edr_validator('collections/collection.yaml')
|
|
748
|
+
col = client(grid_mirror).get(f'/collections/{gid(grid_mirror, "soil")}').json()
|
|
749
|
+
broken = {**col, 'extent': {**col['extent'], 'vertical': {**col['extent']['vertical'], 'interval': [[0.1, 2.0]]}}}
|
|
750
|
+
assert _errors(v, broken)
|
|
751
|
+
cube = col['data_queries']['cube']['link']['variables']
|
|
752
|
+
no_units = {k: x for k, x in cube.items() if k != 'height_units'}
|
|
753
|
+
dq = {**col['data_queries'], 'cube': {'link': {**col['data_queries']['cube']['link'], 'variables': no_units}}}
|
|
754
|
+
assert _errors(v, {**col, 'data_queries': dq})
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def test_the_transformer_cache_is_shared_safely_across_threads(grid_mirror, refs):
|
|
758
|
+
wkt = refs['wrf'].crs.to_wkt()
|
|
759
|
+
want = pyproj.Transformer.from_crs('OGC:CRS84', refs['wrf'].crs, always_xy=True).transform(179.6, -38.6)
|
|
760
|
+
out, errors = [], []
|
|
761
|
+
|
|
762
|
+
def run():
|
|
763
|
+
try:
|
|
764
|
+
for _ in range(50):
|
|
765
|
+
out.append(grid._transformer(wkt, False).transform(179.6, -38.6))
|
|
766
|
+
except Exception as err: # noqa: BLE001
|
|
767
|
+
errors.append(err)
|
|
768
|
+
|
|
769
|
+
threads = [threading.Thread(target=run) for _ in range(16)]
|
|
770
|
+
for t in threads:
|
|
771
|
+
t.start()
|
|
772
|
+
for t in threads:
|
|
773
|
+
t.join()
|
|
774
|
+
assert not errors and len(out) == 800 and all(o == want for o in out)
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
@pytest.mark.parametrize('inverse', [False, True])
|
|
778
|
+
def test_the_cached_transformer_is_the_searched_operation_as_a_pipeline(refs, inverse):
|
|
779
|
+
"""The cache holds a from_pipeline transformer of the operation from_crs chose (a new thread
|
|
780
|
+
rebuilds it in 0.2 ms, not 16 ms), and it gives the same numbers as from_crs."""
|
|
781
|
+
crs = refs['wrf'].crs
|
|
782
|
+
searched = (
|
|
783
|
+
pyproj.Transformer.from_crs(crs, 'OGC:CRS84', always_xy=True)
|
|
784
|
+
if inverse
|
|
785
|
+
else pyproj.Transformer.from_crs('OGC:CRS84', crs, always_xy=True)
|
|
786
|
+
)
|
|
787
|
+
cached = grid._transformer(crs.to_wkt(), inverse)
|
|
788
|
+
assert cached.definition == searched.definition and cached.definition.startswith('proj=pipeline')
|
|
789
|
+
assert grid._transformer(crs.to_wkt(), inverse) is cached # held, not rebuilt per call
|
|
790
|
+
assert isinstance(cached._transformer_maker, pyproj.transformer.TransformerFromPipeline)
|
|
791
|
+
rng = np.random.default_rng(8)
|
|
792
|
+
if inverse:
|
|
793
|
+
x, y = refs['wrf'].coords['x'], refs['wrf'].coords['y']
|
|
794
|
+
a, b = rng.uniform(x.min(), x.max(), 5000), rng.uniform(y.min(), y.max(), 5000)
|
|
795
|
+
else:
|
|
796
|
+
a, b = rng.uniform(178.0, 182.0, 5000), rng.uniform(-39.5, -38.2, 5000)
|
|
797
|
+
assert np.array_equal(np.array(cached.transform(a, b)), np.array(searched.transform(a, b)))
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
# -- code review edr-api-code-4 ---------------------------------------------------------------------
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
@pytest.mark.parametrize(
|
|
804
|
+
'crs',
|
|
805
|
+
['EPSG:4272', '+proj=ob_tran +o_proj=longlat +o_lon_p=0 +o_lat_p=39.25 +lon_0=18 +R=6371229 +no_defs'],
|
|
806
|
+
ids=['NZGD49', 'rotated pole'],
|
|
807
|
+
)
|
|
808
|
+
def test_a_geographic_crs_other_than_wgs84_is_not_served(grid_mirror, monkeypatch, crs):
|
|
809
|
+
"""NZGD49 is 187 m from WGS 84; a rotated pole is a Derived Geographic CRS. Read as CRS84 they would
|
|
810
|
+
serve the wrong cells (Mike, 2026-11-25: refuse them)."""
|
|
811
|
+
with grid_mirror.world.direct('sst') as ds:
|
|
812
|
+
attrs = read.snapshot_attrs(ds)
|
|
813
|
+
assert grid.Grid(ds, attrs).geographic # served on its own WGS 84
|
|
814
|
+
for ok in ('OGC:CRS84', 'EPSG:4326'):
|
|
815
|
+
monkeypatch.setattr(type(ds), 'crs', property(lambda self, c=ok: pyproj.CRS(c)), raising=False)
|
|
816
|
+
assert grid.Grid(ds, attrs).geographic
|
|
817
|
+
monkeypatch.setattr(type(ds), 'crs', property(lambda self: pyproj.CRS(crs)), raising=False)
|
|
818
|
+
assert pyproj.CRS(crs).is_geographic # the premise
|
|
819
|
+
with pytest.raises(grid.ApiError) as e:
|
|
820
|
+
grid.Grid(ds, attrs)
|
|
821
|
+
assert e.value.status == 404 and 'other than WGS 84' in e.value.description
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def test_each_query_link_lists_only_the_crs_it_accepts(grid_mirror):
|
|
825
|
+
c = client(grid_mirror)
|
|
826
|
+
for name, cube in (('wrf', ['native']), ('soil', ['native']), ('sst', ['CRS84'])):
|
|
827
|
+
dq = c.get(f'/collections/{gid(grid_mirror, name)}').json()['data_queries']
|
|
828
|
+
assert [d['crs'] for d in dq['cube']['link']['variables']['crs_details']] == cube
|
|
829
|
+
assert [d['crs'] for d in dq['position']['link']['variables']['crs_details']] == ['CRS84']
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def test_the_transformer_cache_falls_back_when_proj_keeps_several_operations():
|
|
833
|
+
"""EPSG:27200 (NZMG): PROJ's definition is 'unavailable until proj_trans is called', so from_pipeline
|
|
834
|
+
refuses it and the from_crs transformer is cached; its numbers are from_crs's."""
|
|
835
|
+
crs = pyproj.CRS('EPSG:27200')
|
|
836
|
+
searched = pyproj.Transformer.from_crs('OGC:CRS84', crs, always_xy=True)
|
|
837
|
+
assert 'unavailable' in searched.definition # the premise
|
|
838
|
+
cached = grid._transformer(crs.to_wkt(), False)
|
|
839
|
+
assert isinstance(cached._transformer_maker, pyproj.transformer.TransformerFromCRS)
|
|
840
|
+
rng = np.random.default_rng(12)
|
|
841
|
+
lon, lat = rng.uniform(167.0, 178.0, 2000), rng.uniform(-47.0, -35.0, 2000)
|
|
842
|
+
assert np.array_equal(np.array(cached.transform(lon, lat)), np.array(searched.transform(lon, lat)))
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _point_bbox(lon, lat):
|
|
846
|
+
return (float(lon), float(lat), float(lon), float(lat))
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def test_a_bbox_edge_on_a_centre_includes_it_and_w_equal_e_is_one_meridian(grid_mirror):
|
|
850
|
+
"""A bbox that is one centre (w = e, s = n) selects exactly that cell: the edges are inclusive."""
|
|
851
|
+
with grid_mirror.world.direct('sst') as ds:
|
|
852
|
+
g = grid.Grid(ds, read.snapshot_attrs(ds))
|
|
853
|
+
i, j = 10, 30
|
|
854
|
+
assert g.hull(_point_bbox(g.x[j], g.y[i])) == ((i, i + 1), (j, j + 1))
|
|
855
|
+
assert g.hull((float(g.x[j]), float(g.y[i]), float(g.x[j + 2]), float(g.y[i + 2]))) == ((i, i + 3), (j, j + 3))
|
|
856
|
+
with grid_mirror.world.direct('wrf') as ds:
|
|
857
|
+
g = grid.Grid(ds, read.snapshot_attrs(ds))
|
|
858
|
+
i, j = 12, 17
|
|
859
|
+
lon, lat = g.lonlat(np.array([g.x[j]]), np.array([g.y[i]]))
|
|
860
|
+
assert g.hull(_point_bbox(lon[0], lat[0])) == ((i, i + 1), (j, j + 1))
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
@pytest.mark.parametrize(
|
|
864
|
+
'bbox,ok',
|
|
865
|
+
[
|
|
866
|
+
('360,0,360,1', True),
|
|
867
|
+
('-360,0,-360,1', True),
|
|
868
|
+
('360.0001,0,360.0001,1', False),
|
|
869
|
+
('-180,0,180,1', True), # width exactly 360
|
|
870
|
+
('-180,0,180.0001,1', False),
|
|
871
|
+
('1_0,2,30,4', False), # float() would take these
|
|
872
|
+
('٣,0,5,5', False),
|
|
873
|
+
('1e999,0,5,5', False),
|
|
874
|
+
],
|
|
875
|
+
)
|
|
876
|
+
def test_bbox_limits_and_strict_numbers(bbox, ok):
|
|
877
|
+
if ok:
|
|
878
|
+
grid.parse_bbox(bbox)
|
|
879
|
+
else:
|
|
880
|
+
with pytest.raises(grid.ApiError) as e:
|
|
881
|
+
grid.parse_bbox(bbox)
|
|
882
|
+
assert e.value.status == 400
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
@pytest.mark.parametrize('text', ['1_0', '١', '1e999'])
|
|
886
|
+
def test_z_takes_plain_numbers_only(text):
|
|
887
|
+
with pytest.raises(grid.ApiError):
|
|
888
|
+
grid.parse_z(text)
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def test_a_point_with_z_answers_400(grid_mirror):
|
|
892
|
+
r = _position(client(grid_mirror), grid_mirror, 'wrf', coords='POINT Z (179.6 -38.6 5)')
|
|
893
|
+
assert r.status_code == 400 and '2-D' in r.json()['description']
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def test_the_csv_row_cap_applies_to_a_position(grid_mirror, refs):
|
|
897
|
+
rows = 4 * len(refs['soil'].coords['time']) # 4 levels x every step
|
|
898
|
+
params = {'coords': 'POINT(179.6 -38.6)', 'f': 'CSV'}
|
|
899
|
+
r = _position(client(grid_mirror, max_csv_rows=rows - 1), grid_mirror, 'soil', **params)
|
|
900
|
+
assert r.status_code == 413 and r.json()['limits'] == [{'limit': 'CSV rows', 'requested': rows, 'max': rows - 1}]
|
|
901
|
+
assert _position(client(grid_mirror, max_csv_rows=rows), grid_mirror, 'soil', **params).status_code == 200
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
def test_a_windowed_position_has_the_window_s_labels_and_values(grid_mirror, refs, wps):
|
|
905
|
+
xlat, xlong = wps
|
|
906
|
+
ref = refs['wrf']
|
|
907
|
+
t = ref.coords['time']
|
|
908
|
+
window = (np.datetime64('2026-01-01T15:30'), np.datetime64('2026-01-02T03:00')) # an off-step start
|
|
909
|
+
m = (t >= window[0]) & (t <= window[1])
|
|
910
|
+
cov = _position(
|
|
911
|
+
client(grid_mirror),
|
|
912
|
+
grid_mirror,
|
|
913
|
+
'wrf',
|
|
914
|
+
coords=f'POINT({xlong[14, 9]} {xlat[14, 9]})',
|
|
915
|
+
datetime='2026-01-01T15:30Z/2026-01-02T03:00Z',
|
|
916
|
+
).json()
|
|
917
|
+
assert cov['domain']['axes']['t']['values'] == [str(x) + ':00Z' for x in t[m]]
|
|
918
|
+
assert same(nd(cov['ranges']['temperature'], cov['domain']['axes'], ['t']), ref.vars['temperature'][m, 14, 9], 2)
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
@pytest.mark.parametrize(
|
|
922
|
+
'path,params', [('position', {'coords': 'POINT(179.6 -38.6)'}), ('cube', {'bbox': ','.join(map(str, BBOX_180))})]
|
|
923
|
+
)
|
|
924
|
+
def test_a_time_window_with_no_step_answers_204(grid_mirror, path, params):
|
|
925
|
+
r = client(grid_mirror).get(
|
|
926
|
+
f'/collections/{gid(grid_mirror, "wrf")}/{path}', params={**params, 'datetime': '2030-01-01T00:00Z'}
|
|
927
|
+
)
|
|
928
|
+
assert r.status_code == 204
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def test_parameter_name_selects_on_grids(grid_mirror, refs):
|
|
932
|
+
ref = refs['sst']
|
|
933
|
+
c = client(grid_mirror)
|
|
934
|
+
pos = _position(c, grid_mirror, 'sst', coords='POINT(179.6 -40.0)', **{'parameter-name': 'sea_ice_fraction'}).json()
|
|
935
|
+
assert list(pos['ranges']) == ['sea_ice_fraction'] and list(pos['parameters']) == ['sea_ice_fraction']
|
|
936
|
+
cube = _cube(
|
|
937
|
+
c, grid_mirror, 'sst', (179.81, -40.31, -179.69, -39.81), **{'parameter-name': 'sea_ice_fraction'}
|
|
938
|
+
).json()
|
|
939
|
+
assert list(cube['ranges']) == ['sea_ice_fraction']
|
|
940
|
+
j = int(np.argmin(np.abs(ref.coords['longitude'] - 179.6)))
|
|
941
|
+
i = int(np.argmin(np.abs(ref.coords['latitude'] + 40.0)))
|
|
942
|
+
assert same(
|
|
943
|
+
nd(pos['ranges']['sea_ice_fraction'], pos['domain']['axes'], ['t']), ref.vars['sea_ice_fraction'][:, i, j], 2
|
|
944
|
+
)
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def test_a_grid_answer_s_etag_names_its_version(grid_mirror):
|
|
948
|
+
c = client(grid_mirror)
|
|
949
|
+
tags = {}
|
|
950
|
+
for name in ('wrf', 'sst'):
|
|
951
|
+
r = _position(c, grid_mirror, name, coords='POINT(179.6 -38.6)' if name == 'wrf' else 'POINT(179.6 -40.0)')
|
|
952
|
+
tags[name] = r.headers['ETag']
|
|
953
|
+
applied = grid_mirror.admin['datasets'].find_one({'_id': grid_mirror.world.dvid[name]})['applied']
|
|
954
|
+
assert tags[name] == f'"{grid_mirror.world.dvid[name]}-{applied["uuid"]}-{applied["ts"]}"'
|
|
955
|
+
assert c.get(f'/collections/{gid(grid_mirror, name)}').headers['ETag'] == tags[name]
|
|
956
|
+
assert tags['wrf'] != tags['sst']
|
|
957
|
+
|
|
958
|
+
|
|
959
|
+
def test_the_deadline_is_checked_after_the_grid_fetch(grid_mirror, monkeypatch):
|
|
960
|
+
real = MongoStore.load_items
|
|
961
|
+
calls = []
|
|
962
|
+
|
|
963
|
+
def slow_first(store, keys=None):
|
|
964
|
+
calls.append(1)
|
|
965
|
+
if len(calls) == 1:
|
|
966
|
+
time.sleep(0.3)
|
|
967
|
+
return real(store, keys)
|
|
968
|
+
|
|
969
|
+
monkeypatch.setattr(MongoStore, 'load_items', slow_first)
|
|
970
|
+
r = _cube(client(grid_mirror, request_deadline_seconds=0.2), grid_mirror, 'wrf', BBOX_180)
|
|
971
|
+
assert r.status_code == 503 and r.json()['code'] == 'Deadline'
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
def test_a_read_of_another_shape_than_selected_answers_500(grid_mirror, monkeypatch):
|
|
975
|
+
"""A stop past the axis: cfdb clamps it, so the read is smaller than the selection; the shape
|
|
976
|
+
assertion turns that into a 500, never a short answer."""
|
|
977
|
+
from envlib_api.api import app as app_mod
|
|
978
|
+
|
|
979
|
+
real = app_mod.GridSelection.sel
|
|
980
|
+
|
|
981
|
+
def past_the_end(self, dims):
|
|
982
|
+
return tuple(
|
|
983
|
+
(a, b + 50) if d == self.grid.x_name else (a, b) for d, (a, b) in zip(dims, real(self, dims), strict=True)
|
|
984
|
+
)
|
|
985
|
+
|
|
986
|
+
monkeypatch.setattr(app_mod.GridSelection, 'sel', past_the_end)
|
|
987
|
+
r = _cube(client(grid_mirror), grid_mirror, 'wrf', BBOX_180)
|
|
988
|
+
assert r.status_code == 500 and r.json()['code'] == 'ReadError'
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _local_grid(
|
|
992
|
+
path,
|
|
993
|
+
*,
|
|
994
|
+
lat=(-41.0, -40.95, -40.9),
|
|
995
|
+
lon=(178.0, 178.05),
|
|
996
|
+
names=('latitude', 'longitude'),
|
|
997
|
+
extra=None,
|
|
998
|
+
time_coord=True,
|
|
999
|
+
):
|
|
1000
|
+
"""A small WGS 84 grid built through cfdb as the SST producer builds one; `extra(ds)` adds to it."""
|
|
1001
|
+
dt = dtypes.dtype('float32', precision=2, min_value=-10.0, max_value=40.0)
|
|
1002
|
+
with cfdb.open_dataset(path, flag='n') as ds:
|
|
1003
|
+
if names == ('latitude', 'longitude'):
|
|
1004
|
+
ds.create.coord.lat(data=np.array(lat))
|
|
1005
|
+
ds.create.coord.lon(data=np.array(lon))
|
|
1006
|
+
else:
|
|
1007
|
+
ds.create.coord.generic(names[0], data=np.array(lat), dtype='float64')
|
|
1008
|
+
ds.create.coord.generic(names[1], data=np.array(lon), dtype='float64')
|
|
1009
|
+
dims = (names[0], names[1])
|
|
1010
|
+
if time_coord:
|
|
1011
|
+
ds.create.coord.time(data=np.array(['2026-01-01', '2026-01-02'], dtype='datetime64[D]'), step=1)
|
|
1012
|
+
dims = ('time', *dims)
|
|
1013
|
+
ds.create.crs.from_user_input(4326, x_coord=names[1], y_coord=names[0])
|
|
1014
|
+
dv = ds.create.data_var.generic('temperature', dims, dtype=dt, chunk_shape=tuple(2 for _ in dims))
|
|
1015
|
+
dv.attrs.update({'units': 'degC'})
|
|
1016
|
+
if extra:
|
|
1017
|
+
extra(ds, dt)
|
|
1018
|
+
return cfdb.open_dataset(path)
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def _add_depths(n_axes, deep_var=True):
|
|
1022
|
+
def add(ds, dt):
|
|
1023
|
+
for k in range(n_axes):
|
|
1024
|
+
name = f'depth{k}'
|
|
1025
|
+
ds.create.coord.generic(name, data=np.array([0.1, 0.5]), dtype='float64')
|
|
1026
|
+
ds[name].attrs.update({'axis': 'Z', 'units': 'm', 'positive': 'down'})
|
|
1027
|
+
if deep_var:
|
|
1028
|
+
ds.create.data_var.generic(
|
|
1029
|
+
'moisture', ('time', 'depth0', 'latitude', 'longitude'), dtype=dt, chunk_shape=(2, 1, 2, 2)
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
return add
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def test_cfdb_refuses_a_second_x_axis(tmp_path):
|
|
1036
|
+
"""Grid's x/y-count check is therefore a guard no cfdb-built dataset reaches."""
|
|
1037
|
+
|
|
1038
|
+
def second_x(ds, dt):
|
|
1039
|
+
ds.create.coord.generic('x2', data=np.array([1.0, 2.0]), dtype='float64', axis='x')
|
|
1040
|
+
|
|
1041
|
+
with pytest.raises(ValueError, match='axis x already exists'):
|
|
1042
|
+
_local_grid(tmp_path / 'g.cfdb', extra=second_x).close()
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
@pytest.mark.parametrize(
|
|
1046
|
+
'kw,message',
|
|
1047
|
+
[
|
|
1048
|
+
({'time_coord': False}, 'no time coordinate'),
|
|
1049
|
+
({'extra': _add_depths(1)}, 'both with ([\'moisture\']) and without ([\'temperature\'])'),
|
|
1050
|
+
({'extra': _add_depths(2, deep_var=False)}, 'vertical coordinates'),
|
|
1051
|
+
({'lat': (-41.0,)}, 'has 1 value'),
|
|
1052
|
+
],
|
|
1053
|
+
ids=['no time', 'mixed levels', 'two vertical axes', 'one row'],
|
|
1054
|
+
)
|
|
1055
|
+
def test_each_not_served_convention(tmp_path, kw, message):
|
|
1056
|
+
with _local_grid(tmp_path / 'g.cfdb', **kw) as ds:
|
|
1057
|
+
with pytest.raises(grid.ApiError) as e:
|
|
1058
|
+
grid.Grid(ds, read.snapshot_attrs(ds))
|
|
1059
|
+
assert e.value.status == 404 and e.value.code == 'NotServed' and message in e.value.description, e.value.description
|
|
1060
|
+
|
|
1061
|
+
|
|
1062
|
+
def test_position_csv_suffixes_native_columns_named_lon_or_lat(tmp_path):
|
|
1063
|
+
from envlib_api.api import encode
|
|
1064
|
+
from envlib_api.api.app import GridSelection
|
|
1065
|
+
|
|
1066
|
+
with _local_grid(tmp_path / 'g.cfdb', names=('lat', 'lon')) as ds:
|
|
1067
|
+
g = grid.Grid(ds, read.snapshot_attrs(ds))
|
|
1068
|
+
times = np.asarray(ds['time'].data)
|
|
1069
|
+
sel = GridSelection(g, {'time': (0, 2), 'lat': (1, 2), 'lon': (0, 1)}, times, cell=(1, 0))
|
|
1070
|
+
body = encode.position_csv(
|
|
1071
|
+
g, sel, {'temperature': np.array([[[1.5]], [[2.25]]], dtype='float32')}, {'temperature': 2}
|
|
1072
|
+
)
|
|
1073
|
+
head, first = body.decode().splitlines()[:2]
|
|
1074
|
+
assert head == 'time,lon_native,lat_native,lon,lat,temperature'
|
|
1075
|
+
assert first == '2026-01-01T00:00:00Z,178.0,-40.95,178.0,-40.95,1.50'
|