forked from zarr-developers/zarr-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindexing.py
More file actions
1431 lines (1143 loc) · 51.6 KB
/
indexing.py
File metadata and controls
1431 lines (1143 loc) · 51.6 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
from __future__ import annotations
import itertools
import math
import numbers
import operator
from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from enum import Enum
from functools import reduce
from types import EllipsisType
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
NamedTuple,
Protocol,
TypeAlias,
TypeGuard,
TypeVar,
cast,
runtime_checkable,
)
import numpy as np
import numpy.typing as npt
from zarr.core.common import ceildiv, product
from zarr.core.metadata import T_ArrayMetadata
if TYPE_CHECKING:
from zarr.core.array import Array, AsyncArray
from zarr.core.buffer import NDArrayLikeOrScalar
from zarr.core.chunk_grids import ChunkGrid
from zarr.core.common import ChunkCoords
IntSequence = list[int] | npt.NDArray[np.intp]
ArrayOfIntOrBool = npt.NDArray[np.intp] | npt.NDArray[np.bool_]
BasicSelector = int | slice | EllipsisType
Selector = BasicSelector | ArrayOfIntOrBool
BasicSelection = BasicSelector | tuple[BasicSelector, ...] # also used for BlockIndex
CoordinateSelection = IntSequence | tuple[IntSequence, ...]
MaskSelection = npt.NDArray[np.bool_]
OrthogonalSelection = Selector | tuple[Selector, ...]
Selection = BasicSelection | CoordinateSelection | MaskSelection | OrthogonalSelection
CoordinateSelectionNormalized = tuple[npt.NDArray[np.intp], ...]
SelectionNormalized = tuple[Selector, ...] | ArrayOfIntOrBool
SelectionWithFields = Selection | str | Sequence[str]
SelectorTuple = tuple[Selector, ...] | npt.NDArray[np.intp] | slice
Fields = str | list[str] | tuple[str, ...]
class ArrayIndexError(IndexError):
pass
class BoundsCheckError(IndexError):
_msg = ""
def __init__(self, dim_len: int) -> None:
self._msg = f"index out of bounds for dimension with length {dim_len}"
class NegativeStepError(IndexError):
_msg = "only slices with step >= 1 are supported"
class VindexInvalidSelectionError(IndexError):
_msg = (
"unsupported selection type for vectorized indexing; only "
"coordinate selection (tuple of integer arrays) and mask selection "
"(single Boolean array) are supported; got {!r}"
)
def err_too_many_indices(selection: Any, shape: ChunkCoords) -> None:
raise IndexError(f"too many indices for array; expected {len(shape)}, got {len(selection)}")
def _zarr_array_to_int_or_bool_array(arr: Array) -> npt.NDArray[np.intp] | npt.NDArray[np.bool_]:
if arr.dtype.kind in ("i", "b"):
return np.asarray(arr)
else:
raise IndexError(
f"Invalid array dtype: {arr.dtype}. Arrays used as indices must be of integer or boolean type"
)
@runtime_checkable
class Indexer(Protocol):
shape: ChunkCoords
drop_axes: ChunkCoords
def __iter__(self) -> Iterator[ChunkProjection]: ...
_ArrayIndexingOrder: TypeAlias = Literal["lexicographic"]
def _iter_grid(
grid_shape: Sequence[int],
*,
origin: Sequence[int] | None = None,
selection_shape: Sequence[int] | None = None,
order: _ArrayIndexingOrder = "lexicographic",
) -> Iterator[ChunkCoords]:
"""
Iterate over the elements of grid of integers, with the option to restrict the domain of
iteration to a contiguous subregion of that grid.
Parameters
----------
grid_shape : Sequence[int]
The size of the domain to iterate over.
origin : Sequence[int] | None, default=None
The first coordinate of the domain to return.
selection_shape : Sequence[int] | None, default=None
The shape of the selection.
order : Literal["lexicographic"], default="lexicographic"
The linear indexing order to use.
Returns
-------
itertools.product object
An iterator over tuples of integers
Examples
--------
>>> tuple(iter_grid((1,)))
((0,),)
>>> tuple(iter_grid((2,3)))
((0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2))
>>> tuple(iter_grid((2,3)), origin=(1,1))
((1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3))
>>> tuple(iter_grid((2,3)), origin=(1,1), selection_shape=(2,2))
((1, 1), (1, 2), (1, 3), (2, 1))
"""
if origin is None:
origin_parsed = (0,) * len(grid_shape)
else:
if len(origin) != len(grid_shape):
msg = (
"Shape and origin parameters must have the same length."
f"Got {len(grid_shape)} elements in shape, but {len(origin)} elements in origin."
)
raise ValueError(msg)
origin_parsed = tuple(origin)
if selection_shape is None:
selection_shape_parsed = tuple(
g - o for o, g in zip(origin_parsed, grid_shape, strict=True)
)
else:
selection_shape_parsed = tuple(selection_shape)
if order == "lexicographic":
dimensions: tuple[range, ...] = ()
for idx, (o, gs, ss) in enumerate(
zip(origin_parsed, grid_shape, selection_shape_parsed, strict=True)
):
if o + ss > gs:
raise IndexError(
f"Invalid selection shape ({selection_shape}) for origin ({origin}) and grid shape ({grid_shape}) at axis {idx}."
)
dimensions += (range(o, o + ss),)
yield from itertools.product(*(dimensions))
else:
msg = f"Indexing order {order} is not supported at this time." # type: ignore[unreachable]
raise NotImplementedError(msg)
def is_integer(x: Any) -> TypeGuard[int]:
"""True if x is an integer (both pure Python or NumPy)."""
return isinstance(x, numbers.Integral) and not is_bool(x)
def is_bool(x: Any) -> TypeGuard[bool | np.bool_]:
"""True if x is a boolean (both pure Python or NumPy)."""
return type(x) in [bool, np.bool_]
def is_integer_list(x: Any) -> TypeGuard[list[int]]:
"""True if x is a list of integers."""
return isinstance(x, list) and len(x) > 0 and all(is_integer(i) for i in x)
def is_bool_list(x: Any) -> TypeGuard[list[bool | np.bool_]]:
"""True if x is a list of boolean."""
return isinstance(x, list) and len(x) > 0 and all(is_bool(i) for i in x)
def is_integer_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.intp]]:
t = not np.isscalar(x) and hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype.kind in "ui"
if ndim is not None:
t = t and hasattr(x, "shape") and len(x.shape) == ndim
return t
def is_bool_array(x: Any, ndim: int | None = None) -> TypeGuard[npt.NDArray[np.bool_]]:
t = hasattr(x, "shape") and hasattr(x, "dtype") and x.dtype == bool
if ndim is not None:
t = t and hasattr(x, "shape") and len(x.shape) == ndim
return t
def is_int_or_bool_iterable(x: Any) -> bool:
return is_integer_list(x) or is_integer_array(x) or is_bool_array(x) or is_bool_list(x)
def is_scalar(value: Any, dtype: np.dtype[Any]) -> bool:
if np.isscalar(value):
return True
if hasattr(value, "shape") and value.shape == ():
return True
return isinstance(value, tuple) and dtype.names is not None and len(value) == len(dtype.names)
def is_pure_fancy_indexing(selection: Any, ndim: int) -> bool:
"""Check whether a selection contains only scalars or integer/bool array-likes.
Parameters
----------
selection : tuple, slice, or scalar
A valid selection value for indexing into arrays.
Returns
-------
is_pure : bool
True if the selection is a pure fancy indexing expression (ie not mixed
with boolean or slices).
"""
if is_bool_array(selection):
# is mask selection
return True
if ndim == 1 and (
is_integer_list(selection) or is_integer_array(selection) or is_bool_list(selection)
):
return True
# if not, we go through the normal path below, because a 1-tuple
# of integers is also allowed.
no_slicing = (
isinstance(selection, tuple)
and len(selection) == ndim
and not (any(isinstance(elem, slice) or elem is Ellipsis for elem in selection))
)
return (
no_slicing
and all(
is_integer(elem) or is_integer_list(elem) or is_integer_array(elem)
for elem in selection
)
and any(is_integer_list(elem) or is_integer_array(elem) for elem in selection)
)
def is_pure_orthogonal_indexing(selection: Selection, ndim: int) -> TypeGuard[OrthogonalSelection]:
if not ndim:
return False
selection_normalized = (selection,) if not isinstance(selection, tuple) else selection
# Case 1: Selection contains of iterable of integers or boolean
if len(selection_normalized) == ndim and all(
is_int_or_bool_iterable(s) for s in selection_normalized
):
return True
# Case 2: selection contains either zero or one integer iterables.
# All other selection elements are slices or integers
return (
len(selection_normalized) <= ndim
and sum(is_int_or_bool_iterable(s) for s in selection_normalized) <= 1
and all(
is_int_or_bool_iterable(s) or isinstance(s, int | slice) for s in selection_normalized
)
)
def get_chunk_shape(chunk_grid: ChunkGrid) -> ChunkCoords:
from zarr.core.chunk_grids import RegularChunkGrid
assert isinstance(chunk_grid, RegularChunkGrid), (
"Only regular chunk grid is supported, currently."
)
return chunk_grid.chunk_shape
def normalize_integer_selection(dim_sel: int, dim_len: int) -> int:
# normalize type to int
dim_sel = int(dim_sel)
# handle wraparound
if dim_sel < 0:
dim_sel = dim_len + dim_sel
# handle out of bounds
if dim_sel >= dim_len or dim_sel < 0:
raise BoundsCheckError(dim_len)
return dim_sel
class ChunkDimProjection(NamedTuple):
"""A mapping from chunk to output array for a single dimension.
Attributes
----------
dim_chunk_ix
Index of chunk.
dim_chunk_sel
Selection of items from chunk array.
dim_out_sel
Selection of items in target (output) array.
"""
dim_chunk_ix: int
dim_chunk_sel: Selector
dim_out_sel: Selector | None
is_complete_chunk: bool
@dataclass(frozen=True)
class IntDimIndexer:
dim_sel: int
dim_len: int
dim_chunk_len: int
nitems: int = 1
def __init__(self, dim_sel: int, dim_len: int, dim_chunk_len: int) -> None:
object.__setattr__(self, "dim_sel", normalize_integer_selection(dim_sel, dim_len))
object.__setattr__(self, "dim_len", dim_len)
object.__setattr__(self, "dim_chunk_len", dim_chunk_len)
def __iter__(self) -> Iterator[ChunkDimProjection]:
dim_chunk_ix = self.dim_sel // self.dim_chunk_len
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel - dim_offset
dim_out_sel = None
is_complete_chunk = self.dim_chunk_len == 1
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk)
@dataclass(frozen=True)
class SliceDimIndexer:
dim_len: int
dim_chunk_len: int
nitems: int
nchunks: int
start: int
stop: int
step: int
def __init__(self, dim_sel: slice, dim_len: int, dim_chunk_len: int) -> None:
# normalize
start, stop, step = dim_sel.indices(dim_len)
if step < 1:
raise NegativeStepError
object.__setattr__(self, "start", start)
object.__setattr__(self, "stop", stop)
object.__setattr__(self, "step", step)
object.__setattr__(self, "dim_len", dim_len)
object.__setattr__(self, "dim_chunk_len", dim_chunk_len)
object.__setattr__(self, "nitems", max(0, ceildiv((stop - start), step)))
object.__setattr__(self, "nchunks", ceildiv(dim_len, dim_chunk_len))
def __iter__(self) -> Iterator[ChunkDimProjection]:
# figure out the range of chunks we need to visit
dim_chunk_ix_from = 0 if self.start == 0 else self.start // self.dim_chunk_len
dim_chunk_ix_to = ceildiv(self.stop, self.dim_chunk_len)
# iterate over chunks in range
for dim_chunk_ix in range(dim_chunk_ix_from, dim_chunk_ix_to):
# compute offsets for chunk within overall array
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_limit = min(self.dim_len, (dim_chunk_ix + 1) * self.dim_chunk_len)
# determine chunk length, accounting for trailing chunk
dim_chunk_len = dim_limit - dim_offset
if self.start < dim_offset:
# selection starts before current chunk
dim_chunk_sel_start = 0
remainder = (dim_offset - self.start) % self.step
if remainder:
dim_chunk_sel_start += self.step - remainder
# compute number of previous items, provides offset into output array
dim_out_offset = ceildiv((dim_offset - self.start), self.step)
else:
# selection starts within current chunk
dim_chunk_sel_start = self.start - dim_offset
dim_out_offset = 0
if self.stop > dim_limit:
# selection ends after current chunk
dim_chunk_sel_stop = dim_chunk_len
else:
# selection ends within current chunk
dim_chunk_sel_stop = self.stop - dim_offset
dim_chunk_sel = slice(dim_chunk_sel_start, dim_chunk_sel_stop, self.step)
dim_chunk_nitems = ceildiv((dim_chunk_sel_stop - dim_chunk_sel_start), self.step)
# If there are no elements on the selection within this chunk, then skip
if dim_chunk_nitems == 0:
continue
dim_out_sel = slice(dim_out_offset, dim_out_offset + dim_chunk_nitems)
is_complete_chunk = (
dim_chunk_sel_start == 0 and (self.stop >= dim_limit) and self.step in [1, None]
)
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk)
def check_selection_length(selection: SelectionNormalized, shape: ChunkCoords) -> None:
if len(selection) > len(shape):
err_too_many_indices(selection, shape)
def replace_ellipsis(selection: Any, shape: ChunkCoords) -> SelectionNormalized:
selection = ensure_tuple(selection)
# count number of ellipsis present
n_ellipsis = sum(1 for i in selection if i is Ellipsis)
if n_ellipsis > 1:
# more than 1 is an error
raise IndexError("an index can only have a single ellipsis ('...')")
elif n_ellipsis == 1:
# locate the ellipsis, count how many items to left and right
n_items_l = selection.index(Ellipsis) # items to left of ellipsis
n_items_r = len(selection) - (n_items_l + 1) # items to right of ellipsis
n_items = len(selection) - 1 # all non-ellipsis items
if n_items >= len(shape):
# ellipsis does nothing, just remove it
selection = tuple(i for i in selection if i != Ellipsis)
else:
# replace ellipsis with as many slices are needed for number of dims
new_item = selection[:n_items_l] + ((slice(None),) * (len(shape) - n_items))
if n_items_r:
new_item += selection[-n_items_r:]
selection = new_item
# fill out selection if not completely specified
if len(selection) < len(shape):
selection += (slice(None),) * (len(shape) - len(selection))
# check selection not too long
check_selection_length(selection, shape)
return cast("SelectionNormalized", selection)
def replace_lists(selection: SelectionNormalized) -> SelectionNormalized:
return tuple(
np.asarray(dim_sel) if isinstance(dim_sel, list) else dim_sel for dim_sel in selection
)
T = TypeVar("T")
def ensure_tuple(v: Any) -> SelectionNormalized:
if not isinstance(v, tuple):
v = (v,)
return cast("SelectionNormalized", v)
class ChunkProjection(NamedTuple):
"""A mapping of items from chunk to output array. Can be used to extract items from the
chunk array for loading into an output array. Can also be used to extract items from a
value array for setting/updating in a chunk array.
Attributes
----------
chunk_coords
Indices of chunk.
chunk_selection
Selection of items from chunk array.
out_selection
Selection of items in target (output) array.
is_complete_chunk:
True if a complete chunk is indexed
"""
chunk_coords: ChunkCoords
chunk_selection: tuple[Selector, ...] | npt.NDArray[np.intp]
out_selection: tuple[Selector, ...] | npt.NDArray[np.intp] | slice
is_complete_chunk: bool
def is_slice(s: Any) -> TypeGuard[slice]:
return isinstance(s, slice)
def is_contiguous_slice(s: Any) -> TypeGuard[slice]:
return is_slice(s) and (s.step is None or s.step == 1)
def is_positive_slice(s: Any) -> TypeGuard[slice]:
return is_slice(s) and (s.step is None or s.step >= 1)
def is_contiguous_selection(selection: Any) -> TypeGuard[slice]:
selection = ensure_tuple(selection)
return all((is_integer_array(s) or is_contiguous_slice(s) or s == Ellipsis) for s in selection)
def is_basic_selection(selection: Any) -> TypeGuard[BasicSelection]:
selection = ensure_tuple(selection)
return all(is_integer(s) or is_positive_slice(s) for s in selection)
@dataclass(frozen=True)
class BasicIndexer(Indexer):
dim_indexers: list[IntDimIndexer | SliceDimIndexer]
shape: ChunkCoords
drop_axes: ChunkCoords
def __init__(
self,
selection: BasicSelection,
shape: ChunkCoords,
chunk_grid: ChunkGrid,
) -> None:
chunk_shape = get_chunk_shape(chunk_grid)
# handle ellipsis
selection_normalized = replace_ellipsis(selection, shape)
# setup per-dimension indexers
dim_indexers: list[IntDimIndexer | SliceDimIndexer] = []
for dim_sel, dim_len, dim_chunk_len in zip(
selection_normalized, shape, chunk_shape, strict=True
):
dim_indexer: IntDimIndexer | SliceDimIndexer
if is_integer(dim_sel):
dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len)
elif is_slice(dim_sel):
dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len)
else:
raise IndexError(
"unsupported selection item for basic indexing; "
f"expected integer or slice, got {type(dim_sel)!r}"
)
dim_indexers.append(dim_indexer)
object.__setattr__(self, "dim_indexers", dim_indexers)
object.__setattr__(
self,
"shape",
tuple(s.nitems for s in self.dim_indexers if not isinstance(s, IntDimIndexer)),
)
object.__setattr__(self, "drop_axes", ())
def __iter__(self) -> Iterator[ChunkProjection]:
for dim_projections in itertools.product(*self.dim_indexers):
chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections)
chunk_selection = tuple(p.dim_chunk_sel for p in dim_projections)
out_selection = tuple(
p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None
)
is_complete_chunk = all(p.is_complete_chunk for p in dim_projections)
yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk)
@dataclass(frozen=True)
class BoolArrayDimIndexer:
dim_sel: npt.NDArray[np.bool_]
dim_len: int
dim_chunk_len: int
nchunks: int
chunk_nitems: npt.NDArray[Any]
chunk_nitems_cumsum: npt.NDArray[Any]
nitems: int
dim_chunk_ixs: npt.NDArray[np.intp]
def __init__(self, dim_sel: npt.NDArray[np.bool_], dim_len: int, dim_chunk_len: int) -> None:
# check number of dimensions
if not is_bool_array(dim_sel, 1):
raise IndexError("Boolean arrays in an orthogonal selection must be 1-dimensional only")
# check shape
if dim_sel.shape[0] != dim_len:
raise IndexError(
f"Boolean array has the wrong length for dimension; expected {dim_len}, got {dim_sel.shape[0]}"
)
# precompute number of selected items for each chunk
nchunks = ceildiv(dim_len, dim_chunk_len)
chunk_nitems = np.zeros(nchunks, dtype="i8")
for dim_chunk_ix in range(nchunks):
dim_offset = dim_chunk_ix * dim_chunk_len
chunk_nitems[dim_chunk_ix] = np.count_nonzero(
dim_sel[dim_offset : dim_offset + dim_chunk_len]
)
chunk_nitems_cumsum = np.cumsum(chunk_nitems)
nitems = chunk_nitems_cumsum[-1]
dim_chunk_ixs = np.nonzero(chunk_nitems)[0]
# store attributes
object.__setattr__(self, "dim_sel", dim_sel)
object.__setattr__(self, "dim_len", dim_len)
object.__setattr__(self, "dim_chunk_len", dim_chunk_len)
object.__setattr__(self, "nchunks", nchunks)
object.__setattr__(self, "chunk_nitems", chunk_nitems)
object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum)
object.__setattr__(self, "nitems", nitems)
object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs)
def __iter__(self) -> Iterator[ChunkDimProjection]:
# iterate over chunks with at least one item
for dim_chunk_ix in self.dim_chunk_ixs:
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[dim_offset : dim_offset + self.dim_chunk_len]
# pad out if final chunk
if dim_chunk_sel.shape[0] < self.dim_chunk_len:
tmp = np.zeros(self.dim_chunk_len, dtype=bool)
tmp[: dim_chunk_sel.shape[0]] = dim_chunk_sel
dim_chunk_sel = tmp
# find region in output
if dim_chunk_ix == 0:
start = 0
else:
start = self.chunk_nitems_cumsum[dim_chunk_ix - 1]
stop = self.chunk_nitems_cumsum[dim_chunk_ix]
dim_out_sel = slice(start, stop)
is_complete_chunk = False # TODO
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk)
class Order(Enum):
"""
Enum for indexing order.
"""
UNKNOWN = 0
INCREASING = 1
DECREASING = 2
UNORDERED = 3
@staticmethod
def check(a: npt.NDArray[Any]) -> Order:
diff = np.diff(a)
diff_positive = diff >= 0
n_diff_positive = np.count_nonzero(diff_positive)
all_increasing = n_diff_positive == len(diff_positive)
any_increasing = n_diff_positive > 0
if all_increasing:
order = Order.INCREASING
elif any_increasing:
order = Order.UNORDERED
else:
order = Order.DECREASING
return order
def wraparound_indices(x: npt.NDArray[Any], dim_len: int) -> None:
loc_neg = x < 0
if np.any(loc_neg):
x[loc_neg] += dim_len
def boundscheck_indices(x: npt.NDArray[Any], dim_len: int) -> None:
if np.any(x < 0) or np.any(x >= dim_len):
raise BoundsCheckError(dim_len)
@dataclass(frozen=True)
class IntArrayDimIndexer:
"""Integer array selection against a single dimension."""
dim_len: int
dim_chunk_len: int
nchunks: int
nitems: int
order: Order
dim_sel: npt.NDArray[np.intp]
dim_out_sel: npt.NDArray[np.intp]
chunk_nitems: int
dim_chunk_ixs: npt.NDArray[np.intp]
chunk_nitems_cumsum: npt.NDArray[np.intp]
def __init__(
self,
dim_sel: npt.NDArray[np.intp],
dim_len: int,
dim_chunk_len: int,
wraparound: bool = True,
boundscheck: bool = True,
order: Order = Order.UNKNOWN,
) -> None:
# ensure 1d array
dim_sel = np.asanyarray(dim_sel)
if not is_integer_array(dim_sel, 1):
raise IndexError("integer arrays in an orthogonal selection must be 1-dimensional only")
nitems = len(dim_sel)
nchunks = ceildiv(dim_len, dim_chunk_len)
# handle wraparound
if wraparound:
wraparound_indices(dim_sel, dim_len)
# handle out of bounds
if boundscheck:
boundscheck_indices(dim_sel, dim_len)
# determine which chunk is needed for each selection item
# note: for dense integer selections, the division operation here is the
# bottleneck
dim_sel_chunk = dim_sel // dim_chunk_len
# determine order of indices
if order == Order.UNKNOWN:
order = Order.check(dim_sel)
order = Order(order)
if order == Order.INCREASING:
dim_out_sel = None
elif order == Order.DECREASING:
dim_sel = dim_sel[::-1]
# TODO should be possible to do this without creating an arange
dim_out_sel = np.arange(nitems - 1, -1, -1)
else:
# sort indices to group by chunk
dim_out_sel = np.argsort(dim_sel_chunk)
dim_sel = np.take(dim_sel, dim_out_sel)
# precompute number of selected items for each chunk
chunk_nitems = np.bincount(dim_sel_chunk, minlength=nchunks)
# find chunks that we need to visit
dim_chunk_ixs = np.nonzero(chunk_nitems)[0]
# compute offsets into the output array
chunk_nitems_cumsum = np.cumsum(chunk_nitems)
# store attributes
object.__setattr__(self, "dim_len", dim_len)
object.__setattr__(self, "dim_chunk_len", dim_chunk_len)
object.__setattr__(self, "nchunks", nchunks)
object.__setattr__(self, "nitems", nitems)
object.__setattr__(self, "order", order)
object.__setattr__(self, "dim_sel", dim_sel)
object.__setattr__(self, "dim_out_sel", dim_out_sel)
object.__setattr__(self, "chunk_nitems", chunk_nitems)
object.__setattr__(self, "dim_chunk_ixs", dim_chunk_ixs)
object.__setattr__(self, "chunk_nitems_cumsum", chunk_nitems_cumsum)
def __iter__(self) -> Iterator[ChunkDimProjection]:
for dim_chunk_ix in self.dim_chunk_ixs:
dim_out_sel: slice | npt.NDArray[np.intp]
# find region in output
if dim_chunk_ix == 0:
start = 0
else:
start = self.chunk_nitems_cumsum[dim_chunk_ix - 1]
stop = self.chunk_nitems_cumsum[dim_chunk_ix]
if self.order == Order.INCREASING:
dim_out_sel = slice(start, stop)
else:
dim_out_sel = self.dim_out_sel[start:stop]
# find region in chunk
dim_offset = dim_chunk_ix * self.dim_chunk_len
dim_chunk_sel = self.dim_sel[start:stop] - dim_offset
is_complete_chunk = False # TODO
yield ChunkDimProjection(dim_chunk_ix, dim_chunk_sel, dim_out_sel, is_complete_chunk)
def slice_to_range(s: slice, length: int) -> range:
return range(*s.indices(length))
def ix_(selection: Any, shape: ChunkCoords) -> npt.NDArray[np.intp]:
"""Convert an orthogonal selection to a numpy advanced (fancy) selection, like ``numpy.ix_``
but with support for slices and single ints."""
# normalisation
selection = replace_ellipsis(selection, shape)
# replace slice and int as these are not supported by numpy.ix_
selection = [
slice_to_range(dim_sel, dim_len)
if isinstance(dim_sel, slice)
else [dim_sel]
if is_integer(dim_sel)
else dim_sel
for dim_sel, dim_len in zip(selection, shape, strict=True)
]
# now get numpy to convert to a coordinate selection
selection = np.ix_(*selection)
return cast("npt.NDArray[np.intp]", selection)
def oindex(a: npt.NDArray[Any], selection: Selection) -> npt.NDArray[Any]:
"""Implementation of orthogonal indexing with slices and ints."""
selection = replace_ellipsis(selection, a.shape)
drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s))
selection = ix_(selection, a.shape)
result = a[selection]
if drop_axes:
result = result.squeeze(axis=drop_axes)
return result
def oindex_set(a: npt.NDArray[Any], selection: Selection, value: Any) -> None:
selection = replace_ellipsis(selection, a.shape)
drop_axes = tuple(i for i, s in enumerate(selection) if is_integer(s))
selection = ix_(selection, a.shape)
if not np.isscalar(value) and drop_axes:
value = np.asanyarray(value)
value_selection: list[Selector | None] = [slice(None)] * len(a.shape)
for i in drop_axes:
value_selection[i] = np.newaxis
value = value[tuple(value_selection)]
a[selection] = value
@dataclass(frozen=True)
class OrthogonalIndexer(Indexer):
dim_indexers: list[IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer]
shape: ChunkCoords
chunk_shape: ChunkCoords
is_advanced: bool
drop_axes: tuple[int, ...]
def __init__(self, selection: Selection, shape: ChunkCoords, chunk_grid: ChunkGrid) -> None:
chunk_shape = get_chunk_shape(chunk_grid)
# handle ellipsis
selection = replace_ellipsis(selection, shape)
# normalize list to array
selection = replace_lists(selection)
# setup per-dimension indexers
dim_indexers: list[
IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer
] = []
for dim_sel, dim_len, dim_chunk_len in zip(selection, shape, chunk_shape, strict=True):
dim_indexer: IntDimIndexer | SliceDimIndexer | IntArrayDimIndexer | BoolArrayDimIndexer
if is_integer(dim_sel):
dim_indexer = IntDimIndexer(dim_sel, dim_len, dim_chunk_len)
elif isinstance(dim_sel, slice):
dim_indexer = SliceDimIndexer(dim_sel, dim_len, dim_chunk_len)
elif is_integer_array(dim_sel):
dim_indexer = IntArrayDimIndexer(dim_sel, dim_len, dim_chunk_len)
elif is_bool_array(dim_sel):
dim_indexer = BoolArrayDimIndexer(dim_sel, dim_len, dim_chunk_len)
else:
raise IndexError(
"unsupported selection item for orthogonal indexing; "
"expected integer, slice, integer array or Boolean "
f"array, got {type(dim_sel)!r}"
)
dim_indexers.append(dim_indexer)
shape = tuple(s.nitems for s in dim_indexers if not isinstance(s, IntDimIndexer))
is_advanced = not is_basic_selection(selection)
if is_advanced:
drop_axes = tuple(
i
for i, dim_indexer in enumerate(dim_indexers)
if isinstance(dim_indexer, IntDimIndexer)
)
else:
drop_axes = ()
object.__setattr__(self, "dim_indexers", dim_indexers)
object.__setattr__(self, "shape", shape)
object.__setattr__(self, "chunk_shape", chunk_shape)
object.__setattr__(self, "is_advanced", is_advanced)
object.__setattr__(self, "drop_axes", drop_axes)
def __iter__(self) -> Iterator[ChunkProjection]:
for dim_projections in itertools.product(*self.dim_indexers):
chunk_coords = tuple(p.dim_chunk_ix for p in dim_projections)
chunk_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple(
p.dim_chunk_sel for p in dim_projections
)
out_selection: tuple[Selector, ...] | npt.NDArray[Any] = tuple(
p.dim_out_sel for p in dim_projections if p.dim_out_sel is not None
)
# handle advanced indexing arrays orthogonally
if self.is_advanced:
# N.B., numpy doesn't support orthogonal indexing directly as yet,
# so need to work around via np.ix_. Also np.ix_ does not support a
# mixture of arrays and slices or integers, so need to convert slices
# and integers into ranges.
chunk_selection = ix_(chunk_selection, self.chunk_shape)
# special case for non-monotonic indices
if not is_basic_selection(out_selection):
out_selection = ix_(out_selection, self.shape)
is_complete_chunk = all(p.is_complete_chunk for p in dim_projections)
yield ChunkProjection(chunk_coords, chunk_selection, out_selection, is_complete_chunk)
@dataclass(frozen=True)
class OIndex:
array: Array
# TODO: develop Array generic and move zarr.Array[np.intp] | zarr.Array[np.bool_] to ArrayOfIntOrBool
def __getitem__(self, selection: OrthogonalSelection | Array) -> NDArrayLikeOrScalar:
from zarr.core.array import Array
# if input is a Zarr array, we materialize it now.
if isinstance(selection, Array):
selection = _zarr_array_to_int_or_bool_array(selection)
fields, new_selection = pop_fields(selection)
new_selection = ensure_tuple(new_selection)
new_selection = replace_lists(new_selection)
return self.array.get_orthogonal_selection(
cast("OrthogonalSelection", new_selection), fields=fields
)
def __setitem__(self, selection: OrthogonalSelection, value: npt.ArrayLike) -> None:
fields, new_selection = pop_fields(selection)
new_selection = ensure_tuple(new_selection)
new_selection = replace_lists(new_selection)
return self.array.set_orthogonal_selection(
cast("OrthogonalSelection", new_selection), value, fields=fields
)
@dataclass(frozen=True)
class AsyncOIndex(Generic[T_ArrayMetadata]):
array: AsyncArray[T_ArrayMetadata]
async def getitem(self, selection: OrthogonalSelection | Array) -> NDArrayLikeOrScalar:
from zarr.core.array import Array
# if input is a Zarr array, we materialize it now.
if isinstance(selection, Array):
selection = _zarr_array_to_int_or_bool_array(selection)
fields, new_selection = pop_fields(selection)
new_selection = ensure_tuple(new_selection)
new_selection = replace_lists(new_selection)
return await self.array.get_orthogonal_selection(
cast(OrthogonalSelection, new_selection), fields=fields
)
@dataclass(frozen=True)
class BlockIndexer(Indexer):
dim_indexers: list[SliceDimIndexer]
shape: ChunkCoords
drop_axes: ChunkCoords
def __init__(
self, selection: BasicSelection, shape: ChunkCoords, chunk_grid: ChunkGrid
) -> None:
chunk_shape = get_chunk_shape(chunk_grid)
# handle ellipsis
selection_normalized = replace_ellipsis(selection, shape)
# normalize list to array
selection_normalized = replace_lists(selection_normalized)
# setup per-dimension indexers
dim_indexers = []
for dim_sel, dim_len, dim_chunk_size in zip(
selection_normalized, shape, chunk_shape, strict=True
):