Debian Codegraph @

tests/test_grib.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import os.path
2
3 import eccodes
4 import fsspec
5 import numpy as np
6 import pandas as pd
7 import pytest
8 import xarray as xr
9 import zarr
10 import ujson
11 from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
12 from kerchunk.grib2 import (
13 scan_grib,
14 _split_file,
15 GribToZarr,
16 grib_tree,
17 correct_hrrr_subhf_step,
18 parse_grib_idx,
19 )
20 from kerchunk._grib_idx import (
21 extract_dataset_chunk_index,
22 extract_datatree_chunk_index,
23 )
24 from kerchunk.utils import fs_as_store, refs_as_store
25
26 eccodes_ver = tuple(int(i) for i in eccodes.__version__.split("."))
27 cfgrib = pytest.importorskip("cfgrib")
28 here = os.path.dirname(__file__)
29
30
31 def test_one():
32 # from https://dd.weather.gc.ca/model_gem_regional/10km/grib2/00/000
33 fn = os.path.join(here, "CMC_reg_DEPR_ISBL_10_ps10km_2022072000_P000.grib2")
34 out = scan_grib(fn)
35
36 fs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
37 store = refs_as_store(out[0], fs=fs)
38 ds = xr.open_zarr(store, zarr_format=2, consolidated=False)
39
40 assert ds.attrs["GRIB_centre"] == "cwao"
41 ds2 = xr.open_dataset(fn, engine="cfgrib", backend_kwargs={"indexpath": ""})
42
43 for var in ["latitude", "longitude", "unknown", "isobaricInhPa", "time"]:
44 d1 = ds[var].values
45 d2 = ds2[var].values
46 assert (np.isnan(d1) == np.isnan(d2)).all()
47 assert (d1[~np.isnan(d1)] == d2[~np.isnan(d2)]).all()
48
49
50 def _fetch_first(url):
51 fs = fsspec.filesystem("s3", anon=True)
52 with fs.open(url, "rb") as f:
53 for _, _, data in _split_file(f, skip=1):
54 return data
55
56
57 @pytest.mark.parametrize(
58 "url",
59 [
60 pytest.param(
61 "s3://noaa-hrrr-bdp-pds/hrrr.20140730/conus/hrrr.t23z.wrfsubhf08.grib2",
62 marks=pytest.mark.skipif(eccodes_ver >= (2, 34), reason="eccodes too new"),
63 ),
64 "s3://noaa-gefs-pds/gefs.20221011/00/atmos/pgrb2ap5/gep01.t00z.pgrb2a.0p50.f570",
65 "s3://noaa-gefs-retrospective/GEFSv12/reforecast/2000/2000010100/c00/Days:10-16/acpcp_sfc_2000010100_c00.grib2",
66 ],
67 )
68 def test_archives(tmpdir, url):
69 grib = GribToZarr(url, storage_options={"anon": True}, skip=1)
70 out = grib.translate()[0]
71
72 store = refs_as_store(out, remote_options={"anon": True})
73
74 ours = xr.open_zarr(store, zarr_format=2, consolidated=False)
75
76 data = _fetch_first(url)
77 fn = os.path.join(tmpdir, "grib.grib2")
78 with open(fn, "wb") as f:
79 f.write(data)
80
81 theirs = cfgrib.open_dataset(fn)
82 if "hrrr" in url:
83 # for some reason, cfgrib reads `step` as 7.25 hours
84 # while grib_ls and kerchunk reads `step` as 425 hours.
85 ours = ours.drop_vars("step")
86 theirs = theirs.drop_vars("step")
87
88 xr.testing.assert_allclose(ours, theirs)
89
90
91 def test_subhourly():
92 # two messages extracted from a hrrr output including one with an eccodes
93 # non-compliant endstep type which raises WrongStepUnitError
94 fpath = os.path.join(here, "hrrr.wrfsubhf.sample.grib2")
95 result = scan_grib(fpath)
96 assert len(result) == 2, "Expected two grib messages"
97
98
99 def test_tiny_grib():
100 fpath = os.path.join(here, "tinygrib.grb2")
101 result = scan_grib(fpath)
102 assert len(result) == 1, "Expected one grib message"
103
104
105 def test_grib_tree():
106 """
107 End-to-end test from grib file to zarr hierarchy
108 """
109 fpath = os.path.join(here, "hrrr.wrfsubhf.sample.grib2")
110 scanned_msg_groups = scan_grib(fpath)
111 corrected_msg_groups = [correct_hrrr_subhf_step(msg) for msg in scanned_msg_groups]
112 result = grib_tree(corrected_msg_groups)
113 fs = fsspec.filesystem("reference", fo=result)
114 store = fs_as_store(fs)
115 zg = zarr.open_group(store, mode="r", zarr_format=2)
116 assert isinstance(zg["refc/instant/atmosphere/refc"], zarr.Array)
117 assert isinstance(zg["vbdsf/avg/surface/vbdsf"], zarr.Array)
118 assert set(zg["vbdsf/avg/surface"].attrs["coordinates"].split()) == set(
119 "surface latitude longitude step time valid_time".split()
120 )
121 assert set(zg["refc/instant/atmosphere"].attrs["coordinates"].split()) == set(
122 "atmosphere latitude longitude step time valid_time".split()
123 )
124 # Assert that the fill value is set correctly
125 assert np.isnan(zg["refc/instant/atmosphere/step"].fill_value)
126
127
128 # The following two tests use json fixture data generated from calling scan grib
129 # scan_grib("testdata/hrrr.t01z.wrfsubhf00.grib2")
130 # scan_grib("testdata/hrrr.t01z.wrfsubhf01.grib2")
131 # and filtering the results message groups for keys starting with "dswrf" or "u"
132 # The original files are:
133 # gs://high-resolution-rapid-refresh/hrrr.20210928/conus/hrrr.t01z.wrfsubhf00.grib2"
134 # gs://high-resolution-rapid-refresh/hrrr.20210928/conus/hrrr.t01z.wrfsubhf01.grib2"
135
136
137 def test_correct_hrrr_subhf_group_step():
138 fpath = os.path.join(here, "hrrr.wrfsubhf.subset.json")
139 with open(fpath, "rb") as fobj:
140 scanned_msgs = ujson.load(fobj)
141
142 original_zg = [
143 zarr.open_group(
144 fs_as_store(fsspec.filesystem("reference", fo=val)), mode="r", zarr_format=2
145 )
146 for val in scanned_msgs
147 ]
148
149 corrected_msgs = [correct_hrrr_subhf_step(msg) for msg in scanned_msgs]
150
151 corrected_zg = [
152 zarr.open_group(
153 fs_as_store(fsspec.filesystem("reference", fo=val)), mode="r", zarr_format=2
154 )
155 for val in corrected_msgs
156 ]
157
158 # The groups that were missing a step variable got fixed
159 assert all(["step" in zg.array_keys() for zg in corrected_zg])
160 assert not all(["step" in zg.array_keys() for zg in original_zg])
161
162 # The step values are corrected to floating point hour
163 assert all([zg["step"][()] <= 1.0 for zg in corrected_zg])
164 # The original seems to have values in minutes for some step variables!
165 assert not all(
166 [zg["step"][()] <= 1.0 for zg in original_zg if "step" in zg.array_keys()]
167 )
168
169
170 def test_hrrr_subhf_corrected_grib_tree():
171 fpath = os.path.join(here, "hrrr.wrfsubhf.subset.json")
172 with open(fpath, "rb") as fobj:
173 scanned_msgs = ujson.load(fobj)
174
175 corrected_msgs = [correct_hrrr_subhf_step(msg) for msg in scanned_msgs]
176 merged = grib_tree(corrected_msgs)
177 z_fs = fsspec.filesystem("reference", fo=merged, asynchronous=True)
178 zstore = fs_as_store(z_fs)
179 zg = zarr.open_group(zstore, mode="r", zarr_format=2)
180 # Check the values and shape of the time coordinates
181 assert zg["u/instant/heightAboveGround/step"][:].tolist() == [
182 0.0,
183 0.25,
184 0.5,
185 0.75,
186 1.0,
187 ]
188 assert zg["u/instant/heightAboveGround/step"].shape == (5,)
189 assert zg["u/instant/heightAboveGround/valid_time"][:].tolist() == [
190 [1695862800, 1695863700, 1695864600, 1695865500, 1695866400]
191 ]
192 assert zg["u/instant/heightAboveGround/valid_time"].shape == (1, 5)
193 assert zg["u/instant/heightAboveGround/time"][:].tolist() == [1695862800]
194 assert zg["u/instant/heightAboveGround/time"].shape == (1,)
195 assert zg["dswrf/avg/surface/step"][:].tolist() == [0.0, 0.25, 0.5, 0.75, 1.0]
196 assert zg["dswrf/avg/surface/step"].shape == (5,)
197 assert zg["dswrf/avg/surface/valid_time"][:].tolist() == [
198 [1695862800, 1695863700, 1695864600, 1695865500, 1695866400]
199 ]
200 assert zg["dswrf/avg/surface/valid_time"].shape == (1, 5)
201 assert zg["dswrf/avg/surface/time"][:].tolist() == [1695862800]
202 assert zg["dswrf/avg/surface/time"].shape == (1,)
203
204
205 # The following two test use json fixture data generated from calling scan grib
206 # scan_grib("testdata/hrrr.t01z.wrfsfcf00.grib2")
207 # scan_grib("testdata/hrrr.t01z.wrfsfcf01.grib2")
208 # and filtering the results for keys starting with "dswrf" or "u"
209 # The original files are:
210 # gs://high-resolution-rapid-refresh/hrrr.20210928/conus/hrrr.t01z.wrfsfcf00.grib2"
211 # gs://high-resolution-rapid-refresh/hrrr.20210928/conus/hrrr.t01z.wrfsfcf01.grib2"
212 def test_hrrr_sfcf_grib_tree():
213 fpath = os.path.join(here, "hrrr.wrfsfcf.subset.json")
214 with open(fpath, "rb") as fobj:
215 scanned_msgs = ujson.load(fobj)
216 merged = grib_tree(scanned_msgs)
217 store = fs_as_store(fsspec.filesystem("reference", fo=merged))
218 zg = zarr.open_group(store, mode="r", zarr_format=2)
219 # Check the heightAboveGround level shape of the time coordinates
220 assert zg["u/instant/heightAboveGround/heightAboveGround"][()] == 80.0
221 assert zg["u/instant/heightAboveGround/heightAboveGround"].shape == ()
222 assert zg["u/instant/heightAboveGround/step"][:].tolist() == [0.0, 1.0]
223 assert zg["u/instant/heightAboveGround/step"].shape == (2,)
224 assert zg["u/instant/heightAboveGround/valid_time"][:].tolist() == [
225 [1695862800, 1695866400]
226 ]
227 assert zg["u/instant/heightAboveGround/valid_time"].shape == (1, 2)
228 assert zg["u/instant/heightAboveGround/time"][:].tolist() == [1695862800]
229 assert zg["u/instant/heightAboveGround/time"].shape == (1,)
230
231 # Check the isobaricInhPa level shape and time coordinates
232 assert zg["u/instant/isobaricInhPa/isobaricInhPa"][:].tolist() == [
233 250.0,
234 300.0,
235 500.0,
236 700.0,
237 850.0,
238 925.0,
239 1000.0,
240 ]
241 assert zg["u/instant/isobaricInhPa/isobaricInhPa"].shape == (7,)
242 assert zg["u/instant/isobaricInhPa/step"][:].tolist() == [0.0, 1.0]
243 assert zg["u/instant/isobaricInhPa/step"].shape == (2,)
244
245 # Valid time values get exploded by isobaricInhPa aggregation
246 # Is this a feature or a bug?
247 expected_valid_times = [
248 [
249 [1695862800 for _ in range(7)],
250 [1695866400 for _ in range(7)],
251 ]
252 ]
253 assert zg["u/instant/isobaricInhPa/valid_time"][:].tolist() == expected_valid_times
254 assert zg["u/instant/isobaricInhPa/valid_time"].shape == (1, 2, 7)
255
256 assert zg["u/instant/isobaricInhPa/time"][:].tolist() == [1695862800]
257 assert zg["u/instant/isobaricInhPa/time"].shape == (1,)
258
259
260 # def test_hrrr_sfcf_grib_datatree():
261 # fpath = os.path.join(here, "hrrr.wrfsfcf.subset.json")
262 # with open(fpath, "rb") as fobj:
263 # scanned_msgs = ujson.load(fobj)
264 # merged = grib_tree(scanned_msgs)
265 # dt = datatree.open_datatree(
266 # fsspec.filesystem("reference", fo=merged).get_mapper(""),
267 # engine="zarr",
268 # consolidated=False,
269 # )
270 # # Assert a few things... but if it loads we are mostly done.
271 # np.testing.assert_array_equal(
272 # dt.u.instant.heightAboveGround.step.values[:],
273 # np.array([0, 3600 * 10**9], dtype="timedelta64[ns]"),
274 # )
275 # assert dt.u.attrs == dict(name="U component of wind")
276
277
278 def test_parse_grib_idx_invalid_url():
279 with pytest.raises(ValueError):
280 # a random protocol is used
281 parse_grib_idx(
282 "ds://global-forecast-system/gfs.20230928/00/atmos/gfs.t00z.pgrb2.0p25.f001"
283 )
284
285
286 def test_parse_grib_idx_no_file():
287 with pytest.raises(PermissionError):
288 # the url is spelled wrong
289 parse_grib_idx(
290 "s3://noaahrrr-bdp-pds/hrrr.20220804/conus/hrrr.t01z.wrfsfcf01.grib2",
291 storage_options={"anon": True},
292 )
293
294
295 def test_parse_grib_idx_duplicate_attrs():
296 fn = os.path.join(here, "gfs.t00z.pgrb2.0p25.f006.test-limit-100")
297 with pytest.raises(
298 ValueError, match=f"Attribute mapping for grib file {fn} is not unique"
299 ):
300 parse_grib_idx(fn, validate=True)
301
302
303 @pytest.mark.parametrize(
304 "idx_url, storage_options",
305 [
306 (
307 "gs://global-forecast-system/gfs.20230928/00/atmos/gfs.t00z.pgrb2.0p25.f001",
308 dict(),
309 ),
310 (
311 "s3://noaa-gefs-pds/gefs.20170101/06/gec00.t06z.pgrb2af024",
312 dict(anon=True),
313 ),
314 ],
315 )
316 # the test will fail in case the network goes down or the file is moved
317 def test_parse_grib_idx_content(idx_url, storage_options):
318 import re
319
320 # s3 variable assuming you don't have gcsfs locally
321 variable = "gh/0.0"
322
323 if re.match(r"gs://|gcs://", idx_url):
324 pytest.importorskip("gcsfs", reason="gcsfs is not installed on the system")
325 variable = "prmsl/0.0"
326
327 idx_df = parse_grib_idx(idx_url, storage_options=storage_options)
328 assert isinstance(idx_df, pd.DataFrame)
329
330 # comparing the url, length, offset values of the first message
331 message_no = 0
332 output = scan_grib(idx_url, skip=15, storage_options=storage_options)
333 assert idx_df.iloc[message_no]["grib_uri"] == output[message_no]["templates"]["u"]
334
335 assert idx_df.iloc[message_no]["offset"] == output[message_no]["refs"][variable][1]
336 assert idx_df.iloc[message_no]["length"] == output[message_no]["refs"][variable][2]
337
338
339 # @pytest.fixture
340 # def zarr_tree_and_datatree_instance():
341 # fn = os.path.join(here, "gfs.t00z.pgrb2.0p25.f006.test-limit-100")
342 # tree_store = tree_store = grib_tree(scan_grib(fn))
343 # dt_instance = datatree.open_datatree(
344 # fsspec.filesystem("reference", fo=tree_store).get_mapper(""),
345 # engine="zarr",
346 # consolidated=False,
347 # )
348
349 # return tree_store, dt_instance, fn
350
351
352 @pytest.mark.skip(reason="datatree support should be updated to use xarray.Datatree")
353 def test_extract_dataset_chunk_index(zarr_tree_and_datatree_instance):
354 tree_store, dt_instance, fn = zarr_tree_and_datatree_instance
355
356 # extracting the metadata from a single datatree node with key "t/instant/isobaricInhPa" and comparing it.
357 idx_metadata = extract_dataset_chunk_index(
358 dt_instance["t/instant/isobaricInhPa"], tree_store["refs"]
359 )
360
361 # comparing the first metadata generated from the datatree zarr store
362 assert idx_metadata[0]["uri"] == fn
363 assert idx_metadata[0]["offset"] == 5130730
364 assert idx_metadata[0]["length"] == 844711
365
366 # comparing the first metadata with the datatree instance
367 assert (
368 idx_metadata[0]["valid_time"]
369 == dt_instance["t/instant/isobaricInhPa"]
370 .coords["valid_time"][0][0][0]
371 .to_numpy()
372 )
373 assert (
374 idx_metadata[0]["isobaricInhPa"]
375 == dt_instance["t/instant/isobaricInhPa"].coords["isobaricInhPa"][0].to_numpy()
376 )
377 assert (
378 idx_metadata[0]["step"]
379 == dt_instance["t/instant/isobaricInhPa"].coords["step"][0].to_numpy()
380 )
381
382
383 @pytest.mark.skip(reason="datatree support should be updated to use xarray.Datatree")
384 def test_extract_datatree_chunk_index(zarr_tree_and_datatree_instance):
385 tree_store, dt_instance, fn = zarr_tree_and_datatree_instance
386
387 # dataframe generated from a single grib file
388 idx_df = extract_datatree_chunk_index(dt_instance, tree_store)
389
390 assert isinstance(idx_df, pd.DataFrame)
391
392 # comparing the dataframe's columns
393 assert len(idx_df.columns) == 15
394 assert (
395 idx_df.columns.to_numpy()
396 == [
397 "varname",
398 "typeOfLevel",
399 "stepType",
400 "name",
401 "isobaricInhPa",
402 "step",
403 "time",
404 "valid_time",
405 "uri",
406 "offset",
407 "length",
408 "inline_value",
409 "surface",
410 "heightAboveGround",
411 "meanSea",
412 ]
413 ).all()
414
415 # comparing the actual values from random places in the dataframe
416 assert (idx_df["varname"][[1, 4, 62, 75]] == ["absv", "acpcp", "t", "v"]).all()
417 assert (
418 idx_df["typeOfLevel"][[42, 46, 49, 50]]
419 == ["heightAboveGround", "isobaricInhPa", "surface", "heightAboveGround"]
420 ).all()
421 assert (idx_df["stepType"][[26, 33, 83]] == ["instant", "avg", "accum"]).all()
422 assert (idx_df["isobaricInhPa"][[17, 72, 85]] == [1000.0, 975.0, 975.0]).all()
423 assert pd.isna(idx_df["isobaricInhPa"][56])
424 assert (idx_df["step"] == np.timedelta64(21600000000000, "ns")).all()
425 assert (
426 idx_df["valid_time"] == np.datetime64("2023-09-28T06:00:00.000000000")
427 ).all()
428 assert (idx_df["uri"] == fn).all()
429 assert (
430 idx_df["offset"][[23, 45, 67, 80]] == [2243950, 14113893, 28609546, 8510703]
431 ).all()
432 assert (
433 idx_df["length"][[12, 34, 78, 80]] == [722563, 576527, 947435, 1176904]
434 ).all()
435
436
437 @pytest.mark.skip(reason="datatree support should be updated to use xarray.Datatree")
438 def test_extract_methods_grib_parameter(zarr_tree_and_datatree_instance):
439 tree_store, dt_instance, _ = zarr_tree_and_datatree_instance
440
441 # testing grib parameter with "extract_dataset_chunk_index" function
442 grib_metadata = extract_dataset_chunk_index(
443 dt_instance["t/instant/isobaricInhPa"], tree_store["refs"], True
444 )
445
446 # testing grib parameter with "extract_datatree_chunk_index" function
447 metadata_df = extract_datatree_chunk_index(dt_instance, tree_store, True)
448
449 # checking if level in the generated dataframe
450 assert "level" in metadata_df.columns
451
452 # checking if level in each series data
453 assert all(list(map(lambda data: "level" in data.keys(), grib_metadata)))