All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Classes | Functions | Variables
ROOTutils Namespace Reference

Classes

class  DirectoryChanger
 

Functions

def ROOTloader
 Try to save the command line arguments from unconsiderate ROOT behaviour. More...
 
def TVector2ToString
 Print vectors easily. More...
 
def TVector3ToString
 
def TLorentzVectorToString
 
def splitROOTpath
 File management. More...
 
def createROOTpath
 
def activateDirectory
 
def getROOTclass
 
def expandFileList
 this is not really specific to ROOT, but we often have ROOT file lists More...
 

Variables

string __doc__
 
list __all__
 
tuple ROOT = ROOTloader()
 
 args
 

Function Documentation

def ROOTutils.activateDirectory (   ROOTdir)
Sets a directory with `DirectoryChanger`.

Example:
      
      dir = outputFile.GetDirectory("plots")
      with activateDirectory(dir):
        for plot in plots: item.Write()
      # with

Definition at line 227 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

228 def activateDirectory(ROOTdir):
229  """
230  Sets a directory with `DirectoryChanger`.
231 
232  Example:
233 
234  dir = outputFile.GetDirectory("plots")
235  with activateDirectory(dir):
236  for plot in plots: item.Write()
237  # with
238 
239  """
240  return DirectoryChanger(ROOTdir)
241 
def ROOTutils.createROOTpath (   path,
  fileMode = "UPDATE" 
)
Creates a complete ROOT directory path.

The `path` is in the form:
"/UNIX/path/to/file.root:internal/ROOT/directory/structure".
The ROOT file `/UNIX/path/to/file.root` will be created with the specified
`fileMode` (path may be relative), then the `TDirectoryFile` hierarchy
`internal/ROOT/directory/structure` will be created under it.
The return value is a pair `(file, dir)`, where `file` is a open `TFile`
for `/UNIX/path/to/file.root` and `dir` is the `TDirectory` object of
`structure`.

Remember to keep track of `file`, or else python may close it compromising
`dir` as well.

Definition at line 129 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

130 def createROOTpath(path, fileMode = "UPDATE"):
131  """
132  Creates a complete ROOT directory path.
133 
134  The `path` is in the form:
135  "/UNIX/path/to/file.root:internal/ROOT/directory/structure".
136  The ROOT file `/UNIX/path/to/file.root` will be created with the specified
137  `fileMode` (path may be relative), then the `TDirectoryFile` hierarchy
138  `internal/ROOT/directory/structure` will be created under it.
139  The return value is a pair `(file, dir)`, where `file` is a open `TFile`
140  for `/UNIX/path/to/file.root` and `dir` is the `TDirectory` object of
141  `structure`.
142 
143  Remember to keep track of `file`, or else python may close it compromising
144  `dir` as well.
145  """
146 
147  filePath, ROOTpath = splitROOTpath(path)
148 
149  ROOTfile = ROOT.TFile(filePath, fileMode)
150  if not ROOTfile.IsOpen():
151  raise RuntimeError \
152  ("Can't open ROOT file '{}' in '{}' mode".format(filePath, fileMode))
153 
154  # instead of using `TDirectory.mkdir()`, we do that manually
155  ROOTpathElements = ROOTpath.split('/')
156  ROOTdir = ROOTfile
157  for ROOTdirName in ROOTpathElements:
158  if not ROOTdirName: continue # empty name does nothing
159  daughterDir = ROOTdir.GetDirectory(ROOTdirName)
160  if not daughterDir:
161  daughterDir = ROOTdir.CreateDirectory(ROOTdirName)
162  if not daughterDir:
163  raise RuntimeError("Can't access directory '{}' under '{}'".format
164  (ROOTdirName, ROOTdir.GetPath()))
165  ROOTdir = daughterDir
166  # for
167 
168  return ROOTfile, ROOTdir
169 
170 # createROOTpath()
171 
static std::string format(PyObject *obj, unsigned int pos, unsigned int indent, unsigned int maxlen, unsigned int depth)
Definition: fclmodule.cxx:374
def ROOTutils.expandFileList (   fileListPath)

this is not really specific to ROOT, but we often have ROOT file lists

Definition at line 261 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

