Debian Codegraph @

tests/test_hdf.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import asyncio
2 import fsspec
3 import json
4 import os.path as osp
5 import hdf5plugin
6 import zarr.core
7 import zarr.core.buffer
8 import zarr.core.group
9
10 import kerchunk.hdf
11 import numpy as np
12 import pytest
13 import xarray as xr
14 import zarr
15
16 from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper
17 from kerchunk.hdf import SingleHdf5ToZarr, has_visititems_links
18 from kerchunk.combine import MultiZarrToZarr, drop
19 from kerchunk.utils import fs_as_store, refs_as_fs, refs_as_store
20
21 here = osp.dirname(__file__)
22
23
24 def test_single():
25 """Test creating references for a single HDF file"""
26 url = "s3://noaa-nwm-retro-v2.0-pds/full_physics/2017/201704010000.CHRTOUT_DOMAIN1.comp"
27 so = dict(anon=True, default_fill_cache=False, default_cache_type="none")
28
29 with fsspec.open(url, **so) as f:
30 h5chunks = SingleHdf5ToZarr(f, url, storage_options=so, inline_threshold=1)
31 test_dict = h5chunks.translate()
32
33 with open("test_dict.json", "w") as f:
34 json.dump(test_dict, f)
35
36 store = refs_as_store(test_dict, remote_options=dict(asynchronous=True, anon=True))
37 ds = xr.open_zarr(store, zarr_format=2, consolidated=False)
38
39 with fsspec.open(url, **so) as f:
40 expected = xr.open_dataset(f, engine="h5netcdf")
41 xr.testing.assert_equal(ds.drop_vars("crs"), expected.drop_vars("crs"))
42
43
44 def test_single_direct_open():
45 """Test creating references by passing the url directly to SingleHdf5ToZarr for a single HDF file"""
46 url = "s3://noaa-nwm-retro-v2.0-pds/full_physics/2017/201704010000.CHRTOUT_DOMAIN1.comp"
47 so = dict(anon=True, default_fill_cache=False, default_cache_type="first")
48
49 test_dict = SingleHdf5ToZarr(
50 h5f=url, inline_threshold=300, storage_options=so
51 ).translate()
52
53 store = refs_as_store(test_dict, remote_options=dict(asynchronous=True, anon=True))
54
55 ds_direct = xr.open_dataset(
56 store, engine="zarr", zarr_format=2, backend_kwargs=dict(consolidated=False)
57 )
58
59 with fsspec.open(url, **so) as f:
60 h5chunks = SingleHdf5ToZarr(f, url, storage_options=so)
61 test_dict = h5chunks.translate()
62
63 store = refs_as_store(test_dict, remote_options=dict(asynchronous=True, anon=True))
64
65 ds_from_file_opener = xr.open_dataset(
66 store, engine="zarr", zarr_format=2, backend_kwargs=dict(consolidated=False)
67 )
68
69 xr.testing.assert_equal(
70 ds_from_file_opener.drop_vars("crs"), ds_direct.drop_vars("crs")
71 )
72
73
74 urls = [
75 "s3://" + p
76 for p in [
77 "noaa-nwm-retro-v2.0-pds/full_physics/2017/201704010000.CHRTOUT_DOMAIN1.comp",
78 "noaa-nwm-retro-v2.0-pds/full_physics/2017/201704010100.CHRTOUT_DOMAIN1.comp",
79 "noaa-nwm-retro-v2.0-pds/full_physics/2017/201704010200.CHRTOUT_DOMAIN1.comp",
80 ]
81 ]
82 so = dict(anon=True, default_fill_cache=False, default_cache_type="first")
83
84
85 def test_multizarr(generate_mzz):
86 """Test creating a combined reference file with MultiZarrToZarr"""
87 mzz = generate_mzz
88 test_dict = mzz.translate()
89
90 store = refs_as_store(test_dict, remote_options=dict(asynchronous=True, anon=True))
91 ds = xr.open_dataset(
92 store, engine="zarr", zarr_format=2, backend_kwargs=dict(consolidated=False)
93 )
94
95 with fsspec.open_files(urls, **so) as fs:
96 expts = [xr.open_dataset(f, engine="h5netcdf") for f in fs]
97 expected = xr.concat(expts, dim="time")
98
99 assert set(ds) == set(expected)
100 for name in ds:
101 exp = {
102 k: (
103 (v.tolist() if v.size > 1 else v[0])
104 if isinstance(v, np.ndarray)
105 else v
106 )
107 for k, v in expected[name].attrs.items()
108 }
109 assert dict(ds[name].attrs) == dict(exp)
110 for coo in ds.coords:
111 assert (ds[coo].values == expected[coo].values).all()
112
113
114 @pytest.fixture(scope="module")
115 def generate_mzz():
116 """This function generates a MultiZarrToZarr class for tests"""
117
118 dict_list = []
119
120 for u in urls:
121 with fsspec.open(u, **so) as inf:
122 h5chunks = SingleHdf5ToZarr(inf, u, inline_threshold=100)
123 dict_list.append(h5chunks.translate())
124
125 mzz = MultiZarrToZarr(
126 dict_list,
127 remote_protocol="s3",
128 remote_options={"anon": True},
129 concat_dims=["time"],
130 preprocess=drop("reference_time"),
131 )
132 return mzz
133
134
135 @pytest.fixture()
136 def times_data(tmpdir):
137 lat = xr.DataArray(np.linspace(-90, 90, 10), dims=["lat"], name="lat")
138 lon = xr.DataArray(np.linspace(-90, 90, 10), dims=["lon"], name="lon")
139 time_attrs = {"axis": "T", "long_name": "time", "standard_name": "time"}
140 time1 = xr.DataArray(
141 np.arange(-631108800000000000, -630158390000000000, 86400000000000).view(
142 "datetime64[ns]"
143 ),
144 dims=["time"],
145 name="time",
146 attrs=time_attrs,
147 )
148
149 x1 = xr.DataArray(
150 np.zeros((12, 10, 10)),
151 dims=["time", "lat", "lon"],
152 coords={"time": time1, "lat": lat, "lon": lon},
153 name="prcp",
154 )
155 url = str(tmpdir.join("x1.nc"))
156 x1.to_netcdf(url, engine="h5netcdf")
157 return x1, url
158
159
160 def test_times(times_data):
161 x1, url = times_data
162 # Test taken from https://github.com/fsspec/kerchunk/issues/115#issue-1091163872
163 with fsspec.open(url) as f:
164 h5chunks = SingleHdf5ToZarr(f, url)
165 test_dict = h5chunks.translate()
166
167 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
168 store = refs_as_store(test_dict, fs=localfs)
169 result = xr.open_dataset(
170 store, engine="zarr", zarr_format=2, backend_kwargs=dict(consolidated=False)
171 )
172 expected = x1.to_dataset()
173 xr.testing.assert_equal(result, expected)
174
175
176 def test_times_str(times_data):
177 # as test above, but using str input for SingleHdf5ToZarr file
178 x1, url = times_data
179 # Test taken from https://github.com/fsspec/kerchunk/issues/115#issue-1091163872
180 h5chunks = SingleHdf5ToZarr(url)
181 test_dict = h5chunks.translate()
182
183 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
184 store = refs_as_store(test_dict, fs=localfs)
185 result = xr.open_dataset(
186 store, engine="zarr", zarr_format=2, backend_kwargs=dict(consolidated=False)
187 )
188 expected = x1.to_dataset()
189 xr.testing.assert_equal(result, expected)
190
191
192 # https://stackoverflow.com/a/43935389/3821154
193 txt = "the change of water into water vapour"
194
195
196 def test_string_embed():
197 fn = osp.join(here, "vlen.h5")
198 h = kerchunk.hdf.SingleHdf5ToZarr(fn, fn, vlen_encode="embed")
199 out = h.translate()
200
201 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
202 fs = refs_as_fs(out, fs=localfs)
203 # assert txt in fs.references["vlen_str/0"]
204 store = fs_as_store(fs)
205 z = zarr.open(store, zarr_format=2)
206 assert "String" in str(z["vlen_str"])
207 assert z["vlen_str"][0] == txt
208 assert (z["vlen_str"][1:] == "").all()
209
210
211 def test_string_pathlib():
212 # essentially copied test above
213 import pathlib
214
215 fn = osp.join(here, "vlen.h5")
216 h = kerchunk.hdf.SingleHdf5ToZarr(pathlib.Path(fn), vlen_encode="embed")
217 out = h.translate()
218 fs = fsspec.filesystem("reference", fo=out)
219 assert txt in fs.references["vlen_str/0"]
220 z = zarr.open(fs_as_store(fs))
221 assert "String" in str(z["vlen_str"])
222 assert z["vlen_str"][0] == txt
223 assert (z["vlen_str"][1:] == "").all()
224
225
226 def test_string_null():
227 fn = osp.join(here, "vlen.h5")
228 h = kerchunk.hdf.SingleHdf5ToZarr(fn, fn, vlen_encode="null", inline_threshold=0)
229 out = h.translate()
230 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
231 store = refs_as_store(out, fs=localfs)
232 z = zarr.open(store, zarr_format=2)
233 assert z["vlen_str"].dtype == "O"
234 assert (z["vlen_str"][:] == None).all()
235
236
237 def test_string_leave():
238 fn = osp.join(here, "vlen.h5")
239 with open(fn, "rb") as f:
240 h = kerchunk.hdf.SingleHdf5ToZarr(
241 f, fn, vlen_encode="leave", inline_threshold=0
242 )
243 out = h.translate()
244
245 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
246 store = refs_as_store(out, fs=localfs)
247 z = zarr.open(store, zarr_format=2)
248 assert z["vlen_str"].dtype == "S16"
249 assert z["vlen_str"][0] # some obscured ID
250 assert (z["vlen_str"][1:] == b"").all()
251
252
253 def test_string_decode():
254 fn = osp.join(here, "vlen.h5")
255 with open(fn, "rb") as f:
256 h = kerchunk.hdf.SingleHdf5ToZarr(
257 f, fn, vlen_encode="encode", inline_threshold=0
258 )
259 out = h.translate()
260 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
261 fs = refs_as_fs(out, fs=localfs)
262 assert txt in fs.cat("vlen_str/.zarray").decode() # stored in filter def
263 store = fs_as_store(fs)
264 z = zarr.open(store, zarr_format=2)
265 assert z["vlen_str"][0] == txt
266 assert (z["vlen_str"][1:] == "").all()
267
268
269 def test_compound_string_null():
270 fn = osp.join(here, "vlen2.h5")
271 with open(fn, "rb") as f:
272 h = kerchunk.hdf.SingleHdf5ToZarr(f, fn, vlen_encode="null", inline_threshold=0)
273 out = h.translate()
274 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
275 store = refs_as_store(out, fs=localfs)
276 z = zarr.open(store, zarr_format=2)
277 assert z["vlen_str"][0].tolist() == (10, None)
278 assert (z["vlen_str"][1:]["ints"] == 0).all()
279 assert (z["vlen_str"][1:]["strs"] == None).all()
280
281
282 def test_compound_string_leave():
283 fn = osp.join(here, "vlen2.h5")
284 with open(fn, "rb") as f:
285 h = kerchunk.hdf.SingleHdf5ToZarr(
286 f, fn, vlen_encode="leave", inline_threshold=0
287 )
288 out = h.translate()
289 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
290 store = refs_as_store(out, fs=localfs)
291 z = zarr.open(store, zarr_format=2)
292 assert z["vlen_str"][0]["ints"] == 10
293 assert z["vlen_str"][0]["strs"] # random ID
294 assert (z["vlen_str"][1:]["ints"] == 0).all()
295 assert (z["vlen_str"][1:]["strs"] == b"").all()
296
297
298 def test_compound_string_encode():
299 fn = osp.join(here, "vlen2.h5")
300 with open(fn, "rb") as f:
301 h = kerchunk.hdf.SingleHdf5ToZarr(
302 f, fn, vlen_encode="encode", inline_threshold=0, error="raise"
303 )
304 out = h.translate()
305 print(json.dumps(out, indent=4))
306 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
307 store = refs_as_store(out, fs=localfs)
308 z = zarr.open(store, zarr_format=2)
309 assert z["vlen_str"][0]["ints"] == 10
310 assert z["vlen_str"][0]["strs"] == "water"
311 assert (z["vlen_str"][1:]["ints"] == 0).all()
312 assert (z["vlen_str"][1:]["strs"] == "").all()
313
314
315 # def test_compact():
316 # pytest.importorskip("ipfsspec")
317 # h = kerchunk.hdf.SingleHdf5ToZarr(
318 # "ipfs://QmVZc4TzRP7zydgKzDX7CH2JpYw2LJKkWBm6jhCfigeon6"
319 # )
320 # out = h.translate()
321 #
322 # m = fsspec.get_mapper("reference://", fo=out)
323 # g = zarr.open(m)
324 # assert np.allclose(g.ancillary_data.atlas_sdp_gps_epoch[:], 1.19880002e09)
325 #
326 #
327 def test_compress():
328 import glob
329
330 files = glob.glob(osp.join(here, "hdf5_compression_*.h5"))
331 for f in files:
332 h = kerchunk.hdf.SingleHdf5ToZarr(
333 f, error="raise", unsupported_inline_threshold=800
334 )
335 if "compression_lz4" in f or "compression_bitshuffle" in f:
336 with pytest.raises(RuntimeError):
337 h.translate()
338 continue
339 out = h.translate()
340 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
341 store = refs_as_store(out, fs=localfs)
342 g = zarr.open(store, zarr_format=2)
343 assert np.mean(g["data"]) == 49.5
344
345 for f in files:
346 # Small chunk of unsupported can be inlined now
347 h = kerchunk.hdf.SingleHdf5ToZarr(
348 f, error="raise", unsupported_inline_threshold=801
349 )
350 out = h.translate()
351 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
352 store = refs_as_store(out, fs=localfs)
353 g = zarr.open(store, zarr_format=2)
354 assert np.mean(g["data"]) == 49.5
355
356
357 # def test_embed():
358 # fn = osp.join(here, "NEONDSTowerTemperatureData.hdf5")
359 # h = kerchunk.hdf.SingleHdf5ToZarr(fn, vlen_encode="embed", error="pdb")
360 # out = h.translate()
361 #
362 # store = refs_as_store(out)
363 # z = zarr.open(store, zarr_format=2)
364 # data = z["Domain_10"]["STER"]["min_1"]["boom_1"]["temperature"][:]
365 # assert data[0].tolist() == [
366 # "2014-04-01 00:00:00.0",
367 # "60",
368 # "6.72064364129017",
369 # "6.667845743708792",
370 # "6.774491093631761",
371 # "0.0012746926446369846",
372 # "0.004609216572327277",
373 # "0.01298182345556785",
374 # ]
375 #
376
377
378 def test_inline_threshold():
379 fn = osp.join(here, "air.nc")
380 inline_0 = kerchunk.hdf.SingleHdf5ToZarr(fn, inline_threshold=0).translate()
381 inline_1_million = kerchunk.hdf.SingleHdf5ToZarr(
382 fn, inline_threshold=1e9
383 ).translate()
384 assert inline_0 != inline_1_million
385
386
387 @pytest.mark.skipif(
388 not has_visititems_links(),
389 reason="'h5py.Group.visititems_links' requires h5py 3.11.0 or later",
390 )
391 def test_translate_links():
392 fn = osp.join(here, "air_linked.nc")
393 # choose a threshold that will give both inline and non-inline
394 # datasets for maximum test coverage
395 out = kerchunk.hdf.SingleHdf5ToZarr(fn, inline_threshold=50).translate(
396 preserve_linked_dsets=True
397 )
398 localfs = AsyncFileSystemWrapper(fsspec.filesystem("file"))
399 store = refs_as_store(out, fs=localfs)
400 z = zarr.open(store, zarr_format=2)
401
402 # 1. Test the hard linked datasets were translated correctly
403 # 2. Test the soft linked datasets were translated correctly
404 for link in ("hard", "soft"):
405 for dset in ("lat", "time"):
406 np.testing.assert_allclose(z[dset], z[f"{dset}_{link}"])
407 for key in z[f"{dset}_{link}"].attrs.keys():
408 if key not in kerchunk.hdf._HIDDEN_ATTRS and key != "_ARRAY_DIMENSIONS":
409 assert z[f"{dset}_{link}"].attrs[key] == z[dset].attrs[key]
410
411
412 def test_small_chunks():
413 from fsspec.implementations.reference import ReferenceFileSystem
414
415 suffixes = ["blosc", "shuffle_zstd", "zstd", "lz4", "shuffle_blosc"]
416 for suffix in suffixes:
417 fname = osp.join(here, f"hdf5_mini_{suffix}.h5")
418 with open(fname, "rb") as f:
419 ref = kerchunk.hdf.SingleHdf5ToZarr(f, None).translate()
420 store = ReferenceFileSystem(ref, target=fname, asynchronous=True).get_mapper()
421 data = zarr.group(store)["data"][:]
422 assert (data == np.arange(6, dtype=np.int32).reshape((3, 2))).all()
423
424 if suffix == "lz4":
425 with pytest.raises(RuntimeError):
426 with open(fname, "rb") as f:
427 ref = kerchunk.hdf.SingleHdf5ToZarr(
428 f, None, unsupported_inline_threshold=0, error="raise"
429 ).translate()
430 continue
431 with open(fname, "rb") as f:
432 ref = kerchunk.hdf.SingleHdf5ToZarr(
433 f, None, unsupported_inline_threshold=0
434 ).translate()
435 store2 = ReferenceFileSystem(ref, target=fname).get_mapper()
436 data2 = zarr.group(store2)["data"][:]
437 assert (data2 == np.arange(6, dtype=np.int32).reshape((3, 2))).all()
438
439
440 def test_malicious_chunks():
441 from fsspec.implementations.reference import ReferenceFileSystem
442
443 suffixes = ["", "2"]
444 for suffix in suffixes:
445 fname = osp.join(here, f"hdf5_mali_chunk{suffix}.h5")
446 with open(fname, "rb") as f:
447 ref = kerchunk.hdf.SingleHdf5ToZarr(f, None).translate()
448 store = ReferenceFileSystem(ref, target=fname, asynchronous=True).get_mapper()
449 data = zarr.group(store)["data"][:]
450 assert (data == np.arange(8, dtype=np.int32)).all()