-
-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathtest_core.py
2523 lines (2137 loc) · 83.4 KB
/
test_core.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 atexit
import os
import sys
import pickle
import shutil
from typing import Any, Literal, Optional, Tuple, Union
import unittest
from itertools import zip_longest
from tempfile import mkdtemp
import numpy as np
import packaging.version
import pytest
from numcodecs import (
BZ2,
JSON,
LZ4,
Blosc,
Categorize,
Delta,
FixedScaleOffset,
GZip,
MsgPack,
Pickle,
VLenArray,
VLenBytes,
VLenUTF8,
Zlib,
)
from numcodecs.compat import ensure_bytes, ensure_ndarray
try:
from numcodecs.tests.common import greetings
except ModuleNotFoundError:
greetings = ['¡Hola mundo!', 'Hej Världen!', 'Servus Woid!', 'Hei maailma!',
'Xin chào thế giới', 'Njatjeta Botë!', 'Γεια σου κόσμε!',
'こんにちは世界', '世界,你好!', 'Helló, világ!', 'Zdravo svete!',
'เฮลโลเวิลด์']
from numpy.testing import assert_array_almost_equal, assert_array_equal
import zarr.v2
from zarr.v2._storage.store import (
BaseStore,
)
from zarr.v2.core import Array
from zarr.v2.meta import json_loads
from zarr.v2.n5 import N5Store, N5FSStore, n5_keywords
from zarr.v2.storage import (
ABSStore,
DBMStore,
DirectoryStore,
FSStore,
KVStore,
LMDBStore,
LRUStoreCache,
NestedDirectoryStore,
SQLiteStore,
atexit_rmglob,
atexit_rmtree,
init_array,
init_group,
normalize_store_arg,
)
from zarr.v2.util import buffer_size
from .util import abs_container, skip_test_env_var, have_fsspec, mktemp
from zarr.testing.utils import IS_WASM
# noinspection PyMethodMayBeStatic
class TestArray:
root = ""
path = ""
compressor = Zlib(level=1)
filters = None
dimension_separator: Literal["/", ".", None] = None
cache_metadata = True
cache_attrs = True
partial_decompress: bool = False
write_empty_chunks = True
read_only = False
storage_transformers: Tuple[Any, ...] = ()
def create_store(self) -> BaseStore:
return KVStore(dict())
# used by child classes
def create_chunk_store(self) -> Optional[BaseStore]:
return None
def create_storage_transformers(self, shape: Union[int, Tuple[int, ...]]) -> Tuple[Any, ...]:
return ()
def create_filters(self, dtype: Optional[str]) -> Tuple[Any, ...]:
return ()
def create_array(self, shape: Union[int, Tuple[int, ...]], **kwargs):
store = self.create_store()
chunk_store = self.create_chunk_store()
# keyword arguments for array initialization
init_array_kwargs = {
"path": kwargs.pop("path", self.path),
"compressor": kwargs.pop("compressor", self.compressor),
"chunk_store": chunk_store,
"storage_transformers": self.create_storage_transformers(shape),
"filters": kwargs.pop("filters", self.create_filters(kwargs.get("dtype", None))),
}
# keyword arguments for array instantiation
access_array_kwargs = {
"path": init_array_kwargs["path"],
"read_only": kwargs.pop("read_only", self.read_only),
"chunk_store": chunk_store,
"cache_metadata": kwargs.pop("cache_metadata", self.cache_metadata),
"cache_attrs": kwargs.pop("cache_attrs", self.cache_attrs),
"partial_decompress": kwargs.pop("partial_decompress", self.partial_decompress),
"write_empty_chunks": kwargs.pop("write_empty_chunks", self.write_empty_chunks),
}
init_array(store, shape, **{**init_array_kwargs, **kwargs})
return Array(store, **access_array_kwargs)
def test_array_init(self):
# normal initialization
store = self.create_store()
init_array(store, shape=100, chunks=10, dtype="<f8")
a = Array(store)
assert isinstance(a, Array)
assert (100,) == a.shape
assert (10,) == a.chunks
assert "" == a.path
assert a.name is None
assert a.basename is None
assert a.store == normalize_store_arg(store)
store.close()
# initialize at path
store = self.create_store()
init_array(store, shape=100, chunks=10, path="foo/bar", dtype="<f8")
a = Array(store, path="foo/bar")
assert isinstance(a, Array)
assert (100,) == a.shape
assert (10,) == a.chunks
assert "foo/bar" == a.path
assert "/foo/bar" == a.name
assert "bar" == a.basename
assert a.store == normalize_store_arg(store)
# store not initialized
store = self.create_store()
with pytest.raises(ValueError):
Array(store)
# group is in the way
store = self.create_store()
init_group(store, path="baz")
with pytest.raises(ValueError):
Array(store, path="baz")
def test_store_has_text_keys(self):
# Initialize array
np.random.seed(42)
z = self.create_array(shape=(1050,), chunks=100, dtype="f8", compressor=[])
z[:] = np.random.random(z.shape)
expected_type = str
for k in z.chunk_store.keys():
if not isinstance(k, expected_type): # pragma: no cover
pytest.fail("Non-text key: %s" % repr(k))
z.store.close()
def test_store_has_binary_values(self):
# Initialize array
np.random.seed(42)
z = self.create_array(shape=(1050,), chunks=100, dtype="f8", compressor=[])
z[:] = np.random.random(z.shape)
for v in z.chunk_store.values():
try:
ensure_ndarray(v)
except TypeError: # pragma: no cover
pytest.fail("Non-bytes-like value: %s" % repr(v))
z.store.close()
def test_store_has_bytes_values(self):
# Test that many stores do hold bytes values.
# Though this is not a strict requirement.
# Should be disabled by any stores that fail this as needed.
# Initialize array
np.random.seed(42)
z = self.create_array(shape=(1050,), chunks=100, dtype="f8", compressor=[])
z[:] = np.random.random(z.shape)
# Check in-memory array only contains `bytes`
assert all(isinstance(v, bytes) for v in z.chunk_store.values())
z.store.close()
def test_nbytes_stored(self):
# dict as store
z = self.create_array(shape=1000, chunks=100)
expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())
assert expect_nbytes_stored == z.nbytes_stored
z[:] = 42
expect_nbytes_stored = sum(buffer_size(v) for v in z.store.values())
assert expect_nbytes_stored == z.nbytes_stored
# mess with store
try:
z.store[z._key_prefix + "foo"] = list(range(10))
assert -1 == z.nbytes_stored
except TypeError:
pass
z.store.close()
# noinspection PyStatementEffect
def test_array_1d(self):
a = np.arange(1050)
z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)
# check properties
assert len(a) == len(z)
assert a.ndim == z.ndim
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (100,) == z.chunks
assert a.nbytes == z.nbytes
assert 11 == z.nchunks
assert 0 == z.nchunks_initialized
assert (11,) == z.cdata_shape
# check empty
b = z[:]
assert isinstance(b, np.ndarray)
assert a.shape == b.shape
assert a.dtype == b.dtype
# check attributes
z.attrs["foo"] = "bar"
assert "bar" == z.attrs["foo"]
# set data
z[:] = a
# check properties
assert a.nbytes == z.nbytes
assert 11 == z.nchunks
assert 11 == z.nchunks_initialized
# check slicing
assert_array_equal(a, np.array(z))
assert_array_equal(a, z[:])
assert_array_equal(a, z[...])
# noinspection PyTypeChecker
assert_array_equal(a, z[slice(None)])
assert_array_equal(a[:10], z[:10])
assert_array_equal(a[10:20], z[10:20])
assert_array_equal(a[-10:], z[-10:])
assert_array_equal(a[:10, ...], z[:10, ...])
assert_array_equal(a[10:20, ...], z[10:20, ...])
assert_array_equal(a[-10:, ...], z[-10:, ...])
assert_array_equal(a[..., :10], z[..., :10])
assert_array_equal(a[..., 10:20], z[..., 10:20])
assert_array_equal(a[..., -10:], z[..., -10:])
# ...across chunk boundaries...
assert_array_equal(a[:110], z[:110])
assert_array_equal(a[190:310], z[190:310])
assert_array_equal(a[-110:], z[-110:])
# single item
assert a[0] == z[0]
assert a[-1] == z[-1]
# unusual integer items
assert a[42] == z[np.int64(42)]
assert a[42] == z[np.int32(42)]
assert a[42] == z[np.uint64(42)]
assert a[42] == z[np.uint32(42)]
# too many indices
with pytest.raises(IndexError):
z[:, :]
with pytest.raises(IndexError):
z[0, :]
with pytest.raises(IndexError):
z[:, 0]
with pytest.raises(IndexError):
z[0, 0]
# only single ellipsis allowed
with pytest.raises(IndexError):
z[..., ...]
# check partial assignment
b = np.arange(1e5, 2e5)
z[190:310] = b[190:310]
assert_array_equal(a[:190], z[:190])
assert_array_equal(b[190:310], z[190:310])
assert_array_equal(a[310:], z[310:])
z.store.close()
def test_array_1d_fill_value(self):
for fill_value in -1, 0, 1, 10:
a = np.arange(1050)
f = np.empty_like(a)
f.fill(fill_value)
z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype, fill_value=fill_value)
z[190:310] = a[190:310]
assert_array_equal(f[:190], z[:190])
assert_array_equal(a[190:310], z[190:310])
assert_array_equal(f[310:], z[310:])
z.store.close()
def test_array_1d_set_scalar(self):
# test setting the contents of an array with a scalar value
# setup
a = np.zeros(100)
z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)
z[:] = a
assert_array_equal(a, z[:])
for value in -1, 0, 1, 10:
a[15:35] = value
z[15:35] = value
assert_array_equal(a, z[:])
a[:] = value
z[:] = value
assert_array_equal(a, z[:])
z.store.close()
def test_array_1d_selections(self):
# light test here, full tests in test_indexing
# setup
a = np.arange(1050)
z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype)
z[:] = a
# get
assert_array_equal(a[50:150], z.get_orthogonal_selection(slice(50, 150)))
assert_array_equal(a[50:150], z.oindex[50:150])
ix = [99, 100, 101]
bix = np.zeros_like(a, dtype=bool)
bix[ix] = True
assert_array_equal(a[ix], z.get_orthogonal_selection(ix))
assert_array_equal(a[ix], z.oindex[ix])
assert_array_equal(a[ix], z.get_coordinate_selection(ix))
assert_array_equal(a[ix], z.vindex[ix])
assert_array_equal(a[bix], z.get_mask_selection(bix))
assert_array_equal(a[bix], z.oindex[bix])
assert_array_equal(a[bix], z.vindex[bix])
assert_array_equal(a[200:400], z.get_block_selection(slice(2, 4)))
assert_array_equal(a[200:400], z.blocks[2:4])
# set
z.set_orthogonal_selection(slice(50, 150), 1)
assert_array_equal(1, z[50:150])
z.oindex[50:150] = 2
assert_array_equal(2, z[50:150])
z.set_orthogonal_selection(ix, 3)
assert_array_equal(3, z.get_coordinate_selection(ix))
z.oindex[ix] = 4
assert_array_equal(4, z.oindex[ix])
z.set_coordinate_selection(ix, 5)
assert_array_equal(5, z.get_coordinate_selection(ix))
z.vindex[ix] = 6
assert_array_equal(6, z.vindex[ix])
z.set_mask_selection(bix, 7)
assert_array_equal(7, z.get_mask_selection(bix))
z.vindex[bix] = 8
assert_array_equal(8, z.vindex[bix])
z.oindex[bix] = 9
assert_array_equal(9, z.oindex[bix])
z.set_block_selection(slice(2, 4), 10)
assert_array_equal(10, z[200:400])
z.blocks[2:4] = 11
assert_array_equal(11, z[200:400])
z.store.close()
# noinspection PyStatementEffect
def test_array_2d(self):
a = np.arange(10000).reshape((1000, 10))
z = self.create_array(shape=a.shape, chunks=(100, 2), dtype=a.dtype)
# check properties
assert len(a) == len(z)
assert a.ndim == z.ndim
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (100, 2) == z.chunks
assert 0 == z.nchunks_initialized
assert (10, 5) == z.cdata_shape
# set data
z[:] = a
# check properties
assert a.nbytes == z.nbytes
assert 50 == z.nchunks_initialized
# check array-like
assert_array_equal(a, np.array(z))
# check slicing
# total slice
assert_array_equal(a, z[:])
assert_array_equal(a, z[...])
# noinspection PyTypeChecker
assert_array_equal(a, z[slice(None)])
# slice first dimension
assert_array_equal(a[:10], z[:10])
assert_array_equal(a[10:20], z[10:20])
assert_array_equal(a[-10:], z[-10:])
assert_array_equal(a[:10, :], z[:10, :])
assert_array_equal(a[10:20, :], z[10:20, :])
assert_array_equal(a[-10:, :], z[-10:, :])
assert_array_equal(a[:10, ...], z[:10, ...])
assert_array_equal(a[10:20, ...], z[10:20, ...])
assert_array_equal(a[-10:, ...], z[-10:, ...])
assert_array_equal(a[:10, :, ...], z[:10, :, ...])
assert_array_equal(a[10:20, :, ...], z[10:20, :, ...])
assert_array_equal(a[-10:, :, ...], z[-10:, :, ...])
# slice second dimension
assert_array_equal(a[:, :2], z[:, :2])
assert_array_equal(a[:, 2:4], z[:, 2:4])
assert_array_equal(a[:, -2:], z[:, -2:])
assert_array_equal(a[..., :2], z[..., :2])
assert_array_equal(a[..., 2:4], z[..., 2:4])
assert_array_equal(a[..., -2:], z[..., -2:])
assert_array_equal(a[:, ..., :2], z[:, ..., :2])
assert_array_equal(a[:, ..., 2:4], z[:, ..., 2:4])
assert_array_equal(a[:, ..., -2:], z[:, ..., -2:])
# slice both dimensions
assert_array_equal(a[:10, :2], z[:10, :2])
assert_array_equal(a[10:20, 2:4], z[10:20, 2:4])
assert_array_equal(a[-10:, -2:], z[-10:, -2:])
# slicing across chunk boundaries
assert_array_equal(a[:110], z[:110])
assert_array_equal(a[190:310], z[190:310])
assert_array_equal(a[-110:], z[-110:])
assert_array_equal(a[:110, :], z[:110, :])
assert_array_equal(a[190:310, :], z[190:310, :])
assert_array_equal(a[-110:, :], z[-110:, :])
assert_array_equal(a[:, :3], z[:, :3])
assert_array_equal(a[:, 3:7], z[:, 3:7])
assert_array_equal(a[:, -3:], z[:, -3:])
assert_array_equal(a[:110, :3], z[:110, :3])
assert_array_equal(a[190:310, 3:7], z[190:310, 3:7])
assert_array_equal(a[-110:, -3:], z[-110:, -3:])
# single row/col/item
assert_array_equal(a[0], z[0])
assert_array_equal(a[-1], z[-1])
assert_array_equal(a[:, 0], z[:, 0])
assert_array_equal(a[:, -1], z[:, -1])
assert a[0, 0] == z[0, 0]
assert a[-1, -1] == z[-1, -1]
# too many indices
with pytest.raises(IndexError):
z[:, :, :]
with pytest.raises(IndexError):
z[0, :, :]
with pytest.raises(IndexError):
z[:, 0, :]
with pytest.raises(IndexError):
z[:, :, 0]
with pytest.raises(IndexError):
z[0, 0, 0]
# only single ellipsis allowed
with pytest.raises(IndexError):
z[..., ...]
# check partial assignment
b = np.arange(10000, 20000).reshape((1000, 10))
z[190:310, 3:7] = b[190:310, 3:7]
assert_array_equal(a[:190], z[:190])
assert_array_equal(a[:, :3], z[:, :3])
assert_array_equal(b[190:310, 3:7], z[190:310, 3:7])
assert_array_equal(a[310:], z[310:])
assert_array_equal(a[:, 7:], z[:, 7:])
z.store.close()
def test_array_2d_edge_case(self):
# this fails with filters - chunks extend beyond edge of array, messes with delta
# filter if no fill value?
shape = 1000, 10
chunks = 300, 30
dtype = "i8"
z = self.create_array(shape=shape, dtype=dtype, chunks=chunks)
z[:] = 0
expect = np.zeros(shape, dtype=dtype)
actual = z[:]
assert_array_equal(expect, actual)
z.store.close()
def test_array_2d_partial(self):
z = self.create_array(shape=(1000, 10), chunks=(100, 2), dtype="i4", fill_value=0)
# check partial assignment, single row
c = np.arange(z.shape[1])
z[0, :] = c
with pytest.raises(ValueError):
# N.B., NumPy allows this, but we'll be strict for now
z[2:3] = c
with pytest.raises(ValueError):
# N.B., NumPy allows this, but we'll be strict for now
z[-1:] = c
z[2:3] = c[None, :]
z[-1:] = c[None, :]
assert_array_equal(c, z[0, :])
assert_array_equal(c, z[2, :])
assert_array_equal(c, z[-1, :])
# check partial assignment, single column
d = np.arange(z.shape[0])
z[:, 0] = d
with pytest.raises(ValueError):
z[:, 2:3] = d
with pytest.raises(ValueError):
z[:, -1:] = d
z[:, 2:3] = d[:, None]
z[:, -1:] = d[:, None]
assert_array_equal(d, z[:, 0])
assert_array_equal(d, z[:, 2])
assert_array_equal(d, z[:, -1])
# check single item assignment
z[0, 0] = -1
z[2, 2] = -1
z[-1, -1] = -1
assert -1 == z[0, 0]
assert -1 == z[2, 2]
assert -1 == z[-1, -1]
z.store.close()
def test_array_order(self):
# 1D
a = np.arange(1050)
for order in "C", "F":
z = self.create_array(shape=a.shape, chunks=100, dtype=a.dtype, order=order)
assert order == z.order
if order == "F":
assert z[:].flags.f_contiguous
else:
assert z[:].flags.c_contiguous
z[:] = a
assert_array_equal(a, z[:])
z.store.close()
# 2D
a = np.arange(10000).reshape((100, 100))
for order in "C", "F":
z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype, order=order)
assert order == z.order
if order == "F":
assert z[:].flags.f_contiguous
else:
assert z[:].flags.c_contiguous
z[:] = a
actual = z[:]
assert_array_equal(a, actual)
z.store.close()
def test_setitem_data_not_shared(self):
# check that data don't end up being shared with another array
# https://github.com/alimanfoo/zarr/issues/79
z = self.create_array(shape=20, chunks=10, dtype="i4")
a = np.arange(20, dtype="i4")
z[:] = a
assert_array_equal(z[:], np.arange(20, dtype="i4"))
a[:] = 0
assert_array_equal(z[:], np.arange(20, dtype="i4"))
z.store.close()
def expected(self):
return [
"063b02ff8d9d3bab6da932ad5828b506ef0a6578",
"f97b84dc9ffac807415f750100108764e837bb82",
"c7190ad2bea1e9d2e73eaa2d3ca9187be1ead261",
"14470724dca6c1837edddedc490571b6a7f270bc",
"2a1046dd99b914459b3e86be9dde05027a07d209",
]
def test_hexdigest(self):
found = []
# Check basic 1-D array
z = self.create_array(shape=(1050,), chunks=100, dtype="<i4")
found.append(z.hexdigest())
z.store.close()
# Check basic 1-D array with different type
z = self.create_array(shape=(1050,), chunks=100, dtype="<f4")
found.append(z.hexdigest())
z.store.close()
# Check basic 2-D array
z = self.create_array(
shape=(
20,
35,
),
chunks=10,
dtype="<i4",
)
found.append(z.hexdigest())
z.store.close()
# Check basic 1-D array with some data
z = self.create_array(shape=(1050,), chunks=100, dtype="<i4")
z[200:400] = np.arange(200, 400, dtype="i4")
found.append(z.hexdigest())
z.store.close()
# Check basic 1-D array with attributes
z = self.create_array(shape=(1050,), chunks=100, dtype="<i4")
z.attrs["foo"] = "bar"
found.append(z.hexdigest())
z.store.close()
assert self.expected() == found
def test_resize_1d(self):
z = self.create_array(shape=105, chunks=10, dtype="i4", fill_value=0)
a = np.arange(105, dtype="i4")
z[:] = a
assert (105,) == z.shape
assert (105,) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10,) == z.chunks
assert_array_equal(a, z[:])
z.resize(205)
assert (205,) == z.shape
assert (205,) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10,) == z.chunks
assert_array_equal(a, z[:105])
assert_array_equal(np.zeros(100, dtype="i4"), z[105:])
z.resize(55)
assert (55,) == z.shape
assert (55,) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10,) == z.chunks
assert_array_equal(a[:55], z[:])
# via shape setter
z.shape = (105,)
assert (105,) == z.shape
assert (105,) == z[:].shape
z.store.close()
def test_resize_2d(self):
z = self.create_array(shape=(105, 105), chunks=(10, 10), dtype="i4", fill_value=0)
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z[:] = a
assert (105, 105) == z.shape
assert (105, 105) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10, 10) == z.chunks
assert_array_equal(a, z[:])
z.resize((205, 205))
assert (205, 205) == z.shape
assert (205, 205) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10, 10) == z.chunks
assert_array_equal(a, z[:105, :105])
assert_array_equal(np.zeros((100, 205), dtype="i4"), z[105:, :])
assert_array_equal(np.zeros((205, 100), dtype="i4"), z[:, 105:])
z.resize((55, 55))
assert (55, 55) == z.shape
assert (55, 55) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10, 10) == z.chunks
assert_array_equal(a[:55, :55], z[:])
z.resize((55, 1))
assert (55, 1) == z.shape
assert (55, 1) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10, 10) == z.chunks
assert_array_equal(a[:55, :1], z[:])
z.resize((1, 55))
assert (1, 55) == z.shape
assert (1, 55) == z[:].shape
assert np.dtype("i4") == z.dtype
assert np.dtype("i4") == z[:].dtype
assert (10, 10) == z.chunks
assert_array_equal(a[:1, :10], z[:, :10])
assert_array_equal(np.zeros((1, 55 - 10), dtype="i4"), z[:, 10:55])
# via shape setter
z.shape = (105, 105)
assert (105, 105) == z.shape
assert (105, 105) == z[:].shape
z.store.close()
# checks that resizing preserves metadata
if self.dimension_separator == "/":
z_ = zarr.v2.open(z.store)
if hasattr(z_, "dimension_separator"):
assert z_.dimension_separator == self.dimension_separator
z_.store.close()
def test_append_1d(self):
a = np.arange(105)
z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10,) == z.chunks
assert_array_equal(a, z[:])
b = np.arange(105, 205)
e = np.append(a, b)
z.append(b)
assert e.shape == z.shape
assert e.dtype == z.dtype
assert (10,) == z.chunks
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
assert_array_equal(f, z[:])
z.store.close()
def test_append_2d(self):
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10, 10) == z.chunks
actual = z[:]
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[:]
assert_array_equal(e, actual)
z.store.close()
def test_append_2d_axis(self):
a = np.arange(105 * 105, dtype="i4").reshape((105, 105))
z = self.create_array(shape=a.shape, chunks=(10, 10), dtype=a.dtype)
z[:] = a
assert a.shape == z.shape
assert a.dtype == z.dtype
assert (10, 10) == z.chunks
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
assert_array_equal(e, z[:])
z.store.close()
def test_append_bad_shape(self):
a = np.arange(100)
z = self.create_array(shape=a.shape, chunks=10, dtype=a.dtype)
z[:] = a
b = a.reshape(10, 10)
with pytest.raises(ValueError):
z.append(b)
z.store.close()
def test_read_only(self):
z = self.create_array(shape=1000, chunks=100)
assert not z.read_only
z.store.close()
z = self.create_array(shape=1000, chunks=100, read_only=True)
assert z.read_only
with pytest.raises(PermissionError):
z[:] = 42
with pytest.raises(PermissionError):
z.resize(2000)
with pytest.raises(PermissionError):
z.append(np.arange(1000))
with pytest.raises(PermissionError):
z.set_basic_selection(Ellipsis, 42)
with pytest.raises(PermissionError):
z.set_orthogonal_selection([0, 1, 2], 42)
with pytest.raises(PermissionError):
z.oindex[[0, 1, 2]] = 42
with pytest.raises(PermissionError):
z.set_coordinate_selection([0, 1, 2], 42)
with pytest.raises(PermissionError):
z.vindex[[0, 1, 2]] = 42
with pytest.raises(PermissionError):
z.blocks[...] = 42
with pytest.raises(PermissionError):
z.set_mask_selection(np.ones(z.shape, dtype=bool), 42)
z.store.close()
def test_pickle(self):
# setup array
z = self.create_array(
shape=1000, chunks=100, dtype=int, cache_metadata=False, cache_attrs=False
)
shape = z.shape
chunks = z.chunks
dtype = z.dtype
compressor_config = None
if z.compressor:
compressor_config = z.compressor.get_config()
fill_value = z.fill_value
cache_metadata = z._cache_metadata
attrs_cache = z.attrs.cache
a = np.random.randint(0, 1000, 1000)
z[:] = a
# round trip through pickle
dump = pickle.dumps(z)
# some stores cannot be opened twice at the same time, need to close
# store before can round-trip through pickle
z.store.close()
z2 = pickle.loads(dump)
# verify
assert shape == z2.shape
assert chunks == z2.chunks
assert dtype == z2.dtype
if z2.compressor:
assert compressor_config == z2.compressor.get_config()
assert fill_value == z2.fill_value
assert cache_metadata == z2._cache_metadata
assert attrs_cache == z2.attrs.cache
assert_array_equal(a, z2[:])
z2.store.close()
def test_np_ufuncs(self):
z = self.create_array(shape=(100, 100), chunks=(10, 10))
a = np.arange(10000).reshape(100, 100)
z[:] = a
assert np.sum(a) == np.sum(z)
assert_array_equal(np.sum(a, axis=0), np.sum(z, axis=0))
assert np.mean(a) == np.mean(z)
assert_array_equal(np.mean(a, axis=1), np.mean(z, axis=1))
condition = np.random.randint(0, 2, size=100, dtype=bool)
assert_array_equal(np.compress(condition, a, axis=0), np.compress(condition, z, axis=0))
indices = np.random.choice(100, size=50, replace=True)
assert_array_equal(np.take(a, indices, axis=1), np.take(z, indices, axis=1))
z.store.close()
# use zarr array as indices or condition
zc = self.create_array(
shape=condition.shape, dtype=condition.dtype, chunks=10, filters=None
)
zc[:] = condition
assert_array_equal(np.compress(condition, a, axis=0), np.compress(zc, a, axis=0))
zc.store.close()
zi = self.create_array(shape=indices.shape, dtype=indices.dtype, chunks=10, filters=None)
zi[:] = indices
# this triggers __array__() call with dtype argument
assert_array_equal(np.take(a, indices, axis=1), np.take(a, zi, axis=1))
zi.store.close()
# noinspection PyStatementEffect
def test_0len_dim_1d(self):
# Test behaviour for 1D array with zero-length dimension.
z = self.create_array(shape=0, fill_value=0)
a = np.zeros(0)
assert a.ndim == z.ndim
assert a.shape == z.shape
assert a.dtype == z.dtype
assert a.size == z.size
assert 0 == z.nchunks
# cannot make a good decision when auto-chunking if a dimension has zero length,
# fall back to 1 for now
assert (1,) == z.chunks
# check __getitem__
assert isinstance(z[:], np.ndarray)
assert_array_equal(a, np.array(z))
assert_array_equal(a, z[:])
assert_array_equal(a, z[...])
assert_array_equal(a[0:0], z[0:0])
with pytest.raises(IndexError):
z[0]
# check __setitem__
# these should succeed but do nothing
z[:] = 42
z[...] = 42
# this should error
with pytest.raises(IndexError):
z[0] = 42
z.store.close()
# noinspection PyStatementEffect
def test_0len_dim_2d(self):
# Test behavioud for 2D array with a zero-length dimension.
z = self.create_array(shape=(10, 0), fill_value=0)
a = np.zeros((10, 0))
assert a.ndim == z.ndim
assert a.shape == z.shape
assert a.dtype == z.dtype
assert a.size == z.size
assert 0 == z.nchunks
# cannot make a good decision when auto-chunking if a dimension has zero length,
# fall back to 1 for now
assert (10, 1) == z.chunks
# check __getitem__
assert isinstance(z[:], np.ndarray)
assert_array_equal(a, np.array(z))
assert_array_equal(a, z[:])
assert_array_equal(a, z[...])
assert_array_equal(a[0], z[0])
assert_array_equal(a[0, 0:0], z[0, 0:0])
assert_array_equal(a[0, :], z[0, :])
assert_array_equal(a[0, 0:0], z[0, 0:0])
with pytest.raises(IndexError):
z[:, 0]
# check __setitem__
# these should succeed but do nothing
z[:] = 42
z[...] = 42
z[0, :] = 42
# this should error
with pytest.raises(IndexError):
z[:, 0] = 42
z.store.close()
# noinspection PyStatementEffect
@pytest.mark.xfail(reason="Can't get this to pass under WASM right now")
def test_array_0d(self):
# test behaviour for array with 0 dimensions
# setup
a = np.zeros(())
z = self.create_array(shape=(), dtype=a.dtype, fill_value=0, write_empty_chunks=False)
# check properties
assert a.ndim == z.ndim
assert a.shape == z.shape
assert a.size == z.size
assert a.dtype == z.dtype
assert a.nbytes == z.nbytes
with pytest.raises(TypeError):