Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-11-26 02:34:13

0001 #!/bin/env python3
0002 
0003 """
0004 Script converting DQM I/O format input file into folder structured ROOT file.
0005 Ouput files historgrams are easy browseable by ROOT. When there are more than 1 run
0006 in input file it creates a Run X named folder for each run.
0007 Thanks for Marco Rovere for giving example script/class needed to browse DQM I/O 
0008 formatted input.
0009 """
0010 
0011 from builtins import range
0012 import ROOT as R
0013 import sys
0014 import re
0015 import os
0016 import argparse
0017 
0018 class DQMIO:
0019     """
0020     Class responsible for browsing the content of a DQM file produced
0021     with the DQMIO I/O framework of CMSSW
0022     """
0023     types=["Ints","Floats","Strings",  ##defined DQMIO types
0024          "TH1Fs","TH1Ss","TH1Ds",
0025          "TH2Fs", "TH2Ss", "TH2Ds",
0026          "TH3Fs", "TProfiles","TProfile2Ds", "kNIndicies"]
0027 
0028     def __init__(self, input_filename, output_filename):
0029         self._filename = input_filename
0030         self._canvas = None
0031         self.f = R.TFile(output_filename, "RECREATE")
0032         self.already_defined = {"TProfiles" : False, "TProfile2Ds" : False,
0033                 "TH2Fs" : False, "TH2Ds" : False}
0034 
0035         if os.path.exists(self._filename): #we try to open input file if fail
0036             self._root_file = R.TFile.Open(self._filename) #-> close script
0037             if args.debug:
0038                 print("## DEBUG ##:")
0039                 print("    Input: %s\n    Output: %s" % (input_filename, 
0040                     output_filename))
0041 
0042         else:
0043             print("File %s does not exists" % self._filename)
0044             sys.exit(1)
0045     
0046     def print_index(self):
0047         """
0048         Loop over the complete index and dump it on the screen.
0049         """
0050         indices = self._root_file.Get("Indices")
0051         if args.debug:
0052             print("## DEBUG ##:")
0053             print("Run,\tLumi,\tType,\t\tFirstIndex,\tLastIndex")
0054             for i in range(indices.GetEntries()):
0055                 indices.GetEntry(i)
0056                 print('{0:4d}\t{1:4d}\t{2:4d}({3:s})\t\t{4:4d}\t{5:4d}'.format(
0057                     indices.Run, indices.Lumi, indices.Type, 
0058                     DQMIO.types[indices.Type], indices.FirstIndex, indices.LastIndex))
0059 
0060         for i in range(indices.GetEntries()):
0061             indices.GetEntry(i)
0062             if indices.Type < len(DQMIO.types):
0063                 self.write_to_file(self.types[indices.Type],
0064                     [indices.FirstIndex,indices.LastIndex], str(indices.Run))
0065 
0066             else:
0067                 print("Unknown histogram type. Type numer: %s" % (indices.Type))
0068         self.f.Close()
0069 
0070     def write_to_file(self, hist_type, index_range, run):
0071         """
0072         Method looping over entries for specified histogram type and 
0073         writing to FullName path to output ROOT File
0074         """
0075         print("Working on: %s indexes: %s..%s" % (hist_type ,index_range[0],
0076             index_range[1]))
0077         t_tree = self._root_file.Get(hist_type)
0078         __run_dir = "Run %s" % (run)
0079         ###we set Branch for the needed type
0080         if hist_type == "TProfiles":
0081             if not self.already_defined["TProfiles"]:
0082                 R.gROOT.ProcessLine("TProfile* _tprof;")
0083                 self.already_defined["TProfiles"] = True
0084             t_tree.SetBranchAddress("Value", R._tprof)
0085             t_tree.GetEntry(index_range[0])
0086         elif hist_type == "TProfile2Ds":
0087             if not self.already_defined["TProfile2Ds"]:
0088                 R.gROOT.ProcessLine("TProfile2D* _tprof2d;")
0089                 self.already_defined["TProfile2Ds"] = True
0090             t_tree.SetBranchAddress("Value", R._tprof2d)
0091             t_tree.GetEntry(index_range[0])
0092         elif hist_type == "TH2Fs":
0093             if not self.already_defined["TH2Fs"]:
0094                 R.gROOT.ProcessLine("TH2F* _th2f;")
0095                 self.already_defined["TH2Fs"] = True
0096             t_tree.SetBranchAddress("Value", R._th2f)
0097             t_tree.GetEntry(index_range[0])
0098         elif hist_type == "TH2Ds":
0099             if not self.already_defined["TH2Ds"]:
0100                 R.gROOT.ProcessLine("TH2D* _th2d;")
0101                 self.already_defined["TH2Ds"] = True
0102             t_tree.SetBranchAddress("Value", R._th2d)
0103             t_tree.GetEntry(index_range[0])
0104 
0105         for i in range(0,t_tree.GetEntries()+1): ##iterate on entries for specified type
0106             if i >= index_range[0] and i <= index_range[1]: ##if entries as in range:
0107                 t_tree.GetEntry(i)
0108                 name = str(t_tree.FullName)
0109                # print "  %s:  %s" % (i, name)
0110                 file_path = name.split("/")[:-1]            ##  same run/lumi histograms
0111                 __directory = "%s/%s" % (os.path.join("DQMData", __run_dir),
0112                     "/".join(file_path))
0113                 directory_ret = self.f.GetDirectory(__directory)
0114                 if not directory_ret:
0115                     self.f.mkdir(os.path.join(__directory))
0116                 self.f.cd(os.path.join(__directory))
0117                 if hist_type == "Strings":
0118                     construct_str = '<%s>s=%s</%s>' % (name.split("/")[-1:][0],
0119                         t_tree.Value, name.split("/")[-1:][0])
0120                     tmp_str = R.TObjString(construct_str)
0121                     tmp_str.Write()
0122                 elif hist_type == "Ints":
0123                     construct_str = '<%s>i=%s</%s>' % (name.split("/")[-1:][0],
0124                         t_tree.Value, name.split("/")[-1:][0])
0125                     tmp_str = R.TObjString(construct_str)
0126                     tmp_str.Write()
0127                 elif hist_type == "Floats":
0128                     construct_str = '<%s>f=%s</%s>' % (name.split("/")[-1:][0],
0129                         t_tree.Value, name.split("/")[-1:][0])
0130                     tmp_str = R.TObjString(construct_str)
0131                     tmp_str.Write()
0132                 else:
0133                     if hist_type in ["TProfiles", "TProfile2Ds", "TH2Fs", "TH2Ds"]: 
0134                         if hist_type == "TProfiles": #if type is specific we write it.
0135                             R._tprof.Write()
0136                         elif hist_type == "TProfile2Ds":
0137                             R._tprof2d.Write()
0138                         elif hist_type == "TH2Fs":
0139                             R._th2f.Write()
0140                         elif hist_type == "TH2Ds":
0141                             R._th2d.Write()
0142                     else: #else we wirte Leafs Value which is a histogram
0143                         t_tree.Value.Write()
0144 
0145 if __name__ == '__main__':
0146     parser = argparse.ArgumentParser()
0147     parser.add_argument("-in", "--input", help = "Input DQMIO ROOT file")
0148     parser.add_argument("-o", "--output", help = "Output filename",
0149         default = "DQMIO_converter_output.root")
0150     parser.add_argument("--debug", help = "Debug mode to spam you console",
0151         action = "store_true")
0152 
0153     args = parser.parse_args()
0154     __in_file = args.input
0155     __out_file = args.output
0156     dqmio = DQMIO(__in_file, __out_file)
0157     dqmio.print_index()