CMS 3D CMS Logo

rootinfo.py
Go to the documentation of this file.
1 """
2 Print information about objects in a ROOT file.
3 """
4 from __future__ import absolute_import
5 from __future__ import print_function
6 
7 from .version import __version__
8 
9 from ROOT import Double
10 import copy
11 from . import argparse
12 import sys
13 import os
14 
15 #### Load classes from ROOT, ensuring it doesn't intercept -h or --help
16 saved_argv = sys.argv[:]
17 sys.argv = [sys.argv[0], '-b']
18 from ROOT import TFile, TH1, TDirectory, gDirectory
19 sys.argv = saved_argv
20 
21 def recurse_thru_file(in_tfile, options, full_path='/'):
22  '''Recursive function to find all contents in a given ROOT file'''
23  keys = in_tfile.GetDirectory(full_path).GetListOfKeys()
24  for key in keys:
25  name = key.GetName()
26  classname = key.GetClassName()
27  if 'TDirectory' in classname:
28  gDirectory.cd(name)
29  recurse_thru_file(in_tfile, options, '/'.join([full_path,name]))
30  gDirectory.cd("..")
31  else:
32  if options.name and name != options.name: continue
33  full_name = '/'.join([full_path,name])
34  obj = in_tfile.Get(full_name)
35  if not obj:
36  continue
37  simple_name = full_name[2:]
38  print("%s" % simple_name, end=' ')
39  for arg in [x[2:] for x in sys.argv if x.startswith("--")]:
40  if "classname" == arg:
41  print("%s" % classname, end=' ')
42  if obj.InheritsFrom('TH1'):
43  if "entries" == arg:
44  print(" %i" % obj.GetEntries(), end=' ')
45  if "contents" == arg:
46  if obj.InheritsFrom('TH2'):
47  # Print contents as they would look on the 2D graph
48  # Left to right, top to bottom. Start in upper left corner.
49  for j in reversed(range(obj.GetNbinsY())):
50  print()
51  print(" %s" % ' '.join(
52  [str(obj.GetBinContent(i+1, j+1)) for i in range(obj.GetNbinsX())]), end=' ')
53  else:
54  print(" %s" % ' '.join(
55  [str(obj.GetBinContent(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
56  if "errors" == arg:
57  if obj.InheritsFrom('TH2'):
58  for j in reversed(range(obj.GetNbinsY())):
59  print()
60  print(" %s" % ' '.join(
61  [str(obj.GetBinError(i+1, j+1)) for i in range(obj.GetNbinsX())]), end=' ')
62  else:
63  print(" %s" % ' '.join(
64  [str(obj.GetBinError(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
65  if "bincenter" == arg:
66  print(" %s" % ' '.join(
67  [str(obj.GetBinCenter(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
68  if "max" == arg:
69  print(" %i" % obj.GetMaximum(), end=' ')
70  if "min" == arg:
71  print(" %i" % obj.GetMinimum(), end=' ')
72  if "overflow" == arg:
73  print(" %i" % obj.GetBinContent(obj.GetNbinsX()), end=' ')
74  if "underflow" == arg:
75  print(" %i" % obj.GetBinContent(0), end=' ')
76  if obj.InheritsFrom('TGraph'):
77  if "contents" == arg:
78  x, y = Double(0), Double(0)
79  xvals = []
80  yvals = []
81  for i in range(obj.GetN()):
82  obj.GetPoint(i, x, y)
83  xvals.append(copy.copy(x))
84  yvals.append(copy.copy(y))
85  for point in zip(xvals,yvals):
86  print(" (%d, %d)" % point, end=' ')
87  print("")
88 
89 def main():
90  parser = argparse.ArgumentParser(description='Print information from an SC2 replay file.')
91  parser.add_argument('filenames', metavar='filename', type=str, nargs='+',
92  help="Names of one or more root files")
93  parser.add_argument('--bincenter', action="store_true", default=False,
94  help="Get Bin Centers from each bin in each histogram")
95  parser.add_argument('--classname', action="store_true", default=False,
96  help="Get type from each object in root file")
97  parser.add_argument('--contents', action="store_true", default=False,
98  help="Get Bin Contents from each bin in each histogram")
99  parser.add_argument('--errors', action="store_true", default=False,
100  help="Get Bin Errors from each bin in each histogram")
101  parser.add_argument('--entries', action="store_true", default=False,
102  help="Get Entries from each histogram")
103  parser.add_argument('--max', action="store_true", default=False,
104  help="Get Maximum value from each histogram")
105  parser.add_argument('--min', action="store_true", default=False,
106  help="Get Minimum value from each histogram")
107  parser.add_argument('--name', default=None,
108  help="Get information only from object with matching name")
109  parser.add_argument('--overflow', action="store_true", default=False,
110  help="Get value of overflow bin from each histogram")
111  parser.add_argument('--underflow', action="store_true", default=False,
112  help="Get value of underflow bin from each histogram")
113  arguments = parser.parse_args()
114  for arg in arguments.filenames:
115  if arg[-5:] != ".root":
116  raise TypeError("Arguments must include root file names")
117  filenames_from_interface = [x for x in arguments.filenames if x[-5:] == ".root"]
118  if len(filenames_from_interface) == 0:
119  parser.print_help()
120  sys.exit(0)
121  for filename in filenames_from_interface:
122  if not os.path.exists(filename):
123  print("%s does not exist." % filename)
124  sys.exit(0)
125  tfile = TFile(filename, "read")
126  try:
127  recurse_thru_file(tfile, arguments)
128  except IOError as e:
129  if e.errno != 32:
130  raise
131 
132 if __name__ == '__main__':
133  main()
def recurse_thru_file(in_tfile, options, full_path='/')
Definition: rootinfo.py:21
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:65
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
Definition: main.py:1
#define str(s)