CMS 3D CMS Logo

Classes | Functions | Variables

python::rootplot::tree2hists Namespace Reference

Classes

class  Plot
class  RootTree
 Define classes and generators #######################################. More...

Functions

def duration_to_string
def join_cuts
def main
def make_all_hists_all_files
def tree2hists_main
 Define the main program #############################################.
def write_default_T2H_config

Variables

string __license__

Function Documentation

def python::rootplot::tree2hists::duration_to_string (   start,
  end 
)

Definition at line 91 of file tree2hists.py.

00092                                   :
00093     timeTaken = end - start
00094     hours, remainder = divmod(timeTaken.seconds, 3600)
00095     minutes, seconds = divmod(remainder, 60)
00096     if hours>0:
00097         return "%i hours, %i minutes" % (hours, minutes)
00098     elif minutes>0:
00099         return "%i minutes" % minutes
00100     return "%i seconds" % seconds                            

def python::rootplot::tree2hists::join_cuts (   list_of_cuts)
Joins list of cuts (strings) into something ROOT can handle.
Example:  given ('1<2','','5>4') returns '1<2&&5>4'

Definition at line 82 of file tree2hists.py.

00083                             :
00084     """Joins list of cuts (strings) into something ROOT can handle.
00085     Example:  given ('1<2','','5>4') returns '1<2&&5>4'"""
00086     list_of_nonempty_cuts = []
00087     for cut in list_of_cuts:
00088         if cut:
00089             list_of_nonempty_cuts.append(cut)
00090     return '&&'.join(list_of_nonempty_cuts)

def python::rootplot::tree2hists::main ( )

Definition at line 286 of file tree2hists.py.

00287           :
00288     if len(sys.argv) > 1:
00289         if path.isfile(sys.argv[1]):
00290             config_file = sys.argv[1].split('.')[0]
00291             tree2hists_main(config_file)
00292         else:
00293             print "%s not found." % sys.argv[1]
00294             print("Create default config file by running tree2hists "
00295                   "with no argument.")
00296             sys.exit(1)
00297     else:
00298         if path.exists('t2h_config.py'):
00299             print "Run with specific config file, like:"
00300             print "  tree2hists t2h_config.py"
00301             sys.exit(1)
00302         write_default_T2H_config()
00303         sys.exit(0)    

def python::rootplot::tree2hists::make_all_hists_all_files (   list_of_RootTrees,
  list_of_Plots,
  cut_for_all_files,
  list_of_cutSets 
)
Open root files one at a time, make plots, then close them.

Definition at line 151 of file tree2hists.py.

00152                                                                                                   :
00153     '''Open root files one at a time, make plots, then close them.'''
00154     list_of_plots_to_write = []
00155 
00156     # Create plots for each set of cuts
00157     for set_of_cuts in list_of_cutSets:
00158         histname_fix, title_fix, current_cut_set = set_of_cuts
00159         for plot in list_of_Plots:
00160             new_plot  = deepcopy(plot)
00161             new_title = ' '.join((plot.histogram.GetTitle(), title_fix))
00162             new_plot.histogram.SetTitle(new_title)
00163             list_of_plots_to_write.append((new_plot, set_of_cuts))
00164     
00165     for j, rootTree in enumerate(list_of_RootTrees):
00166         rootTree.tfile = TFile(rootTree.fileName, "read")           # Open TFile
00167         if rootTree.tfile.IsZombie():
00168             print "Error opening %s, exiting..." % rootTree.fileName
00169             sys.exit(0)
00170         try:                                      # Try to get TTree from file.
00171             rootTree.tfile.GetObject(rootTree.treeName, rootTree.ttree)
00172         except:
00173             print "Error: %s not found in %s, exiting..." % (rootTree.treeName,
00174                                                              rootTree.fileName)
00175             sys.exit(1)
00176 
00177         print "\n%s: Opened %s  %i MB" % (datetime.now().strftime("%I:%M%p"),
00178                                           rootTree.fileName,
00179                                           path.getsize(rootTree.fileName)/1048576)
00180         print " %s has %i entries, will plot with scale=%.2e, cuts='%s'" % (rootTree.treeName,
00181                                                                             rootTree.ttree.GetEntries(),
00182                                                                             rootTree.scale,
00183                                                                             rootTree.cuts)
00184         
00185         # Loop over plots
00186         print "   # entries                  var >> histogram"
00187         for i, (plot, set_of_cuts) in enumerate(list_of_plots_to_write):
00188             histname_fix, title_fix, current_cut_set = set_of_cuts
00189             tmp_hist = plot.histogram.Clone("temp")    # Create temp hist
00190             all_cuts = join_cuts(cut_for_all_files, rootTree.cuts,
00191                                  current_cut_set, plot.cuts) # Set cuts
00192             rootTree.ttree.Draw( "%s >> temp" % plot.treeVariable, all_cuts,
00193                                  "goff")               # Draw with graphics off
00194             tmp_hist.Scale(rootTree.scale)             # Scale temp
00195             entries_before = plot.histogram.GetEntries()
00196             plot.histogram.Add(tmp_hist)               # Add temp hist to total
00197             entries_after = plot.histogram.GetEntries()
00198             print " %3i %7i %20s >> %s/%s" % (i, entries_after-entries_before,
00199                                               plot.treeVariable, histname_fix,
00200                                               plot.histogram.GetName()),
00201             if plot.cuts:
00202                 print "\textra cuts: %s" % plot.cuts, # plot-specific cuts
00203             print
00204             
00205         rootTree.tfile.Close()                                    # Close TFile
00206         print "%s: Closed %s" % (datetime.now().strftime("%I:%M%p"),
00207                                  rootTree.fileName)
00208     return list_of_plots_to_write
00209 

