CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
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 #############################################. More...
 
def write_default_T2H_config
 

Variables

string __license__
 

Function Documentation

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

Definition at line 92 of file tree2hists.py.

Referenced by python.rootplot.tree2hists.tree2hists_main().

92 
93 def duration_to_string(start, end):
94  timeTaken = end - start
95  hours, remainder = divmod(timeTaken.seconds, 3600)
96  minutes, seconds = divmod(remainder, 60)
97  if hours>0:
98  return "%i hours, %i minutes" % (hours, minutes)
99  elif minutes>0:
100  return "%i minutes" % minutes
101  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 83 of file tree2hists.py.

References join().

Referenced by python.rootplot.tree2hists.make_all_hists_all_files().

83 
84 def join_cuts(*list_of_cuts):
85  """Joins list of cuts (strings) into something ROOT can handle.
86  Example: given ('1<2','','5>4') returns '1<2&&5>4'"""
87  list_of_nonempty_cuts = []
88  for cut in list_of_cuts:
89  if cut:
90  list_of_nonempty_cuts.append(cut)
91  return '&&'.join(list_of_nonempty_cuts)
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def python.rootplot.tree2hists.main ( )

Definition at line 287 of file tree2hists.py.

References print(), submitPVValidationJobs.split(), python.rootplot.tree2hists.tree2hists_main(), and python.rootplot.tree2hists.write_default_T2H_config().

288 def main():
289  if len(sys.argv) > 1:
290  if path.isfile(sys.argv[1]):
291  config_file = sys.argv[1].split('.')[0]
292  tree2hists_main(config_file)
293  else:
294  print("%s not found." % sys.argv[1])
295  print("Create default config file by running tree2hists "
296  "with no argument.")
297  sys.exit(1)
298  else:
299  if path.exists('t2h_config.py'):
300  print("Run with specific config file, like:")
301  print(" tree2hists t2h_config.py")
302  sys.exit(1)
304  sys.exit(0)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def tree2hists_main
Define the main program #############################################.
Definition: tree2hists.py:212
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 152 of file tree2hists.py.

References join(), python.rootplot.tree2hists.join_cuts(), and print().

Referenced by python.rootplot.tree2hists.tree2hists_main().

153 def make_all_hists_all_files(list_of_RootTrees, list_of_Plots, cut_for_all_files, list_of_cutSets):
154  '''Open root files one at a time, make plots, then close them.'''
155  list_of_plots_to_write = []
156 
157  # Create plots for each set of cuts
158  for set_of_cuts in list_of_cutSets:
159  histname_fix, title_fix, current_cut_set = set_of_cuts
160  for plot in list_of_Plots:
161  new_plot = deepcopy(plot)
162  new_title = ' '.join((plot.histogram.GetTitle(), title_fix))
163  new_plot.histogram.SetTitle(new_title)
164  list_of_plots_to_write.append((new_plot, set_of_cuts))
165 
166  for j, rootTree in enumerate(list_of_RootTrees):
167  rootTree.tfile = TFile(rootTree.fileName, "read") # Open TFile
168  if rootTree.tfile.IsZombie():
169  print("Error opening %s, exiting..." % rootTree.fileName)
170  sys.exit(0)
171  try: # Try to get TTree from file.
172  rootTree.tfile.GetObject(rootTree.treeName, rootTree.ttree)
173  except:
174  print("Error: %s not found in %s, exiting..." % (rootTree.treeName,
175  rootTree.fileName))
176  sys.exit(1)
177 
178  print("\n%s: Opened %s %i MB" % (datetime.now().strftime("%I:%M%p"),
179  rootTree.fileName,
180  path.getsize(rootTree.fileName)/1048576))
181  print(" %s has %i entries, will plot with scale=%.2e, cuts='%s'" % (rootTree.treeName,
182  rootTree.ttree.GetEntries(),
183  rootTree.scale,
184  rootTree.cuts))
185 
186  # Loop over plots
187  print(" # entries var >> histogram")
188  for i, (plot, set_of_cuts) in enumerate(list_of_plots_to_write):
189  histname_fix, title_fix, current_cut_set = set_of_cuts
190  tmp_hist = plot.histogram.Clone("temp") # Create temp hist
191  all_cuts = join_cuts(cut_for_all_files, rootTree.cuts,
192  current_cut_set, plot.cuts) # Set cuts
193  rootTree.ttree.Draw( "%s >> temp" % plot.treeVariable, all_cuts,
194  "goff") # Draw with graphics off
195  tmp_hist.Scale(rootTree.scale) # Scale temp
196  entries_before = plot.histogram.GetEntries()
197  plot.histogram.Add(tmp_hist) # Add temp hist to total
198  entries_after = plot.histogram.GetEntries()
199  print(" %3i %7i %20s >> %s/%s" % (i, entries_after-entries_before,
200  plot.treeVariable, histname_fix,
201  plot.histogram.GetName()), end=' ')
202  if plot.cuts:
203  print("\textra cuts: %s" % plot.cuts, end=' ') # plot-specific cuts
204  print()
205 
206  rootTree.tfile.Close() # Close TFile
207  print("%s: Closed %s" % (datetime.now().strftime("%I:%M%p"),
208  rootTree.fileName))
209  return list_of_plots_to_write
210 
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def python.rootplot.tree2hists.tree2hists_main (   config_file)

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

