Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2023-03-17 11:16:37

0001 """
0002 Print information about objects in a ROOT file.
0003 """
0004 from __future__ import absolute_import
0005 from __future__ import print_function
0006 
0007 from builtins import range
0008 from .version import __version__
0009 
0010 from ROOT import Double
0011 import copy
0012 from . import argparse
0013 import sys
0014 import os
0015 
0016 #### Load classes from ROOT, ensuring it doesn't intercept -h or --help
0017 saved_argv = sys.argv[:]
0018 sys.argv = [sys.argv[0], '-b']
0019 from ROOT import TFile, TH1, TDirectory, gDirectory
0020 sys.argv = saved_argv
0021 
0022 def recurse_thru_file(in_tfile, options, full_path='/'):
0023     '''Recursive function to find all contents in a given ROOT file'''
0024     keys = in_tfile.GetDirectory(full_path).GetListOfKeys()
0025     for key in keys:
0026         name = key.GetName()
0027         classname = key.GetClassName()
0028         if 'TDirectory' in classname:
0029             gDirectory.cd(name)
0030             recurse_thru_file(in_tfile, options, '/'.join([full_path,name]))
0031             gDirectory.cd("..")
0032         else:
0033             if options.name and name != options.name: continue
0034             full_name = '/'.join([full_path,name])
0035             obj = in_tfile.Get(full_name)
0036             if not obj:
0037                 continue
0038             simple_name = full_name[2:]
0039             print("%s" % simple_name, end=' ')
0040             for arg in [x[2:] for x in sys.argv if x.startswith("--")]:
0041                 if "classname" == arg:
0042                     print("%s" % classname, end=' ')
0043                 if obj.InheritsFrom('TH1'):
0044                     if "entries" == arg:
0045                         print(" %i" % obj.GetEntries(), end=' ')
0046                     if "contents" == arg:
0047                         if obj.InheritsFrom('TH2'):
0048                             # Print contents as they would look on the 2D graph
0049                             # Left to right, top to bottom.  Start in upper left corner.
0050                             for j in reversed(list(range(obj.GetNbinsY()))):
0051                                 print()
0052                                 print(" %s" % ' '.join(
0053                                     [str(obj.GetBinContent(i+1, j+1)) for i in range(obj.GetNbinsX())]), end=' ')
0054                         else:
0055                             print(" %s" % ' '.join(
0056                                 [str(obj.GetBinContent(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
0057                     if "errors" == arg:
0058                         if obj.InheritsFrom('TH2'):
0059                             for j in reversed(list(range(obj.GetNbinsY()))):
0060                                 print()
0061                                 print(" %s" % ' '.join(
0062                                     [str(obj.GetBinError(i+1, j+1)) for i in range(obj.GetNbinsX())]), end=' ')
0063                         else:
0064                             print(" %s" % ' '.join(
0065                                 [str(obj.GetBinError(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
0066                     if "bincenter" == arg:
0067                         print(" %s" % ' '.join(
0068                             [str(obj.GetBinCenter(i+1)) for i in range(obj.GetNbinsX())]), end=' ')
0069                     if "max" == arg:
0070                         print(" %i" % obj.GetMaximum(), end=' ')
0071                     if "min" == arg:
0072                         print(" %i" % obj.GetMinimum(), end=' ')
0073                     if "overflow" == arg:
0074                         print(" %i" % obj.GetBinContent(obj.GetNbinsX()), end=' ')
0075                     if "underflow" == arg:
0076                         print(" %i" % obj.GetBinContent(0), end=' ')
0077                 if obj.InheritsFrom('TGraph'):
0078                     if "contents" == arg:
0079                         x, y = Double(0), Double(0)
0080                         xvals = []
0081                         yvals = []
0082                         for i in range(obj.GetN()):
0083                             obj.GetPoint(i, x, y)
0084                             xvals.append(copy.copy(x))
0085                             yvals.append(copy.copy(y))
0086                         for point in zip(xvals,yvals):
0087                             print(" (%d, %d)" % point, end=' ')
0088             print("")
0089 
0090 def main():
0091     parser = argparse.ArgumentParser(description='Print information from an SC2 replay file.')
0092     parser.add_argument('filenames', metavar='filename', type=str, nargs='+',
0093                         help="Names of one or more root files")
0094     parser.add_argument('--bincenter', action="store_true", default=False,
0095                       help="Get Bin Centers from each bin in each histogram")
0096     parser.add_argument('--classname', action="store_true", default=False,
0097                       help="Get type from each object in root file")
0098     parser.add_argument('--contents', action="store_true", default=False,
0099                       help="Get Bin Contents from each bin in each histogram")
0100     parser.add_argument('--errors', action="store_true", default=False,
0101                       help="Get Bin Errors from each bin in each histogram")
0102     parser.add_argument('--entries', action="store_true", default=False,
0103                       help="Get Entries from each histogram")
0104     parser.add_argument('--max', action="store_true", default=False,
0105                       help="Get Maximum value from each histogram")
0106     parser.add_argument('--min', action="store_true", default=False,
0107                       help="Get Minimum value from each histogram")
0108     parser.add_argument('--name', default=None,
0109                       help="Get information only from object with matching name")
0110     parser.add_argument('--overflow', action="store_true", default=False,
0111                       help="Get value of overflow bin from each histogram")
0112     parser.add_argument('--underflow', action="store_true", default=False,
0113                       help="Get value of underflow bin from each histogram")
0114     arguments = parser.parse_args()
0115     for arg in arguments.filenames:
0116         if arg[-5:] != ".root":
0117             raise TypeError("Arguments must include root file names")
0118     filenames_from_interface = [x for x in arguments.filenames if x[-5:] == ".root"]
0119     if len(filenames_from_interface) == 0:
0120         parser.print_help()
0121         sys.exit(0)
0122     for filename in filenames_from_interface:
0123         if not os.path.exists(filename):
0124             print("%s does not exist." % filename)
0125             sys.exit(0)
0126         tfile = TFile(filename, "read")
0127         try:
0128             recurse_thru_file(tfile, arguments)
0129         except IOError as e:
0130             if e.errno != 32:
0131                 raise
0132 
0133 if __name__ == '__main__':
0134     main()