ATLAS Offline Software
MaterialValidation.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
4 # encoding: utf-8
5 from __future__ import print_function
6 
7 """
8 MaterialValidation.py
9 
10 Created by Andreas Salzburger on 2009-04-16.
11 Updated by Wolfgang Lukas on 2011-04-29.
12 Copyright (c) 2009-2011 The ATLAS Collaboration. All rights reserved.
13 """
14 
15 import time
16 import sys,os
17 import getopt
18 from TTreeHelper import *
19 from ROOT import TCanvas,TTree,TProfile,gDirectory,TColor,TH1F,THStack
20 
21 help_message = '''
22 The help message goes here.
23 '''
24 
25 class Usage(Exception):
26  def __init__(self, msg):
27  self.msg = msg
28 
29 def main(argv=None):
30  if argv is None:
31  argv = sys.argv
32  try:
33  try:
34  opts, args = getopt.getopt(argv[1:], "ho:v", ["help", "output="])
35  except getopt.error as msg:
36  raise Usage(msg)
37 
38  # option processing
39  for option, value in opts:
40  if option == "-v":
41  verbose = True
42  if option in ("-h", "--help"):
43  raise Usage(help_message)
44  if option in ("-o", "--output"):
45  output = value
46 
47  except Usage as err:
48  print (sys.argv[0].split("/")[-1] + ": " + str(err.msg),file=sys.stderr)
49  print ("\t for help use --help", file=sys.stderr)
50  return 2
51 
52  inputfiles =''
53  inputtrees =''
54  inputparams =''
55  saveasfiles =''
56  # argument list given
57  for iarg in range(len(argv)) :
58  if argv[iarg].find('files') >= 0:
59  inputfiles = argv[iarg]
60  elif argv[iarg].find('trees') >= 0:
61  inputtrees = argv[iarg]
62  elif argv[iarg].find('params') >= 0:
63  inputparams = argv[iarg]
64  elif argv[iarg].find('saveas') >= 0:
65  saveasfiles = argv[iarg]
66 
67  filelist = splitInputArgs(inputfiles)
68  treelist = splitInputArgs(inputtrees)
69  parslist = splitInputArgs(inputparams)
70  saveaslist = splitInputArgs(saveasfiles)
71 
72  # prepare the output directory
73  if len(saveaslist) > 0:
74  if not os.path.isdir('./output/'):
75  os.mkdir('./output/')
76  # make the output directory
77  outputdir = './output/mval_'+str(time.time())+'/'
78  if not os.path.isdir(outputdir):
79  os.mkdir(outputdir)
80  # save according to the given parameters
81  for saveas in saveaslist :
82  # check whether the directory exists
83  if not os.path.isdir(outputdir+saveas+'/'):
84  os.mkdir(outputdir+saveas+'/')
85 
86  # draw numbering
87  numPlots = len(parslist)
88  numRows = 1
89  numCols = numPlots
90  if numPlots > 2 :
91  numRows = 2
92  numCols = numPlots//2 + numPlots%2
93 
94  print ('[>] Files to be processed :', filelist)
95  print ('[>] Trees to be drawn :', len(treelist))
96  print ('[>] Profiles to be made :', parslist)
97  print ('[>] Going to be saved as :', saveaslist )
98  print ('[>] Number of cols/rows :',numCols,', ',numRows)
99 
100  # get the file and the associated dictionaries
101  canvasDict = {}
102  canvasTotalDict = {}
103 
104  fileNum = 0
105  #filename = argv[1]
106  for filename in filelist :
107  # get the tree selector and the dictionary
108  singleSelector = TTreeSelector(filename)
109  singleDict = singleSelector.loadTrees(treelist[0])
110 
111  # create the canvas list
112  for entry in singleDict :
113  iden = entry.lstrip('TVolume_').replace('::','_')
114  # create the canvas for this
115  if iden not in canvasDict :
116  canvas = TCanvas(iden,'TrackingVolume:'+iden,100,100,numCols*300,numRows*300)
117  if numCols > 1 :
118  canvas.Divide(numCols,numRows)
119  # fill into canvas dictionary
120  canvasDict[iden] = canvas
121  else :
122  canvas = canvasDict[iden]
123 
124  # now loop over the parameter list
125  pad = 0
126  if len(parslist) > 1 : pad = 1
127 
128  for par in parslist :
129  tree = singleDict[entry]
130  plotProfile(canvas,pad,tree,par,fileNum)
131  pad += 1
132 
133  # save according to the given parameters
134  for saveas in saveaslist :
135  canvas.SaveAs(outputdir+saveas+'/'+iden+'.'+saveas)
136 
137  # create the canvas list for stacked plots
138  for entry in singleDict :
139  iden = entry.lstrip('TVolume_').replace('::','_') + '_TOTAL'
140  # take only mapped trees as a basis
141  if '_UNMAPPED' in entry : continue
142  # do stack only if unmapped trees are also available
143  if (entry+'_UNMAPPED') not in singleDict : continue
144  # create the canvas for this
145  if iden not in canvasTotalDict :
146  canvas = TCanvas(iden,'TrackingVolume:'+iden,100,100,numCols*300,numRows*300)
147  if numCols > 1 :
148  canvas.Divide(numCols,numRows)
149  # fill into canvas dictionary
150  canvasTotalDict[iden] = canvas
151  else :
152  canvas = canvasTotalDict[iden]
153 
154  # now loop over the parameter list
155  pad = 0
156  if len(parslist) > 1 : pad = 1
157 
158  for par in parslist :
159  tree1 = singleDict[entry]
160  tree2 = singleDict[entry+'_UNMAPPED']
161  # TODO: also give saveaslist ... or rewrite and only give persistent THStack and save as above
162  outpath = outputdir+saveas+'/'+iden+'.'+saveas
163  plotStack(canvas,pad,tree1,tree2,par,fileNum,outpath)
164  pad += 1
165 
166 
167  # fileNum
168  fileNum += 1
169  print ('[>] Next file, switching to same option (',fileNum,')')
170 
171 
172 def splitInputArgs(argstring):
173  # split the keyword off
174  splitlist = argstring.split('=')
175  inputlist = []
176  if len(splitlist) is 2 :
177  inputlist = splitlist[1].split(",")
178  return inputlist
179 
180 
181 def plotProfile(canvas,pad,tree,param,fileNum):
182  # the name
183  tprofname = tree.GetName()+param+str(fileNum)
184  # draw it and get it
185  tmpCanv = TCanvas(tprofname)
186  tmpCanv.cd()
187  tree.Draw(param+'>>'+tprofname+'(200)','','prof,goff')
188 
189  print ('[>] In plotProfile() with option :',fileNum)
190 
191  if pad > 0:
192  canvas.cd(pad)
193  else :
194  canvas.cd()
195 
196  tprofile = gDirectory.Get(tprofname)
197 
198 # lower = tprofile.GetBinLowEdge(1)
199 # upper = tprofile.GetBinLowEdge(201)
200 # print (lower,upper)
201 # h1 = tprofile.ProjectionX('h1')
202 
203 # if fileNum == 1 # for full comparison plot with 2 histos
204 # tprofile.SetFillColor(5)
205 # tprofile.Draw("hist,same")
206 # elif fileNum :
207  title = tree.GetName().split('_')[1]
208  color = 5
209  if '_UNMAPPED' in tree.GetName() :
210  title += ' UNMAPPED'
211  color = 17
212  tprofile.SetTitle(title)
213  tprofile.GetXaxis().SetTitle(param.split(':')[1])
214  tprofile.GetYaxis().SetTitle(param.split(':')[0])
215 # h1.SetTitle(title)
216 # h1.GetXaxis().SetTitle(param.split(':')[1])
217 # h1.GetYaxis().SetTitle(param.split(':')[0])
218  if fileNum :
219  tprofile.SetLineColor(fileNum)
220  tprofile.SetMarkerColor(fileNum)
221  tprofile.SetMarkerStyle(8)
222  tprofile.SetMarkerSize(0.35)
223  tprofile.Draw("p,same")
224 # h1.SetLineColor(fileNum)
225 # h1.SetMarkerColor(fileNum)
226 # h1.SetMarkerStyle(8)
227 # h1.SetMarkerSize(0.35)
228 # h1.Draw("p,same")
229  else :
230  tprofile.SetLineColor(1)
231  tprofile.SetFillColor(color)
232  tprofile.Draw('hist')
233 # h1.SetFillColor(color)
234 # h1.Draw('hist')
235 
236 
237 def plotStack(canvas,pad,tree1,tree2,param,fileNum,outpath):
238  # the name
239  tprofname1 = tree1.GetName()+param+str(fileNum)
240  tprofname2 = tree2.GetName()+param+str(fileNum)
241  # they already exist in gDirectory, get them
242  tmpCanv = TCanvas(tprofname1+'stack')
243  tmpCanv.cd()
244  tprofile1 = gDirectory.Get(tprofname1)
245  tprofile2 = gDirectory.Get(tprofname2)
246 
247  # get the overall upper and lower bin limits
248  lower1 = tprofile1.GetBinLowEdge(1)
249  lower2 = tprofile2.GetBinLowEdge(1)
250 # lower2 = tprofile2.GetBinCenter(1) - tprofile2.GetXAxis.GetBinWidth()/2.
251 # upper1 = tprofile1.GetBinCenter(200) + tprofile1.GetXAxis.GetBinWidth()/2.
252  upper1 = tprofile1.GetBinLowEdge(201)
253  upper2 = tprofile2.GetBinLowEdge(201)
254 
255  newmin = min(lower1,lower2)
256  newmax = max(upper1,upper2)
257 
258  # draw the plots again with new binning
259  tprofname1new = tprofname1 + 'rebin'
260  tprofname2new = tprofname2 + 'rebin'
261  tree1.Draw(param+'>>'+tprofname1new+'(200,'+str(newmin)+','+str(newmax)+')','','prof,goff')
262  tree2.Draw(param+'>>'+tprofname2new+'(200,'+str(newmin)+','+str(newmax)+')','','prof,goff')
263  tprofile1new = gDirectory.Get(tprofname1new)
264  tprofile2new = gDirectory.Get(tprofname2new)
265 
266  print ('[>] In plotStack() with option :',fileNum)
267 
268  if pad > 0:
269  canvas.cd(pad)
270  else :
271  canvas.cd()
272 
273  # projection to TH1F for stacking
274  h1st = tprofile1new.ProjectionX(tprofname1new+'h1')
275  h2st = tprofile2new.ProjectionX(tprofname2new+'h2')
276  ts = THStack()
277 
278  title = tree1.GetName().split('_')[1] + ' TOTAL'
279  ts.SetTitle(title)
280  print ('[>] Stack:', tree1.GetName().split('_')[1], ' newmin =', newmin, ' newmax =', newmax)
281  h1st.GetXaxis().SetTitle(param.split(':')[1])
282  h1st.GetYaxis().SetTitle(param.split(':')[0])
283  h2st.GetXaxis().SetTitle(param.split(':')[1])
284  h2st.GetYaxis().SetTitle(param.split(':')[0])
285 
286  if fileNum :
287  h1st.SetLineColor(fileNum)
288  h1st.SetMarkerColor(fileNum)
289  h1st.SetMarkerStyle(8)
290  h1st.SetMarkerSize(0.35)
291  h1st.Draw("p,same")
292  h2st.SetLineColor(fileNum+10)
293  h2st.SetMarkerColor(fileNum+10)
294  h2st.SetMarkerStyle(8)
295  h2st.SetMarkerSize(0.35)
296  h2st.Draw("p,same")
297  ts.Add(h1st)
298  ts.Add(h2st)
299  ts.Draw()
300  else :
301  h1st.SetLineColor(1)
302  h1st.SetFillColor(5)
303  h1st.Draw('hist')
304  h2st.SetLineColor(1)
305  h2st.SetFillColor(17)
306  h2st.Draw('hist')
307  ts.Add(h1st,'hist')
308  ts.Add(h2st,'hist')
309  ts.Draw()
310 
311  canvas.SaveAs(outpath)
312 
313 
314 if __name__ == "__main__":
315  sys.exit(main())
replace
std::string replace(std::string s, const std::string &s2, const std::string &s3)
Definition: hcg.cxx:307
max
#define max(a, b)
Definition: cfImp.cxx:41
find
std::string find(const std::string &s)
return a remapped string
Definition: hcg.cxx:135
MaterialValidation.main
def main(argv=None)
Definition: MaterialValidation.py:29
MaterialValidation.Usage.msg
msg
Definition: MaterialValidation.py:27
MaterialValidation.Usage.__init__
def __init__(self, msg)
Definition: MaterialValidation.py:26
MaterialValidation.Usage
Definition: MaterialValidation.py:25
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
TTreeHelper.TTreeSelector
Definition: TTreeHelper.py:13
MaterialValidation.plotStack
def plotStack(canvas, pad, tree1, tree2, param, fileNum, outpath)
Definition: MaterialValidation.py:237
min
#define min(a, b)
Definition: cfImp.cxx:40
MaterialValidation.plotProfile
def plotProfile(canvas, pad, tree, param, fileNum)
Definition: MaterialValidation.py:181
MaterialValidation.splitInputArgs
def splitInputArgs(argstring)
Definition: MaterialValidation.py:172
str
Definition: BTagTrackIpAccessor.cxx:11
Trk::split
@ split
Definition: LayerMaterialProperties.h:38