Definition at line 212 of file tree2hists.py.

References python.rootplot.tree2hists.duration_to_string(), python.rootplot.tree2hists.make_all_hists_all_files(), and print().

Referenced by python.rootplot.tree2hists.main().

213 def tree2hists_main(config_file):
214  try:
215  # Import only certain variables
216  sys.path.insert(0, '')
217  _temp = __import__(config_file, globals(), locals(),
218  ['list_of_files','output_filename',
219  'cut_for_all_files','cut_sets','list_of_plots'], -1)
220  list_of_files = _temp.list_of_files
221  output_filename = _temp.output_filename
222  cut_for_all_files = _temp.cut_for_all_files
223  cut_sets = _temp.cut_sets
224  list_of_plots = _temp.list_of_plots
225  for rootTree in list_of_files:
226  if not path.isfile(rootTree.fileName):
227  print("Error:\n %s\nnot found for input." % rootTree.fileName)
228  sys.exit(1)
229  hist_names = [plot.name for plot in list_of_plots]
230  if len(hist_names)>len(set(hist_names)):
231  print(hist_names)
232  print("Error: Each plot needs a unique name, exiting...")
233  sys.exit(1)
234  if path.isfile(output_filename):
235  print("Warning: %s exists" % output_filename)
236  except Exception as e:
237  print(e)
238  print("Error with %s" % config_file)
239  sys.exit(1)
240 
241  if path.isfile('rootlogon.C'):
242  print("Loading rootlogon.C")
243  gROOT.Macro('rootlogon.C') # Load functions from rootlogon script
244 
245  if cut_sets:
246  print("\n%i defined cut sets:" % len(cut_sets))
247  for cut in cut_sets:
248  name, title_fix, current_cut_set = cut
249  print(" %s\t: '%s'" % (name, current_cut_set))
250  cut_names = [name for name,num,cut in cut_sets]
251  if len(cut_names)>len(set(cut_names)):
252  print("Error: Each cut set needs a unique name, exiting...")
253  sys.exit(1)
254  else:
255  cut_sets = [("","","")] # Make all plots, no extra cuts
256 
257  print("\nCuts to apply to all files:\n\t'%s'" % cut_for_all_files)
258 
259  start_time = datetime.now()
260  list_of_plots_to_write = make_all_hists_all_files(list_of_files,
261  list_of_plots,
262  cut_for_all_files,
263  cut_sets)
264  end_time = datetime.now()
265  print("Done drawing all plots after %s." % duration_to_string(start_time, end_time))
266 
267  # Store and save/close files
268  outputFile = TFile(output_filename, "recreate")
269  if outputFile.IsZombie():
270  print("Error opening %s for output exiting..." % output_filename)
271  sys.exit(1)
272  print("\nOpened output file. Saving histograms...")
273  outputFile.cd()
274  for set_of_cuts in cut_sets:
275  outputFile.mkdir(set_of_cuts[0])
276  print(" # entries histogram")
277  for i, (plot, cutset) in enumerate(list_of_plots_to_write):
278  outputFile.cd(cutset[0])
279  print(" %3i %7i %s/%s" % (i, plot.histogram.GetEntries(),
280  cutset[0],
281  plot.histogram.GetName()))
282  plot.histogram.Write()
283  outputFile.Close()
284  print("Done saving.")
print("\nScaled & added histograms from %i TTrees saved in\n %s" % (len(list_of_files), output_filename))
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def tree2hists_main
Define the main program #############################################.
Definition: tree2hists.py:212
def python.rootplot.tree2hists.write_default_T2H_config ( )
Writes configuration file for tree2hists

