-
Notifications
You must be signed in to change notification settings - Fork 68
/
model.py
1693 lines (1439 loc) · 64.5 KB
/
model.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 defines utilities for modeling C++ objects as Python objects and the
:doc:`uproot.model.Model` class, which is the superclass of all objects that
are read from ROOT files.
The :doc:`uproot.model.VersionedModel` class is the superclass of all models
whose deserialization routines are specialized by ROOT class version.
A :doc:`uproot.model.DispatchByVersion` subclass selects a versioned model
after reading its version bytes.
The :doc:`uproot.model.UnknownClass` and
:doc:`uproot.model.UnknownClassVersion` are placeholders for data that could
not be modeled, either because the class has no streamer or no streamer for its
version.
"""
from __future__ import annotations
import re
import sys
import threading
import weakref
import numpy
import uproot
bootstrap_classnames = [
"TStreamerInfo",
"TStreamerElement",
"TStreamerArtificial",
"TStreamerBase",
"TStreamerBasicPointer",
"TStreamerBasicType",
"TStreamerLoop",
"TStreamerObject",
"TStreamerObjectAny",
"TStreamerObjectAnyPointer",
"TStreamerObjectPointer",
"TStreamerSTL",
"TStreamerSTLstring",
"TStreamerString",
"TList",
"TObjArray",
"TClonesArray",
"TObjString",
]
never_from_streamers = [
"TString",
"TList",
]
np_uint8 = numpy.dtype("u1")
def bootstrap_classes():
"""
Returns the basic classes that are needed to load other classes (streamers,
TList, TObjArray, TObjString).
"""
import uproot.models.TList
import uproot.models.TObjArray
import uproot.models.TObjString
import uproot.streamers
custom_classes = {}
for classname in bootstrap_classnames:
custom_classes[classname] = uproot.classes[classname]
return custom_classes
def reset_classes():
"""
Removes all classes from ``uproot.classes`` and ``uproot.unknown_classes``
and refills ``uproot.classes`` with original versions of these classes.
"""
from importlib import reload
uproot.classes = {}
uproot.unknown_classes = {}
reload(uproot.streamers)
reload(uproot.models.TObject)
reload(uproot.models.TString)
reload(uproot.models.TArray)
reload(uproot.models.TNamed)
reload(uproot.models.TList)
reload(uproot.models.THashList)
reload(uproot.models.TObjArray)
reload(uproot.models.TObjString)
reload(uproot.models.TAtt)
reload(uproot.models.TDatime)
reload(uproot.models.TRef)
reload(uproot.models.TTable)
reload(uproot.models.TTree)
reload(uproot.models.TBranch)
reload(uproot.models.TLeaf)
reload(uproot.models.TBasket)
reload(uproot.models.RNTuple)
reload(uproot.models.TH)
reload(uproot.models.TGraph)
reload(uproot.models.TMatrixT)
reload(uproot.models.TTime)
_root_alias_to_c_primitive = {
"Bool_t": "bool",
"Char_t": "char",
"UChar_t": "unsigned char",
"Short_t": "short",
"UShort_t": "unsigned short",
"Int_t": "int",
"UInt_t": "unsigned int",
"Long_t": "long",
"ULong_t": "unsigned long",
"Long64_t": "long long",
"ULong64_t": "unsigned long long",
"Size_t": "size_t",
"Float_t": "float",
"Double_t": "double",
"LongDouble_t": "long double",
}
_classname_regularize = re.compile(r"\s*(<|>|,|::)\s*")
_classname_regularize_type = re.compile(
r"[<,](" + "|".join([re.escape(p) for p in _root_alias_to_c_primitive]) + r")[>,]"
)
_classname_encode_pattern = re.compile(rb"[^a-zA-Z0-9]+")
_classname_decode_antiversion = re.compile(rb".*_([0-9a-f][0-9a-f])+_v([0-9]+)$")
_classname_decode_version = re.compile(rb".*_v([0-9]+)$")
_classname_decode_pattern = re.compile(rb"_(([0-9a-f][0-9a-f])+)_")
def _classname_decode_convert(hex_characters):
g = hex_characters.group(1)
return bytes(int(g[i : i + 2], 16) for i in range(0, len(g), 2))
def _classname_encode_convert(bad_characters):
g = bad_characters.group(0)
return b"_" + b"".join(f"{x:02x}".encode() for x in g) + b"_"
def classname_regularize(classname):
"""
Removes spaces around ``<``, ``>``, and ``::`` characters in a classname
so that they can be matched by string name.
If ``classname`` is None, this function returns None. Otherwise, it must be
a string and it returns a string.
"""
if classname is not None:
classname = re.sub(_classname_regularize, r"\1", classname)
m = _classname_regularize_type.search(classname)
while m is not None:
start, stop = m.span(1)
token = classname[start:stop]
replacement = _root_alias_to_c_primitive[token]
classname = classname[:start] + replacement + classname[stop:]
m = _classname_regularize_type.search(classname)
return classname
def classname_decode(encoded_classname):
"""
Converts a Python (encoded) classname, such as ``Model_Some_3a3a_Thing``
into a C++ (decoded) classname, such as ``Some::Thing``.
C++ classnames can include namespace delimiters (``::``) and template
arguments (``<`` and ``>``), which have to be translated into
``[A-Za-z_][A-Za-z0-9_]*`` for Python. Non-conforming characters and also
underscores are translated to their hexadecimal equivalents and surrounded
by underscores. Additionally, Python models of C++ classes are prepended
with ``Model_`` (or ``Unknown_`` if a streamer isn't found).
"""
if encoded_classname.startswith("Unknown_"):
raw = encoded_classname[8:].encode()
elif encoded_classname.startswith("Model_"):
raw = encoded_classname[6:].encode()
else:
raise ValueError(f"not an encoded classname: {encoded_classname}")
if _classname_decode_antiversion.match(raw) is not None:
version = None
else:
m = _classname_decode_version.match(raw)
if m is None:
version = None
else:
version = int(m.group(1))
raw = raw[: -len(m.group(1)) - 2]
out = _classname_decode_pattern.sub(_classname_decode_convert, raw)
return out.decode(), version
def classname_encode(classname, version=None, unknown=False):
"""
Converts a C++ (decoded) classname, such as ``Some::Thing`` into a Python
classname (encoded), such as ``Model_Some_3a3a_Thing``.
If ``version`` is a number such as ``2``, the Python name is suffixed by
version, such as ``Model_Some_3a3a_Thing_v2``.
If ``unknown`` is True, the ``Model_`` prefix becomes ``Unknown_``.
C++ classnames can include namespace delimiters (``::``) and template
arguments (``<`` and ``>``), which have to be translated into
``[A-Za-z_][A-Za-z0-9_]*`` for Python. Non-conforming characters and also
underscores are translated to their hexadecimal equivalents and surrounded
by underscores. Additionally, Python models of C++ classes are prepended
with ``Model_`` (or ``Unknown_`` if a streamer isn't found).
"""
prefix = "Unknown_" if unknown else "Model_"
if classname.startswith(prefix):
raise ValueError(f"classname is already encoded: {classname}")
v = "" if version is None else "_v" + str(version)
raw = classname.encode()
out = _classname_encode_pattern.sub(_classname_encode_convert, raw)
return prefix + out.decode() + v
def classname_version(encoded_classname):
"""
Extracts a version number from a Python (encoded) classname, if it has one.
For example, ``Model_Some_3a3a_Thing_v2`` returns ``2``.
A name without a version number, such as ``Model_Some_3a3a_Thing``, returns
None.
"""
raw = encoded_classname.encode()
if _classname_decode_antiversion.match(raw) is not None:
return None
else:
m = _classname_decode_version.match(raw)
if m is None:
return None
else:
return int(m.group(1))
def class_named(classname, version=None, custom_classes=None):
"""
Returns a class with a given C++ (decoded) classname.
If ``version`` is None, no attempt is made to find a specific version.
* If the class is a :doc:`uproot.model.DispatchByVersion`, then this is
object returned.
* If the class is a versionless model, then this is the object returned.
If ``version`` is an integer, an attempt is made to find the specific
version.
* If the class is a :doc:`uproot.model.DispatchByVersion`, then it is
queried for a versioned model.
* If the class is a versionless model, then this is the object returned.
If ``custom_classes`` are provided, then these are searched (exclusively)
for the class. If ``custom_classes`` is None, then ``uproot.classes`` is
used.
No classes are created if a class is not found (an error is raised).
"""
if custom_classes is None:
classes = uproot.classes
where = "the 'custom_classes' dict"
else:
where = "uproot.classes"
cls = classes.get(classname)
if cls is None:
raise ValueError(f"no class named {classname} in {where}")
if version is not None and isinstance(cls, DispatchByVersion):
versioned_cls = cls.class_of_version(version)
if versioned_cls is not None:
return versioned_cls
else:
raise ValueError(
f"no class named {classname} with version {version} in {where}"
)
else:
return cls
def has_class_named(classname, version=None, custom_classes=None):
"""
Returns True if :doc:`uproot.model.class_named` would find a class,
False if it would raise an exception.
"""
cls = maybe_custom_classes(classname, custom_classes).get(classname)
if cls is None:
return False
if version is not None and isinstance(cls, DispatchByVersion):
return cls.has_version(version)
else:
return True
def maybe_custom_classes(classname, custom_classes):
"""
Passes through ``custom_classes`` if it is not None; returns
``uproot.classes`` otherwise.
Some ``classnames`` are never custom (see ``uproot.model.never_from_streamers``).
"""
if custom_classes is None or classname in never_from_streamers:
return uproot.classes
else:
return custom_classes
class Model:
"""
Abstract class for all objects extracted from ROOT files (except for
:doc:`uproot.reading.ReadOnlyFile`, :doc:`uproot.reading.ReadOnlyDirectory`,
and :doc:`uproot.reading.ReadOnlyKey`).
A model is instantiated from a file using the :ref:`uproot.model.Model.read`
classmethod or synthetically using the :ref:`uproot.model.Model.empty`
classmethod, not through a normal constructor.
Models point back to the file from which they were created, though only a
few classes (named in ``uproot.reading.must_be_attached``) have an open,
readable file attached; the rest have a :doc:`uproot.reading.DetachedFile`
with information about the file, while not holding the file open.
Uproot recognizes *some* of ROOT's thousands of classes, by way of methods
and properties defined in :doc:`uproot.behaviors`. Examples include
* :doc:`uproot.behaviors.TTree.TTree`
* :doc:`uproot.behaviors.TH1.TH1`
These classes are the most convenient to work with and have specialized
documentation.
Classes that don't have any predefined behaviors are still usable through
their member data.
* :ref:`uproot.model.Model.members`: a dict of C++ member names and values
directly in this class.
* :ref:`uproot.model.Model.all_members`: a dict of C++ member names and
values in this class or any superclasses.
* :ref:`uproot.model.Model.member`: method that takes a C++ member name
and returns its value (from this or any superclass).
* :ref:`uproot.model.Model.has_member`: method that takes a C++ member
name and returns True if it exists (in this or any superclass), False
otherwise.
Accessing a data structure through its C++ members may be a prelude to
adding custom behaviors for it. Before we know what conveniences to add, we
need to know how they'll be used: this information comes from the user
community.
Pythonic models don't follow the same class inheritance tree as their C++
counterparts: most of them are direct subclasses of
:doc:`uproot.model.Model`, :doc:`uproot.model.DispatchByVersion`, or
:doc:`uproot.model.VersionedModel`. To separate an object's members
from its superclass members, a model instance is created for each and
the superclass parts are included in a list called
:ref:`uproot.model.Model.bases`.
"""
base_names_versions = []
member_names = []
class_flags = {}
class_code = None
class_streamer = None
class_rawstreamers = ()
writable = False
_deeply_writable = False
behaviors = ()
def __repr__(self):
if self.class_version is None:
version = ""
else:
version = f" (version {self.class_version})"
return f"<{self.classname}{version} at 0x{id(self):012x}>"
def __enter__(self):
if isinstance(self._file, uproot.reading.ReadOnlyFile):
self._file.source.__enter__()
return self
def __exit__(self, exception_type, exception_value, traceback):
if isinstance(self._file, uproot.reading.ReadOnlyFile):
self._file.source.__exit__(exception_type, exception_value, traceback)
@property
def classname(self):
"""
The C++ (decoded) classname of the modeled class.
See :doc:`uproot.model.classname_decode`,
:doc:`uproot.model.classname_encode`, and
:doc:`uproot.model.classname_version`.
"""
return classname_decode(self.encoded_classname)[0]
@property
def encoded_classname(self):
"""
The Python (encoded) classname of the modeled class. May or may not
include version.
See :doc:`uproot.model.classname_decode`,
:doc:`uproot.model.classname_encode`, and
:doc:`uproot.model.classname_version`.
"""
return type(self).__name__
@property
def class_version(self):
"""
The version number of the modeled class (int) if any; None otherwise.
See :doc:`uproot.model.classname_decode`,
:doc:`uproot.model.classname_encode`, and
:doc:`uproot.model.classname_version`.
"""
return classname_decode(self.encoded_classname)[1]
@property
def cursor(self):
"""
A cursor pointing to the start of this instance in the byte stream
(before :ref:`uproot.model.Model.read_numbytes_version`).
"""
return self._cursor
@property
def file(self):
"""
A :doc:`uproot.reading.ReadOnlyFile`, which may be open and readable,
or a :doc:`uproot.reading.DetachedFile`, which only contains
information about the original file (not an open file handle).
"""
return self._file
def close(self):
"""
Closes the file from which this object is derived, if such a file is
still attached (i.e. not :doc:`uproot.reading.DetachedFile`).
"""
if isinstance(self._file, uproot.reading.ReadOnlyFile):
self._file.close()
@property
def closed(self):
"""
True if the associated file is known to be closed; False if it is known
to be open. If the associated file is detached
(:doc:`uproot.reading.DetachedFile`), then the value is None.
"""
if isinstance(self._file, uproot.reading.ReadOnlyFile):
return self._file.closed
else:
return None
@property
def parent(self):
"""
The object that was deserialized before this one in recursive descent,
usually the containing object (or the container's container).
"""
return self._parent
@property
def concrete(self):
"""
The Python instance corresponding to the concrete (instantiated) class
in C++, which is ``self`` if this is the concrete class or another
object if this is actually a holder of superclass members for that other
object (i.e. if this object is in the other's
:ref:`uproot.model.Model.bases`).
"""
if self._concrete is None:
return self
return self._concrete
@property
def members(self):
"""
A dict of C++ member data directly associated with this class (i.e. not
its superclasses). For all members, see
:ref:`uproot.model.Model.all_members`.
"""
return self._members
@property
def all_members(self):
"""
A dict of C++ member data for this class and its superclasses. For only
direct members, see :ref:`uproot.model.Model.members`.
"""
out = {}
for base in self._bases:
out.update(base.all_members)
out.update(self._members)
return out
def has_member(self, name, all=True):
"""
Returns True if calling :ref:`uproot.model.Model.member` with the same
arguments would return a value; False if the member is missing.
"""
if name in self._members:
return True
if all:
for base in reversed(self._bases):
if base.has_member(name, all=True):
return True
return False
def member(self, name, all=True, none_if_missing=False):
"""
Args:
name (str): The name of the member datum to retrieve.
all (bool): If True, recursively search all superclasses in
:ref:`uproot.model.Model.bases`. Otherwise, search the
direct class only.
none_if_missing (bool): If a member datum doesn't exist in the
search path, ``none_if_missing=True`` has this function return
None, but ``none_if_missing=False`` would have it raise an
exception. Note that None is a possible value for some member
data.
Returns a C++ member datum by name.
"""
if name in self._members:
return self._members[name]
if all:
for base in reversed(self._bases):
if base.has_member(name, all=True):
return base.member(name, all=True)
if none_if_missing:
return None
else:
raise uproot.KeyInFileError(
name,
because="""{}.{} has only the following members:
{}
""".format(
type(self).__module__,
type(self).__name__,
", ".join(repr(x) for x in self.all_members),
),
file_path=getattr(self._file, "file_path", None),
)
@property
def bases(self):
"""
List of :doc:`uproot.model.Model` objects representing superclass data
for this object in the order given in C++ (opposite method resolution
order).
* If this object has no superclasses, ``bases`` is empty.
* If it has one superclass, which itself might have superclasses,
``bases`` has length 1.
* Only if this object *multiply inherits* from more than one superclass
at the same level does ``bases`` have length greater than 1.
Since multiple inheritance is usually avoided, ``bases`` rarely has
length greater than 1. A linear chain of superclasses deriving from
super-superclasses is represented by ``bases`` containing an object
whose ``bases`` contains objects.
"""
return self._bases
def base(self, *cls):
"""
Extracts instances from :ref:`uproot.model.Model.bases` by Python class
type.
The ``cls`` arguments may be Python classes or C++ classname strings to match.
"""
cpp_names = [classname_regularize(x) for x in cls if isinstance(x, str)]
py_types = tuple(x for x in cls if not isinstance(x, str))
out = []
for x in getattr(self, "_bases", []):
if isinstance(x, py_types) or any(
getattr(x, "classname", None) == n for n in cpp_names
):
out.append(x)
if isinstance(x, Model):
out.extend(x.base(*cls))
return out
def is_instance(self, *cls):
"""
Returns True if this object matches a given type in the C++ class hierarchy.
The ``cls`` arguments may be Python classes or C++ classname strings to match.
"""
cpp_names = [classname_regularize(x) for x in cls if isinstance(x, str)]
py_types = tuple(x for x in cls if not isinstance(x, str))
if isinstance(self, py_types) or any(self.classname == n for n in cpp_names):
return True
else:
return len(self.base(*cls)) != 0
@property
def num_bytes(self):
"""
Number of bytes expected in the (uncompressed) serialization of this
instance.
This value may be None (unknown before reading) or an integer.
If the value is an integer and the object exists (no exceptions in
:ref:`uproot.model.Model.read`), then the expected number of bytes
agreed with the actual number of bytes, and this numer is reliable.
If this object is re-serialized, it won't necessarily occupy the same
number of bytes.
"""
return self._num_bytes
@property
def instance_version(self):
"""
Version of this instance as read from the byte stream.
If this model is versioned (:doc:`uproot.model.VersionedModel`), the
``instance_version`` ought to be equal to the
:ref:`uproot.model.Model.class_version`.
If this model is versionless, the ``instance_version`` contains new
information about the actual version deserialized.
"""
return self._instance_version
@property
def is_memberwise(self):
"""
True if the object was serialized in ROOT's memberwise format; False
otherwise.
"""
return self._is_memberwise
@classmethod
def awkward_form(cls, file, context):
"""
Args:
cls (subclass of :doc:`uproot.model.Model`): This class.
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.
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 uproot.interpretation.objects.CannotBeAwkward(
classname_decode(cls.__name__)[0]
)
@classmethod
def strided_interpretation(
cls, file, header=False, tobject_header=True, breadcrumbs=(), original=None
):
"""
Args:
cls (subclass of :doc:`uproot.model.Model`): This class.
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.
original (None, :doc:`uproot.model.Model`, or :doc:`uproot.containers.Container`): The
original, non-strided model or container.
breadcrumbs (tuple of class objects): Used to check for recursion.
Types that contain themselves cannot be strided because the
depth of instances is unknown.
Returns a list of (str, ``numpy.dtype``) pairs to build a
:doc:`uproot.interpretation.objects.AsStridedObjects` interpretation.
"""
raise uproot.interpretation.objects.CannotBeStrided(
classname_decode(cls.__name__)[0]
)
def tojson(self):
"""
Serializes this object in its ROOT JSON form (as Python lists and dicts,
which can be passed to ``json.dump`` or ``json.dumps``).
"""
out = {}
for base in self._bases:
tmp = base.tojson()
if isinstance(tmp, dict):
out.update(tmp)
for k, v in self.members.items():
if isinstance(v, Model):
out[k] = v.tojson()
elif isinstance(v, (numpy.number, numpy.ndarray)):
out[k] = v.tolist()
else:
out[k] = v
out["_typename"] = self.classname
return out
@classmethod
def empty(cls):
"""
Creates a model instance (of subclass ``cls``) with no data; all
required attributes are None or empty.
"""
self = cls.__new__(cls)
self._cursor = None
self._file = None
self._parent = None
self._concrete = None
self._members = {}
self._bases = []
self._num_bytes = None
self._instance_version = None
self._is_memberwise = False
return self
@classmethod
def read(cls, chunk, cursor, context, file, selffile, parent, concrete=None):
"""
Args:
cls (subclass of :doc:`uproot.model.Model`): Class to instantiate.
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.
concrete (None or :doc:`uproot.model.Model` instance): If None,
this model corresponds to the concrete (instantiated) class in
C++. Otherwise, this model represents a superclass part of the
object, and ``concrete`` points to the concrete instance.
Creates a model instance by reading data from a file.
"""
self = cls.__new__(cls)
self._cursor = cursor.copy()
self._file = selffile
self._parent = parent
self._concrete = concrete
self._members = {}
self._bases = []
self._num_bytes = None
self._instance_version = None
self._is_memberwise = False
old_breadcrumbs = context.get("breadcrumbs", ())
context["breadcrumbs"] = (*old_breadcrumbs, self)
self.hook_before_read(chunk=chunk, cursor=cursor, context=context, file=file)
forth_obj = uproot._awkwardforth.get_forth_obj(context)
if forth_obj is not None:
forth_stash = uproot._awkwardforth.Node(
name=f"wrong-instance-version {uproot._awkwardforth.get_first_key_number(context)}",
form_details={"offsets": "i64"},
)
if context.get("reading", True):
temp_index = cursor._index
self.read_numbytes_version(chunk, cursor, context)
length = cursor._index - temp_index
if length != 0 and forth_obj is not None:
forth_stash.pre_code.append(f"{length} stream skip\n")
if (
issubclass(cls, VersionedModel)
and self._instance_version != classname_version(cls.__name__)
and self._instance_version is not None
):
correct_cls = file.class_named(self.classname, self._instance_version)
if classname_version(correct_cls.__name__) != classname_version(
cls.__name__
):
cursor.move_to(self._cursor.index)
context["breadcrumbs"] = old_breadcrumbs
if forth_obj is not None:
forth_obj.add_node(forth_stash)
forth_obj.push_active_node(forth_stash)
temp_var = correct_cls.read(
chunk,
cursor,
context,
file,
selffile,
parent,
concrete=concrete,
)
if forth_obj is not None:
forth_obj.pop_active_node()
return temp_var
if context.get("in_TBranch", False):
# AwkwardForth testing A: test_0637's 01,02,05,08,09,11,12,13,15,16,29,35,38,39,44,45,46,47,49,50,52,56
if self._num_bytes is None and self._instance_version != self.class_version:
self._instance_version = None
cursor = self._cursor
if forth_obj is not None:
forth_stash._pre_code.pop(-1)
elif self._instance_version == 0:
if forth_obj is not None:
forth_stash.pre_code.append("4 stream skip\n")
cursor.skip(4)
if context.get("reading", True):
self.hook_before_read_members(
chunk=chunk, cursor=cursor, context=context, file=file
)
if forth_obj is not None:
key = uproot._awkwardforth.get_first_key_number(context)
forth_stash.name = f"start-of-model {key}"
forth_obj.add_node(forth_stash)
forth_obj.push_active_node(forth_stash)
self.read_members(chunk, cursor, context, file)
if forth_obj is not None:
forth_obj.pop_active_node()
self.hook_after_read_members(
chunk=chunk, cursor=cursor, context=context, file=file
)
self.check_numbytes(chunk, cursor, context)
self.hook_before_postprocess(
chunk=chunk, cursor=cursor, context=context, file=file
)
out = self.postprocess(chunk, cursor, context, file)
context["breadcrumbs"] = old_breadcrumbs
return out
def read_numbytes_version(self, chunk, cursor, context):
"""
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.
Reads the number of bytes and instance version from the byte stream,
which is usually 6 bytes (4 + 2). Bits with special meanings are
appropriately masked out.
Some types don't have a 6-byte header or handle it differently; in
those cases, this method should be overridden.
"""
import uproot.deserialization
(
self._num_bytes,
self._instance_version,
self._is_memberwise,
) = uproot.deserialization.numbytes_version(chunk, cursor, context)
def read_members(self, chunk, cursor, context, file):
"""
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`.
Reads the member data for this class. The abstract class
:doc:`uproot.model.Model` has an empty ``read_members`` method; this
*must* be overridden by subclasses.
"""
def check_numbytes(self, chunk, cursor, context):
"""
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.
Reads nothing; checks the expected number of bytes against the actual
movement of the ``cursor`` at the end of the object, possibly raising
a :doc:`uproot.deserialization.DeserializationError` exception.
If :ref:`uproot.model.Model.num_bytes` is None, this method does
nothing.
It is *possible* that a subclass would override this method, but not
likely.
"""
import uproot.deserialization
uproot.deserialization.numbytes_check(
chunk,
self._cursor,
cursor,
self._num_bytes,
self.classname,
context,
getattr(self._file, "file_path", None),
)
def postprocess(self, chunk, cursor, context, file):
"""
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`.
Called for any additional processing after the object has been fully
read.
The return value from this method is the object that actually represents
the ROOT data, which might be a different instance or even a different
type from this class. The default in :doc:`uproot.model.Model` is to
return ``self``.
Note that for versioned models,
:ref:`uproot.model.VersionedModel.postprocess` is called first, then
:ref:`uproot.model.DispatchByVersion.postprocess` is called on its
output, allowing a :doc:`uproot.model.DispatchByVersion` to refine all
data of its type, regardless of version.
"""
return self
def hook_before_read(self, **kwargs):
"""
Called in :ref:`uproot.model.Model.read`, before any data have been
read.
"""
def hook_before_read_members(self, **kwargs):
"""
Called in :ref:`uproot.model.Model.read`, after
:ref:`uproot.model.Model.read_numbytes_version` and before
:ref:`uproot.model.Model.read_members`.
"""
def hook_after_read_members(self, **kwargs):
"""
Called in :ref:`uproot.model.Model.read`, after
:ref:`uproot.model.Model.read_members` and before
:ref:`uproot.model.Model.check_numbytes`.
"""
def hook_before_postprocess(self, **kwargs):
"""
Called in :ref:`uproot.model.Model.read`, after
:ref:`uproot.model.Model.check_numbytes` and before
:ref:`uproot.model.Model.postprocess`.
"""