262  fileListPath: "path of the file list",
263  comment: "(default: '#') character used to introduce a comment" = '#',
264  fileListSuffixes: "suffix of entries to recursively add file lists" = [],
265  ) -> "a list of file names":
266  """Returns a list of file names as found in the specified file list.
267 
268  The `fileListPath` path is read as a text file; each line represents a full
269  file path.
270  Empty lines and lines starting with a comment character are ignored.
271  Also if blanks and a comment character are found, the content of the line
272  from the first of those blank characters on is ignored as part of a comment.
273  If `comment` is `None`, this feature is disabled.
274 
275  If file list suffixes are specified, a line ending with any of those suffixes
276  will be considered a file list itself, and recursively expanded.
277 
278  If `fileListPath` can't be read, an exception is raised.
279  """
280 
281  import logging
282 
283  l = []
284  with open(fileListPath, 'r') as fileList:
285 
286  for iLine, line in enumerate(fileList):
287  line = line.strip()
288  if not line: continue
289  if comment:
290  if line.startswith(comment): continue
291 
292  words = line.split(comment)
293  line = words[0]
294  for left, right in zip(words[:-1], words[1:]):
295  if left and left[-1].isspace():
296  logging.debug("Comment starting at line %d between '%s' and '%s'", iLine, left, right)
297  break
298  line += comment + right
299  # for
300  line = line.rstrip()
301  # if comment
302 
303  for suffix in fileListSuffixes:
304  if not line.endswith(suffix): continue
305  logging.debug("Adding content of file list from line %d ('%s')", iLine, line)
306  extra = expandFileList(line, comment=comment, fileListSuffixes=fileListSuffixes)
307  logging.debug("%d entries collected under file list '%s'", len(extra), line)
308  l.extend(extra)
309  break
310  else:
311  logging.debug("Line %d added to the list", iLine)
312  l.append(line)
313  # for suffix... else
314  # for line in list
315 
316  # with
317  return l
318 # expandFileList()
319 
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
def expandFileList
this is not really specific to ROOT, but we often have ROOT file lists
auto zip(Iterables &&...iterables)
Range-for loop helper iterating across many collections at the same time.
Definition: zip.h:295
open(RACETRACK) or die("Could not open file $RACETRACK for writing")
def ROOTutils.getROOTclass (   classPath)
Returns the object specified by `classPath` within ROOT module.

Throws `AttributeError` if any object in the path is not available.

Example: `getROOTclass('geo::GeometryCore')` returns `ROOT.geo.GeometryCore`.

Definition at line 243 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

244 def getROOTclass(classPath):
245  """Returns the object specified by `classPath` within ROOT module.
246 
247  Throws `AttributeError` if any object in the path is not available.
248 
249  Example: `getROOTclass('geo::GeometryCore')` returns `ROOT.geo.GeometryCore`.
250  """
251  classPath = classPath.replace('::', '.').lstrip('.')
252  base = ROOT
253  for objName in classPath.split('.'):
254  base = getattr(base, objName)
255  return base
256 # getROOTclass()
257 
def ROOTutils.ROOTloader ( )

Try to save the command line arguments from unconsiderate ROOT behaviour.

The ROOT interpreter likes to peek at the command line arguments and interpret
them its own way.
For example, an option `-b` will be interpreted to set ROOT in batch mode.
Likewise, if a `--help` argument is present on the command line, the
interpreter will print the ROOT help message and, even worse, halt the script.
This is clearly not very friendly to the script.

The initialization of the interpreter happens lazily the first time anything
is read out of `ROOT` module: `import ROOT` is not enough, but pretty much
everything after that involving ROOT is (exception: `ROOT.gROOT` will not
trigger the interpreter, but trying to get anything out of `ROOT.gROOT` will).
That makes it complicate to control when that happens.

This function triggers the interpreter initialization after having removed all
command line options, and finally restores them (we use a context manager to
show that we know Python). The loaded module is returned.

This function is called as soon as this module is imported. It is important
that this happens as early as possible, possibly as a replacement of ROOT
import, as:
    
    from ROOTutils import ROOT
    
    from ROOTutils import *
    
    import ROOTutils
    import ROOT
    
or equivalent.

Definition at line 20 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

