This repository has been archived by the owner on Jun 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathjagged.py
1907 lines (1584 loc) · 83 KB
/
jagged.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
#!/usr/bin/env python
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-array/blob/master/LICENSE
import functools
import math
import numbers
import operator
from collections import OrderedDict
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import awkward.array.base
import awkward.persist
import awkward.type
import awkward.util
class JaggedArray(awkward.array.base.AwkwardArrayWithContent):
"""
JaggedArray
"""
@classmethod
def offsetsaliased(cls, starts, stops):
return (isinstance(starts, cls.numpy.ndarray) and isinstance(stops, cls.numpy.ndarray) and
starts.base is not None and stops.base is not None and starts.base is stops.base and
starts.ctypes.data == starts.base.ctypes.data and
stops.ctypes.data == stops.base.ctypes.data + stops.dtype.itemsize and
len(starts) == len(starts.base) - 1 and
len(stops) == len(stops.base) - 1)
@classmethod
def counts2offsets(cls, counts):
offsets = cls.numpy.empty(len(counts) + 1, dtype=cls.JaggedArray.fget(None).INDEXTYPE)
offsets[0] = 0
cls.numpy.cumsum(counts, out=offsets[1:])
return offsets
@classmethod
def offsets2parents(cls, offsets):
dtype = cls.JaggedArray.fget(None).INDEXTYPE
counts = cls.numpy.diff(cls.numpy.r_[dtype.type(0), offsets]) # numpy >= 1.16: diff prepend
indices = cls.numpy.arange(-1, len(offsets) - 1, dtype=dtype)
return cls.numpy.repeat(indices, awkward.util.windows_safe(counts))
@classmethod
def startsstops2parents(cls, starts, stops):
assert starts.shape == stops.shape
starts = starts.reshape(-1) # flatten in case multi-d jagged
stops = stops.reshape(-1)
dtype = cls.JaggedArray.fget(None).INDEXTYPE
out = cls.numpy.full(stops.max(), -1, dtype=dtype)
indices = cls.numpy.arange(len(starts), dtype=dtype)
counts = stops - starts
parents = cls.numpy.repeat(indices, awkward.util.windows_safe(counts))
contiguous_offsets = cls.JaggedArray.fget(None).counts2offsets(counts)
content_indices = cls.numpy.arange(contiguous_offsets[-1])
content_indices -= cls.numpy.repeat(contiguous_offsets[:-1], awkward.util.windows_safe(counts))
content_indices += starts[parents]
cls.numpy.put(out, awkward.util.windows_safe(content_indices), parents)
return out
@classmethod
def parents2startsstops(cls, parents, length=None):
# FIXME for 1.0: use length to add empty lists at the end of the jagged array or truncate
# assumes that children are contiguous, but not necessarily in order or fully covering (allows empty lists)
tmp = cls.numpy.nonzero(parents[1:] != parents[:-1])[0] + 1
changes = cls.numpy.empty(len(tmp) + 2, dtype=cls.JaggedArray.fget(None).INDEXTYPE)
changes[0] = 0
changes[-1] = len(parents)
changes[1:-1] = tmp
length = parents.max() + 1 if len(parents) > 0 else 0
starts = cls.numpy.zeros(length, dtype=cls.JaggedArray.fget(None).INDEXTYPE)
counts = cls.numpy.zeros(length, dtype=cls.JaggedArray.fget(None).INDEXTYPE)
where = parents[changes[:-1]]
real = (where >= 0)
starts[where[real]] = (changes[:-1])[real]
counts[where[real]] = (changes[1:] - changes[:-1])[real]
return starts, starts + counts
@classmethod
def uniques2offsetsparents(cls, uniques):
# assumes that children are contiguous, in order, and fully covering (can't have empty lists)
# values are ignored, apart from uniqueness
changes = cls.numpy.nonzero(uniques[1:] != uniques[:-1])[0] + 1
offsets = cls.numpy.empty(len(changes) + 2, dtype=cls.JaggedArray.fget(None).INDEXTYPE)
offsets[0] = 0
offsets[-1] = len(uniques)
offsets[1:-1] = changes
parents = cls.numpy.zeros(len(uniques), dtype=cls.JaggedArray.fget(None).INDEXTYPE)
parents[changes] = 1
cls.numpy.cumsum(parents, out=parents)
return offsets, parents
def __init__(self, starts, stops, content):
if self.offsetsaliased(starts, stops):
self.content = content
self._starts, self._stops = starts, stops
self._offsets = starts.base
self._counts, self._parents = None, None
self._isvalid = False
if not self._util_isintegertype(self._offsets.dtype.type):
raise TypeError("offsets must have integer dtype")
if len(self._offsets.shape) != 1:
raise ValueError("offsets must be a one-dimensional array")
if len(self._offsets) == 0:
raise ValueError("offsets must be a non-empty array")
if (self._offsets < 0).any():
raise ValueError("offsets must be a non-negative array")
else:
self.starts = starts
self.stops = stops
self.content = content
@classmethod
def fromiter(cls, iterable):
import awkward.generate
if len(iterable) == 0:
return cls.JaggedArray.fget(None)([], [], [])
else:
return awkward.generate.fromiter(iterable, awkwardlib=cls.awkward.fget(None))
@classmethod
def fromoffsets(cls, offsets, content):
offsets = cls._util_toarray(offsets, cls.INDEXTYPE, cls.numpy.ndarray)
if hasattr(offsets.base, 'base') and type(offsets.base.base).__module__ == "pyarrow.lib" and type(offsets.base.base).__name__ == "Buffer":
# special exception to prevent copy in awkward.fromarrow
pass
elif offsets.base is not None:
# We rely on the starts,stops slices to be views.
# If offsets is already a view, the base will not be offsets but its underlying base.
# Make a copy to prevent that
offsets = offsets.copy()
return cls(offsets[:-1], offsets[1:], content)
@classmethod
def fromcounts(cls, counts, content):
counts = cls._util_toarray(counts, cls.INDEXTYPE, cls.numpy.ndarray)
if not cls._util_isintegertype(counts.dtype.type):
raise TypeError("counts must have integer dtype")
if (counts < 0).any():
raise ValueError("counts must be a non-negative array")
offsets = cls.counts2offsets(counts.reshape(-1))
out = cls(offsets[:-1].reshape(counts.shape), offsets[1:].reshape(counts.shape), content)
out._offsets = offsets if len(counts.shape) == 1 else None
out._counts = counts
return out
@classmethod
def fromparents(cls, parents, content, length=None):
parents = cls._util_toarray(parents, cls.INDEXTYPE, cls.numpy.ndarray)
if not cls._util_isintegertype(parents.dtype.type):
raise TypeError("parents must have integer dtype")
if len(parents.shape) != 1 or len(parents) != len(content):
raise ValueError("parents array must be one-dimensional with the same length as content")
starts, stops = cls.parents2startsstops(parents, length=length)
out = cls(starts, stops, content)
out._parents = parents
return out
@classmethod
def fromuniques(cls, uniques, content):
uniques = cls._util_toarray(uniques, cls.INDEXTYPE, cls.numpy.ndarray)
if not cls._util_isintegertype(uniques.dtype.type):
raise TypeError("uniques must have integer dtype")
if len(uniques.shape) != 1 or len(uniques) != len(content):
raise ValueError("uniques array must be one-dimensional with the same length as content")
offsets, parents = cls.uniques2offsetsparents(uniques)
out = cls.fromoffsets(offsets, content)
out._parents = parents
return out
@classmethod
def fromlocalindex(cls, index, content, validate=True):
index = cls._util_toarray(index, cls.INDEXTYPE, (cls.numpy.ndarray, JaggedArray))
original_counts = None
if isinstance(index, JaggedArray):
if validate:
original_counts = index.counts
index = index.flatten()
if not cls._util_isintegertype(index.dtype.type):
raise TypeError("localindex must have integer dtype")
if len(index.shape) != 1 or len(index) != len(content):
raise ValueError("localindex array must be one-dimensional with the same length as content")
if validate:
if not ((index[1:] - index[:-1])[(index != 0)[1:]] == 1).all():
raise ValueError("every localindex that is not zero must be one greater than the previous")
starts = cls.numpy.nonzero(index == 0)[0]
offsets = cls.numpy.empty(len(starts) + 1, dtype=cls.INDEXTYPE)
offsets[:-1] = starts
offsets[-1] = len(index)
if original_counts is not None:
if not cls.numpy.array_equal(offsets[1:] - starts, original_counts):
raise ValueError("jagged structure of index does not match jagged structure derived from localindex")
return cls.fromoffsets(offsets, content)
@classmethod
def fromjagged(cls, jagged):
return cls(jagged._starts, jagged._stops, jagged._content)
@classmethod
def fromregular(cls, regular):
regular = cls._util_toarray(regular, cls.DEFAULTTYPE, cls.numpy.ndarray)
shape = regular.shape
if len(shape) <= 1:
raise ValueError("regular array must have more than one dimension")
out = regular.reshape(-1)
for x in shape[:0:-1]:
out = cls.fromfolding(out, x)
return out
@classmethod
def fromfolding(cls, content, size):
content = cls._util_toarray(content, cls.DEFAULTTYPE)
quotient = -(-len(content) // size)
offsets = cls.numpy.arange(0, quotient * size + 1, size, dtype=cls.INDEXTYPE)
if len(offsets) > 0:
offsets[-1] = len(content)
return cls.fromoffsets(offsets, content)
def copy(self, starts=None, stops=None, content=None):
out = self.__class__.__new__(self.__class__)
out._starts = self._starts
out._stops = self._stops
out._content = self._content
out._offsets = self._offsets
out._counts = self._counts
out._parents = self._parents
out._isvalid = self._isvalid
if starts is not None:
out.starts = starts
if stops is not None:
out.stops = stops
if content is not None:
out.content = content
return out
def deepcopy(self, starts=None, stops=None, content=None):
out = self.copy(starts=starts, stops=stops, content=content)
out._starts = self._util_deepcopy(out._starts)
out._stops = self._util_deepcopy(out._stops)
out._content = self._util_deepcopy(out._content)
out._offsets = self._util_deepcopy(out._offsets)
out._counts = self._util_deepcopy(out._counts)
out._parents = self._util_deepcopy(out._parents)
return out
def empty_like(self, **overrides):
if isinstance(self._content, self.numpy.ndarray):
return self.copy(content=self.numpy.empty_like(self._content))
else:
return self.copy(content=self._content.empty_like(**overrides))
def zeros_like(self, **overrides):
if isinstance(self._content, self.numpy.ndarray):
return self.copy(content=self.numpy.zeros_like(self._content))
else:
return self.copy(content=self._content.zeros_like(**overrides))
def ones_like(self, **overrides):
if isinstance(self._content, self.numpy.ndarray):
return self.copy(content=self.numpy.ones_like(self._content))
else:
return self.copy(content=self._content.ones_like(**overrides))
def __awkward_serialize__(self, serializer):
if self._canuseoffset() and len(self) > 0:
return serializer.encode_call(
["awkward", "JaggedArray", "fromcounts"],
serializer(self.counts, "JaggedArray.counts"),
serializer(self._content[self._starts[0]:self._stops[-1]], "JaggedArray.content"),
)
else:
return serializer.encode_call(
["awkward", "JaggedArray"],
serializer(self._starts, "JaggedArray.starts"),
serializer(self._stops, "JaggedArray.stops"),
serializer(self._content, "JaggedArray.content"),
)
@property
def starts(self):
return self._starts
@starts.setter
def starts(self, value):
value = self._util_toarray(value, self.INDEXTYPE, self.numpy.ndarray)
if self.check_prop_valid:
if not self._util_isintegertype(value.dtype.type):
raise TypeError("starts must have integer dtype")
if len(value.shape) == 0:
raise ValueError("starts must have at least one dimension")
if (value < 0).any():
raise ValueError("starts must be a non-negative array")
self._starts = value
self._offsets, self._counts, self._parents = None, None, None
self._isvalid = False
@property
def stops(self):
if len(self._stops) == len(self._starts):
return self._stops
else:
return self._stops[:len(self._starts)]
@stops.setter
def stops(self, value):
value = self._util_toarray(value, self.INDEXTYPE, self.numpy.ndarray)
if self.check_prop_valid:
if not self._util_isintegertype(value.dtype.type):
raise TypeError("stops must have integer dtype")
if len(value.shape) == 0:
raise ValueError("stops must have at least one dimension")
if (value < 0).any():
raise ValueError("stops must be a non-negative array")
self._stops = value
self._offsets, self._counts, self._parents = None, None, None
self._isvalid = False
@property
def content(self):
return self._content
@content.setter
def content(self, value):
self._content = self._util_toarray(value, self.DEFAULTTYPE)
self._isvalid = False
@property
def offsets(self):
if self._offsets is None:
self._valid()
if self.offsetsaliased(self._starts, self._stops):
self._offsets = self._starts.base
elif len(self._starts.shape) == 1 and self.numpy.array_equal(self._starts[1:], self._stops[:-1]):
if len(self._stops) == 0:
return self.numpy.array([0], dtype=self.INDEXTYPE)
else:
self._offsets = self.numpy.append(self._starts, self._stops[-1])
else:
raise ValueError("starts and stops are not compatible with a single offsets array")
return self._offsets
@offsets.setter
def offsets(self, value):
value = self._util_toarray(value, self.INDEXTYPE, self.numpy.ndarray)
if self.check_prop_valid:
if not self._util_isintegertype(value.dtype.type):
raise TypeError("offsets must have integer dtype")
if len(value.shape) != 1 or (value < 0).any():
raise ValueError("offsets must be a one-dimensional, non-negative array")
if len(value) == 0:
raise ValueError("offsets must be non-empty")
self._starts = value[:-1]
self._stops = value[1:]
self._offsets = value
self._counts, self._parents = None, None
self._isvalid = False
@property
def counts(self):
if self._counts is None:
self._valid()
self._counts = self.stops - self._starts
return self._counts
@counts.setter
def counts(self, value):
value = self._util_toarray(value, self.INDEXTYPE, self.numpy.ndarray)
if self.check_prop_valid:
if not self._util_isintegertype(value.dtype.type):
raise TypeError("counts must have integer dtype")
if len(value.shape) == 0:
raise ValueError("counts must have at least one dimension")
if (value < 0).any():
raise ValueError("counts must be a non-negative array")
offsets = self.counts2offsets(value.reshape(-1))
self._starts = offsets[:-1].reshape(value.shape)
self._stops = offsets[1:].reshape(value.shape)
self._offsets = offsets if len(value.shape) == 1 else None
self._counts = value
self._parents = None
self._isvalid = False
@property
def parents(self):
if self._parents is None:
self._valid()
if self._canuseoffset():
self._parents = self.offsets2parents(self.offsets)
else:
self._parents = self.startsstops2parents(self._starts, self._stops)
return self._parents
@parents.setter
def parents(self, value):
value = self._util_toarray(value, self.INDEXTYPE, self.numpy.ndarray)
if self.check_prop_valid:
if not self._util_isintegertype(value.dtype.type):
raise TypeError("parents must have integer dtype")
if len(value.shape) == 0:
raise ValueError("parents must have at least one dimension")
self._starts, self._stops = self.parents2startsstops(value)
self._offsets, self._counts = None, None
self._parents = value
@property
def localindex(self):
if len(self) == 0:
return self.JaggedArray([], [], self.numpy.array([], dtype=self.INDEXTYPE))
elif self._canuseoffset():
out = self.numpy.arange(self.offsets[0], self.offsets[-1], dtype=self.INDEXTYPE)
out -= self.offsets[self.parents[self.parents >= 0]]
return self.JaggedArray.fromoffsets(self.offsets - self.offsets[0], out)
else:
counts = self.counts.reshape(-1) # flatten in case multi-d jagged
offsets = self.counts2offsets(counts)
out = self.numpy.arange(offsets[-1], dtype=self.INDEXTYPE)
out -= self.numpy.repeat(offsets[:-1], awkward.util.windows_safe(counts))
return self.JaggedArray(offsets[:-1].reshape(self.shape), offsets[1:].reshape(self.shape), out)
def _getnbytes(self, seen):
if id(self) in seen:
return 0
else:
seen.add(id(self))
if self.offsetsaliased(self._starts, self._stops):
return self._starts.base.nbytes + (self._content.nbytes if isinstance(self._content, self.numpy.ndarray) else self._content._getnbytes(seen))
else:
return self._starts.nbytes + self._stops.nbytes + (self._content.nbytes if isinstance(self._content, self.numpy.ndarray) else self._content._getnbytes(seen))
def __len__(self):
return len(self._starts)
def _gettype(self, seen):
return awkward.type.ArrayType(*(self._starts.shape[1:] + (self.numpy.inf, awkward.type._fromarray(self._content, seen))))
def _util_layout(self, position, seen, lookup):
awkward.type.LayoutNode(self._starts, position + (0,), seen, lookup)
awkward.type.LayoutNode(self._stops, position + (1,), seen, lookup)
awkward.type.LayoutNode(self._content, position + (2,), seen, lookup)
return (awkward.type.LayoutArg("starts", position + (0,)),
awkward.type.LayoutArg("stops", position + (1,)),
awkward.type.LayoutArg("content", position + (2,)))
def _valid(self):
if not self._isvalid:
if self.offsetsaliased(self._starts, self._stops):
self._offsets = self._starts.base
if self.check_whole_valid:
if not (self._offsets[1:] >= self._offsets[:-1]).all():
raise ValueError("offsets must be monatonically increasing")
if self._offsets.max() > len(self._content):
raise ValueError("maximum offset {0} is beyond the length of the content ({1})".format(self._offsets.max(), len(self._content)))
else:
if self.check_whole_valid:
self._validstartsstops(self._starts, self._stops)
nonempty = (self._starts != self._stops)
starts = self._starts[nonempty].reshape(-1)
if self.check_whole_valid:
if len(starts) != 0 and starts.reshape(-1).max() >= len(self._content):
raise ValueError("maximum start ({0}) is at or beyond the length of the content ({1})".format(starts.reshape(-1).max(), len(self._content)))
stops = self._stops[nonempty].reshape(-1)
if self.check_whole_valid:
if len(stops) != 0 and stops.reshape(-1).max() > len(self._content):
raise ValueError("maximum stop ({0}) is beyond the length of the content ({1})".format(self._stops.reshape(-1).max(), len(self._content)))
self._isvalid = True
@classmethod
def _validstartsstops(cls, starts, stops):
if cls.check_whole_valid:
if len(starts) > len(stops):
raise ValueError("starts must have the same (or shorter) length than stops")
if starts.shape[1:] != stops.shape[1:]:
raise ValueError("starts and stops must have the same dimensionality (shape[1:])")
if not (stops[:len(starts)] >= starts).all():
raise ValueError("stops must be greater than or equal to starts")
def __iter__(self, checkiter=True):
if checkiter:
self._checkiter()
self._valid()
if len(self._starts.shape) != 1:
for x in super(JaggedArray, self).__iter__(checkiter=checkiter):
yield x
else:
stops = self._stops
content = self._content
for i, start in enumerate(self._starts):
yield content[start:stops[i]]
def __getitem__(self, where):
self._valid()
if self._util_isstringslice(where):
content = self._content[where]
cls = awkward.array.objects.Methods.maybemixin(type(content), self.JaggedArray)
out = cls.__new__(cls)
out.__dict__.update(self.__dict__)
out._content = content
out.__doc__ = content.__doc__
return out
if isinstance(where, tuple) and len(where) == 0:
return self
if not isinstance(where, tuple):
where = (where,)
head, tail = where[:len(self._starts.shape)], where[len(self._starts.shape):]
if len(head) == 1 and isinstance(head[0], JaggedArray):
head = head[0]
if isinstance(self._content, JaggedArray) and isinstance(head._content, JaggedArray):
return self.copy(content=self._content[head._content])
elif self._util_isintegertype(head._content.dtype.type):
if len(head.shape) == 1 and head._starts.shape != self._starts.shape:
raise ValueError("jagged array used as index has a different shape {0} from the jagged array it is selecting from {1}".format(head._starts.shape, self._starts.shape))
headoffsets = self.counts2offsets(head.counts)
head = head._tojagged(headoffsets[:-1], headoffsets[1:], copy=False)
counts = head.tojagged(self.counts)._content
indexes = self.numpy.array(head._content[:headoffsets[-1]], dtype=self.INDEXTYPE, copy=True)
negatives = (indexes < 0)
indexes[negatives] += counts[negatives]
if not self.numpy.bitwise_and(0 <= indexes, indexes < counts).all():
raise IndexError("jagged array used as index contains out-of-bounds values")
indexes += head.tojagged(self._starts)._content
return self.copy(starts=head._starts, stops=head._stops, content=self._content[indexes])
elif len(head.shape) == 1 and issubclass(head._content.dtype.type, (self.numpy.bool, self.numpy.bool_)):
try:
offsets = self.offsets
thyself = self
except ValueError:
offsets = self.counts2offsets(self.counts.reshape(-1))
thyself = self._tojagged(offsets[:-1], offsets[1:], copy=False)
thyself._starts.shape = self._starts.shape
thyself._stops.shape = self._stops.shape
head = head._tojagged(thyself._starts, thyself._stops, copy=False)
inthead = head.copy(content=head._content.astype(self.INDEXTYPE))
intheadsum = inthead.sum()
offsets = self.counts2offsets(intheadsum)
headcontent = self.numpy.array(head._content, dtype=self.BOOLTYPE)
headcontent_indices_to_ignore = self.numpy.resize(head.parents < 0, headcontent.shape)
headcontent_indices_to_ignore[len(head.parents):] = True
headcontent[headcontent_indices_to_ignore] = False
original_headcontent_length = len(headcontent)
headcontent = self.numpy.resize(headcontent, thyself._content.shape)
headcontent[original_headcontent_length:] = False
return self.copy(starts=offsets[:-1].reshape(intheadsum.shape), stops=offsets[1:].reshape(intheadsum.shape), content=thyself._content[headcontent])
elif head.shape == self.shape and issubclass(head._content.dtype.type, (self.numpy.bool, self.numpy.bool_)):
index = self.localindex + self.starts
flatindex = index.flatten()[head.flatten()]
return type(self).fromcounts(head.sum(), self._content[flatindex])
else:
raise TypeError("jagged index must be boolean (mask) or integer (fancy indexing)")
else:
starts = self._starts[head]
stops = self._stops[head]
if len(starts.shape) == len(stops.shape) == 0:
return self._content[starts:stops][tail]
else:
node = self.copy(starts=starts, stops=stops)
head = head[-1]
nslices = 0
while isinstance(node, JaggedArray) and len(tail) > 0:
wasslice = isinstance(head, slice)
head, tail = tail[0], tail[1:]
original_head = head
if self._util_isinteger(head):
stack = []
for x in range(nslices):
stack.insert(0, node.counts)
node = node.flatten()
if isinstance(node, JaggedArray):
counts = node.stops - node._starts
if head < 0:
head = counts + head
if not self.numpy.bitwise_and(0 <= head, head < counts).all():
raise IndexError("index {0} is out of bounds for jagged min size {1}".format(original_head, counts.min()))
node = node._content[node._starts + head]
else:
node = node[:, head]
for oldcounts in stack:
node = type(self).fromcounts(oldcounts, node)
elif isinstance(head, slice):
nslices += 1
if nslices >= 2:
raise NotImplementedError("this implementation cannot slice a JaggedArray in more than two dimensions")
# If we sliced down to an empty jagged array, take a shortcut
if len(node) == 0:
return node
counts = node.stops - node._starts
step = 1 if head.step is None else head.step
if step == 0:
raise ValueError("slice step cannot be zero")
elif step > 0:
if head.start is None:
starts = self.numpy.zeros(counts.shape, dtype=self.INDEXTYPE)
elif head.start >= 0:
starts = self.numpy.minimum(counts, head.start)
else:
starts = self.numpy.maximum(0, self.numpy.minimum(counts, counts + head.start))
if head.stop is None:
stops = counts
elif head.stop >= 0:
stops = self.numpy.minimum(counts, head.stop)
else:
stops = self.numpy.maximum(0, self.numpy.minimum(counts, counts + head.stop))
stops = self.numpy.maximum(starts, stops)
start = starts.min()
stop = stops.max()
indexes = self.numpy.empty((len(node), abs(stop - start)), dtype=self.INDEXTYPE)
indexes[:, :] = self.numpy.arange(start, stop)
mask = indexes >= starts.reshape((len(node), 1))
self.numpy.bitwise_and(mask, indexes < stops.reshape((len(node), 1)), out=mask)
if step != 1:
self.numpy.bitwise_and(mask, self.numpy.remainder(indexes - starts.reshape((len(node), 1)), step) == 0, out=mask)
else:
if head.start is None:
starts = counts - 1
elif head.start >= 0:
starts = self.numpy.minimum(counts - 1, head.start)
else:
starts = self.numpy.maximum(-1, self.numpy.minimum(counts - 1, counts + head.start))
if head.stop is None:
stops = self.numpy.full(counts.shape, -1, dtype=self.INDEXTYPE)
elif head.stop >= 0:
stops = self.numpy.minimum(counts - 1, head.stop)
else:
stops = self.numpy.maximum(-1, self.numpy.minimum(counts - 1, counts + head.stop))
stops = self.numpy.minimum(starts, stops)
start = starts.max()
stop = stops.min()
indexes = self.numpy.empty((len(node), abs(stop - start)), dtype=self.INDEXTYPE)
indexes[:, :] = self.numpy.arange(start, stop, -1)
mask = indexes <= starts.reshape((len(node), 1))
self.numpy.bitwise_and(mask, indexes > stops.reshape((len(node), 1)), out=mask)
if step != -1:
self.numpy.bitwise_and(mask, self.numpy.remainder(indexes - starts.reshape((len(node), 1)), step) == 0, out=mask)
newcounts = self.numpy.count_nonzero(mask, axis=1)
newoffsets = self.counts2offsets(newcounts.reshape(-1))
newcontent = node._content[(indexes + node._starts.reshape((len(node), 1)))[mask]]
node = node.copy(starts=newoffsets[:-1], stops=newoffsets[1:], content=newcontent)
else:
head = self.numpy.array(head, copy=False)
if len(head.shape) == 1 and self._util_isintegertype(head.dtype.type):
if wasslice:
stack = []
for x in range(nslices):
stack.insert(0, node.counts)
node = node.flatten()
index = self.numpy.tile(head, len(node))
mask = (index < 0)
if mask.any():
pluscounts = (index.reshape(-1, len(head)) + node.counts.reshape(-1, 1)).reshape(-1)
index[mask] = pluscounts[mask]
if (index < 0).any() or (index.reshape(-1, len(head)) >= node.counts.reshape(-1, 1)).any():
raise IndexError("index in jagged subdimension is out of bounds")
index = (index.reshape(-1, len(head)) + node._starts.reshape(-1, 1)).reshape(-1)
node = node._content[index]
if isinstance(node, JaggedArray):
node._starts = node._starts.reshape(-1, len(head))
node._stops = node._stops.reshape(-1, len(head))
elif isinstance(node, self.numpy.ndarray):
node = node.reshape(-1, len(head))
else:
raise NotImplementedError
for oldcounts in stack:
node = type(self).fromcounts(oldcounts, node)
else:
if len(node) != len(head):
raise IndexError("shape mismatch: indexing arrays could not be broadcast together with shapes {0} {1}".format(len(node), len(head)))
index = head.copy() if head is original_head else head
mask = (index < 0)
if mask.any():
index[mask] += head.counts
if (index < 0).any() or (index >= node.counts).any():
raise IndexError("index in jagged subdimension is out of bounds")
index += node._starts
node = node._content[index]
elif len(head.shape) == 1 and issubclass(head.dtype.type, (self.numpy.bool, self.numpy.bool_)):
if wasslice:
stack = []
for x in range(nslices):
stack.insert(0, node.counts)
node = node.flatten()
if len(node) != 0 and not (node.counts == len(head)).all():
raise IndexError("jagged subdimension is not regular and cannot match boolean shape {0}".format(len(head)))
head = self.numpy.nonzero(head)[0]
index = self.numpy.tile(head, len(node))
index = (index.reshape(-1, len(node)) + node._starts.reshape(-1, 1)).reshape(-1)
node = node._content[index]
if isinstance(node, JaggedArray):
node._starts = node._starts.reshape(-1, len(head))
node._stops = node._stops.reshape(-1, len(head))
elif isinstance(node, self.numpy.ndarray):
node = node.reshape(-1, len(head))
else:
raise NotImplementedError
for oldcounts in stack:
node = type(self).fromcounts(oldcounts, node)
else:
index = self.numpy.nonzero(head)[0]
if len(node) != len(index):
raise IndexError("shape mismatch: indexing arrays could not be broadcast together with shapes {0} {1}".format(len(node), len(index)))
index += node._starts
node = node._content[index]
else:
raise TypeError("cannot interpret shape {0}, dtype {1} as a fancy index or mask".format(head.shape, head.dtype))
if isinstance(node, self.numpy.ndarray) and len(node.shape) < sum(0 if isinstance(x, slice) else 1 for x in tail):
raise IndexError("IndexError: too many indices for array")
return node[tail]
def __setitem__(self, where, what):
if isinstance(where, awkward.util.string):
self._content[where] = self.tojagged(what)._content
elif self._util_isstringslice(where):
what = what.unzip()
if len(where) != len(what):
raise ValueError("number of keys ({0}) does not match number of provided arrays ({1})".format(len(where), len(what)))
for x, y in zip(where, what):
self._content[x] = self.tojagged(y)._content
elif isinstance(where, JaggedArray):
if isinstance(what, JaggedArray):
what = what.flatten()
if len(where.shape) == 1:
if where._starts.shape != self._starts.shape:
raise ValueError("jagged array used as index has a different shape {0} from the jagged array it is selecting from {1}".format(where._starts.shape, self._starts.shape))
elif where.shape != self.shape:
raise ValueError("jagged array used as index has a different shape {0} from the jagged array it is selecting from {1}".format(where._starts.shape, self._starts.shape))
if self._util_isintegertype(where._content.dtype.type):
whereoffsets = self.counts2offsets(where.counts)
where = where._tojagged(whereoffsets[:-1], whereoffsets[1:], copy=False)
counts = where.tojagged(self.counts)._content
indexes = self.numpy.array(where._content[:whereoffsets[-1]], copy=True)
negatives = (indexes < 0)
indexes[negatives] += counts[negatives]
if not self.numpy.bitwise_and(0 <= indexes, indexes < counts).all():
raise IndexError("jagged array used as index contains out-of-bounds values")
indexes += where.tojagged(self._starts)._content
self._content[indexes] = what
elif issubclass(where._content.dtype.type, (self.numpy.bool, self.numpy.bool_)):
index = self.localindex + self.starts
flatindex = index.flatten()[where.flatten()]
self._content[flatindex] = what
else:
raise TypeError("jagged index must be boolean (mask) or integer (fancy indexing)")
else:
raise TypeError("invalid index for assigning to JaggedArray: {0}".format(where))
def tojagged(self, data):
if isinstance(data, JaggedArray):
selfcounts = self.stops - self._starts
datacounts = data.stops - data._starts
if not self.numpy.array_equal(selfcounts, datacounts):
raise ValueError("cannot broadcast JaggedArray to match JaggedArray with a different counts")
if len(self._starts) == 0:
return self.copy(content=data._content)
tmp = self.compact()
tmpparents = self.offsets2parents(tmp.offsets)
index = self.JaggedArray(tmp._starts, tmp._stops, (self.numpy.arange(tmp._stops[-1], dtype=self.INDEXTYPE) - tmp._starts[tmpparents]))
data = data.compact()
return self.copy(content=data._content[self.IndexedArray.invert((index + self._starts)._content)])
elif isinstance(data, awkward.array.base.AwkwardArray):
if len(self._starts) != len(data):
raise ValueError("cannot broadcast AwkwardArray to match JaggedArray with a different length")
if len(self._starts) == 0:
return self.copy(content=data)
out = self.copy(content=data[self.parents])
out._parents = self.parents
return out
elif isinstance(data, self.numpy.ndarray):
content = self.numpy.empty(len(self.parents), dtype=data.dtype)
if len(data.shape) == 0 or (len(data.shape) == 1 and data.shape[0] == 1):
content[:] = data
else:
good = (self.parents >= 0)
content[good] = data[self.parents[good]]
out = self.copy(content=content)
out._parents = self.parents
return out
elif isinstance(data, Iterable):
return self.tojagged(self.numpy.array(data))
else:
return self.tojagged(self.numpy.array([data]))
def _tojagged(self, starts=None, stops=None, copy=True):
if starts is None and stops is None:
if copy:
starts, stops = self._util_deepcopy(self._starts), self._util_deepcopy(self._stops)
else:
starts, stops = self._starts, self._stops
elif stops is None:
starts = self._util_toarray(starts, self.INDEXTYPE)
if len(self) != len(starts):
raise ValueError("cannot fit JaggedArray of length {0} into starts of length {1}".format(len(self), len(starts)))
stops = starts + self.counts
if (stops[:-1] > starts[1:]).any():
raise ValueError("cannot fit contents of JaggedArray into the given starts array")
elif starts is None:
stops = self._util_toarray(stops, self.INDEXTYPE)
if len(self) != len(stops):
raise ValueError("cannot fit JaggedArray of length {0} into stops of length {1}".format(len(self), len(stops)))
starts = stops - self.counts
if (stops[:-1] > starts[1:]).any():
raise ValueError("cannot fit contents of JaggedArray into the given stops array")
else:
if not self.numpy.array_equal(stops - starts, self.counts):
raise ValueError("cannot fit contents of JaggedArray into the given starts and stops arrays")
self._validstartsstops(starts, stops)
if not copy and starts is self._starts and stops is self._stops:
return self
elif (starts is self._starts or self.numpy.array_equal(starts, self._starts)) and (stops is self._stops or self.numpy.array_equal(stops, self._stops)):
return self.copy(starts=starts, stops=stops, content=(self._util_deepcopy(self._content) if copy else self._content))
else:
if self.offsetsaliased(starts, stops):
parents = self.offsets2parents(starts.base)
elif len(starts.shape) == 1 and self.numpy.array_equal(starts[1:], stops[:-1]):
if len(stops) == 0:
offsets = self.numpy.array([0], dtype=self.INDEXTYPE)
else:
offsets = self.numpy.append(starts, stops[-1])
parents = self.offsets2parents(offsets)
else:
parents = self.startsstops2parents(starts, stops)
good = (parents >= 0)
increase = self.numpy.arange(len(parents), dtype=self.INDEXTYPE)
increase[good] -= increase[starts[parents[good]]]
index = self._starts[parents]
index += increase
index *= good
out = self.copy(starts=starts, stops=stops, content=self._content[index])
out._parents = parents
return out
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
import awkward.array.objects
import awkward.array.table
if "out" in kwargs:
raise NotImplementedError("in-place operations not supported")
if method != "__call__":
return NotImplemented
starts, stops = None, None
for i in range(len(inputs)):
if isinstance(inputs[i], JaggedArray):
try:
offsets = inputs[i].offsets # calls _valid()
except ValueError:
counts = inputs[i].counts
offsets = self.counts2offsets(counts.reshape(-1))
starts, stops = offsets[:-1], offsets[1:]
starts = starts.reshape(counts.shape)
stops = stops.reshape(counts.shape)
else:
starts, stops = offsets[:-1], offsets[1:]
assert starts is not None and stops is not None
inputs = list(inputs)
for i in range(len(inputs)):
if isinstance(inputs[i], JaggedArray):
inputs[i] = inputs[i]._tojagged(starts, stops, copy=False)
elif isinstance(inputs[i], (self.numpy.ndarray, awkward.array.base.AwkwardArray)):
pass
else:
try:
for first in inputs[i]:
break
except TypeError:
pass
else:
if "first" not in locals() or isinstance(first, (numbers.Number, self.numpy.bool_, self.numpy.bool, self.numpy.number)):
inputs[i] = self.numpy.array(inputs[i], copy=False)
else:
inputs[i] = self.JaggedArray.fromiter(inputs[i])
for jaggedarray in inputs:
if isinstance(jaggedarray, JaggedArray):
starts, stops, parents, good = jaggedarray._starts, jaggedarray._stops, None, None
break
else:
assert False
for i in range(len(inputs)):
if isinstance(inputs[i], (self.numpy.ndarray, awkward.array.base.AwkwardArray)) and not isinstance(inputs[i], JaggedArray):
data = self._util_toarray(inputs[i], inputs[i].dtype)
if starts.shape != data.shape:
raise ValueError("cannot broadcast JaggedArray of shape {0} with array of shape {1}".format(starts.shape, data.shape))
if parents is None:
parents = jaggedarray.parents
if self._canuseoffset() and len(jaggedarray.starts) > 0 and jaggedarray.starts[0] == 0:
good = None
else:
good = (parents >= 0)