This repository has been archived by the owner on Jun 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
tree.py
2093 lines (1736 loc) · 97.7 KB
/
tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot/blob/master/LICENSE
from __future__ import absolute_import
import base64
import codecs
import glob
import importlib
import inspect
import itertools
import math
import numbers
import os
import re
import struct
import sys
import threading
from collections import namedtuple
from collections import OrderedDict
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import numpy
import cachetools
import awkward
import uproot_methods.profiles
import uproot.rootio
from uproot.rootio import _bytesid
from uproot.rootio import _memsize
from uproot.rootio import nofilter
from uproot.interp.auto import interpret
from uproot.interp.numerical import asdtype
from uproot.interp.jagged import asjagged
from uproot.interp.objects import asobj
from uproot.interp.objects import asgenobj
from uproot.source.cursor import Cursor
from uproot.source.memmap import MemmapSource
from uproot.source.xrootd import XRootDSource
from uproot.source.http import HTTPSource
if sys.version_info[0] <= 2:
string_types = (unicode, str)
else:
string_types = (str, bytes)
def _delayedraise(excinfo):
if excinfo is not None:
cls, err, trc = excinfo
if sys.version_info[0] <= 2:
exec("raise cls, err, trc")
else:
raise err.with_traceback(trc)
def _filename_explode(x):
if isinstance(x, getattr(os, "PathLike", ())):
x = os.fspath(x)
elif hasattr(x, "__fspath__"):
x = x.__fspath__()
elif x.__class__.__module__ == "pathlib":
import pathlib
if isinstance(x, pathlib.Path):
x = str(x)
parsed = urlparse(x)
if _bytesid(parsed.scheme) == b"file" or len(parsed.scheme) == 0 or (os.name == "nt" and _filename_explode._windows_absolute.match(x) is not None):
if not (os.name == "nt" and _filename_explode._windows_absolute.match(x) is not None):
path = parsed.netloc + parsed.path
pattern = os.path.expanduser(path)
if "*" in pattern or "?" in pattern or "[" in pattern:
out = sorted(glob.glob(pattern))
if len(out) == 0:
raise TypeError("no matches for filename {0}".format(repr(pattern)))
else:
out = [pattern]
return out
else:
return [x]
_filename_explode._windows_absolute = re.compile(r"^[A-Za-z]:\\")
def _normalize_awkwardlib(awkwardlib):
if awkwardlib is None:
return awkward
elif isinstance(awkwardlib, str):
return importlib.import_module(awkwardlib)
else:
return awkwardlib
def _normalize_entrystartstop(numentries, entrystart, entrystop):
if entrystart is None:
entrystart = 0
elif entrystart < 0:
entrystart += numentries
entrystart = min(numentries, max(0, entrystart))
if entrystop is None:
entrystop = numentries
elif entrystop < 0:
entrystop += numentries
entrystop = min(numentries, max(0, entrystop))
if entrystop < entrystart:
raise IndexError("entrystop must be greater than or equal to entrystart")
return int(entrystart), int(entrystop)
################################################################ high-level interface
def iterate(path, treepath, branches=None, entrysteps=float("inf"), outputtype=dict, namedecode=None, reportpath=False, reportfile=False, reportentries=False, flatten=False, flatname=None, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, blocking=True, localsource=MemmapSource.defaults, xrootdsource=XRootDSource.defaults, httpsource=HTTPSource.defaults, **options):
awkward = _normalize_awkwardlib(awkwardlib)
for tree, branchesinterp, globalentrystart, thispath, thisfile in _iterate(path, treepath, branches, awkward, localsource, xrootdsource, httpsource, **options):
for start, stop, arrays in tree.iterate(branches=branchesinterp, entrysteps=entrysteps, outputtype=outputtype, namedecode=namedecode, reportentries=True, entrystart=0, entrystop=tree.numentries, flatten=flatten, flatname=flatname, awkwardlib=awkward, cache=cache, basketcache=basketcache, keycache=keycache, executor=executor, blocking=blocking):
if getattr(outputtype, "__name__", None) == "DataFrame" and getattr(outputtype, "__module__", None) == "pandas.core.frame":
if type(arrays.index).__name__ == "MultiIndex":
if hasattr(arrays.index.levels[0], "array"):
index = arrays.index.levels[0].array # pandas>=0.24.0
else:
index = arrays.index.levels[0].values # pandas<0.24.0
awkward.numpy.add(index, globalentrystart, out=index)
elif type(arrays.index).__name__ == "RangeIndex":
if hasattr(arrays.index, "start") and hasattr(arrays.index, "stop"):
indexstart = arrays.index.start # pandas>=0.25.0
indexstop = arrays.index.stop
else:
indexstart = arrays.index._start # pandas<0.25.0
indexstop = arrays.index._stop
arrays.index = type(arrays.index)(indexstart + globalentrystart, indexstop + globalentrystart)
else:
if hasattr(arrays.index, "array"):
index = arrays.index.array # pandas>=0.24.0
else:
index = arrays.index.values # pandas<0.24.0
awkward.numpy.add(index, globalentrystart, out=index)
out = (arrays,)
if reportentries:
out = (globalentrystart + start, globalentrystart + stop) + out
if reportfile:
out = (thisfile,) + out
if reportpath:
out = (thispath,) + out
if len(out) == 1:
yield out[0]
else:
yield out
def _iterate(path, treepath, branches, awkward, localsource, xrootdsource, httpsource, **options):
if isinstance(path, string_types):
paths = _filename_explode(path)
else:
paths = [y for x in path for y in _filename_explode(x)]
globalentrystart = 0
for path in paths:
file = uproot.rootio.open(path, localsource=localsource, xrootdsource=xrootdsource, httpsource=httpsource, **options)
try:
tree = file[treepath]
except KeyError:
continue
branchesinterp = OrderedDict()
for branch, interpretation in tree._normalize_branches(branches, awkward):
branchesinterp[branch.name] = interpretation
yield tree, branchesinterp, globalentrystart, path, file
globalentrystart += tree.numentries
################################################################ methods for TTree
class TTreeMethods(object):
# makes __doc__ attribute mutable before Python 3.3
__metaclass__ = type.__new__(type, "type", (uproot.rootio.ROOTObject.__metaclass__,), {})
_copycontext = True
_vector_regex = re.compile(b"^vector<(.+)>$")
_objectpointer_regex = re.compile(br"\(([^()]*)\)$")
def _attachstreamer(self, branch, streamer, streamerinfosmap, isTClonesArray):
if streamer is None:
m = re.match(self._vector_regex, getattr(branch, "_fClassName", b""))
if m is None:
if branch.name in streamerinfosmap:
streamer = streamerinfosmap[branch.name]
else:
return
else:
if m.group(1) in streamerinfosmap:
substreamer = streamerinfosmap[m.group(1)]
if isinstance(substreamer, uproot.rootio.TStreamerInfo):
streamer = uproot.rootio.TStreamerSTL.vector(None, substreamer._fName)
else:
streamer = uproot.rootio.TStreamerSTL.vector(substreamer._fType, substreamer._fTypeName)
else:
return
if isinstance(streamer, uproot.rootio.TStreamerInfo):
if len(streamer._fElements) == 1 and isinstance(streamer._fElements[0], uproot.rootio.TStreamerBase) and streamer._fElements[0]._fName == b"TObjArray":
if streamer._fName == b"TClonesArray":
return self._attachstreamer(branch, streamerinfosmap.get(branch._fClonesName, None), streamerinfosmap, True)
else:
# FIXME: can only determine streamer by reading some values?
return
elif len(streamer._fElements) == 1 and isinstance(streamer._fElements[0], uproot.rootio.TStreamerSTL) and streamer._fElements[0]._fName == b"This":
return self._attachstreamer(branch, streamer._fElements[0], streamerinfosmap, isTClonesArray)
if isinstance(streamer, uproot.rootio.TStreamerObject):
if streamer._fTypeName == b"TClonesArray":
return self._attachstreamer(branch, streamerinfosmap.get(branch._fClonesName, None), streamerinfosmap, True)
else:
return self._attachstreamer(branch, streamerinfosmap.get(streamer._fTypeName, None), streamerinfosmap, True)
branch._streamer = streamer
branch._isTClonesArray = isTClonesArray
if isinstance(streamer, uproot.rootio.TStreamerSTL) and streamer._fSTLtype == uproot.const.kSTLvector:
branch._vecstreamer = streamerinfosmap.get(re.match(self._vector_regex, streamer._fTypeName).group(1), None)
isTClonesArray = True
else:
branch._vecstreamer = None
digDeeperTypes = (uproot.rootio.TStreamerObject, uproot.rootio.TStreamerObjectAny, uproot.rootio.TStreamerObjectPointer, uproot.rootio.TStreamerObjectAnyPointer)
members = None
if isinstance(streamer, uproot.rootio.TStreamerInfo):
members = streamer.members
elif isinstance(streamer, digDeeperTypes):
typename = streamer._fTypeName.rstrip(b"*")
if typename in streamerinfosmap:
m = self._objectpointer_regex.search(streamer._fTitle)
if typename == b'TClonesArray' and m is not None:
typename = m.group(1)
members = streamerinfosmap[typename].members
elif isinstance(streamer, uproot.rootio.TStreamerSTL):
try:
# FIXME: string manipulation only works for one-parameter templates
typename = streamer._fTypeName[streamer._fTypeName.index(b"<") + 1 : streamer._fTypeName.rindex(b">")].rstrip(b"*")
except ValueError:
pass
else:
if typename in streamerinfosmap:
members = streamerinfosmap[typename].members
if members is not None:
for subbranch in branch.itervalues(recursive=True):
name = subbranch._fName
if name.startswith(branch._fName + b"."): # drop parent branch's name
name = name[len(branch._fName) + 1:]
submembers = members
while True: # drop nested struct names one at a time
try:
index = name.index(b".")
except ValueError:
break
else:
base, name = name[:index], name[index + 1:]
if base in submembers and isinstance(submembers[base], digDeeperTypes):
submembers = streamerinfosmap[submembers[base]._fTypeName.rstrip(b"*")].members
try:
name = name[:name.index(b"[")]
except ValueError:
pass
self._attachstreamer(subbranch, submembers.get(name, None), streamerinfosmap, isTClonesArray)
def _postprocess(self, source, cursor, context, parent):
self._context = context
self._context.treename = self.name
self._context.speedbump = True
for branch in self._fBranches:
self._attachstreamer(branch, context.streamerinfosmap.get(getattr(branch, "_fClassName", None), None), context.streamerinfosmap, False)
self._branchlookup = {}
self._fill_branchlookup(self._branchlookup)
leaf2branch = {}
for branch in self.itervalues(recursive=True):
if len(branch._fLeaves) == 1:
leaf2branch[id(branch._fLeaves[0])] = branch
for branch in self.itervalues(recursive=True):
if len(branch._fLeaves) > 0:
branch._countleaf = branch._fLeaves[0]._fLeafCount
if branch._countleaf is not None:
branch._countbranch = leaf2branch.get(id(branch._countleaf), None)
if getattr(self, "_fAliases", None) is None:
self.aliases = {}
else:
self.aliases = dict((alias._fName, alias._fTitle) for alias in self._fAliases)
def _fill_branchlookup(self, branchlookup):
for subbranch in self._fBranches:
subbranch._fill_branchlookup(branchlookup)
branchlookup[subbranch.name] = subbranch
@property
def name(self):
return self._fName
@property
def title(self):
return self._fTitle
@property
def numentries(self):
return int(self._fEntries)
@property
def numbranches(self):
count = 0
for x in self.itervalues(recursive=True):
count += 1
return count
def iterkeys(self, recursive=False, filtername=nofilter, filtertitle=nofilter, aliases=True):
for branch in self.itervalues(recursive, filtername, filtertitle):
if aliases:
for aliasname, branchname in self.aliases.items():
if branch.name == branchname:
yield aliasname
yield branch.name
def itervalues(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
for branch in self._fBranches:
if filtername(branch.name) and filtertitle(branch.title):
yield branch
if recursive:
for x in branch.itervalues(recursive, filtername, filtertitle):
yield x
def iteritems(self, recursive=False, filtername=nofilter, filtertitle=nofilter, aliases=True):
for branch in self.itervalues(recursive, filtername, filtertitle):
if aliases:
for aliasname, branchname in self.aliases.items():
if branch.name == branchname:
yield aliasname, branch
yield branch.name, branch
def keys(self, recursive=False, filtername=nofilter, filtertitle=nofilter, aliases=True):
return list(self.iterkeys(recursive=recursive, filtername=filtername, filtertitle=filtertitle, aliases=aliases))
def _ipython_key_completions_(self):
"Support for completion of keys in an IPython kernel"
return [item.decode("ascii") for item in self.iterkeys()]
def values(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
return list(self.itervalues(recursive=recursive, filtername=filtername, filtertitle=filtertitle))
def items(self, recursive=False, filtername=nofilter, filtertitle=nofilter, aliases=True):
return list(self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle, aliases=aliases))
def allkeys(self, filtername=nofilter, filtertitle=nofilter, aliases=True):
return self.keys(recursive=True, filtername=filtername, filtertitle=filtertitle, aliases=aliases)
def allvalues(self, filtername=nofilter, filtertitle=nofilter):
return self.values(recursive=True, filtername=filtername, filtertitle=filtertitle)
def allitems(self, filtername=nofilter, filtertitle=nofilter, aliases=True):
return self.items(recursive=True, filtername=filtername, filtertitle=filtertitle, aliases=aliases)
def get(self, name, recursive=True, filtername=nofilter, filtertitle=nofilter, aliases=True):
name = _bytesid(name)
try:
return self._branchlookup[name]
except KeyError:
for n, b in self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle, aliases=aliases):
if n == name:
self._branchlookup[name] = b
return b
raise uproot.rootio._KeyError("not found: {0}\n in file: {1}".format(repr(name), self._context.sourcepath))
def __contains__(self, name):
try:
self.get(name)
except KeyError:
return False
else:
return True
def mempartitions(self, numbytes, branches=None, entrystart=None, entrystop=None, keycache=None, linear=True):
m = _memsize(numbytes)
if m is not None:
numbytes = m
if numbytes <= 0:
raise ValueError("target numbytes must be positive")
awkward = _normalize_awkwardlib(None)
branches = list(self._normalize_branches(branches, awkward))
entrystart, entrystop = _normalize_entrystartstop(self.numentries, entrystart, entrystop)
if not linear:
raise NotImplementedError("non-linear mempartition has not been implemented")
relevant_numbytes = 0.0
for branch, interpretation in branches:
if branch._recoveredbaskets is None:
branch._tryrecover()
for i, key in enumerate(branch._threadsafe_iterate_keys(keycache, False)):
start, stop = branch._entryoffsets[i], branch._entryoffsets[i + 1]
if entrystart < stop and start < entrystop:
this_numbytes = key._fObjlen * (min(stop, entrystop) - max(start, entrystart)) / float(stop - start)
assert this_numbytes >= 0.0
relevant_numbytes += this_numbytes
entrysteps = max(1, int(round(math.ceil((entrystop - entrystart) * numbytes / relevant_numbytes))))
start, stop = entrystart, entrystart
while stop < entrystop:
stop = min(stop + entrysteps, entrystop)
if stop > start:
yield start, stop
start = stop
def clusters(self, branches=None, entrystart=None, entrystop=None, strict=False):
awkward = _normalize_awkwardlib(None)
branches = list(self._normalize_branches(branches, awkward))
# convenience class; simplifies presentation of the algorithm
class BranchCursor(object):
def __init__(self, branch):
self.branch = branch
self.basketstart = 0
self.basketstop = 0
@property
def entrystart(self):
return self.branch.basket_entrystart(self.basketstart)
@property
def entrystop(self):
return self.branch.basket_entrystop(self.basketstop)
cursors = [BranchCursor(branch) for branch, interpretation in branches if branch.numbaskets > 0]
if len(cursors) == 0:
yield _normalize_entrystartstop(self.numentries, entrystart, entrystop)
else:
# everybody starts at the same entry number; if there is no such place before someone runs out of baskets, there will be an exception
leadingstart = max(cursor.entrystart for cursor in cursors)
while not all(cursor.entrystart == leadingstart for cursor in cursors):
for cursor in cursors:
while cursor.entrystart < leadingstart:
cursor.basketstart += 1
cursor.basketstop += 1
leadingstart = max(cursor.entrystart for cursor in cursors)
entrystart, entrystop = _normalize_entrystartstop(self.numentries, entrystart, entrystop)
# move all cursors forward, yielding a (start, stop) pair if their baskets line up
while any(cursor.basketstop < cursor.branch.numbaskets for cursor in cursors):
# move all subleading baskets forward until they are no longer subleading
leadingstop = max(cursor.entrystop for cursor in cursors)
for cursor in cursors:
while cursor.entrystop < leadingstop:
cursor.basketstop += 1
# if they all line up, this is a good cluster
if all(cursor.entrystop == leadingstop for cursor in cursors):
# check to see if it's within the bounds the user requested (strictly or not strictly)
if strict:
if entrystart <= leadingstart and leadingstop <= entrystop:
yield leadingstart, leadingstop
else:
if entrystart < leadingstop and leadingstart < entrystop:
yield leadingstart, leadingstop
# anyway, move all the starts to the new stopping position and move all stops forward by one
leadingstart = leadingstop
for cursor in cursors:
cursor.basketstart = cursor.basketstop
cursor.basketstop += 1
# stop iterating if we're past all acceptable clusters
if leadingstart >= entrystop:
break
def array(self, branch, interpretation=None, entrystart=None, entrystop=None, flatten=False, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, blocking=True):
awkward = _normalize_awkwardlib(awkwardlib)
branches = list(self._normalize_branches(branch, awkward))
if len(branches) == 1:
if interpretation is None:
tbranch, interpretation = branches[0]
else:
tbranch, _ = branches[0]
else:
raise ValueError("list of branch names or glob/regex matches more than one branch; use TTree.arrays (plural)")
return tbranch.array(interpretation=interpretation, entrystart=entrystart, entrystop=entrystop, flatten=flatten, awkwardlib=awkwardlib, cache=cache, basketcache=basketcache, keycache=keycache, executor=executor, blocking=blocking)
def arrays(self, branches=None, outputtype=dict, namedecode=None, entrystart=None, entrystop=None, flatten=False, flatname=None, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, blocking=True):
awkward = _normalize_awkwardlib(awkwardlib)
branches = list(self._normalize_branches(branches, awkward))
for branch, interpretation in branches:
if branch._recoveredbaskets is None:
branch._tryrecover()
if flatten is None:
branches = [(branch, interpretation) for branch, interpretation in branches if not isinstance(interpretation, asjagged)]
flatten = False
# for the case of outputtype == pandas.DataFrame, do some preparation to fill DataFrames efficiently
ispandas = getattr(outputtype, "__name__", None) == "DataFrame" and getattr(outputtype, "__module__", None) == "pandas.core.frame"
entrystart, entrystop = _normalize_entrystartstop(self.numentries, entrystart, entrystop)
# start the job of filling the arrays
futures = [(branch.name if namedecode is None else branch.name.decode(namedecode), interpretation, branch.array(interpretation=interpretation, entrystart=entrystart, entrystop=entrystop, flatten=(flatten and not ispandas), awkwardlib=awkward, cache=cache, basketcache=basketcache, keycache=keycache, executor=executor, blocking=False)) for branch, interpretation in branches]
# make functions that wait for the filling job to be done and return the right outputtype
if outputtype == namedtuple:
outputtype = namedtuple("Arrays", [codecs.ascii_decode(branch.name, "replace")[0] if namedecode is None else branch.name.decode(namedecode) for branch, interpretation in branches])
def wait():
return outputtype(*[future() for name, interpretation, future in futures])
elif ispandas:
import uproot._connect._pandas
def wait():
return uproot._connect._pandas.futures2df(futures, outputtype, entrystart, entrystop, flatten, flatname, awkward)
elif isinstance(outputtype, type) and issubclass(outputtype, dict):
def wait():
return outputtype((name, future()) for name, interpretation, future in futures)
elif isinstance(outputtype, type) and issubclass(outputtype, (list, tuple)):
def wait():
return outputtype(future() for name, interpretation, future in futures)
else:
def wait():
return outputtype(*[future() for name, interpretation, future in futures])
# if blocking, return the result of that function; otherwise, the function itself
if blocking:
return wait()
else:
return wait
def lazyarray(self, branch, interpretation=None, entrysteps=None, entrystart=None, entrystop=None, flatten=False, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, persistvirtual=False, chunked=True):
awkward = _normalize_awkwardlib(awkwardlib)
branches = list(self._normalize_branches(branch, awkward))
if len(branches) == 1:
if interpretation is None:
tbranch, interpretation = branches[0]
else:
tbranch, _ = branches[0]
else:
raise ValueError("list of branch names or glob/regex matches more than one branch; use TTree.lazyarrays (plural)")
return tbranch.lazyarray(interpretation=interpretation, entrysteps=entrysteps, entrystart=entrystart, entrystop=entrystop, flatten=flatten, awkwardlib=awkwardlib, cache=cache, basketcache=basketcache, keycache=keycache, executor=executor, persistvirtual=persistvirtual, chunked=chunked)
def lazyarrays(self, branches=None, namedecode="utf-8", entrysteps=None, entrystart=None, entrystop=None, flatten=False, profile=None, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, persistvirtual=False, chunked=True):
entrystart, entrystop = _normalize_entrystartstop(self.numentries, entrystart, entrystop)
if not chunked and entrysteps is None:
entrysteps = float('inf')
entrysteps = list(self._normalize_entrysteps(entrysteps, branches, entrystart, entrystop, keycache))
awkward = _normalize_awkwardlib(awkwardlib)
branches = list(self._normalize_branches(branches, awkward))
for branch, interpretation in branches:
if branch._recoveredbaskets is None:
branch._tryrecover()
lazytree = _LazyTree(self._context.sourcepath, self._context.treename, self, dict((b.name, x) for b, x in branches), flatten, awkward.__name__, basketcache, keycache, executor)
out = awkward.Table()
for branch, interpretation in branches:
inner = interpretation
while isinstance(inner, asjagged):
inner = inner.content
if isinstance(inner, asobj) and getattr(inner.cls, "_arraymethods", None) is not None:
VirtualArray = awkward.Methods.mixin(inner.cls._arraymethods, awkward.VirtualArray)
elif isinstance(inner, asgenobj) and getattr(inner.generator.cls, "_arraymethods", None) is not None:
VirtualArray = awkward.Methods.mixin(inner.generator.cls._arraymethods, awkward.VirtualArray)
else:
VirtualArray = awkward.VirtualArray
name = branch.name.decode("ascii") if namedecode is None else branch.name.decode(namedecode)
if chunked:
chunks = []
counts = []
for start, stop in entrysteps:
chunks.append(VirtualArray(lazytree, (branch.name, start, stop), cache=cache, type=awkward.type.ArrayType(stop - start, interpretation.type), persistvirtual=persistvirtual))
counts.append(stop - start)
out[name] = awkward.ChunkedArray(chunks, counts)
out[name].__doc__ = branch.title.decode('ascii')
else:
start, stop = entrysteps[0]
out[name] = VirtualArray(lazytree, (branch.name, start, stop), cache=cache, type=awkward.type.ArrayType(stop - start, interpretation.type), persistvirtual=persistvirtual)
out[name].__doc__ = branch.title.decode('ascii')
if profile is not None:
out = uproot_methods.profiles.transformer(profile)(out)
return out
def _normalize_entrysteps(self, entrysteps, branches, entrystart, entrystop, keycache):
numbytes = _memsize(entrysteps)
if numbytes is not None:
return self.mempartitions(numbytes, branches=branches, entrystart=entrystart, entrystop=entrystop, keycache=keycache, linear=True)
if isinstance(entrysteps, string_types):
raise ValueError("string {0} does not match the memory size pattern (number followed by B/kB/MB/GB/etc.)".format(repr(entrysteps)))
if entrysteps is None:
return self.clusters(branches, entrystart=entrystart, entrystop=entrystop, strict=False)
elif entrysteps == float("inf"):
return [(entrystart, min(entrystop, self.numentries))]
elif isinstance(entrysteps, (numbers.Integral, numpy.integer)):
entrystepsize = entrysteps
if entrystepsize <= 0:
raise ValueError("if an integer, entrysteps must be positive")
effectivestop = min(entrystop, self.numentries)
starts = numpy.arange(entrystart, effectivestop, entrystepsize)
stops = numpy.append(starts[1:], effectivestop)
return zip(starts, stops)
else:
try:
iter(entrysteps)
except TypeError:
raise TypeError("entrysteps must be None for cluster iteration, a positive integer for equal steps in number of entries (inf for maximal), a memory size string (number followed by B/kB/MB/GB/etc.), or an iterable of 2-tuples for explicit entry starts (inclusive) and stops (exclusive)")
return entrysteps
def iterate(self, branches=None, entrysteps=None, outputtype=dict, namedecode=None, reportentries=False, entrystart=None, entrystop=None, flatten=False, flatname=None, awkwardlib=None, cache=None, basketcache=None, keycache=None, executor=None, blocking=True):
if keycache is None:
keycache = {}
if basketcache is None:
basketcache = {}
explicit_basketcache = False
else:
explicit_basketcache = True
entrystart, entrystop = _normalize_entrystartstop(self.numentries, entrystart, entrystop)
entrysteps = self._normalize_entrysteps(entrysteps, branches, entrystart, entrystop, keycache)
awkward = _normalize_awkwardlib(awkwardlib)
branches = list(self._normalize_branches(branches, awkward))
for branch, interpretation in branches:
if branch._recoveredbaskets is None:
branch._tryrecover()
# for the case of outputtype == pandas.DataFrame, do some preparation to fill DataFrames efficiently
ispandas = getattr(outputtype, "__name__", None) == "DataFrame" and getattr(outputtype, "__module__", None) == "pandas.core.frame"
def evaluate(branch, interpretation, future, past, cachekey, pythonize):
if future is None:
return past
else:
out = interpretation.finalize(future(), branch)
if cache is not None:
cache[cachekey] = out
if flatten and isinstance(interpretation, asjagged):
return out.flatten()
elif pythonize:
return list(out)
else:
return out
if outputtype == namedtuple:
outputtype = namedtuple("Arrays", [codecs.ascii_decode(branch.name, "replace")[0] if namedecode is None else branch.name.decode(namedecode) for branch, interpretation in branches])
def wrap_for_python_scope(futures, start, stop):
return lambda: outputtype(*[evaluate(branch, interpretation, future, past, cachekey, False) for branch, interpretation, future, past, cachekey in futures])
elif ispandas:
import uproot._connect._pandas
def wrap_for_python_scope(futures, start, stop):
def wrap_again(branch, interpretation, future):
return lambda: interpretation.finalize(future(), branch)
return lambda: uproot._connect._pandas.futures2df([(branch.name, interpretation, wrap_again(branch, interpretation, future)) for branch, interpretation, future, past, cachekey in futures], outputtype, start, stop, flatten, flatname, awkward)
elif isinstance(outputtype, type) and issubclass(outputtype, dict):
def wrap_for_python_scope(futures, start, stop):
return lambda: outputtype((branch.name if namedecode is None else branch.name.decode(namedecode), evaluate(branch, interpretation, future, past, cachekey, False)) for branch, interpretation, future, past, cachekey in futures)
elif isinstance(outputtype, type) and issubclass(outputtype, (list, tuple)):
def wrap_for_python_scope(futures, start, stop):
return lambda: outputtype(evaluate(branch, interpretation, future, past, cachekey, False) for branch, interpretation, future, past, cachekey in futures)
else:
def wrap_for_python_scope(futures, start, stop):
return lambda: outputtype(*[evaluate(branch, interpretation, future, past, cachekey, False) for branch, interpretation, future, past, cachekey in futures])
for start, stop in entrysteps:
start = max(start, entrystart)
stop = min(stop, entrystop)
if start > stop:
continue
futures = []
for branch, interpretation in branches:
cachekey = branch._cachekey(interpretation, start, stop)
if branch.numbaskets == 0:
futures.append((branch, interpretation, interpretation.empty, None, cachekey))
else:
basketstart, basketstop = branch._basketstartstop(start, stop)
basket_itemoffset = branch._basket_itemoffset(interpretation, basketstart, basketstop, keycache)
basket_entryoffset = branch._basket_entryoffset(basketstart, basketstop)
if cache is not None:
out = cache.get(cachekey, None)
if out is not None:
futures.append((branch, interpretation, None, out, cachekey))
continue
future = branch._step_array(interpretation, basket_itemoffset, basket_entryoffset, start, stop, awkward, basketcache, keycache, executor, explicit_basketcache)
futures.append((branch, interpretation, future, None, cachekey))
out = wrap_for_python_scope(futures, start, stop)
if blocking:
out = out()
if reportentries:
yield start, stop, out
else:
yield out
def _format(self, indent=""):
# TODO: add TTree data to the bottom of this
out = []
for branch in self._fBranches:
out.extend(branch._format(indent))
return out
def show(self, foldnames=False, stream=sys.stdout):
if stream is None:
return "\n".join(self._format(foldnames))
else:
for line in self._format(foldnames):
stream.write(line)
stream.write("\n")
def _recover(self):
for branch in self.allvalues():
branch._recover()
def matches(self, branches):
awkward = _normalize_awkwardlib(None)
return [b.name for b, i in self._normalize_branches(branches, awkward, allownone=False, allowcallable=False, allowdict=False, allowstring=True)]
_branch_regex = re.compile(b"^/(.*)/([iLmsux]*)$")
@staticmethod
def _branch_flags(flags):
flagsbyte = 0
for flag in flags:
if flag == "i":
flagsbyte += re.I
elif flag == "L":
flagsbyte += re.L
elif flag == "m":
flagsbyte += re.M
elif flag == "s":
flagsbyte += re.S
elif flag == "u":
flagsbyte += re.U
elif flag == "x":
flagsbyte += re.X
return flagsbyte
def _normalize_branches(self, arg, awkward, allownone=True, allowcallable=True, allowdict=True, allowstring=True, aliases=True):
if allownone and arg is None: # no specification; read all branches
for branch in self.allvalues(): # that have interpretations
interpretation = interpret(branch, awkward)
if interpretation is not None:
yield branch, interpretation
elif allowcallable and callable(arg):
for branch in self.allvalues():
result = arg(branch)
if result is None or result is False:
pass
elif result is True: # function is a filter
interpretation = interpret(branch, awkward)
if interpretation is not None:
yield branch, interpretation
else: # function is giving interpretations
yield branch, branch._normalize_dtype(result, awkward)
elif allowdict and isinstance(arg, dict):
for word, interpretation in arg.items():
word = _bytesid(word)
isregex = re.match(self._branch_regex, word)
if isregex is not None:
regex, flags = isregex.groups()
for name, branch in self.iteritems(recursive=True, aliases=aliases):
if re.match(regex, name, self._branch_flags(flags)):
yield branch, branch._normalize_dtype(interpretation, awkward)
elif b"*" in word or b"?" in word or b"[" in word:
for name, branch in self.iteritems(recursive=True, aliases=aliases):
if name == word or glob.fnmatch.fnmatchcase(name, word):
yield branch, branch._normalize_dtype(interpretation, awkward)
else:
branch = self.get(word, aliases=aliases)
yield branch, branch._normalize_dtype(interpretation, awkward)
elif allowstring and isinstance(arg, string_types):
for x in self._normalize_branches([arg], awkward):
yield x
else:
try:
words = iter(arg) # only way to check for iterable (in general)
except Exception:
raise TypeError("'branches' argument not understood")
else:
for word in words:
word = _bytesid(word)
isregex = re.match(self._branch_regex, word)
if isregex is not None:
regex, flags = isregex.groups()
for name, branch in self.iteritems(recursive=True, aliases=aliases):
if re.match(regex, name, self._branch_flags(flags)):
interpretation = interpret(branch, awkward)
if interpretation is None:
if name == word:
raise ValueError("cannot interpret branch {0} as a Python type\n in file: {1}".format(repr(branch.name), self._context.sourcepath))
else:
yield branch, interpretation
elif b"*" in word or b"?" in word or b"[" in word:
for name, branch in self.iteritems(recursive=True, aliases=aliases):
if name == word or glob.fnmatch.fnmatchcase(name, word):
interpretation = interpret(branch, awkward)
if interpretation is None:
if name == word:
raise ValueError("cannot interpret branch {0} as a Python type\n in file: {1}".format(repr(branch.name), self._context.sourcepath))
else:
yield branch, interpretation
else:
branch = self.get(word, aliases=aliases)
interpretation = interpret(branch, awkward)
if interpretation is None:
raise ValueError("cannot interpret branch {0} as a Python type\n in file: {1}".format(repr(branch.name), self._context.sourcepath))
else:
yield branch, interpretation
def __len__(self):
return self.numentries
def __getitem__(self, name):
return self.get(name)
def __iter__(self):
# prevent Python's attempt to interpret __len__ and __getitem__ as iteration
raise TypeError("'TTree' object is not iterable")
@property
def pandas(self):
import uproot._connect._pandas
return uproot._connect._pandas.TTreeMethods_pandas(self)
################################################################ methods for TBranch
class TBranchMethods(object):
# makes __doc__ attribute mutable before Python 3.3
__metaclass__ = type.__new__(type, "type", (uproot.rootio.ROOTObject.__metaclass__,), {})
def _postprocess(self, source, cursor, context, parent):
self._source = source
self._context = context
self._streamer = None
self._interpretation = None
self._numgoodbaskets = 0
for i, x in enumerate(self._fBasketSeek):
if x == 0 or i == self._fWriteBasket:
break
self._numgoodbaskets += 1
if self.numentries == self._fBasketEntry[self._numgoodbaskets]:
self._recoveredbaskets = []
self._entryoffsets = self._fBasketEntry[: self._numgoodbaskets + 1].tolist()
self._recoverylock = None
else:
self._recoveredbaskets = None
self._entryoffsets = None
self._recoverylock = threading.Lock()
self._countbranch = None
self._tree_iofeatures = 0
if hasattr(parent, "_fIOFeatures"):
self._tree_iofeatures = parent._fIOFeatures._fIOBits
def _fill_branchlookup(self, branchlookup):
for subbranch in self._fBranches:
subbranch._fill_branchlookup(branchlookup)
branchlookup[subbranch.name] = subbranch
@property
def name(self):
return self._fName
@property
def title(self):
return self._fTitle
@property
def interpretation(self):
awkward = _normalize_awkwardlib(None)
if self._interpretation is None:
self._interpretation = interpret(self, awkward)
return self._interpretation
@property
def countbranch(self):
return self._countbranch
@property
def countleaf(self):
return self._countleaf
@property
def numentries(self):
return int(self._fEntries) # or self._fEntryNumber?
@property
def numbranches(self):
count = 0
for x in self.itervalues(recursive=True):
count += 1
return count
def iterkeys(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
for branch in self.itervalues(recursive, filtername, filtertitle):
yield branch.name
def itervalues(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
for branch in self._fBranches:
if filtername(branch.name) and filtertitle(branch.title):
yield branch
if recursive:
for x in branch.itervalues(recursive, filtername, filtertitle):
yield x
def iteritems(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
for branch in self._fBranches:
if filtername(branch.name) and filtertitle(branch.title):
yield branch.name, branch
if recursive:
for x in branch.iteritems(recursive, filtername, filtertitle):
yield x
def keys(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
return list(self.iterkeys(recursive=recursive, filtername=filtername, filtertitle=filtertitle))
def _ipython_key_completions_(self):
"Support for completion of keys in an IPython kernel"
return [item.decode("ascii") for item in self.iterkeys()]
def values(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
return list(self.itervalues(recursive=recursive, filtername=filtername, filtertitle=filtertitle))
def items(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
return list(self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle))
def allkeys(self, recursive=False, filtername=nofilter, filtertitle=nofilter):
return self.keys(recursive=True, filtername=filtername, filtertitle=filtertitle)
def allvalues(self, filtername=nofilter, filtertitle=nofilter):
return self.values(recursive=True, filtername=filtername, filtertitle=filtertitle)
def allitems(self, filtername=nofilter, filtertitle=nofilter):
return self.items(recursive=True, filtername=filtername, filtertitle=filtertitle)
def get(self, name, recursive=True, filtername=nofilter, filtertitle=nofilter, aliases=True):
name = _bytesid(name)
for n, b in self.iteritems(recursive=recursive, filtername=filtername, filtertitle=filtertitle):
if n == name:
return b
raise uproot.rootio._KeyError("not found: {0}\n in file: {1}".format(repr(name), self._context.sourcepath))
@property
def numbaskets(self):
if self._recoveredbaskets is None:
self._tryrecover()
return self._numgoodbaskets + len(self._recoveredbaskets)
def _cachekey(self, interpretation, entrystart, entrystop):
return "{0};{1};{2};{3};{4}-{5}".format(base64.b64encode(self._context.uuid).decode("ascii"), self._context.treename.decode("ascii"), self.name.decode("ascii"), interpretation.identifier, entrystart, entrystop)
def _basketcachekey(self, i):
return "{0};{1};{2};{3};raw".format(base64.b64encode(self._context.uuid).decode("ascii"), self._context.treename.decode("ascii"), self.name.decode("ascii"), i)
def _keycachekey(self, i):