Debian Codegraph @

tests/test_hdf.py

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