-
Notifications
You must be signed in to change notification settings - Fork 74
/
containers.py
1933 lines (1583 loc) · 63 KB
/
containers.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/uproot5/blob/main/LICENSE
"""
This module interpretations and models for standard containers, such as
``std::vector`` and simple arrays.
See :doc:`uproot.interpretation` and :doc:`uproot.model`.
"""
from __future__ import annotations
import struct
import types
from collections.abc import KeysView, Mapping, Sequence, Set, ValuesView
import numpy
import uproot
import uproot._awkwardforth
_stl_container_size = struct.Struct(">I")
_stl_object_type = numpy.dtype(object)
def _content_typename(content):
if isinstance(content, numpy.dtype):
return uproot.interpretation.numerical._dtype_kind_itemsize_to_typename[
content.kind, content.itemsize
]
elif isinstance(content, type):
return uproot.model.classname_decode(content.__name__)[0]
else:
return content.typename
def _content_cache_key(content):
if isinstance(content, numpy.dtype):
bo = uproot.interpretation.numerical._numpy_byteorder_to_cache_key[
content.byteorder
]
return f"{bo}{content.kind}{content.itemsize}"
elif isinstance(content, type):
return content.__name__
else:
return content.cache_key
def _read_nested(
model, length, chunk, cursor, context, file, selffile, parent, header=True
):
forth_obj = uproot._awkwardforth.get_forth_obj(context)
if isinstance(model, numpy.dtype):
symbol = uproot._awkwardforth.dtype_to_struct.get(model)
if forth_obj is not None and symbol is None:
raise uproot.interpretation.objects.CannotBeForth()
if forth_obj is not None:
key = uproot._awkwardforth.get_first_key_number(context)
forth_stash = uproot._awkwardforth.Node(
f"node{key}",
form_details={
"class": "NumpyArray",
"primitive": uproot._awkwardforth.struct_to_dtype_name[symbol],
"form_key": f"node{key}",
},
)
forth_stash.header_code.append(
f"output node{key}-data {uproot._awkwardforth.struct_to_dtype_name[symbol]}\n"
)
forth_stash.pre_code.append(f"stream #!{symbol}-> node{key}-data\n")
forth_obj.add_node(forth_stash)
return cursor.array(chunk, length, model, context)
else:
values = numpy.empty(length, dtype=_stl_object_type)
if forth_obj is not None:
# These two attributes in ForthGenerator need to be the same each iteration, but are changed in .read()
original_model = forth_obj.active_node
for i in range(length):
if forth_obj is not None:
forth_obj.set_active_node(original_model)
if isinstance(model, AsContainer):
values[i] = model.read(
chunk,
cursor,
context,
file,
selffile,
parent,
header=header,
)
else:
values[i] = model.read(
chunk,
cursor,
context,
file,
selffile,
parent,
)
return values
def _tostring(value):
if isinstance(value, str):
return repr(value)
else:
return str(value)
def _str_with_ellipsis(tostring, length, lbracket, rbracket, limit):
leftlen = len(lbracket)
rightlen = len(rbracket)
left, right, i, j, done = [], [], 0, length - 1, False
while True:
if i > j:
done = True
break
x = tostring(i) + ("" if i == length - 1 else ", ")
i += 1
dotslen = 0 if i > j else 5
if leftlen + rightlen + len(x) + dotslen > limit:
break
left.append(x)
leftlen += len(x)
if i > j:
done = True
break
y = tostring(j) + ("" if j == length - 1 else ", ")
j -= 1
dotslen = 0 if i > j else 5
if leftlen + rightlen + len(y) + dotslen > limit:
break
right.insert(0, y)
rightlen += len(y)
if length == 0:
return lbracket + rbracket
elif done:
return lbracket + "".join(left) + "".join(right) + rbracket
elif len(left) == len(right) == 0:
return lbracket + f"{tostring(0)}, ..." + rbracket
elif len(right) == 0:
return lbracket + "".join(left) + "..." + rbracket
else:
return lbracket + "".join(left) + "..., " + "".join(right) + rbracket
class AsContainer:
"""
Abstract class for all descriptions of data as containers, such as
``std::vector``.
Note that these are not :doc:`uproot.interpretation.Interpretation`
objects, since they are recursively nestable and have a ``read``
instance method like :doc:`uproot.model.Model`'s ``read`` classmethod.
A nested tree of :doc:`uproot.containers.AsContainer` instances and
:doc:`uproot.model.Model` class objects may be the ``model`` argument
of a :doc:`uproot.interpretation.objects.AsObjects`.
"""
@property
def cache_key(self):
"""
String that uniquely specifies this container, to use as part of
an array's cache key.
"""
raise AssertionError
@property
def typename(self):
"""
String that describes this container as a C++ type.
This type might not exactly correspond to the type in C++, but it would
have equivalent meaning.
"""
raise AssertionError
def awkward_form(self, file, context):
"""
Args:
file (:doc:`uproot.reading.CommonFileMethods`): The file associated
with this interpretation's ``TBranch``.
context (dict): Context for the Form-generation; defaults are
the remaining arguments below.
index_format (str): Format to use for indexes of the
``awkward.forms.Form``; may be ``"i32"``, ``"u32"``, or
``"i64"``.
header (bool): If True, include header fields of each C++ class.
tobject_header (bool): If True, include header fields of each ``TObject``
base class.
breadcrumbs (tuple of class objects): Used to check for recursion.
Types that contain themselves cannot be Awkward Arrays because the
depth of instances is unknown.
The ``awkward.forms.Form`` to use to put objects of type type in an
Awkward Array.
"""
raise AssertionError
def strided_interpretation(
self, file, header=False, tobject_header=True, breadcrumbs=(), original=None
):
"""
Args:
file (:doc:`uproot.reading.ReadOnlyFile`): File to use to generate
:doc:`uproot.model.Model` classes from its
:ref:`uproot.reading.ReadOnlyFile.streamers` and ``file_path``
for error messages.
header (bool): If True, assume the outermost object has a header.
tobject_header (bool): If True, assume that ``TObjects`` have headers.
breadcrumbs (tuple of class objects): Used to check for recursion.
Types that contain themselves cannot be strided because the
depth of instances is unknown.
original (None, :doc:`uproot.model.Model`, or :doc:`uproot.containers.Container`): The
original, non-strided model or container.
Returns a list of (str, ``numpy.dtype``) pairs to build a
:doc:`uproot.interpretation.objects.AsStridedObjects` interpretation.
"""
raise uproot.interpretation.objects.CannotBeStrided(self.typename)
@property
def header(self):
"""
If True, assume this container has a header.
"""
return self._header
@header.setter
def header(self, value):
if value is True or value is False:
self._header = value
else:
raise TypeError(f"{type(self).__name__}.header must be True or False")
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
cursor (:doc:`uproot.source.cursor.Cursor`): Current position in
that ``chunk``.
context (dict): Auxiliary data used in deserialization.
file (:doc:`uproot.reading.ReadOnlyFile`): An open file object,
capable of generating new :doc:`uproot.model.Model` classes
from its :ref:`uproot.reading.ReadOnlyFile.streamers`.
selffile (:doc:`uproot.reading.CommonFileMethods`): A possibly
:doc:`uproot.reading.DetachedFile` associated with this object.
parent (None or calling object): The previous ``read`` in the
recursive descent.
header (bool): If True, enable the container's
:ref:`uproot.containers.AsContainer.header`.
Read one object as part of a recursive descent.
"""
raise AssertionError
def __eq__(self, other):
raise AssertionError
def __ne__(self, other):
return not self == other
class AsDynamic(AsContainer):
"""
Args:
model (None, :doc:`uproot.model.Model`, or :doc:`uproot.containers.Container`): Optional
description of the data, used in
:ref:`uproot.containers.AsDynamic.awkward_form` but ignored in
:ref:`uproot.containers.AsDynamic.read`.
A :doc:`uproot.containers.AsContainer` for one object whose class may
not be known before reading.
The byte-stream consists of a class name followed by instance data. Only
known use: in ``TBranchObject`` branches.
"""
def __init__(self, model=None):
self._model = model
@property
def model(self):
"""
Optional description of the data, used in
:ref:`uproot.containers.AsDynamic.awkward_form` but ignored in
:ref:`uproot.containers.AsDynamic.read`.
"""
return self._model
def __repr__(self):
if self._model is None:
model = ""
elif isinstance(self._model, type):
model = "model=" + self._model.__name__
else:
model = "model=" + repr(self._model)
return f"AsDynamic({model})"
@property
def cache_key(self):
if self._model is None:
return "AsDynamic(None)"
else:
return f"AsDynamic({_content_cache_key(self._model)})"
@property
def typename(self):
if self._model is None:
return "void*"
else:
return uproot.model.classname_decode(self._model.__name__)[0]
def awkward_form(self, file, context):
uproot.extras.awkward()
if self._model is None:
raise uproot.interpretation.objects.CannotBeAwkward("dynamic type")
else:
return uproot._util.awkward_form(self._model, file, context)
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
# AwkwardForth testing K: test_0637's tests aren't expected to enter here
if uproot._awkwardforth.get_forth_obj(context) is not None:
raise uproot.interpretation.objects.CannotBeForth()
classname = cursor.string(chunk, context)
cursor.skip(1)
cls = file.class_named(classname)
return cls.read(chunk, cursor, context, file, selffile, parent)
class AsFIXME(AsContainer):
"""
Args:
message (str): Required string, prefixes the error message.
A :doc:`uproot.containers.AsContainer` for types that are known to be
unimplemented. The name is intended to be conspicuous, so that such cases
may be more easily fixed.
:ref:`uproot.containers.AsFIXME.read` raises a
:doc:`uproot.deserialization.DeserializationError` asking for a bug-report.
"""
def __init__(self, message):
self.message = message
def __hash__(self):
return hash((AsFIXME, self.message))
def __repr__(self):
return f"AsFIXME({self.message!r})"
@property
def cache_key(self):
return f"AsFIXME({self.message!r})"
@property
def typename(self):
return "unknown"
def awkward_form(self, file, context):
raise uproot.interpretation.objects.CannotBeAwkward(self.message)
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
raise uproot.deserialization.DeserializationError(
self.message + "; please file a bug report!", None, None, None, None
)
def __eq__(self, other):
if isinstance(other, AsFIXME):
return self.message == other.message
else:
return False
class AsString(AsContainer):
"""
Args:
header (bool): Sets the :ref:`uproot.containers.AsContainer.header`.
length_bytes ("1-5" or "4"): Method used to determine the length of
a string: "1-5" means one byte if the length is less than 256,
otherwise the true length is in the next four bytes; "4" means
always four bytes.
typename (None or str): If None, construct a plausible C++ typename.
Otherwise, take the suggestion as given.
A :doc:`uproot.containers.AsContainer` for strings nested withing other
objects.
This is not an :doc:`uproot.interpretation.Interpretation`; it *must* be
nested, at least within :doc:`uproot.interpretation.objects.AsObjects`.
Note that the :doc:`uproot.interpretation.strings.AsStrings` class is
for a ``TBranch`` that contains only strings.
(:ref:`uproot.interpretation.objects.AsObjects.simplify` converts an
:doc:`uproot.interpretation.objects.AsObjects` of
:doc:`uproot.containers.AsString` into a
:doc:`uproot.interpretation.strings.AsStrings`.)
"""
def __init__(self, header, length_bytes="1-5", typename=None):
self.header = header
if length_bytes in ("1-5", "4"):
self._length_bytes = length_bytes
else:
raise ValueError("length_bytes must be '1-5' or '4'")
self._typename = typename
@property
def length_bytes(self):
"""
Method used to determine the length of a string: "1-5" means one byte
if the length is less than 256, otherwise the true length is in the
next four bytes; "4" means always four bytes.
"""
return self._length_bytes
def __hash__(self):
return hash((AsString, self._header, self._length_bytes))
def __repr__(self):
args = [repr(self._header)]
if self._length_bytes != "1-5":
args.append(f"length_bytes={self._length_bytes!r}")
return "AsString({})".format(", ".join(args))
@property
def cache_key(self):
return f"AsString({self._header},{self._length_bytes!r})"
@property
def typename(self):
if self._typename is None:
return "std::string"
else:
return self._typename
def awkward_form(self, file, context):
awkward = uproot.extras.awkward()
return awkward.forms.ListOffsetForm(
context["index_format"],
awkward.forms.NumpyForm("uint8", parameters={"__array__": "char"}),
parameters={"__array__": "string"},
)
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
# AwkwardForth testing L: test_0637's 00,03,25,27,30,33,35,36,38,39,45,47,51,56,57,58,60,61,63,65,68,70,71,72,73,74,75,78,79
forth_obj = uproot._awkwardforth.get_forth_obj(context)
if forth_obj:
context = uproot._awkwardforth.add_to_path(
forth_obj, context, uproot._awkwardforth.SpecialPathItem("string")
)
offsets_num = uproot._awkwardforth.get_first_key_number(context)
data_num = offsets_num + 1
forth_stash = uproot._awkwardforth.Node(
f"node{offsets_num}",
form_details={
"class": "ListOffsetArray",
"offsets": "i64",
"content": {
"class": "NumpyArray",
"primitive": "uint8",
"inner_shape": [],
"parameters": {"__array__": "char"},
"form_key": f"node{data_num}",
},
"parameters": {"__array__": "string"},
"form_key": f"node{offsets_num}",
},
)
if self._header and header:
start_cursor = cursor.copy()
(
num_bytes,
instance_version,
is_memberwise,
) = uproot.deserialization.numbytes_version(chunk, cursor, context)
if forth_obj is not None:
cursor_jump = cursor._index - start_cursor._index
if cursor_jump != 0:
forth_stash.pre_code.append(f"{cursor_jump} stream skip\n")
if self._length_bytes == "1-5":
out = cursor.string(chunk, context)
if forth_obj is not None:
forth_stash.pre_code.append(
f"stream !B-> stack dup 255 = if drop stream !I-> stack then dup node{offsets_num}-offsets +<- stack stream #!B-> node{data_num}-data\n"
)
elif self._length_bytes == "4":
length = cursor.field(chunk, _stl_container_size, context)
out = cursor.string_with_length(chunk, context, length)
if forth_obj is not None:
forth_stash.pre_code.append(
f"stream !I-> stack dup node{offsets_num}-offsets +<- stack stream #B-> node{data_num}-data\n"
)
else:
raise AssertionError(repr(self._length_bytes))
if self._header and header:
uproot.deserialization.numbytes_check(
chunk,
start_cursor,
cursor,
num_bytes,
self.typename,
context,
file.file_path,
)
if forth_obj is not None:
forth_stash.header_code.append(
f"output node{offsets_num}-offsets int64\noutput node{data_num}-data uint8\n"
)
forth_stash.init_code.append(f"0 node{offsets_num}-offsets <- stack\n")
forth_obj.add_node(forth_stash)
return out
def __eq__(self, other):
return (
isinstance(other, AsString)
and self.header == other.header
and self.length_bytes == other.length_bytes
)
class AsPointer(AsContainer):
"""
Args:
pointee (None, :doc:`uproot.model.Model`, or :doc:`uproot.containers.Container`): Optional
description of the data, used in
:ref:`uproot.containers.AsPointer.awkward_form` but ignored in
:ref:`uproot.containers.AsPointer.read`.
A :doc:`uproot.containers.AsContainer` for an object referred to by
pointer, meaning that it could be None (``nullptr``) or identical to
an already-read object.
The deserialization procedure calls
:doc:`uproot.deserialization.read_object_any`.
"""
def __init__(self, pointee=None):
self._pointee = pointee
@property
def pointee(self):
"""
Optional description of the data, used in
:ref:`uproot.containers.AsPointer.awkward_form` but ignored in
:ref:`uproot.containers.AsPointer.read`.
"""
return self._pointee
def __hash__(self):
return hash((AsPointer, self._pointee))
def __repr__(self):
if self._pointee is None:
pointee = ""
elif isinstance(self._pointee, type):
pointee = self._pointee.__name__
else:
pointee = repr(self._pointee)
return f"AsPointer({pointee})"
@property
def cache_key(self):
if self._pointee is None:
return "AsPointer(None)"
else:
return f"AsPointer({_content_cache_key(self._pointee)})"
@property
def typename(self):
if self._pointee is None:
return "void*"
else:
return _content_typename(self._pointee) + "*"
def awkward_form(self, file, context):
raise uproot.interpretation.objects.CannotBeAwkward("arbitrary pointer")
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
# AwkwardForth testing M: test_0637's 29,45,46,49,50 (Awkward Form discovered at read-time)
return uproot.deserialization.read_object_any(
chunk, cursor, context, file, selffile, parent
)
def __eq__(self, other):
if isinstance(other, AsPointer):
return self._pointee == other._pointee
else:
return False
class AsArray(AsContainer):
"""
Args:
header (bool): Sets the :ref:`uproot.containers.AsContainer.header`.
speedbump (bool): If True, one byte must be skipped before reading the
data.
values (:doc:`uproot.model.Model`, :doc:`uproot.containers.Container`, or ``numpy.dtype``): Data
type for data nested in the array.
inner_shape (Optional[Tuple[int]]): Shape not counting first axis, if any
A :doc:`uproot.containers.AsContainer` for simple arrays (not
``std::vector``).
"""
def __init__(self, header, speedbump, values, inner_shape=()):
self._header = header
self._speedbump = speedbump
self._values = values
self._inner_shape = inner_shape
if isinstance(values, numpy.dtype) and inner_shape:
raise RuntimeError("Logic error: the dtype should have contained the shape")
@property
def speedbump(self):
"""
If True, one byte must be skipped before reading the data.
"""
return self._speedbump
@property
def values(self):
"""
Data type for data nested in the array. May be a
:doc:`uproot.model.Model`, :doc:`uproot.containers.Container`, or
``numpy.dtype``.
"""
return self._values
@property
def inner_shape(self):
"""
The shape of possible extra dimensions in this array
"""
return self._inner_shape
def __repr__(self):
if isinstance(self._values, type):
values = self._values.__name__
else:
values = repr(self._values)
return f"AsArray({self.header}, {self.speedbump}, {values}, {self.inner_shape})"
@property
def cache_key(self):
return f"AsArray({self.header},{self.speedbump},{_content_cache_key(self._values)},{self.inner_shape})"
@property
def typename(self):
shape = "".join(f"[{d}]" for d in self.inner_shape)
return _content_typename(self._values) + "[]" + shape
def awkward_form(self, file, context):
awkward = uproot.extras.awkward()
values_form = uproot._util.awkward_form(self._values, file, context)
for dim in reversed(self.inner_shape):
values_form = awkward.forms.RegularForm(values_form, dim)
return awkward.forms.ListOffsetForm(context["index_format"], values_form)
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
# AwkwardForth testing N: test_0637's 01,02,23,24,25,26,27,28,30,51,52
forth_obj = uproot._awkwardforth.get_forth_obj(context)
if forth_obj is not None:
context = uproot._awkwardforth.add_to_path(
forth_obj, context, uproot._awkwardforth.SpecialPathItem("array")
)
offsets_num = uproot._awkwardforth.get_first_key_number(context)
if len(self.inner_shape) > 0:
temp_form = {
"class": "ListOffsetArray",
"offsets": "i64",
"content": {
"class": "RegularArray",
"size": self.inner_shape[0],
},
"parameters": {},
"form_key": f"node{offsets_num}",
}
else:
temp_form = {
"class": "ListOffsetArray",
"offsets": "i64",
"parameters": {},
"form_key": f"node{offsets_num}",
}
forth_stash = uproot._awkwardforth.Node(
f"node{offsets_num}",
form_details=temp_form,
)
if self._header and header:
start_cursor = cursor.copy()
(
num_bytes,
instance_version,
is_memberwise,
) = uproot.deserialization.numbytes_version(chunk, cursor, context)
if is_memberwise:
raise NotImplementedError(
f"""memberwise serialization of {type(self).__name__}
in file {selffile.file_path}"""
)
if forth_obj is not None:
temp_jump = cursor._index - start_cursor._index
if temp_jump != 0:
forth_stash.pre_code.append(f"{temp_jump} stream skip\n")
if isinstance(self._values, numpy.dtype):
remainder = chunk.get(
cursor.index, cursor.index + num_bytes, cursor, context
)
return remainder.view(self._values).reshape(-1, *self.inner_shape)
else:
if forth_obj is not None:
forth_stash.header_code.append(
f"output node{offsets_num}-offsets int64\n"
)
forth_stash.init_code.append(
f"0 node{offsets_num}-offsets <- stack\n"
)
forth_stash.pre_code.append(
"0 bytestops I-> stack \nbegin\ndup stream pos <>\nwhile\nswap 1 + swap\n"
)
if len(self.inner_shape) > 0:
forth_stash.post_code.append(
f"repeat\nswap {self.inner_shape[0]} / node{offsets_num}-offsets +<- stack drop\n"
)
else:
forth_stash.post_code.append(
f"repeat\nswap node{offsets_num}-offsets +<- stack drop\n"
)
forth_obj.add_node(forth_stash)
out = []
while cursor.displacement(start_cursor) < num_bytes:
if forth_obj is not None:
forth_obj.push_active_node(forth_stash)
out.append(
self._values.read(
chunk,
cursor,
uproot._awkwardforth.add_to_path(
forth_obj,
context,
uproot._awkwardforth.SpecialPathItem("item"),
),
file,
selffile,
parent,
)
)
if forth_obj is not None:
forth_obj.pop_active_node()
if self._header and header:
uproot.deserialization.numbytes_check(
chunk,
start_cursor,
cursor,
num_bytes,
self.typename,
context,
file.file_path,
)
return uproot._util.objectarray1d(out).reshape(-1, *self.inner_shape)
else:
if self._speedbump:
if forth_obj is not None:
forth_stash.pre_code.append("1 stream skip\n")
cursor.skip(1)
if isinstance(self._values, numpy.dtype):
remainder = chunk.remainder(cursor.index, cursor, context)
return remainder.view(self._values).reshape(-1, *self.inner_shape)
else:
if forth_obj is not None:
forth_stash.header_code.append(
f"output node{offsets_num}-offsets int64\n"
)
forth_stash.init_code.append(
f"0 node{offsets_num}-offsets <- stack\n"
)
forth_stash.pre_code.append(
"0 bytestops I-> stack \nbegin\ndup stream pos <>\nwhile\nswap 1 + swap\n"
)
if len(self.inner_shape) > 0:
forth_stash.post_code.append(
f"repeat\nswap {self.inner_shape[0]} / node{offsets_num}-offsets +<- stack drop\n"
)
else:
forth_stash.post_code.append(
f"repeat\nswap node{offsets_num}-offsets +<- stack drop\n"
)
forth_obj.add_node(forth_stash)
out = []
while cursor.index < chunk.stop:
if forth_obj is not None:
forth_obj.push_active_node(forth_stash)
out.append(
self._values.read(
chunk,
cursor,
uproot._awkwardforth.add_to_path(
forth_obj,
context,
uproot._awkwardforth.SpecialPathItem("item"),
),
file,
selffile,
parent,
)
)
if forth_obj is not None:
forth_obj.pop_active_node()
return uproot._util.objectarray1d(out).reshape(-1, *self.inner_shape)
class AsVectorLike(AsContainer):
"""
Args:
header (bool): Sets the :ref:`uproot.containers.AsContainer.header`.
values (:doc:`uproot.model.Model` or :doc:`uproot.containers.Container`): Data
type for data nested in the container.
Superclass of :doc:`uproot.containers.AsRVec`, :doc:`uproot.containers.AsVector`,
and :doc:`uproot.containers.AsSet`, which have the same ROOT serialization, but
represent different runtime classes. The purpose of this superclass is just to
consolidate implementations.
"""
def __init__(self, header, values):
self.header = header
if isinstance(self, uproot.containers.AsBitSet):
self._items = numpy.dtype(numpy.bool_)
elif isinstance(values, AsContainer):
self._items = values
elif isinstance(values, type) and issubclass(
values, (uproot.model.Model, uproot.model.DispatchByVersion)
):
self._items = values
else:
self._items = numpy.dtype(values)
def __hash__(self):
return hash((type(self), self._header, self._items))
def __repr__(self):
if isinstance(self._items, type):
values = self._items.__name__
else:
values = repr(self._items)
return f"{type(self).__name__}({self._header}, {values})"
@property
def cache_key(self):
return (
f"{type(self).__name__}({self._header},{_content_cache_key(self._items)})"
)
_form_parameters = {}
def awkward_form(self, file, context):
awkward = uproot.extras.awkward()
return awkward.forms.ListOffsetForm(
context["index_format"],
uproot._util.awkward_form(self._items, file, context),
parameters=self._form_parameters,
)
def read(self, chunk, cursor, context, file, selffile, parent, header=True):
# AwkwardForth testing P: test_0637's 00,03,04,06,07,08,09,10,11,12,13,14,15,16,17,23,24,26,27,28,31,33,36,38,41,42,43,44,45,46,49,50,55,56,57,58,59,60,61,62,63,67,68,72,73,76,77,80
# AwkwardForth testing Q: test_0637's 62,63,64,65,69,70,74,75,77
# AwkwardForth testing O: test_0637's (none for RVec)
forth_obj = uproot._awkwardforth.get_forth_obj(context)
if forth_obj is not None:
context = uproot._awkwardforth.add_to_path(
forth_obj,
context,
uproot._awkwardforth.SpecialPathItem(self._specialpathitem_name),
)
key = uproot._awkwardforth.get_first_key_number(context)
node_key = f"node{key}"
forth_stash = uproot._awkwardforth.Node(
node_key,
form_details={
"class": "ListOffsetArray",
"offsets": "i64",
"parameters": self._form_parameters,
"form_key": node_key,
},
)
if self._header and header:
start_cursor = cursor.copy()
(
num_bytes,
instance_version,
is_memberwise,
) = uproot.deserialization.numbytes_version(chunk, cursor, context)
if forth_obj is not None:
forth_stash.pre_code.append(
f"{cursor._index - start_cursor._index} stream skip\n"
)
else:
is_memberwise = False
# Note: self._items can also be a NumPy dtype, and not necessarily a class
# (e.g. type(self._items) == type)
_value_typename = _content_typename(self._items)
if is_memberwise:
if forth_obj is not None:
raise uproot.interpretation.objects.CannotBeForth()
# FIXME: let's hard-code in logic for std::pair<T1,T2> for now
if not _value_typename.startswith("pair"):
raise NotImplementedError(
f"""memberwise serialization of {type(self).__name__}({_value_typename})
in file {selffile.file_path}"""
)
if not issubclass(self._items, uproot.model.DispatchByVersion):
raise NotImplementedError(
f"""streamerless memberwise serialization of class {type(self).__name__}({_value_typename})
in file {selffile.file_path}"""
)
# uninterpreted header
cursor.skip(6)
length = cursor.field(chunk, _stl_container_size, context)
# no known class version number (maybe in that header? unclear...)
model = self._items.new_class(file, "max")
values = numpy.empty(length, dtype=_stl_object_type)
# only do anything if we have anything to read...
if length > 0:
for i in range(length):
values[i] = model.read(
chunk,
cursor,
dict(context, reading=False),
file,
selffile,
parent,
)
# memberwise reading!
for member_index in range(len(values[0].member_names)):
for i in range(length):
values[i].read_member_n(
chunk, cursor, context, file, member_index
)
else:
length = cursor.field(chunk, _stl_container_size, context)
if forth_obj is not None:
forth_stash.header_code.append(f"output node{key}-offsets int64\n")
forth_stash.init_code.append(f"0 node{key}-offsets <- stack\n")
forth_stash.pre_code.append(
f"stream !I-> stack\n dup node{key}-offsets +<- stack\n"