Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-11-25 02:29:52

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