-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
indexing.py
1531 lines (1245 loc) · 52.3 KB
/
indexing.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
from __future__ import annotations
import enum
import functools
import operator
from collections import Counter, defaultdict
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import timedelta
from html import escape
from typing import TYPE_CHECKING, Any, Callable, Hashable, Iterable, Mapping
import numpy as np
import pandas as pd
from packaging.version import Version
from . import duck_array_ops, nputils, utils
from .npcompat import DTypeLike
from .options import OPTIONS
from .pycompat import dask_version, integer_types, is_duck_dask_array, sparse_array_type
from .types import T_Xarray
from .utils import either_dict_or_kwargs, get_valid_numpy_dtype
if TYPE_CHECKING:
from .indexes import Index
from .variable import Variable
@dataclass
class IndexSelResult:
"""Index query results.
Attributes
----------
dim_indexers: dict
A dictionary where keys are array dimensions and values are
location-based indexers.
indexes: dict, optional
New indexes to replace in the resulting DataArray or Dataset.
variables : dict, optional
New variables to replace in the resulting DataArray or Dataset.
drop_coords : list, optional
Coordinate(s) to drop in the resulting DataArray or Dataset.
drop_indexes : list, optional
Index(es) to drop in the resulting DataArray or Dataset.
rename_dims : dict, optional
A dictionary in the form ``{old_dim: new_dim}`` for dimension(s) to
rename in the resulting DataArray or Dataset.
"""
dim_indexers: dict[Any, Any]
indexes: dict[Any, Index] = field(default_factory=dict)
variables: dict[Any, Variable] = field(default_factory=dict)
drop_coords: list[Hashable] = field(default_factory=list)
drop_indexes: list[Hashable] = field(default_factory=list)
rename_dims: dict[Any, Hashable] = field(default_factory=dict)
def as_tuple(self):
"""Unlike ``dataclasses.astuple``, return a shallow copy.
See https://stackoverflow.com/a/51802661
"""
return (
self.dim_indexers,
self.indexes,
self.variables,
self.drop_coords,
self.drop_indexes,
self.rename_dims,
)
def merge_sel_results(results: list[IndexSelResult]) -> IndexSelResult:
all_dims_count = Counter([dim for res in results for dim in res.dim_indexers])
duplicate_dims = {k: v for k, v in all_dims_count.items() if v > 1}
if duplicate_dims:
# TODO: this message is not right when combining indexe(s) queries with
# location-based indexing on a dimension with no dimension-coordinate (failback)
fmt_dims = [
f"{dim!r}: {count} indexes involved"
for dim, count in duplicate_dims.items()
]
raise ValueError(
"Xarray does not support label-based selection with more than one index "
"over the following dimension(s):\n"
+ "\n".join(fmt_dims)
+ "\nSuggestion: use a multi-index for each of those dimension(s)."
)
dim_indexers = {}
indexes = {}
variables = {}
drop_coords = []
drop_indexes = []
rename_dims = {}
for res in results:
dim_indexers.update(res.dim_indexers)
indexes.update(res.indexes)
variables.update(res.variables)
drop_coords += res.drop_coords
drop_indexes += res.drop_indexes
rename_dims.update(res.rename_dims)
return IndexSelResult(
dim_indexers, indexes, variables, drop_coords, drop_indexes, rename_dims
)
def group_indexers_by_index(
obj: T_Xarray,
indexers: Mapping[Any, Any],
options: Mapping[str, Any],
) -> list[tuple[Index, dict[Any, Any]]]:
"""Returns a list of unique indexes and their corresponding indexers."""
unique_indexes = {}
grouped_indexers: Mapping[int | None, dict] = defaultdict(dict)
for key, label in indexers.items():
index: Index = obj.xindexes.get(key, None)
if index is not None:
index_id = id(index)
unique_indexes[index_id] = index
grouped_indexers[index_id][key] = label
elif key in obj.coords:
raise KeyError(f"no index found for coordinate {key!r}")
elif key not in obj.dims:
raise KeyError(f"{key!r} is not a valid dimension or coordinate")
elif len(options):
raise ValueError(
f"cannot supply selection options {options!r} for dimension {key!r}"
"that has no associated coordinate or index"
)
else:
# key is a dimension without a "dimension-coordinate"
# failback to location-based selection
# TODO: depreciate this implicit behavior and suggest using isel instead?
unique_indexes[None] = None
grouped_indexers[None][key] = label
return [(unique_indexes[k], grouped_indexers[k]) for k in unique_indexes]
def map_index_queries(
obj: T_Xarray,
indexers: Mapping[Any, Any],
method=None,
tolerance=None,
**indexers_kwargs: Any,
) -> IndexSelResult:
"""Execute index queries from a DataArray / Dataset and label-based indexers
and return the (merged) query results.
"""
from .dataarray import DataArray
# TODO benbovy - flexible indexes: remove when custom index options are available
if method is None and tolerance is None:
options = {}
else:
options = {"method": method, "tolerance": tolerance}
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "map_index_queries")
grouped_indexers = group_indexers_by_index(obj, indexers, options)
results = []
for index, labels in grouped_indexers:
if index is None:
# forward dimension indexers with no index/coordinate
results.append(IndexSelResult(labels))
else:
results.append(index.sel(labels, **options)) # type: ignore[call-arg]
merged = merge_sel_results(results)
# drop dimension coordinates found in dimension indexers
# (also drop multi-index if any)
# (.sel() already ensures alignment)
for k, v in merged.dim_indexers.items():
if isinstance(v, DataArray):
if k in v._indexes:
v = v.reset_index(k)
drop_coords = [name for name in v._coords if name in merged.dim_indexers]
merged.dim_indexers[k] = v.drop_vars(drop_coords)
return merged
def expanded_indexer(key, ndim):
"""Given a key for indexing an ndarray, return an equivalent key which is a
tuple with length equal to the number of dimensions.
The expansion is done by replacing all `Ellipsis` items with the right
number of full slices and then padding the key with full slices so that it
reaches the appropriate dimensionality.
"""
if not isinstance(key, tuple):
# numpy treats non-tuple keys equivalent to tuples of length 1
key = (key,)
new_key = []
# handling Ellipsis right is a little tricky, see:
# https://numpy.org/doc/stable/reference/arrays.indexing.html#advanced-indexing
found_ellipsis = False
for k in key:
if k is Ellipsis:
if not found_ellipsis:
new_key.extend((ndim + 1 - len(key)) * [slice(None)])
found_ellipsis = True
else:
new_key.append(slice(None))
else:
new_key.append(k)
if len(new_key) > ndim:
raise IndexError("too many indices")
new_key.extend((ndim - len(new_key)) * [slice(None)])
return tuple(new_key)
def _expand_slice(slice_, size):
return np.arange(*slice_.indices(size))
def _normalize_slice(sl, size):
"""Ensure that given slice only contains positive start and stop values
(stop can be -1 for full-size slices with negative steps, e.g. [-10::-1])"""
return slice(*sl.indices(size))
def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
old_slice = _normalize_slice(old_slice, size)
size_after_old_slice = len(range(old_slice.start, old_slice.stop, old_slice.step))
if size_after_old_slice == 0:
# nothing left after applying first slice
return slice(0)
applied_slice = _normalize_slice(applied_slice, size_after_old_slice)
start = old_slice.start + applied_slice.start * old_slice.step
if start < 0:
# nothing left after applying second slice
# (can only happen for old_slice.step < 0, e.g. [10::-1], [20:])
return slice(0)
stop = old_slice.start + applied_slice.stop * old_slice.step
if stop < 0:
stop = None
step = old_slice.step * applied_slice.step
return slice(start, stop, step)
def _index_indexer_1d(old_indexer, applied_indexer, size):
assert isinstance(applied_indexer, integer_types + (slice, np.ndarray))
if isinstance(applied_indexer, slice) and applied_indexer == slice(None):
# shortcut for the usual case
return old_indexer
if isinstance(old_indexer, slice):
if isinstance(applied_indexer, slice):
indexer = slice_slice(old_indexer, applied_indexer, size)
else:
indexer = _expand_slice(old_indexer, size)[applied_indexer]
else:
indexer = old_indexer[applied_indexer]
return indexer
class ExplicitIndexer:
"""Base class for explicit indexer objects.
ExplicitIndexer objects wrap a tuple of values given by their ``tuple``
property. These tuples should always have length equal to the number of
dimensions on the indexed array.
Do not instantiate BaseIndexer objects directly: instead, use one of the
sub-classes BasicIndexer, OuterIndexer or VectorizedIndexer.
"""
__slots__ = ("_key",)
def __init__(self, key):
if type(self) is ExplicitIndexer:
raise TypeError("cannot instantiate base ExplicitIndexer objects")
self._key = tuple(key)
@property
def tuple(self):
return self._key
def __repr__(self):
return f"{type(self).__name__}({self.tuple})"
def as_integer_or_none(value):
return None if value is None else operator.index(value)
def as_integer_slice(value):
start = as_integer_or_none(value.start)
stop = as_integer_or_none(value.stop)
step = as_integer_or_none(value.step)
return slice(start, stop, step)
class BasicIndexer(ExplicitIndexer):
"""Tuple for basic indexing.
All elements should be int or slice objects. Indexing follows NumPy's
rules for basic indexing: each axis is independently sliced and axes
indexed with an integer are dropped from the result.
"""
__slots__ = ()
def __init__(self, key):
if not isinstance(key, tuple):
raise TypeError(f"key must be a tuple: {key!r}")
new_key = []
for k in key:
if isinstance(k, integer_types):
k = int(k)
elif isinstance(k, slice):
k = as_integer_slice(k)
else:
raise TypeError(
f"unexpected indexer type for {type(self).__name__}: {k!r}"
)
new_key.append(k)
super().__init__(new_key)
class OuterIndexer(ExplicitIndexer):
"""Tuple for outer/orthogonal indexing.
All elements should be int, slice or 1-dimensional np.ndarray objects with
an integer dtype. Indexing is applied independently along each axis, and
axes indexed with an integer are dropped from the result. This type of
indexing works like MATLAB/Fortran.
"""
__slots__ = ()
def __init__(self, key):
if not isinstance(key, tuple):
raise TypeError(f"key must be a tuple: {key!r}")
new_key = []
for k in key:
if isinstance(k, integer_types):
k = int(k)
elif isinstance(k, slice):
k = as_integer_slice(k)
elif isinstance(k, np.ndarray):
if not np.issubdtype(k.dtype, np.integer):
raise TypeError(
f"invalid indexer array, does not have integer dtype: {k!r}"
)
if k.ndim != 1:
raise TypeError(
f"invalid indexer array for {type(self).__name__}; must have "
f"exactly 1 dimension: {k!r}"
)
k = np.asarray(k, dtype=np.int64)
else:
raise TypeError(
f"unexpected indexer type for {type(self).__name__}: {k!r}"
)
new_key.append(k)
super().__init__(new_key)
class VectorizedIndexer(ExplicitIndexer):
"""Tuple for vectorized indexing.
All elements should be slice or N-dimensional np.ndarray objects with an
integer dtype and the same number of dimensions. Indexing follows proposed
rules for np.ndarray.vindex, which matches NumPy's advanced indexing rules
(including broadcasting) except sliced axes are always moved to the end:
https://github.com/numpy/numpy/pull/6256
"""
__slots__ = ()
def __init__(self, key):
if not isinstance(key, tuple):
raise TypeError(f"key must be a tuple: {key!r}")
new_key = []
ndim = None
for k in key:
if isinstance(k, slice):
k = as_integer_slice(k)
elif isinstance(k, np.ndarray):
if not np.issubdtype(k.dtype, np.integer):
raise TypeError(
f"invalid indexer array, does not have integer dtype: {k!r}"
)
if ndim is None:
ndim = k.ndim
elif ndim != k.ndim:
ndims = [k.ndim for k in key if isinstance(k, np.ndarray)]
raise ValueError(
"invalid indexer key: ndarray arguments "
f"have different numbers of dimensions: {ndims}"
)
k = np.asarray(k, dtype=np.int64)
else:
raise TypeError(
f"unexpected indexer type for {type(self).__name__}: {k!r}"
)
new_key.append(k)
super().__init__(new_key)
class ExplicitlyIndexed:
"""Mixin to mark support for Indexer subclasses in indexing."""
__slots__ = ()
class ExplicitlyIndexedNDArrayMixin(utils.NDArrayMixin, ExplicitlyIndexed):
__slots__ = ()
def __array__(self, dtype=None):
key = BasicIndexer((slice(None),) * self.ndim)
return np.asarray(self[key], dtype=dtype)
class ImplicitToExplicitIndexingAdapter(utils.NDArrayMixin):
"""Wrap an array, converting tuples into the indicated explicit indexer."""
__slots__ = ("array", "indexer_cls")
def __init__(self, array, indexer_cls=BasicIndexer):
self.array = as_indexable(array)
self.indexer_cls = indexer_cls
def __array__(self, dtype=None):
return np.asarray(self.array, dtype=dtype)
def __getitem__(self, key):
key = expanded_indexer(key, self.ndim)
result = self.array[self.indexer_cls(key)]
if isinstance(result, ExplicitlyIndexed):
return type(self)(result, self.indexer_cls)
else:
# Sometimes explicitly indexed arrays return NumPy arrays or
# scalars.
return result
class LazilyIndexedArray(ExplicitlyIndexedNDArrayMixin):
"""Wrap an array to make basic and outer indexing lazy."""
__slots__ = ("array", "key")
def __init__(self, array, key=None):
"""
Parameters
----------
array : array_like
Array like object to index.
key : ExplicitIndexer, optional
Array indexer. If provided, it is assumed to already be in
canonical expanded form.
"""
if isinstance(array, type(self)) and key is None:
# unwrap
key = array.key
array = array.array
if key is None:
key = BasicIndexer((slice(None),) * array.ndim)
self.array = as_indexable(array)
self.key = key
def _updated_key(self, new_key):
iter_new_key = iter(expanded_indexer(new_key.tuple, self.ndim))
full_key = []
for size, k in zip(self.array.shape, self.key.tuple):
if isinstance(k, integer_types):
full_key.append(k)
else:
full_key.append(_index_indexer_1d(k, next(iter_new_key), size))
full_key = tuple(full_key)
if all(isinstance(k, integer_types + (slice,)) for k in full_key):
return BasicIndexer(full_key)
return OuterIndexer(full_key)
@property
def shape(self):
shape = []
for size, k in zip(self.array.shape, self.key.tuple):
if isinstance(k, slice):
shape.append(len(range(*k.indices(size))))
elif isinstance(k, np.ndarray):
shape.append(k.size)
return tuple(shape)
def __array__(self, dtype=None):
array = as_indexable(self.array)
return np.asarray(array[self.key], dtype=None)
def transpose(self, order):
return LazilyVectorizedIndexedArray(self.array, self.key).transpose(order)
def __getitem__(self, indexer):
if isinstance(indexer, VectorizedIndexer):
array = LazilyVectorizedIndexedArray(self.array, self.key)
return array[indexer]
return type(self)(self.array, self._updated_key(indexer))
def __setitem__(self, key, value):
if isinstance(key, VectorizedIndexer):
raise NotImplementedError(
"Lazy item assignment with the vectorized indexer is not yet "
"implemented. Load your data first by .load() or compute()."
)
full_key = self._updated_key(key)
self.array[full_key] = value
def __repr__(self):
return f"{type(self).__name__}(array={self.array!r}, key={self.key!r})"
# keep an alias to the old name for external backends pydata/xarray#5111
LazilyOuterIndexedArray = LazilyIndexedArray
class LazilyVectorizedIndexedArray(ExplicitlyIndexedNDArrayMixin):
"""Wrap an array to make vectorized indexing lazy."""
__slots__ = ("array", "key")
def __init__(self, array, key):
"""
Parameters
----------
array : array_like
Array like object to index.
key : VectorizedIndexer
"""
if isinstance(key, (BasicIndexer, OuterIndexer)):
self.key = _outer_to_vectorized_indexer(key, array.shape)
else:
self.key = _arrayize_vectorized_indexer(key, array.shape)
self.array = as_indexable(array)
@property
def shape(self):
return np.broadcast(*self.key.tuple).shape
def __array__(self, dtype=None):
return np.asarray(self.array[self.key], dtype=None)
def _updated_key(self, new_key):
return _combine_indexers(self.key, self.shape, new_key)
def __getitem__(self, indexer):
# If the indexed array becomes a scalar, return LazilyIndexedArray
if all(isinstance(ind, integer_types) for ind in indexer.tuple):
key = BasicIndexer(tuple(k[indexer.tuple] for k in self.key.tuple))
return LazilyIndexedArray(self.array, key)
return type(self)(self.array, self._updated_key(indexer))
def transpose(self, order):
key = VectorizedIndexer(tuple(k.transpose(order) for k in self.key.tuple))
return type(self)(self.array, key)
def __setitem__(self, key, value):
raise NotImplementedError(
"Lazy item assignment with the vectorized indexer is not yet "
"implemented. Load your data first by .load() or compute()."
)
def __repr__(self):
return f"{type(self).__name__}(array={self.array!r}, key={self.key!r})"
def _wrap_numpy_scalars(array):
"""Wrap NumPy scalars in 0d arrays."""
if np.isscalar(array):
return np.array(array)
else:
return array
class CopyOnWriteArray(ExplicitlyIndexedNDArrayMixin):
__slots__ = ("array", "_copied")
def __init__(self, array):
self.array = as_indexable(array)
self._copied = False
def _ensure_copied(self):
if not self._copied:
self.array = as_indexable(np.array(self.array))
self._copied = True
def __array__(self, dtype=None):
return np.asarray(self.array, dtype=dtype)
def __getitem__(self, key):
return type(self)(_wrap_numpy_scalars(self.array[key]))
def transpose(self, order):
return self.array.transpose(order)
def __setitem__(self, key, value):
self._ensure_copied()
self.array[key] = value
def __deepcopy__(self, memo):
# CopyOnWriteArray is used to wrap backend array objects, which might
# point to files on disk, so we can't rely on the default deepcopy
# implementation.
return type(self)(self.array)
class MemoryCachedArray(ExplicitlyIndexedNDArrayMixin):
__slots__ = ("array",)
def __init__(self, array):
self.array = _wrap_numpy_scalars(as_indexable(array))
def _ensure_cached(self):
if not isinstance(self.array, NumpyIndexingAdapter):
self.array = NumpyIndexingAdapter(np.asarray(self.array))
def __array__(self, dtype=None):
self._ensure_cached()
return np.asarray(self.array, dtype=dtype)
def __getitem__(self, key):
return type(self)(_wrap_numpy_scalars(self.array[key]))
def transpose(self, order):
return self.array.transpose(order)
def __setitem__(self, key, value):
self.array[key] = value
def as_indexable(array):
"""
This function always returns a ExplicitlyIndexed subclass,
so that the vectorized indexing is always possible with the returned
object.
"""
if isinstance(array, ExplicitlyIndexed):
return array
if isinstance(array, np.ndarray):
return NumpyIndexingAdapter(array)
if isinstance(array, pd.Index):
return PandasIndexingAdapter(array)
if is_duck_dask_array(array):
return DaskIndexingAdapter(array)
if hasattr(array, "__array_function__"):
return NdArrayLikeIndexingAdapter(array)
raise TypeError(f"Invalid array type: {type(array)}")
def _outer_to_vectorized_indexer(key, shape):
"""Convert an OuterIndexer into an vectorized indexer.
Parameters
----------
key : Outer/Basic Indexer
An indexer to convert.
shape : tuple
Shape of the array subject to the indexing.
Returns
-------
VectorizedIndexer
Tuple suitable for use to index a NumPy array with vectorized indexing.
Each element is an array: broadcasting them together gives the shape
of the result.
"""
key = key.tuple
n_dim = len([k for k in key if not isinstance(k, integer_types)])
i_dim = 0
new_key = []
for k, size in zip(key, shape):
if isinstance(k, integer_types):
new_key.append(np.array(k).reshape((1,) * n_dim))
else: # np.ndarray or slice
if isinstance(k, slice):
k = np.arange(*k.indices(size))
assert k.dtype.kind in {"i", "u"}
shape = [(1,) * i_dim + (k.size,) + (1,) * (n_dim - i_dim - 1)]
new_key.append(k.reshape(*shape))
i_dim += 1
return VectorizedIndexer(tuple(new_key))
def _outer_to_numpy_indexer(key, shape):
"""Convert an OuterIndexer into an indexer for NumPy.
Parameters
----------
key : Basic/OuterIndexer
An indexer to convert.
shape : tuple
Shape of the array subject to the indexing.
Returns
-------
tuple
Tuple suitable for use to index a NumPy array.
"""
if len([k for k in key.tuple if not isinstance(k, slice)]) <= 1:
# If there is only one vector and all others are slice,
# it can be safely used in mixed basic/advanced indexing.
# Boolean index should already be converted to integer array.
return key.tuple
else:
return _outer_to_vectorized_indexer(key, shape).tuple
def _combine_indexers(old_key, shape, new_key):
"""Combine two indexers.
Parameters
----------
old_key : ExplicitIndexer
The first indexer for the original array
shape : tuple of ints
Shape of the original array to be indexed by old_key
new_key
The second indexer for indexing original[old_key]
"""
if not isinstance(old_key, VectorizedIndexer):
old_key = _outer_to_vectorized_indexer(old_key, shape)
if len(old_key.tuple) == 0:
return new_key
new_shape = np.broadcast(*old_key.tuple).shape
if isinstance(new_key, VectorizedIndexer):
new_key = _arrayize_vectorized_indexer(new_key, new_shape)
else:
new_key = _outer_to_vectorized_indexer(new_key, new_shape)
return VectorizedIndexer(
tuple(o[new_key.tuple] for o in np.broadcast_arrays(*old_key.tuple))
)
@enum.unique
class IndexingSupport(enum.Enum):
# for backends that support only basic indexer
BASIC = 0
# for backends that support basic / outer indexer
OUTER = 1
# for backends that support outer indexer including at most 1 vector.
OUTER_1VECTOR = 2
# for backends that support full vectorized indexer.
VECTORIZED = 3
def explicit_indexing_adapter(
key: ExplicitIndexer,
shape: tuple[int, ...],
indexing_support: IndexingSupport,
raw_indexing_method: Callable,
) -> Any:
"""Support explicit indexing by delegating to a raw indexing method.
Outer and/or vectorized indexers are supported by indexing a second time
with a NumPy array.
Parameters
----------
key : ExplicitIndexer
Explicit indexing object.
shape : Tuple[int, ...]
Shape of the indexed array.
indexing_support : IndexingSupport enum
Form of indexing supported by raw_indexing_method.
raw_indexing_method : callable
Function (like ndarray.__getitem__) that when called with indexing key
in the form of a tuple returns an indexed array.
Returns
-------
Indexing result, in the form of a duck numpy-array.
"""
raw_key, numpy_indices = decompose_indexer(key, shape, indexing_support)
result = raw_indexing_method(raw_key.tuple)
if numpy_indices.tuple:
# index the loaded np.ndarray
result = NumpyIndexingAdapter(np.asarray(result))[numpy_indices]
return result
def decompose_indexer(
indexer: ExplicitIndexer, shape: tuple[int, ...], indexing_support: IndexingSupport
) -> tuple[ExplicitIndexer, ExplicitIndexer]:
if isinstance(indexer, VectorizedIndexer):
return _decompose_vectorized_indexer(indexer, shape, indexing_support)
if isinstance(indexer, (BasicIndexer, OuterIndexer)):
return _decompose_outer_indexer(indexer, shape, indexing_support)
raise TypeError(f"unexpected key type: {indexer}")
def _decompose_slice(key, size):
"""convert a slice to successive two slices. The first slice always has
a positive step.
"""
start, stop, step = key.indices(size)
if step > 0:
# If key already has a positive step, use it as is in the backend
return key, slice(None)
else:
# determine stop precisely for step > 1 case
# e.g. [98:2:-2] -> [98:3:-2]
stop = start + int((stop - start - 1) / step) * step + 1
start, stop = stop + 1, start + 1
return slice(start, stop, -step), slice(None, None, -1)
def _decompose_vectorized_indexer(
indexer: VectorizedIndexer,
shape: tuple[int, ...],
indexing_support: IndexingSupport,
) -> tuple[ExplicitIndexer, ExplicitIndexer]:
"""
Decompose vectorized indexer to the successive two indexers, where the
first indexer will be used to index backend arrays, while the second one
is used to index loaded on-memory np.ndarray.
Parameters
----------
indexer : VectorizedIndexer
indexing_support : one of IndexerSupport entries
Returns
-------
backend_indexer: OuterIndexer or BasicIndexer
np_indexers: an ExplicitIndexer (VectorizedIndexer / BasicIndexer)
Notes
-----
This function is used to realize the vectorized indexing for the backend
arrays that only support basic or outer indexing.
As an example, let us consider to index a few elements from a backend array
with a vectorized indexer ([0, 3, 1], [2, 3, 2]).
Even if the backend array only supports outer indexing, it is more
efficient to load a subslice of the array than loading the entire array,
>>> array = np.arange(36).reshape(6, 6)
>>> backend_indexer = OuterIndexer((np.array([0, 1, 3]), np.array([2, 3])))
>>> # load subslice of the array
... array = NumpyIndexingAdapter(array)[backend_indexer]
>>> np_indexer = VectorizedIndexer((np.array([0, 2, 1]), np.array([0, 1, 0])))
>>> # vectorized indexing for on-memory np.ndarray.
... NumpyIndexingAdapter(array)[np_indexer]
array([ 2, 21, 8])
"""
assert isinstance(indexer, VectorizedIndexer)
if indexing_support is IndexingSupport.VECTORIZED:
return indexer, BasicIndexer(())
backend_indexer_elems = []
np_indexer_elems = []
# convert negative indices
indexer_elems = [
np.where(k < 0, k + s, k) if isinstance(k, np.ndarray) else k
for k, s in zip(indexer.tuple, shape)
]
for k, s in zip(indexer_elems, shape):
if isinstance(k, slice):
# If it is a slice, then we will slice it as-is
# (but make its step positive) in the backend,
# and then use all of it (slice(None)) for the in-memory portion.
bk_slice, np_slice = _decompose_slice(k, s)
backend_indexer_elems.append(bk_slice)
np_indexer_elems.append(np_slice)
else:
# If it is a (multidimensional) np.ndarray, just pickup the used
# keys without duplication and store them as a 1d-np.ndarray.
oind, vind = np.unique(k, return_inverse=True)
backend_indexer_elems.append(oind)
np_indexer_elems.append(vind.reshape(*k.shape))
backend_indexer = OuterIndexer(tuple(backend_indexer_elems))
np_indexer = VectorizedIndexer(tuple(np_indexer_elems))
if indexing_support is IndexingSupport.OUTER:
return backend_indexer, np_indexer
# If the backend does not support outer indexing,
# backend_indexer (OuterIndexer) is also decomposed.
backend_indexer1, np_indexer1 = _decompose_outer_indexer(
backend_indexer, shape, indexing_support
)
np_indexer = _combine_indexers(np_indexer1, shape, np_indexer)
return backend_indexer1, np_indexer
def _decompose_outer_indexer(
indexer: BasicIndexer | OuterIndexer,
shape: tuple[int, ...],
indexing_support: IndexingSupport,
) -> tuple[ExplicitIndexer, ExplicitIndexer]:
"""
Decompose outer indexer to the successive two indexers, where the
first indexer will be used to index backend arrays, while the second one
is used to index the loaded on-memory np.ndarray.
Parameters
----------
indexer : OuterIndexer or BasicIndexer
indexing_support : One of the entries of IndexingSupport
Returns
-------
backend_indexer: OuterIndexer or BasicIndexer
np_indexers: an ExplicitIndexer (OuterIndexer / BasicIndexer)
Notes
-----
This function is used to realize the vectorized indexing for the backend
arrays that only support basic or outer indexing.
As an example, let us consider to index a few elements from a backend array
with a orthogonal indexer ([0, 3, 1], [2, 3, 2]).
Even if the backend array only supports basic indexing, it is more
efficient to load a subslice of the array than loading the entire array,
>>> array = np.arange(36).reshape(6, 6)
>>> backend_indexer = BasicIndexer((slice(0, 3), slice(2, 4)))
>>> # load subslice of the array
... array = NumpyIndexingAdapter(array)[backend_indexer]
>>> np_indexer = OuterIndexer((np.array([0, 2, 1]), np.array([0, 1, 0])))
>>> # outer indexing for on-memory np.ndarray.
... NumpyIndexingAdapter(array)[np_indexer]
array([[ 2, 3, 2],
[14, 15, 14],
[ 8, 9, 8]])
"""
if indexing_support == IndexingSupport.VECTORIZED:
return indexer, BasicIndexer(())
assert isinstance(indexer, (OuterIndexer, BasicIndexer))
backend_indexer: list[Any] = []
np_indexer = []
# make indexer positive
pos_indexer: list[np.ndarray | int | np.number] = []
for k, s in zip(indexer.tuple, shape):
if isinstance(k, np.ndarray):
pos_indexer.append(np.where(k < 0, k + s, k))
elif isinstance(k, integer_types) and k < 0:
pos_indexer.append(k + s)
else:
pos_indexer.append(k)
indexer_elems = pos_indexer
if indexing_support is IndexingSupport.OUTER_1VECTOR:
# some backends such as h5py supports only 1 vector in indexers
# We choose the most efficient axis
gains = [
(np.max(k) - np.min(k) + 1.0) / len(np.unique(k))
if isinstance(k, np.ndarray)
else 0
for k in indexer_elems
]
array_index = np.argmax(np.array(gains)) if len(gains) > 0 else None
for i, (k, s) in enumerate(zip(indexer_elems, shape)):
if isinstance(k, np.ndarray) and i != array_index:
# np.ndarray key is converted to slice that covers the entire
# entries of this key.
backend_indexer.append(slice(np.min(k), np.max(k) + 1))
np_indexer.append(k - np.min(k))
elif isinstance(k, np.ndarray):
# Remove duplicates and sort them in the increasing order
pkey, ekey = np.unique(k, return_inverse=True)
backend_indexer.append(pkey)
np_indexer.append(ekey)