-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathstructure.py
4473 lines (3773 loc) · 166 KB
/
structure.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-1.0/blob/main/LICENSE
from __future__ import absolute_import
import numbers
import json
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import awkward as ak
np = ak.nplike.NumpyMetadata.instance()
@ak._connect._numpy.implements("copy")
def copy(array):
"""
Returns a deep copy of the array (no memory shared with original).
This is identical to `np.copy` and `copy.deepcopy`.
It's only useful to explicitly copy an array if you're going to change it
in-place. This doesn't come up often because Awkward Arrays are immutable.
That is to say, the Awkward Array library doesn't have any operations that
change an array in-place, but the data in the array might be owned by another
library that can change it in-place.
For example, if the array comes from NumPy:
>>> underlying_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5])
>>> wrapper = ak.Array(underlying_array)
>>> duplicate = ak.copy(wrapper)
>>> underlying_array[2] = 123
>>> underlying_array
array([ 1.1, 2.2, 123. , 4.4, 5.5])
>>> wrapper
<Array [1.1, 2.2, 123, 4.4, 5.5] type='5 * float64'>
>>> duplicate
<Array [1.1, 2.2, 3.3, 4.4, 5.5] type='5 * float64'>
There is an exception to this rule: you can add fields to records in an
#ak.Array in-place. However, this changes the #ak.Array wrapper without
affecting the underlying layout data (it *replaces* its layout), so a
shallow copy will do:
>>> original = ak.Array([{"x": 1}, {"x": 2}, {"x": 3}])
>>> shallow_copy = copy.copy(original)
>>> shallow_copy["y"] = original.x**2
>>> shallow_copy
<Array [{x: 1, y: 1}, ... y: 4}, {x: 3, y: 9}] type='3 * {"x": int64, "y": int64}'>
>>> original
<Array [{x: 1}, {x: 2}, {x: 3}] type='3 * {"x": int64}'>
This is key to Awkward Array's efficiency (memory and speed): operations that
only change part of a structure re-use pieces from the original ("structural
sharing"). Changing data in-place would result in many surprising long-distance
changes, so we don't support it. However, an #ak.Array's data might come from
a mutable third-party library, so this function allows you to make a true copy.
"""
layout = ak.operations.convert.to_layout(
array,
allow_record=True,
allow_other=False,
)
return ak._util.wrap(layout.deep_copy(), ak._util.behaviorof(array))
def mask(array, mask, valid_when=True, highlevel=True, behavior=None):
"""
Args:
array: Data to mask, rather than filter.
mask (array of booleans): The mask that overlays elements in the
`array` with None. Must have the same length as `array`.
valid_when (bool): If True, True values in `mask` are considered
valid (passed from `array` to the output); if False, False
values in `mask` are considered valid.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Returns an array for which
output[i] = array[i] if mask[i] == valid_when else None
Unlike filtering data with #ak.Array.__getitem__, this `output` has the
same length as the original `array` and can therefore be used in
calculations with it, such as
[universal functions](https://docs.scipy.org/doc/numpy/reference/ufuncs.html).
For example, with an `array` like
ak.Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
with a boolean selection of `good` elements like
>>> good = (array % 2 == 1)
>>> good
<Array [False, True, False, ... False, True] type='10 * bool'>
could be used to filter the original `array` (or another with the same
length).
>>> array[good]
<Array [1, 3, 5, 7, 9] type='5 * int64'>
However, this eliminates information about which elements were dropped and
where they were. If we instead use #ak.mask,
>>> ak.mask(array, good)
<Array [None, 1, None, 3, ... None, 7, None, 9] type='10 * ?int64'>
this information and the length of the array is preserved, and it can be
used in further calculations with the original `array` (or another with
the same length).
>>> ak.mask(array, good) + array
<Array [None, 2, None, 6, ... 14, None, 18] type='10 * ?int64'>
In particular, successive filters can be applied to the same array.
Even if the `array` and/or the `mask` is nested,
>>> array = ak.Array([[[0, 1, 2], [], [3, 4], [5]], [[6, 7, 8], [9]]])
>>> good = (array % 2 == 1)
>>> good
<Array [[[False, True, False], ... [True]]] type='2 * var * var * bool'>
it can still be used with #ak.mask because the `array` and `mask`
parameters are broadcasted.
>>> ak.mask(array, good)
<Array [[[None, 1, None], ... None], [9]]] type='2 * var * var * ?int64'>
See #ak.broadcast_arrays for details about broadcasting and the generalized
set of broadcasting rules.
Another syntax for
ak.mask(array, array_of_booleans)
is
array.mask[array_of_booleans]
(which is 5 characters away from simply filtering the `array`).
"""
def getfunction(inputs):
layoutarray, layoutmask = inputs
if isinstance(layoutmask, ak.layout.NumpyArray):
m = ak.nplike.of(layoutmask).asarray(layoutmask)
if not issubclass(m.dtype.type, (bool, np.bool_)):
raise ValueError(
"mask must have boolean type, not "
"{0}".format(repr(m.dtype)) + ak._util.exception_suffix(__file__)
)
bytemask = ak.layout.Index8(m.view(np.int8))
return lambda: (
ak.layout.ByteMaskedArray(
bytemask, layoutarray, valid_when=valid_when
).simplify(),
)
else:
return None
layoutarray = ak.operations.convert.to_layout(
array, allow_record=True, allow_other=False
)
layoutmask = ak.operations.convert.to_layout(
mask, allow_record=True, allow_other=False
)
behavior = ak._util.behaviorof(array, mask, behavior=behavior)
out = ak._util.broadcast_and_apply(
[layoutarray, layoutmask],
getfunction,
behavior,
numpy_to_regular=True,
right_broadcast=False,
pass_depth=False,
)
assert isinstance(out, tuple) and len(out) == 1
return ak._util.maybe_wrap(out[0], behavior, highlevel)
def num(array, axis=1, highlevel=True, behavior=None):
"""
Args:
array: Data containing nested lists to count.
axis (int): The dimension at which this operation is applied. The
outermost dimension is `0`, followed by `1`, etc., and negative
values count backward from the innermost: `-1` is the innermost
dimension, `-2` is the next level up, etc.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Returns an array of integers specifying the number of elements at a
particular level.
For instance, given the following doubly nested `array`,
ak.Array([[
[1.1, 2.2, 3.3],
[],
[4.4, 5.5],
[6.6]
],
[],
[
[7.7],
[8.8, 9.9]]
])
The number of elements in `axis=1` is
>>> ak.num(array, axis=1)
<Array [4, 0, 2] type='3 * int64'>
and the number of elements at the next level down, `axis=2`, is
>>> ak.num(array, axis=2)
<Array [[3, 0, 2, 1], [], [1, 2]] type='3 * var * int64'>
The `axis=0` case is special: it returns a scalar, the length of the array.
>>> ak.num(array, axis=0)
3
This function is useful for ensuring that slices do not raise errors. For
instance, suppose that we want to select the first element from each
of the outermost nested lists of `array`. One of these lists is empty, so
selecting the first element (`0`) would raise an error. However, if our
first selection is `ak.num(array) > 0`, we are left with only those lists
that *do* have a first element:
>>> array[ak.num(array) > 0, 0]
<Array [[1.1, 2.2, 3.3], [7.7]] type='2 * var * float64'>
To keep a placeholder (None) in each place we do not want to select,
consider using #ak.mask instead of a #ak.Array.__getitem__.
>>> ak.mask(array, ak.num(array) > 0)[:, 0]
<Array [[1.1, 2.2, 3.3], None, [7.7]] type='3 * option[var * float64]'>
"""
layout = ak.operations.convert.to_layout(
array, allow_record=False, allow_other=False
)
out = layout.num(axis=axis)
return ak._util.maybe_wrap_like(out, array, behavior, highlevel)
def run_lengths(array, highlevel=True, behavior=None):
"""
Args:
array: Data containing runs of numbers to count.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Computes the lengths of sequences of identical values at the deepest level
of nesting, returning an array with the same structure but with `int64` type.
For example,
>>> array = ak.Array([1.1, 1.1, 1.1, 2.2, 3.3, 3.3, 4.4, 4.4, 5.5])
>>> ak.run_lengths(array)
<Array [3, 1, 2, 2, 1] type='5 * int64'>
There are 3 instances of 1.1, followed by 1 instance of 2.2, 2 instances of 3.3,
2 instances of 4.4, and 1 instance of 5.5.
The order and uniqueness of the input data doesn't matter,
>>> array = ak.Array([1.1, 1.1, 1.1, 5.5, 4.4, 4.4, 1.1, 1.1, 5.5])
>>> ak.run_lengths(array)
<Array [3, 1, 2, 2, 1] type='5 * int64'>
just the difference between each value and its neighbors.
The data can be nested, but runs don't cross list boundaries.
>>> array = ak.Array([[1.1, 1.1, 1.1, 2.2, 3.3], [3.3, 4.4], [4.4, 5.5]])
>>> ak.run_lengths(array)
<Array [[3, 1, 1], [1, 1], [1, 1]] type='3 * var * int64'>
This function recognizes strings as distinguishable values.
>>> array = ak.Array([["one", "one"], ["one", "two", "two"], ["three", "two", "two"]])
>>> ak.run_lengths(array)
<Array [[2], [1, 2], [1, 2]] type='3 * var * int64'>
Note that this can be combined with #ak.argsort and #ak.unflatten to compute
a "group by" operation:
>>> array = ak.Array([{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}, {"x": 1, "y": 1.1},
... {"x": 3, "y": 3.3}, {"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}])
>>> sorted = array[ak.argsort(array.x)]
>>> sorted.x
<Array [1, 1, 1, 2, 2, 3] type='6 * int64'>
>>> ak.run_lengths(sorted.x)
<Array [3, 2, 1] type='3 * int64'>
>>> ak.unflatten(sorted, ak.run_lengths(sorted.x)).tolist()
[[{'x': 1, 'y': 1.1}, {'x': 1, 'y': 1.1}, {'x': 1, 'y': 1.1}],
[{'x': 2, 'y': 2.2}, {'x': 2, 'y': 2.2}],
[{'x': 3, 'y': 3.3}]]
Unlike a database "group by," this operation can be applied in bulk to many sublists
(though the run lengths need to be fully flattened to be used as `counts` for
#ak.unflatten, and you need to specify `axis=-1` as the depth).
>>> array = ak.Array([[{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}, {"x": 1, "y": 1.1}],
... [{"x": 3, "y": 3.3}, {"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}]])
>>> sorted = array[ak.argsort(array.x)]
>>> sorted.x
<Array [[1, 1, 2], [1, 2, 3]] type='2 * var * int64'>
>>> ak.run_lengths(sorted.x)
<Array [[2, 1], [1, 1, 1]] type='2 * var * int64'>
>>> counts = ak.flatten(ak.run_lengths(sorted.x), axis=None)
>>> ak.unflatten(sorted, counts, axis=-1).tolist()
[[[{'x': 1, 'y': 1.1}, {'x': 1, 'y': 1.1}],
[{'x': 2, 'y': 2.2}]],
[[{'x': 1, 'y': 1.1}],
[{'x': 2, 'y': 2.2}],
[{'x': 3, 'y': 3.3}]]]
See also #ak.num, #ak.argsort, #ak.unflatten.
"""
nplike = ak.nplike.of(array)
def lengths_of(data, offsets):
if len(data) == 0:
return nplike.empty(0, np.int64), offsets
else:
diffs = data[1:] != data[:-1]
if isinstance(diffs, ak.highlevel.Array):
diffs = nplike.asarray(diffs)
if offsets is not None:
diffs[offsets[1:-1] - 1] = True
positions = nplike.nonzero(diffs)[0]
full_positions = nplike.empty(len(positions) + 2, np.int64)
full_positions[0] = 0
full_positions[-1] = len(data)
full_positions[1:-1] = positions + 1
nextcontent = full_positions[1:] - full_positions[:-1]
if offsets is None:
nextoffsets = None
else:
nextoffsets = nplike.searchsorted(full_positions, offsets, side="left")
return nextcontent, nextoffsets
def getfunction(layout):
if layout.branch_depth == (False, 1):
if isinstance(layout, ak._util.indexedtypes):
layout = layout.project()
if (
layout.parameter("__array__") == "string"
or layout.parameter("__array__") == "bytestring"
):
nextcontent, _ = lengths_of(ak.highlevel.Array(layout), None)
return lambda: ak.layout.NumpyArray(nextcontent)
if not isinstance(layout, (ak.layout.NumpyArray, ak.layout.EmptyArray)):
raise NotImplementedError(
"run_lengths on "
+ type(layout).__name__
+ ak._util.exception_suffix(__file__)
)
nextcontent, _ = lengths_of(nplike.asarray(layout), None)
return lambda: ak.layout.NumpyArray(nextcontent)
elif layout.branch_depth == (False, 2):
if isinstance(layout, ak._util.indexedtypes):
layout = layout.project()
if not isinstance(layout, ak._util.listtypes):
raise NotImplementedError(
"run_lengths on "
+ type(layout).__name__
+ ak._util.exception_suffix(__file__)
)
if (
layout.content.parameter("__array__") == "string"
or layout.content.parameter("__array__") == "bytestring"
):
listoffsetarray = layout.toListOffsetArray64(False)
offsets = nplike.asarray(listoffsetarray.offsets)
content = listoffsetarray.content[offsets[0] : offsets[-1]]
if isinstance(content, ak._util.indexedtypes):
content = content.project()
nextcontent, nextoffsets = lengths_of(
ak.highlevel.Array(content), offsets - offsets[0]
)
return lambda: ak.layout.ListOffsetArray64(
ak.layout.Index64(nextoffsets), ak.layout.NumpyArray(nextcontent)
)
listoffsetarray = layout.toListOffsetArray64(False)
offsets = nplike.asarray(listoffsetarray.offsets)
content = listoffsetarray.content[offsets[0] : offsets[-1]]
if isinstance(content, ak._util.indexedtypes):
content = content.project()
if not isinstance(content, (ak.layout.NumpyArray, ak.layout.EmptyArray)):
raise NotImplementedError(
"run_lengths on "
+ type(layout).__name__
+ " with content "
+ type(content).__name__
+ ak._util.exception_suffix(__file__)
)
nextcontent, nextoffsets = lengths_of(
nplike.asarray(content), offsets - offsets[0]
)
return lambda: ak.layout.ListOffsetArray64(
ak.layout.Index64(nextoffsets), ak.layout.NumpyArray(nextcontent)
)
else:
return None
layout = ak.operations.convert.to_layout(
array, allow_record=False, allow_other=False
)
if isinstance(layout, ak.partition.PartitionedArray):
if len(layout.partitions) != 0 and layout.partitions[0].branch_depth == (
False,
1,
):
out = ak._util.recursively_apply(
layout.toContent(),
getfunction,
pass_depth=False,
pass_user=False,
)
else:
outparts = []
for part in layout.partitions:
outparts.append(
ak._util.recursively_apply(
part,
getfunction,
pass_depth=False,
pass_user=False,
)
)
out = ak.partition.IrregularlyPartitionedArray(outparts)
else:
out = ak._util.recursively_apply(
layout,
getfunction,
pass_depth=False,
pass_user=False,
)
return ak._util.maybe_wrap_like(out, array, behavior, highlevel)
def zip(
arrays,
depth_limit=None,
parameters=None,
with_name=None,
highlevel=True,
behavior=None,
):
"""
Args:
arrays (dict or iterable of arrays): Arrays to combine into a
record-containing structure (if a dict) or a tuple-containing
structure (if any other kind of iterable).
depth_limit (None or int): If None, attempt to fully broadcast the
`array` to all levels. If an int, limit the number of dimensions
that get broadcasted. The minimum value is `1`, for no
broadcasting.
parameters (None or dict): Parameters for the new
#ak.layout.RecordArray node that is created by this operation.
with_name (None or str): Assigns a `"__record__"` name to the new
#ak.layout.RecordArray node that is created by this operation
(overriding `parameters`, if necessary).
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Combines `arrays` into a single structure as the fields of a collection
of records or the slots of a collection of tuples. If the `arrays` have
nested structure, they are broadcasted with one another to form the
records or tuples as deeply as possible, though this can be limited by
`depth_limit`.
This operation may be thought of as the opposite of projection in
#ak.Array.__getitem__, which extracts fields one at a time, or
#ak.unzip, which extracts them all in one call.
Consider the following arrays, `one` and `two`.
>>> one = ak.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6]])
>>> two = ak.Array([["a", "b", "c"], [], ["d", "e"], ["f"]])
Zipping them together using a dict creates a collection of records with
the same nesting structure as `one` and `two`.
>>> ak.to_list(ak.zip({"x": one, "y": two}))
[
[{'x': 1.1, 'y': 'a'}, {'x': 2.2, 'y': 'b'}, {'x': 3.3, 'y': 'c'}],
[],
[{'x': 4.4, 'y': 'd'}, {'x': 5.5, 'y': 'e'}],
[{'x': 6.6, 'y': 'f'}]
]
Doing so with a list creates tuples, whose fields are not named.
>>> ak.to_list(ak.zip([one, two]))
[
[(1.1, 'a'), (2.2, 'b'), (3.3, 'c')],
[],
[(4.4, 'd'), (5.5, 'e')],
[(6.6, 'f')]
]
Adding a third array with the same length as `one` and `two` but less
internal structure is okay: it gets broadcasted to match the others.
(See #ak.broadcast_arrays for broadcasting rules.)
>>> three = ak.Array([100, 200, 300, 400])
>>> ak.to_list(ak.zip([one, two, three]))
[
[[(1.1, 97, 100)], [(2.2, 98, 100)], [(3.3, 99, 100)]],
[],
[[(4.4, 100, 300)], [(5.5, 101, 300)]],
[[(6.6, 102, 400)]]
]
However, if arrays have the same depth but different lengths of nested
lists, attempting to zip them together is a broadcasting error.
>>> one = ak.Array([[[1, 2, 3], [], [4, 5], [6]], [], [[7, 8]]])
>>> two = ak.Array([[[1.1, 2.2], [3.3], [4.4], [5.5]], [], [[6.6]]])
>>> ak.zip([one, two])
ValueError: in ListArray64, cannot broadcast nested list
For this, one can set the `depth_limit` to prevent the operation from
attempting to broadcast what can't be broadcasted.
>>> ak.to_list(ak.zip([one, two], depth_limit=1))
[([[1, 2, 3], [], [4, 5], [6]], [[1.1, 2.2], [3.3], [4.4], [5.5]]),
([], []),
([[7, 8]], [[6.6]])]
As an extreme, `depth_limit=1` is a handy way to make a record structure
at the outermost level, regardless of whether the fields have matching
structure or not.
"""
if depth_limit is not None and depth_limit <= 0:
raise ValueError(
"depth_limit must be None or at least 1"
+ ak._util.exception_suffix(__file__)
)
if isinstance(arrays, dict):
behavior = ak._util.behaviorof(*arrays.values(), behavior=behavior)
recordlookup = []
layouts = []
num_scalars = 0
for n, x in arrays.items():
recordlookup.append(n)
try:
layout = ak.operations.convert.to_layout(
x, allow_record=False, allow_other=False
)
except TypeError:
num_scalars += 1
layout = ak.operations.convert.to_layout(
[x], allow_record=False, allow_other=False
)
layouts.append(layout)
else:
behavior = ak._util.behaviorof(*arrays, behavior=behavior)
recordlookup = None
layouts = []
num_scalars = 0
for x in arrays:
try:
layout = ak.operations.convert.to_layout(
x, allow_record=False, allow_other=False
)
except TypeError:
num_scalars += 1
layout = ak.operations.convert.to_layout(
[x], allow_record=False, allow_other=False
)
layouts.append(layout)
to_record = num_scalars == len(arrays)
if with_name is not None:
if parameters is None:
parameters = {}
else:
parameters = dict(parameters)
parameters["__record__"] = with_name
def getfunction(inputs, depth):
if depth_limit == depth or (
depth_limit is None
and all(
x.purelist_depth == 1
or (
x.purelist_depth == 2
and x.purelist_parameter("__array__")
in ("string", "bytestring", "categorical")
)
for x in inputs
)
):
return lambda: (
ak.layout.RecordArray(inputs, recordlookup, parameters=parameters),
)
else:
return None
out = ak._util.broadcast_and_apply(
layouts,
getfunction,
behavior,
right_broadcast=False,
pass_depth=True,
regular_to_jagged=True,
)
assert isinstance(out, tuple) and len(out) == 1
out = out[0]
if to_record:
out = out[0]
assert isinstance(out, ak.layout.Record)
return ak._util.maybe_wrap(out, behavior, highlevel)
def unzip(array):
"""
If the `array` contains tuples or records, this operation splits them
into a Python tuple of arrays, one for each field.
If the `array` does not contain tuples or records, the single `array`
is placed in a length 1 Python tuple.
For example,
>>> array = ak.Array([{"x": 1.1, "y": [1]},
... {"x": 2.2, "y": [2, 2]},
... {"x": 3.3, "y": [3, 3, 3]}])
>>> x, y = ak.unzip(array)
>>> x
<Array [1.1, 2.2, 3.3] type='3 * float64'>
>>> y
<Array [[1], [2, 2], [3, 3, 3]] type='3 * var * int64'>
"""
fields = ak.operations.describe.fields(array)
if len(fields) == 0:
return (array,)
else:
return tuple(array[n] for n in fields)
def to_regular(array, axis=1, highlevel=True, behavior=None):
"""
Args:
array: Array to convert.
axis (int): The dimension at which this operation is applied. The
outermost dimension is `0`, followed by `1`, etc., and negative
values count backward from the innermost: `-1` is the innermost
dimension, `-2` is the next level up, etc.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Converts a variable-length axis into a regular one, if possible.
>>> irregular = ak.from_iter(np.arange(2*3*5).reshape(2, 3, 5))
>>> ak.type(irregular)
2 * var * var * int64
>>> ak.type(ak.to_regular(irregular))
2 * 3 * var * int64
>>> ak.type(ak.to_regular(irregular, axis=2))
2 * var * 5 * int64
>>> ak.type(ak.to_regular(irregular, axis=-1))
2 * var * 5 * int64
But truly irregular data cannot be converted.
>>> ak.to_regular(ak.Array([[1, 2, 3], [], [4, 5]]))
ValueError: in ListOffsetArray64, cannot convert to RegularArray because
subarray lengths are not regular
See also #ak.from_regular.
"""
def getfunction(layout, depth, posaxis):
posaxis = layout.axis_wrap_if_negative(posaxis)
if posaxis == depth and isinstance(layout, ak.layout.RegularArray):
return lambda: layout
elif posaxis == depth and isinstance(layout, ak._util.listtypes):
return lambda: layout.toRegularArray()
elif posaxis == 0:
raise ValueError(
"array has no axis {0}".format(axis)
+ ak._util.exception_suffix(__file__)
)
else:
return posaxis
out = ak.operations.convert.to_layout(array)
if axis != 0:
out = ak._util.recursively_apply(
out,
getfunction,
pass_depth=True,
pass_user=True,
user=axis,
numpy_to_regular=True,
)
return ak._util.maybe_wrap_like(out, array, behavior, highlevel)
def from_regular(array, axis=1, highlevel=True, behavior=None):
"""
Args:
array: Array to convert.
axis (int): The dimension at which this operation is applied. The
outermost dimension is `0`, followed by `1`, etc., and negative
values count backward from the innermost: `-1` is the innermost
dimension, `-2` is the next level up, etc.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Converts a regular axis into an irregular one.
>>> regular = ak.Array(np.arange(2*3*5).reshape(2, 3, 5))
>>> ak.type(regular)
2 * 3 * 5 * int64
>>> ak.type(ak.from_regular(regular))
2 * var * 5 * int64
>>> ak.type(ak.from_regular(regular, axis=2))
2 * 3 * var * int64
>>> ak.type(ak.from_regular(regular, axis=-1))
2 * 3 * var * int64
See also #ak.to_regular.
"""
def getfunction(layout, depth, posaxis):
posaxis = layout.axis_wrap_if_negative(posaxis)
if posaxis == depth and isinstance(layout, ak.layout.RegularArray):
return lambda: layout.toListOffsetArray64(False)
elif posaxis == depth and isinstance(layout, ak._util.listtypes):
return lambda: layout
elif posaxis == 0:
raise ValueError(
"array has no axis {0}".format(axis)
+ ak._util.exception_suffix(__file__)
)
else:
return posaxis
out = ak.operations.convert.to_layout(array)
if axis != 0:
out = ak._util.recursively_apply(
out,
getfunction,
pass_depth=True,
pass_user=True,
user=axis,
numpy_to_regular=True,
)
return ak._util.maybe_wrap_like(out, array, behavior, highlevel)
def with_name(array, name, highlevel=True, behavior=None):
"""
Args:
base: Data containing records or tuples.
name (str): Name to give to the records or tuples; this assigns
the `"__record__"` parameter.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Returns an #ak.Array or #ak.Record (or low-level equivalent, if
`highlevel=False`) with a new name. This function does not change the
array in-place.
The records or tuples may be nested within multiple levels of nested lists.
If records are nested within records, only the outermost are affected.
Setting the `"__record__"` parameter makes it possible to add behaviors
to the data; see #ak.Array and #ak.behavior for a more complete
description.
"""
def getfunction(layout):
if isinstance(layout, ak.layout.RecordArray):
parameters = dict(layout.parameters)
parameters["__record__"] = name
return lambda: ak.layout.RecordArray(
layout.contents,
layout.recordlookup,
len(layout),
layout.identities,
parameters,
)
else:
return None
out = ak._util.recursively_apply(
ak.operations.convert.to_layout(array), getfunction, pass_depth=False
)
def getfunction2(layout):
if isinstance(layout, ak._util.uniontypes):
return lambda: layout.simplify(merge=True, mergebool=False)
else:
return None
out2 = ak._util.recursively_apply(out, getfunction2, pass_depth=False)
return ak._util.maybe_wrap_like(out2, array, behavior, highlevel)
def with_field(base, what, where=None, highlevel=True, behavior=None):
"""
Args:
base: Data containing records or tuples.
what: Data to add as a new field.
where (None or str or non-empy iterable of str): If None, the new field
has no name (can be accessed as an integer slot number in a
string); If str, the name of the new field. If iterable, it is
interpreted as a path where to add the field in a nested record.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
Returns an #ak.Array or #ak.Record (or low-level equivalent, if
`highlevel=False`) with a new field attached. This function does not
change the array in-place.
See #ak.Array.__setitem__ and #ak.Record.__setitem__ for a variant that
changes the high-level object in-place. (These methods internally use
#ak.with_field, so performance is not a factor in choosing one over the
other.)
"""
if isinstance(what, (ak.highlevel.Array, ak.highlevel.Record)):
what_caches = what.caches # noqa: F841
if not (
where is None
or isinstance(where, str)
or (isinstance(where, Iterable) and all(isinstance(x, str) for x in where))
):
raise TypeError(
"New fields may only be assigned by field name(s) "
"or as a new integer slot by passing None for 'where'"
+ ak._util.exception_suffix(__file__)
)
if (
not isinstance(where, str)
and isinstance(where, Iterable)
and all(isinstance(x, str) for x in where)
and len(where) > 1
):
return with_field(
base,
with_field(
base[where[0]],
what,
where=where[1:],
highlevel=highlevel,
behavior=behavior,
),
where=where[0],
highlevel=highlevel,
behavior=behavior,
)
else:
if not (isinstance(where, str) or where is None):
where = where[0]
behavior = ak._util.behaviorof(base, what, behavior=behavior)
base = ak.operations.convert.to_layout(
base, allow_record=True, allow_other=False
)
if base.numfields < 0:
raise ValueError(
"no tuples or records in array; cannot add a new field"
+ ak._util.exception_suffix(__file__)
)
what = ak.operations.convert.to_layout(
what, allow_record=True, allow_other=True
)
keys = base.keys()
if where in base.keys():
keys.remove(where)
if len(keys) == 0:
# the only key was removed, so just create new Record
out = (ak.layout.RecordArray([what], [where], parameters=base.parameters),)
else:
def getfunction(inputs):
nplike = ak.nplike.of(*inputs)
base, what = inputs
if isinstance(base, ak.layout.RecordArray):
if what is None:
what = ak.layout.IndexedOptionArray64(
ak.layout.Index64(nplike.full(len(base), -1, np.int64)),
ak.layout.EmptyArray(),
)
elif not isinstance(what, ak.layout.Content):
what = ak.layout.NumpyArray(nplike.repeat(what, len(base)))
if base.istuple and where is None:
recordlookup = None
elif base.istuple:
recordlookup = keys + [where]
elif where is None:
recordlookup = keys + [str(len(keys))]
else:
recordlookup = keys + [where]
out = ak.layout.RecordArray(
[base[k] for k in keys] + [what],
recordlookup,
parameters=base.parameters,
)
return lambda: (out,)
else:
return None
out = ak._util.broadcast_and_apply(
[base, what],
getfunction,
behavior,
right_broadcast=False,
pass_depth=False,
)
assert isinstance(out, tuple) and len(out) == 1
return ak._util.maybe_wrap(out[0], behavior, highlevel)
def with_parameter(array, parameter, value, highlevel=True, behavior=None):
"""
Args:
array: Data convertible into an Awkward Array.
parameter (str): Name of the parameter to set on that array.
value (JSON): Value of the parameter to set on that array.
highlevel (bool): If True, return an #ak.Array; otherwise, return
a low-level #ak.layout.Content subclass.
behavior (None or dict): Custom #ak.behavior for the output array, if
high-level.
This function returns a new array with a parameter set on the outermost
node of its #ak.Array.layout.
Note that a "new array" is a lightweight shallow copy, not a duplication
of large data buffers.
You can also remove a single parameter with this function, since setting
a parameter to None is equivalent to removing it.
"""
layout = ak.operations.convert.to_layout(
array, allow_record=True, allow_other=False
)