-
-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathtest_array.py
1619 lines (1426 loc) · 54.6 KB
/
test_array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dataclasses
import json
import math
import multiprocessing as mp
import pickle
import re
import sys
from itertools import accumulate
from typing import TYPE_CHECKING, Any, Literal
from unittest import mock
import numcodecs
import numpy as np
import numpy.typing as npt
import pytest
from packaging.version import Version
import zarr.api.asynchronous
import zarr.api.synchronous as sync_api
from zarr import Array, AsyncArray, Group
from zarr.abc.store import Store
from zarr.codecs import (
BytesCodec,
GzipCodec,
TransposeCodec,
VLenBytesCodec,
VLenUTF8Codec,
ZstdCodec,
)
from zarr.core._info import ArrayInfo
from zarr.core.array import (
CompressorsLike,
FiltersLike,
_get_default_chunk_encoding_v2,
_get_default_chunk_encoding_v3,
_parse_chunk_encoding_v2,
_parse_chunk_encoding_v3,
chunks_initialized,
create_array,
)
from zarr.core.buffer import NDArrayLike, NDArrayLikeOrScalar, default_buffer_prototype
from zarr.core.buffer.cpu import NDBuffer
from zarr.core.chunk_grids import _auto_partition
from zarr.core.common import JSON, MemoryOrder, ZarrFormat
from zarr.core.group import AsyncGroup
from zarr.core.indexing import BasicIndexer, ceildiv
from zarr.core.metadata.v3 import ArrayV3Metadata, DataType
from zarr.core.sync import sync
from zarr.errors import ContainsArrayError, ContainsGroupError
from zarr.storage import LocalStore, MemoryStore, StorePath
if TYPE_CHECKING:
from zarr.core.array_spec import ArrayConfigLike
from zarr.core.metadata.v2 import ArrayV2Metadata
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
@pytest.mark.parametrize("overwrite", [True, False])
@pytest.mark.parametrize("extant_node", ["array", "group"])
def test_array_creation_existing_node(
store: LocalStore | MemoryStore,
zarr_format: ZarrFormat,
overwrite: bool,
extant_node: Literal["array", "group"],
) -> None:
"""
Check that an existing array or group is handled as expected during array creation.
"""
spath = StorePath(store)
group = Group.from_store(spath, zarr_format=zarr_format)
expected_exception: type[ContainsArrayError | ContainsGroupError]
if extant_node == "array":
expected_exception = ContainsArrayError
_ = group.create_array("extant", shape=(10,), dtype="uint8")
elif extant_node == "group":
expected_exception = ContainsGroupError
_ = group.create_group("extant")
else:
raise AssertionError
new_shape = (2, 2)
new_dtype = "float32"
if overwrite:
if not store.supports_deletes:
pytest.skip("store does not support deletes")
arr_new = zarr.create_array(
spath / "extant",
shape=new_shape,
dtype=new_dtype,
overwrite=overwrite,
zarr_format=zarr_format,
)
assert arr_new.shape == new_shape
assert arr_new.dtype == new_dtype
else:
with pytest.raises(expected_exception):
arr_new = zarr.create_array(
spath / "extant",
shape=new_shape,
dtype=new_dtype,
overwrite=overwrite,
zarr_format=zarr_format,
)
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
async def test_create_creates_parents(
store: LocalStore | MemoryStore, zarr_format: ZarrFormat
) -> None:
# prepare a root node, with some data set
await zarr.api.asynchronous.open_group(
store=store, path="a", zarr_format=zarr_format, attributes={"key": "value"}
)
# create a child node with a couple intermediates
await zarr.api.asynchronous.create(
shape=(2, 2), store=store, path="a/b/c/d", zarr_format=zarr_format
)
parts = ["a", "a/b", "a/b/c"]
if zarr_format == 2:
files = [".zattrs", ".zgroup"]
else:
files = ["zarr.json"]
expected = [f"{part}/{file}" for file in files for part in parts]
if zarr_format == 2:
expected.extend([".zattrs", ".zgroup", "a/b/c/d/.zarray", "a/b/c/d/.zattrs"])
else:
expected.extend(["zarr.json", "a/b/c/d/zarr.json"])
expected = sorted(expected)
result = sorted([x async for x in store.list_prefix("")])
assert result == expected
paths = ["a", "a/b", "a/b/c"]
for path in paths:
g = await zarr.api.asynchronous.open_group(store=store, path=path)
assert isinstance(g, AsyncGroup)
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
def test_array_name_properties_no_group(
store: LocalStore | MemoryStore, zarr_format: ZarrFormat
) -> None:
arr = zarr.create_array(
store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4"
)
assert arr.path == ""
assert arr.name == "/"
assert arr.basename == ""
@pytest.mark.parametrize("store", ["local", "memory", "zip"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
def test_array_name_properties_with_group(
store: LocalStore | MemoryStore, zarr_format: ZarrFormat
) -> None:
root = Group.from_store(store=store, zarr_format=zarr_format)
foo = root.create_array("foo", shape=(100,), chunks=(10,), dtype="i4")
assert foo.path == "foo"
assert foo.name == "/foo"
assert foo.basename == "foo"
bar = root.create_group("bar")
spam = bar.create_array("spam", shape=(100,), chunks=(10,), dtype="i4")
assert spam.path == "bar/spam"
assert spam.name == "/bar/spam"
assert spam.basename == "spam"
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("specifiy_fill_value", [True, False])
@pytest.mark.parametrize("dtype_str", ["bool", "uint8", "complex64"])
def test_array_v3_fill_value_default(
store: MemoryStore, specifiy_fill_value: bool, dtype_str: str
) -> None:
"""
Test that creating an array with the fill_value parameter set to None, or unspecified,
results in the expected fill_value attribute of the array, i.e. 0 cast to the array's dtype.
"""
shape = (10,)
default_fill_value = 0
if specifiy_fill_value:
arr = zarr.create_array(
store=store,
shape=shape,
dtype=dtype_str,
zarr_format=3,
chunks=shape,
fill_value=None,
)
else:
arr = zarr.create_array(
store=store, shape=shape, dtype=dtype_str, zarr_format=3, chunks=shape
)
assert arr.fill_value == np.dtype(dtype_str).type(default_fill_value)
assert arr.fill_value.dtype == arr.dtype
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize(
("dtype_str", "fill_value"),
[("bool", True), ("uint8", 99), ("float32", -99.9), ("complex64", 3 + 4j)],
)
def test_array_v3_fill_value(store: MemoryStore, fill_value: int, dtype_str: str) -> None:
shape = (10,)
arr = zarr.create_array(
store=store,
shape=shape,
dtype=dtype_str,
zarr_format=3,
chunks=shape,
fill_value=fill_value,
)
assert arr.fill_value == np.dtype(dtype_str).type(fill_value)
assert arr.fill_value.dtype == arr.dtype
def test_create_positional_args_deprecated() -> None:
store = MemoryStore()
with pytest.warns(FutureWarning, match="Pass"):
zarr.Array.create(store, (2, 2), dtype="f8")
def test_selection_positional_args_deprecated() -> None:
store = MemoryStore()
arr = zarr.create_array(store, shape=(2, 2), dtype="f8")
with pytest.warns(FutureWarning, match="Pass out"):
arr.get_basic_selection(..., NDBuffer(array=np.empty((2, 2))))
with pytest.warns(FutureWarning, match="Pass fields"):
arr.set_basic_selection(..., 1, None)
with pytest.warns(FutureWarning, match="Pass out"):
arr.get_orthogonal_selection(..., NDBuffer(array=np.empty((2, 2))))
with pytest.warns(FutureWarning, match="Pass"):
arr.set_orthogonal_selection(..., 1, None)
with pytest.warns(FutureWarning, match="Pass"):
arr.get_mask_selection(np.zeros((2, 2), dtype=bool), NDBuffer(array=np.empty((0,))))
with pytest.warns(FutureWarning, match="Pass"):
arr.set_mask_selection(np.zeros((2, 2), dtype=bool), 1, None)
with pytest.warns(FutureWarning, match="Pass"):
arr.get_coordinate_selection(([0, 1], [0, 1]), NDBuffer(array=np.empty((2,))))
with pytest.warns(FutureWarning, match="Pass"):
arr.set_coordinate_selection(([0, 1], [0, 1]), 1, None)
with pytest.warns(FutureWarning, match="Pass"):
arr.get_block_selection((0, slice(None)), NDBuffer(array=np.empty((2, 2))))
with pytest.warns(FutureWarning, match="Pass"):
arr.set_block_selection((0, slice(None)), 1, None)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
async def test_array_v3_nan_fill_value(store: MemoryStore) -> None:
shape = (10,)
arr = zarr.create_array(
store=store,
shape=shape,
dtype=np.float64,
zarr_format=3,
chunks=shape,
fill_value=np.nan,
)
arr[:] = np.nan
assert np.isnan(arr.fill_value)
assert arr.fill_value.dtype == arr.dtype
# all fill value chunk is an empty chunk, and should not be written
assert len([a async for a in store.list_prefix("/")]) == 0
@pytest.mark.parametrize("store", ["local"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
async def test_serializable_async_array(
store: LocalStore | MemoryStore, zarr_format: ZarrFormat
) -> None:
expected = await zarr.api.asynchronous.create_array(
store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4"
)
# await expected.setitems(list(range(100)))
p = pickle.dumps(expected)
actual = pickle.loads(p)
assert actual == expected
# np.testing.assert_array_equal(await actual.getitem(slice(None)), await expected.getitem(slice(None)))
# TODO: uncomment the parts of this test that will be impacted by the config/prototype changes in flight
@pytest.mark.parametrize("store", ["local"], indirect=["store"])
@pytest.mark.parametrize("zarr_format", [2, 3])
def test_serializable_sync_array(store: LocalStore, zarr_format: ZarrFormat) -> None:
expected = zarr.create_array(
store=store, shape=(100,), chunks=(10,), zarr_format=zarr_format, dtype="i4"
)
expected[:] = list(range(100))
p = pickle.dumps(expected)
actual = pickle.loads(p)
assert actual == expected
np.testing.assert_array_equal(actual[:], expected[:])
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_storage_transformers(store: MemoryStore) -> None:
"""
Test that providing an actual storage transformer produces a warning and otherwise passes through
"""
metadata_dict: dict[str, JSON] = {
"zarr_format": 3,
"node_type": "array",
"shape": (10,),
"chunk_grid": {"name": "regular", "configuration": {"chunk_shape": (1,)}},
"data_type": "uint8",
"chunk_key_encoding": {"name": "v2", "configuration": {"separator": "/"}},
"codecs": (BytesCodec().to_dict(),),
"fill_value": 0,
"storage_transformers": ({"test": "should_raise"}),
}
match = "Arrays with storage transformers are not supported in zarr-python at this time."
with pytest.raises(ValueError, match=match):
Array.from_dict(StorePath(store), data=metadata_dict)
@pytest.mark.parametrize("test_cls", [Array, AsyncArray[Any]])
@pytest.mark.parametrize("nchunks", [2, 5, 10])
def test_nchunks(test_cls: type[Array] | type[AsyncArray[Any]], nchunks: int) -> None:
"""
Test that nchunks returns the number of chunks defined for the array.
"""
store = MemoryStore()
shape = 100
arr = zarr.create_array(store, shape=(shape,), chunks=(ceildiv(shape, nchunks),), dtype="i4")
expected = nchunks
if test_cls == Array:
observed = arr.nchunks
else:
observed = arr._async_array.nchunks
assert observed == expected
@pytest.mark.parametrize("test_cls", [Array, AsyncArray[Any]])
async def test_nchunks_initialized(test_cls: type[Array] | type[AsyncArray[Any]]) -> None:
"""
Test that nchunks_initialized accurately returns the number of stored chunks.
"""
store = MemoryStore()
arr = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="i4")
# write chunks one at a time
for idx, region in enumerate(arr._iter_chunk_regions()):
arr[region] = 1
expected = idx + 1
if test_cls == Array:
observed = arr.nchunks_initialized
else:
observed = await arr._async_array.nchunks_initialized()
assert observed == expected
# delete chunks
for idx, key in enumerate(arr._iter_chunk_keys()):
sync(arr.store_path.store.delete(key))
if test_cls == Array:
observed = arr.nchunks_initialized
else:
observed = await arr._async_array.nchunks_initialized()
expected = arr.nchunks - idx - 1
assert observed == expected
async def test_chunks_initialized() -> None:
"""
Test that chunks_initialized accurately returns the keys of stored chunks.
"""
store = MemoryStore()
arr = zarr.create_array(store, shape=(100,), chunks=(10,), dtype="i4")
chunks_accumulated = tuple(
accumulate(tuple(tuple(v.split(" ")) for v in arr._iter_chunk_keys()))
)
for keys, region in zip(chunks_accumulated, arr._iter_chunk_regions(), strict=False):
arr[region] = 1
observed = sorted(await chunks_initialized(arr._async_array))
expected = sorted(keys)
assert observed == expected
def test_nbytes_stored() -> None:
arr = zarr.create(shape=(100,), chunks=(10,), dtype="i4", codecs=[BytesCodec()])
result = arr.nbytes_stored()
assert result == 502 # the size of the metadata document. This is a fragile test.
arr[:50] = 1
result = arr.nbytes_stored()
assert result == 702 # the size with 5 chunks filled.
arr[50:] = 2
result = arr.nbytes_stored()
assert result == 902 # the size with all chunks filled.
async def test_nbytes_stored_async() -> None:
arr = await zarr.api.asynchronous.create(
shape=(100,), chunks=(10,), dtype="i4", codecs=[BytesCodec()]
)
result = await arr.nbytes_stored()
assert result == 502 # the size of the metadata document. This is a fragile test.
await arr.setitem(slice(50), 1)
result = await arr.nbytes_stored()
assert result == 702 # the size with 5 chunks filled.
await arr.setitem(slice(50, 100), 2)
result = await arr.nbytes_stored()
assert result == 902 # the size with all chunks filled.
def test_default_fill_values() -> None:
a = zarr.Array.create(MemoryStore(), shape=5, chunk_shape=5, dtype="<U4")
assert a.fill_value == ""
b = zarr.Array.create(MemoryStore(), shape=5, chunk_shape=5, dtype="<S4")
assert b.fill_value == b""
c = zarr.Array.create(MemoryStore(), shape=5, chunk_shape=5, dtype="i")
assert c.fill_value == 0
d = zarr.Array.create(MemoryStore(), shape=5, chunk_shape=5, dtype="f")
assert d.fill_value == 0.0
def test_vlen_errors() -> None:
with pytest.raises(ValueError, match="At least one ArrayBytesCodec is required."):
Array.create(MemoryStore(), shape=5, chunks=5, dtype="<U4", codecs=[])
with pytest.raises(
ValueError,
match="For string dtype, ArrayBytesCodec must be `VLenUTF8Codec`, got `BytesCodec`.",
):
Array.create(MemoryStore(), shape=5, chunks=5, dtype="<U4", codecs=[BytesCodec()])
with pytest.raises(ValueError, match="Only one ArrayBytesCodec is allowed."):
Array.create(
MemoryStore(),
shape=5,
chunks=5,
dtype="<U4",
codecs=[BytesCodec(), VLenBytesCodec()],
)
with pytest.raises(
ValueError,
match="For string dtype, ArrayBytesCodec must be `VLenUTF8Codec`, got `BytesCodec`.",
):
zarr.create_array(
MemoryStore(), shape=(5,), chunks=(5,), dtype="<U4", serializer=BytesCodec()
)
@pytest.mark.parametrize("zarr_format", [2, 3])
def test_update_attrs(zarr_format: ZarrFormat) -> None:
# regression test for https://github.com/zarr-developers/zarr-python/issues/2328
store = MemoryStore()
arr = zarr.create_array(
store=store, shape=(5,), chunks=(5,), dtype="f8", zarr_format=zarr_format
)
arr.attrs["foo"] = "bar"
assert arr.attrs["foo"] == "bar"
arr2 = zarr.open_array(store=store, zarr_format=zarr_format)
assert arr2.attrs["foo"] == "bar"
@pytest.mark.parametrize(("chunks", "shards"), [((2, 2), None), ((2, 2), (4, 4))])
class TestInfo:
def test_info_v2(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None:
arr = zarr.create_array(store={}, shape=(8, 8), dtype="f8", chunks=chunks, zarr_format=2)
result = arr.info
expected = ArrayInfo(
_zarr_format=2,
_data_type=np.dtype("float64"),
_shape=(8, 8),
_chunk_shape=chunks,
_shard_shape=None,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_count_bytes=512,
_compressors=(numcodecs.Zstd(),),
)
assert result == expected
def test_info_v3(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None:
arr = zarr.create_array(store={}, shape=(8, 8), dtype="f8", chunks=chunks, shards=shards)
result = arr.info
expected = ArrayInfo(
_zarr_format=3,
_data_type=DataType.parse("float64"),
_shape=(8, 8),
_chunk_shape=chunks,
_shard_shape=shards,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_compressors=(ZstdCodec(),),
_serializer=BytesCodec(),
_count_bytes=512,
)
assert result == expected
def test_info_complete(self, chunks: tuple[int, int], shards: tuple[int, int] | None) -> None:
arr = zarr.create_array(
store={},
shape=(8, 8),
dtype="f8",
chunks=chunks,
shards=shards,
compressors=(),
)
result = arr.info_complete()
expected = ArrayInfo(
_zarr_format=3,
_data_type=DataType.parse("float64"),
_shape=(8, 8),
_chunk_shape=chunks,
_shard_shape=shards,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_serializer=BytesCodec(),
_count_bytes=512,
_count_chunks_initialized=0,
_count_bytes_stored=521 if shards is None else 982, # the metadata?
)
assert result == expected
arr[:4, :4] = 10
result = arr.info_complete()
if shards is None:
expected = dataclasses.replace(
expected, _count_chunks_initialized=4, _count_bytes_stored=649
)
else:
expected = dataclasses.replace(
expected, _count_chunks_initialized=1, _count_bytes_stored=1178
)
assert result == expected
async def test_info_v2_async(
self, chunks: tuple[int, int], shards: tuple[int, int] | None
) -> None:
arr = await zarr.api.asynchronous.create_array(
store={}, shape=(8, 8), dtype="f8", chunks=chunks, zarr_format=2
)
result = arr.info
expected = ArrayInfo(
_zarr_format=2,
_data_type=np.dtype("float64"),
_shape=(8, 8),
_chunk_shape=(2, 2),
_shard_shape=None,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_count_bytes=512,
_compressors=(numcodecs.Zstd(),),
)
assert result == expected
async def test_info_v3_async(
self, chunks: tuple[int, int], shards: tuple[int, int] | None
) -> None:
arr = await zarr.api.asynchronous.create_array(
store={},
shape=(8, 8),
dtype="f8",
chunks=chunks,
shards=shards,
)
result = arr.info
expected = ArrayInfo(
_zarr_format=3,
_data_type=DataType.parse("float64"),
_shape=(8, 8),
_chunk_shape=chunks,
_shard_shape=shards,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_compressors=(ZstdCodec(),),
_serializer=BytesCodec(),
_count_bytes=512,
)
assert result == expected
async def test_info_complete_async(
self, chunks: tuple[int, int], shards: tuple[int, int] | None
) -> None:
arr = await zarr.api.asynchronous.create_array(
store={},
dtype="f8",
shape=(8, 8),
chunks=chunks,
shards=shards,
compressors=None,
)
result = await arr.info_complete()
expected = ArrayInfo(
_zarr_format=3,
_data_type=DataType.parse("float64"),
_shape=(8, 8),
_chunk_shape=chunks,
_shard_shape=shards,
_order="C",
_read_only=False,
_store_type="MemoryStore",
_serializer=BytesCodec(),
_count_bytes=512,
_count_chunks_initialized=0,
_count_bytes_stored=521 if shards is None else 982, # the metadata?
)
assert result == expected
await arr.setitem((slice(4), slice(4)), 10)
result = await arr.info_complete()
if shards is None:
expected = dataclasses.replace(
expected, _count_chunks_initialized=4, _count_bytes_stored=553
)
else:
expected = dataclasses.replace(
expected, _count_chunks_initialized=1, _count_bytes_stored=1178
)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_resize_1d(store: MemoryStore, zarr_format: ZarrFormat) -> None:
z = zarr.create(
shape=105, chunks=10, dtype="i4", fill_value=0, store=store, zarr_format=zarr_format
)
a = np.arange(105, dtype="i4")
z[:] = a
result = z[:]
assert isinstance(result, NDArrayLike)
assert (105,) == z.shape
assert (105,) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(a, result)
z.resize(205)
result = z[:]
assert isinstance(result, NDArrayLike)
assert (205,) == z.shape
assert (205,) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(a, z[:105])
np.testing.assert_array_equal(np.zeros(100, dtype="i4"), z[105:])
z.resize(55)
result = z[:]
assert isinstance(result, NDArrayLike)
assert (55,) == z.shape
assert (55,) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(a[:55], result)
# via shape setter
new_shape = (105,)
z.shape = new_shape
result = z[:]
assert isinstance(result, NDArrayLike)
assert new_shape == z.shape
assert new_shape == result.shape
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_resize_2d(store: MemoryStore, zarr_format: ZarrFormat) -> None:
z = zarr.create(
shape=(105, 105),
chunks=(10, 10),
dtype="i4",
fill_value=0,
store=store,
zarr_format=zarr_format,
)
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z[:] = a
result = z[:]
assert isinstance(result, NDArrayLike)
assert (105, 105) == z.shape
assert (105, 105) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a, result)
z.resize((205, 205))
result = z[:]
assert isinstance(result, NDArrayLike)
assert (205, 205) == z.shape
assert (205, 205) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a, z[:105, :105])
np.testing.assert_array_equal(np.zeros((100, 205), dtype="i4"), z[105:, :])
np.testing.assert_array_equal(np.zeros((205, 100), dtype="i4"), z[:, 105:])
z.resize((55, 55))
result = z[:]
assert isinstance(result, NDArrayLike)
assert (55, 55) == z.shape
assert (55, 55) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a[:55, :55], result)
z.resize((55, 1))
result = z[:]
assert isinstance(result, NDArrayLike)
assert (55, 1) == z.shape
assert (55, 1) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a[:55, :1], result)
z.resize((1, 55))
result = z[:]
assert isinstance(result, NDArrayLike)
assert (1, 55) == z.shape
assert (1, 55) == result.shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == result.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a[:1, :10], z[:, :10])
np.testing.assert_array_equal(np.zeros((1, 55 - 10), dtype="i4"), z[:, 10:55])
# via shape setter
new_shape = (105, 105)
z.shape = new_shape
result = z[:]
assert isinstance(result, NDArrayLike)
assert new_shape == z.shape
assert new_shape == result.shape
@pytest.mark.parametrize("store", ["local"], indirect=True)
@pytest.mark.parametrize("open", ["open", "open_array"])
def test_append_config_passed(store: LocalStore, open: str, zarr_format: ZarrFormat) -> None:
z = zarr.create_array(
store=store,
name="test",
shape=(2,),
dtype=int,
fill_value=0,
chunks=(1,),
config={"write_empty_chunks": True},
overwrite=True,
zarr_format=zarr_format,
)
z[:] = 0
def assert_correct_files_written(expected: list[str]) -> None:
"""Helper to compare written files"""
if zarr_format == 2:
actual = [f.name for f in store.root.rglob("test/*")]
else:
actual = [f.name for f in store.root.rglob("test/c/*")]
actual = [f for f in actual if f not in [".zattrs", ".zarray", "zarr.json"]]
assert sorted(expected) == sorted(actual)
assert_correct_files_written(["0", "1"])
# parametrized over open and open_array
z = getattr(zarr, open)(store, path="test", config={"write_empty_chunks": True}, fill_value=0)
z.resize((4,))
assert_correct_files_written(["0", "1"])
z[2:] = 0
assert_correct_files_written(["0", "1", "2", "3"])
z[:] = 0
assert_correct_files_written(["0", "1", "2", "3"])
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_append_1d(store: MemoryStore, zarr_format: ZarrFormat) -> None:
a = np.arange(105)
z = zarr.create(shape=a.shape, chunks=10, dtype=a.dtype, store=store, zarr_format=zarr_format)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(a, z[:])
b = np.arange(105, 205)
e = np.append(a, b)
assert z.shape == (105,)
z.append(b)
assert e.shape == z.shape
assert e.dtype == z.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(e, z[:])
# check append handles array-like
c = [1, 2, 3]
f = np.append(e, c)
z.append(c)
assert f.shape == z.shape
assert f.dtype == z.dtype
assert (10,) == z.chunks
np.testing.assert_array_equal(f, z[:])
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_append_2d(store: MemoryStore, zarr_format: ZarrFormat) -> None:
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z = zarr.create(
shape=a.shape, chunks=(10, 10), dtype=a.dtype, store=store, zarr_format=zarr_format
)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10, 10) == z.chunks
actual = z[:]
np.testing.assert_array_equal(a, actual)
b = np.arange(105 * 105, 2 * 105 * 105, dtype="i4").reshape((105, 105))
e = np.append(a, b, axis=0)
z.append(b)
assert e.shape == z.shape
assert e.dtype == z.dtype
assert (10, 10) == z.chunks
actual = z[:]
np.testing.assert_array_equal(e, actual)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_append_2d_axis(store: MemoryStore, zarr_format: ZarrFormat) -> None:
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z = zarr.create(
shape=a.shape, chunks=(10, 10), dtype=a.dtype, store=store, zarr_format=zarr_format
)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(a, z[:])
b = np.arange(105 * 105, 2 * 105 * 105, dtype="i4").reshape((105, 105))
e = np.append(a, b, axis=1)
z.append(b, axis=1)
assert e.shape == z.shape
assert e.dtype == z.dtype
assert (10, 10) == z.chunks
np.testing.assert_array_equal(e, z[:])
@pytest.mark.parametrize("store", ["memory"], indirect=True)
def test_append_bad_shape(store: MemoryStore, zarr_format: ZarrFormat) -> None:
a = np.arange(100)
z = zarr.create(shape=a.shape, chunks=10, dtype=a.dtype, store=store, zarr_format=zarr_format)
z[:] = a
b = a.reshape(10, 10)
with pytest.raises(ValueError):
z.append(b)
@pytest.mark.parametrize("store", ["memory"], indirect=True)
@pytest.mark.parametrize("write_empty_chunks", [True, False])
@pytest.mark.parametrize("fill_value", [0, 5])
def test_write_empty_chunks_behavior(
zarr_format: ZarrFormat, store: MemoryStore, write_empty_chunks: bool, fill_value: int
) -> None:
"""
Check that the write_empty_chunks value of the config is applied correctly. We expect that
when write_empty_chunks is True, writing chunks equal to the fill value will result in
those chunks appearing in the store.
When write_empty_chunks is False, writing chunks that are equal to the fill value will result in
those chunks not being present in the store. In particular, they should be deleted if they were
already present.
"""
arr = zarr.create_array(
store=store,
shape=(2,),
zarr_format=zarr_format,
dtype="i4",
fill_value=fill_value,
chunks=(1,),
config={"write_empty_chunks": write_empty_chunks},
)
assert arr._async_array._config.write_empty_chunks == write_empty_chunks
# initialize the store with some non-fill value chunks
arr[:] = fill_value + 1
assert arr.nchunks_initialized == arr.nchunks
arr[:] = fill_value
if not write_empty_chunks:
assert arr.nchunks_initialized == 0
else:
assert arr.nchunks_initialized == arr.nchunks
@pytest.mark.parametrize(
("fill_value", "expected"),
[
(np.nan * 1j, ["NaN", "NaN"]),
(np.nan, ["NaN", 0.0]),
(np.inf, ["Infinity", 0.0]),
(np.inf * 1j, ["NaN", "Infinity"]),
(-np.inf, ["-Infinity", 0.0]),
(math.inf, ["Infinity", 0.0]),
],
)
async def test_special_complex_fill_values_roundtrip(fill_value: Any, expected: list[Any]) -> None:
store = MemoryStore()
zarr.create_array(store=store, shape=(1,), dtype=np.complex64, fill_value=fill_value)
content = await store.get("zarr.json", prototype=default_buffer_prototype())
assert content is not None
actual = json.loads(content.to_bytes())
assert actual["fill_value"] == expected
@pytest.mark.parametrize("shape", [(1,), (2, 3), (4, 5, 6)])
@pytest.mark.parametrize("dtype", ["uint8", "float32"])
@pytest.mark.parametrize("array_type", ["async", "sync"])
async def test_nbytes(
shape: tuple[int, ...], dtype: str, array_type: Literal["async", "sync"]
) -> None:
"""
Test that the ``nbytes`` attribute of an Array or AsyncArray correctly reports the capacity of
the chunks of that array.
"""
store = MemoryStore()
arr = zarr.create_array(store=store, shape=shape, dtype=dtype, fill_value=0)
if array_type == "async":
assert arr._async_array.nbytes == np.prod(arr.shape) * arr.dtype.itemsize
else:
assert arr.nbytes == np.prod(arr.shape) * arr.dtype.itemsize
@pytest.mark.parametrize(
("array_shape", "chunk_shape"),
[((256,), (2,))],
)
def test_auto_partition_auto_shards(
array_shape: tuple[int, ...], chunk_shape: tuple[int, ...]
) -> None:
"""
Test that automatically picking a shard size returns a tuple of 2 * the chunk shape for any axis
where there are 8 or more chunks.
"""
dtype = np.dtype("uint8")
expected_shards: tuple[int, ...] = ()
for cs, a_len in zip(chunk_shape, array_shape, strict=False):
if a_len // cs >= 8:
expected_shards += (2 * cs,)
else:
expected_shards += (cs,)
auto_shards, _ = _auto_partition(
array_shape=array_shape, chunk_shape=chunk_shape, shard_shape="auto", dtype=dtype
)
assert auto_shards == expected_shards
@pytest.mark.parametrize("store", ["memory"], indirect=True)
class TestCreateArray:
@staticmethod
def test_chunks_and_shards(store: Store) -> None:
spath = StorePath(store)
shape = (100, 100)
chunks = (5, 5)
shards = (10, 10)