Debian Codegraph @

tests/test_combine.py

raw
1 import fsspec
2 import fsspec.utils
3 import numpy as np
4 import dask.array as da
5 import pytest
6 import xarray as xr
7 import zarr.storage
8
9 import kerchunk.combine
10 from kerchunk.zarr import single_zarr
11 from kerchunk.combine import MultiZarrToZarr
12 from kerchunk.utils import fs_as_store, refs_as_store, consolidate
13
14
15 fs = fsspec.filesystem("memory")
16 arr = np.random.rand(1, 10, 10)
17
18
19 @pytest.fixture(scope="module", autouse=True)
20 def datasets():
21 # if something fails here, it won't crash the test run
22 static = xr.DataArray(data=np.random.rand(10, 10), dims=["x", "y"], name="static")
23 data = xr.DataArray(
24 data=arr.squeeze(),
25 dims=["x", "y"],
26 name="data",
27 )
28 xr.Dataset({"data": data}, attrs={"attr0": 3}).to_zarr(
29 "memory://simple1.zarr", zarr_format=2
30 )
31
32 data = xr.DataArray(
33 data=arr.squeeze() + 1,
34 dims=["x", "y"],
35 name="data",
36 )
37 xr.Dataset({"data": data}, attrs={"attr0": 4}).to_zarr(
38 "memory://simple2.zarr", zarr_format=2
39 )
40
41 data = xr.DataArray(
42 data=arr.squeeze(),
43 dims=["x", "y"],
44 name="datum",
45 )
46 xr.Dataset({"datum": data}, attrs={"attr0": 3}).to_zarr(
47 "memory://simple_var1.zarr", zarr_format=2
48 )
49
50 data = xr.DataArray(
51 data=arr.squeeze() + 1,
52 dims=["x", "y"],
53 name="datum",
54 )
55 xr.Dataset({"datum": data}, attrs={"attr0": 4}).to_zarr(
56 "memory://simple_var2.zarr", zarr_format=2
57 )
58
59 data = xr.DataArray(
60 data=arr,
61 coords={"time": np.array([1])},
62 dims=["time", "x", "y"],
63 name="data",
64 attrs={"attr0": 3},
65 )
66 xr.Dataset({"data": data, "static": static}, attrs={"attr1": 5}).to_zarr(
67 "memory://single1.zarr", zarr_format=2
68 )
69
70 data = xr.DataArray(
71 data=arr,
72 coords={"time": np.array([2])},
73 dims=["time", "x", "y"],
74 name="data",
75 attrs={"attr0": 4},
76 )
77 xr.Dataset({"data": data, "static": static}, attrs={"attr1": 6}).to_zarr(
78 "memory://single2.zarr", zarr_format=2
79 )
80
81 data = xr.DataArray(
82 data=arr,
83 coords={"time": np.array([3])},
84 dims=["time", "x", "y"],
85 name="data",
86 attrs={"attr0": 4},
87 )
88 xr.Dataset({"data": data, "static": static}, attrs={"attr1": 6}).to_zarr(
89 "memory://single3.zarr", zarr_format=2
90 )
91
92 data = xr.DataArray(
93 data=np.vstack([arr] * 4),
94 coords={"time": np.array([1, 2, 3, 4])},
95 dims=["time", "x", "y"],
96 name="data",
97 attrs={"attr0": 0},
98 )
99 xr.Dataset({"data": data}).to_zarr("memory://quad_nochunk1.zarr", zarr_format=2)
100 xr.Dataset({"data": data}).to_zarr(
101 "memory://group1.zarr", group="group", zarr_format=2
102 )
103
104 data = xr.DataArray(
105 data=np.vstack([arr] * 4),
106 coords={"time": np.array([5, 6, 7, 8])},
107 dims=["time", "x", "y"],
108 name="data",
109 attrs={"attr0": 0},
110 )
111 xr.Dataset({"data": data}).to_zarr("memory://quad_nochunk2.zarr", zarr_format=2)
112 xr.Dataset({"data": data}).to_zarr(
113 "memory://group2.zarr", group="group", zarr_format=2
114 )
115
116 data = xr.DataArray(
117 data=da.from_array(np.vstack([arr] * 4), chunks=(1, 10, 10)),
118 coords={"time": np.array([1, 2, 3, 4])},
119 dims=["time", "x", "y"],
120 name="data",
121 attrs={"attr0": 0},
122 )
123 xr.Dataset({"data": data}).to_zarr("memory://quad_1chunk1.zarr", zarr_format=2)
124
125 data = xr.DataArray(
126 data=da.from_array(np.vstack([arr] * 4), chunks=(1, 10, 10)),
127 coords={"time": np.array([5, 6, 7, 8])},
128 dims=["time", "x", "y"],
129 name="data",
130 attrs={"attr0": 0},
131 )
132 xr.Dataset({"data": data}).to_zarr("memory://quad_1chunk2.zarr", zarr_format=2)
133
134 data = xr.DataArray(
135 data=da.from_array(np.vstack([arr] * 4), chunks=(2, 10, 10)),
136 coords={"time": np.array([1, 2, 3, 4])},
137 dims=["time", "x", "y"],
138 name="data",
139 attrs={"attr0": 0},
140 )
141 xr.Dataset({"data": data}).to_zarr("memory://quad_2chunk1.zarr", zarr_format=2)
142
143 data = xr.DataArray(
144 data=da.from_array(np.vstack([arr] * 4), chunks=(2, 10, 10)),
145 coords={"time": np.array([5, 6, 7, 8])},
146 dims=["time", "x", "y"],
147 name="data",
148 attrs={"attr0": 0},
149 )
150 xr.Dataset({"data": data}).to_zarr("memory://quad_2chunk2.zarr", zarr_format=2)
151
152 # simple time arrays - xarray can't make these!
153 z = zarr.open("memory://time1.zarr", mode="w", zarr_format=2)
154 time1_array = np.array([1], dtype="M8[s]")
155 ar = z.create_array("time", shape=time1_array.shape, dtype=time1_array.dtype)
156 ar[:] = time1_array
157 ar.attrs.update({"_ARRAY_DIMENSIONS": ["time"]})
158 ar = z.create_array("data", dtype=arr.dtype, shape=arr.shape)
159 ar[:] = arr
160 ar.attrs.update({"_ARRAY_DIMENSIONS": ["time", "x", "y"]})
161
162 z = zarr.open("memory://time2.zarr", mode="w", zarr_format=2)
163 time2_array = np.array([2], dtype="M8[s]")
164 ar = z.create_array("time", dtype=time2_array.dtype, shape=time2_array.shape)
165 ar[:] = time2_array
166 ar.attrs.update({"_ARRAY_DIMENSIONS": ["time"]})
167 ar = z.create_array("data", dtype=arr.dtype, shape=arr.shape)
168 ar[:] = arr
169 ar.attrs.update({"_ARRAY_DIMENSIONS": ["time", "x", "y"]})
170
171 # cftime arrays - standard
172 tdata1 = xr.DataArray(
173 data=arr,
174 coords={"time": np.array([1])},
175 dims=["time", "x", "y"],
176 name="data",
177 )
178 xr.Dataset({"data": tdata1}).to_zarr("memory://cfstdtime1.zarr", zarr_format=2)
179 fs.pipe(
180 "cfstdtime1.zarr/time/.zattrs",
181 b'{"_ARRAY_DIMENSIONS": ["time"], "units": "seconds since '
182 b'1970-01-01T00:00:00"}',
183 )
184
185 tdata1 = xr.DataArray(
186 data=arr,
187 coords={"time": np.array([2])},
188 dims=["time", "x", "y"],
189 name="data",
190 )
191 xr.Dataset({"data": tdata1}).to_zarr("memory://cfstdtime2.zarr", zarr_format=2)
192 fs.pipe(
193 "cfstdtime2.zarr/time/.zattrs",
194 b'{"_ARRAY_DIMENSIONS": ["time"], "units": "seconds since '
195 b'1970-01-01T00:00:00"}',
196 )
197
198 tdata1 = xr.DataArray(
199 data=arr,
200 coords={"time": np.array([3])},
201 dims=["time", "x", "y"],
202 name="data",
203 )
204 xr.Dataset({"data": tdata1}).to_zarr("memory://cfstdtime3.zarr", zarr_format=2)
205 fs.pipe(
206 "cfstdtime3.zarr/time/.zattrs",
207 b'{"_ARRAY_DIMENSIONS": ["time"], "units": "seconds since '
208 b'1970-01-01T00:00:00"}',
209 )
210
211 # cftime arrays - non standard
212 tdata1 = xr.DataArray(
213 data=arr,
214 coords={"time": np.array([1])},
215 dims=["time", "x", "y"],
216 name="data",
217 attrs={"units": "months since 1970-01-01", "calendar": "360_day"},
218 )
219 xr.Dataset({"data": tdata1}).to_zarr("memory://cfnontime1.zarr", zarr_format=2)
220 fs.pipe(
221 "cfnontime1.zarr/time/.zattrs",
222 b'{"_ARRAY_DIMENSIONS": ["time"], "units": "months since 1970-01-01", "calendar": "360_day"}',
223 )
224
225 tdata1 = xr.DataArray(
226 data=arr,
227 coords={"time": np.array([2])},
228 dims=["time", "x", "y"],
229 name="data",
230 attrs={"units": "months since 1970-01-01", "calendar": "360_day"},
231 )
232 xr.Dataset({"data": tdata1}).to_zarr("memory://cfnontime2.zarr", zarr_format=2)
233 fs.pipe(
234 "cfnontime2.zarr/time/.zattrs",
235 b'{"_ARRAY_DIMENSIONS": ["time"], "units": "months since 1970-01-01", "calendar": "360_day"}',
236 )
237
238
239 @pytest.fixture(scope="module")
240 def refs():
241 return {
242 path.replace(".zarr", "").lstrip("/"): single_zarr(f"memory://{path}")
243 for path in fs.ls("", detail=False)
244 }
245
246
247 def test_fixture(refs):
248 # effectively checks that single_zarr works
249 assert "single1" in refs
250 fs = fsspec.filesystem("reference", fo=refs["single1"], remote_protocol="memory")
251 store = zarr.storage.FsspecStore(fs)
252 g = xr.open_dataset(store, engine="zarr", backend_kwargs={"consolidated": False})
253 assert g.time.values.tolist() == [1]
254 assert (g.data.values == arr).all()
255 assert g.attrs["attr1"] == 5
256 assert g.data.attrs["attr0"] == 3
257
258
259 @pytest.mark.parametrize(
260 "dataset,chunks",
261 [
262 ["quad_nochunk1", ["data/0.0.0"]],
263 ["quad_1chunk1", ["data/0.0.0", "data/1.0.0", "data/2.0.0", "data/3.0.0"]],
264 ["quad_2chunk1", ["data/0.0.0", "data/1.0.0"]],
265 ],
266 )
267 def test_fixture_chunks(refs, dataset, chunks):
268 # checks that the right number of chunks are made per dataset
269 fs = fsspec.filesystem("reference", fo=refs[dataset], remote_protocol="memory")
270 out = fs.ls("data", detail=False)
271 assert out == ["data/.zarray", "data/.zattrs"] + chunks
272 out = fs.ls("time", detail=False)
273 assert out == ["time/.zarray", "time/.zattrs", "time/0"]
274
275
276 @pytest.mark.parametrize(
277 "selector,expected",
278 [
279 ["data:time", [1, 2]],
280 [[9, 10], [9, 10]],
281 ["INDEX", [0, 1]],
282 # [re.compile("simple(\\d)"), [1, 2]], # we don't give path names here
283 ["attr:attr1", [5, 6]],
284 ["vattr:data:attr0", [3, 4]],
285 ],
286 )
287 def test_get_coos(refs, selector, expected):
288 mzz = MultiZarrToZarr(
289 [refs["single1"], refs["single2"]],
290 remote_protocol="memory",
291 concat_dims=["time"],
292 coo_map={"time": selector},
293 )
294 mzz.first_pass()
295 assert mzz.coos["time"].tolist() == expected
296 mzz.store_coords()
297 store = refs_as_store(mzz.out)
298 g = zarr.open(store, zarr_format=2)
299 assert g["time"][:].tolist() == expected
300 assert dict(g.attrs)
301
302
303 def test_coo_vars(refs):
304 mzz = MultiZarrToZarr(
305 [refs["simple1"], refs["simple_var1"]],
306 remote_protocol="memory",
307 concat_dims=["var"],
308 )
309 mzz.first_pass()
310 assert mzz.coos["var"].tolist() == ["data", "datum"]
311
312 mzz = MultiZarrToZarr(
313 [refs["simple1"], refs["simple2"], refs["simple_var1"], refs["simple_var2"]],
314 remote_protocol="memory",
315 concat_dims=["var", "time"],
316 coo_map={"time": "attr:attr0"},
317 )
318 mzz.first_pass()
319 assert mzz.coos["var"].tolist() == ["data", "datum"]
320 assert mzz.coos["time"].tolist() == [3, 4]
321
322
323 def test_single(refs):
324 mzz = MultiZarrToZarr(
325 [refs["single1"], refs["single2"]],
326 remote_protocol="memory",
327 concat_dims=["time"],
328 coo_dtypes={"time": "int16"},
329 )
330 mzz.first_pass()
331 mzz.store_coords()
332 mzz.second_pass()
333 out = kerchunk.combine.consolidate(mzz.out)
334 z = xr.open_dataset(
335 "reference://",
336 backend_kwargs={
337 "storage_options": {"fo": out, "remote_protocol": "memory"},
338 "consolidated": False,
339 },
340 engine="zarr",
341 decode_cf=False,
342 )
343 # TODO: make some assert_eq style function
344 assert (
345 z.time.dtype == "int16"
346 ) # default is int64, or float64 if decode_cf is True because or array special name
347 assert z.time.values.tolist() == [1, 2]
348 assert z.data.shape == (2, 10, 10)
349 assert (z.data[0].values == arr).all()
350 assert (z.data[1].values == arr).all()
351
352
353 def test_single_append(refs):
354 mzz = MultiZarrToZarr(
355 [refs["single1"], refs["single2"]],
356 remote_protocol="memory",
357 concat_dims=["time"],
358 coo_dtypes={"time": "int16"},
359 )
360 out = mzz.translate()
361 mzz = MultiZarrToZarr.append(
362 [refs["single3"]],
363 out,
364 remote_protocol="memory",
365 concat_dims=["time"],
366 coo_dtypes={"time": "int16"},
367 )
368 out = mzz.translate()
369 z = xr.open_dataset(
370 "reference://",
371 backend_kwargs={
372 "storage_options": {"fo": out, "remote_protocol": "memory"},
373 "consolidated": False,
374 },
375 engine="zarr",
376 decode_cf=False,
377 )
378 assert z.data.shape == (3, 10, 10)
379 assert out["refs"]["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]
380 assert out["refs"]["data/2.0.0"] == ["memory:///single3.zarr/data/0.0.0"]
381 assert z.time.values.tolist() == [1, 2, 3]
382
383
384 @pytest.mark.parametrize("mapper", [{}, {"time": "cf:time"}])
385 @pytest.mark.parametrize("dtype", [{"time": "M8[s]"}, {}])
386 def test_single_append_cf(refs, mapper, dtype):
387 mzz = MultiZarrToZarr(
388 [refs["cfstdtime1"], refs["cfstdtime2"]],
389 remote_protocol="memory",
390 concat_dims=["time"],
391 coo_map=mapper,
392 coo_dtypes=dtype,
393 )
394 out = mzz.translate()
395 mzz = MultiZarrToZarr.append(
396 [refs["cfstdtime3"]],
397 out,
398 remote_protocol="memory",
399 concat_dims=["time"],
400 coo_map=mapper,
401 coo_dtypes=dtype,
402 )
403 out = mzz.translate()
404 z = xr.open_dataset(
405 "reference://",
406 backend_kwargs={
407 "storage_options": {"fo": out, "remote_protocol": "memory"},
408 "consolidated": False,
409 },
410 engine="zarr",
411 )
412 assert z.data.shape == (3, 10, 10)
413 assert out["refs"]["data/0.0.0"] == ["memory:///cfstdtime1.zarr/data/0.0.0"]
414 assert out["refs"]["data/1.0.0"] == ["memory:///cfstdtime2.zarr/data/0.0.0"]
415 assert out["refs"]["data/2.0.0"] == ["memory:///cfstdtime3.zarr/data/0.0.0"]
416 np.testing.assert_equal(
417 z.time.values,
418 np.array(
419 [
420 "1970-01-01T00:00:01.000000000",
421 "1970-01-01T00:00:02.000000000",
422 "1970-01-01T00:00:03.000000000",
423 ],
424 dtype="datetime64[ns]",
425 ),
426 )
427
428
429 def test_single_append_parquet(refs):
430 from fsspec.implementations.reference import LazyReferenceMapper
431
432 m = fsspec.filesystem("memory")
433 out = LazyReferenceMapper.create("memory://refs/out.parquet", fs=m)
434 mzz = MultiZarrToZarr(
435 [refs["single1"], refs["single2"]],
436 remote_protocol="memory",
437 concat_dims=["time"],
438 coo_dtypes={"time": "int16"},
439 out=out,
440 )
441 mzz.translate()
442
443 # reload here due to unknown bug after flush
444 out = LazyReferenceMapper("memory://refs/out.parquet", fs=m)
445 mzz = MultiZarrToZarr.append(
446 [refs["single3"]],
447 out,
448 remote_protocol="memory",
449 concat_dims=["time"],
450 coo_dtypes={"time": "int16"},
451 )
452 out = mzz.translate()
453
454 z = xr.open_dataset(
455 out,
456 backend_kwargs={
457 "storage_options": {"remote_protocol": "memory"},
458 },
459 engine="kerchunk",
460 decode_cf=False,
461 )
462 assert z.data.shape == (3, 10, 10)
463 assert out["data/1.0.0"] == ["memory:///single2.zarr/data/0.0.0"]
464 assert out["data/2.0.0"] == ["memory:///single3.zarr/data/0.0.0"]
465 assert z.time.values.tolist() == [1, 2, 3]
466
467
468 def test_lazy_filler(tmpdir, refs):
469 pd = pytest.importorskip("pandas")
470 pytest.importorskip("fastparquet")
471 from fsspec.implementations.reference import LazyReferenceMapper
472
473 fs = fsspec.filesystem("file")
474 tmpdir = str(tmpdir)
475 out = LazyReferenceMapper.create(record_size=10, root=tmpdir, fs=fs)
476
477 mzz = MultiZarrToZarr(
478 [refs["single1"], refs["single2"]],
479 remote_protocol="memory",
480 concat_dims=["time"],
481 coo_dtypes={"time": "int16"},
482 out=out,
483 )
484 mzz.first_pass()
485 mzz.store_coords()
486
487 out.flush()
488 allfiles = fs.find(tmpdir)
489 assert allfiles == [f"{tmpdir}/{a}" for a in [".zmetadata", "time/refs.0.parq"]]
490 df = pd.read_parquet(f"{tmpdir}/time/refs.0.parq", engine="fastparquet")
491 assert df.iloc[:1].to_dict() == {
492 "raw": {0: b"\x01\x00\x02\x00"},
493 "offset": {0: 0},
494 "size": {0: 0},
495 "path": {0: None},
496 }
497 assert out["time/0"] == b"\x01\x00\x02\x00"
498 mzz.second_pass()
499
500 # actual references don't show
501 assert set(out.zmetadata) == {
502 ".zattrs",
503 ".zgroup",
504 "data/.zarray",
505 "data/.zattrs",
506 "static/.zarray",
507 "static/.zattrs",
508 "time/.zarray",
509 "time/.zattrs",
510 }
511 assert out._items
512 out.flush()
513 assert set(out.zmetadata) == {
514 ".zattrs",
515 ".zgroup",
516 "data/.zarray",
517 "data/.zattrs",
518 "static/.zarray",
519 "static/.zattrs",
520 "time/.zarray",
521 "time/.zattrs",
522 }
523 assert set(out._items) == {".zmetadata"}
524 allfiles = fs.find(tmpdir)
525 assert [
526 f"{tmpdir}/{a}" in allfiles for a in ["static/refs.0.parq", "data/refs.0.parq"]
527 ]
528
529 z = xr.open_dataset(
530 "reference://",
531 backend_kwargs={
532 "storage_options": {"fo": tmpdir, "remote_protocol": "memory"},
533 "consolidated": False,
534 },
535 engine="zarr",
536 decode_cf=False,
537 )
538 assert z.time.values.tolist() == [1, 2]
539 assert z.data.shape == (2, 10, 10)
540 assert (z.data[0].values == arr).all()
541 assert (z.data[1].values == arr).all()
542
543
544 def test_run_twice(refs):
545 mzz = MultiZarrToZarr(
546 [refs["single1"], refs["single2"]],
547 remote_protocol="memory",
548 concat_dims=["time"],
549 coo_dtypes={"time": "int16"},
550 )
551 mzz.translate()
552 out = mzz.translate()
553 z = xr.open_dataset(
554 "reference://",
555 backend_kwargs={
556 "storage_options": {"fo": out, "remote_protocol": "memory"},
557 "consolidated": False,
558 },
559 engine="zarr",
560 decode_cf=False,
561 )
562 assert (
563 z.time.dtype == "int16"
564 ) # default is int64, or float64 if decode_cf is True because or array special name
565 assert z.time.values.tolist() == [1, 2]
566 assert z.data.shape == (2, 10, 10)
567 assert (z.data[0].values == arr).all()
568 assert (z.data[1].values == arr).all()
569
570
571 def test_outfile_postprocess(refs):
572 def post_process(ref):
573 # renamed "data" array to "a_data"; to rename a coordinate, one would nee
574 # to alter attributes of arrays pointing to it
575 return {("a_" + k if k.startswith("data") else k): v for k, v in ref.items()}
576
577 mzz = MultiZarrToZarr(
578 [refs["single1"], refs["single2"]],
579 remote_protocol="memory",
580 concat_dims=["time"],
581 postprocess=post_process,
582 )
583 mzz.translate("memory://myout.json")
584 z = xr.open_dataset(
585 "reference://",
586 backend_kwargs={
587 "storage_options": {
588 "fo": "memory://myout.json",
589 "remote_protocol": "memory",
590 },
591 "consolidated": False,
592 },
593 engine="zarr",
594 )
595 assert z.time.values.tolist() == [1, 2]
596 assert z.a_data.shape == (2, 10, 10)
597 assert (z.a_data[0].values == arr).all()
598 assert (z.a_data[1].values == arr).all()
599
600
601 @pytest.mark.parametrize(
602 "inputs, chunks",
603 [
604 [["quad_nochunk1", "quad_nochunk2"], ((4, 4), (10,), (10,))],
605 [["quad_1chunk1", "quad_1chunk2"], ((1,) * 8, (10,), (10,))],
606 [["quad_2chunk1", "quad_2chunk2"], ((2,) * 4, (10,), (10,))],
607 [["group1", "group2"], ((4, 4), (10,), (10,))],
608 ],
609 )
610 def test_chunked(refs, inputs, chunks):
611 mzz = MultiZarrToZarr(
612 [refs[inputs[0]], refs[inputs[1]]],
613 remote_protocol="memory",
614 concat_dims=["time"],
615 coo_map={"time": "data:group/time"} if "group" in inputs[0] else None,
616 )
617 out = mzz.translate()
618 z = xr.open_dataset(
619 f"reference://{'group' if 'group' in inputs[0] else ''}",
620 backend_kwargs={
621 "storage_options": {"fo": out, "remote_protocol": "memory"},
622 "consolidated": False,
623 },
624 engine="zarr",
625 chunks={},
626 )
627 # TODO: make some assert_eq style function
628 assert z["time"].values.tolist() == [1, 2, 3, 4, 5, 6, 7, 8]
629 assert z["data"].shape == (8, 10, 10)
630 assert z["data"].chunks == chunks
631 for i in range(z.data.shape[0]):
632 assert (z.data[i].values == arr).all()
633
634
635 def test_var(refs):
636 mzz = MultiZarrToZarr(
637 [refs["simple1"], refs["simple_var1"]],
638 remote_protocol="memory",
639 concat_dims=["var"],
640 )
641 out = mzz.translate()
642 z = xr.open_dataset(
643 "reference://",
644 backend_kwargs={
645 "storage_options": {"fo": out, "remote_protocol": "memory"},
646 "consolidated": False,
647 },
648 engine="zarr",
649 chunks={},
650 )
651 assert list(z) == ["data", "datum"]
652 assert list(z.dims) == ["x", "y"]
653 assert z.data.shape == z.datum.shape == (10, 10)
654 assert (z.data.values == arr).all()
655 assert (z.datum.values == arr).all()
656
657
658 def test_var_dimension(refs):
659 mzz = MultiZarrToZarr(
660 [refs["simple1"], refs["simple_var1"]],
661 remote_protocol="memory",
662 coo_map={"varname": "VARNAME", "var": "output"},
663 )
664 out = mzz.translate()
665 z = xr.open_dataset(
666 "reference://",
667 backend_kwargs={
668 "storage_options": {"fo": out, "remote_protocol": "memory"},
669 "consolidated": False,
670 },
671 engine="zarr",
672 chunks={},
673 )
674 assert list(z) == ["output"]
675 assert list(z.dims) == ["varname", "x", "y"]
676 assert list(z.varname) == ["data", "datum"]
677 assert z.output.shape == (2, 10, 10)
678 assert (z.output.values == arr).all()
679
680
681 def test_var_and_dim(refs):
682 mzz = MultiZarrToZarr(
683 [refs["simple1"], refs["simple2"], refs["simple_var1"], refs["simple_var2"]],
684 remote_protocol="memory",
685 concat_dims=["var", "dim"],
686 coo_map={"dim": "attr:attr0"},
687 )
688 out = mzz.translate()
689 z = xr.open_dataset(
690 "reference://",
691 backend_kwargs={
692 "storage_options": {"fo": out, "remote_protocol": "memory"},
693 "consolidated": False,
694 },
695 engine="zarr",
696 chunks={},
697 )
698 assert list(z) == ["data", "datum"]
699 assert list(z.dims) == ["dim", "x", "y"]
700 assert z.data.shape == z.datum.shape == (2, 10, 10)
701 assert z["dim"].values.tolist() == [3, 4]
702 assert (z.data.values == np.vstack([arr, arr + 1])).all()
703
704
705 @pytest.mark.parametrize(
706 "inps,expected",
707 [
708 ["time", ["1970-01-01T00:00:01", "1970-01-01T00:00:02"]],
709 ["cfstdtime", ["1970-01-01T00:00:01", "1970-01-01T00:00:02"]],
710 ["cfnontime", ["1970-02-01T00:00:00", "1970-03-01T00:00:00"]],
711 ],
712 )
713 def test_times(refs, inps, expected):
714 mapper = "data:time" if inps == "time" else "cf:time"
715 mzz = MultiZarrToZarr(
716 [refs[inps + "1"], refs[inps + "2"]],
717 remote_protocol="memory",
718 concat_dims=["time"],
719 coo_map={"time": mapper},
720 )
721 out = mzz.translate()
722 z = xr.open_dataset(
723 "reference://",
724 backend_kwargs={
725 "storage_options": {"fo": out, "remote_protocol": "memory"},
726 "consolidated": False,
727 },
728 engine="zarr",
729 chunks={},
730 )
731 if inps == "cfnontime":
732 assert [_.isoformat() for _ in z.time.values] == expected
733 else:
734 assert (z.time == np.array(expected, dtype="M8[ms]")).all()
735
736
737 def test_cftimes_to_normal(refs):
738 mzz = MultiZarrToZarr(
739 [refs["cfnontime1"], refs["cfnontime2"]],
740 remote_protocol="memory",
741 concat_dims=["time"],
742 coo_map={"time": "cf:time"},
743 coo_dtypes={"time": "M8[s]"},
744 )
745 out = mzz.translate()
746 z = xr.open_dataset(
747 "reference://",
748 backend_kwargs={
749 "storage_options": {"fo": out, "remote_protocol": "memory"},
750 "consolidated": False,
751 },
752 engine="zarr",
753 chunks={},
754 )
755 assert z.time.dtype.kind == "M"
756 assert (
757 z.time.values
758 == np.array(["1970-02-01T00:00:00", "1970-03-01T00:00:00"], dtype="M8[s]")
759 ).all()
760
761
762 def test_inline(refs):
763 mzz = MultiZarrToZarr(
764 [refs["single1"], refs["single2"]],
765 remote_protocol="memory",
766 concat_dims=["time"],
767 coo_dtypes={"time": "int16"},
768 inline_threshold=50000,
769 )
770 out = mzz.translate()
771 z = xr.open_dataset(
772 "reference://",
773 backend_kwargs={
774 "storage_options": {"fo": out, "remote_protocol": "memory"},
775 "consolidated": False,
776 },
777 engine="zarr",
778 decode_cf=False,
779 )
780 ref = fsspec.filesystem("reference", fo=out, remote_protocol="memory")
781 assert (
782 z.time.dtype == "int16"
783 ) # default is int64, or float64 if decode_cf is True because or array special name
784 assert z.time.values.tolist() == [1, 2]
785 assert z.data.shape == (2, 10, 10)
786 assert (z.data[0].values == arr).all()
787 assert (z.data[1].values == arr).all()
788
789 assert isinstance(ref.references["data/0.0.0"], str)
790 assert ref.references["data/0.0.0"].startswith("base64:")
791
792
793 def test_no_inline():
794 """Ensure that inline_threshold=0 disables MultiZarrToZarr checking file size."""
795 ds = xr.Dataset(dict(x=[1, 2, 3]))
796 ds["y"] = 3 + ds["x"]
797 ds.to_zarr("memory://zarr_store", mode="w", zarr_format=2, consolidated=False)
798 store = fsspec.get_mapper("memory://zarr_store")
799 ref = kerchunk.utils.consolidate(store)
800 # This type of reference with no offset or total size is produced by
801 # kerchunk.zarr.single_zarr or equivalently ZarrToZarr.translate.
802 ref["refs"]["y/0"] = ["file:///tmp/some/data-that-shouldnt-be-accessed"]
803
804 mzz_no_inline = MultiZarrToZarr([ref], concat_dims=["x"], inline_threshold=0)
805 # Should be okay because inline_threshold=None so we don't check the file size
806 # in order to see if it should be inlined
807 mzz_no_inline.translate()
808
809 mzz_inline = MultiZarrToZarr([ref], concat_dims=["x"], inline_threshold=1)
810 with pytest.raises(FileNotFoundError):
811 # Should raise because we check the file size to see if it should be inlined,
812 # and the example was engineered so that the file doesn't exist.
813 mzz_inline.translate()
814
815
816 def test_merge_vars():
817 a = dict({"version": 1, "refs": dict({"item1": 1})})
818 b = dict({"version": 1, "refs": dict({"item2": 2})})
819 merge = kerchunk.combine.merge_vars([a, b])
820 assert list(merge["refs"]) == ["item1", "item2"]
821 fs = fsspec.filesystem("memory")
822 fs.pipe("file1.json", b"""{"version": 1, "refs": {"item1": 1}}""")
823 fs.pipe("file2.json", b"""{"version": 1, "refs": {"item2": 2}}""")
824 merge = kerchunk.combine.merge_vars(["memory://file1.json", "memory://file2.json"])
825 assert list(merge["refs"]) == ["item1", "item2"]
826
827
828 def test_bad_coo_warning(refs):
829 def f(*_, **__):
830 return 1
831
832 mzz = MultiZarrToZarr(
833 [refs["single1"], refs["single2"]],
834 remote_protocol="memory",
835 concat_dims=["time"],
836 coo_map={"time": f},
837 )
838 with pytest.warns(match="contains less than expected"):
839 mzz.first_pass()
840
841
842 def test_chunk_error(refs):
843 # Work with the refs in the output of single_zarr
844 refs1 = refs["single1"]["refs"]
845 refs2 = refs1.copy()
846 refs2.pop(".zmetadata")
847 fs = fsspec.filesystem("reference", fo=refs2, remote_protocol="memory") # noqa
848 refs2[
849 "data/.zarray"
850 ] = b"""
851 {
852 "chunks": [2, 3, 3],
853 "zarr_format": 2,
854 "shape": [1, 10, 10]
855 }
856 """
857 mzz = MultiZarrToZarr(
858 [refs1, refs2],
859 remote_protocol="memory",
860 concat_dims=["time"],
861 )
862 with pytest.raises(ValueError) as e:
863 mzz.translate()
864 assert "chunk size mismatch" in str(e.value)