20 
21 def ROOTloader():
22  """
23  The ROOT interpreter likes to peek at the command line arguments and interpret
24  them its own way.
25  For example, an option `-b` will be interpreted to set ROOT in batch mode.
26  Likewise, if a `--help` argument is present on the command line, the
27  interpreter will print the ROOT help message and, even worse, halt the script.
28  This is clearly not very friendly to the script.
29 
30  The initialization of the interpreter happens lazily the first time anything
31  is read out of `ROOT` module: `import ROOT` is not enough, but pretty much
32  everything after that involving ROOT is (exception: `ROOT.gROOT` will not
33  trigger the interpreter, but trying to get anything out of `ROOT.gROOT` will).
34  That makes it complicate to control when that happens.
35 
36  This function triggers the interpreter initialization after having removed all
37  command line options, and finally restores them (we use a context manager to
38  show that we know Python). The loaded module is returned.
39 
40  This function is called as soon as this module is imported. It is important
41  that this happens as early as possible, possibly as a replacement of ROOT
42  import, as:
43 
44  from ROOTutils import ROOT
45 
46  from ROOTutils import *
47 
48  import ROOTutils
49  import ROOT
50 
51  or equivalent.
52  """
53  import sys, logging
54  try: alreadyLoaded = 'gInterpreter' in dir(ROOT)
55  except NameError: alreadyLoaded = False
56  if alreadyLoaded:
57  logging.warning(
58  "ROOT module was loaded before ROOTutils.py: command line arguments may be garbled"
59  )
60  return sys.modules['ROOT']
61  # if already loaded
62 
63  class EmptyArgs:
64  def __enter__(self):
65  self.args = sys.argv
66  logging.debug("Saving command line: %s", self.args)
67  sys.argv = sys.argv[0:1]
68  logging.debug(
69  "Replaced command line %s with %s before loading ROOT module",
70  self.args, sys.argv)
71  def __exit__(self, exc_type, exc_value, traceback):
72  sys.argv = self.args
73  logging.debug("Restored command line %s", sys.argv)
74  # class EmptyArgs
75 
76  with EmptyArgs():
77  import ROOT
78  ROOT.gInterpreter # make sure that an interpreter is initialized
79  return ROOT
80  # with
81 
82 # ROOTloader()
def ROOTloader
Try to save the command line arguments from unconsiderate ROOT behaviour.
tuple dir
Definition: dropbox.py:28
def ROOTutils.splitROOTpath (   path)

File management.

Returns the specified path split into file path and ROOT directory path.

The `path` is in the form:
"/UNIX/path/to/file.root:internal/ROOT/directory/and/object".
The returned value is a pair `(filePath, dirPath)`: in the example, that
would be `("/UNIX/path/to/file.root", "internal/ROOT/directory/and/object")`.

Note: for compatibility with some ROOT tradition, the separator ':' can be
replaced by '/'

Definition at line 103 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

104 def splitROOTpath(path):
105  """
106  Returns the specified path split into file path and ROOT directory path.
107 
108  The `path` is in the form:
109  "/UNIX/path/to/file.root:internal/ROOT/directory/and/object".
110  The returned value is a pair `(filePath, dirPath)`: in the example, that
111  would be `("/UNIX/path/to/file.root", "internal/ROOT/directory/and/object")`.
112 
113  Note: for compatibility with some ROOT tradition, the separator ':' can be
114  replaced by '/'
115  """
116 
117  # this implementation is not robust, but I am in a hurry :-P
118  try:
119  filePath, ROOTpath = path.rsplit('.root')
120  except ValueError:
121  raise RuntimeError("Path '{}' does not include a ROOT file.".format(path))
122  filePath += '.root'
123  ROOTpath.lstrip(':')
124  ROOTpath.lstrip('/')
125  return filePath, ROOTpath
126 
127 # splitROOTpath()
128 
static std::string format(PyObject *obj, unsigned int pos, unsigned int indent, unsigned int maxlen, unsigned int depth)
Definition: fclmodule.cxx:374
def ROOTutils.TLorentzVectorToString (   v)

Definition at line 92 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

92 
94  return "( %g, %g, %g; %g )" % (v.X(), v.Y(), v.Z(), v.T())
95 
96 ROOT.TVector2.__str__ = TVector2ToString
97 ROOT.TVector3.__str__ = TVector3ToString
98 ROOT.TLorentzVector.__str__ = TLorentzVectorToString
99 
def ROOTutils.TVector2ToString (   v)

Print vectors easily.

Definition at line 88 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

88 
89 def TVector2ToString(v):
return "( %g, %g )" % (v.X(), v.Y())
def ROOTutils.TVector3ToString (   v)

Definition at line 90 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

90 
91 def TVector3ToString(v):
return "( %g, %g, %g )" % (v.X(), v.Y(), v.Z())

Variable Documentation

list ROOTutils.__all__
Initial value:
1 = [
2  "splitROOTpath", "createROOTpath", "getROOTclass",
3  "activateDirectory",
4  "ROOT",
5  ]

Definition at line 10 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

string ROOTutils.__doc__
Initial value:
1 = """
2 Collection of utilities to ease interaction with ROOT.
3 
4 Unsurprisingly, this module requires ROOT.
5 """

Definition at line 4 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

ROOTutils.args

Definition at line 64 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.

tuple ROOTutils.ROOT = ROOTloader()

Definition at line 83 of file icarusalg/icarusalg/gallery/helpers/python/ROOTutils.py.