def python::rootplot::tree2hists::tree2hists_main (   config_file)

Define the main program #############################################.

Definition at line 211 of file tree2hists.py.

00212                                 :
00213     try:
00214         # Import only certain variables
00215         sys.path.insert(0, '')
00216         _temp = __import__(config_file, globals(), locals(),
00217                            ['list_of_files','output_filename',
00218                             'cut_for_all_files','cut_sets','list_of_plots'], -1)
00219         list_of_files     = _temp.list_of_files
00220         output_filename   = _temp.output_filename
00221         cut_for_all_files = _temp.cut_for_all_files
00222         cut_sets          = _temp.cut_sets
00223         list_of_plots     = _temp.list_of_plots
00224         for rootTree in list_of_files:
00225             if not path.isfile(rootTree.fileName):
00226                 print "Error:\n  %s\nnot found for input." % rootTree.fileName
00227                 sys.exit(1)
00228         hist_names = [plot.name for plot in list_of_plots]
00229         if len(hist_names)>len(set(hist_names)):
00230             print hist_names
00231             print "Error: Each plot needs a unique name, exiting..."
00232             sys.exit(1)
00233         if path.isfile(output_filename):
00234             print "Warning: %s exists" % output_filename
00235     except Exception, e:
00236         print e
00237         print "Error with %s" % config_file
00238         sys.exit(1)
00239 
00240     if path.isfile('rootlogon.C'):
00241         print "Loading rootlogon.C"
00242         gROOT.Macro('rootlogon.C')    # Load functions from rootlogon script
00243 
00244     if cut_sets:
00245         print "\n%i defined cut sets:" % len(cut_sets)
00246         for cut in cut_sets:
00247             name, title_fix, current_cut_set = cut
00248             print "  %s\t: '%s'" % (name, current_cut_set)
00249         cut_names = [name for name,num,cut in cut_sets]
00250         if len(cut_names)>len(set(cut_names)):
00251             print "Error: Each cut set needs a unique name, exiting..."
00252             sys.exit(1)
00253     else:
00254         cut_sets = [("","","")] # Make all plots, no extra cuts
00255 
00256     print "\nCuts to apply to all files:\n\t'%s'" % cut_for_all_files
00257 
00258     start_time = datetime.now()
00259     list_of_plots_to_write = make_all_hists_all_files(list_of_files,
00260                                                       list_of_plots,
00261                                                       cut_for_all_files,
00262                                                       cut_sets)
00263     end_time = datetime.now()
00264     print "Done drawing all plots after %s." % duration_to_string(start_time, end_time)
00265 
00266     #   Store and save/close files
00267     outputFile = TFile(output_filename, "recreate")
00268     if outputFile.IsZombie():
00269         print "Error opening %s for output exiting..." % output_filename
00270         sys.exit(1)
00271     print "\nOpened output file. Saving histograms..."
00272     outputFile.cd()
00273     for set_of_cuts in cut_sets:
00274         outputFile.mkdir(set_of_cuts[0])
00275     print "   # entries  histogram"
00276     for i, (plot, cutset) in enumerate(list_of_plots_to_write):
00277         outputFile.cd(cutset[0])
00278         print " %3i %7i  %s/%s" % (i, plot.histogram.GetEntries(),
00279                                    cutset[0],
00280                                    plot.histogram.GetName())
00281         plot.histogram.Write()
00282     outputFile.Close()
00283     print "Done saving."
    print "\nScaled & added histograms from %i TTrees saved in\n  %s" % (len(list_of_files), output_filename)
