ATLAS Offline Software
Loading...
Searching...
No Matches
python.RootUtils Namespace Reference

Classes

class  RootFileDumper

Functions

 import_root (batch=True)
 functions --------------------------------------------------------------—
 root_compile (src=None, fname=None, batch=True)
 _root_compile (src, fname, batch)
 _pythonize_tfile ()
 _getLeaf (l)
 _test_main ()

Variables

str __doc__ = "a few utils to ease the day-to-day work with ROOT"
str __author__ = "Sebastien Binet"
list __all__
list _tempfiles = []
bool _first_compile = True

Function Documentation

◆ _getLeaf()

python.RootUtils._getLeaf ( l)
protected

Definition at line 184 of file RootUtils.py.

184def _getLeaf (l):
185 tname = l.GetTypeName()
186 ndat = l.GetNdata()
187 if (l.GetLeafCount() # a varying length array
188 or ndat > 1): # a fixed size array
189 if tname in ['UInt_t', 'Int_t', 'ULong_t', 'Long_t', 'ULong64_t', 'Long64_t', 'UShort_t', 'Short_t', 'Bool_t']:
190 return tuple(l.GetValueLong64(i) for i in range(ndat))
191 elif tname in ['Float_t', 'Double_t', 'Float16_t', 'Double32_t']:
192 return tuple(l.GetValue(i) for i in range(ndat))
193 elif tname in ['UChar_t', 'Char_t']:
194 try:
195 return l.GetValueString() # TLeafC for variable size string
196 except Exception:
197 return tuple(l.GetValueLong64(i) for i in range(ndat)) # TLeafB for 8-bit integers
198 elif ndat == 1: # a single value
199 if tname in ['UInt_t', 'Int_t', 'ULong_t', 'Long_t', 'ULong64_t', 'Long64_t', 'UShort_t', 'Short_t', 'Bool_t']:
200 return l.GetValueLong64()
201 elif tname in ['Float_t', 'Double_t', 'Float16_t', 'Double32_t']:
202 return l.GetValue()
203 elif tname in ['UChar_t', 'Char_t']:
204 try:
205 return l.GetValueString() # TLeafC for variable size string
206 except Exception:
207 return l.GetValueLong64() # TLeafB for 8-bit integers
208
209 return None
210

◆ _pythonize_tfile()

python.RootUtils._pythonize_tfile ( )
protected

Definition at line 120 of file RootUtils.py.

120def _pythonize_tfile():
121 import cppyy
122 root = import_root()
123 import PyUtils.Helpers as H
124 with H.ShutUp(filters=[
125 re.compile(
126 'TClass::TClass:0: RuntimeWarning: no dictionary for.*'),
127 re.compile(
128 'Warning in <TEnvRec::ChangeValue>: duplicate entry.*'
129 ),
130 ]):
131 cppyy.load_library("libRootUtilsPyROOTDict")
132 _ = root.RootUtils.PyBytes
133 #MN: lines below fail in ROOT6 if PCM from RootUtils is not found
134 read_root_file = root.RootUtils._pythonize_read_root_file
135 tell_root_file = root.RootUtils._pythonize_tell_root_file
136 pass
137 def read(self, size=-1):
138 """read([size]) -> read at most size bytes, returned as a string.
139
140 If the size argument is negative or omitted, read until EOF is reached.
141 Notice that when in non-blocking mode, less data than what was requested
142 may be returned, even if no size parameter was given.
143
144 FIXME: probably doesn't follow python file-like conventions...
145 """
146 SZ = 4096
147
148 if size>=0:
149 #size = _adjust_sz(size)
150 #print ("-->0",self.tell(),size)
151 c_buf = read_root_file(self, size)
152 if c_buf and c_buf.sz:
153 v = c_buf.buf
154 return bytes([ord(v[i]) for i in range(v.size())])
155 return ''
156 else:
157 size = SZ
158 out = []
159 while True:
160 #size = _adjust_sz(size)
161 c_buf = read_root_file(self, size)
162 if c_buf and c_buf.sz:
163 v = c_buf.buf
164 chunk = bytes([ord(v[i]) for i in range(v.size())])
165 out.append(chunk)
166 else:
167 break
168 return b''.join(out)
169
170 root.TFile.read = read
171 del read
172
173 root.TFile.seek = root.TFile.Seek
174 root.TFile.tell = lambda self: tell_root_file(self)
175
181 return
182
183
IovVectorMap_t read(const Folder &theFolder, const SelectionCriterion &choice, const unsigned int limit=10)

◆ _root_compile()

python.RootUtils._root_compile ( src,
fname,
batch )
protected

Definition at line 66 of file RootUtils.py.

