Repository navigation
Expand file tree
/
Copy pathtest_unified_chunk_grid.py
More file actions
3166 lines (2614 loc) · 112 KB
/
Copy pathtest_unified_chunk_grid.py
File metadata and controls
3166 lines (2614 loc) · 112 KB
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
"""
Tests for the unified ChunkGrid design (POC).
Tests the core ChunkGrid with FixedDimension/VaryingDimension internals,
ChunkSpec, serialization round-trips, indexing with rectilinear grids,
and end-to-end array creation + read/write.
"""
from __future__ import annotations
import re
from functools import partial
from typing import TYPE_CHECKING, Any
import numpy as np
import pytest
import zarr
from tests.test_metadata.conftest import minimal_metadata_dict_v3
from zarr.core.buffer import default_buffer_prototype
from zarr.core.chunk_grids import (
ChunkGrid,
ChunkSpec,
FixedDimension,
VaryingDimension,
guess_chunks,
)
from zarr.core.common import compress_rle, expand_rle
from zarr.core.dtype import UInt8
from zarr.core.metadata.v3 import (
ArrayV3Metadata,
RectilinearChunkGridMetadata,
RectilinearChunkGridMetadataJSON,
RegularChunkGridMetadata,
parse_chunk_grid,
)
from zarr.errors import BoundsCheckError
from zarr.storage import MemoryStore
if TYPE_CHECKING:
from collections.abc import Callable, Generator
from pathlib import Path
from zarr.core.common import ChunksLike
@pytest.fixture(autouse=True)
def _enable_rectilinear_chunks() -> Generator[None, None, None]:
"""Enable rectilinear chunks for all tests in this module."""
with zarr.config.set({"array.rectilinear_chunks": True}):
yield
def _edges(grid: ChunkGrid, dim: int) -> tuple[int, ...]:
"""Extract the per-chunk edge lengths for *dim* from a ChunkGrid."""
d = grid._dimensions[dim]
if isinstance(d, FixedDimension):
return tuple(d.size for _ in range(d.nchunks))
if isinstance(d, VaryingDimension):
return tuple(d.edges)
raise TypeError(f"Unexpected dimension type: {type(d)}")
# ---------------------------------------------------------------------------
# Dimension index_to_chunk bounds tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("dim", "index", "match"),
[
(VaryingDimension([10, 20, 30], extent=60), 60, "out of bounds"),
(VaryingDimension([10, 20, 30], extent=60), 100, "out of bounds"),
(FixedDimension(size=10, extent=95), 95, "out of bounds"),
(FixedDimension(size=10, extent=95), -1, "Negative"),
],
ids=[
"varying-at-extent",
"varying-past-extent",
"fixed-at-extent",
"fixed-negative",
],
)
def test_dimension_index_to_chunk_bounds(
dim: FixedDimension | VaryingDimension, index: int, match: str
) -> None:
"""Out-of-bounds or negative indices raise IndexError for both dimension types"""
with pytest.raises(IndexError, match=match):
dim.index_to_chunk(index)
@pytest.mark.parametrize(
("dim", "index", "expected"),
[
(VaryingDimension([10, 20, 30], extent=60), 59, 2),
(FixedDimension(size=10, extent=95), 94, 9),
],
ids=["varying-last-valid", "fixed-last-valid"],
)
def test_dimension_index_to_chunk_last_valid(
dim: FixedDimension | VaryingDimension, index: int, expected: int
) -> None:
"""Last valid index maps to the correct chunk for both dimension types"""
assert dim.index_to_chunk(index) == expected
# ---------------------------------------------------------------------------
# Rectilinear feature flag tests
# ---------------------------------------------------------------------------
_RECTILINEAR_DOC = minimal_metadata_dict_v3(
shape=(30, 50),
chunk_grid={
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[10, 20], [25, 25]]},
},
)
@pytest.mark.parametrize(
"action",
[
lambda: ArrayV3Metadata.from_dict(dict(_RECTILINEAR_DOC)), # type: ignore[arg-type]
lambda: ArrayV3Metadata(
shape=(30, 50),
data_type=UInt8(),
chunk_grid=RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25))),
chunk_key_encoding={"name": "default"},
fill_value=0,
codecs=[{"name": "bytes"}],
attributes=None,
dimension_names=None,
).to_buffer_dict(default_buffer_prototype()),
lambda: zarr.create_array(MemoryStore(), shape=(30,), chunks=[[10, 20]], dtype="int32"),
],
ids=["read", "store", "create_array"],
)
def test_rectilinear_feature_flag_blocked(action: Any) -> None:
"""Reading or storing an array metadata document that declares a rectilinear chunk
grid raises ValueError when the feature flag is disabled."""
with zarr.config.set({"array.rectilinear_chunks": False}):
with pytest.raises(ValueError, match="experimental and disabled by default"):
action()
def test_rectilinear_feature_flag_names_stored_array() -> None:
"""Opening a stored array whose document the flag refuses names the array."""
store = MemoryStore()
with zarr.config.set({"array.rectilinear_chunks": True}):
zarr.create_array(store, name="r", shape=(30,), chunks=[[10, 20]], dtype="int32")
with (
zarr.config.set({"array.rectilinear_chunks": False}),
pytest.raises(ValueError, match="experimental and disabled by default") as info,
):
zarr.open_array(store, path="r")
assert info.value.__notes__ == [f"Array {str(store) + '/r'!r}: nothing was read."]
def test_rectilinear_metadata_classes_not_gated() -> None:
"""The flag gates stored documents, not the chunk grid metadata classes."""
with zarr.config.set({"array.rectilinear_chunks": False}):
grid = RectilinearChunkGridMetadata(chunk_shapes=((10, 20), (25, 25)))
assert grid.ndim == 2
# ---------------------------------------------------------------------------
# FixedDimension tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
(
"size",
"extent",
"chunk_ix",
"expected_nchunks",
"expected_chunk_size",
"expected_data_size",
"expected_offset",
),
[
(10, 100, 0, 10, 10, 10, 0),
(10, 100, 1, 10, 10, 10, 10),
(10, 100, 9, 10, 10, 10, 90),
(10, 95, 9, 10, 10, 5, 90), # boundary chunk
(10, 0, None, 0, None, None, None), # zero-extent: no chunks, size still >= 1
],
ids=["start", "middle", "end", "boundary", "zero-extent"],
)
def test_fixed_dimension(
size: int,
extent: int,
chunk_ix: int | None,
expected_nchunks: int,
expected_chunk_size: int | None,
expected_data_size: int | None,
expected_offset: int | None,
) -> None:
"""FixedDimension properties match expected values for various chunk/extent combinations"""
d = FixedDimension(size=size, extent=extent)
assert d.nchunks == expected_nchunks
if chunk_ix is not None:
assert d.chunk_size(chunk_ix) == expected_chunk_size
assert d.data_size(chunk_ix) == expected_data_size
assert d.chunk_offset(chunk_ix) == expected_offset
@pytest.mark.parametrize(
("idx", "expected"),
[(0, 0), (9, 0), (10, 1), (25, 2)],
)
def test_fixed_dimension_index_to_chunk(idx: int, expected: int) -> None:
"""FixedDimension.index_to_chunk maps element indices to correct chunk indices"""
d = FixedDimension(size=10, extent=100)
assert d.index_to_chunk(idx) == expected
def test_fixed_dimension_indices_to_chunks() -> None:
"""FixedDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array"""
d = FixedDimension(size=10, extent=100)
indices = np.array([0, 5, 10, 15, 99])
np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 9])
@pytest.mark.parametrize(
("size", "extent", "match"),
[
(-1, 100, "size must be >= 1"),
(0, 100, "size must be >= 1"),
(0, 0, "size must be >= 1"),
(10, -1, "extent must be >= 0"),
],
ids=["negative-size", "zero-size", "zero-size-zero-extent", "negative-extent"],
)
def test_fixed_dimension_rejects_invalid(size: int, extent: int, match: str) -> None:
"""FixedDimension raises ValueError for a size below 1 or a negative extent."""
with pytest.raises(ValueError, match=match):
FixedDimension(size=size, extent=extent)
# ---------------------------------------------------------------------------
# VaryingDimension tests
# ---------------------------------------------------------------------------
def test_varying_dimension_construction() -> None:
"""VaryingDimension stores edges, cumulative sums, nchunks, and extent correctly"""
d = VaryingDimension([10, 20, 30], extent=60)
assert d.edges == (10, 20, 30)
assert d.cumulative == (10, 30, 60)
assert d.nchunks == 3
assert d.extent == 60
@pytest.mark.parametrize(
(
"chunk_idx",
"expected_offset",
"expected_size",
"expected_data",
"expected_chunk_for_first_idx",
),
[
(0, 0, 10, 10, 0),
(1, 10, 20, 20, 1),
(2, 30, 30, 30, 2),
],
)
def test_varying_dimension(
chunk_idx: int,
expected_offset: int,
expected_size: int,
expected_data: int,
expected_chunk_for_first_idx: int,
) -> None:
"""VaryingDimension chunk_offset, chunk_size, data_size, and index_to_chunk return correct values"""
d = VaryingDimension([10, 20, 30], extent=60)
assert d.chunk_offset(chunk_idx) == expected_offset
assert d.chunk_size(chunk_idx) == expected_size
assert d.data_size(chunk_idx) == expected_data
assert d.index_to_chunk(expected_offset) == expected_chunk_for_first_idx
def test_varying_dimension_indices_to_chunks() -> None:
"""VaryingDimension.indices_to_chunks vectorizes index-to-chunk mapping over an array"""
d = VaryingDimension([10, 20, 30], extent=60)
indices = np.array([0, 9, 10, 29, 30, 59])
np.testing.assert_array_equal(d.indices_to_chunks(indices), [0, 0, 1, 1, 2, 2])
@pytest.mark.parametrize(
("edges", "extent", "match"),
[
([], 0, "must not be empty"),
([10, 0, 5], 15, "must be > 0"),
],
ids=["empty", "zero-edge"],
)
def test_varying_dimension_rejects_invalid(edges: list[int], extent: int, match: str) -> None:
"""VaryingDimension raises ValueError for empty edges or zero-length edges"""
with pytest.raises(ValueError, match=match):
VaryingDimension(edges, extent=extent)
# ---------------------------------------------------------------------------
# ChunkSpec tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("slices", "codec_shape", "expected_shape", "expected_boundary"),
[
((slice(0, 10), slice(0, 20)), (10, 20), (10, 20), False),
((slice(90, 95), slice(0, 20)), (10, 20), (5, 20), True),
((slice(10, 10),), (0,), (0,), False),
((slice(0, 10), slice(0, 5)), (10, 10), (10, 5), True),
],
ids=["basic", "boundary", "empty-slices", "multidim-boundary"],
)
def test_chunk_spec(
slices: tuple[slice, ...],
codec_shape: tuple[int, ...],
expected_shape: tuple[int, ...],
expected_boundary: bool,
) -> None:
"""ChunkSpec reports correct shape and boundary status from slices and codec_shape"""
spec = ChunkSpec(slices=slices, codec_shape=codec_shape)
assert spec.shape == expected_shape
assert spec.is_boundary == expected_boundary
# ---------------------------------------------------------------------------
# ChunkGrid construction tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("array_shape", "chunk_sizes", "expected_regular", "expected_ndim", "expected_chunk_shape"),
[
((100, 200), (10, 20), True, 2, (10, 20)),
((), (), True, 0, ()),
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], False, 2, None),
# explicit edge lists stay rectilinear even when uniform (gh-4272), including
# uniform edges overhanging the extent after a shrinking resize
((30, 50), [[10, 10, 10], [25, 25]], False, 2, None),
((35,), [[10, 10, 10, 10]], False, 1, None),
],
ids=["regular", "zero-dim", "rectilinear", "uniform-edges", "uniform-edges-overhang"],
)
def test_chunk_grid_construction(
array_shape: tuple[int, ...],
chunk_sizes: Any,
expected_regular: bool,
expected_ndim: int,
expected_chunk_shape: tuple[int, ...] | None,
) -> None:
"""ChunkGrid.from_sizes produces grids with correct regularity, ndim, and chunk_shape"""
g = ChunkGrid.from_sizes(array_shape, chunk_sizes)
assert g.is_regular == expected_regular
assert g.ndim == expected_ndim
if expected_chunk_shape is not None:
assert g.chunk_shape == expected_chunk_shape
else:
with pytest.raises(ValueError, match="only available for regular"):
_ = g.chunk_shape
# ---------------------------------------------------------------------------
# ChunkGrid query tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("shape", "chunks", "expected_grid_shape"),
[
((100, 200), (10, 20), (10, 10)),
((95, 200), (10, 20), (10, 10)),
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 4)),
],
ids=["regular", "regular-boundary", "rectilinear"],
)
def test_chunk_grid_shape(
shape: tuple[int, ...],
chunks: Any,
expected_grid_shape: tuple[int, ...],
) -> None:
"""ChunkGrid.grid_shape returns the expected number of chunks per dimension"""
g = ChunkGrid.from_sizes(shape, chunks)
assert g.grid_shape == expected_grid_shape
@pytest.mark.parametrize(
(
"array_shape",
"chunk_sizes",
"coords",
"expected_shape",
"expected_codec_shape",
"expected_boundary",
),
[
# regular interior
((100, 200), (10, 20), (0, 0), (10, 20), (10, 20), False),
# regular boundary
((95, 200), (10, 20), (9, 0), (5, 20), (10, 20), True),
# rectilinear
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (0, 0), (10, 25), (10, 25), False),
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (1, 0), (20, 25), (20, 25), False),
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (2, 3), (30, 25), (30, 25), False),
],
ids=["regular", "regular-boundary", "rectilinear-0,0", "rectilinear-1,0", "rectilinear-2,3"],
)
def test_chunk_grid_getitem(
array_shape: tuple[int, ...],
chunk_sizes: Any,
coords: tuple[int, ...],
expected_shape: tuple[int, ...],
expected_codec_shape: tuple[int, ...],
expected_boundary: bool,
) -> None:
"""ChunkGrid.__getitem__ returns a ChunkSpec with correct shape, codec_shape, and boundary flag"""
g = ChunkGrid.from_sizes(array_shape, chunk_sizes)
spec = g[coords]
assert spec is not None
assert spec.shape == expected_shape
assert spec.codec_shape == expected_codec_shape
assert spec.is_boundary == expected_boundary
@pytest.mark.parametrize(
("array_shape", "chunk_sizes", "coords"),
[
((100, 200), (10, 20), (99, 0)),
((60, 100), [[10, 20, 30], [25, 25, 25, 25]], (3, 0)),
],
ids=["regular-oob", "rectilinear-oob"],
)
def test_chunk_grid_getitem_oob(
array_shape: tuple[int, ...], chunk_sizes: Any, coords: tuple[int, ...]
) -> None:
"""Out-of-bounds chunk coordinates return None"""
g = ChunkGrid.from_sizes(array_shape, chunk_sizes)
assert g[coords] is None
def test_chunk_grid_getitem_slices() -> None:
"""ChunkSpec.slices reflect the correct start/stop for a rectilinear chunk"""
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]])
spec = g[(1, 2)]
assert spec is not None
assert spec.slices == (slice(10, 30, 1), slice(50, 75, 1))
# -- all_chunk_coords tests --
@pytest.mark.parametrize(
("array_shape", "chunk_sizes", "origin", "selection_shape", "expected_coords"),
[
# rectilinear grid
(
(60, 100),
[[10, 20, 30], [50, 50]],
None,
None,
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)],
),
((60, 100), [[10, 20, 30], [50, 50]], (1, 0), None, [(1, 0), (1, 1), (2, 0), (2, 1)]),
((60, 100), [[10, 20, 30], [50, 50]], None, (2, 1), [(0, 0), (1, 0)]),
((60, 100), [[10, 20, 30], [50, 50]], (1, 1), (2, 1), [(1, 1), (2, 1)]),
# regular grid
((30, 40), (10, 20), (2, 1), None, [(2, 1)]),
((30, 40), (10, 20), None, (0, 0), []),
((60, 80), (20, 20), (0, 2), (3, 1), [(0, 2), (1, 2), (2, 2)]),
],
ids=[
"all",
"with-origin",
"with-sel-shape",
"origin+sel",
"last-chunk",
"zero-sel",
"single-dim",
],
)
def test_all_chunk_coords(
array_shape: tuple[int, ...],
chunk_sizes: Any,
origin: tuple[int, ...] | None,
selection_shape: tuple[int, ...] | None,
expected_coords: list[tuple[int, ...]],
) -> None:
"""all_chunk_coords yields the expected coordinates with optional origin and selection_shape"""
g = ChunkGrid.from_sizes(array_shape, chunk_sizes)
kwargs: dict[str, Any] = {}
if origin is not None:
kwargs["origin"] = origin
if selection_shape is not None:
kwargs["selection_shape"] = selection_shape
assert list(g.all_chunk_coords(**kwargs)) == expected_coords
def test_chunk_grid_get_nchunks() -> None:
"""get_nchunks returns the total number of chunks across all dimensions"""
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
assert g.get_nchunks() == 6
def test_chunk_grid_iter() -> None:
"""Iterating a ChunkGrid yields the correct number of ChunkSpec objects"""
g = ChunkGrid.from_sizes((30, 40), (10, 20))
specs = list(g)
assert len(specs) == 6
assert all(isinstance(s, ChunkSpec) for s in specs)
# ---------------------------------------------------------------------------
# RLE tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("compressed", "expected"),
[
([[10, 3]], [10, 10, 10]),
([[10, 2], [20, 1]], [10, 10, 20]),
([[True, 2], [3, 1]], [1, 1, 3]),
],
)
def test_rle_expand(compressed: list[Any], expected: list[int]) -> None:
"""RLE-encoded edges expand correctly"""
assert expand_rle(compressed) == expected
@pytest.mark.parametrize(
("original", "expected"),
[
([10, 10, 10], [[10, 3]]),
([10, 10, 20], [[10, 2], 20]),
([5], [5]),
([10, 20, 30], [10, 20, 30]),
],
)
def test_rle_compress(original: list[int], expected: list[Any]) -> None:
"""compress_rle produces the expected RLE encoding for various input sequences"""
assert compress_rle(original) == expected
def test_rle_roundtrip() -> None:
"""compress_rle followed by expand_rle recovers the original sequence"""
original = [10, 10, 10, 20, 20, 30]
compressed = compress_rle(original)
assert expand_rle(compressed) == original
@pytest.mark.parametrize(
("rle_input", "match"),
[
([0], "Chunk edge length must be >= 1"),
([-5], "Chunk edge length must be >= 1"),
([[0, 3]], "Chunk edge length must be >= 1"),
([[-10, 2]], "Chunk edge length must be >= 1"),
([[5, 0]], "RLE repeat count must be >= 1"),
([[5, -1]], "RLE repeat count must be >= 1"),
([[5, 2, 1]], r"RLE entries must be an integer or \[size, count\], got \[5, 2, 1\]"),
],
ids=[
"zero-edge",
"negative-edge",
"zero-rle-size",
"negative-rle-size",
"zero-rle-count",
"negative-rle-count",
"rle-entry-of-three",
],
)
def test_rle_expand_rejects_invalid(rle_input: list[Any], match: str) -> None:
"""expand_rle raises ValueError for zero/negative edge lengths or repeat counts"""
with pytest.raises(ValueError, match=match):
expand_rle(rle_input)
@pytest.mark.parametrize(
("rle_input", "match"),
[
([10.5], "Chunk edge length must be an int, got 10.5"),
([10.0], "Chunk edge length must be an int, got 10.0"),
([[10.0, 3]], "Chunk edge length must be an int, got 10.0"),
(["10"], "Chunk edge length must be an int, got '10'"),
([[10, 3.5]], "RLE repeat count must be an int, got 3.5"),
([[10, 3.0]], "RLE repeat count must be an int, got 3.0"),
([np.int64(10)], "Chunk edge length must be an int, got np.int64(10)"),
([[10, np.int64(3)]], "RLE repeat count must be an int, got np.int64(3)"),
],
ids=[
"fractional-edge",
"float-edge",
"float-rle-size",
"string-edge",
"fractional-count",
"float-count",
"numpy-int-edge",
"numpy-int-count",
],
)
def test_rle_expand_rejects_non_int(rle_input: list[Any], match: str) -> None:
"""expand_rle reads `int`s (and `bool`s) only, not floats or NumPy integers."""
with pytest.raises(TypeError, match=re.escape(match)):
expand_rle(rle_input)
@pytest.mark.parametrize(
("rle_input", "match"),
[
([0], "chunk edge length must be >= 1"),
([10.5], "chunk edge length must be an int,"),
([[5, 0]], "RLE repeat count must be >= 1"),
([[5, 2, 1]], r"RLE entries must be an integer or \[size, count\]"),
],
ids=["zero-edge", "fractional-edge", "zero-rle-count", "rle-entry-of-three"],
)
def test_rle_expand_names_dimension(rle_input: list[Any], match: str) -> None:
"""Given the dimension `axis` the edges belong to, every error of expand_rle names it."""
with pytest.raises((TypeError, ValueError), match=f"^Dimension 2: {match}"):
expand_rle(rle_input, axis=2)
# ---------------------------------------------------------------------------
# Serialization tests
# ---------------------------------------------------------------------------
def test_serialization_error_non_regular_chunk_shape() -> None:
"""Accessing chunk_shape on a non-regular grid raises ValueError."""
grid = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [25, 25, 25, 25]])
with pytest.raises(ValueError, match="only available for regular"):
grid.chunk_shape # noqa: B018
def test_serialization_error_zero_extent_rectilinear() -> None:
"""RectilinearChunkGridMetadata rejects empty edge tuples."""
with pytest.raises(ValueError, match="has no chunk edges"):
RectilinearChunkGridMetadata(chunk_shapes=((),))
def test_serialization_unknown_name_parse() -> None:
"""Parsing metadata with an unknown chunk grid name raises ValueError"""
with pytest.raises(ValueError, match="Unknown chunk grid"):
parse_chunk_grid({"name": "hexagonal", "configuration": {}})
def test_from_metadata_unknown_chunk_grid_type() -> None:
"""ChunkGrid.from_metadata raises TypeError for unrecognised chunk grid metadata."""
from unittest.mock import MagicMock
from zarr.core.metadata.v3 import ArrayV3Metadata
mock_meta = MagicMock(spec=ArrayV3Metadata)
mock_meta.chunk_grid = MagicMock() # not Regular or Rectilinear
with pytest.raises(TypeError, match="Unknown chunk grid metadata type"):
ChunkGrid.from_metadata(mock_meta)
def test_from_sizes_rejects_empty_edge_list() -> None:
"""ChunkGrid.from_sizes raises ValueError when a dimension has an empty edge list."""
with pytest.raises(ValueError, match="edges must not be empty"):
ChunkGrid.from_sizes((10,), ([],))
# ---------------------------------------------------------------------------
# Spec compliance tests
# ---------------------------------------------------------------------------
def test_spec_kind_inline_required_on_deserialize() -> None:
"""Deserialization requires kind: 'inline'."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"chunk_shapes": [[10, 20], [15, 15]]},
}
with pytest.raises(ValueError, match="requires a 'kind' field"):
parse_chunk_grid(data)
def test_spec_kind_unknown_rejected() -> None:
"""Unsupported rectilinear chunk grid kind raises ValueError on parse"""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "reference", "chunk_shapes": [[10, 20], [15, 15]]},
}
with pytest.raises(ValueError, match="Unsupported rectilinear chunk grid kind"):
parse_chunk_grid(data)
def test_spec_integer_shorthand_per_dimension() -> None:
"""A bare integer in chunk_shapes means repeat until >= extent."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [4, [1, 2, 3]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((6, 6), meta.chunk_shapes)
assert _edges(g, 0) == (4, 4)
assert _edges(g, 1) == (1, 2, 3)
def test_spec_mixed_rle_and_bare_integers() -> None:
"""An array can mix bare integers and [value, count] RLE pairs."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[[1, 3], 3]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((6,), meta.chunk_shapes)
assert _edges(g, 0) == (1, 1, 1, 3)
def test_spec_overflow_chunks_allowed() -> None:
"""Edge sum >= extent is valid (overflow chunks permitted)."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[4, 4, 4]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((6,), meta.chunk_shapes)
assert _edges(g, 0) == (4, 4, 4)
def test_spec_example() -> None:
"""The full example from the spec README."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {
"kind": "inline",
"chunk_shapes": [
4,
[1, 2, 3],
[[4, 2]],
[[1, 3], 3],
[4, 4, 4],
],
},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((6, 6, 6, 6, 6), meta.chunk_shapes)
assert _edges(g, 0) == (4, 4)
assert _edges(g, 1) == (1, 2, 3)
assert _edges(g, 2) == (4, 4)
assert _edges(g, 3) == (1, 1, 1, 3)
assert _edges(g, 4) == (4, 4, 4)
# ---------------------------------------------------------------------------
# parse_chunk_grid validation tests
# ---------------------------------------------------------------------------
def test_parse_chunk_grid_varying_extent_mismatch_raises() -> None:
"""Reconstructing a ChunkGrid with mismatched extents raises ValueError"""
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
with pytest.raises(ValueError, match="extent"):
ChunkGrid(
dimensions=tuple(
dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 100), strict=True)
)
)
def test_parse_chunk_grid_varying_extent_match_ok() -> None:
"""Reconstructing a ChunkGrid with matching extents succeeds"""
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
g2 = ChunkGrid(
dimensions=tuple(
dim.with_extent(ext) for dim, ext in zip(g._dimensions, (60, 100), strict=True)
)
)
assert g2._dimensions[0].extent == 60
@pytest.mark.parametrize(
("chunk_shapes", "array_shape", "match"),
[
([[10, 20, 30], [25, 25]], (100, 50), "extent 100 exceeds sum of edges 60"),
([[50, 50], [10, 20]], (100, 50), "extent 50 exceeds sum of edges 30"),
],
ids=["first-dim-mismatch", "second-dim-mismatch"],
)
def test_parse_chunk_grid_rectilinear_extent_mismatch_raises(
chunk_shapes: list[list[int]], array_shape: tuple[int, ...], match: str
) -> None:
"""Rectilinear grid raises ValueError when array extent exceeds sum of edges"""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": chunk_shapes},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
with pytest.raises(ValueError, match=match):
ChunkGrid.from_sizes(array_shape, meta.chunk_shapes)
def test_parse_chunk_grid_rectilinear_extent_match_passes() -> None:
"""Rectilinear grid with matching extents parses and builds successfully"""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[10, 20, 30], [25, 25]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((60, 50), meta.chunk_shapes)
assert g.grid_shape == (3, 2)
def test_parse_chunk_grid_rectilinear_ndim_mismatch_raises() -> None:
"""Mismatched ndim between array shape and chunk_sizes raises ValueError"""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[10, 20], [25, 25]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
with pytest.raises(ValueError, match="3 dimensions but chunk_sizes has 2"):
ChunkGrid.from_sizes((30, 50, 100), meta.chunk_shapes)
def test_parse_chunk_grid_rectilinear_rle_extent_validated() -> None:
"""RLE-encoded edges are expanded before validation."""
data: dict[str, Any] = {
"name": "rectilinear",
"configuration": {"kind": "inline", "chunk_shapes": [[[10, 5]], [[25, 2]]]},
}
meta = parse_chunk_grid(data)
assert isinstance(meta, RectilinearChunkGridMetadata)
g = ChunkGrid.from_sizes((50, 50), meta.chunk_shapes)
assert g.grid_shape == (5, 2)
with pytest.raises(ValueError, match="extent 100 exceeds sum of edges 50"):
ChunkGrid.from_sizes((100, 50), meta.chunk_shapes)
def test_parse_chunk_grid_varying_dimension_extent_mismatch_on_chunkgrid_input() -> None:
"""ChunkGrid constructor rejects VaryingDimension with extent exceeding sum of edges"""
g = ChunkGrid.from_sizes((60, 50), [[10, 20, 30], [25, 25]])
with pytest.raises(ValueError, match="less than"):
ChunkGrid(
dimensions=tuple(
dim.with_extent(ext) for dim, ext in zip(g._dimensions, (100, 50), strict=True)
)
)
# ---------------------------------------------------------------------------
# Rectilinear indexing tests
# ---------------------------------------------------------------------------
def test_basic_indexer_rectilinear() -> None:
"""BasicIndexer produces correct projections for a full-slice rectilinear selection"""
from zarr.core.indexing import BasicIndexer
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
indexer = BasicIndexer(
selection=(slice(None), slice(None)),
shape=(60, 100),
chunk_grid=g,
)
projections = list(indexer)
assert len(projections) == 6
p0 = projections[0]
assert p0.chunk_coords == (0, 0)
assert p0.chunk_selection == (slice(0, 10, 1), slice(0, 50, 1))
p1 = projections[2]
assert p1.chunk_coords == (1, 0)
assert p1.chunk_selection == (slice(0, 20, 1), slice(0, 50, 1))
def test_basic_indexer_int_selection() -> None:
"""BasicIndexer with integer selection maps to the correct chunk and local offset"""
from zarr.core.indexing import BasicIndexer
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
indexer = BasicIndexer(
selection=(15, slice(None)),
shape=(60, 100),
chunk_grid=g,
)
projections = list(indexer)
assert len(projections) == 2
assert projections[0].chunk_coords == (1, 0)
assert projections[0].chunk_selection == (5, slice(0, 50, 1))
def test_basic_indexer_slice_subset() -> None:
"""BasicIndexer with partial slices spans the expected chunk dimensions"""
from zarr.core.indexing import BasicIndexer
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
indexer = BasicIndexer(
selection=(slice(5, 35), slice(0, 50)),
shape=(60, 100),
chunk_grid=g,
)
projections = list(indexer)
chunk_coords_dim0 = sorted({p.chunk_coords[0] for p in projections})
assert chunk_coords_dim0 == [0, 1, 2]
def test_orthogonal_indexer_rectilinear() -> None:
"""OrthogonalIndexer produces the expected number of projections for a rectilinear grid"""
from zarr.core.indexing import OrthogonalIndexer
g = ChunkGrid.from_sizes((60, 100), [[10, 20, 30], [50, 50]])
indexer = OrthogonalIndexer(
selection=(slice(None), slice(None)),
shape=(60, 100),
chunk_grid=g,
)
projections = list(indexer)
assert len(projections) == 6
def test_oob_block_raises_bounds_check_error() -> None:
"""Out-of-bounds block index should raise BoundsCheckError, not IndexError."""
store = MemoryStore()
a = zarr.create_array(store, shape=(30,), chunks=[[10, 20]], dtype="int32")
with pytest.raises(BoundsCheckError):
a.get_block_selection((2,))
# ---------------------------------------------------------------------------
# End-to-end tests
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("shape", "chunks", "expected_regular"),
[
((100, 200), (10, 20), True),
((60, 100), [[10, 20, 30], [50, 50]], False),
],
ids=["regular", "rectilinear"],
)
def test_e2e_create_array(
tmp_path: Path, shape: tuple[int, ...], chunks: Any, expected_regular: bool
) -> None:
"""End-to-end array creation sets correct regularity and ndim on chunk_grid"""
arr = zarr.create_array(
store=tmp_path / "arr.zarr",
shape=shape,
chunks=chunks,
dtype="float32",
)
assert ChunkGrid.from_metadata(arr.metadata).is_regular == expected_regular
assert ChunkGrid.from_metadata(arr.metadata).ndim == len(shape)
@pytest.mark.parametrize(
("shape", "chunks", "grid_type_name", "grid_name"),
[
((100, 200), (10, 20), "RegularChunkGridMetadata", "regular"),
((60, 100), [[10, 20, 30], [50, 50]], "RectilinearChunkGridMetadata", "rectilinear"),
],
ids=["regular", "rectilinear"],
)
def test_e2e_chunk_grid_serializes(
tmp_path: Path, shape: tuple[int, ...], chunks: Any, grid_type_name: str, grid_name: str
) -> None:
"""Array metadata serializes chunk_grid with the correct type and name"""
from zarr.core.metadata.v3 import (
ArrayV3Metadata,
RectilinearChunkGridMetadata,
RegularChunkGridMetadata,
)
grid_type = (
RegularChunkGridMetadata
if grid_type_name == "RegularChunkGridMetadata"
else RectilinearChunkGridMetadata
)
arr = zarr.create_array(
store=tmp_path / "arr.zarr",
shape=shape,
chunks=chunks,
dtype="float32",
)
assert isinstance(arr.metadata, ArrayV3Metadata)
assert isinstance(arr.metadata.chunk_grid, grid_type)
d = arr.metadata.to_dict()
chunk_grid_dict = d["chunk_grid"]
assert isinstance(chunk_grid_dict, dict)
assert chunk_grid_dict["name"] == grid_name
def test_e2e_chunk_grid_name_roundtrip_preserves_rectilinear(tmp_path: Path) -> None: