-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathnumpyarray.py
More file actions
1475 lines (1296 loc) · 51.2 KB
/
numpyarray.py
File metadata and controls
1475 lines (1296 loc) · 51.2 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
# 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._backends.dispatch import backend_of_obj
from awkward._backends.numpy import NumpyBackend
from awkward._backends.typetracer import TypeTracerBackend
from awkward._layout import maybe_posaxis
from awkward._meta.numpymeta import NumpyMeta
from awkward._nplikes import to_nplike
from awkward._nplikes.array_like import ArrayLike, maybe_materialize
from awkward._nplikes.cupy import Cupy
from awkward._nplikes.jax import Jax
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 TypeTracerArray
from awkward._nplikes.virtual import VirtualNDArray
from awkward._parameters import (
parameters_intersect,
type_parameters_equal,
)
from awkward._regularize import is_integer_like
from awkward._slicing import NO_HEAD
from awkward._typing import (
TYPE_CHECKING,
Any,
Callable,
Final,
Literal,
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, FormKeyPathT
from awkward.forms.numpyform import NumpyForm
from awkward.index import Index, resolve_index
from awkward.types.numpytype import primitive_to_dtype
if TYPE_CHECKING:
from awkward._slicing import SliceItem
np = NumpyMetadata.instance()
numpy = Numpy.instance()
@final
class NumpyArray(NumpyMeta, Content):
"""
A NumpyArray describes 1-dimensional or rectilinear data using a NumPy
`np.ndarray`, a CuPy `cp.ndarray`, etc., depending on the backend.
This class is aware of the rectilinear array's `shape` and `strides`, and
allows for arbitrary `strides`, such as Fortran-ordered data. However, many
operations require C-contiguous data, so derivatives of Fortran-ordered
arrays may not be Fortran-ordered.
Only a subset of `dtype` values are allowed, and only for your system's
native endianness:
* `bool`: boolean, like NumPy's `np.bool_` (considered distinct from integers)
* `int8`: signed 8-bit
* `uint8`: unsigned 8-bit
* `int16`: signed 16-bit
* `uint16`: unsigned 16-bit
* `int32`: signed 32-bit
* `uint32`: unsigned 32-bit
* `int64`: signed 64-bit
* `uint64`: unsigned 64-bit
* `float16`: floating point 16-bit, if your system's NumPy supports it
* `float32`: floating point 32-bit
* `float64`: floating point 64-bit
* `float128`: floating point 128-bit, if your system's NumPy supports it
* `complex64`: floating complex numbers composed of 32-bit real/imag parts
* `complex128`: floating complex numbers composed of 64-bit real/imag parts
* `complex256`: floating complex numbers composed of 128-bit real/imag parts, if your system's NumPy supports it
* `datetime64`: date/time, origin is midnight on January 1, 1970, in any units NumPy supports
* `timedelta64`: time difference, in any units NumPy supports
If the `shape` is one-dimensional, a NumpyArray corresponds to an Apache
Arrow [Primitive array](https://arrow.apache.org/docs/format/Columnar.html#fixed-size-primitive-layout).
To illustrate how the constructor arguments are interpreted, the following is a
simplified implementation of `__init__`, `__len__`, and `__getitem__`::
class NumpyArray(Content):
def __init__(self, data):
assert isinstance(data, numpy_like_array)
assert data.dtype in allowed_dtypes
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, where):
result = self.data[where]
if isinstance(result, numpy_like_array):
return NumpyArray(result)
else:
return result
"""
def __init__(self, data: ArrayLike, *, parameters=None, backend=None):
if backend is None:
backend = backend_of_obj(data, default=NumpyBackend.instance())
self._data = backend.nplike.asarray(data)
if not isinstance(backend.nplike, Jax):
ak.types.numpytype.dtype_to_primitive(self._data.dtype)
if len(ak._util.maybe_shape_of(self._data)) == 0:
raise TypeError(
f"{type(self).__name__} 'data' must be an array, not a scalar: {data!r}"
)
if parameters is not None and parameters.get("__array__") in ("char", "byte"):
if (
data.dtype != np.dtype(np.uint8)
or len(ak._util.maybe_shape_of(data)) != 1
):
raise ValueError(
"{} is a {}, so its 'data' must be 1-dimensional and uint8, not {}".format(
type(self).__name__, parameters["__array__"], repr(data)
)
)
self._init(parameters, backend)
@property
def data(self) -> ArrayLike:
return self._data
form_cls: Final = NumpyForm
def copy(
self,
data=UNSET,
*,
parameters=UNSET,
backend=UNSET,
):
return NumpyArray(
self._data if data is UNSET else data,
parameters=self._parameters if parameters is UNSET else parameters,
backend=self._backend if backend is UNSET else backend,
)
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
return self.copy(
data=copy.deepcopy(self._data, memo),
parameters=copy.deepcopy(self._parameters, memo),
)
@classmethod
def simplified(cls, data, *, parameters=None, backend=None):
return cls(data, parameters=parameters, backend=backend)
@property
def shape(self) -> tuple[ShapeItem, ...]:
return self._data.shape
@property
def inner_shape(self) -> tuple[ShapeItem, ...]:
if hasattr(self._data, "inner_shape"):
inner_shape = self._data.inner_shape
else:
inner_shape = self._data.shape[1:]
return inner_shape
@property
def strides(self) -> tuple[ShapeItem, ...]:
return self._backend.nplike.strides(self._data)
@property
def dtype(self) -> np.dtype:
return self._data.dtype
def _raw(self, nplike=None):
return to_nplike(self.data, nplike, from_nplike=self._backend.nplike)
def _form_with_key(self, getkey: Callable[[Content], str | None]) -> NumpyForm:
return self.form_cls(
ak.types.numpytype.dtype_to_primitive(self._data.dtype),
self.inner_shape,
parameters=self._parameters,
form_key=getkey(self),
)
def _form_with_key_path(self, path: FormKeyPathT) -> NumpyForm:
return self.form_cls(
ak.types.numpytype.dtype_to_primitive(self._data.dtype),
self.inner_shape,
parameters=self._parameters,
form_key=repr(path),
)
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, "data")
container[key] = ak._util.native_to_byteorder(
self._raw(backend.nplike), byteorder
)
def _to_typetracer(self, forget_length: bool) -> Self:
backend = TypeTracerBackend.instance()
data = self._raw(backend.nplike)
return NumpyArray(
data.forget_length() if forget_length else data,
parameters=self._parameters,
backend=backend,
)
def _touch_data(self, recursive: bool):
if not self._backend.nplike.known_data:
self._data.touch_data()
def _touch_shape(self, recursive: bool):
if not self._backend.nplike.known_data:
self._data.touch_shape()
@property
def length(self) -> ShapeItem:
return self._data.shape[0]
def __repr__(self):
return self._repr("", "", "")
def _repr(self, indent, pre, post):
out = [indent, pre, "<NumpyArray dtype="]
out.append(repr(str(self.dtype)))
shape = ak._util.maybe_shape_of(self._data)
if len(shape) == 1:
out.append(" len=" + repr(str(shape[0])))
else:
out.append(" shape='({})'".format(", ".join(str(x) for x in shape)))
extra = self._repr_extra(indent + " ")
arraystr_lines = self._backend.nplike.array_str(
self._data, max_line_width=30
).split("\n")
if len(extra) != 0 or len(arraystr_lines) > 1:
arraystr_lines = self._backend.nplike.array_str(
self._data, max_line_width=max(80 - len(indent) - 4, 40)
).split("\n")
if len(arraystr_lines) > 5:
arraystr_lines = [*arraystr_lines[:2], " ...", *arraystr_lines[-2:]]
out.append(">")
out.extend(extra)
out.append("\n" + indent + " ")
out.append(("\n" + indent + " ").join(arraystr_lines))
out.append("\n" + indent + "</NumpyArray>")
else:
out.append(">")
out.append(arraystr_lines[0])
out.append("</NumpyArray>")
out.append(post)
return "".join(out)
def to_RegularArray(self):
shape = self._data.shape
zeroslen = [1]
for x in shape:
zeroslen.append(zeroslen[-1] * x)
out = NumpyArray(
self._backend.nplike.reshape(self._data, (-1,)),
parameters=None,
backend=self._backend,
)
for i in range(len(shape) - 1, 0, -1):
out = ak.contents.RegularArray(out, shape[i], zeroslen[i], parameters=None)
out._parameters = self._parameters
return out
def maybe_to_NumpyArray(self) -> Self:
return self
def __iter__(self):
return iter(self._data)
def _getitem_nothing(self):
tmp = self._data[0:0]
return NumpyArray(
self._backend.nplike.reshape(tmp, (0, *tmp.shape[2:])),
parameters=None,
backend=self._backend,
)
def _is_getitem_at_placeholder(self) -> bool:
return isinstance(self._data, PlaceholderArray)
def _is_getitem_at_virtual(self) -> bool:
is_virtual = (
isinstance(self._data, VirtualNDArray) and not self._data.is_materialized
)
return is_virtual
def _getitem_at(self, where: IndexType):
if not self._backend.nplike.known_data and len(self._data.shape) == 1:
self._touch_data(recursive=False)
return TypeTracerArray._new(self._data.dtype, shape=())
try:
out = self._data[where]
except IndexError as err:
raise ak._errors.index_error(self, where, str(err)) from err
if hasattr(out, "shape") and len(out.shape) != 0:
return NumpyArray(out, parameters=None, backend=self._backend)
else:
return out
def _getitem_range(self, start: IndexType, stop: IndexType) -> Content:
# in non-typetracer mode (and if all lengths are known) we can check if the slice is a no-op
# (i.e. slicing the full array) and shortcut to avoid noticeable python overhead
if self._backend.nplike.known_data and (start == 0 and stop == self.length):
return self
try:
out = self._data[start:stop]
except IndexError as err:
raise ak._errors.index_error(self, slice(start, stop), str(err)) from err
return NumpyArray(out, parameters=self._parameters, backend=self._backend)
def _getitem_field(
self, where: str | SupportsIndex, only_fields: tuple[str, ...] = ()
) -> Content:
raise ak._errors.index_error(self, where, "not an array of records")
def _getitem_fields(
self, where: list[str | SupportsIndex], only_fields: tuple[str, ...] = ()
) -> Content:
if len(where) == 0:
return self._getitem_range(0, 0)
raise ak._errors.index_error(self, where, "not an array of records")
def _carry(self, carry: Index, allow_lazy: bool) -> Content:
assert isinstance(carry, ak.index.Index)
try:
nextdata = self._data[carry.data]
except IndexError as err:
raise ak._errors.index_error(self, carry.data, str(err)) from err
return NumpyArray(nextdata, parameters=self._parameters, backend=self._backend)
def _getitem_next_jagged(
self, slicestarts: Index, slicestops: Index, slicecontent: Content, tail
) -> Content:
if self._data.ndim == 1:
raise ak._errors.index_error(
self,
ak.contents.ListArray(
slicestarts, slicestops, slicecontent, parameters=None
),
"too many jagged slice dimensions for array",
)
else:
next = self.to_RegularArray()
return next._getitem_next_jagged(
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):
where = (slice(None), head, *tail)
try:
out = self._data[where]
except IndexError as err:
raise ak._errors.index_error(self, (head, *tail), str(err)) from err
if hasattr(out, "shape") and len(out.shape) != 0:
return NumpyArray(out, parameters=None, backend=self._backend)
else:
return out
elif isinstance(head, slice) or head is np.newaxis or head is Ellipsis:
where = (slice(None), head, *tail)
try:
out = self._data[where]
except IndexError as err:
raise ak._errors.index_error(self, (head, *tail), str(err)) from err
return NumpyArray(out, parameters=self._parameters, backend=self._backend)
elif isinstance(head, str):
return self._getitem_next_field(head, tail, advanced)
elif isinstance(head, list):
return self._getitem_next_fields(head, tail, advanced)
elif isinstance(head, ak.index.Index64):
if advanced is None:
where = (slice(None), head.data, *tail)
else:
where = (
self._backend.nplike.asarray(advanced.data),
head.data,
*tail,
)
try:
out = self._data[where]
except IndexError as err:
raise ak._errors.index_error(self, (head, *tail), str(err)) from err
return NumpyArray(out, parameters=self._parameters, backend=self._backend)
elif isinstance(head, ak.contents.ListOffsetArray):
where = (slice(None), head, *tail)
try:
out = self._data[where]
except IndexError as err:
raise ak._errors.index_error(self, (head, *tail), str(err)) from err
return NumpyArray(out, parameters=self._parameters, backend=self._backend)
elif isinstance(head, ak.contents.IndexedOptionArray):
next = self.to_RegularArray()
return next._getitem_next_missing(head, tail, advanced)
else:
raise AssertionError(repr(head))
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")
elif len(self.shape) != 1:
return self.to_RegularArray()._offsets_and_flattened(axis, depth)
else:
raise AxisError(f"axis={axis} exceeds the depth of this array ({depth})")
def _mergeable_next(
self,
other: Content,
mergebool: bool,
mergecastable: Literal["same_kind", "equiv", "family"],
) -> 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_indexed or other.is_option:
return self._mergeable_next(other.content, mergebool, mergecastable)
# Otherwise, do the parameters match? If not, we can't merge.
elif not type_parameters_equal(self._parameters, other._parameters):
return False
# Simplify *this* branch to be 1D self
elif len(self.shape) > 1:
return self._to_regular_primitive()._mergeable_next(
other, mergebool, mergecastable
)
elif isinstance(other, ak.contents.NumpyArray):
if self._data.ndim != other._data.ndim:
return False
# Obvious fast-path
if self.dtype == other.dtype:
return True
# Special-case booleans i.e. {bool, number}
elif (
np.issubdtype(self.dtype, np.bool_)
and np.issubdtype(other.dtype, np.number)
) or (
np.issubdtype(self.dtype, np.number)
and np.issubdtype(other.dtype, np.bool_)
):
return mergebool
# Currently we're less permissive than NumPy on merging datetimes / timedeltas
elif (
np.issubdtype(self.dtype, np.datetime64)
or np.issubdtype(self.dtype, np.timedelta64)
or np.issubdtype(other.dtype, np.datetime64)
or np.issubdtype(other.dtype, np.timedelta64)
):
return False
# Only equivalent dtypes merge (only byte order changes allowed)
elif mergecastable == "equiv":
return self.backend.nplike.can_cast(
self.dtype, other.dtype, "equiv"
) or self.backend.nplike.can_cast(other.dtype, self.dtype, "equiv")
# Only same family of dtypes merge (integers, floats, complex)
elif mergecastable == "family":
for family in np.integer, np.floating, np.complexfloating:
if np.issubdtype(self.dtype, family):
return np.issubdtype(other.dtype, family)
# Default merging (can we cast one to the other)
elif mergecastable == "same_kind":
return self.backend.nplike.can_cast(
self.dtype, other.dtype, "same_kind"
) or self.backend.nplike.can_cast(other.dtype, self.dtype, "same_kind")
else:
raise TypeError(f"unrecognized mergecastable option: {mergecastable}")
else:
return False
def _mergemany(self, others: Sequence[Content]) -> Content:
if len(others) == 0:
return self
if len(self.shape) > 1:
return self.to_RegularArray()._mergemany(others)
head, tail = self._merging_strategy(others)
contiguous_arrays = []
parameters = self._parameters
for array in head:
if isinstance(array, ak.contents.EmptyArray):
continue
parameters = parameters_intersect(parameters, array._parameters)
if isinstance(array, ak.contents.NumpyArray):
contiguous_arrays.append(array.data)
else:
raise AssertionError(
"cannot merge "
+ type(self).__name__
+ " with "
+ type(array).__name__
)
contiguous_arrays = self._backend.nplike.concat(contiguous_arrays)
next = NumpyArray(
contiguous_arrays, parameters=parameters, backend=self._backend
)
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:
return self
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()
elif len(self.shape) <= 1:
raise AxisError(f"axis={axis} exceeds the depth of this array ({depth})")
else:
return self.to_RegularArray()._local_index(axis, depth)
def to_contiguous(self) -> Self:
if self.is_contiguous:
return self
else:
return ak.contents.NumpyArray(
self._backend.nplike.ascontiguousarray(self._data),
parameters=self._parameters,
backend=self._backend,
)
@property
def is_contiguous(self) -> bool:
return self._backend.nplike.is_c_contiguous(self._data)
def _subranges_equal(self, starts, stops, length, sorted=True):
is_equal = self._backend.nplike.zeros(1, dtype=np.bool_)
assert (
starts.nplike is self._backend.nplike
and stops.nplike is self._backend.nplike
)
if self.dtype == np.bool_:
self._backend.maybe_kernel_error(
self._backend[
"awkward_NumpyArray_subrange_equal_bool",
self.dtype.type,
starts.dtype.type,
stops.dtype.type,
np.bool_,
](
self._backend.nplike.astype(
self._data, dtype=self.dtype, copy=True
),
starts.data,
stops.data,
starts.length,
is_equal,
)
)
else:
self._backend.maybe_kernel_error(
self._backend[
"awkward_NumpyArray_subrange_equal",
self.dtype.type,
starts.dtype.type,
stops.dtype.type,
np.bool_,
](
self._backend.nplike.astype(
self._data, dtype=self.dtype, copy=True
),
starts.data,
stops.data,
starts.length,
is_equal,
)
)
return True if is_equal[0] == 1 else False
def _as_unique_strings(self, offsets):
offsets = ak.index.Index64(offsets.data, nplike=offsets.nplike)
outoffsets = ak.index.Index64.empty(offsets.length, nplike=self._backend.nplike)
out = self._backend.nplike.empty(self.shape[0], dtype=self.dtype)
assert (
offsets.nplike is self._backend.nplike
and outoffsets.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_NumpyArray_sort_asstrings_uint8",
self.dtype.type,
self._data.dtype.type,
offsets._data.dtype.type,
outoffsets.dtype.type,
](
out,
self._data,
offsets.data,
offsets.length,
outoffsets.data,
True,
False,
)
)
outlength = ak.index.Index64.empty(1, self._backend.nplike)
nextoffsets = ak.index.Index64.empty(offsets.length, self._backend.nplike)
assert (
outoffsets.nplike is self._backend.nplike
and nextoffsets.nplike is self._backend.nplike
and outlength.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_NumpyArray_unique_strings",
self.dtype.type,
outoffsets.dtype.type,
nextoffsets.dtype.type,
outlength.dtype.type,
](
out,
outoffsets.data,
offsets.length,
nextoffsets.data,
outlength.data,
)
)
out2 = NumpyArray(out, parameters=self._parameters, backend=self._backend)
return out2, nextoffsets[: outlength[0]]
def _numbers_to_type(self, name, including_unknown):
if (
self.parameter("__array__") == "char"
or self.parameter("__array__") == "byte"
):
return self
else:
dtype = primitive_to_dtype(name)
return NumpyArray(
self._backend.nplike.asarray(self._data, dtype=dtype),
parameters=self._parameters,
backend=self._backend,
)
def _is_unique(self, negaxis, starts, parents, offsets, outlength):
if self.length is not unknown_length and self.length == 0:
return True
elif len(self.shape) != 1:
return self.to_RegularArray()._is_unique(
negaxis,
starts,
parents,
offsets,
outlength,
)
elif not self.is_contiguous:
return self.to_contiguous()._is_unique(
negaxis,
starts,
parents,
offsets,
outlength,
)
else:
out = self._unique(negaxis, starts, parents, offsets, outlength)
if isinstance(out, ak.contents.ListOffsetArray):
return (
out.content.length is not unknown_length
and out.content.length == self.length
)
else:
return out.length is not unknown_length and out.length == self.length
def _unique(self, negaxis, starts, parents, offsets, outlength):
if self.shape[0] is not unknown_length and self.shape[0] == 0:
return self
elif len(self.shape) == 0:
return self
elif negaxis is None:
contiguous_self = self.to_contiguous()
offsets = ak.index.Index64.zeros(2, self._backend.nplike)
offsets[1] = self._data.size
dtype = (
np.dtype(np.int64)
if self._data.dtype.kind.upper() == "M"
else self._data.dtype
)
out = self._backend.nplike.empty(self._data.size, dtype=dtype)
assert offsets.nplike is self._backend.nplike
self._backend.maybe_kernel_error(
self._backend[
"awkward_sort",
dtype.type,
dtype.type,
offsets.dtype.type,
](
out,
contiguous_self._data,
offsets[1],
offsets.data,
2,
offsets[1],
True,
False,
)
)
nextlength = ak.index.Index64.empty(1, self._backend.nplike)
assert nextlength.nplike is self._backend.nplike
out = self._backend.nplike.unique_values(out)
nextlength[0] = out.size
return ak.contents.NumpyArray(
self._backend.nplike.asarray(out[: nextlength[0]], dtype=self.dtype),
parameters=None,
backend=self._backend,
)
# axis is not None
elif len(self.shape) != 1:
return self.to_RegularArray()._unique(
negaxis,
starts,
parents,
offsets,
outlength,
)
else:
parents_length = parents.length
offsets_length = ak.index.Index64.empty(1, self._backend.nplike)
assert (
offsets_length.nplike is self._backend.nplike
and parents.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_sorting_ranges_length",
offsets_length.dtype.type,
parents.dtype.type,
](
offsets_length.data,
parents.data,
parents_length,
)
)
offsets = ak.index.Index64.empty(offsets_length[0], self._backend.nplike)
assert (
offsets.nplike is self._backend.nplike
and parents.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_sorting_ranges",
offsets.dtype.type,
parents.dtype.type,
](
offsets.data,
offsets_length[0],
parents.data,
parents_length,
)
)
out = self._backend.nplike.empty(self.length, dtype=self.dtype)
assert offsets.nplike is self._backend.nplike
self._backend.maybe_kernel_error(
self._backend[
"awkward_sort",
out.dtype.type,
self._data.dtype.type,
offsets.dtype.type,
](
out,
self._data,
self.shape[0],
offsets.data,
offsets_length[0],
parents_length,
True,
False,
)
)
nextoffsets = ak.index.Index64.empty(offsets.length, self._backend.nplike)
assert (
offsets.nplike is self._backend.nplike
and nextoffsets.nplike is self._backend.nplike
)
if out.dtype == np.bool_:
self._backend.maybe_kernel_error(
self._backend[
"awkward_unique_ranges_bool",
out.dtype.type,
offsets.dtype.type,
nextoffsets.dtype.type,
](
out,
offsets.data,
offsets.length,
nextoffsets.data,
)
)
else:
self._backend.maybe_kernel_error(
self._backend[
"awkward_unique_ranges",
out.dtype.type,
offsets.dtype.type,
nextoffsets.dtype.type,
](
out,
offsets.data,
offsets.length,
nextoffsets.data,
)
)
outoffsets = ak.index.Index64.empty(starts.length + 1, self._backend.nplike)
assert (
outoffsets.nplike is self._backend.nplike
and nextoffsets.nplike is self._backend.nplike
and starts.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_unique_offsets",
outoffsets.dtype.type,
nextoffsets.dtype.type,
starts.dtype.type,
](
outoffsets.data,
nextoffsets.length,
nextoffsets.data,
starts.data,
starts.length,
)
)
return ak.contents.ListOffsetArray(
outoffsets, ak.contents.NumpyArray(out), parameters=self._parameters
)
def _argsort_next(
self, negaxis, starts, shifts, parents, offsets, outlength, ascending, stable
):
if len(self.shape) != 1:
return self.to_RegularArray()._argsort_next(
negaxis, starts, shifts, parents, offsets, outlength, ascending, stable
)
elif not self.is_contiguous:
return self.to_contiguous()._argsort_next(
negaxis, starts, shifts, parents, offsets, outlength, ascending, stable
)
else:
parents = resolve_index(parents, self._backend)
parents_length = parents.length
_offsets_length = ak.index.Index64.empty(1, self._backend.nplike)
assert (
_offsets_length.nplike is self._backend.nplike
and parents.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_sorting_ranges_length",
_offsets_length.dtype.type,
parents.dtype.type,
](
_offsets_length.data,
parents.data,
parents_length,
)
)
offsets_length = self._backend.nplike.index_as_shape_item(
_offsets_length[0]
)
offsets = ak.index.Index64.empty(offsets_length, self._backend.nplike)
assert (
offsets.nplike is self._backend.nplike
and parents.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_sorting_ranges",
offsets.dtype.type,
parents.dtype.type,
](
offsets.data,
offsets_length,
parents.data,
parents_length,
)
)
dtype = (
np.dtype(np.int64)
if self._data.dtype.kind.upper() == "M"
else self._data.dtype
)
nextcarry = ak.index.Index64.empty(self.length, self._backend.nplike)
assert (
nextcarry.nplike is self._backend.nplike
and offsets.nplike is self._backend.nplike
)
self._backend.maybe_kernel_error(
self._backend[
"awkward_argsort",
nextcarry.dtype.type,
dtype.type,
offsets.dtype.type,
](
nextcarry.data,
self._data,
self.length,