9"""Various functions to interact with ROOT objects and the runtime environment"""
13from functools
import singledispatch
16def root_walk(tdirectory):
17 """Walks the content of a TDirectory similar to os.walk.
19 Yields 3-tuples of current TDirectories, contained TObjects and contained TDirectories
20 for each of the directories nested inside the given TDirectory
in a depth first manner.
24 (TDirectory, list(TObject), list(TDirectory))
26 tkeys = tdirectory.GetListOfKeys()
31 tobject = tdirectory.Get(tkey.GetName())
32 if isinstance(tobject, ROOT.TDirectory):
33 tdirectories.append(tobject)
35 tobjects.append(tobject)
37 yield tdirectory, tobjects, tdirectories
40 for sub_tdirectory
in tdirectories:
41 for tdirectory, tobjects, tdirectories
in root_walk(sub_tdirectory):
42 yield tdirectory, tobjects, tdirectories
45@contextlib.contextmanager
46def root_open(tfile_or_file_path, tfile_options=None):
47 """Context manager to open a TFile.
49 If a file path is given open the TFile
and close it after the context
is left.
50 If an already opened TFile
is received simply
return it
and do
not close on exit.
54 tfile_or_file_path : str
or ROOT.TFile
55 Path to the file
or the TFile that should be activated.
57 Option string forwarded to the ROOT.TFile constructor
58 Typical options
as "RECREATE",
"READ" or "UPDATE".
60 if isinstance(tfile_or_file_path, ROOT.TFile):
61 tfile = tfile_or_file_path
62 with root_cd(tfile)
as tfile:
65 save_tdirectory = ROOT.gROOT.CurrentDirectory().load()
67 if tfile_options
is None:
68 tfile = ROOT.TFile(tfile_or_file_path)
70 tfile = ROOT.TFile(tfile_or_file_path, tfile_options)
79@contextlib.contextmanager
80def root_cd(tdirectory):
81 """Context manager that temporarily switches the current global ROOT directory while in the context.
83 If a string as the name of a directory
is given
as the argument
84 try to switch to the directory
with that name
in the current ROOT folder.
86 If it
is not present create it.
90 tdirectory : ROOT.TDirectory
or str
91 ROOT directory to switch to
or name of a folder to switch.
96 The new current ROOT directory.
102 save_tdirectory = ROOT.gROOT.CurrentDirectory().load()
104 if not tdirectory
or "." == tdirectory:
105 tdirectory = save_tdirectory
107 elif isinstance(tdirectory, str):
108 tdirectory_name = tdirectory
112 tdirectory = save_tdirectory.GetDirectory(tdirectory_name)
114 tdirectory = save_tdirectory.mkdir(tdirectory_name, tdirectory_name)
116 raise RuntimeError(f
"Could not create or find folder {tdirectory_name}")
120 tdirectory = save_tdirectory.GetDirectory(tdirectory_name)
123 if tdirectory
is not None:
131def root_save_name(name):
132 """Strips all meta characters that might be unsafe to use as a ROOT name.
137 A name that should be transformed
142 Name with potentially harmful characters deleted / replaced.
144 deletechars = str.maketrans("",
"",
r"/$\#{}()[]=")
145 name = name.replace(
' ',
'_').replace(
'-',
'_').replace(
',',
'_').translate(deletechars)
149def root_browse(tobject):
150 """Open a browser and show the given object.
154 tobject : ROOT.TObject
155 The object to be shown
160 The new TBrowser used to show the object.
166 tbrowser = ROOT.TBrowser()
167 if isinstance(tobject, ROOT.TObject):
168 if hasattr(tobject,
"Browse"):
169 tobject.Browse(tbrowser)
171 tbrowser.BrowseObject(tobject)
173 raise ValueError(
"Can only browse ROOT objects inheriting from TObject.")
179 """Returns a list of names that are contained in the given obj.
181 This is a convenience function to investigate the content of ROOT objects,
182 that dispatches on to object type
and retrieves different things depending on the type.
183 If the obj
is a string it
is interpreted
as a filename.
188@root_ls.register(str)
190 """Overloaded function for root_ls for filenames (e.g. opens the file and ls its content)."""
191 rootFile = ROOT.TFile(filename)
192 result = root_ls(rootFile)
199@root_ls.register(ROOT.TDirectory)
201 """Overloaded function for root_ls for ROOT directories (e.g. list the keys in the directory)."""
202 tKeys = list(tDirectory.GetListOfKeys())
203 result = sorted([tKey.GetName()
for tKey
in tKeys])
207@root_ls.register(ROOT.TTree)
208@root_ls.register(ROOT.TNtuple)
210 """Overloaded function for root_ls for trees and ntuples (e.g. list the keys in the tuple/tree)."""
211 tBranches = list(tTree.GetListOfBranches())
212 result = sorted([tBranch.GetName()
for tBranch
in tBranches])