def python::rootplot::tree2hists::write_default_T2H_config ( )
Writes configuration file for tree2hists

Definition at line 101 of file tree2hists.py.

00102                               :
00103     """Writes configuration file for tree2hists"""
00104     defaultConfig = '''# Configuration file for tree2hists
00105 # Created %s.
00106 try:
00107     ## the normal way to import from rootplot
00108     from rootplot.tree2hists import RootTree, Plot
00109 except ImportError:
00110     ## special import for CMSSW installations of rootplot
00111     from PhysicsTools.PythonAnalysis.rootplot.tree2hists import RootTree, Plot
00112 from array import array      # to allow making Float_t arrays for ROOT hists
00113 from math import pi
00114 from ROOT import TH1F, TH2F  # import other kinds of hists as neeeded
00115 
00116 list_of_files = [RootTree("Treename", fileName="photons.root", scale=1.0, cuts=""),
00117                  RootTree("Treename", fileName="photons2.root", scale=1.0, cuts="")]
00118 
00119 output_filename = "Hists_photons.root"
00120 
00121 cut_for_all_files = "(!TTBit[36] && !TTBit[37] && !TTBit[38] && !TTBit[39] && !vtxIsFake && vtxNdof>4 && abs(vtxZ)<=15)"
00122 
00123 # All plots are made for each "cut set".
00124 # A "cut set" is 3 things: folder name to store hists in, string to add to hist titles, and cuts for these hists.
00125 # Let cut_sets = [] to make all plots.
00126 cut_sets = [
00127     ("barrel15to20", "(|#eta|<1.45, 15<E_{T}<20)", "et>15&&et<20&&abs(eta)<1.45"),
00128     ("barrel20to30", "(|#eta|<1.45, 20<E_{T}<30)", "et>20&&et<30&&abs(eta)<1.45"),
00129     ("endcap15to20", "(1.7<|#eta|<2.5, 15<E_{T}<20)", "et>15&&et<20&&abs(eta)>1.7&&abs(eta)<2.5"),
00130     ("endcap20to30", "(1.7<|#eta|<2.5, 20<E_{T}<30)", "et>20&&et<30&&abs(eta)>1.7&&abs(eta)<2.5")
00131     ]
00132 
00133 # Define histograms to plot
00134 bins_et     = array("f", [15.0, 20.0, 30.0, 50.0, 80.0, 120.0]) # example custom bins
00135 list_of_plots = [
00136     Plot("et"           , TH1F("pho_et"           , "Lead #gamma: E_{T};E_{T} (GeV);entries/bin", 25, 0.0, 100.0)),
00137     Plot("eta"          , TH1F("pho_eta"          , "Lead #gamma: #eta;#eta;entries/bin"        , 25, -3.0, 3.0)),
00138     Plot("et"           , TH1F("pho_et_binned"    , "Lead #gamma: E_{T};E_{T} (GeV);entries/bin", len(bins_et)-1, bins_et)),
00139     Plot("sigmaIetaIeta", TH1F("pho_sigmaIEtaIEta", "Lead #gamma: #sigma_{i#etai#eta};#sigma_{i#etai#eta};entries/bin",20, 0, 0.06)),
00140     Plot("metEt/et"     , TH1F("metEt_over_phoEt" , "MET / E_{T}(#gamma);MET/E_{T}(sc);entries/bin"   , 20, 0.0, 3.0)),
00141     Plot("phi:eta"      , TH2F("phoPhi_vs_phoEta" , "Lead #gamma: #phi vs #eta;#eta;#phi"             , 50, -2.5, 2.5, 18, -pi, pi))
00142     ]
00143 ''' % datetime.now().strftime("%b %d, %Y")
00144     f = open('t2h_config.py', 'w')
00145     f.write(defaultConfig)
00146     f.close()
00147     print "Created default configuration file: t2h_config.py"
00148     print "Edit it, then run by typing:"
    print "  tree2hists t2h_config.py"

Variable Documentation

Initial value:
00001 '''\
00002 Copyright (c) 2010 Michael Anderson <mbanderson@wisc.edu>
00003 
00004 Permission is hereby granted, free of charge, to any person obtaining a copy
00005 of this software and associated documentation files (the "Software"), to deal
00006 in the Software without restriction, including without limitation the rights
00007 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00008 copies of the Software, and to permit persons to whom the Software is
00009 furnished to do so, subject to the following conditions:
00010 
00011 The above copyright notice and this permission notice shall be included in
00012 all copies or substantial portions of the Software.
00013 
00014 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00015 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00016 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00017 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00018 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00019 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
00020 THE SOFTWARE.
00021 '''

Definition at line 13 of file tree2hists.py.