-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathreading.py
2702 lines (2277 loc) · 95.8 KB
/
reading.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 the entry-point for opening a file, :doc:`uproot.reading.open`,
and the classes that are too fundamental to be models:
:doc:`uproot.reading.ReadOnlyFile` (``TFile``),
:doc:`uproot.reading.ReadOnlyDirectory` (``TDirectory`` or ``TDirectoryFile``),
and :doc:`uproot.reading.ReadOnlyKey` (``TKey``).
"""
from __future__ import annotations
import re
import struct
import sys
import uuid
from collections.abc import Mapping, MutableMapping
from pathlib import Path
from typing import IO
import uproot
import uproot.behaviors.TBranch
import uproot.source.fsspec
from uproot._util import no_filter
def open(
path: str | Path | IO | dict[str | Path | IO, str],
*,
object_cache=100,
array_cache="100 MB",
custom_classes=None,
decompression_executor=None,
interpretation_executor=None,
**options,
):
"""
Args:
path (str or ``pathlib.Path``): The filesystem path or remote URL of
the file to open. If a string, it may be followed by a colon (``:``)
and an object path within the ROOT file, to return an object,
rather than a file. Path objects are interpreted strictly as
filesystem paths or URLs.
Examples: ``"rel/file.root"``, ``"C:\\abs\\file.root"``,
``"http://where/what.root"``,
``"https://username:password@where/secure.root"``,
``"rel/file.root:tdirectory/ttree"``, ``Path("rel:/file.root")``,
``Path("/abs/path:stuff.root")``
object_cache (None, MutableMapping, or int): Cache of objects drawn
from ROOT directories (e.g. histograms, TTrees, other directories);
if None, do not use a cache; if an int, create a new cache of this
size.
array_cache (None, MutableMapping, or memory size): Cache of arrays
drawn from ``TTrees``; if None, do not use a cache; if a memory
size, create a new cache of this size.
custom_classes (None or MutableMapping): If None, classes come from
uproot.classes; otherwise, a container of class definitions that
is both used to fill with new classes and search for dependencies.
decompression_executor (None or Executor with a ``submit`` method): The
executor that is used to decompress ``TBaskets``; if None, a
:doc:`uproot.source.futures.TrivialExecutor` is created.
Executors attached to a file are ``shutdown`` when the file is closed.
interpretation_executor (None or Executor with a ``submit`` method): The
executor that is used to interpret uncompressed ``TBasket`` data as
arrays; if None, a :doc:`uproot.source.futures.TrivialExecutor`
is created.
Executors attached to a file are ``shutdown`` when the file is closed.
options: See below.
Opens a ROOT file, possibly through a remote protocol.
If an object path is given, the return type of this function can be anything
that can be extracted from a ROOT file (subclass of
:doc:`uproot.model.Model`).
If an object path is not given, the return type is a
:doc:`uproot.reading.ReadOnlyDirectory` *and not*
:doc:`uproot.reading.ReadOnlyFile`. ROOT objects can be extracted from a
:doc:`uproot.reading.ReadOnlyDirectory` but not a
:doc:`uproot.reading.ReadOnlyFile`.
Options (type; default):
* handler (:doc:`uproot.source.chunk.Source` class; None)
* timeout (float for HTTP, int for XRootD; 30)
* max_num_elements (None or int; None)
* num_workers (int; 1)
* use_threads (bool; False on the emscripten platform (i.e. in a web browser), else True)
* num_fallback_workers (int; 10)
* begin_chunk_size (memory_size; 403, the smallest a ROOT file can be)
* minimal_ttree_metadata (bool; True)
Any object derived from a ROOT file is a context manager (works in Python's
``with`` statement) that closes the file when exiting the ``with`` block.
Therefore, the :doc:`uproot.reading.open` function can and usually should
be used in a ``with`` statement to clean up file handles and threads
associated with open files:
.. code-block:: python
with uproot.open("/path/to/file.root:path/to/histogram") as h:
h.to_hist().plot()
# file is now closed, even if an exception was raised in the block
Other file entry points:
* :doc:`uproot.reading.open` (this function): opens one file to read any
of its objects.
* :doc:`uproot.behaviors.TBranch.iterate`: iterates through chunks of
contiguous entries in ``TTrees``.
* :doc:`uproot.behaviors.TBranch.concatenate`: returns a single concatenated
array from ``TTrees``.
* :doc:`uproot._dask.dask`: returns an unevaluated Dask array from ``TTrees``.
For remote ROOT files served over HTTP(S), basic authentication is supported.
In this case, the credentials may be provided part of the URL in, as in
``https://username:password@example.org/secure/protected.root.`` Note that
for security reasons, it is recommended basic authentication only be used
for HTTPS resources.
"""
if isinstance(path, dict) and len(path) == 1:
((file_path, object_path),) = path.items()
elif isinstance(path, str):
file_path, object_path = uproot._util.file_object_path_split(path)
else:
file_path = path
object_path = None
file_path = uproot._util.regularize_path(file_path)
if not isinstance(file_path, str) and not (
hasattr(file_path, "read") and hasattr(file_path, "seek")
):
raise ValueError(
"'path' must be a string, pathlib.Path, an object with 'read' and "
"'seek' methods, or a length-1 dict of {file_path: object_path}, "
f"not {path!r}"
)
file = ReadOnlyFile(
file_path,
object_cache=object_cache,
array_cache=array_cache,
custom_classes=custom_classes,
decompression_executor=decompression_executor,
interpretation_executor=interpretation_executor,
**options,
)
if object_path is None:
return file.root_directory
else:
return file.root_directory[object_path]
open.defaults = {
"handler": None,
"timeout": 30,
"max_num_elements": None,
"num_workers": 1,
"use_threads": sys.platform != "emscripten",
"num_fallback_workers": 10,
"begin_chunk_size": 403, # the smallest a ROOT file can be
"minimal_ttree_metadata": True,
"http_max_header_bytes": 21784,
}
class _OpenDefaults(dict):
def __init__(self):
raise NotImplementedError # kept for backwards compatibility
must_be_attached = [
"TROOT",
"TDirectory",
"TDirectoryFile",
"RooWorkspace::WSDir",
"TTree",
"TChain",
"TProofChain",
"THbookTree",
"TNtuple",
"TNtupleD",
"TTreeSQL",
"ROOT::RNTuple",
]
class CommonFileMethods:
"""
Abstract class for :doc:`uproot.reading.ReadOnlyFile` and
:doc:`uproot.reading.DetachedFile`. The latter is a placeholder for file
information, such as the :ref:`uproot.reading.CommonFileMethods.file_path`
used in many error messages, without holding a reference to the active
:doc:`uproot.source.chunk.Source`.
This allows the file to be closed and deleted while objects that were read
from it still exist. Also, only objects that hold detached file references,
rather than active ones, can be pickled.
The (unpickleable) objects that must hold a reference to an active
:doc:`uproot.reading.ReadOnlyFile` are listed by C++ (decoded) classname
in ``uproot.must_be_attached``.
"""
@property
def file_path(self):
"""
The original path to the file (converted to ``str`` if it was originally
a ``pathlib.Path``).
"""
return self._file_path
@property
def options(self):
"""
The dict of ``options`` originally passed to the file constructor.
If this is a :doc:`uproot.writing.writable.WritableFile`, the ``options`` are a copy
of the current state of the options; change the properties (e.g.
``initial_directory_bytes``, ``uuid_function``) directly on the file object
to make a lasting change. Modifying the copied dict does not change the
file's future behavior.
"""
return self._options
@property
def root_version(self):
"""
Version of ROOT used to write the file as a string.
See :ref:`uproot.reading.CommonFileMethods.root_version_tuple` and
:ref:`uproot.reading.CommonFileMethods.fVersion`.
"""
return "{}.{:02d}/{:02d}".format(*self.root_version_tuple)
@property
def root_version_tuple(self):
"""
Version of ROOT used to write teh file as a tuple.
See :ref:`uproot.reading.CommonFileMethods.root_version` and
:ref:`uproot.reading.CommonFileMethods.fVersion`.
"""
version = self._fVersion
if version >= 1000000:
version -= 1000000
major = version // 10000
version %= 10000
minor = version // 100
version %= 100
return major, minor, version
@property
def is_64bit(self):
"""
True if the ROOT file is 64-bit ready; False otherwise.
A file that is larger than 4 GiB must be 64-bit ready, though any file
might be. This refers to seek points like
:ref:`uproot.reading.ReadOnlyFile.fSeekFree` being 64-bit integers,
rather than 32-bit.
Note that a file being 64-bit is distinct from a ``TDirectory`` being
64-bit; see :ref:`uproot.reading.ReadOnlyDirectory.is_64bit`.
"""
return self._fVersion >= 1000000
@property
def compression(self):
"""
A :doc:`uproot.compression.Compression` object describing the
compression setting for the ROOT file.
Note that different objects (even different ``TBranches`` within a
``TTree``) can be compressed differently, so this file-level
compression is only a strong hint of how the objects are likely to
be compressed.
For some versions of ROOT ``TStreamerInfo`` is always compressed with
:doc:`uproot.compression.ZLIB`, even if the compression is set to a
different algorithm.
See :ref:`uproot.reading.CommonFileMethods.fCompress`.
"""
return uproot.compression.Compression.from_code(self._fCompress)
@property
def hex_uuid(self):
"""
The unique identifier (UUID) of the ROOT file expressed as a hexadecimal
string.
See :ref:`uproot.reading.CommonFileMethods.uuid` and
:ref:`uproot.reading.CommonFileMethods.fUUID`.
"""
out = "".join(f"{x:02x}" for x in self._fUUID)
return "-".join([out[0:8], out[8:12], out[12:16], out[16:20], out[20:32]])
@property
def uuid(self):
"""
The unique identifier (UUID) of the ROOT file expressed as a Python
``uuid.UUID`` object.
See :ref:`uproot.reading.CommonFileMethods.hex_uuid` and
:ref:`uproot.reading.CommonFileMethods.fUUID`.
"""
return uuid.UUID(self.hex_uuid.replace("-", ""))
@property
def fVersion(self):
"""
Raw version information for the ROOT file; this number is used to derive
:ref:`uproot.reading.CommonFileMethods.root_version`,
:ref:`uproot.reading.CommonFileMethods.root_version_tuple`, and
:ref:`uproot.reading.CommonFileMethods.is_64bit`.
"""
return self._fVersion
@property
def fBEGIN(self):
"""
The seek point (int) for the first data record, past the TFile header.
Usually 100.
"""
return self._fBEGIN
@property
def fEND(self):
"""
The seek point (int) to the last free word at the end of the ROOT file.
"""
return self._fEND
@property
def fSeekFree(self):
"""
The seek point (int) to the ``TFree`` data, for managing empty spaces
in a ROOT file (filesystem-like fragmentation).
"""
return self._fSeekFree
@property
def fNbytesFree(self):
"""
The number of bytes in the ``TFree`` data, for managing empty spaces
in a ROOT file (filesystem-like fragmentation).
"""
return self._fNbytesFree
@property
def nfree(self):
"""
The number of objects in the ``TFree`` data, for managing empty spaces
in a ROOT file (filesystem-like fragmentation).
"""
return self._nfree
@property
def fNbytesName(self):
"""
The number of bytes in the filename (``TNamed``) that is embedded in
the ROOT file.
"""
return self._fNbytesName
@property
def fUnits(self):
"""
Number of bytes in the serialization of file seek points, which can either
be 4 or 8.
"""
return self._fUnits
@property
def fCompress(self):
"""
The raw integer describing the compression setting for the ROOT file.
Note that different objects (even different ``TBranches`` within a
``TTree``) can be compressed differently, so this file-level
compression is only a strong hint of how the objects are likely to
be compressed.
For some versions of ROOT ``TStreamerInfo`` is always compressed with
:doc:`uproot.compression.ZLIB`, even if the compression is set to a
different algorithm.
See :ref:`uproot.reading.CommonFileMethods.compression`.
"""
return self._fCompress
@property
def fSeekInfo(self):
"""
The seek point (int) to the ``TStreamerInfo`` data, where
:ref:`uproot.reading.ReadOnlyFile.streamers` are located.
"""
return self._fSeekInfo
@property
def fNbytesInfo(self):
"""
The number of bytes in the ``TStreamerInfo`` data, where
:ref:`uproot.reading.ReadOnlyFile.streamers` are located.
"""
return self._fNbytesInfo
@property
def fUUID(self):
"""
The unique identifier (UUID) of the ROOT file as a raw bytestring
(Python ``bytes``).
See :ref:`uproot.reading.CommonFileMethods.hex_uuid` and
:ref:`uproot.reading.CommonFileMethods.uuid`.
"""
return self._fUUID
class DetachedFile(CommonFileMethods):
"""
Args:
file (:doc:`uproot.reading.ReadOnlyFile`): The active file object to
convert into a detached file.
A placeholder for a :doc:`uproot.reading.ReadOnlyFile` with useful
information, such as the :ref:`uproot.reading.CommonFileMethods.file_path`
used in many error messages, without holding a reference to the active
:doc:`uproot.source.chunk.Source`.
This allows the file to be closed and deleted while objects that were read
from it still exist. Also, only objects that hold detached file references,
rather than active ones, can be pickled.
The (unpickleable) objects that must hold a reference to an active
:doc:`uproot.reading.ReadOnlyFile` are listed by C++ (decoded) classname
in ``uproot.must_be_attached``.
"""
def __init__(self, file):
self._file_path = file._file_path
self._options = file._options
self._fVersion = file._fVersion
self._fBEGIN = file._fBEGIN
self._fEND = file._fEND
self._fSeekFree = file._fSeekFree
self._fNbytesFree = file._fNbytesFree
self._nfree = file._nfree
self._fNbytesName = file._fNbytesName
self._fUnits = file._fUnits
self._fCompress = file._fCompress
self._fSeekInfo = file._fSeekInfo
self._fNbytesInfo = file._fNbytesInfo
self._fUUID_version = file._fUUID_version
self._fUUID = file._fUUID
_file_header_fields_small = struct.Struct(">4siiiiiiiBiiiH16s")
_file_header_fields_big = struct.Struct(">4siiqqiiiBiqiH16s")
class ReadOnlyFile(CommonFileMethods):
"""
Args:
file_path (str or ``pathlib.Path``): The filesystem path or remote URL
of the file to open. Unlike :doc:`uproot.reading.open`, it cannot
be followed by a colon (``:``) and an object path within the ROOT
file.
object_cache (None, MutableMapping, or int): Cache of objects drawn
from ROOT directories (e.g histograms, TTrees, other directories);
if None, do not use a cache; if an int, create a new cache of this
size.
array_cache (None, MutableMapping, or memory size): Cache of arrays
drawn from ``TTrees``; if None, do not use a cache; if a memory size,
create a new cache of this size.
custom_classes (None or MutableMapping): If None, classes come from
uproot.classes; otherwise, a container of class definitions that
is both used to fill with new classes and search for dependencies.
decompression_executor (None or Executor with a ``submit`` method): The
executor that is used to decompress ``TBaskets``; if None, a
:doc:`uproot.source.futures.TrivialExecutor` is created.
Executors attached to a file are ``shutdown`` when the file is closed.
interpretation_executor (None or Executor with a ``submit`` method): The
executor that is used to interpret uncompressed ``TBasket`` data as
arrays; if None, a :doc:`uproot.source.futures.TrivialExecutor`
is created.
Executors attached to a file are ``shutdown`` when the file is closed.
options: See below.
Handle to an open ROOT file, the way to access data in ``TDirectories``
(:doc:`uproot.reading.ReadOnlyDirectory`) and create new classes from
``TStreamerInfo`` (:ref:`uproot.reading.ReadOnlyFile.streamers`).
All objects derived from ROOT files have a pointer back to the file,
though this is a :doc:`uproot.reading.DetachedFile` (no active connection,
cannot read more data) if the object's :ref:`uproot.model.Model.classname`
is not in ``uproot.reading.must_be_attached``: objects that can read
more data and need to have an active connection (like ``TTree``,
``TBranch``, and ``TDirectory``).
Note that a :doc:`uproot.reading.ReadOnlyFile` can't be directly used to
extract objects. To read data, use the :doc:`uproot.reading.ReadOnlyDirectory`
returned by :ref:`uproot.reading.ReadOnlyFile.root_directory`. This is why
:doc:`uproot.reading.open` returns a :doc:`uproot.reading.ReadOnlyDirectory`
and not a :doc:`uproot.reading.ReadOnlyFile`.
Options (type; default):
* handler (:doc:`uproot.source.chunk.Source` class; None)
* timeout (float for HTTP, int for XRootD; 30)
* max_num_elements (None or int; None)
* num_workers (int; 1)
* use_threads (bool; False on the emscripten platform (i.e. in a web browser), else True)
* num_fallback_workers (int; 10)
* begin_chunk_size (memory_size; 403, the smallest a ROOT file can be)
* minimal_ttree_metadata (bool; True)
See the `ROOT TFile documentation <https://root.cern.ch/doc/master/classTFile.html>`__
for a specification of ``TFile`` header fields.
"""
def __init__(
self,
file_path: str | Path | IO,
*,
object_cache=100,
array_cache="100 MB",
custom_classes=None,
decompression_executor=None,
interpretation_executor=None,
**options,
):
self._file_path = file_path
self.object_cache = object_cache
self.array_cache = array_cache
self.custom_classes = custom_classes
self.decompression_executor = decompression_executor
self.interpretation_executor = interpretation_executor
self._options = open.defaults.copy()
self._options.update(options)
for option in ["begin_chunk_size"]:
self._options[option] = uproot._util.memory_size(self._options[option])
self._streamers = None
self._streamer_rules = None
self.hook_before_create_source()
source_cls, file_path = uproot._util.file_path_to_source_class(
file_path, self._options
)
self._source = source_cls(file_path, **self._options)
self.hook_before_get_chunks()
if self._options["begin_chunk_size"] < _file_header_fields_big.size:
raise ValueError(
"begin_chunk_size={} is not enough to read the TFile header ({})".format(
self._options["begin_chunk_size"],
_file_header_fields_big.size,
)
)
self._begin_chunk = self._source.chunk(
0, self._options["begin_chunk_size"]
).detach_memmap()
self.hook_before_interpret()
(
magic,
self._fVersion,
self._fBEGIN,
self._fEND,
self._fSeekFree,
self._fNbytesFree,
self._nfree,
self._fNbytesName,
self._fUnits,
self._fCompress,
self._fSeekInfo,
self._fNbytesInfo,
self._fUUID_version,
self._fUUID,
) = uproot.source.cursor.Cursor(0).fields(
self._begin_chunk, _file_header_fields_small, {}
)
if self.is_64bit:
(
magic,
self._fVersion,
self._fBEGIN,
self._fEND,
self._fSeekFree,
self._fNbytesFree,
self._nfree,
self._fNbytesName,
self._fUnits,
self._fCompress,
self._fSeekInfo,
self._fNbytesInfo,
self._fUUID_version,
self._fUUID,
) = uproot.source.cursor.Cursor(0).fields(
self._begin_chunk, _file_header_fields_big, {}
)
self.hook_after_interpret(magic=magic)
if magic != b"root":
raise ValueError(
f"""not a ROOT file: first four bytes are {magic!r}
in file {file_path}"""
)
def __repr__(self):
return f"<ReadOnlyFile {self._file_path!r} at 0x{id(self):012x}>"
@property
def detached(self):
"""
A :doc:`uproot.reading.DetachedFile` version of this file.
"""
return DetachedFile(self)
def close(self):
"""
Explicitly close the file.
(Files can also be closed with the Python ``with`` statement, as context
managers.)
After closing, new objects and classes cannot be extracted from the file,
but objects with :doc:`uproot.reading.DetachedFile` references instead
of :doc:`uproot.reading.ReadOnlyFile` that are still in the
:ref:`uproot.reading.ReadOnlyFile.object_cache` would still be
accessible.
"""
self._source.close()
if hasattr(self._decompression_executor, "shutdown"):
getattr(self._decompression_executor, "shutdown", None)()
if hasattr(self._interpretation_executor, "shutdown"):
getattr(self._interpretation_executor, "shutdown", None)()
@property
def closed(self):
"""
True if the file has been closed; False otherwise.
The file may have been closed explicitly with
:ref:`uproot.reading.ReadOnlyFile.close` or implicitly in the Python
``with`` statement, as a context manager.
After closing, new objects and classes cannot be extracted from the file,
but objects with :doc:`uproot.reading.DetachedFile` references instead
of :doc:`uproot.reading.ReadOnlyFile` that are still in the
:ref:`uproot.reading.ReadOnlyFile.object_cache` would still be
accessible.
"""
return self._source.closed
def __enter__(self):
self._source.__enter__()
return self
def __exit__(self, exception_type, exception_value, traceback):
self._source.__exit__(exception_type, exception_value, traceback)
if hasattr(self._decompression_executor, "shutdown"):
getattr(self._decompression_executor, "shutdown", None)()
if hasattr(self._interpretation_executor, "shutdown"):
getattr(self._interpretation_executor, "shutdown", None)()
@property
def source(self):
"""
The :doc:`uproot.source.chunk.Source` associated with this file, which
is the "physical layer" that knows how to communicate with local file
systems or through remote protocols like HTTP(S) or XRootD, but does not
know what the bytes mean.
"""
return self._source
@property
def object_cache(self):
"""
A cache used to hold previously extracted objects, so that code like
.. code-block:: python
h = my_file["histogram"]
h = my_file["histogram"]
h = my_file["histogram"]
only reads the ``"histogram"`` once.
Any Python ``MutableMapping`` can be used as a cache (i.e. a Python
dict would be a cache that never evicts old objects), though
:doc:`uproot.cache.LRUCache` is a good choice because it is thread-safe
and evicts least-recently used objects when a maximum number of objects
is reached.
"""
return self._object_cache
@object_cache.setter
def object_cache(self, value):
if value is None or isinstance(value, MutableMapping):
self._object_cache = value
elif uproot._util.isint(value):
self._object_cache = uproot.cache.LRUCache(value)
else:
raise TypeError("object_cache must be None, a MutableMapping, or an int")
@property
def array_cache(self):
"""
A cache used to hold previously extracted arrays, so that code like
.. code-block:: python
a = my_tree["branch"].array()
a = my_tree["branch"].array()
a = my_tree["branch"].array()
only reads the ``"branch"`` once.
Any Python ``MutableMapping`` can be used as a cache (i.e. a Python
dict would be a cache that never evicts old objects), though
:doc:`uproot.cache.LRUArrayCache` is a good choice because it is
thread-safe and evicts least-recently used objects when a size limit is
reached.
"""
return self._array_cache
@array_cache.setter
def array_cache(self, value):
if value is None or isinstance(value, MutableMapping):
self._array_cache = value
elif uproot._util.isint(value) or isinstance(value, str):
self._array_cache = uproot.cache.LRUArrayCache(value)
else:
raise TypeError(
"array_cache must be None, a MutableMapping, or a memory size"
)
@property
def root_directory(self):
"""
The root ``TDirectory`` of the file
(:doc:`uproot.reading.ReadOnlyDirectory`).
"""
return ReadOnlyDirectory(
(),
uproot.source.cursor.Cursor(self._fBEGIN + self._fNbytesName),
{},
self,
self,
)
def show_streamers(self, classname=None, version="max", stream=sys.stdout):
"""
Args:
classname (None or str): If None, all streamers that are
defined in the file are shown; if a class name, only
this class and its dependencies are shown.
version (int, "min", or "max"): Version number of the desired
class; "min" or "max" returns the minimum or maximum version
number, respectively.
stream (object with a ``write(str)`` method): Stream to write the
output to.
Interactively display a file's ``TStreamerInfo``.
Example with ``classname="TLorentzVector"``:
.. code-block::
TVector3 (v3): TObject (v1)
fX: double (TStreamerBasicType)
fY: double (TStreamerBasicType)
fZ: double (TStreamerBasicType)
TObject (v1)
fUniqueID: unsigned int (TStreamerBasicType)
fBits: unsigned int (TStreamerBasicType)
TLorentzVector (v4): TObject (v1)
fP: TVector3 (TStreamerObject)
fE: double (TStreamerBasicType)
"""
classname = uproot.model.classname_regularize(classname)
if classname is None:
names = []
for name, streamer_versions in self.streamers.items():
for version in streamer_versions:
names.append((name, version))
else:
names = self.streamer_dependencies(classname, version=version)
first = True
for name, version in names:
for v, streamer in self.streamers[name].items():
if v == version:
if not first:
stream.write("\n")
streamer.show(stream=stream)
first = False
@property
def streamers(self):
"""
A list of :doc:`uproot.streamers.Model_TStreamerInfo` objects
representing the ``TStreamerInfos`` in the ROOT file.
A file's ``TStreamerInfos`` are only read the first time they are needed.
Uproot has a suite of predefined models in ``uproot.models`` to reduce
the probability that ``TStreamerInfos`` will need to be read (depending
on the choice of classes or versions of the classes that are accessed).
See also :ref:`uproot.reading.ReadOnlyFile.streamer_rules`, which are
read in the same pass with ``TStreamerInfos``.
"""
import uproot.models.TList
import uproot.models.TObjArray
import uproot.models.TObjString
import uproot.streamers
if self._streamers is None:
if self._fSeekInfo == 0:
self._streamers = {}
else:
key_cursor = uproot.source.cursor.Cursor(self._fSeekInfo)
key_start = self._fSeekInfo
key_stop = min(self._fSeekInfo + _key_format_big.size, self._fEND)
# Chunk will not be retained; we don't have to detach_memmap()
key_chunk = self.chunk(key_start, key_stop)
self.hook_before_read_streamer_key(
key_chunk=key_chunk,
key_cursor=key_cursor,
)
streamer_key = ReadOnlyKey(key_chunk, key_cursor, {}, self, self)
self.hook_before_read_decompress_streamers(
key_chunk=key_chunk,
key_cursor=key_cursor,
streamer_key=streamer_key,
)
(
streamer_chunk,
streamer_cursor,
) = streamer_key.get_uncompressed_chunk_cursor()
self.hook_before_interpret_streamers(
key_chunk=key_chunk,
key_cursor=key_cursor,
streamer_key=streamer_key,
streamer_cursor=streamer_cursor,
streamer_chunk=streamer_chunk,
)
classes = uproot.model.maybe_custom_classes(
"TList", self._custom_classes
)
tlist = classes["TList"].read(
streamer_chunk, streamer_cursor, {}, self, self.detached, None
)
self._streamers = {}
self._streamer_rules = []
for x in tlist:
if isinstance(x, uproot.streamers.Model_TStreamerInfo):
if x.name not in self._streamers:
self._streamers[x.name] = {}
self._streamers[x.name][x.class_version] = x
elif isinstance(x, uproot.models.TList.Model_TList) and all(
isinstance(y, uproot.models.TObjString.Model_TObjString)
for y in x
):
self._streamer_rules.extend([str(y) for y in x])
else:
raise ValueError(
f"""unexpected type in TList of streamers and streamer rules: {type(x)}
in file {self._file_path}"""
)
self.hook_after_interpret_streamers(
key_chunk=key_chunk,
key_cursor=key_cursor,
streamer_key=streamer_key,
streamer_cursor=streamer_cursor,
streamer_chunk=streamer_chunk,
)
return self._streamers
@property
def streamer_rules(self):
"""
A list of strings of C++ code that help schema evolution of
``TStreamerInfo`` by providing rules to evaluate when new objects are
accessed by old ROOT versions.
Uproot does not evaluate these rules because they are written in C++ and
Uproot does not have access to a C++ compiler.
These rules are read in the same pass that produces
:ref:`uproot.reading.ReadOnlyFile.streamers`.
"""
if self._streamer_rules is None:
self.streamers # noqa: B018 (this is not a useless expression; it runs code)
return self._streamer_rules
def streamers_named(self, classname):
"""
Returns a list of :doc:`uproot.streamers.Model_TStreamerInfo` objects
that match C++ (decoded) ``classname``.
More that one streamer matching a given name is unlikely, but possible
because there may be different versions of the same class. (Perhaps such
files can be created by merging data from different ROOT versions with
hadd?)
See also :ref:`uproot.reading.ReadOnlyFile.streamer_named` (singular).
"""
classname = uproot.model.classname_regularize(classname)
streamer_versions = self.streamers.get(classname)
if streamer_versions is None:
return []
else:
return list(streamer_versions.values())
def streamer_named(self, classname, version="max"):
"""
Returns a single :doc:`uproot.streamers.Model_TStreamerInfo` object
that matches C++ (decoded) ``classname`` and ``version``.
The ``version`` can be an integer or ``"min"`` or ``"max"`` for the
minimum and maximum version numbers available in the file. The default
is ``"max"`` because there's usually only one.
See also :ref:`uproot.reading.ReadOnlyFile.streamers_named` (plural).
"""
classname = uproot.model.classname_regularize(classname)
streamer_versions = self.streamers.get(classname)
if streamer_versions is None or len(streamer_versions) == 0:
return None
elif version == "min":
return streamer_versions[min(streamer_versions)]
elif version == "max":
return streamer_versions[max(streamer_versions)]
else:
return streamer_versions.get(version)
def streamer_dependencies(self, classname, version="max"):
"""
Returns a list of :doc:`uproot.streamers.Model_TStreamerInfo` objects
that depend on the one that matches C++ (decoded) ``classname`` and
``version``.
The ``classname`` and ``version`` are interpreted the same way as
:ref:`uproot.reading.ReadOnlyFile.streamer_named`.
"""
classname = uproot.model.classname_regularize(classname)
if version == "all":
streamers = self.streamers_named(classname)
streamers.sort(key=lambda x: -x.class_version)
out = []
for streamer in streamers:
batch = []
streamer._dependencies(self.streamers, batch)
for x in batch[::-1]:
if x not in out:
for i in range(-1, -len(out) - 1, -1):
if out[i][0] == x[0]:
out.insert(i + 1, x)
break
else:
out.append(x)
return out
else:
streamer = self.streamer_named(classname, version=version)
out = []