GSI Object Oriented Online Offline (Go4)  GO4-6.1.4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
expmem.py
Go to the documentation of this file.
1 
2 import ROOT
3 from fnmatch import fnmatchcase
4 from six import string_types
5 
6 class ExpMem(object):
7  """
8  Wraps exported Go4 memory .root-files
9  """
10 
11  def __init__(self, filename, rootfolder="Analysis"):
12  """
13  Open the TFile filename as file and
14  get the TDirectory rootfolder as root
15  For rootfolder, "Workspace" might be desired besides the default
16  An unset rootfolder, "*", and "/" all mean the actual root of the file
17  """
18  if not rootfolder or rootfolder in ["*", "/"]:
19  rootfolder = ""
20 
21  self.file = f = ROOT.TFile(filename)
22  self.root = f.GetDirectory(rootfolder)
23 
24  if not self.root:
25  self.root = self.file
26 
27 
28  def Objects(self, folder=None):
29  """
30  Iterate over all objects in the opened .root-file
31  folder can be a string (relative to rootfolder) or a TDirectory
32  """
33  if folder is None:
34  folder = self.root
35  elif isinstance(folder, string_types):
36  folder = self.root.GetDirectory(folder)
37 
38  if not folder:
39  return
40 
41  diriter = folder.GetListOfKeys().MakeIterator()
42  while True:
43  key = diriter.Next()
44  if not key:
45  break
46  if key.GetClassName().startswith("TDirectory"):
47  subfolder = key.ReadObj()
48  for obj in self.Objects(subfolder):
49  yield obj
50  else:
51  yield key.ReadObj()
52 
53 
54  def MatchingObjects(self, expr="*", folder=None):
55  """
56  Iterate over Objects() that match expr
57  """
58  for obj in self.Objects(folder):
59  name = obj.GetName()
60  if fnmatchcase(name, expr):
61  yield obj
62 
63 
64  def tree(self, folder=None, indent=1):
65  """
66  Recursively print the object/folder tree of the opened .root-file
67  """
68  if folder is None:
69  folder = self.root
70  print(folder.GetName())
71 
72  diriter = folder.GetListOfKeys().MakeIterator()
73  while True:
74  key = diriter.Next()
75  if not key:
76  break
77  if key.GetClassName().startswith("TDirectory"):
78  subfolder = key.ReadObj()
79  sfname = subfolder.GetName()
80  print("-"*indent, sfname)
81  self.tree(subfolder, indent+1)
82  else:
83  print("="*indent, key.ReadObj().GetName())
84 
85 
86