CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
cuy.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #____________________________________________________________
3 #
4 # cuy
5 #
6 # A very simple way to make plots with ROOT via an XML file
7 #
8 # Francisco Yumiceva
9 # yumiceva@fnal.gov
10 #
11 # Fermilab, 2008
12 #
13 # imported from UserCode/Yumiceva/cuy
14 #
15 # modified by Adrien Caudron to create TGraphErrors for b-tag performance plots
16 # UCLouvain, 2012
17 #_____________________________________________________________
18 
19 """
20  cuy
21 
22  A very simple way to make plots with ROOT via an XML file.
23 
24  usage: %prog -x <XML configuration file>
25  -b, --batch : run in batch mode without graphics.
26  -c, --create = CREATE: create XML configuration file from a ROOT file.
27  -e, --example = EXAMPLE: generate an example xml file.
28  -f, --flag = FLAG: create a baneer
29  -l, --list = LIST: list of objects in the ROOT file.
30  -p, --prt = PRT: print canvas in the format specified png, ps, eps, pdf, etc.
31  -t, --tag = TAG: tag name for XML configuration file.
32  -v, --verbose : verbose output.
33  -w, --wait : Pause script after plotting a new superposition of histograms.
34  -x, --xml = XML: xml configuration file.
35 
36  Francisco Yumiceva (yumiceva@fnal.gov)
37  Fermilab 2008
38 
39 """
40 
41 
42 import os, string, re, sys, math
43 
44 try:
45  import ROOT
46 except:
47  print "\nCannot load PYROOT, make sure you have setup ROOT in the path"
48  print "and pyroot library is also defined in the variable PYTHONPATH, try:\n"
49  if (os.getenv("PYTHONPATH")):
50  print " setenv PYTHONPATH ${PYTHONPATH}:$ROOTSYS/lib\n"
51  else:
52  print " setenv PYTHONPATH $ROOTSYS/lib\n"
53  sys.exit()
54 
55 from ROOT import TFile
56 from ROOT import TCanvas
57 from ROOT import TLegend
58 from ROOT import SetOwnership
59 from ROOT import THStack
60 from ROOT import TLatex
61 from ROOT import TH1
62 from ROOT import TH1F
63 from ROOT import TGraphErrors
64 from ROOT import TVectorD
65 from ROOT import std
66 
67 from xml.sax import saxutils, make_parser, handler
68 from xml.sax.handler import feature_namespaces
69 
70 import Inspector
71 import Style
72 
73 #_______________OPTIONS________________
74 import optparse
75 
76 USAGE = re.compile(r'(?s)\s*usage: (.*?)(\n[ \t]*\n|$)')
77 
78 def nonzero(self): # will become the nonzero method of optparse.Values
79  "True if options were given"
80  for v in self.__dict__.itervalues():
81  if v is not None: return True
82  return False
83 
84 optparse.Values.__nonzero__ = nonzero # dynamically fix optparse.Values
85 
86 class ParsingError(Exception): pass
87 
88 optionstring=""
89 
90 def exit(msg=""):
91  raise SystemExit(msg or optionstring.replace("%prog",sys.argv[0]))
92 
93 def parse(docstring, arglist=None):
94  global optionstring
95  optionstring = docstring
96  match = USAGE.search(optionstring)
97  if not match: raise ParsingError("Cannot find the option string")
98  optlines = match.group(1).splitlines()
99  try:
100  p = optparse.OptionParser(optlines[0])
101  for line in optlines[1:]:
102  opt, help=line.split(':')[:2]
103  short,long=opt.split(',')[:2]
104  if '=' in opt:
105  action='store'
106  long=long.split('=')[0]
107  else:
108  action='store_true'
109  p.add_option(short.strip(),long.strip(),
110  action = action, help = help.strip())
111  except (IndexError,ValueError):
112  raise ParsingError("Cannot parse the option string correctly")
113  return p.parse_args(arglist)
114 
115 #______________________________________________________________________
116 
118  def __init__(self):
119  self.type = ""
120  self.filename = ""
121  self.release = ""
122  self.histos = {}
123  self.TH1s = {}
124  self.weight = None
125 
127  def __init__(self):
128  self.name = ""
129  self.numerator = None
130  self.denominator = None
131 
133  def __init__(self):
134  self.name = ""
135  self.title = ""
136  self.color = ""
137 
139  def __init__(self):
140  self.name = ""
141  self.title = ""
142  self.SetLogy = ""
143  self.SetGrid = ""
144  self.histos = []
145  self.weight = []
146 
148  def __init__(self):
149  self.name = ""
150  self.title = ""
151  self.SetLogy = ""
152  self.SetGrid = ""
153  self.histos = []
154  self.color = []
155  self.marker = []
156  self.legend = []
157  self.weight = []
158  #self.flavour = []
159 #**********************************
161  def __init__(self):
162  self.name = ""
163  self.title = ""
164  self.SetLogy = ""
165  self.SetGrid = ""
166  self.histos = []
167  self.color = []
168  self.marker = []
169  self.legend = []
170  self.weight = []
171  self.flavour = []
172 #**********************************
173 
174 class FindIssue(handler.ContentHandler):
175  def __init__(self):
176  self.data = {}
177  self.divide = {}
178  self.addition = {}
179  self.superimpose = {}
180  self.graph = {}
181  self.tmpaddname = ""
182  self.plot = {}
183  self.size = 0
184  self.atype = ""
185  self.tmpsupername = ""
186  self.tmpgraphname = ""
187 
188  def startElement(self, name, attrs):
189  if name == 'validation':
190  self.size = self.size + 1
191  self.atype = attrs.get('type',None)
192  self.data[self.atype] = ValElement()
193  self.data[self.atype].type = attrs.get('type',None)
194  self.data[self.atype].filename = attrs.get('file',None)
195  self.data[self.atype].release = attrs.get('release',None)
196  self.data[self.atype].weight = attrs.get('weight','')
197  if name == 'TH1':
198  self.data[self.atype].histos[attrs.get('name',None)] = attrs.get('source',None)
199  #print attrs.get('name',None)
200  #print attrs.get('source',None)
201  if name == 'divide':
202  aname = attrs.get('name',None)
203  self.divide[aname] = divideElement()
204  self.divide[aname].name = aname
205  self.divide[aname].numerator = attrs.get('numerator',None)
206  self.divide[aname].denominator = attrs.get('denominator',None)
207  self.divide[aname].DivideOption = attrs.get('DivideOption',None)
208  self.divide[aname].Option = attrs.get('Option',None)
209  if name == 'addition':
210  aname = attrs.get('name',None)
211  self.addition[aname] = additionElement()
212  self.tmpaddname = aname
213  self.addition[aname].name = aname
214  self.addition[aname].title = attrs.get('title',None)
215  self.addition[aname].YTitle = attrs.get('YTitle',None)
216  self.addition[aname].XTitle = attrs.get('XTitle',None)
217  self.addition[aname].Option = attrs.get('Option',None)
218  self.addition[aname].Weight = attrs.get('Wight',None)
219  self.addition[aname].Normalize = attrs.get('Normalize',None)
220  self.addition[aname].SetGrid = attrs.get('SetGrid',None)
221  if name == 'additionItem':
222  #print "in element: " + self.tmpsupername
223  self.addition[self.tmpaddname].histos.append(attrs.get('name',None))
224  self.addition[self.tmpaddname].weight.append(attrs.get('weight',None))
225  if name == 'superimpose':
226  aname = attrs.get('name',None)
227  self.superimpose[aname] = superimposeElement()
228  self.superimpose[aname].name = aname
229  self.superimpose[aname].title = attrs.get('title',None)
230  self.superimpose[aname].SetLogy = attrs.get('SetLogy',None)
231  self.superimpose[aname].SetGrid = attrs.get('SetGrid',None)
232  self.superimpose[aname].Normalize = attrs.get('Normalize',None)
233  self.superimpose[aname].Stack = attrs.get('Stack',None)
234  self.superimpose[aname].YTitle = attrs.get('YTitle',None)
235  self.superimpose[aname].XTitle = attrs.get('XTitle',None)
236  self.superimpose[aname].projection = attrs.get('Projection',None)
237  self.superimpose[aname].bin = attrs.get('bin',None)
238  self.superimpose[aname].profile = attrs.get('Profile',None)
239  self.superimpose[aname].Fill = attrs.get('Fill',None)
240  self.superimpose[aname].Option = attrs.get('Option',None)
241  self.superimpose[aname].Weight = attrs.get('Weight',None)
242  self.superimpose[aname].Maximum = attrs.get('Maximum',None)
243  self.superimpose[aname].Minimum = attrs.get('Minimum',None)
244  self.superimpose[aname].Labels = attrs.get('Labels',None)
245  self.superimpose[aname].Rebin = attrs.get('Rebin',None)
246  self.tmpsupername = aname
247  if name == 'graph':
248  aname = attrs.get('name',None)
249  self.graph[aname] = graphElement()
250  self.graph[aname].name = aname
251  self.graph[aname].title = attrs.get('title',None)
252  self.graph[aname].SetLogy = attrs.get('SetLogy',None)
253  self.graph[aname].SetGrid = attrs.get('SetGrid',None)
254  self.graph[aname].Normalize = attrs.get('Normalize',None)
255  self.graph[aname].Stack = attrs.get('Stack',None)
256  self.graph[aname].YTitle = attrs.get('YTitle',None)
257  self.graph[aname].XTitle = attrs.get('XTitle',None)
258  self.graph[aname].projection = attrs.get('Projection',None)
259  self.graph[aname].bin = attrs.get('bin',None)
260  self.graph[aname].profile = attrs.get('Profile',None)
261  self.graph[aname].Fill = attrs.get('Fill',None)
262  self.graph[aname].Option = attrs.get('Option',None)
263  self.graph[aname].Weight = attrs.get('Weight',None)
264  self.graph[aname].Maximum = attrs.get('Maximum',None)
265  self.graph[aname].Minimum = attrs.get('Minimum',None)
266  self.graph[aname].Labels = attrs.get('Labels',None)
267  self.tmpgraphname = aname
268  if name == 'superimposeItem':
269  #print "in element: " + self.tmpsupername
270  self.superimpose[self.tmpsupername].histos.append(attrs.get('name',None))
271  self.superimpose[self.tmpsupername].color.append(attrs.get('color',None))
272  self.superimpose[self.tmpsupername].marker.append(attrs.get('MarkerStyle',None))
273  self.superimpose[self.tmpsupername].legend.append(attrs.get('legend',None))
274  #self.superimpose[self.tmpsupername].flavour.append(attrs.get('flavour',None))
275  #self.superimpose[self.tmpsupername].weight.append(attrs.get('weight',None))
276  if name == 'graphItem':
277  #print "in element: " + self.tmpsupername
278  self.graph[self.tmpgraphname].histos.append(attrs.get('name',None))
279  self.graph[self.tmpgraphname].color.append(attrs.get('color',None))
280  self.graph[self.tmpgraphname].marker.append(attrs.get('MarkerStyle',None))
281  self.graph[self.tmpgraphname].legend.append(attrs.get('legend',None))
282  self.graph[self.tmpgraphname].flavour.append(attrs.get('flavour',None))
283  #self.se[self.tmpsupername].weight.append(attrs.get('weight',None))
284 
285 
286 
287 if __name__ == '__main__':
288 
289 
290 
291  # style
292  thestyle = Style.Style()
293  thestyle.SetStyle()
294 
295  printCanvas = False
296  printFormat = "png"
297  printBanner = False
298  Banner = "CMS Preliminary"
299  verbose = False
300 
301  # check options
302  option,args = parse(__doc__)
303  if not args and not option: exit()
304 
305  if option.batch:
306  ROOT.gROOT.SetBatch()
307 
308  if option.verbose:
309  verbose = True
310 
311  if option.list:
313  ins.Verbose(True)
314  ins.createXML(False)
315  ins.SetFilename(option.list)
316  ins.GetListObjects()
317  sys.exit()
318 
319  if option.create:
320  createXML = Inspector.Inspector()
321  createXML.Verbose(False)
322  createXML.createXML(True)
323  if option.tag:
324  createXML.SetTag(option.tag)
325  createXML.SetFilename(option.create)
326  createXML.GetListObjects()
327  sys.exit()
328 
329  if not option.xml: exit()
330  if option.prt:
331  printCanvas = True
332  printFormat = option.prt
333 
334  if option.flag:
335  printBanner = True
336  Banner = option.flag
337 
338  # check xml file
339  try:
340  xmlfile = open(option.xml)
341  xmlfile.close()
342  except:
343  print " ERROR: xml file \"" + option.xml + "\" does not exist"
344  sys.exit()
345 
346  # Create a parser
347  parser = make_parser()
348 
349  # Tell the parser we are not interested in XML namespaces
350  parser.setFeature(feature_namespaces, 0)
351 
352  # Create the handler
353  dh = FindIssue()
354 
355  # Tell the parser to use our handler
356  parser.setContentHandler(dh)
357 
358  # Parse the input
359  parser.parse(option.xml)
360 
361  # list of canvas
362  cv = {}
363  afilelist = {}
364  stacklist = {}
365 
366  # root output file
367  outputroot = TFile("cuy.root","RECREATE")
368 
369  # new histograms
370  newTH1list = []
371 
372  # extract histograms
373  thedata = dh.data
374 
375  firstFilename = ''
376 
377  for ikey in thedata:
378  if verbose : print "= Processing set called: " + ikey
379  afilename = thedata[ikey].filename
380  if firstFilename == '':
381  firstFilename = afilename
382  arelease = ""
383  if thedata[ikey].release != None:
384  arelease = thedata[ikey].release
385  if verbose : print "== filename: " + afilename
386  if verbose : print "== release: " + arelease
387  if verbose : print "== weight: " + thedata[ikey].weight
388  thehistos = thedata[ikey].histos
389  afilelist[afilename] = TFile(afilename)
390  if verbose : print "== get histograms: "
391  histonamekeys = thehistos.keys()
392  for ihname in histonamekeys:
393  if verbose : print "=== Histogram name: \""+ ihname + "\" source: \""+thehistos[ihname]+"\""
394  thedata[ikey].TH1s[ihname] = ROOT.gDirectory.Get(thehistos[ihname])
395  #SetOwnership(thedata[ikey].TH1s[ihname], 0)
396  # check if file exists
397  print thedata[ikey].TH1s[ihname].GetName()
398 
399 
400  # plot superimpose histograms
401  #afilelist['../outputLayer2_ttbarmuonic_all.root'].cd()
402  afilelist[firstFilename].cd()
403  #print thedata['ttbar'].TH1s['gen_eta'].GetEntries()
404 
405 
406  theaddition = dh.addition
407  if verbose : print "= Create addition histograms:"
408 
409  for ikey in theaddition:
410  if verbose : print "== plot name: \""+theaddition[ikey].name+"\" title: \""+theaddition[ikey].title+"\""
411  listname = theaddition[ikey].histos
412  listweight = theaddition[ikey].weight
413 
414  #create canvas
415  cv[theaddition[ikey].name] = TCanvas(theaddition[ikey].name,theaddition[ikey].name,700,700)
416 
417  isFirst = True
418  ihnameIt = 0
419  for ihname in listname:
420  aweight = 1
421  if listweight[ihnameIt]:
422  #if thedata[jkey].weight != None and theaddition[ikey].Weight == "true":
423  aweight = float(listweight[ihnameIt])
424  #aweight = float(thedata[jkey].weight)
425  for jkey in thedata:
426  tmpkeys = thedata[jkey].histos.keys()
427  for tmpname in tmpkeys:
428  if tmpname == ihname:
429  ath = thedata[jkey].TH1s[tmpname]
430  if ath is None:
431  print "ERROR: histogram name \""+tmpname+"\" does not exist in file "+thedata[jkey].filename
432  exit(0)
433  if verbose : print "=== add histogram: "+ath.GetName() + " from " + thedata[jkey].filename + " mean = " + "%.2f" % round(ath.GetMean(),2) + " weight= " + str(aweight)
434  #ath.Print("all")
435  if isFirst:
436  newth = ath.Clone(theaddition[ikey].name)
437  newth.Sumw2()
438  if theaddition[ikey].Normalize == "true":
439  newth.Scale(1/newth.Integral())
440  newth.Scale(aweight)
441  isFirst = False
442  else:
443  atmpth = ath.Clone()
444  atmpth.Sumw2()
445  if theaddition[ikey].Normalize == "true":
446  atmpth.Scale(1/atmpth.Integral())
447  atmpth.Scale(aweight)
448  newth.Add( atmpth )
449  ihnameIt = ihnameIt + 1
450 
451  if theaddition[ikey].XTitle != None:
452  newth.SetXTitle(theaddition[ikey].XTitle)
453  if theaddition[ikey].YTitle != None:
454  newth.SetYTitle(theaddition[ikey].YTitle)
455 
456  if theaddition[ikey].Option:
457  newth.Draw(theaddition[ikey].Option)
458  else:
459  newth.Draw()
460 
461  if theaddition[ikey].SetGrid == "true":
462  cv[theaddition[ikey].name].SetGrid()
463 
464  cv[theaddition[ikey].name].Update()
465 
466  # add new histogram to the list
467  newth.SetName(theaddition[ikey].name)
468  newTH1list.append(newth.GetName())
469  thedata[newth.GetName()] = ValElement()
470  thedata[newth.GetName()].TH1s[newth.GetName()] = newth
471  thedata[newth.GetName()].histos[newth.GetName()] = newth.GetName()
472 
473  # write new histograms to file
474  outputroot.cd()
475  newth.Write()
476 
477 
478  if verbose : print "= Create ratio histograms:"
479 
480  thedivition = dh.divide
481  for ikey in thedivition:
482  if verbose : print "== plot name: \""+thedivition[ikey].name+"\" title: \""+"\""
483  numerator = thedivition[ikey].numerator
484  denominator = thedivition[ikey].denominator
485 
486  #create canvas
487  cv[thedivition[ikey].name] = TCanvas(thedivition[ikey].name,thedivition[ikey].name,700,700)
488 
489  for jkey in thedata:
490  tmpkeys = thedata[jkey].histos.keys()
491  for tmpname in tmpkeys:
492  if tmpname == numerator:
493  numeratorth = thedata[jkey].TH1s[tmpname]
494  if numeratorth is None:
495  print "ERROR: histogram name \""+tmpname+"\" does not exist in file "+thedata[jkey].filename
496  exit(0)
497  #print "=== numerator histogram: "+numeratorth.GetName() + " from " + thedata[jkey].filename + " mean = " + "%.2f" % round(numeratorth.GetMean(),2) + " weight= " + str(aweight)
498 
499  if tmpname == denominator:
500  denominatorth = thedata[jkey].TH1s[tmpname]
501  if denominatorth is None:
502  print "ERROR: histogram name \""+tmpname+"\" does not exist in file "+thedata[jkey].filename
503  exit(0)
504  #print "=== denominator histogram: "+denominatorth.GetName() + " from " + thedata[jkey].filename + " mean = " + "%.2f" % round(denominatorth.GetMean(),2) + " weight= " + str(aweight)
505 
506 
507 
508  numeratorth.Sumw2()
509  denominatorth.Sumw2()
510  newth = numeratorth.Clone()
511  newth.Clear()
512  if thedivition[ikey].DivideOption is None:
513  newth.Divide(numeratorth,denominatorth)
514  else:
515  newth.Divide(numeratorth,denominatorth,1.,1.,thedivition[ikey].DivideOption)
516 # if theaddition[ikey].XTitle != None:
517 # newth.SetXTitle(theaddition[ikey].XTitle)
518 # if theaddition[ikey].YTitle != None:
519 # newth.SetYTitle(theaddition[ikey].YTitle)
520 
521  if thedivition[ikey].Option:
522  newth.Draw(thedivition[ikey].Option)
523  else:
524  newth.Draw()
525 
526  cv[thedivition[ikey].name].Update()
527 
528 
529  # pause
530  if option.wait:
531  raw_input( 'Press ENTER to continue\n ' )
532 
533  # add new histogram to the list
534  newth.SetName(thedivition[ikey].name)
535  newTH1list.append(newth.GetName())
536  thedata[newth.GetName()] = ValElement()
537  thedata[newth.GetName()].TH1s[newth.GetName()] = newth
538  thedata[newth.GetName()].histos[newth.GetName()] = newth.GetName()
539 
540  # write new histograms to file
541  outputroot.cd()
542  newth.Write()
543 
544 
545  thesuper = dh.superimpose
546  if verbose : print "= Create superimpose histograms:"
547  for ikey in thesuper:
548  if verbose : print "== plot name: \""+thesuper[ikey].name+"\" title: \""+thesuper[ikey].title+"\""
549  listname = thesuper[ikey].histos
550  listcolor = thesuper[ikey].color
551  listmarker = thesuper[ikey].marker
552  listlegend = thesuper[ikey].legend
553  #listweight = thesuper[ikey].weight
554  dolegend = False
555  for il in listlegend:
556  if il==None: dolegend = False
557  if verbose : print "dolegend = " +str(dolegend)
558  doNormalize = False
559  doRebin=thesuper[ikey].Rebin
560  if doRebin is not None :
561  doRebin=int(doRebin)
562  if verbose : print "Rebin is ", doRebin
563  if thesuper[ikey].Normalize == "true":
564  doNormalize = True
565  if verbose : print "normalize = " +str(doNormalize)
566  projectAxis = "no"
567  projectBin = -1 #all
568  if thesuper[ikey].projection == "x": projectAxis = "x"
569  if thesuper[ikey].projection == "y": projectAxis = "y"
570  if thesuper[ikey].bin != None: projectBin = thesuper[ikey].bin
571  profileAxis = "no"
572  if thesuper[ikey].profile == "x": profileAxis = "x"
573  if thesuper[ikey].profile == "y": profileAxis = "y"
574  doFill = False
575  if thesuper[ikey].Fill == "true": doFill = True
576  if verbose : print "fill option:"+ doFill
577  #create canvas
578  cv[thesuper[ikey].name] = TCanvas(thesuper[ikey].name,thesuper[ikey].title,700,700)
579  #legend
580  aleg = TLegend(0.6,0.4,0.8,0.6)
581  SetOwnership( aleg, 0 )
582  aleg.SetMargin(0.12)
583  aleg.SetTextSize(0.035)
584  aleg.SetFillColor(10)
585  aleg.SetBorderSize(0)
586 
587  isFirst = 1
588  ii = 0
589 
590  stacklist[thesuper[ikey].name] = THStack("astack"+thesuper[ikey].name,thesuper[ikey].title)
591  astack = stacklist[thesuper[ikey].name]
592  for ihname in listname:
593 
594  for jkey in thedata:
595  tmpkeys = thedata[jkey].histos.keys()
596 
597  for tmpname in tmpkeys:
598 
599  if tmpname == ihname:
600  ath = thedata[jkey].TH1s[tmpname]
601  if ath is None:
602  print "ERROR: histogram name \""+tmpname+"\" does not exist in file "+thedata[jkey].filename
603  exit(0)
604  if verbose : print "=== superimpose histogram: "+ath.GetName() + " mean = " + "%.2f" % round(ath.GetMean(),2)
605  # project 2D histogram if requested
606  if projectAxis == "x":
607  if projectBin == -1:
608  newthpx = ath.ProjectionX(ath.GetName()+"_px",0,-1,"e")
609  else:
610  newthpx = ath.ProjectionX(ath.GetName()+"_px",int(projectBin),int(projectBin),"e")
611  newth = newthpx.Clone()
612  if projectAxis == "y":
613  if projectBin == -1:
614  newthpy = ath.ProjectionY(ath.GetName()+"_py",0,-1,"e")
615  else:
616  newthpx = ath.ProjectionY(ath.GetName()+"_py",int(projectBin),int(projectBin),"e")
617  newth = newthpy.Clone()
618  if profileAxis == "x":
619  newthpx = ath.ProfileX(ath.GetName()+"_px",0,-1,"e")
620  newth = newthpx.Clone()
621  if profileAxis == "y":
622  newthpy = ath.ProfileY(ath.GetName()+"_py",0,-1,"e")
623  newth = newthpy.Clone()
624 
625  # get weight
626  aweight = 1
627  if thedata[jkey].weight != None and thesuper[ikey].Weight=="true":
628  aweight = float( thedata[jkey].weight )
629  if verbose: print " with weight = " + str(aweight)
630  #if listweight[ii]:
631  # aweight = float( listweight[ii] )
632 
633  # clone original histogram
634  if projectAxis == "no" and profileAxis == "no" :newth = ath.Clone()
635 
636  if doRebin is not None and doRebin>0 :
637  newth.Rebin(doRebin)
638 
639  newth.Sumw2()
640  newth.Scale(aweight)
641 
642  # check if we have color
643  if not listcolor[ii]:
644  listcolor[ii] = 1
645 
646  newth.SetLineColor(int(listcolor[ii]))
647  newth.SetMarkerColor(int(listcolor[ii]))
648 
649  if doFill: newth.SetFillColor(int(listcolor[ii]))
650 
651  if listmarker[ii] != None:
652  newth.SetMarkerStyle(int(listmarker[ii]))
653  # normalize
654  if doNormalize:
655  newth.Scale(1./newth.Integral())
656  #print " "+listlegend[ii]
657 
658  if thesuper[ikey].Labels != None:
659  thelabels = thesuper[ikey].Labels.split(',')
660  ib = 1
661  #print thelabels
662 
663  for ilabel in thelabels:
664  newth.GetXaxis().SetBinLabel(ib,ilabel)
665  #if ib==1:
666  #newth.GetXaxis().SetBinLabel(ib,"")
667  #newth.GetHistogram().GetXaxis().SetBinLabel(ib,ilabel)
668  ib += 1
669  #if aweight==0.0081:
670  # newth.SetBinContent(1, newth.GetBinContent(1) / 0.28756)
671  # if aweight==0.0883:
672  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.01953)
673  #if aweight==0.0731:
674  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.0367)
675  #if aweight==0.4003:
676  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.5683)
677  #if aweight==0.003:
678  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.21173)
679  #if aweight==0.0027:
680  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.26394)
681  #if aweight==0.0034:
682  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.26394)
683 
684 
685  # stack histograms
686  if doFill:
687  if thesuper[ikey].XTitle != None:
688  newth.SetXTitle("")
689  astack.Add(newth,"HIST")
690  elif thesuper[ikey].Option:
691  astack.Add(newth,thesuper[ikey].Option)
692  else:
693  #newth.Fit("landau")
694  astack.Add(newth)
695 
696  astack.SetTitle(thesuper[ikey].title)
697 
698  if isFirst==1:
699  newth.GetPainter().PaintStat(ROOT.gStyle.GetOptStat(),0);
700  isFirst=0
701  tmpsumth = newth.Clone()
702  else:
703  tmpsumth.Add(newth)
704  # newth.SetTitle(thesuper[ikey].title)
705  # if thesuper[ikey].YTitle != None:
706  # newth.SetYTitle(thesuper[ikey].YTitle)
707  # newth.Draw()
708  # isFirst=0
709  #else:
710  # newth.Draw("same")
711  if dolegend and doFill:
712  aleg.AddEntry(newth,listlegend[ii],"F")
713  elif dolegend:
714  aleg.AddEntry(newth,listlegend[ii],"P")
715 
716  newth.SetName(tmpname)
717  outputroot.cd()
718  newth.Write()
719  ii = ii + 1
720 
721 
722  if thesuper[ikey].Maximum != None:
723  astack.SetMaximum( float(thesuper[ikey].Maximum) )
724  if thesuper[ikey].Minimum != None:
725  astack.SetMinimum( float(thesuper[ikey].Minimum) )
726  if thesuper[ikey].Stack == "true":
727  astack.Draw()
728  if thesuper[ikey].Stack == "false" or thesuper[ikey].Stack == None:
729  astack.Draw()
730  astack.Draw("nostack")
731  if thesuper[ikey].XTitle != None:
732  astack.GetHistogram().SetXTitle(thesuper[ikey].XTitle)
733  if thesuper[ikey].YTitle != None:
734  astack.GetHistogram().SetYTitle(thesuper[ikey].YTitle)
735  if doFill:
736  astack.Draw("sameaxis")
737 
738 
739  #thelabels = []
740  #if thesuper[ikey].Labels != None:
741  # thelabels = thesuper[ikey].Labels.split(',')
742  # ib = 1
743  # print thelabels
744 
745  # for ilabel in thelabels:
746  # astack.GetXaxis().SetBinLabel(ib,ilabel)
747  #astack.GetHistogram().GetXaxis().SetBinLabel(ib,ilabel)
748  #ib += 1
749  # astack.Draw()
750  # astack.Draw("sameaxis")
751 
752  if dolegend:
753  aleg.Draw()
754  if thesuper[ikey].SetLogy == "true":
755  cv[thesuper[ikey].name].SetLogy()
756  if thesuper[ikey].SetGrid == "true":
757  cv[thesuper[ikey].name].SetGrid()
758 
759  # test smearing
760  #rn = ROOT.TRandom(12345)
761  #for iibin in range(0,tmpsumth.GetNbinsX()):
762  # tmpsumth.SetBinContent(iibin, rn.Poisson(tmpsumth.GetBinContent(iibin)) )
763  # if tmpsumth.GetBinContent(iibin) == 0:
764  # tmpsumth.SetBinError(iibin, 0 )
765  # else:
766  # tmpsumth.SetBinError(iibin, 1/math.sqrt(tmpsumth.GetBinContent(iibin)) )
767 
768  #tmpsumth.Draw("same E1")
769 
770 
771  if printBanner:
772  tex = TLatex(0.35,0.95,Banner)
773  tex.SetNDC()
774  tex.SetTextSize(0.05)
775  tex.Draw()
776 
777  cv[thesuper[ikey].name].Update()
778  #cv[thesuper[ikey].name].Print("test.png")
779 
780  # pause
781  if option.wait:
782  raw_input( 'Press ENTER to continue\n ' )
783 
784 
785 
786 #**********************************************************************
787 
788 
789  thegraph = dh.graph
790  if verbose : print "= Create graph histograms:"
791  for ikey in thegraph:
792  if verbose : print "== plot name: \""+thegraph[ikey].name+"\" title: \""+thegraph[ikey].title+"\""
793  listname = thegraph[ikey].histos
794  listcolor = thegraph[ikey].color
795  listmarker = thegraph[ikey].marker
796  listlegend = thegraph[ikey].legend
797  listflavour = thegraph[ikey].flavour
798  #listweight = thegraph[ikey].weight
799  dolegend = False
800  for il in listlegend:
801  if il==None: dolegend = False
802  if verbose : print "dolegend = " +str(dolegend)
803  doNormalize = False
804  if thegraph[ikey].Normalize == "true":
805  doNormalize = True
806  if verbose : print "normalize = " +str(doNormalize)
807  projectAxis = "no"
808  projectBin = -1 #all
809  if thegraph[ikey].projection == "x": projectAxis = "x"
810  if thegraph[ikey].projection == "y": projectAxis = "y"
811  if thegraph[ikey].bin != None: projectBin = thegraph[ikey].bin
812  profileAxis = "no"
813  if thegraph[ikey].profile == "x": profileAxis = "x"
814  if thegraph[ikey].profile == "y": profileAxis = "y"
815  doFill = False
816  if thegraph[ikey].Fill == "true": doFill = True
817  if verbose : print "fill option:"+ doFill
818  #create canvas
819  cv[thegraph[ikey].name] = TCanvas(thegraph[ikey].name,thegraph[ikey].title,700,700)
820  #legend
821  aleg = TLegend(0.6,0.4,0.8,0.6)
822  SetOwnership( aleg, 0 )
823  aleg.SetMargin(0.12)
824  aleg.SetTextSize(0.035)
825  aleg.SetFillColor(10)
826  aleg.SetBorderSize(0)
827 
828  isFirst = 1
829  ii = 0
830 
831  stacklist[thegraph[ikey].name] = THStack("astack"+thegraph[ikey].name,thegraph[ikey].title)
832  astack = stacklist[thegraph[ikey].name]
833  xVal_val = TVectorD()
834  yVal_val = TVectorD()
835  yBin_val = std.vector(int)()
836  xErr_val = TVectorD()
837  yErr_val = TVectorD()
838  zVal_val = TVectorD()
839  zErr_val = TVectorD()
840  nVal_val = 0
841 
842  xVal_ref = TVectorD()
843  yVal_ref = TVectorD()
844  yBin_ref = std.vector(int)()
845  xErr_ref = TVectorD()
846  yErr_ref = TVectorD()
847  zVal_ref = TVectorD()
848  zErr_ref = TVectorD()
849  nVal_ref = 0
850 
851  RangeMax = 0.005
852  RangeMin = 0.9
853 
854  for ihname in listname:
855 
856  for jkey in thedata:
857  tmpkeys = thedata[jkey].histos.keys()
858 
859  for tmpname in tmpkeys:
860 
861  if tmpname == ihname:
862 
863  ath = thedata[jkey].TH1s[tmpname]
864  if ath is None:
865  print "ERROR: histogram name \""+tmpname+"\" does not exist in file "+thedata[jkey].filename
866  exit(0)
867  if verbose : print "=== graph histogram: "+ath.GetName() + " mean = " + "%.2f" % round(ath.GetMean(),2)
868  #print listflavour[ii]
869  if listflavour[ii] == "5":
870  #print "iiiiiiiiiii"
871  nBinB = 200 #ath.GetNbinsX()
872  BinWidth = (0.01+ath.GetMaximum())/nBinB
873  BMid = 0.005+BinWidth/2
874  Err = BinWidth
875  for iBinB in range(1,nBinB+1):
876  #BinWidth = (0.01+ath.GetMaximum())/200 #ath.GetBinWidth(iBinB)
877  BMid = BMid+Err #BinWidth #ath.GetBinCenter(iBinB)
878  #newh = TH1(ath)
879  nAthBin = ath.GetNbinsX()-2
880  #newh = TH1(ath)
881  maxInHisto = ath.GetMaximum()
882  minInHisto = ath.GetMinimum()
883  #print minInHisto
884  yClosestInit = 0
885  iBinClosestInit = 0
886  if BMid <= maxInHisto : yClosestInit = maxInHisto + 1
887  else : yClosestInit = minInHisto - 1.0
888  iBinClosest = iBinClosestInit
889  yClosest = yClosestInit
890  for iAthBin in range(1,nAthBin+1):
891  yBin = ath.GetBinContent(iAthBin)
892  dif1 = BMid-yBin
893  if dif1 < 0 : dif1 = yBin-BMid
894  dif2 = yClosest-BMid
895  if dif2 < 0 : dif2 = BMid-yClosest
896  if dif1 < dif2:
897  yClosest = yBin
898  iBinClosest = iAthBin
899  min = BMid-Err/2
900  max = BMid+Err/2
901  #print iBinClosest
902  if yClosest < min or yClosest > max:
903  iBinClosest = 0
904  #print "iji"
905  if iBinClosest > 0 and listmarker[ii] == "8":
906  #print "hhhhhhhhhhhhhhhh"
907  nVal_ref = nVal_ref+1
908  xVal_ref.ResizeTo(nVal_ref)
909  #yBin_ref.ResizeTo(nVal_ref)
910  xErr_ref.ResizeTo(nVal_ref)
911  xVal_ref[nVal_ref-1] = BMid
912  yBin_ref.push_back(iBinClosest)
913  xErr_ref[nVal_ref-1] = ath.GetBinError ( iBinClosest )
914  Err = xErr_ref[nVal_ref-1]
915  if Err < BinWidth : Err = BinWidth
916  elif iBinClosest > 0:
917  nVal_val = nVal_val+1
918  xVal_val.ResizeTo(nVal_val)
919  #yBin_val.ResizeTo(nVal_val)
920  xErr_val.ResizeTo(nVal_val)
921  xVal_val[nVal_val-1] = BMid
922  yBin_val.push_back(iBinClosest)
923  xErr_val[nVal_val-1] = ath.GetBinError ( iBinClosest )
924  Err = xErr_val[nVal_val-1]
925  if Err < BinWidth : Err = BinWidth
926  elif listflavour[ii] == "4" and listmarker[ii] == "8":
927  yVal_ref.ResizeTo(nVal_ref)
928  yErr_ref.ResizeTo(nVal_ref)
929  for iVal in range(0,nVal_ref):
930  yVal_ref[iVal] = ath.GetBinContent (yBin_ref[iVal])
931  if yVal_ref[iVal] > RangeMax : RangeMax = yVal_ref[iVal]
932  yErr_ref[iVal] = ath.GetBinError (yBin_ref[iVal])
933  elif listflavour[ii] == "4":
934  yVal_val.ResizeTo(nVal_val)
935  yErr_val.ResizeTo(nVal_val)
936  for iVal in range(0,nVal_val):
937  yVal_val[iVal] = ath.GetBinContent (yBin_val[iVal])
938  yErr_val[iVal] = ath.GetBinError (yBin_val[iVal])
939  elif listmarker[ii] == "8":
940  zVal_ref.ResizeTo(nVal_ref)
941  zErr_ref.ResizeTo(nVal_ref)
942  for iVal in range(0,nVal_ref):
943  zVal_ref[iVal] = ath.GetBinContent (yBin_ref[iVal])
944  zErr_ref[iVal] = ath.GetBinError (yBin_ref[iVal])
945  if zVal_ref[iVal] < RangeMin : RangeMin = zVal_ref[iVal]
946  else:
947  zVal_val.ResizeTo(nVal_val)
948  zErr_val.ResizeTo(nVal_val)
949  for iVal in range(0,nVal_val):
950  zVal_val[iVal] = ath.GetBinContent (yBin_val[iVal])
951  zErr_val[iVal] = ath.GetBinError (yBin_val[iVal])
952  ii = ii + 1
953 
954  #print xVal_ref.GetNoElements()
955  #print yVal_ref.GetNrows()
956  #print xErr_ref.GetNrows()
957  #print yErr_ref.GetNrows()
958 
959  #graphs = std.vector(TGraphErrors)()
960  graphs = [TGraphErrors(xVal_ref,yVal_ref,xErr_ref,yErr_ref),
961  TGraphErrors(xVal_ref,zVal_ref,xErr_ref,zErr_ref),
962  TGraphErrors(xVal_val,yVal_val,xErr_val,yErr_val),
963  TGraphErrors(xVal_val,zVal_val,xErr_val,zErr_val)]
964  ii = 0
965 
966 
967 
968  for ii in range(0,4):
969 
970  # project 2D histogram if requested
971  #if projectAxis == "x":
972  # if projectBin == -1:
973  # newthpx = ath.ProjectionX(ath.GetName()+"_px",0,-1,"e")
974  # else:
975  # newthpx = ath.ProjectionX(ath.GetName()+"_px",int(projectBin),int(projectBin),"e")
976  # newth = newthpx.Clone()
977  #if projectAxis == "y":
978  # if projectBin == -1:
979  # newthpy = ath.ProjectionY(ath.GetName()+"_py",0,-1,"e")
980  # else:
981  # newthpx = ath.ProjectionY(ath.GetName()+"_py",int(projectBin),int(projectBin),"e")
982  # newth = newthpy.Clone()
983  #if profileAxis == "x":
984  # newthpx = ath.ProfileX(ath.GetName()+"_px",0,-1,"e")
985  # newth = newthpx.Clone()
986  #if profileAxis == "y":
987  # newthpy = ath.ProfileY(ath.GetName()+"_py",0,-1,"e")
988  # newth = newthpy.Clone()
989 
990  # get weight
991  aweight = 1
992  #if thedata[jkey].weight != None and thegraph[ikey].Weight=="true":
993  # aweight = float( thedata[jkey].weight )
994  #if verbose: print " with weight = " + str(aweight)
995  #if listweight[ii]:
996  # aweight = float( listweight[ii] )
997 
998  # clone original histogram
999  #if projectAxis == "no" and profileAxis == "no" :newth = ath.Clone()
1000 
1001  #newth.Sumw2()
1002  #newth.Scale(aweight)
1003 
1004  # check if we have color
1005  #if not listcolor[ii]:
1006  # listcolor[ii] = 1
1007 
1008  col = 2
1009  mark = 22
1010  if ii == 0 or ii == 2:
1011  col = 1
1012  if ii == 0 or ii == 1:
1013  mark = 8
1014 
1015  graphs[ii].SetLineColor(col)
1016  graphs[ii].SetMarkerStyle(mark)
1017  graphs[ii].SetMarkerColor(col)
1018  graphs[ii].SetTitle(thegraph[ikey].title)
1019  #if doFill: newth.SetFillColor(int(listcolor[ii]))
1020 
1021  #if listmarker[ii] != None:
1022  # newth.SetMarkerStyle(int(listmarker[ii]))
1023  # normalize
1024  #if doNormalize:
1025  # newth.Scale(1./newth.Integral())
1026  #print " "+listlegend[ii]
1027 
1028  #if thegraph[ikey].Labels != None:
1029  # thelabels = thesuper[ikey].Labels.split(',')
1030  # ib = 1
1031  #print thelabels
1032 
1033  # for ilabel in thelabels:
1034  # newth.GetXaxis().SetBinLabel(ib,ilabel)
1035  #if ib==1:
1036  #newth.GetXaxis().SetBinLabel(ib,"")
1037  #newth.GetHistogram().GetXaxis().SetBinLabel(ib,ilabel)
1038  # ib += 1
1039  #if aweight==0.0081:
1040  # newth.SetBinContent(1, newth.GetBinContent(1) / 0.28756)
1041  # if aweight==0.0883:
1042  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.01953)
1043  #if aweight==0.0731:
1044  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.0367)
1045  #if aweight==0.4003:
1046  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.5683)
1047  #if aweight==0.003:
1048  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.21173)
1049  #if aweight==0.0027:
1050  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.26394)
1051  #if aweight==0.0034:
1052  #newth.SetBinContent(1, newth.GetBinContent(1) / 0.26394)
1053 
1054 
1055  # stack histograms
1056  #if doFill:
1057  # if thegraph[ikey].XTitle != None:
1058  # newth.SetXTitle("")
1059  # astack.Add(newth,"HIST")
1060  #elif thegraph[ikey].Option:
1061  # astack.Add(newth,thegraph[ikey].Option)
1062  #else:
1063  #newth.Fit("landau")
1064  # astack.Add(newth)
1065 
1066  #astack.SetTitle(thegraph[ikey].title)
1067 
1068  if isFirst==1:
1069  #graphs[ii].GetPainter().PaintStat(ROOT.gStyle.GetOptStat(),0);
1070  isFirst=0
1071  #tmpsumth = graphs[ii].Clone()
1072  #else:
1073  # tmpsumth.Add(graphs[ii])
1074  # newth.SetTitle(thesuper[ikey].title)
1075  # if thesuper[ikey].YTitle != None:
1076  # newth.SetYTitle(thesuper[ikey].YTitle)
1077  # newth.Draw()
1078  # isFirst=0
1079  #else:
1080  # newth.Draw("same")
1081  #if dolegend and doFill:
1082  # aleg.AddEntry(newth,listlegend[ii],"F")
1083  #elif dolegend:
1084  # aleg.AddEntry(newth,listlegend[ii],"P")
1085 
1086  #graphs[ii].SetName(tmpname)
1087  #if ii == 0 : graphs[ii].Draw()
1088  #else : graphs[ii].Draw("same")
1089  outputroot.cd()
1090  graphs[ii].Write()
1091  ii = ii + 1
1092 
1093 
1094  #if thegraph[ikey].Maximum != None:
1095  # graphs[0].SetMaximum( float(thegraph[ikey].Maximum) )
1096  #if thegraph[ikey].Minimum != None:
1097  # graphs[0].SetMinimum( float(thegraph[ikey].Minimum) )
1098  #if thegraph[ikey].Stack == "true":
1099  # astack.Draw()
1100  #if thegraph[ikey].Stack == "false" or thegraph[ikey].Stack == None:
1101  # astack.Draw()
1102  # astack.Draw("nostack")
1103  if thegraph[ikey].XTitle != None:
1104  graphs[0].GetHistogram().SetXTitle(thegraph[ikey].XTitle)
1105  if thegraph[ikey].YTitle != None:
1106  graphs[0].GetHistogram().SetYTitle(thegraph[ikey].YTitle)
1107  #if doFill:
1108  # astack.Draw("sameaxis")
1109  if RangeMax > 0.5 : RangeMax = 1.5
1110  if RangeMax < 0.5 : RangeMax = RangeMax + 0.05
1111  #RangeMax = 1.1
1112  RangeMin = RangeMin - 0.5*RangeMin
1113  #print RangeMax
1114  #print RangeMin
1115  if RangeMin < 0.00001 : RangeMin = 0.00005
1116  graphs[0].GetYaxis().SetRangeUser(RangeMin,RangeMax)
1117 
1118  #thelabels = []
1119  #if thesuper[ikey].Labels != None:
1120  # thelabels = thesuper[ikey].Labels.split(',')
1121  # ib = 1
1122  # print thelabels
1123 
1124  # for ilabel in thelabels:
1125  # astack.GetXaxis().SetBinLabel(ib,ilabel)
1126  #astack.GetHistogram().GetXaxis().SetBinLabel(ib,ilabel)
1127  #ib += 1
1128  # astack.Draw()
1129  # astack.Draw("sameaxis")
1130 
1131  #h = TH1F()
1132  #h.Draw()
1133  graphs[0].Draw("AP")
1134  graphs[1].Draw("sameP")
1135  graphs[2].Draw("sameP")
1136  graphs[3].Draw("sameP")
1137  if dolegend:
1138  aleg.Draw()
1139  if thegraph[ikey].SetLogy == "true":
1140  cv[thegraph[ikey].name].SetLogy()
1141  if thegraph[ikey].SetGrid == "true":
1142  cv[thegraph[ikey].name].SetGrid()
1143 
1144  # test smearing
1145  #rn = ROOT.TRandom(12345)
1146  #for iibin in range(0,tmpsumth.GetNbinsX()):
1147  # tmpsumth.SetBinContent(iibin, rn.Poisson(tmpsumth.GetBinContent(iibin)) )
1148  # if tmpsumth.GetBinContent(iibin) == 0:
1149  # tmpsumth.SetBinError(iibin, 0 )
1150  # else:
1151  # tmpsumth.SetBinError(iibin, 1/math.sqrt(tmpsumth.GetBinContent(iibin)) )
1152 
1153  #tmpsumth.Draw("same E1")
1154 
1155 
1156  if printBanner:
1157  tex = TLatex(0.35,0.95,Banner)
1158  tex.SetNDC()
1159  tex.SetTextSize(0.05)
1160  tex.Draw()
1161 
1162  cv[thegraph[ikey].name].Update()
1163  save = thegraph[ikey].name
1164  cv[thegraph[ikey].name].Print(save + ".gif")#Print("test.png")
1165 
1166  # pause
1167  if option.wait:
1168  raw_input( 'Press ENTER to continue\n ' )
1169 
1170 
1171 #*********************************************************************
1172 
1173 
1174  if printCanvas:
1175 
1176  for ikey in theaddition:
1177  cv[theaddition[ikey].name].Print(theaddition[ikey].name + "." + printFormat)
1178  for ikey in thesuper:
1179  cv[thesuper[ikey].name].Print(thesuper[ikey].name + "." + printFormat)
1180  for ikey in thegraph:
1181  cv[thegraph[ikey].name].Print(thegraph[ikey].name + "notgood." + printFormat)
1182 
1183 
1184  #outputroot.Write()
1185  #outputroot.Close()
1186 
1187 # if not option.wait:
1188  rep = ''
1189  while not rep in [ 'q', 'Q', '.q', 'qq' 'p']:
1190  rep = raw_input( '\nenter: ["q",".q" to quit] ["p" or "print" to print all canvas]: ' )
1191  if 0<len(rep):
1192  if rep=='quit': rep = 'q'
1193  if rep=='p' or rep=='print':
1194  for ikey in theaddition:
1195  cv[theaddition[ikey].name].Print(theaddition[ikey].name + "." + printFormat)
1196  for ikey in thesuper:
1197  cv[thesuper[ikey].name].Print(thesuper[ikey].name + "." + printFormat)
1198  for ikey in thegraph:
1199  cv[thegraph[ikey].name].Print(thegraph[ikey].name + "." + printFormat)
1200 
1201 
def __init__
Definition: cuy.py:175
def __init__
Definition: cuy.py:127
def __init__
Definition: cuy.py:161
def startElement
Definition: cuy.py:188
def exit
Definition: cuy.py:90
def parse
Definition: cuy.py:93
def __init__
Definition: cuy.py:118
def __init__
Definition: cuy.py:133
def nonzero
Definition: cuy.py:78