Debian Codegraph @

tests/test__grib_idx.py

raw
1 """
2 # Extract, Load and Build Kerchunk aggregations on the fly from hierarchical metadata and kerchunk indexes.
3
4 MIT License Copyright (c) 2023 Camus Energy
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
7 documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
8 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
9 persons to whom the Software is furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
12 Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
15 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 """
19
20 import copy
21 import re
22 import unittest
23 import logging
24 import gzip
25 import os
26 import numpy as np
27 import pandas as pd
28 import pytest
29 import xarray as xr
30 from kerchunk.grib2 import (
31 scan_grib,
32 grib_tree,
33 correct_hrrr_subhf_step,
34 extract_datatree_chunk_index,
35 strip_datavar_chunks,
36 reinflate_grib_store,
37 AggregationType,
38 build_idx_grib_mapping,
39 parse_grib_idx,
40 map_from_index,
41 read_store,
42 write_store,
43 )
44 from kerchunk.utils import refs_as_store
45 import fsspec
46 import zarr
47 import ujson
48 import tempfile
49 import typing
50 import io
51
52 # https://github.com/pydata/xarray/issues/9984
53 # until datatree/xarray supports zarr3
54 pytest.skip(allow_module_level=True)
55 logger = logging.getLogger(__name__)
56
57 THIS_DIR = os.path.dirname(os.path.abspath(__file__))
58
59
60 class DataExtractorTests(unittest.TestCase):
61 def test_integration(self):
62 # Small test file...
63 uri = f"{THIS_DIR}/grib_idx_fixtures/hrrr.wrfsubhf.sample.grib2"
64
65 scanned_msg_groups = scan_grib(uri)
66 corrected_msg_groups = [
67 correct_hrrr_subhf_step(msg) for msg in scanned_msg_groups
68 ]
69 grib_tree_store = grib_tree(corrected_msg_groups)
70 zg = zarr.open_group("reference://", storage_options={"fo": grib_tree_store})
71 self.assertIsInstance(zg["refc/instant/atmosphere/refc"], zarr.Array)
72 self.assertIsInstance(zg["vbdsf/avg/surface/vbdsf"], zarr.Array)
73 self.assertEqual(
74 zg["vbdsf/avg/surface"].attrs["coordinates"],
75 "surface latitude longitude step time valid_time",
76 )
77 self.assertEqual(
78 zg["refc/instant/atmosphere"].attrs["coordinates"],
79 "atmosphere latitude longitude step time valid_time",
80 )
81 # Assert that the fill value is set correctly
82 self.assertIs(zg["refc"]["instant"]["atmosphere"]["step"].fill_value, np.nan)
83
84 np.testing.assert_array_equal(
85 zg["refc"]["instant"]["atmosphere"]["time"][:], np.array([1665709200])
86 )
87
88 # Read it with data tree and assert the same...
89 dt = xr.open_datatree(
90 "reference://",
91 storage_options={"fo": grib_tree_store},
92 engine="zarr",
93 consolidated=False,
94 )
95 # Assert a few things... but if it loads we are mostly done.
96 np.testing.assert_array_equal(
97 dt["refc"]["instant"]["atmosphere"]["time"].values[:],
98 np.array([np.datetime64("2022-10-14T01:00:00")]),
99 )
100 self.assertDictEqual(
101 dt["refc"].attrs, dict(name="Maximum/Composite radar reflectivity")
102 )
103
104 # Now try the extract and reinflate methods
105 self.assertEqual(len(grib_tree_store["refs"]), 55)
106 deflated_grib_tree = copy.deepcopy(grib_tree_store)
107 kind = extract_datatree_chunk_index(dt, deflated_grib_tree, grib=True)
108 strip_datavar_chunks(deflated_grib_tree)
109 self.assertEqual(len(deflated_grib_tree["refs"]), 45)
110
111 axes = [
112 pd.Index(
113 [
114 pd.timedelta_range(
115 start="0 minutes",
116 end="60 minutes",
117 freq="15min",
118 closed="left",
119 name="001 hour",
120 ),
121 ],
122 name="step",
123 ),
124 pd.date_range(
125 "2022-10-14T00:00:00",
126 "2022-10-14T02:00:00",
127 freq="15min",
128 name="valid_time",
129 ),
130 ]
131
132 zstore = reinflate_grib_store(
133 axes=axes,
134 aggregation_type=AggregationType.HORIZON,
135 chunk_index=kind,
136 zarr_ref_store=deflated_grib_tree,
137 )
138 # Back to the same number of keys!
139 self.assertEqual(len(zstore["refs"]), 55)
140
141 dt = xr.open_datatree(
142 "reference://",
143 storage_options={"fo": zstore},
144 engine="zarr",
145 consolidated=False,
146 )
147 for node in dt.subtree:
148 if node.has_data:
149 with self.subTest(node_path=node.path):
150 np.testing.assert_array_equal(
151 node.time.values, node.valid_time.values - node.step.values
152 )
153
154 npath = node.path.lstrip("/")
155
156 # Assert the values that should be nonnull based on where the chunk is in the time slice
157 expected_null = np.full((1, 9, 1059, 1799), True)
158 expected_null[0, 5, :, :] = False
159 for var in node.data_vars.values():
160 vpath = f"{npath}/{var.name}"
161 with self.subTest(var_name=var.name):
162 key_set = sorted(
163 [
164 key
165 for key in zstore["refs"].keys()
166 if key.startswith(vpath)
167 ]
168 )
169 expected_keys = [
170 f"{vpath}/.zarray",
171 f"{vpath}/.zattrs",
172 f"{vpath}/0.5.0.0",
173 ]
174 self.assertListEqual(key_set, expected_keys)
175
176 np.testing.assert_array_equal(
177 np.isnan(var.values[:, :, :, :]), expected_null
178 )
179
180 def test_build_idx_grib_mapping(self):
181 """
182 This test builds a mapping between idx and grib metadata from one runtime and applies it in another, asserting the
183 mapped index matches the direct index (fixture from the next test).
184 :return:
185 """
186 grib_uri = os.path.join(THIS_DIR, "grib_idx_fixtures")
187
188 # Define pairs of files with the same horizon but from different runtimes to validate idx mapping
189 datasets = {
190 "hrrr.wrfsubhf": [
191 {
192 "20221014": "hrrr.t01z.wrfsubhf00.grib2.test-limit-10",
193 "20231104": "hrrr.t01z.wrfsubhf00.grib2.test-limit-10",
194 },
195 {
196 "20221014": "hrrr.t03z.wrfsubhf09.grib2.test-limit-10",
197 "20231104": "hrrr.t01z.wrfsubhf09.grib2.test-limit-10",
198 },
199 ],
200 "gfs.pgrb2.0p25": [
201 {
202 "20221014": "gfs.t00z.pgrb2.0p25.f000.test-limit-10",
203 "20231104": "gfs.t00z.pgrb2.0p25.f000.test-limit-10",
204 },
205 {
206 "20221014": "gfs.t06z.pgrb2.0p25.f021.test-limit-10",
207 "20231104": "gfs.t00z.pgrb2.0p25.f021.test-limit-10",
208 },
209 ],
210 "hrrr.wrfsfcf": [
211 {
212 "20221014": "hrrr.t01z.wrfsfcf00.grib2.test-limit-10",
213 "20231104": "hrrr.t01z.wrfsfcf00.grib2.test-limit-10",
214 },
215 {
216 "20221014": "hrrr.t09z.wrfsfcf05.grib2.test-limit-10",
217 "20231104": "hrrr.t01z.wrfsfcf05.grib2.test-limit-10",
218 },
219 ],
220 }
221 for sample_prefix, input_pairs in datasets.items():
222 for fnames in input_pairs:
223 # First, build a mapping from the 2022 10 14 data
224 mapping_fname = fnames["20221014"]
225 basename = os.path.join(grib_uri, "20221014", mapping_fname)
226 with self.subTest(sample_prefix=sample_prefix):
227 mapping = build_idx_grib_mapping(
228 basename=basename,
229 mapper=correct_hrrr_subhf_step,
230 )
231
232 mapping = mapping.assign(
233 uri=lambda x: x.uri.str.replace(THIS_DIR, ""),
234 grib_uri=lambda x: x.uri.str.replace(THIS_DIR, ""),
235 idx_uri=lambda x: x.uri.str.replace(THIS_DIR, ""),
236 )
237
238 # # To update the test fixture
239 # write_path = os.path.join(
240 # THIS_DIR,
241 # "grib_idx_fixtures",
242 # sample_prefix,
243 # "20221014",
244 # f"{mapping_fname}.idx_grib_mapping.parquet",
245 # )
246 # mapping.to_parquet(write_path)
247
248 test_path = os.path.join(
249 THIS_DIR,
250 "grib_idx_fixtures",
251 sample_prefix,
252 "20221014",
253 f"{mapping_fname}.idx_grib_mapping.parquet",
254 )
255 # Build the mapping from idx to cfgrib metadata and assert it matches the fixture
256 expected = pd.read_parquet(test_path, engine="fastparquet")
257 pd.testing.assert_frame_equal(mapping, expected)
258
259 # parse the idx files for 20231104 and compare the mapped result to the direct indexed result
260 test_name = fnames["20231104"]
261 basename = os.path.join(grib_uri, "20231104", test_name)
262
263 idxdf = parse_grib_idx(
264 basename=basename,
265 )
266
267 # Get the runtime hour from the filename as we would in prod
268 matcher = re.compile(r"\w*\.t(?P<hour>\d{2})z\..*")
269 matched = matcher.match(test_name)
270 if not matched:
271 raise ValueError(f"test name {test_name} hour not matched")
272 runtime_hour = matched.groupdict()["hour"]
273
274 # hard code the runtime date for now and build the index using the
275 # 2022-10-14 mapping for 2023-11-04 idx file!
276 mapped_index = map_from_index(
277 pd.Timestamp(f"2023-11-04T{runtime_hour}"), mapping, idxdf
278 )
279
280 mapped_index = mapped_index.assign(
281 uri=lambda x: x.uri.str.replace(THIS_DIR, "")
282 )
283
284 # Read the expected fixture - created by test_kerchunk_indexing
285 kindex_test_path = os.path.join(
286 THIS_DIR,
287 "grib_idx_fixtures",
288 sample_prefix,
289 "20231104",
290 f"{test_name}.kindex.parquet",
291 )
292 expected = pd.read_parquet(kindex_test_path, engine="fastparquet")
293
294 expected = expected.set_index(
295 ["varname", "typeOfLevel", "stepType", "step", "level"]
296 ).sort_index()
297 mapped_index = mapped_index.set_index(
298 ["varname", "typeOfLevel", "stepType", "step", "level"]
299 ).sort_index()
300
301 pd.testing.assert_index_equal(expected.index, mapped_index.index)
302
303 pd.testing.assert_frame_equal(
304 expected[["time", "valid_time"]],
305 mapped_index[["time", "valid_time"]],
306 )
307
308 # The grib index can build inline values so only compare the offset, length, and uri where
309 # the inline value is not present
310
311 expected_subset = expected.loc[
312 expected.inline_value.isna(), ["offset", "length", "uri"]
313 ]
314
315 mapped_index_subset = mapped_index.loc[
316 expected.inline_value.isna(), ["offset", "length", "uri"]
317 ]
318 pd.testing.assert_frame_equal(expected_subset, mapped_index_subset)
319
320 def test_kerchunk_indexing(self):
321 """
322 This test builds the grib metadata index for a set of forecasts and asserts it has not changed from what is
323 recorded in the fixture files
324 :return:
325 """
326 TEST_DATE = "20231104"
327 grib_uri = os.path.join(THIS_DIR, "grib_idx_fixtures", TEST_DATE)
328
329 datasets = {
330 "hrrr.wrfsubhf": [
331 "hrrr.t01z.wrfsubhf00.grib2.test-limit-10",
332 "hrrr.t01z.wrfsubhf09.grib2.test-limit-10",
333 ],
334 "gfs.pgrb2.0p25": [
335 "gfs.t00z.pgrb2.0p25.f000.test-limit-10",
336 "gfs.t00z.pgrb2.0p25.f021.test-limit-10",
337 ],
338 "hrrr.wrfsfcf": [
339 "hrrr.t01z.wrfsfcf00.grib2.test-limit-10",
340 "hrrr.t01z.wrfsfcf05.grib2.test-limit-10",
341 ],
342 }
343 for sample_prefix, fnames in datasets.items():
344 for fname in fnames:
345 with self.subTest(sample_prefix=sample_prefix, fname=fname):
346
347 basename = os.path.join(grib_uri, fname)
348 if "hrrr.wrfsubhf" == sample_prefix:
349 grib_tree_store = grib_tree(
350 [
351 correct_hrrr_subhf_step(scan)
352 for scan in scan_grib(basename)
353 ]
354 )
355 else:
356 grib_tree_store = grib_tree(scan_grib(basename))
357
358 dt = xr.open_datatree(
359 "reference://",
360 storage_options={"fo": grib_tree_store},
361 engine="zarr",
362 consolidated=False,
363 )
364
365 kindex = extract_datatree_chunk_index(
366 dt, grib_tree_store, grib=True
367 )
368
369 # Strip the current working directory
370 kindex = kindex.assign(
371 uri=lambda x: x.uri.str.replace(THIS_DIR, "")
372 )
373
374 # # To update the test fixture
375 # write_path = os.path.join(
376 # THIS_DIR,
377 # "grib_idx_fixtures",
378 # sample_prefix,
379 # TEST_DATE,
380 # f"{fname}.kindex.parquet",
381 # )
382 # kindex.to_parquet(write_path)
383
384 test_path = os.path.join(
385 THIS_DIR,
386 "grib_idx_fixtures",
387 sample_prefix,
388 TEST_DATE,
389 f"{fname}.kindex.parquet",
390 )
391 expected = pd.read_parquet(test_path, engine="fastparquet")
392 pd.testing.assert_frame_equal(kindex, expected)
393
394 def test_index_extraction(self):
395 for sample_prefix in ["hrrr.wrfsubhf", "hrrr.wrfsfcf", "gfs.pgrb2.0p25"]:
396 with self.subTest(sample_prefix):
397 self._test_index_extraction(sample_prefix)
398
399 def _read_sample_prefix(self, sample_prefix: str) -> tuple[xr.DataTree, dict]:
400 read_path = os.path.join(
401 THIS_DIR, "grib_idx_fixtures", sample_prefix, "subset.json.gz"
402 )
403 with gzip.open(read_path, "rt") as f:
404 scanned_msgs = ujson.load(typing.cast(io.TextIOWrapper, f))
405
406 if "subhf" in sample_prefix:
407 scanned_msgs = [correct_hrrr_subhf_step(msg) for msg in scanned_msgs]
408 grib_tree_store = grib_tree(scanned_msgs)
409
410 dt = xr.open_datatree(
411 "reference://",
412 storage_options={"fo": grib_tree_store},
413 engine="zarr",
414 consolidated=False,
415 )
416 return dt, grib_tree_store
417
418 def _test_index_extraction(self, sample_prefix: str):
419 dt, grib_tree_store = self._read_sample_prefix(sample_prefix)
420
421 k_index = extract_datatree_chunk_index(dt, grib_tree_store, grib=True)
422
423 # # To update the test fixture
424 # write_path = os.path.join(
425 # THIS_DIR, "grib_idx_fixtures", sample_prefix, "kerchunk_index.parquet"
426 # )
427 # k_index.to_parquet(write_path)
428
429 test_path = os.path.join(
430 THIS_DIR, "grib_idx_fixtures", sample_prefix, "kerchunk_index.parquet"
431 )
432 expected = pd.read_parquet(test_path, engine="fastparquet")
433 pd.testing.assert_frame_equal(k_index, expected)
434
435 def test_strip_datavar_chunks(self):
436 for sample_prefix, pre, post in [
437 ("hrrr.wrfsubhf", 104, 65),
438 ("hrrr.wrfsfcf", 108, 63),
439 ("gfs.pgrb2.0p25", 917, 205),
440 ]:
441 with self.subTest(sample_prefix=sample_prefix, pre=pre, post=post):
442 self._test_strip_datavar_chunks(sample_prefix, pre, post)
443
444 def _test_strip_datavar_chunks(self, sample_prefix: str, pre: int, post: int):
445 dt, grib_tree_store = self._read_sample_prefix(sample_prefix)
446
447 self.assertEqual(len(grib_tree_store["refs"]), pre)
448 strip_datavar_chunks(grib_tree_store)
449 self.assertEqual(len(grib_tree_store["refs"]), post)
450
451 # # To update the test grib_idx_fixtures
452 # write_path = os.path.join(
453 # TESTS_DIR, "grib_idx_fixtures", sample_prefix
454 # )
455 # dynamic_zarr_store.write_store(write_path, grib_tree_store)
456
457 test_path = os.path.join(THIS_DIR, "grib_idx_fixtures", sample_prefix)
458 expected = read_store(test_path)
459 self.assertDictEqual(grib_tree_store, expected)
460
461 def test_read_write_store(self):
462 data = {
463 "version": 1,
464 "refs": {
465 ".zgroup": '{"zarr_format":2}',
466 ".zattrs": '{"GRIB_centre":"kwbc","GRIB_centreDescription":"US National Weather Service - NCEP ","GRIB_edition":2,"GRIB_subCentre":0,"coordinates":"heightAboveGround latitude longitude step time valid_time","institution":"US National Weather Service - NCEP "}',
467 "u/.zarray": '{"chunks":[1059,1799],"compressor":null,"dtype":"<f8","fill_value":null,"filters":[{"dtype":"float64","id":"grib","var":"u"}],"order":"C","shape":[1059,1799],"zarr_format":2}',
468 "u/0.0": ["{{u}}", 3653893, 1088857],
469 "u/.zattrs": '{"GRIB_DxInMetres":3000.0,"GRIB_DyInMetres":3000.0,"GRIB_LaDInDegrees":38.5,"GRIB_Latin1InDegrees":38.5,"GRIB_Latin2InDegrees":38.5,"GRIB_LoVInDegrees":262.5,"GRIB_NV":0,"GRIB_Nx":1799,"GRIB_Ny":1059,"GRIB_cfName":"eastward_wind","GRIB_cfVarName":"u","GRIB_dataType":"fc","GRIB_gridDefinitionDescription":"Lambert Conformal can be secant or tangent, conical or bipolar","GRIB_gridType":"lambert","GRIB_iScansNegatively":0,"GRIB_jPointsAreConsecutive":0,"GRIB_jScansPositively":1,"GRIB_latitudeOfFirstGridPointInDegrees":21.138123,"GRIB_latitudeOfSouthernPoleInDegrees":0.0,"GRIB_longitudeOfFirstGridPointInDegrees":237.280472,"GRIB_longitudeOfSouthernPoleInDegrees":0.0,"GRIB_missingValue":3.4028234663852886e+38,"GRIB_name":"U component of wind","GRIB_numberOfPoints":1905141,"GRIB_paramId":131,"GRIB_shortName":"u","GRIB_stepType":"instant","GRIB_stepUnits":1,"GRIB_typeOfLevel":"heightAboveGround","GRIB_units":"m s**-1","_ARRAY_DIMENSIONS":["y","x"],"long_name":"U component of wind","standard_name":"eastward_wind","units":"m s**-1"}',
470 "heightAboveGround/.zarray": '{"chunks":[],"compressor":null,"dtype":"<f8","fill_value":null,"filters":null,"order":"C","shape":[],"zarr_format":2}',
471 "heightAboveGround/0": "\x00\x00\x00\x00\x00\x00T@",
472 "heightAboveGround/.zattrs": '{"_ARRAY_DIMENSIONS":[],"long_name":"height above the surface","positive":"up","standard_name":"height","units":"m"}',
473 "latitude/.zarray": '{"chunks":[1059,1799],"compressor":null,"dtype":"<f8","fill_value":null,"filters":[{"dtype":"float64","id":"grib","var":"latitude"}],"order":"C","shape":[1059,1799],"zarr_format":2}',
474 "latitude/0.0": ["{{u}}", 3653893, 1088857],
475 "latitude/.zattrs": '{"_ARRAY_DIMENSIONS":["y","x"],"long_name":"latitude","standard_name":"latitude","units":"degrees_north"}',
476 "longitude/.zarray": '{"chunks":[1059,1799],"compressor":null,"dtype":"<f8","fill_value":null,"filters":[{"dtype":"float64","id":"grib","var":"longitude"}],"order":"C","shape":[1059,1799],"zarr_format":2}',
477 "longitude/0.0": ["{{u}}", 3653893, 1088857],
478 "longitude/.zattrs": '{"_ARRAY_DIMENSIONS":["y","x"],"long_name":"longitude","standard_name":"longitude","units":"degrees_east"}',
479 "step/.zarray": '{"chunks":[],"compressor":null,"dtype":"<f8","fill_value":null,"filters":null,"order":"C","shape":[],"zarr_format":2}',
480 "step/0": "\x00\x00\x00\x00\x00\x00\x00\x00",
481 "step/.zattrs": '{"_ARRAY_DIMENSIONS":[],"long_name":"time since forecast_reference_time","standard_name":"forecast_period","units":"hours"}',
482 "time/.zarray": '{"chunks":[],"compressor":null,"dtype":"<i8","fill_value":null,"filters":null,"order":"C","shape":[],"zarr_format":2}',
483 "time/0": "base64:ENAUZQAAAAA=",
484 "time/.zattrs": '{"_ARRAY_DIMENSIONS":[],"calendar":"proleptic_gregorian","long_name":"initial time of forecast","standard_name":"forecast_reference_time","units":"seconds since 1970-01-01T00:00:00"}',
485 "valid_time/.zarray": '{"chunks":[],"compressor":null,"dtype":"<i8","fill_value":null,"filters":null,"order":"C","shape":[],"zarr_format":2}',
486 "valid_time/0": "base64:ENAUZQAAAAA=",
487 "valid_time/.zattrs": '{"_ARRAY_DIMENSIONS":[],"calendar":"proleptic_gregorian","long_name":"time","standard_name":"time","units":"seconds since 1970-01-01T00:00:00"}',
488 },
489 "templates": {"u": "testdata/hrrr.t01z.wrfsubhf00.grib2"},
490 }
491 with tempfile.TemporaryDirectory(suffix=".test") as ntd:
492 write_store(ntd, data)
493
494 result = read_store(ntd)
495 self.assertDictEqual(data, result)
496
497 def _reinflate_grib_store_dataset(self):
498 datasets = [
499 "hrrr.wrfsfcf",
500 "gfs.pgrb2.0p25",
501 "hrrr.wrfsubhf",
502 ]
503 for name in datasets:
504 yield name
505
506 def _reinflate_grib_store_aggregation(self):
507 # Provide some general axes - this will subset the dataset for the selected times
508 aggregations = {
509 AggregationType.HORIZON: [
510 pd.Index(
511 [
512 pd.timedelta_range(
513 start="0 minutes",
514 end="60 minutes",
515 freq="60min",
516 closed="left",
517 name="000 hour",
518 ),
519 pd.timedelta_range(
520 start="60 minutes",
521 end="120 minutes",
522 freq="60min",
523 closed="left",
524 name="001 hour",
525 ),
526 ],
527 name="step",
528 ),
529 pd.date_range(
530 "2023-09-28T00:00",
531 "2023-09-28T03:00",
532 freq="60min",
533 name="valid_time",
534 ),
535 ],
536 AggregationType.VALID_TIME: [
537 pd.timedelta_range("0 min", "300 min", freq="60 min", name="step"),
538 pd.DatetimeIndex(
539 ["2023-09-28T02:00", "2023-09-28T04:00"], name="valid_time"
540 ),
541 ],
542 AggregationType.RUN_TIME: [
543 pd.timedelta_range("0 min", "120 min", freq="15 min", name="step"),
544 pd.DatetimeIndex(["2023-09-28T00:00", "2023-09-28T02:00"], name="time"),
545 ],
546 AggregationType.BEST_AVAILABLE: [
547 pd.date_range(
548 "2023-09-28T00:00",
549 "2023-09-28T10:00",
550 freq="60min",
551 name="valid_time",
552 ),
553 pd.DatetimeIndex(["2023-09-28T02:00"], name="time"),
554 ],
555 }
556
557 for aggregation, axes in aggregations.items():
558 yield aggregation, axes
559
560 def _reinflate_grib_store(
561 self,
562 dataset: str,
563 aggregation: AggregationType,
564 axes: list[pd.Index],
565 ):
566 kind = pd.read_parquet(
567 os.path.join(
568 THIS_DIR, "grib_idx_fixtures", dataset, "test_reinflate.parquet"
569 ),
570 engine="fastparquet",
571 )
572
573 zstore = reinflate_grib_store(
574 axes=axes,
575 aggregation_type=aggregation,
576 chunk_index=kind,
577 zarr_ref_store=read_store(
578 os.path.join(THIS_DIR, "grib_idx_fixtures", dataset)
579 ),
580 )
581 dt = xr.open_datatree(refs_as_store(zstore), engine="zarr")
582 for node in dt.subtree:
583 if not node.has_data:
584 continue
585 with self.subTest(node_path=node.path):
586
587 match aggregation:
588 case AggregationType.HORIZON | AggregationType.BEST_AVAILABLE:
589
590 self.assertEqual(node.time.dims, node.valid_time.dims)
591 self.assertEqual(node.time.dims, node.step.dims)
592 np.testing.assert_array_equal(
593 node.time.values, node.valid_time.values - node.step.values
594 )
595 case AggregationType.VALID_TIME:
596 steps2d = np.tile(
597 node.step.values, (node.valid_time.shape[0], 1)
598 )
599 valid_times2d = np.tile(
600 np.reshape(node.valid_time.values, (-1, 1)),
601 (1, node.step.shape[0]),
602 )
603
604 np.testing.assert_array_equal(
605 node.time.values, valid_times2d - steps2d
606 )
607 case AggregationType.RUN_TIME:
608 steps2d = np.tile(node.step.values, (node.time.shape[0], 1))
609 times2d = np.tile(
610 np.reshape(node.time.values, (-1, 1)),
611 (1, node.step.shape[0]),
612 )
613 np.testing.assert_array_equal(
614 times2d, node.valid_time.values - steps2d
615 )
616 case _:
617 raise RuntimeError("uhoh - unknown aggregation!")
618
619 npath = node.path.lstrip("/")
620 # Can't read nonlocal data here, but we can assert the correct keys are present
621 for var in node.data_vars.values():
622 vpath = f"{npath}/{var.name}"
623 with self.subTest(var_name=var.name):
624 key_set = sorted(
625 [
626 key
627 for key in zstore["refs"].keys()
628 if key.startswith(vpath)
629 ]
630 )
631
632 # # To update test grib_idx_fixtures
633 # write_path = os.path.join(THIS_DIR, "grib_idx_fixtures", dataset, "reinflate", aggregation.value, f"{vpath}_chunks.json")
634 # with fsspec.open(write_path, "w",) as f:
635 # f.write(ujson.dumps(key_set, indent=2))
636
637 test_path = os.path.join(
638 THIS_DIR,
639 "grib_idx_fixtures",
640 dataset,
641 "reinflate",
642 aggregation.value,
643 f"{vpath}_chunks.json",
644 )
645 with fsspec.open(test_path, "r") as f:
646 expected_keys = ujson.loads(f.read())
647
648 self.assertListEqual(key_set, expected_keys)
649
650 def test_reinflate_grib_store(self):
651 for dataset in self._reinflate_grib_store_dataset():
652 for aggregation, axes in self._reinflate_grib_store_aggregation():
653 with self.subTest(dataset=dataset, aggregation=aggregation):
654 self._reinflate_grib_store(dataset, aggregation, axes)
655
656
657 if __name__ == "__main__":
658 logging.basicConfig(level=logging.INFO)
659 unittest.main()