-
Notifications
You must be signed in to change notification settings - Fork 240
/
indexer.py
1585 lines (1313 loc) · 40.3 KB
/
indexer.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
"""
Classes that handle array indexing.
"""
import sys
import numpy as np
from numbers import Integral
from itertools import zip_longest
from openmdao.utils.general_utils import shape2tuple
from openmdao.utils.array_utils import shape_to_len
from openmdao.utils.om_warnings import issue_warning
def array2slice(arr):
"""
Try to convert an array to slice.
Conversion is only attempted for a 1D array.
Parameters
----------
arr : ndarray
The index array to be represented as a slice.
Returns
-------
slice or None
If slice conversion is possible, return the slice, else return None.
"""
if arr.ndim == 1 and arr.dtype.kind in ('i', 'u'):
if arr.size > 1: # see if 1D array will convert to slice
if arr[0] >= 0 and arr[1] >= 0:
span = arr[1] - arr[0]
else:
return None
if np.all((arr[1:] - arr[:-1]) == span):
if span > 0:
# array is increasing with constant span
return slice(arr[0], arr[-1] + 1, span)
elif span < 0:
# array is decreasing with constant span
return slice(arr[0], arr[-1] - 1, span)
elif arr.size == 1:
if arr[0] >= 0:
return slice(arr[0], arr[0] + 1)
else:
return slice(0, 0)
def _truncate(s):
if len(s) > 40:
return s[:20] + ' ... ' + s[-20:]
return s
class Indexer(object):
"""
Abstract indexing class.
Parameters
----------
flat_src : bool
True if we're treating the source as flat.
Attributes
----------
_src_shape : tuple or None
Shape of the 'source'. Used to determine actual index or slice values when indices are
negative or slice contains negative start or stop values or ':' or '...'.
_shaped_inst : Indexer or None
Cached shaped_instance if we've computed it before.
_flat_src : bool
If True, index is into a flat source array.
_dist_shape : tuple
Distributed shape of the source.
"""
def __init__(self, flat_src=None):
"""
Initialize attributes.
"""
self._src_shape = None
self._dist_shape = None
self._shaped_inst = None
self._flat_src = flat_src
def __call__(self):
"""
Return the indices in their most efficient form.
For example, if the original indices were an index array that is convertable to a slice,
then a slice would be returned.
This could be either an int, a slice, an index array, or a multidimensional 'fancy' index.
"""
raise NotImplementedError("No implementation of '__call__' found.")
def __repr__(self):
"""
Return simple string representation.
Returns
-------
str
String representation.
"""
return f"{self.__class__.__name__}: {str(self)}"
def copy(self, *args):
"""
Copy this Indexer.
Parameters
----------
*args : position args
Args that are specific to initialization of a derived Indexer.
Returns
-------
Indexer
A copy of this Indexer.
"""
inst = self.__class__(*args)
inst.__dict__.update(self.__dict__)
return inst
def _set_attrs(self, parent):
"""
Copy certain attributes from the parent to self.
Parameters
----------
parent : Indexer
Parent of this indexer.
Returns
-------
Indexer
This indexer.
"""
self._src_shape = parent._src_shape
self._flat_src = parent._flat_src
self._dist_shape = parent._dist_shape
return self
@property
def indexed_src_shape(self):
"""
Return the shape of the result if the indices were applied to a source array.
Returns
-------
tuple
The shape of the result.
"""
s = self.shaped_instance()
if s is None:
raise RuntimeError(f"Can't get indexed_src_shape of {self} because source shape "
"is unknown.")
if self._flat_src:
return resolve_shape(shape_to_len(self._src_shape)).get_shape(self.flat())
else:
return resolve_shape(self._src_shape).get_shape(self())
@property
def indexed_src_size(self):
"""
Return the size of the result if the index were applied to the source.
Returns
-------
int
Size of flattened indices.
"""
return shape_to_len(self.indexed_src_shape)
def flat(self, copy=False):
"""
Return index array or slice into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
"""
raise NotImplementedError("No implementation of 'flat' found.")
def shaped_instance(self):
"""
Return a 'shaped' version of this Indexer type.
This should be overridden for all non-shaped derived classes.
Returns
-------
Indexer
The 'shaped' Indexer type. 'shaped' Indexers know the extent of the array that
they are indexing into, or they don't care what the extent is because they don't
contain negative indices, negative start or stop, ':', or '...'.
"""
return self
def shaped_array(self, copy=False, flat=True):
"""
Return an index array version of the indices that index into a flattened array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
flat : bool
If True, return a flat array.
Returns
-------
ndarray
Version of these indices that index into a flattened array.
"""
s = self.shaped_instance()
if s is None:
raise ValueError(f"Can't get shaped array of {self} because it has no source shape.")
return s.as_array(copy=copy, flat=flat)
def apply(self, subidxer):
"""
Apply a sub-Indexer to this Indexer and return the resulting indices.
Parameters
----------
subidxer : Indexer
The Indexer to be applied to this one.
Returns
-------
ndarray
The resulting indices (always flat).
"""
arr = self.shaped_array().ravel()
return arr[subidxer.flat()]
def set_src_shape(self, shape, dist_shape=None):
"""
Set the shape of the 'source' array .
Parameters
----------
shape : tuple or int
The shape of the 'source' array.
dist_shape : tuple or None
If not None, the full distributed shape of the source.
Returns
-------
Indexer
Self is returned to allow chaining.
"""
sshape, self._dist_shape, = self._get_shapes(shape, dist_shape)
if shape is not None:
if self._flat_src is None:
self._flat_src = len(sshape) <= 1
if sshape != self._src_shape:
self._src_shape = sshape
try:
self._check_bounds()
except Exception:
self._src_shape = None
self._dist_shape = None
raise
self._shaped_inst = None
return self
def to_json(self):
"""
Return a JSON serializable version of self.
"""
raise NotImplementedError("No implementation of 'to_json' found.")
def _get_shapes(self, shape, dist_shape):
if shape is None:
return None, None
shape = shape2tuple(shape)
if self._flat_src:
shape = (shape_to_len(shape),)
if dist_shape is None:
return shape, shape
dist_shape = shape2tuple(dist_shape)
if self._flat_src:
dist_shape = (shape_to_len(dist_shape),)
return shape, dist_shape
class ShapedIntIndexer(Indexer):
"""
Int indexing class.
Parameters
----------
idx : int
The index.
flat_src : bool
If True, source is treated as flat.
Attributes
----------
_idx : int
The integer index.
"""
def __init__(self, idx, flat_src=None):
"""
Initialize attributes.
"""
super().__init__(flat_src)
self._idx = idx
def __call__(self):
"""
Return this index.
Returns
-------
int
This index.
"""
return self._idx
def __str__(self):
"""
Return string representation.
Returns
-------
str
String representation.
"""
return f"{self._idx}"
def apply_offset(self, offset, flat=True):
"""
Apply an offset to this index.
Parameters
----------
offset : int
The offset to apply.
flat : bool
If True, return a flat index.
Returns
-------
int
The offset index.
"""
return self._idx + offset
def copy(self):
"""
Copy this Indexer.
Returns
-------
Indexer
A copy of this Indexer.
"""
return super().copy(self._idx)
@property
def min_src_dim(self):
"""
Return the number of source dimensions.
Returns
-------
int
The number of dimensions expected in the source array.
"""
return 1
@property
def indexed_src_shape(self):
"""
Return the shape of the index ().
Returns
-------
tuple
The shape of the index.
"""
if self._flat_src:
return (1,)
return super().indexed_src_shape
def as_array(self, copy=False, flat=True):
"""
Return an index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
flat : bool
If True, return a flat array.
Returns
-------
ndarray
The index array.
"""
return np.array([self._idx])
def flat(self, copy=False):
"""
Return index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
Returns
-------
ndarray
The index into a flat array.
"""
return np.array([self._idx])
def _check_bounds(self):
"""
Check that indices are within the bounds of the source shape.
"""
if self._src_shape is not None and (self._idx >= self._dist_shape[0] or
self._idx < -self._dist_shape[0]):
raise IndexError(f"index {self._idx} is out of bounds of the source shape "
f"{self._dist_shape}.")
def to_json(self):
"""
Return a JSON serializable version of self.
Returns
-------
int
Int version of self.
"""
return self._idx
class IntIndexer(ShapedIntIndexer):
"""
Int indexing class that may or may not be 'shaped'.
Parameters
----------
idx : int
The index.
flat_src : bool or None
If True, treat source as flat.
"""
def shaped_instance(self):
"""
Return a 'shaped' version of this Indexer type.
Returns
-------
ShapedIntIndexer or None
Will return a ShapedIntIndexer if possible, else None.
"""
if self._shaped_inst is not None:
return self._shaped_inst
if self._src_shape is None:
return None
if self._idx < 0:
self._shaped_inst = ShapedIntIndexer(self._idx + self._src_shape[0])
else:
self._shaped_inst = ShapedIntIndexer(self._idx)
return self._shaped_inst._set_attrs(self)
class ShapedSliceIndexer(Indexer):
"""
Abstract slice class that is 'shaped'.
Parameters
----------
slc : slice
The slice.
flat_src : bool
If True, source is treated as flat.
Attributes
----------
_slice : slice
The wrapped slice object.
"""
def __init__(self, slc, flat_src=None):
"""
Initialize attributes.
"""
super().__init__(flat_src)
if slc.step is None:
slc = slice(slc.start, slc.stop, 1)
self._slice = slc
def __call__(self):
"""
Return this slice.
Returns
-------
slice
This slice.
"""
return self._slice
def __str__(self):
"""
Return string representation.
Returns
-------
str
String representation.
"""
return f"{self._slice}"
def apply_offset(self, offset, flat=True):
"""
Apply an offset to this index.
Parameters
----------
offset : int
The offset to apply.
flat : bool
If True, return a flat index.
Returns
-------
slice
The offset slice.
"""
return slice(self._slice.start + offset, self._slice.stop + offset, self._slice.step)
def copy(self):
"""
Copy this Indexer.
Returns
-------
Indexer
A copy of this Indexer.
"""
return super().copy(self._slice)
def as_array(self, copy=False, flat=True):
"""
Return an index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
flat : bool
If True, return a flat array.
Returns
-------
ndarray
The index array.
"""
if len(self._src_shape) == 1:
# Case 1: Requested flat or nonflat indices but src_shape is None or flat
# return a flattened arange
slc = self._slice
if slc.stop is None and slc.step < 0: # special case - neg step down to -1
return np.arange(self._src_shape[0], dtype=int)[slc]
else:
# use maxsize here since a shaped slice always has positive int start and stop
return np.arange(*slc.indices(sys.maxsize), dtype=int)
else:
src_size = shape_to_len(self._src_shape)
arr = np.arange(src_size, dtype=int).reshape(self._src_shape)[self._slice].ravel()
if flat:
# Case 2: Requested flattened indices of multidimensional array
# Return indices into a flattened src.
return arr
else:
# Case 3: Requested non-flat indices of multidimensional array
# This is never called within OpenMDAO
return np.unravel_index(arr, shape=self._src_shape)
def flat(self, copy=False):
"""
Return a slice into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
Returns
-------
slice
The slice into a flat array.
"""
# slices are immutable, so ignore copy arg
return self._slice
@property
def min_src_dim(self):
"""
Return the number of source dimensions.
Returns
-------
int
The number of dimensions expected in the source array.
"""
return 1
def _check_bounds(self):
"""
Check that indices are within the bounds of the source shape.
"""
# a slice with start or stop outside of the source range is allowed in numpy arrays
# and just results in an empty array, but in OpenMDAO that behavior would probably be
# unintended, so for now make it an error.
if self._src_shape is not None:
start = self._slice.start
stop = self._slice.stop
sz = shape_to_len(self._dist_shape)
if (start is not None and (start >= sz or start < -sz)
or (stop is not None and (stop > sz or stop < -sz))):
raise IndexError(f"{self._slice} is out of bounds of the source shape "
f"{self._dist_shape}.")
def to_json(self):
"""
Return a JSON serializable version of self.
Returns
-------
list of int or int
List or int version of self.
"""
return self.as_array().tolist()
class SliceIndexer(ShapedSliceIndexer):
"""
Abstract slice class that may or may not be 'shaped'.
Parameters
----------
slc : slice
The slice.
flat_src : bool or None
If True, treat source as flat.
"""
def shaped_instance(self):
"""
Return a 'shaped' version of this Indexer type.
Returns
-------
ShapedSliceIndexer or None
Will return a ShapedSliceIndexer if possible, else None.
"""
if self._shaped_inst is not None:
return self._shaped_inst
if self._src_shape is None:
return None
slc = self._slice
if slc.stop is None and slc.step < 0: # special backwards indexing case
self._shaped_inst = \
ShapedSliceIndexer(slc)
elif (slc.start is not None and slc.start < 0) or slc.stop is None or slc.stop < 0:
self._shaped_inst = \
ShapedSliceIndexer(slice(*self._slice.indices(self._src_shape[0])))
else:
self._shaped_inst = ShapedSliceIndexer(slc)
return self._shaped_inst._set_attrs(self)
def as_array(self, copy=False, flat=True):
"""
Return an index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
flat : bool
If True, return a flat array.
Returns
-------
ndarray
The index array.
"""
return self.shaped_array(copy=copy, flat=flat)
@property
def indexed_src_shape(self):
"""
Return the shape of the result of indexing into the source.
Returns
-------
tuple
The shape of the index.
"""
slc = self._slice
if self._flat_src and slc.start is not None and slc.stop is not None:
return (len(range(slc.start, slc.stop, slc.step)),)
return super().indexed_src_shape
class ShapedArrayIndexer(Indexer):
"""
Abstract index array class that knows its source shape.
Parameters
----------
arr : ndarray
The index array.
flat_src : bool
If True, source is treated as flat.
Attributes
----------
_arr : ndarray
The wrapped index array object.
"""
def __init__(self, arr, flat_src=None):
"""
Initialize attributes.
"""
super().__init__(flat_src)
ndarr = np.asarray(arr)
# check type
if ndarr.dtype.kind not in ('i', 'u'):
raise TypeError(f"Can't create an index array using indices of "
f"non-integral type '{ndarr.dtype.type.__name__}'.")
self._arr = ndarr
def __call__(self):
"""
Return this index array.
Returns
-------
int
This index array.
"""
return self._arr
def __str__(self):
"""
Return string representation.
Returns
-------
str
String representation.
"""
return _truncate(f"{self._arr}".replace('\n', ''))
def apply_offset(self, offset, flat=True):
"""
Apply an offset to this index.
Parameters
----------
offset : int
The offset to apply.
flat : bool
If True, return a flat index.
Returns
-------
slice
The offset slice.
"""
return self.as_array(flat=flat) + offset
def copy(self):
"""
Copy this Indexer.
Returns
-------
Indexer
A copy of this Indexer.
"""
return super().copy(self._arr)
@property
def min_src_dim(self):
"""
Return the number of source dimensions.
Returns
-------
int
The number of dimensions expected in the source array.
"""
return 1
def as_array(self, copy=False, flat=True):
"""
Return an index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
flat : bool
If True, return a flat array.
Returns
-------
ndarray
The index array.
"""
if flat:
arr = self._arr.ravel()
else:
arr = self._arr
if copy:
return arr.copy()
return arr
def flat(self, copy=False):
"""
Return an index array into a flat array.
Parameters
----------
copy : bool
If True, make sure the array returned is a copy.
Returns
-------
ndarray
The index into a flat array.
"""
if copy:
return self._arr.ravel().copy()
return self._arr.ravel()
def _check_bounds(self):
"""
Check that indices are within the bounds of the source shape.
"""
if self._src_shape is not None and self._arr.size > 0:
src_size = shape_to_len(self._dist_shape)
amax = np.max(self._arr)
ob = None
if amax >= src_size or -amax < -src_size:
ob = amax
if ob is None:
amin = np.min(self._arr)
if amin < 0 and -amin > src_size:
ob = amin
if ob is not None:
raise IndexError(f"index {ob} is out of bounds for source dimension of size "
f"{src_size}.")
def to_json(self):
"""
Return a JSON serializable version of self.
Returns
-------
list of int or int
List or int version of self.
"""
return self().tolist()
class ArrayIndexer(ShapedArrayIndexer):
"""
Abstract index array class that may or may not be 'shaped'.
Parameters
----------
arr : ndarray
The index array.
flat_src : bool or None
If True, treat source as flat.
"""
def shaped_instance(self):
"""
Return a 'shaped' version of this Indexer type.
Returns
-------
ShapedArrayIndexer or None
Will return a ShapedArrayIndexer if possible, else None.
"""
if self._shaped_inst is not None:
return self._shaped_inst
if self._src_shape is None:
return None
negs = self._arr < 0
if np.any(negs):
sharr = self._arr.copy()
sharr[negs] += self._src_shape[0]
else:
sharr = self._arr
self._shaped_inst = ShapedArrayIndexer(sharr)
return self._shaped_inst._set_attrs(self)
@property
def indexed_src_shape(self):
"""
Return the shape of the result of indexing into the source.
Returns
-------
tuple
The shape of the index.
"""
return self._arr.shape
class ShapedMultiIndexer(Indexer):
"""
Abstract multi indexer class that is 'shaped'.
Parameters
----------
tup : tuple
Tuple of indices/slices.
flat_src : bool
If True, treat source array as flat.
Attributes
----------
_tup : tuple
The wrapped tuple of indices/slices.
_idx_list : list
List of Indexers.
"""
def __init__(self, tup, flat_src=False):
"""
Initialize attributes.
"""
if flat_src and len(tup) > 1:
raise RuntimeError(f"Can't index into a flat array with an indexer expecting {len(tup)}"
" dimensions.")
super().__init__(flat_src)
self._tup = tup
self._set_idx_list()
def _set_idx_list(self):
self._idx_list = []
for i in self._tup:
if isinstance(i, (np.ndarray, list)): # need special handling here for ndim > 1 arrays
self._idx_list.append(ArrayIndexer(i, flat_src=self._flat_src))
else:
self._idx_list.append(indexer(i, flat_src=self._flat_src))
def __call__(self):
"""
Return this multidimensional index.
Returns
-------
int
This multidimensional index.
"""
return tuple(i() for i in self._idx_list)