Debian Codegraph @

tests/test_grib.py

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