-
Notifications
You must be signed in to change notification settings - Fork 81
/
indexedoptionarray.py
1793 lines (1591 loc) · 65.2 KB
/
indexedoptionarray.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
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward/blob/main/LICENSE
from __future__ import annotations
import copy
from collections.abc import Mapping, MutableMapping, Sequence
import awkward as ak
from awkward._backends.backend import Backend
from awkward._layout import maybe_posaxis
from awkward._meta.indexedoptionmeta import IndexedOptionMeta
from awkward._nplikes.array_like import ArrayLike
from awkward._nplikes.numpy import Numpy
from awkward._nplikes.numpy_like import IndexType, NumpyMetadata
from awkward._nplikes.placeholder import PlaceholderArray
from awkward._nplikes.shape import ShapeItem, unknown_length
from awkward._nplikes.typetracer import MaybeNone, TypeTracer
from awkward._parameters import (
parameters_intersect,
parameters_union,
)
from awkward._regularize import is_integer_like
from awkward._slicing import NO_HEAD
from awkward._typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Self,
SupportsIndex,
final,
)
from awkward._util import UNSET
from awkward.contents.content import (
ApplyActionOptions,
Content,
ImplementsApplyAction,
RemoveStructureOptions,
ToArrowOptions,
)
from awkward.errors import AxisError
from awkward.forms.form import Form
from awkward.forms.indexedoptionform import IndexedOptionForm
from awkward.index import Index
if TYPE_CHECKING:
from awkward._slicing import SliceItem
np = NumpyMetadata.instance()
numpy = Numpy.instance()
@final
class IndexedOptionArray(IndexedOptionMeta[Content], Content):
"""
IndexedOptionArray is an #ak.contents.IndexedArray for which
negative values in the index are interpreted as missing. It represents
#ak.types.OptionType data like #ak.contents.ByteMaskedArray,
#ak.contents.BitMaskedArray, and #ak.contents.UnmaskedArray, but
the flexibility of the arbitrary `index` makes it a common output of
many operations.
IndexedOptionArray doesn't have a direct equivalent in Apache Arrow.
To illustrate how the constructor arguments are interpreted, the following is a
simplified implementation of `__init__`, `__len__`, and `__getitem__`:
class IndexedOptionArray(Content):
def __init__(self, index, content):
assert isinstance(index, (Index32, Index64))
assert isinstance(content, Content)
for x in index:
assert x < len(content) # index[i] may be negative
self.index = index
self.content = content
def __len__(self):
return len(self.index)
def __getitem__(self, where):
if isinstance(where, int):
if where < 0:
where += len(self)
assert 0 <= where < len(self)
if self.index[where] < 0:
return None
else:
return self.content[self.index[where]]
elif isinstance(where, slice) and where.step is None:
return IndexedOptionArray(
self.index[where.start : where.stop], self.content
)
elif isinstance(where, str):
return IndexedOptionArray(self.index, self.content[where])
else:
raise AssertionError(where)
"""
def __init__(self, index, content, *, parameters=None):
if not (
isinstance(index, Index)
and index.dtype
in (
np.dtype(np.int32),
np.dtype(np.int64),
)
):
raise TypeError(
f"{type(self).__name__} 'index' must be an Index with dtype in (int32, uint32, int64), "
f"not {index!r}"
)
if not isinstance(content, Content):
raise TypeError(
f"{type(self).__name__} 'content' must be a Content subtype, not {content!r}"
)
is_cat = parameters is not None and parameters.get("__array__") == "categorical"
if (content.is_union and not is_cat) or content.is_indexed or content.is_option:
raise TypeError(
"{0} cannot contain a union-type (unless categorical), option-type, or indexed 'content' ({1}); try {0}.simplified instead".format(
type(self).__name__, type(content).__name__
)
)
assert index.nplike is content.backend.index_nplike
self._index = index
self._content = content
self._init(parameters, content.backend)
@property
def index(self):
return self._index
form_cls: Final = IndexedOptionForm
def copy(self, index=UNSET, content=UNSET, *, parameters=UNSET):
return IndexedOptionArray(
self._index if index is UNSET else index,
self._content if content is UNSET else content,
parameters=self._parameters if parameters is UNSET else parameters,
)
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
return self.copy(
index=copy.deepcopy(self._index, memo),
content=copy.deepcopy(self._content, memo),
parameters=copy.deepcopy(self._parameters, memo),
)
@classmethod
def simplified(cls, index, content, *, parameters=None):
is_cat = parameters is not None and parameters.get("__array__") == "categorical"
if content.is_union and not is_cat:
return content._union_of_optionarrays(index, parameters)
elif content.is_indexed or content.is_option:
backend = content.backend
if content.is_indexed:
inner = content.index
else:
inner = content.to_IndexedOptionArray64().index
result = ak.index.Index64.empty(index.length, nplike=backend.index_nplike)
backend.maybe_kernel_error(
backend[
"awkward_IndexedArray_simplify",
result.dtype.type,
index.dtype.type,
inner.dtype.type,
](
result.data,
index.data,
index.length,
inner.data,
inner.length,
)
)
return IndexedOptionArray(
result,
content.content,
parameters=parameters_union(content._parameters, parameters),
)
else:
return cls(index, content, parameters=parameters)
def _form_with_key(
self, getkey: Callable[[Content], str | None]
) -> IndexedOptionForm:
form_key = getkey(self)
return self.form_cls(
self._index.form,
self._content._form_with_key(getkey),
parameters=self._parameters,
form_key=form_key,
)
def _to_buffers(
self,
form: Form,
getkey: Callable[[Content, Form, str], str],
container: MutableMapping[str, ArrayLike],
backend: Backend,
byteorder: str,
):
assert isinstance(form, self.form_cls)
key = getkey(self, form, "index")
container[key] = ak._util.native_to_byteorder(
self._index.raw(backend.index_nplike), byteorder
)
self._content._to_buffers(form.content, getkey, container, backend, byteorder)
def _to_typetracer(self, forget_length: bool) -> Self:
index = self._index.to_nplike(TypeTracer.instance())
return IndexedOptionArray(
index.forget_length() if forget_length else index,
self._content._to_typetracer(forget_length),
parameters=self._parameters,
)
def _touch_data(self, recursive: bool):
self._index._touch_data()
if recursive:
self._content._touch_data(recursive)
def _touch_shape(self, recursive: bool):
self._index._touch_shape()
if recursive:
self._content._touch_shape(recursive)
@property
def length(self) -> ShapeItem:
return self._index.length
def __repr__(self):
return self._repr("", "", "")
def _repr(self, indent, pre, post):
out = [indent, pre, "<IndexedOptionArray len="]
out.append(repr(str(self.length)))
out.append(">")
out.extend(self._repr_extra(indent + " "))
out.append("\n")
out.append(self._index._repr(indent + " ", "<index>", "</index>\n"))
out.append(self._content._repr(indent + " ", "<content>", "</content>\n"))
out.append(indent + "</IndexedOptionArray>")
out.append(post)
return "".join(out)
def to_IndexedOptionArray64(self) -> IndexedOptionArray:
if self._index.dtype == np.dtype(np.int64):
return self
else:
return IndexedOptionArray(
self._backend.index_nplike.astype(self._index, dtype=np.int64),
self._content,
parameters=self._parameters,
)
def to_ByteMaskedArray(self, valid_when):
mask = ak.index.Index8(self.mask_as_bool(valid_when))
carry = self._index.data
too_negative = carry < -1
if self._backend.index_nplike.known_data and self._backend.index_nplike.any(
too_negative
):
carry = carry.copy()
carry[too_negative] = -1
carry = ak.index.Index(carry)
if self._content.length is not unknown_length and self._content.length == 0:
content = self._content.form.length_one_array(backend=self._backend)._carry(
carry, False
)
else:
content = self._content._carry(carry, False)
return ak.contents.ByteMaskedArray(
mask, content, valid_when, parameters=self._parameters
)
def to_BitMaskedArray(self, valid_when, lsb_order):
return self.to_ByteMaskedArray(valid_when).to_BitMaskedArray(
valid_when, lsb_order
)
def mask_as_bool(self, valid_when: bool = True) -> ArrayLike:
if valid_when:
return self._index.raw(self._backend.index_nplike) >= 0
else:
return self._index.raw(self._backend.index_nplike) < 0
def _getitem_nothing(self):
return self._content._getitem_range(0, 0)
def _is_getitem_at_placeholder(self) -> bool:
if isinstance(self._index, PlaceholderArray):
return True
return self._content._is_getitem_at_placeholder()
def _getitem_at(self, where: IndexType):
if not self._backend.nplike.known_data:
self._touch_data(recursive=False)
return MaybeNone(self._content._getitem_at(where))
if where < 0:
where += self.length
if self._backend.nplike.known_data and not 0 <= where < self.length:
raise ak._errors.index_error(self, where)
if self._index[where] < 0:
return None
else:
return self._content._getitem_at(self._index[where])
def _getitem_range(self, start: IndexType, stop: IndexType) -> Content:
if not self._backend.nplike.known_data:
self._touch_shape(recursive=False)
return self
return IndexedOptionArray(
self._index[start:stop], self._content, parameters=self._parameters
)
def _getitem_field(
self, where: str | SupportsIndex, only_fields: tuple[str, ...] = ()
) -> Content:
return IndexedOptionArray.simplified(
self._index,
self._content._getitem_field(where, only_fields),
parameters=None,
)
def _getitem_fields(
self, where: list[str | SupportsIndex], only_fields: tuple[str, ...] = ()
) -> Content:
return IndexedOptionArray.simplified(
self._index,
self._content._getitem_fields(where, only_fields),
parameters=None,
)
def _carry(self, carry: Index, allow_lazy: bool) -> IndexedOptionArray:
assert isinstance(carry, ak.index.Index)
try:
nextindex = self._index[carry.data]
except IndexError as err:
raise ak._errors.index_error(self, carry.data, str(err)) from err
return IndexedOptionArray(nextindex, self._content, parameters=self._parameters)
def _nextcarry_outindex(self):
backend = self._backend
index_nplike = backend.index_nplike
_numnull = ak.index.Index64.empty(1, nplike=backend.index_nplike)
assert _numnull.nplike is index_nplike and self._index.nplike is index_nplike
self._backend.maybe_kernel_error(
backend[
"awkward_IndexedArray_numnull",
_numnull.dtype.type,
self._index.dtype.type,
](
_numnull.data,
self._index.data,
self._index.length,
)
)
numnull = index_nplike.index_as_shape_item(_numnull[0])
nextcarry = ak.index.Index64.empty(
self._index.length - numnull,
index_nplike,
)
outindex = ak.index.Index.empty(
self._index.length,
index_nplike,
dtype=self._index.dtype,
)
assert (
nextcarry.nplike is index_nplike
and outindex.nplike is index_nplike
and self._index.nplike is index_nplike
)
self._backend.maybe_kernel_error(
backend[
"awkward_IndexedArray_getitem_nextcarry_outindex",
nextcarry.dtype.type,
outindex.dtype.type,
self._index.dtype.type,
](
nextcarry.data,
outindex.data,
self._index.data,
self._index.length,
self._content.length,
)
)
return numnull, nextcarry, outindex
def _getitem_next_jagged_generic(self, slicestarts, slicestops, slicecontent, tail):
slicestarts = slicestarts.to_nplike(self._backend.index_nplike)
slicestops = slicestops.to_nplike(self._backend.index_nplike)
if self._backend.nplike.known_data and slicestarts.length != self.length:
raise ak._errors.index_error(
self,
ak.contents.ListArray(
slicestarts, slicestops, slicecontent, parameters=None
),
f"cannot fit jagged slice with length {slicestarts.length} into {type(self).__name__} of size {self.length}",
)
numnull, nextcarry, outindex = self._nextcarry_outindex()
reducedstarts = ak.index.Index64.empty(
self.length - numnull,
nplike=self._backend.index_nplike,
)
reducedstops = ak.index.Index64.empty(
self.length - numnull,
nplike=self._backend.index_nplike,
)
assert (
outindex.nplike is self._backend.index_nplike
and slicestarts.nplike is self._backend.index_nplike
and slicestops.nplike is self._backend.index_nplike
and reducedstarts.nplike is self._backend.index_nplike
and reducedstops.nplike is self._backend.index_nplike
)
self._maybe_index_error(
self._backend[
"awkward_MaskedArray_getitem_next_jagged_project",
outindex.dtype.type,
slicestarts.dtype.type,
slicestops.dtype.type,
reducedstarts.dtype.type,
reducedstops.dtype.type,
](
outindex.data,
slicestarts.data,
slicestops.data,
reducedstarts.data,
reducedstops.data,
self.length,
),
slicer=ak.contents.ListArray(slicestarts, slicestops, slicecontent),
)
next = self._content._carry(nextcarry, True)
out = next._getitem_next_jagged(reducedstarts, reducedstops, slicecontent, tail)
return ak.contents.IndexedOptionArray.simplified(
outindex, out, parameters=self._parameters
)
def _getitem_next_jagged(
self, slicestarts: Index, slicestops: Index, slicecontent: Content, tail
) -> Content:
return self._getitem_next_jagged_generic(
slicestarts, slicestops, slicecontent, tail
)
def _getitem_next(
self,
head: SliceItem | tuple,
tail: tuple[SliceItem, ...],
advanced: Index | None,
) -> Content:
if head is NO_HEAD:
return self
elif is_integer_like(head) or isinstance(
head, (slice, ak.index.Index64, ak.contents.ListOffsetArray)
):
nexthead, nexttail = ak._slicing.head_tail(tail)
numnull, nextcarry, outindex = self._nextcarry_outindex()
next = self._content._carry(nextcarry, True)
out = next._getitem_next(head, tail, advanced)
return IndexedOptionArray.simplified(
outindex, out, parameters=self._parameters
)
elif isinstance(head, str):
return self._getitem_next_field(head, tail, advanced)
elif isinstance(head, list) and isinstance(head[0], str):
return self._getitem_next_fields(head, tail, advanced)
elif head is np.newaxis:
return self._getitem_next_newaxis(tail, advanced)
elif head is Ellipsis:
return self._getitem_next_ellipsis(tail, advanced)
elif isinstance(head, ak.contents.IndexedOptionArray):
return self._getitem_next_missing(head, tail, advanced)
else:
raise AssertionError(repr(head))
def project(self, mask=None):
if mask is not None:
if self._backend.nplike.known_data and self._index.length != mask.length:
raise ValueError(
f"mask length ({mask.length()}) is not equal to {type(self).__name__} length ({self._index.length})"
)
nextindex = ak.index.Index64.empty(
self._index.length, self._backend.index_nplike
)
assert (
nextindex.nplike is self._backend.index_nplike
and mask.nplike is self._backend.index_nplike
and self._index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_overlay_mask",
nextindex.dtype.type,
mask.dtype.type,
self._index.dtype.type,
](
nextindex.data,
mask.data,
self._index.data,
self._index.length,
)
)
next = ak.contents.IndexedOptionArray(
nextindex, self._content, parameters=self._parameters
)
return next.project()
else:
_numnull = ak.index.Index64.empty(1, self._backend.index_nplike)
assert (
_numnull.nplike is self._backend.index_nplike
and self._index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_numnull",
_numnull.dtype.type,
self._index.dtype.type,
](
_numnull.data,
self._index.data,
self._index.length,
)
)
numnull = self._backend.index_nplike.index_as_shape_item(_numnull[0])
nextcarry = ak.index.Index64.empty(
self.length - numnull,
self._backend.index_nplike,
)
assert (
nextcarry.nplike is self._backend.index_nplike
and self._index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_flatten_nextcarry",
nextcarry.dtype.type,
self._index.dtype.type,
](
nextcarry.data,
self._index.data,
self._index.length,
self._content.length,
)
)
return self._content._carry(nextcarry, False)
def _offsets_and_flattened(self, axis: int, depth: int) -> tuple[Index, Content]:
posaxis = maybe_posaxis(self, axis, depth)
if posaxis is not None and posaxis + 1 == depth:
raise AxisError("axis=0 not allowed for flatten")
else:
numnull, nextcarry, outindex = self._nextcarry_outindex()
next = self._content._carry(nextcarry, False)
offsets, flattened = next._offsets_and_flattened(axis, depth)
if offsets.length == 0:
return (
offsets,
ak.contents.IndexedOptionArray(
outindex, flattened, parameters=self._parameters
),
)
else:
outoffsets = ak.index.Index64.empty(
offsets.length + numnull,
self._backend.index_nplike,
dtype=np.int64,
)
assert (
outoffsets.nplike is self._backend.index_nplike
and outindex.nplike is self._backend.index_nplike
and offsets.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_flatten_none2empty",
outoffsets.dtype.type,
outindex.dtype.type,
offsets.dtype.type,
](
outoffsets.data,
outindex.data,
outindex.length,
offsets.data,
offsets.length,
)
)
return (outoffsets, flattened)
def _mergeable_next(self, other: Content, mergebool: bool) -> bool:
# Is the other content is an identity, or a union?
if other.is_identity_like or other.is_union:
return True
# Is the other array indexed or optional?
elif other.is_option or other.is_indexed:
return self._content._mergeable_next(other.content, mergebool)
else:
return self._content._mergeable_next(other, mergebool)
def _merging_strategy(self, others):
if len(others) == 0:
raise ValueError(
"to merge this array with 'others', at least one other must be provided"
)
head = [self]
tail = []
it_others = iter(others)
for other in it_others:
if isinstance(other, ak.contents.UnionArray):
tail.append(other)
tail.extend(it_others)
break
else:
head.append(other)
if any(x.backend.nplike.known_data for x in head + tail) and not all(
x.backend.nplike.known_data for x in head + tail
):
raise RuntimeError
return head, tail
def _reverse_merge(self, other):
if isinstance(other, ak.contents.EmptyArray):
return self
# FIXME: support categorical-categorical merging
if (
other.is_indexed
and other.parameter("__array__")
== self.parameter("__array__")
== "categorical"
):
raise NotImplementedError(
"merging categorical arrays is currently not implemented. "
"Use `ak.enforce_type` to drop the categorical type and use general merging."
)
theirlength = other.length
mylength = self.length
index = ak.index.Index64.empty(
theirlength + mylength,
self._backend.index_nplike,
)
content = other._mergemany([self._content])
# Fill index::0→theirlength with arange(theirlength)
assert index.nplike is self._backend.index_nplike
self._backend.maybe_kernel_error(
self._backend["awkward_IndexedArray_fill_count", index.dtype.type](
index.data,
0,
theirlength,
0,
)
)
# Fill index::theirlength->end with self.index[:mylength]+theirlength
assert (
index.nplike is self._backend.index_nplike
and self.index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_fill",
index.dtype.type,
self.index.dtype.type,
](
index.data,
theirlength,
self.index.data,
mylength,
theirlength,
)
)
# We can directly merge with other options and indexed types, but we must merge parameters
if other.is_option or other.is_indexed:
parameters = parameters_union(self._parameters, other._parameters)
# Otherwise, this option parameters win out
else:
parameters = self._parameters
return ak.contents.IndexedOptionArray.simplified(
index, content, parameters=parameters
)
def _mergemany(self, others: Sequence[Content]) -> Content:
if len(others) == 0:
return self
head, tail = self._merging_strategy(others)
total_length = 0
for array in head:
total_length += array.length
contents = []
contentlength_so_far = 0
length_so_far = 0
nextindex = ak.index.Index64.empty(total_length, self._backend.index_nplike)
parameters = self._parameters
for array in head:
if isinstance(array, ak.contents.EmptyArray):
continue
if isinstance(
array,
(
ak.contents.ByteMaskedArray,
ak.contents.BitMaskedArray,
ak.contents.UnmaskedArray,
),
):
array = array.to_IndexedOptionArray64()
if isinstance(
array, (ak.contents.IndexedOptionArray, ak.contents.IndexedArray)
):
# If we're merging an option, then merge parameters before pulling out `content`
parameters = parameters_intersect(parameters, array._parameters)
contents.append(array.content)
array_index = array.index
assert (
nextindex.nplike is self._backend.index_nplike
and array_index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_fill",
nextindex.dtype.type,
array_index.dtype.type,
](
nextindex.data,
length_so_far,
array_index.data,
array.length,
contentlength_so_far,
)
)
contentlength_so_far += array.content.length
length_so_far += array.length
else:
contents.append(array)
assert nextindex.nplike is self._backend.index_nplike
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_fill_count",
nextindex.dtype.type,
](
nextindex.data,
length_so_far,
array.length,
contentlength_so_far,
)
)
contentlength_so_far += array.length
length_so_far += array.length
# Categoricals may only survive if all contents are categorical
if (
parameters is not None
and parameters.get("__array__") == "categorical"
):
parameters = {**parameters}
del parameters["__array__"]
tail_contents = contents[1:]
nextcontent = contents[0]._mergemany(tail_contents)
next = ak.contents.IndexedOptionArray(
nextindex, nextcontent, parameters=parameters
)
# FIXME: support categorical merging?
if parameters is not None and parameters.get("__array__") == "categorical":
raise NotImplementedError(
"merging categorical arrays is currently not implemented. "
"Use `ak.enforce_type` to drop the categorical type and use general merging."
)
if len(tail) == 0:
return next
reversed = tail[0]._reverse_merge(next)
if len(tail) == 1:
return reversed
else:
return reversed._mergemany(tail[1:])
def _fill_none(self, value: Content) -> Content:
if value.backend.nplike.known_data and value.length != 1:
raise ValueError(
f"fill_none value length ({value.length}) is not equal to 1"
)
contents = [self._content, value]
tags = ak.index.Index8(self.mask_as_bool(valid_when=False))
index = ak.index.Index64.empty(tags.length, self._backend.index_nplike)
assert (
index.nplike is self._backend.index_nplike
and self._index.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_UnionArray_fillna", index.dtype.type, self._index.dtype.type
](index.data, self._index.data, tags.length)
)
return ak.contents.UnionArray.simplified(
tags,
index,
contents,
parameters=self._parameters,
mergebool=True,
)
def _local_index(self, axis, depth):
posaxis = maybe_posaxis(self, axis, depth)
if posaxis is not None and posaxis + 1 == depth:
return self._local_index_axis0()
else:
_, nextcarry, outindex = self._nextcarry_outindex()
next = self._content._carry(nextcarry, False)
out = next._local_index(axis, depth)
out2 = ak.contents.IndexedOptionArray(
outindex, out, parameters=self._parameters
)
return out2
def _is_subrange_equal(self, starts, stops, length, sorted=True):
nextstarts = ak.index.Index64.empty(length, self._backend.index_nplike)
nextstops = ak.index.Index64.empty(length, self._backend.index_nplike)
subranges_length = ak.index.Index64.empty(1, self._backend.index_nplike)
assert (
self._index.nplike is self._backend.index_nplike
and starts.nplike is self._backend.index_nplike
and stops.nplike is self._backend.index_nplike
and nextstarts.nplike is self._backend.index_nplike
and nextstops.nplike is self._backend.index_nplike
and subranges_length.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_ranges_next_64",
self._index.dtype.type,
starts.dtype.type,
stops.dtype.type,
nextstarts.dtype.type,
nextstops.dtype.type,
subranges_length.dtype.type,
](
self._index.data,
starts.data,
stops.data,
length,
nextstarts.data,
nextstops.data,
subranges_length.data,
)
)
nextcarry = ak.index.Index64.empty(
subranges_length[0], self._backend.index_nplike
)
assert (
self._index.nplike is self._backend.index_nplike
and starts.nplike is self._backend.index_nplike
and stops.nplike is self._backend.index_nplike
and nextcarry.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_ranges_carry_next_64",
self._index.dtype.type,
starts.dtype.type,
stops.dtype.type,
nextcarry.dtype.type,
](
self._index.data,
starts.data,
stops.data,
length,
nextcarry.data,
)
)
next = self._content._carry(nextcarry, False)
if nextstarts.length is not unknown_length and nextstarts.length > 1:
return next._is_subrange_equal(nextstarts, nextstops, nextstarts.length)
else:
return next._subranges_equal(
nextstarts, nextstops, nextstarts.length, False
)
def _numbers_to_type(self, name, including_unknown):
return ak.contents.IndexedOptionArray(
self._index,
self._content._numbers_to_type(name, including_unknown),
parameters=self._parameters,
)
def _is_unique(self, negaxis, starts, parents, outlength):
if self._index.length is not unknown_length and self._index.length == 0:
return True
projected = self.project()
return projected._is_unique(negaxis, starts, parents, outlength)
def _unique(self, negaxis, starts, parents, outlength):
branch, depth = self.branch_depth
inject_nones = (
True if not branch and (negaxis is not None and negaxis != depth) else False
)
index_length = self._index.length
next, nextparents, numnull, outindex = self._rearrange_prepare_next(parents)
out = next._unique(
negaxis,
starts,
nextparents,
outlength,
)
if branch or (negaxis is not None and negaxis != depth):
nextoutindex = ak.index.Index64.empty(
parents.length, self._backend.index_nplike
)
assert (
nextoutindex.nplike is self._backend.index_nplike
and starts.nplike is self._backend.index_nplike
and parents.nplike is self._backend.index_nplike
and nextparents.nplike is self._backend.index_nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_IndexedArray_local_preparenext",
nextoutindex.dtype.type,
starts.dtype.type,
parents.dtype.type,
nextparents.dtype.type,
](
nextoutindex.data,
starts.data,
parents.data,
parents.length,
nextparents.data,
nextparents.length,
)