/
writable.py
2157 lines (1781 loc) · 78.9 KB
/
writable.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 high-level functions and objects for file-writing.
The :doc:`uproot.writing.writable.create`, :doc:`uproot.writing.writable.recreate`, and :doc:`uproot.writing.writable.update`
functions open files for writing, overwriting, or updating, in a way that is similar
to :doc:`uproot.reading.open`.
The :doc:`uproot.writing.writable.WritableFile`, :doc:`uproot.writing.writable.WritableDirectory`,
:doc:`uproot.writing.writable.WritableTree`, and :doc:`uproot.writing.writable.WritableBranch`
classes are writable versions of :doc:`uproot.reading.ReadOnlyFile`, :doc:`uproot.reading.ReadOnlyDirectory`,
:doc:`uproot.behaviors.TTree.TTree`, and :doc:`uproot.behaviors.TBranch.TBranch`.
There is no feature parity between writable and readable versions of each of these
types. Writing and reading are considered separate projects with different capabilities.
"""
from __future__ import annotations
import datetime
import itertools
import queue
import sys
import uuid
from collections.abc import Mapping, MutableMapping
from pathlib import Path
from typing import IO
import uproot._util
import uproot.compression
import uproot.deserialization
import uproot.exceptions
import uproot.model
import uproot.models.TObjString
import uproot.sink.file
import uproot.writing._cascade
from uproot._util import no_filter, no_rename
def create(file_path: str | Path | IO, **options):
"""
Args:
file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
file to open or an open file.
options: See below.
Opens a local file for writing. Like ROOT's ``"CREATE"`` option, this function
raises an error (``FileExistsError``) if a file already exists at ``file_path``.
Returns a :doc:`uproot.writing.writable.WritableDirectory`.
Options (type; default):
* initial_directory_bytes (int; 256)
* initial_streamers_bytes (int; 1024)
* uuid_function (callable; ``uuid.uuid1``)
* compression (:doc:`uproot.compression.Compression` or None): Compression algorithm
and level for new objects added to the file. Can be updated after creating
the :doc:`uproot.writing.writable.WritableFile`. Default is ``uproot.ZLIB(1)``.
See :doc:`uproot.writing.writable.WritableFile` for details on these options.
Additional options are passed to as ``storage_options`` to the fsspec filesystem
"""
file_path = uproot._util.regularize_path(file_path)
storage_options = {
key: value for key, value in options.items() if key not in create.defaults
}
if isinstance(file_path, str) and uproot.sink.file.FileSink._file_exists(
file_path, **storage_options
):
raise FileExistsError(
"path exists and refusing to overwrite (use 'uproot.recreate' to "
f"overwrite)\n\nfor path {file_path}"
)
return recreate(file_path, **options)
def recreate(file_path: str | Path | IO, **options):
"""
Args:
file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
file to open or an open file.
options: See below.
Opens a local file for writing. Like ROOT's ``"RECREATE"`` option, this function
overwrites any file that already exists at ``file_path``.
Returns a :doc:`uproot.writing.writable.WritableDirectory`.
Options (type; default):
* initial_directory_bytes (int; 256)
* initial_streamers_bytes (int; 1024)
* uuid_function (callable; ``uuid.uuid1``)
* compression (:doc:`uproot.compression.Compression` or None): Compression algorithm
and level for new objects added to the file. Can be updated after creating
the :doc:`uproot.writing.writable.WritableFile`. Default is ``uproot.ZLIB(1)``.
See :doc:`uproot.writing.writable.WritableFile` for details on these options.
Additional options are passed to as ``storage_options`` to the fsspec filesystem.
"""
file_path = uproot._util.regularize_path(file_path)
storage_options = {
key: value for key, value in options.items() if key not in recreate.defaults
}
sink = uproot.sink.file.FileSink(file_path, **storage_options)
compression = options.pop("compression", create.defaults["compression"])
initial_directory_bytes = options.pop(
"initial_directory_bytes", create.defaults["initial_directory_bytes"]
)
initial_streamers_bytes = options.pop(
"initial_streamers_bytes", create.defaults["initial_streamers_bytes"]
)
uuid_function = options.pop("uuid_function", create.defaults["uuid_function"])
if options:
raise TypeError(
"unrecognized options for uproot.create or uproot.recreate: "
+ ", ".join(repr(x) for x in options)
)
cascading = uproot.writing._cascade.create_empty(
sink,
compression,
initial_directory_bytes,
initial_streamers_bytes,
uuid_function,
)
return WritableFile(
sink, cascading, initial_directory_bytes, uuid_function
).root_directory
def update(file_path: str | Path | IO, **options):
"""
Args:
file_path (str, ``pathlib.Path`` or file-like object): The filesystem path of the
file to open or an open file.
options: See below.
Opens a local file for writing. Like ROOT's ``"UPDATE"`` option, this function
expects a file to already exist at ``file_path`` and opens it so that new data
can be added to it or individual objects may be deleted from it.
Returns a :doc:`uproot.writing.writable.WritableDirectory`.
Options (type; default):
* initial_directory_bytes (int; 256)
* uuid_function (callable; ``uuid.uuid1``)
See :doc:`uproot.writing.writable.WritableFile` for details on these options.
Additional options are passed to as ``storage_options`` to the fsspec filesystem
"""
file_path = uproot._util.regularize_path(file_path)
storage_options = {
key: value for key, value in options.items() if key not in update.defaults
}
sink = uproot.sink.file.FileSink(file_path, **storage_options)
initial_directory_bytes = options.pop(
"initial_directory_bytes", create.defaults["initial_directory_bytes"]
)
uuid_function = options.pop("uuid_function", create.defaults["uuid_function"])
if options:
raise TypeError(
"unrecognized options for uproot.update: "
+ ", ".join(repr(x) for x in options)
)
cascading = uproot.writing._cascade.update_existing(
sink,
initial_directory_bytes,
uuid_function,
)
return WritableFile(
sink, cascading, initial_directory_bytes, uuid_function
).root_directory
create.defaults = {
"compression": uproot.compression.ZLIB(1),
"initial_directory_bytes": 256,
"initial_streamers_bytes": 1024, # 256,
"uuid_function": uuid.uuid1,
}
recreate.defaults = create.defaults
update.defaults = create.defaults
class WritableFile(uproot.reading.CommonFileMethods):
"""
Args:
sink (:doc:`uproot.sink.file.FileSink`): The physical layer for file-writing.
cascading (:doc:`uproot.writing._cascade.CascadingFile`): The low-level file
object.
initial_directory_bytes (int): Number of bytes to allocate for new directories,
so that TKeys can be added to them without immediately needing to rewrite
the block.
uuid_function (zero-argument callable returning a ``uuid.UUID``): Function to
create the file's UUID and/or any directory's UUID.
Handle to a writable ROOT file, usually created by :doc:`uproot.writing.writable.create`,
:doc:`uproot.writing.writable.recreate`, or :doc:`uproot.writing.writable.update` and
accessed through a :doc:`uproot.writing.writable.WritableDirectory`.
"""
def __init__(self, sink, cascading, initial_directory_bytes, uuid_function):
self._sink = sink
self._cascading = cascading
self._initial_directory_bytes = initial_directory_bytes
self._uuid_function = uuid_function
self._file_path = sink.file_path
self._fVersion = self._cascading.fileheader.version
self._fBEGIN = self._cascading.fileheader.begin
self._fNbytesName = self._cascading.fileheader.begin_num_bytes
self._fUUID = self._cascading.fileheader.uuid.bytes
self._trees = {}
self._ntuples = {}
def __repr__(self):
return f"<WritableFile {self.file_path!r} at 0x{id(self):012x}>"
@property
def sink(self) -> uproot.sink.file.FileSink:
"""
Returns a :doc:`uproot.sink.file.FileSink`, the physical layer for writing
(and sometimes reading) data.
"""
return self._sink
@property
def initial_directory_bytes(self) -> int:
"""
Number of bytes to allocate for new directories, so that TKeys can be added
to them without immediately needing to rewrite the block.
"""
return self._initial_directory_bytes
@initial_directory_bytes.setter
def initial_directory_bytes(self, value):
self._initial_directory_bytes = value
@property
def uuid_function(self):
"""
The function used to create the file's UUID and/or any directory's UUID.
"""
return self._uuid_function
@uuid_function.setter
def uuid_function(self, value):
self._uuid_function = value
@property
def options(self):
"""
The options passed to :doc:`uproot.writing.writable.create`,
:doc:`uproot.writing.writable.recreate`, or :doc:`uproot.writing.writable.update`
when opening this file.
"""
return {
"initial_directory_bytes": self._initial_directory_bytes,
"uuid_function": self._uuid_function,
}
@property
def is_64bit(self) -> bool:
"""
True if the file has 8-byte pointers in its header; False if the pointers are 4-byte.
"""
return self._cascading.fileheader.big
@property
def compression(self) -> uproot.compression.Compression | None:
"""
Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
for new objects added to the file.
This property can be changed, which allows you to write different objects
with different compression settings.
See also :ref:`uproot.writing.writable.WritableFile.fCompress`.
"""
return self._cascading.fileheader.compression
@compression.setter
def compression(self, value):
if value is None or isinstance(value, uproot.compression.Compression):
self._cascading.fileheader.compression = value
self._cascading.fileheader.write(self._sink)
self._sink.flush()
else:
raise TypeError(
"compression must be None or a uproot.compression.Compression object, like uproot.ZLIB(4) or uproot.ZSTD(0)"
)
@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._cascading.fileheader.free_location
@property
def fNbytesFree(self) -> int:
"""
The number of bytes in the ``TFree`` data, for managing empty spaces
in a ROOT file (filesystem-like fragmentation).
"""
return self._cascading.fileheader.free_num_bytes
@property
def nfree(self) -> int:
"""
The number of objects in the ``TFree`` data, for managing empty spaces
in a ROOT file (filesystem-like fragmentation).
"""
return self._cascading.fileheader.free_num_slices + 1
@property
def fUnits(self) -> int:
"""
Number of bytes in the serialization of file seek points, which can either
be 4 or 8.
"""
return 8 if self._cascading.fileheader.big else 4
@property
def fCompress(self):
"""
Compression algorithm and level (as an integer code) for new objects added
to the file.
This property can be changed, which allows you to write different objects
with different compression settings.
See also :ref:`uproot.writing.writable.WritableFile.compression`.
"""
if self._cascading.fileheader.compression is None:
return uproot.compression.ZLIB(0).code
else:
return self._cascading.fileheader.compression.code
@property
def fSeekInfo(self):
"""
The seek point (int) to the ``TStreamerInfo`` data, where
TStreamerInfo records are located.
"""
return self._cascading.fileheader.info_location
@property
def fNbytesInfo(self) -> int:
"""
The number of bytes in the ``TStreamerInfo`` data, where
TStreamerInfo records are located.
"""
return self._cascading.fileheader.info_num_bytes
@property
def uuid(self):
"""
The unique identifier (UUID) of the ROOT file expressed as a Python
``uuid.UUID`` object.
"""
return self._cascading.fileheader.uuid
@property
def root_directory(self):
"""
The root (first) directory in the file as a :doc:`uproot.writing.writable.WritableDirectory`.
"""
return WritableDirectory((), self, self._cascading.rootdirectory)
def update_streamers(self, streamers):
"""
Overwrite the TStreamerInfo in this file with a new list of :doc:`uproot.streamers.Model_TStreamerInfo`
or :doc:`uproot.writable._cascade.RawStreamerInfo`.
"""
self._cascading.streamers.update_streamers(self.sink, streamers)
@property
def file_path(self) -> str | None:
"""
Filesystem path of the open file, or None if using a file-like object.
"""
return self._file_path
def close(self):
"""
Explicitly close the file.
(Files can also be closed with the Python ``with`` statement, as context
managers.)
After closing, objects cannot be read from or written to the file.
"""
self._sink.close()
@property
def closed(self) -> bool:
"""
True if the file has been closed; False otherwise.
The file may have been closed explicitly with
:ref:`uproot.writing.writable.WritableFile.close` or implicitly in the Python
``with`` statement, as a context manager.
After closing, objects cannot be read from or written to the file.
"""
return self._sink.closed
def __enter__(self):
self._sink.__enter__()
return self
def __exit__(self, exception_type, exception_value, traceback):
self._sink.__exit__(exception_type, exception_value, traceback)
def _new_tree(self, tree):
self._trees[tree._cascading.key.seek_location] = tree
def _new_ntuple(self, ntuple):
self._ntuples[ntuple._cascading.key.seek_location] = ntuple
def _has_tree(self, loc):
return loc in self._trees
def _get_tree(self, loc):
return self._trees[loc]
def _has_ntuple(self, loc):
return loc in self._ntuples
def _get_ntuple(self, loc):
return self._ntuples[loc]
def _move_tree(self, oldloc, newloc):
tree = self._trees[oldloc]
del self._trees[oldloc]
self._trees[newloc] = tree
class WritableDirectory(MutableMapping):
"""
Args:
path (tuple of str): Path of directory names to this subdirectory; ``()`` for
the root (first) directory.
file (:doc:`uproot.writing.writable.WritableFile`): Handle to the file in
which this directory can be found.
cascading (:doc:`uproot.writing._cascade.CascadingDirectory`): The low-level
directory object.
Represents a writable ``TDirectory`` from a ROOT file.
Be careful not to confuse :doc:`uproot.writing.writable.WritableFile` and
:doc:`uproot.writing.writable.WritableDirectory`: files are for modifying global
information such as the TStreamerInfo and FreeSegments, whereas directories
are for data in local hierarchies.
A :doc:`uproot.writing.writable.WritableDirectory` is a Python ``MutableMapping``,
which uses square bracket syntax to read, write, and delete objects:
.. code-block:: python
my_directory["histogram"]
my_directory["histogram"] = np.histogram(...)
del my_directory["histogram"]
Objects in ROOT files also have "cycle numbers," which allow multiple versions
of an object to exist with the same name. A cycle number may be specified after
a semicolon for *reading* and *deleting* only:
.. code-block:: python
my_directory["histogram;2"]
del my_directory["histogram;2"]
When *writing*, cycle numbers are generated to avoid overwriting previous objects:
.. code-block:: python
my_directory["histogram"] = np.histogram(...) # creates a new histogram
my_directory["histogram"] = np.histogram(...) # creates another histogram
Note that this is unlike a Python ``MutableMapping``, which would overwrite the
object in the second assignment. However, it is the way ROOT I/O works; use ``del``
to remove unwanted versions of objects.
Any types of objects that can be read from a :doc:`uproot.reading.ReadOnlyDirectory`
can be read from a :doc:`uproot.writing.writable.WritableDirectory` *except TTrees*. A
TTree can only be read from a :doc:`uproot.reading.ReadOnlyDirectory` if it was
created in this open file handle, and then it returns a :doc:`uproot.writing.writable.WritableTree`
instead of the :doc:`uproot.behaviors.TTree.TTree` that you would get from a
:doc:`uproot.reading.ReadOnlyDirectory`. Readable TTrees and writable TTrees are
distinct, with separate sets of features.
Note that subdirectories can be created by assigning to path names that include
slashes:
.. code-block:: python
my_directory["subdir1/subdir2/new_object"] = new_object
Subdirectories created this way will never be empty; to make an empty directory,
use :ref:`uproot.writing.writable.WritableDirectory.mkdir`.
Similarly, non-empty TTrees can be created by assignment (see :doc:`uproot.writing.writable.WritableTree`
for recognized TTree-like data), but empty TTrees require the
:ref:`uproot.writing.writable.WritableDirectory.mktree` method.
"""
def __init__(self, path, file, cascading):
self._path = path
self._file = file
self._cascading = cascading
self._subdirs = {}
def __repr__(self):
return "<WritableDirectory {} at 0x{:012x}>".format(
repr("/" + "/".join(self._path)), id(self)
)
@property
def path(self):
"""
Path of directory names to this subdirectory as a tuple of strings; e.g. ``()``
for the root (first) directory.
"""
return self._path
@property
def object_path(self):
"""
Path of directory names to this subdirectory as a single string, delimited
by slashes.
"""
return "/".join(("", *self._path, "")).replace("//", "/")
@property
def file_path(self):
"""
Filesystem path of the open file, or None if using a file-like object.
"""
return self._file.file_path
@property
def file(self):
"""
Handle to the :doc:`uproot.writing.writable.WritableDirectory` in which
this directory can be found.
"""
return self._file
def close(self):
"""
Explicitly close the file.
(Files can also be closed with the Python ``with`` statement, as context
managers.)
After closing, objects cannot be read from or written to the file.
"""
self._file.close()
@property
def closed(self) -> bool:
"""
True if the file has been closed; False otherwise.
The file may have been closed explicitly with
:ref:`uproot.writing.writable.WritableFile.close` or implicitly in the Python
``with`` statement, as a context manager.
After closing, objects cannot be read from or written to the file.
"""
return self._file.closed
def __enter__(self):
self._file.sink.__enter__()
return self
def __exit__(self, exception_type, exception_value, traceback):
self._file.sink.__exit__(exception_type, exception_value, traceback)
@property
def compression(self):
"""
Compression algorithm and level (:doc:`uproot.compression.Compression` or None)
for new objects added to the file.
This property can be changed, which allows you to write different objects
with different compression settings.
"""
return self._file.compression
@compression.setter
def compression(self, value):
self._file.compression = value
def __len__(self):
return self._cascading.data.num_keys + sum(
len(self._subdir(x)) for x in self._cascading.data.dir_names
)
def __contains__(self, where):
if self._cascading.data.haskey(where):
return True
return any(where in self._subdir(x) for x in self._cascading.data.dir_names)
def __iter__(self):
return self.iterkeys()
def _ipython_key_completions_(self):
"""
Supports key-completion in an IPython or Jupyter kernel.
"""
return self.iterkeys()
def keys(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return the names of objects directly accessible
in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in those names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns the names of the objects in this ``TDirectory`` as a list of
strings.
Note that this does not read any data from the file.
"""
return list(
self.iterkeys(
recursive=recursive,
cycle=cycle,
filter_name=filter_name,
filter_classname=filter_classname,
)
)
def values(
self,
*,
recursive=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return objects directly accessible in this
``TDirectory``.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns objects in this ``TDirectory`` as a list of
:doc:`uproot.model.Model`.
Note that this reads all objects that are selected by ``filter_name``
and ``filter_classname``.
"""
return list(
self.itervalues(
recursive=recursive,
filter_name=filter_name,
filter_classname=filter_classname,
)
)
def items(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return (name, object) pairs directly accessible
in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in the names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns (name, object) pairs for objects in this ``TDirectory`` as a
list of 2-tuples of (str, :doc:`uproot.model.Model`).
Note that this reads all objects that are selected by ``filter_name``
and ``filter_classname``.
"""
return list(
self.iteritems(
recursive=recursive,
cycle=cycle,
filter_name=filter_name,
filter_classname=filter_classname,
)
)
def classnames(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return the names and classnames of objects
directly accessible in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in the names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns the names and C++ (decoded) classnames of the objects in this
``TDirectory`` as a dict of str \u2192 str.
Note that this does not read any data from the file.
"""
return dict(
self.iterclassnames(
recursive=recursive,
cycle=cycle,
filter_name=filter_name,
filter_classname=filter_classname,
)
)
def iterkeys(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return the names of objects directly accessible
in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in those names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns the names of the objects in this ``TDirectory`` as an iterator
over strings.
Note that this does not read any data from the file.
"""
filter_name = uproot._util.regularize_filter(filter_name)
filter_classname = uproot._util.regularize_filter(filter_classname)
for keyname, cyclenum, classname in self._cascading.data.key_triples:
if (filter_name is no_filter or filter_name(keyname)) and (
filter_classname is no_filter or filter_classname(classname)
):
if cycle:
yield f"{keyname};{cyclenum}"
else:
yield keyname
if recursive and classname in ("TDirectory", "TDirectoryFile"):
for k1 in self._get(keyname, cyclenum).iterkeys(
recursive=recursive,
cycle=cycle,
filter_name=filter_name,
filter_classname=filter_classname,
):
k2 = f"{keyname}/{k1}"
k3 = k2[: k2.index(";")] if ";" in k2 else k2
if filter_name is no_filter or filter_name(k3):
yield k2
def itervalues(
self,
*,
recursive=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return objects directly accessible in this
``TDirectory``.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns objects in this ``TDirectory`` as an iterator over
:doc:`uproot.model.Model`.
Note that this reads all objects that are selected by ``filter_name``
and ``filter_classname``.
"""
for keyname in self.iterkeys(
recursive=recursive,
cycle=True,
filter_name=filter_name,
filter_classname=filter_classname,
):
yield self[keyname]
def iteritems(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return (name, object) pairs directly accessible
in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in the names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns (name, object) pairs for objects in this ``TDirectory`` as an
iterator over 2-tuples of (str, :doc:`uproot.model.Model`).
Note that this reads all objects that are selected by ``filter_name``
and ``filter_classname``.
"""
for keyname in self.iterkeys(
recursive=recursive,
cycle=True,
filter_name=filter_name,
filter_classname=filter_classname,
):
if not cycle:
at = keyname.index(";")
keyname = keyname[:at] # noqa: PLW2901 (overwriting keyname)
yield keyname, self[keyname]
def iterclassnames(
self,
*,
recursive=True,
cycle=True,
filter_name=no_filter,
filter_classname=no_filter,
):
"""
Args:
recursive (bool): If True, descend into any nested subdirectories.
If False, only return the names and classnames of objects
directly accessible in this ``TDirectory``.
cycle (bool): If True, include the cycle numbers in the names.
filter_name (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by name.
filter_classname (None, glob string, regex string in ``"/pattern/i"`` syntax, function of str \u2192 bool, or iterable of the above): A
filter to select keys by C++ (decoded) classname.
Returns the names and C++ (decoded) classnames of the objects in this
``TDirectory`` as an iterator of 2-tuples of (str, str).
Note that this does not read any data from the file.
"""
filter_name = uproot._util.regularize_filter(filter_name)
filter_classname = uproot._util.regularize_filter(filter_classname)
for keyname, cyclenum, classname in self._cascading.data.key_triples:
if (filter_name is no_filter or filter_name(keyname)) and (
filter_classname is no_filter or filter_classname(classname)
):
if cycle:
yield f"{keyname};{cyclenum}", classname
else:
yield keyname, classname
if recursive and classname in ("TDirectory", "TDirectoryFile"):
for k1, c1 in self._get(keyname, cyclenum).iterclassnames(
recursive=recursive,
cycle=cycle,
filter_name=filter_name,
filter_classname=filter_classname,
):
k2 = f"{keyname}/{k1}"
k3 = k2[: k2.index(";")] if ";" in k2 else k2
if filter_name is no_filter or filter_name(k3):
yield k2, c1
def _get_del_search(self, where, isget):
if "/" in where or ":" in where:
items = where.split("/")
step = last = self
for i, item in enumerate(items):
if item != "":
if isinstance(step, WritableDirectory):
if ":" in item and not step._cascading.data.haskey(item):
raise uproot.KeyInFileError(
where,
because="TTrees in writable files can't be indexed by TBranch name",
file_path=self.file_path,
)
else:
last = step
step = step[item]
elif isinstance(step, WritableTree):
rest = items[i:]
if len(rest) != 0:
raise uproot.KeyInFileError(
where,
because="TTrees in writable files can't be indexed by TBranch name",
file_path=self.file_path,
)
return step
else:
raise uproot.KeyInFileError(
where,
because="/".join(items[:i]) + " is not a TDirectory",
keys=last._cascading.data.key_names,
file_path=self.file_path,
)
return step
else:
if ";" in where:
at = where.rindex(";")
item, cycle = where[:at], where[at + 1 :]
try:
cycle = int(cycle)
except ValueError:
item, cycle = where, None
else:
item, cycle = where, None
if isget:
return self._get(item, cycle)
else:
return self._del(item, cycle)
def __getitem__(self, where):
if self._file.sink.closed:
raise ValueError("cannot get data from a closed file")
return self._get_del_search(where, True)
def __setitem__(self, where, what):
if self._file.sink.closed:
raise ValueError("cannot write data to a closed file")
self.update({where: what})
def __delitem__(self, where):
if self._file.sink.closed:
raise ValueError("cannot delete data from a closed file")
return self._get_del_search(where, False)
def _get(self, name, cycle):
key = self._cascading.data.get_key(name, cycle)
if key is None:
raise uproot.exceptions.KeyInFileError(
name,
cycle="any" if cycle is None else cycle,
keys=self._cascading.data.key_names,
file_path=self.file_path,
object_path=self.object_path,
)