66def _root_compile (src, fname, batch):
67 import os
68 from .Helpers import ShutUp as root_shutup
69
70 ROOT = import_root(batch=batch)
71 compile_options = "f"
72 if 'dbg' in os.environ.get('CMTCONFIG', 'opt'):
73 compile_options += 'g'
74 else:
75 compile_options += 'O'
76
77 src_file = None
78 if src:
79 import textwrap
80 import tempfile
81 src_file = tempfile.NamedTemporaryFile(prefix='root_aclic_',
82 suffix='.cxx')
83 src_file.write(textwrap.dedent(src).encode())
84 src_file.flush()
85 src_file.seek(0)
86 fname = src_file.name
87
88 # Apparently, cling caches files by inode.
89 # If you ask it to read a file that has the same inode as one
90 # that it has already read, then it will just use the cached
91 # contents rather than rereading. This, however, doesn't play
92 # very well if we're reading temp files, where inodes may be reused,
93 # giving rise to hard-to-reproduce failures.
94 #
95 # Try to avoid this by keeping the temp files open until the
96 # the program exits.
97 _tempfiles.append (src_file)
98 pass
99
100 elif fname:
101 import os.path as osp
102 fname = osp.expanduser(osp.expandvars(fname))
103 pass
104
105 assert os.access(fname, os.R_OK), "could not read [%s]"%(fname,)
106 orig_root_lvl = ROOT.gErrorIgnoreLevel
107 ROOT.gErrorIgnoreLevel = ROOT.kWarning
108 try:
109 with root_shutup():
110 sc = ROOT.gSystem.CompileMacro(fname, compile_options)
111 if sc == ROOT.kFALSE:
112 raise RuntimeError(
113 'problem compiling ROOT macro (rc=%s)'%(sc,)
114 )
115 finally:
116 ROOT.gErrorIgnoreLevel = orig_root_lvl
117 return
118
119@cache

◆ _test_main()

python.RootUtils._test_main ( )
protected

Definition at line 506 of file RootUtils.py.

506def _test_main():
507 root = import_root() # noqa: F841
508 def no_raise(msg, fct, *args, **kwds):
509 caught = False
510 err = None
511 try:
512 fct(*args, **kwds)
513 except Exception as xerr:
514 err = xerr
515 caught = True
516 assert not caught, "%s:\n%s\nERROR" % (msg, err,)
517
518 no_raise("problem pythonizing TFile", fct=_pythonize_tfile)
519 no_raise("problem compiling dummy one-liner",
520 root_compile, "void foo1() { return ; }")
521 no_raise("problem compiling dummy one-liner w/ kwds",
522 fct=root_compile, src="void foo1a() { return ; }")
523 import tempfile
524 # PvG workaround for ROOT-7059
525 dummy = tempfile.NamedTemporaryFile(prefix="foo_",suffix=".cxx") # noqa: F841
526 with tempfile.NamedTemporaryFile(prefix="foo_",suffix=".cxx") as tmp:
527 tmp.write (b"void foo2() { return ; }\n")
528 tmp.flush()
529 no_raise("problem compiling a file",
530 fct=root_compile, fname=tmp.name)
531
532 print ("OK")
533 return True
534

◆ import_root()

python.RootUtils.import_root ( batch = True)

functions --------------------------------------------------------------—

a helper method to wrap the 'import ROOT' statement to prevent ROOT
from screwing up the display or loading graphics libraries when in batch
mode (which is the default.)

e.g.
>>> ROOT = import_root(batch=True)
>>> f = ROOT.TFile.Open(...)

Definition at line 22 of file RootUtils.py.

22def import_root(batch=True):
23 """a helper method to wrap the 'import ROOT' statement to prevent ROOT
24 from screwing up the display or loading graphics libraries when in batch
25 mode (which is the default.)
26
27 e.g.
28 >>> ROOT = import_root(batch=True)
29 >>> f = ROOT.TFile.Open(...)
30 """
31 import ROOT
32 ROOT.gROOT.SetBatch(batch)
33 if batch:
34 ROOT.PyConfig.IgnoreCommandLineOptions = True
35 import cppyy # noqa: F401
36 if os.environ.get('GLIBCXX_USE_CXX11_ABI') == '0':
37 cmd = ROOT.gSystem.GetMakeSharedLib()
38 if cmd.find('GLIBCXX_USE_CXX11_ABI') < 0:
39 cmd = cmd.replace ('$SourceFiles', '$SourceFiles -D_GLIBCXX_USE_CXX11_ABI=0 ')
40 ROOT.gSystem.SetMakeSharedLib(cmd)
41 return ROOT
42

◆ root_compile()

python.RootUtils.root_compile ( src = None,
fname = None,
batch = True )
a helper method to compile a set of C++ statements (via ``src``) or
a C++ file (via ``fname``) via ACLiC

Definition at line 45 of file RootUtils.py.

45def root_compile(src=None, fname=None, batch=True):
46 """a helper method to compile a set of C++ statements (via ``src``) or
47 a C++ file (via ``fname``) via ACLiC
48 """
49 if src is not None and fname is not None:
50 raise ValueError("'src' xor 'fname' should be not None, *not* both")
51
52 if src is None and fname is None:
53 raise ValueError("'src' xor 'fname' should be None, *not* both")
54
55 # Cling bug workaround: Cling will try to find a definition for the
56 # hidden __gmon_start__ by opening all libraries on LD_LIBRARY_PATH.
57 # But it will crash if it encounters a separate-debug library.
58 # Work around by adding a dummy definition of __gmon_start__.
59 # See !31633.
60 global _first_compile
61 if _first_compile:
62 _first_compile = False
63 root_compile ('extern "C" { void __gmon_start__(){}; }', None, True)
64 return _root_compile (src, fname, batch)
65

Variable Documentation

◆ __all__

list python.RootUtils.__all__
private
Initial value:
1= [
2 'import_root',
3 'root_compile',
4 ]

Definition at line 11 of file RootUtils.py.

◆ __author__

str python.RootUtils.__author__ = "Sebastien Binet"
private

Definition at line 9 of file RootUtils.py.

◆ __doc__

str python.RootUtils.__doc__ = "a few utils to ease the day-to-day work with ROOT"
private

Definition at line 8 of file RootUtils.py.

◆ _first_compile

bool python.RootUtils._first_compile = True
protected

Definition at line 44 of file RootUtils.py.

◆ _tempfiles

list python.RootUtils._tempfiles = []
protected

Definition at line 43 of file RootUtils.py.