Definition at line 102 of file tree2hists.py.

References print().

Referenced by python.rootplot.tree2hists.main().

104  """Writes configuration file for tree2hists"""
105  defaultConfig = '''# Configuration file for tree2hists
106 # Created %s.
107 try:
108  ## the normal way to import from rootplot
109  from rootplot.tree2hists import RootTree, Plot
110 except ImportError:
111  ## special import for CMSSW installations of rootplot
112  from PhysicsTools.PythonAnalysis.rootplot.tree2hists import RootTree, Plot
113 from array import array # to allow making Float_t arrays for ROOT hists
114 from math import pi
115 from ROOT import TH1F, TH2F # import other kinds of hists as neeeded
116 
117 list_of_files = [RootTree("Treename", fileName="photons.root", scale=1.0, cuts=""),
118  RootTree("Treename", fileName="photons2.root", scale=1.0, cuts="")]
119 
120 output_filename = "Hists_photons.root"
121 
122 cut_for_all_files = "(!TTBit[36] && !TTBit[37] && !TTBit[38] && !TTBit[39] && !vtxIsFake && vtxNdof>4 && abs(vtxZ)<=15)"
123 
124 # All plots are made for each "cut set".
125 # A "cut set" is 3 things: folder name to store hists in, string to add to hist titles, and cuts for these hists.
126 # Let cut_sets = [] to make all plots.
127 cut_sets = [
128  ("barrel15to20", "(|#eta|<1.45, 15<E_{T}<20)", "et>15&&et<20&&abs(eta)<1.45"),
129  ("barrel20to30", "(|#eta|<1.45, 20<E_{T}<30)", "et>20&&et<30&&abs(eta)<1.45"),
130  ("endcap15to20", "(1.7<|#eta|<2.5, 15<E_{T}<20)", "et>15&&et<20&&abs(eta)>1.7&&abs(eta)<2.5"),
131  ("endcap20to30", "(1.7<|#eta|<2.5, 20<E_{T}<30)", "et>20&&et<30&&abs(eta)>1.7&&abs(eta)<2.5")
132  ]
133 
134 # Define histograms to plot
135 bins_et = array("f", [15.0, 20.0, 30.0, 50.0, 80.0, 120.0]) # example custom bins
136 list_of_plots = [
137  Plot("et" , TH1F("pho_et" , "Lead #gamma: E_{T};E_{T} (GeV);entries/bin", 25, 0.0, 100.0)),
138  Plot("eta" , TH1F("pho_eta" , "Lead #gamma: #eta;#eta;entries/bin" , 25, -3.0, 3.0)),
139  Plot("et" , TH1F("pho_et_binned" , "Lead #gamma: E_{T};E_{T} (GeV);entries/bin", len(bins_et)-1, bins_et)),
140  Plot("sigmaIetaIeta", TH1F("pho_sigmaIEtaIEta", "Lead #gamma: #sigma_{i#etai#eta};#sigma_{i#etai#eta};entries/bin",20, 0, 0.06)),
141  Plot("metEt/et" , TH1F("metEt_over_phoEt" , "MET / E_{T}(#gamma);MET/E_{T}(sc);entries/bin" , 20, 0.0, 3.0)),
142  Plot("phi:eta" , TH2F("phoPhi_vs_phoEta" , "Lead #gamma: #phi vs #eta;#eta;#phi" , 50, -2.5, 2.5, 18, -pi, pi))
143  ]
144 ''' % datetime.now().strftime("%b %d, %Y")
145  f = open('t2h_config.py', 'w')
146  f.write(defaultConfig)
147  f.close()
148  print("Created default configuration file: t2h_config.py")
149  print("Edit it, then run by typing:")
print(" tree2hists t2h_config.py")
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47

Variable Documentation

string python.rootplot.tree2hists.__license__
Initial value:
1 = '''\
2 Copyright (c) 2010 Michael Anderson <mbanderson@wisc.edu>
3 
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10 
11 The above copyright notice and this permission notice shall be included in
12 all copies or substantial portions of the Software.
13 
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE.
21 '''

Definition at line 14 of file tree2hists.py.