def makeROCPlot(rocs, set_name, ymin=0., ymax=1., xmin=0., xmax=1., logy=False): print "makeROCPlot" allrocs = ROOT.TMultiGraph(set_name, '') point_graphs = [] ratio_graphs = [] i_marker = 0 c = ROOT.TCanvas() pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetBottomMargin(0.03) # Upper and lower plot are joined pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad pad1.SetLogy(0) # pad1.SetLogx() if ymin > 0. and logy: pad1.SetLogy() for i_col, graph in enumerate(rocs): col = colours[i_col] graph.SetLineColor(col) graph.SetMarkerColor(col) graph.SetLineWidth(3) graph.SetMarkerStyle(9) graph.SetMarkerSize(0) if i_col == 0: refg = graph.Clone() else: n_points = refg.GetN( ) if refg.GetN() > graph.GetN() else graph.GetN() # rp = ROOT.TGraphAsymmErrors(n_points) rp = graph.Clone() rp.Set(n_points) # n_points = n_points - 1 for i_points in range(n_points): x_refg = refg.GetPointX(i_points) print refg.GetPointX(i_points), refg.GetPointY( i_points), "|", graph.GetPointX(i_points), graph.Eval( x_refg) if refg.GetPointY(i_points) != 0.0: rp.SetPoint(i_points, x_refg, graph.Eval(x_refg) / refg.GetPointY(i_points)) else: rp.SetPoint(i_points, x_refg, 0.0) ratio_graphs.append(rp) if graph.GetN() > 10: allrocs.Add(graph) else: graph.SetMarkerStyle(markers[i_marker]) i_marker += 1 graph.SetMarkerSize(1) point_graphs.append(graph) # allrocs.Draw('APL') # allrocs.Draw('AL') allrocs.GetXaxis().SetTitle('#epsilon_{s}') allrocs.GetYaxis().SetTitle('#epsilon_{b}') allrocs.GetYaxis().SetDecimals(True) allrocs.GetXaxis().SetLabelSize(0.0) allrocs.GetYaxis().SetTitleSize(0.06) allrocs.GetYaxis().SetLabelSize(0.06) allrocs.GetYaxis().SetRangeUser(ymin, ymax) allrocs.GetXaxis().SetRangeUser(xmin, xmax) allrocs.Draw('APL') # allrocs.Draw('AL') for graph in point_graphs: graph.Draw('Psame') allrocs.leg = makeLegend(zip([r.title for r in rocs], rocs)) c.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.27) pad2.SetTopMargin(0.03) pad2.SetBottomMargin(0.35) # pad2.SetLogx() pad2.Draw() pad2.cd() # axis_graph = rocs[0].Clone() # axis_graph.Set(2) # axis_graph = ROOT.TGraph(2) # axis_graph.SetPoint(0, allrocs.GetXaxis().GetXmin(), 1.0); axis_graph.SetPoint(1, 0.999, 1.0); # axis_graph.SetTitle("") # axis_graph.SetMarkerSize(0) # axis_graph.SetLineWidth(0) # # axis_graph.GetYaxis().SetRangeUser(0.75,1.25) # axis_graph.SetMinimum(0.75) # axis_graph.SetMaximum(1.25) # axis_graph.GetXaxis().SetRangeUser(allrocs.GetXaxis().GetXmin(), allrocs.GetXaxis().GetXmax()) # pad2.Update() # pad2.RedrawAxis() # axis_graph.Draw("APL") # line = TLine(allrocs.GetXaxis().GetXmin(),1.,allrocs.GetXaxis().GetXmin(),1.) # line.SetLineColor(1) # line.Draw() # print pad2.GetUxmin(),pad2.GetUxmax() for ii, ratio in enumerate(ratio_graphs): ratio.SetTitle("") print allrocs.GetXaxis().GetXmin(), allrocs.GetXaxis().GetXmax() ratio.GetXaxis().SetRangeUser(allrocs.GetXaxis().GetXmin(), allrocs.GetXaxis().GetXmax()) # ratio.GetXaxis().SetRangeUser(xmin, allrocs.GetXaxis().GetXmax()) ratio.GetXaxis().SetTitle('#epsilon_{s}') ratio.GetXaxis().SetTitleOffset(0.83) ratio.GetXaxis().SetNdivisions(507) ratio.GetYaxis().SetTitle('ratio') ratio.GetYaxis().SetNdivisions(305) ratio.SetMinimum(0.75) ratio.SetMaximum(1.25) ratio.GetYaxis().SetTitleOffset(0.5) ratio.GetYaxis().SetTitleSize(0.16) ratio.GetYaxis().SetLabelSize(0.16) ratio.GetXaxis().SetTitleSize(0.16) ratio.GetXaxis().SetLabelSize(0.16) ratio.Draw('APL') # line.Draw("") # ratio.Draw('APLsame') pad2.Update() pad2.RedrawAxis() # c.cd() # c.Update() c.Print(set_name + '.png') return allrocs
def compareMassRes(trackType): fileCB = open( "BoosteddefaultLeadingCB/MassResolutionVsPt_%s_BE16.pkl" % trackType, "rb") fileDCB = open( "BoosteddefaultLeading/MassResolutionVsPt_%s_BE16.pkl" % trackType, "rb") fileCruijff = open( "BoosteddefaultLeadingCruijff/MassResolutionVsPt_%s_BE16.pkl" % trackType, "rb") resultsCB = pickle.load(fileCB) resultsDCB = pickle.load(fileDCB) resultsCruijff = pickle.load(fileCruijff) graphCB = getGraph(resultsCB, "CB", Data=True) graphDCB = getGraph(resultsDCB, "DCB", Data=True) graphCruijff = getGraph(resultsCruijff, "Cruijff", Data=True) ratioCB = getRatio(resultsCB, resultsDCB, "ratioCB", Data=True) ratioCruijff = getRatio(resultsCruijff, resultsDCB, "ratioCruijff", Data=True) canv = TCanvas("c1", "c1", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) #~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() #~ ratioPad.UseCurrentStyle() plotPad.Draw() #~ ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) xMax = 20 if trackType == "Inner": xMax = 10 if trackType == "Outer": xMax = 20 plotPad.DrawFrame(0, 0, 452, xMax, ";p_{T} [GeV]; #chi^{2}/N_{dof}") graphCB.Draw("samepe") graphDCB.Draw("samepe") graphCruijff.Draw("samepe") graphDCB.SetLineColor(kRed) graphDCB.SetMarkerColor(kRed) graphCruijff.SetLineColor(kBlue) graphCruijff.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graphCB, "Single-Sided CB", "l") leg.AddEntry(graphDCB, "Double-Sided CB", "l") leg.AddEntry(graphCruijff, "Cruijff", "l") leg.Draw() plotPad.RedrawAxis() #~ ratioPad.cd() #~ ratioBB.SetLineColor(kRed) #~ ratioPad.DrawFrame(0,0.5,6000,1.5,";;ratio") #~ ratioBB.Draw("samepe") canv.Print("chi2CompareVsPt_%s_BE16.pdf" % trackType)
def sobWeightedPlot(self, fileName, datasetName, channel, cat, log, mass, tanb, blind, sob=False): # print 'yuta', channel, cat c = TCanvas(fileName, '', 600, 600) c.cd() if log: c.SetLogy(1) f = self.openTFile('Plot_' + fileName + '.root') isEMSM = fileName.find('SM') != -1 and fileName.find('em') != -1 isETSM = fileName.find('SM') != -1 and fileName.find('et') != -1 samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes'] if isEMSM: samples.append('ggH_hww') if isETSM: samples.append('Zee') dataGraph = self.tfileGet(f, 'Graph_from_data_obs') histDict = {} for sample in samples: histDict[sample] = self.tfileGet(f, sample) # print 'check :', sample, histDict[sample].GetSumOfWeights() if not histDict[sample]: print 'Missing histogram', sample, 'in file', 'Plot_' + fileName + '.root' # original for plots xminInset = 60 # 0 xmaxInset = 179 # 340 (for full range) # all range # xminInset = 0 # 0 # xmaxInset = 350 # 340 (for full range) # xminInset = 40 # 0 # xmaxInset = 200 # 340 (for full range) # xminInset = 120 # 0 # xmaxInset = 251 # 340 (for full range) if tanb > 0: xminInset = mass - 100 xmaxInset = mass + 100 if sob: xminInset = 0.4 xmaxInset = 0.7 ztt = histDict['Ztt'] ggH = histDict['ggH'] data = histDict['data_obs'] # This is to fix a weird plotting bug if sob: new_data = TH1F('new_data', '', ggH.GetNbinsX(), 0., 0.7) for i in range(1, new_data.GetNbinsX() + 1): new_data.SetBinContent(i, data.GetBinContent(i)) # print data.GetBinContent(i) data = new_data ggH_hww = 0 zee = 0 signal = histDict['signal'] if isEMSM: ggH_hww = histDict['ggH_hww'] if isETSM: print 'retrieve Zee' zee = histDict['Zee'] tt = histDict['ttbar'] ewk = histDict['EWK'] fakes = histDict['Fakes'] ztt.GetYaxis().SetRangeUser(0., 1.3 * self.findMaxY(data, 0)) if log: ztt.GetYaxis().SetRangeUser(0.001, 50. * self.findMaxY(data, 0)) ztt.GetXaxis().SetTitle('#bf{m_{#tau#tau} [GeV]}') ztt.GetYaxis().SetTitle('#bf{S/B Weighted dN/dm_{#tau#tau} [1/GeV]}') if tanb > 0. and not log: ztt.GetXaxis().SetRangeUser(0., mass + 200.) if sob: ztt.GetXaxis().SetTitle('S/(S+B)') ztt.GetYaxis().SetTitle('Events') ztt.SetTitleOffset(1.3, 'Y') ztt.SetTitleOffset(1., 'X') ztt.GetYaxis().SetNdivisions(505) ztt.SetNdivisions(505) for b in range(0, signal.GetNbinsX() + 2): if signal.GetBinCenter( b) < xminInset or xmaxInset < signal.GetBinCenter(b): signal.SetBinContent(b, 0.) signal.SetBinError(b, 0.) signal.SetName('sig') signal.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal signal.SetFillColor(2) signal.SetLineColor(2) signal.SetLineStyle(1) signal.SetLineWidth(0) ggH.SetBinContent(0, 0) # remove red line on top of y axis in plot ggH.SetBinContent(ggH.GetNbinsX() + 1, 0) ggH.SetBinError(0, 0) ggH.SetBinError(ggH.GetNbinsX() + 1, 0) ggH.SetName('ggH') ggH.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal ggH.SetFillColor(2) ggH.SetLineColor(2) ggH.SetLineStyle(1) ggH.SetLineWidth(0) if isEMSM: errorBand = TH1F(ggH_hww) else: errorBand = TH1F(ztt) errorBand.SetName("errorBand") errorBand.SetMarkerSize(0) errorBand.SetFillColor(1) errorBand.SetFillStyle(3013) errorBand.SetLineWidth(1) legend = TLegend() mssmLabel = '' if tanb > 0: mssmLabel = "tan#beta={tanb}".format(tanb=tanb) higgsLabel = "H(125 GeV)#rightarrow#tau#tau" if tanb > 0: higgsLabel = "H(125 GeV)#rightarrow#tau#tau" legend.SetFillStyle(0) legend.SetFillColor(0) legend.SetBorderSize(0) legend.AddEntry(ggH, higgsLabel, "F") if tanb > 0: legend.AddEntry(TObject(0), mssmLabel, "") legend.AddEntry(data, "observed", "LP") if isEMSM: legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F") legend.AddEntry(ztt, "Z#rightarrow#tau#tau", "F") legend.AddEntry(tt, "t#bar{t}", "F") if isETSM: legend.AddEntry(zee, "Z#rightarrowee", "F") legend.AddEntry(ewk, "electroweak", "F") legend.AddEntry(fakes, "QCD", "F") legend.SetX1NDC(0.63) legend.SetX2NDC(1.05) legend.SetY1NDC(0.25) legend.SetY2NDC(0.46) if log: legend.SetX1NDC(0.18) legend.SetX2NDC(0.60) legend.SetY1NDC(0.17) legend.SetY2NDC(0.38) legend.SetTextSize(.028) legend.SetTextAlign(12) if isEMSM: dataDiff = self.diffPlot(data, ggH_hww, 1) dataDiffGraph = self.diffGraph(dataGraph, ggH_hww, 1) errBand = self.getErrorBand(ggH_hww) else: dataDiff = self.diffPlot(data, ztt, 1) dataDiffGraph = self.diffGraph(dataGraph, ztt, 1) errBand = self.getErrorBand(ztt) errBand.SetFillStyle( 3013 ) # 1001=solid , 3004,3005=diagonal, 3013=hatched official for H.tau tau errBand.SetFillColor(1) errBand.SetLineStyle(1) errBand.SetLineColor(1) errBand.SetLineWidth(1) errBandFrame = TH1F( 'errBandFrame', '', int((xmaxInset - xminInset) / dataDiff.GetBinWidth(1)), xminInset, xmaxInset) errBandFrame.GetYaxis().SetTitle("") errBandFrame.GetYaxis().SetRangeUser( -1.1 * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) # errBandFrame.GetYaxis().SetRangeUser(-1.*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),1.1*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) # good ! # errBandFrame.GetYaxis().SetRangeUser(-0.2*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),0.5*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) print 'Yuta', channel, cat if (channel == 'e#tau_{h}' and cat == 'vbf') or (channel == 'e#tau_{h}' and cat == ''): print 'enter' errBandFrame.GetYaxis().SetRangeUser( -2. * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) errBandFrame.GetYaxis().SetNdivisions(5) errBandFrame.GetYaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetTitle("#bf{m_{#tau#tau} [GeV]} ") errBandFrame.GetXaxis().SetTitleColor(kBlack) errBandFrame.GetXaxis().SetTitleSize(0.07) errBandFrame.GetXaxis().SetTitleOffset(0.85) errBandFrame.GetXaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetNdivisions(506) # errBandFrame.SetNdivisions(505) legendDiff = TLegend() legendDiff.SetFillStyle(0) legendDiff.SetFillColor(0) legendDiff.SetBorderSize(0) legendDiff.AddEntry(signal, higgsLabel, "F") if tanb > 0: legendDiff.AddEntry(TObject(0), mssmLabel, '') # That might not work in python # legendDiff.AddEntry(dataDiff,"Data - Background","LP") legendDiff.AddEntry(dataDiffGraph, "Data - Background", "LEP") legendDiff.AddEntry(errBand, "Bkg. Uncertainty", "F") legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.67) legendDiff.SetY2NDC(0.88) if dataDiff.GetBinContent(dataDiff.FindBin(mass)) < 0.: legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.24) legendDiff.SetY2NDC(0.45) legendDiff.SetTextSize(.045) legendDiff.SetTextAlign(12) padBack = TPad( "padBack", "padBack", 0.57, 0.58, 0.975, 0.956) # TPad must be created after TCanvas otherwise ROOT crashes padBack.SetFillColor(0) pad = TPad( "diff", "diff", 0.45, 0.5, 0.9765, 0.957) # TPad must be created after TCanvas otherwise ROOT crashes pad.cd() pad.SetFillColor(0) pad.SetFillStyle(0) errBandFrame.Draw() errBand.Draw("e2lsame") signal.Draw("histsame") line = TLine() line.DrawLine(xminInset, 0, xmaxInset, 0) # dataDiff.Draw("pe same") if blind == False: self.HideBin(dataDiffGraph) dataDiffGraph.SetMarkerSize(0.5) dataDiffGraph.Draw('pe same') for ibin in range(0, dataDiffGraph.GetN()): x = Double(0.) y = Double(0.) dataDiffGraph.GetPoint(ibin, x, y) print 'Yuta_bin=', ibin, 'x=', x, 'y=', y, dataDiffGraph.GetErrorYhigh( ibin), dataDiffGraph.GetErrorYlow(ibin) print 'Yuta_error=', ibin, errBand.GetXaxis().GetBinCenter( ibin + 1), errBand.GetBinError(ibin + 1) legendDiff.Draw() pad.RedrawAxis() c.cd() ztt.Draw("hist") ggH.Draw("hist same") if isEMSM: ggH_hww.Draw("hist same") ztt.Draw("hist same") errorBand.Draw("e2 same") tt.Draw("hist same") if isETSM: zee.Draw("hist same") ewk.Draw("hist same") fakes.Draw("hist same") # data.Draw("pe same") dataGraph.SetMarkerSize(1) dataGraph.Draw('PE same') if blind == False: self.HideBin(dataGraph) print '#####', data.Integral(), data.GetBinContent(1) legend.Draw() c.RedrawAxis() padBack.Draw() # clear the background axe pad.Draw() if log: c.SetLogy(1) self.CMSPrelim(c, datasetName, channel, cat) savepath = 'figure/Plot_' + fileName if cat == '': savepath = savepath + '.pdf' else: savepath = savepath + '_' + cat + '.pdf' # c.Print('figure/Plot_'+fileName+".eps") # c.Print('figure/Plot_'+fileName+".png") # c.Print('figure/Plot_'+fileName+".pdf") c.Print(savepath) c.Close()
def signalRegion(path, selection, plots, runRange, backgrounds, cmsExtra): for name in plots: plot = getPlot(name) plot.addRegion(selection) #~ plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut plot.cuts = plot.cuts.replace("weight*", "") print runRange.lumi #~ plot.cuts = plot.cuts+"*!((abs(motherPdgId1) == 15 || abs(motherPdgId1) == 24 || abs(motherPdgId1) == 23) && (abs(motherPdgId2) == 15 || abs(motherPdgId2) == 24 || abs(motherPdgId2) == 23))" #~ plot.cuts = plot.cuts+"*!(abs(motherPdgId1) == 15 || abs(motherPdgId1) == 24 || abs(motherPdgId1) == 23 || abs(motherPdgId2) == 15 || abs(motherPdgId2) == 24 || abs(motherPdgId2) == 23)" #~ plot.cuts = plot.cuts+"*!((abs(motherPdgId1) != 15 && abs(motherPdgId1) != 24 && abs(motherPdgId1) != 23) || (abs(motherPdgId2) != 15 && abs(motherPdgId2) != 24 && abs(motherPdgId2) != 23))" #~ plot.cuts = plot.cuts+"*((abs(pdgId1) != 11 && abs(pdgId1) != 13 && abs(pdgId1) != 15) || ( abs(pdgId2) != 11 && abs(pdgId2) != 13 && abs(pdgId2) != 15))" if not "Forward" in selection.name: corr = rSFOF.central.val corrErr = rSFOF.central.err if "Central" in selection.name: region = "central" else: region = "inclusive" else: corr = rSFOF.forward.val corrErr = rSFOF.forward.err region = "forward" #~ #~ eventCounts = totalNumberOfGeneratedEvents(path) #~ #~ for background in backgrounds: #~ process = Process(getattr(Backgrounds,background),eventCounts) #~ for subprocess in process.samples: #~ #~ print subprocess #~ treeEE, treeMM, treeEM = getTrees(path,plot,runRange, subprocess,region) #~ for ev in treeMM: #~ #~ print ev.motherPdgId1, ev.motherPdgId2 #~ print treeEE.GetEntries(), treeMM.GetEntries(), treeEM.GetEntries() histEE, histMM, histOF = getHistograms(path, plot, runRange, backgrounds, region) print histEE.Integral(), histMM.Integral(), histOF.Integral() print histEE.GetEntries(), histMM.GetEntries(), histOF.GetEntries() hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() logScale = plot.log if plot.variable == "met" or plot.variable == "type1Met" or plot.variable == "tcMet" or plot.variable == "caloMet" or plot.variable == "mht": logScale = True yMax = histEE.GetBinContent( histEE.GetMaximumBin()) + histMM.GetBinContent( histMM.GetMaximumBin()) if logScale: yMax = yMax * 1000 else: yMax = yMax * 1.5 #~ else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin, plot.yMin, plot.lastBin, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) histSF = histEE.Clone("histSF") histSF.Add(histMM.Clone()) histSF.SetMarkerStyle(20) histOF.SetLineColor(ROOT.kBlue) histEE.SetLineColor(ROOT.kRed) histMM.SetLineColor(ROOT.kGreen + 3) histEE.SetLineStyle(ROOT.kDashed) histMM.SetLineStyle(ROOT.kDashed) histSF.Draw("samep") histOF.Draw("samehist") histEE.Draw("samehist") histMM.Draw("samehist") latex = ROOT.TLatex() latex.SetTextSize(0.04) latex.SetNDC(True) legend = TLegend(0.5, 0.6, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(0) entryHist = TH1F() entryHist.SetFillColor(ROOT.kWhite) legend.AddEntry(entryHist, selection.latex, "h") legend.AddEntry(histSF, "SF", "p") legend.AddEntry(histEE, "EE", "l") legend.AddEntry(histMM, "MM", "l") legend.AddEntry(histOF, "OF", "l") legend.Draw("same") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.89, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.82 else: yLabelPos = 0.85 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() hCanvas.Print("fig/nonPromptMC_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName))
def comparePtRes(trackType): file2016B = open("default2016Pt/PtResolutionVsPt_%s_B.pkl" % trackType, 'rb') file2016O = open("default2016Pt/PtResolutionVsPt_%s_O.pkl" % trackType, 'rb') file2016E = open("default2016Pt/PtResolutionVsPt_%s_E.pkl" % trackType, 'rb') file2017B = open("defaultPtSplit/PtResolutionVsPt_%s_B.pkl" % trackType, 'rb') file2017O = open("defaultPtSplit/PtResolutionVsPt_%s_O.pkl" % trackType, 'rb') file2017E = open("defaultPtSplit/PtResolutionVsPt_%s_E.pkl" % trackType, 'rb') file2018B = open("default2018Pt/PtResolutionVsPt_%s_B.pkl" % trackType, 'rb') file2018O = open("default2018Pt/PtResolutionVsPt_%s_O.pkl" % trackType, 'rb') file2018E = open("default2018Pt/PtResolutionVsPt_%s_E.pkl" % trackType, 'rb') results2016B = pickle.load(file2016B) results2016O = pickle.load(file2016O) results2016E = pickle.load(file2016E) results2017B = pickle.load(file2017B) results2017O = pickle.load(file2017O) results2017E = pickle.load(file2017E) results2018B = pickle.load(file2018B) results2018O = pickle.load(file2018O) results2018E = pickle.load(file2018E) graph2016B = getGraph(results2016B, "2016B") graph2016O = getGraph(results2016O, "2016O") graph2016E = getGraph(results2016E, "2016E") graph2017B = getGraph(results2017B, "2017B") graph2017O = getGraph(results2017O, "2017O") graph2017E = getGraph(results2017E, "2017E") graph2018B = getGraph(results2018B, "2018B") graph2018O = getGraph(results2018O, "2018O") graph2018E = getGraph(results2018E, "2018E") canv = TCanvas("c1", "c1", 800, 1200) plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1) # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() # ~ ratioPad.UseCurrentStyle() plotPad.Draw() # ~ ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) xMax = 0.15 if trackType == "Inner": xMax = 0.3 if trackType == "Outer": xMax = 0.5 plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]") graph2016B.Draw("samepe") # ~ graph2016O.Draw("samepe") graph2016E.Draw("samepe") graph2016B.SetLineColor(kRed) graph2016B.SetMarkerColor(kRed) graph2016O.SetLineColor(kGreen) graph2016O.SetMarkerColor(kGreen) graph2016E.SetLineColor(kBlue) graph2016E.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2016" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graph2016B, "Barrel", "l") # ~ leg.AddEntry(graph2016O,"Overlap","l") leg.AddEntry(graph2016E, "Endcap", "l") leg.Draw() plotPad.RedrawAxis() canv.Print("PtResolutionCompare_%s_2016.pdf" % trackType) canv.Print("PtResolutionCompare_%s_2016.root" % trackType) canv = TCanvas("c1", "c1", 800, 1200) plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1) # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() # ~ ratioPad.UseCurrentStyle() plotPad.Draw() # ~ ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) xMax = 0.15 if trackType == "Inner": xMax = 0.3 if trackType == "Outer": xMax = 0.5 plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]") graph2017B.Draw("samepe") # ~ graph2017O.Draw("samepe") graph2017E.Draw("samepe") graph2017B.SetLineColor(kRed) graph2017B.SetMarkerColor(kRed) graph2017O.SetLineColor(kGreen) graph2017O.SetMarkerColor(kGreen) graph2017E.SetLineColor(kBlue) graph2017E.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2017" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graph2017B, "Barrel", "l") # ~ leg.AddEntry(graph2017O,"Overlap","l") leg.AddEntry(graph2017E, "Endcap", "l") leg.Draw() plotPad.RedrawAxis() canv.Print("PtResolutionCompare_%s_2017.pdf" % trackType) canv.Print("PtResolutionCompare_%s_2017.root" % trackType) canv = TCanvas("c1", "c1", 800, 1200) plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1) # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() # ~ ratioPad.UseCurrentStyle() plotPad.Draw() # ~ ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) xMax = 0.15 if trackType == "Inner": xMax = 0.3 if trackType == "Outer": xMax = 0.5 plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]") graph2018B.Draw("samepe") # ~ graph2018O.Draw("samepe") graph2018E.Draw("samepe") graph2018B.SetLineColor(kRed) graph2018B.SetMarkerColor(kRed) graph2018O.SetLineColor(kGreen) graph2018O.SetMarkerColor(kGreen) graph2018E.SetLineColor(kBlue) graph2018E.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2018" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graph2018B, "Barrel", "l") # ~ leg.AddEntry(graph2018O,"Overlap","l") leg.AddEntry(graph2018E, "Endcap", "l") leg.Draw() plotPad.RedrawAxis() canv.Print("PtResolutionCompare_%s_2018.pdf" % trackType) canv.Print("PtResolutionCompare_%s_2018.root" % trackType)
def drawMassRes(data,mc,output,rapidity,ptda,ptmc,trackType,funct,mcIsData,dataIsMC,year): style = setTDRStyle() print (data) pt_e = [0 for x in range(len(data))] pt_x = [0 for x in range(len(data))] for i,pt in enumerate(pt_x): pt_x[i] = ptbins[i]+(ptbins[i+1]-ptbins[i])/2. pt_e[i] = (ptbins[i+1]-ptbins[i])/2. if dataIsMC: (da_mean,da_meane,da_sig,da_sige, da_nChi2) = doFit(data,output,rapidity,"MC2",trackType,funct) else: (da_mean,da_meane,da_sig,da_sige, da_nChi2) = doFit(data,output,rapidity,"DATA",trackType,funct) if mcIsData: (mc_mean,mc_meane,mc_sig,mc_sige, mc_nChi2) = doFit(mc ,output,rapidity,"DATA2",trackType,funct) else: (mc_mean,mc_meane,mc_sig,mc_sige, mc_nChi2) = doFit(mc ,output,rapidity,"MC",trackType,funct) result = {} result["data_mean"] = da_mean result["data_meane"] = da_meane result["data_sig"] = da_sig result["data_sige"] = da_sige result["mc_mean"] = mc_mean result["mc_meane"] = mc_meane result["mc_sig"] = mc_sig result["mc_sige"] = mc_sige result["ptda"] = ptda result["ptmc"] = ptmc result["da_nChi2"] = da_nChi2 result["mc_nChi2"] = mc_nChi2 pklFile = open(output+"/MassResolutionVsPt_%s_%s.pkl" %(trackType,rapidity),"wb") pickle.dump(result,pklFile) pklFile.close() c2 = TCanvas("c2","c2",800,800) c2.cd() # Upper plot will be in pad1 pad1 = TPad("pad1", "pad1", 0.01, 0.01, 0.99, 0.99) # ~ pad1.SetGrid() # Vertical grid pad1.SetTopMargin(0.05) pad1.SetLeftMargin(0.13) pad1.SetRightMargin(0.045) pad1.SetBottomMargin(0.3) pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad pad1.SetTicks() res_data = TGraphAsymmErrors() res_data.SetName("res_data") res_mc = TGraphAsymmErrors() res_mc .SetName("res_mc") ratio = TGraphErrors() ratio .SetName("ratio") #~ print len(pt_x) for i,pt in enumerate(pt_x): res_data.SetPoint(i,ptda[i],da_sig[i]) res_data.SetPointError(i,ptda[i]-ptbins[i],ptbins[i+1]-ptda[i],da_sige[i],da_sige[i]) res_mc .SetPoint(i,ptmc[i],mc_sig[i]) res_mc .SetPointError(i,ptmc[i]-ptbins[i],ptbins[i+1]-ptmc[i],mc_sige[i],mc_sige[i]) if mc_sig[i] > 0: ratio .SetPoint(i,pt,da_sig[i]/mc_sig[i]) ratio .SetPointError(i,pt_e[i],(da_sig[i]/mc_sig[i])*math.sqrt((da_sige[i]/da_sig[i])**2+(mc_sige[i]/mc_sig[i])**2)) res_data.SetMarkerStyle(22) res_data.SetMarkerSize(2) res_data.SetMarkerColor(kBlack) res_data.SetLineColor(kBlack) res_data.SetLineWidth(2) res_data.SetFillColor(0) res_data.SetTitle("Dimuon mass resolution vs pT for %s tracks"%trackType) res_data.GetYaxis().SetTitle("Mass resolution at Z peak (GeV)") # ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") res_data.GetYaxis().SetTitleFont(42) res_data.GetYaxis().SetTitleSize(0.05) res_data.GetYaxis().SetTitleOffset(1.35) res_data.GetYaxis().SetLabelFont(42) res_data.GetYaxis().SetLabelSize(0.038) res_data.GetYaxis().SetRangeUser(0.,6.) res_data.GetXaxis().SetTitleSize(0.0) res_data.GetXaxis().SetLabelSize(0.0) if trackType == "Outer": res_data.GetYaxis().SetRangeUser(1.,20.) res_data.GetXaxis().SetRangeUser(ptbins[0],ptbins[len(ptda)]) res_data.Draw("AP E0") res_mc.SetMarkerStyle(22) res_mc.SetMarkerSize(2) res_mc.SetMarkerColor(kRed) res_mc.SetLineColor(kRed) res_mc.SetLineWidth(2) res_mc.SetFillColor(0) res_mc.SetTitle("Dimuon mass resolution vs pT for %s tracks"%trackType) res_mc.GetYaxis().SetTitle("Mass resolution at Z peak (GeV)") res_mc.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) (GeV)") res_mc.GetYaxis().SetTitleOffset(1.5) res_mc.Draw("P E0 SAME") if rapidity == "BB": leg = TLegend(0.5,0.65,0.95,0.90,"Both muons |#eta| < 1.2","brNDC") elif rapidity == "BE": leg = TLegend(0.5,0.65,0.95,0.9,"At least one muon |#eta| > 1.2","brNDC") else: leg = TLegend(0.2,0.65,0.9,0.9,"At least one muon |#eta| > 1.6","brNDC") if mcIsData: leg.AddEntry(res_data,"DATA 2017") leg.AddEntry(res_mc,"DATA 2016") elif dataIsMC: leg.AddEntry(res_data,"MC 2017") leg.AddEntry(res_mc,"MC 2016") else: leg.AddEntry(res_data,"Data","p") leg.AddEntry(res_mc,"Simulation") leg.SetTextFont(62) leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(0) leg.SetMargin(0.15) leg.Draw("SAME") latex = TLatex() # ~ latex.SetTextFont(42) # ~ latex.SetTextAlign(31) # ~ latex.SetTextSize(0.04) # ~ latex.SetNDC(True) # ~ latexCMS = TLatex() # ~ latexCMS.SetTextFont(62) # ~ latexCMS.SetTextSize(0.04) # ~ latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03/0.7) latexCMSExtra.SetNDC(True) # ~ if '2016' in year: # ~ latex.DrawLatex(0.95, 0.96, "2016, 36.3 fb^{-1} (13 TeV)") # ~ elif '2017' in year: # ~ latex.DrawLatex(0.95, 0.96, "2017, 42.1 fb^{-1} (13 TeV)") # ~ else: # ~ latex.DrawLatex(0.95, 0.96, "2018, 61.3 fb^{-1} (13 TeV)") if '2016' in year: latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{ 2016, 36.3 fb^{-1} (13 TeV)}}") elif '2017' in year: latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{ 2017, 42.1 fb^{-1} (13 TeV)}}") else: latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{ 2018, 61.3 fb^{-1} (13 TeV)}}") # ~ cmsExtra = "Preliminary" # ~ latexCMS.DrawLatex(0.15,0.96,"CMS") latex.DrawLatexNDC(0.13, 0.96, "#font[62]{CMS}") # ~ yLabelPos = 0.84 # ~ latexCMSExtra.DrawLatex(0.78,yLabelPos,"%s"%(cmsExtra)) c2.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2",0.01, 0.01, 0.99, 0.29) pad2.SetTopMargin(0) pad2.SetTopMargin(0.05) pad2.SetLeftMargin(0.13) pad2.SetRightMargin(0.045) pad2.SetBottomMargin(0.4) # ~ pad2.SetGrid() pad2.Draw() pad2.cd() pad2.SetTicks() ratio.SetMarkerColor(kBlue-4) ratio.SetFillColor(kBlue-4 ) ratio.SetTitle("") ratio.GetYaxis().SetTitle("Data/MC") ratio.GetXaxis().SetNoExponent(0) ratio.GetXaxis().SetTitleFont(42) ratio.GetXaxis().SetTitleOffset(0.85) ratio.GetXaxis().SetTitleSize(0.2) ratio.GetXaxis().SetLabelColor(1) ratio.GetXaxis().SetLabelOffset(0.01) ratio.GetXaxis().SetLabelFont(42) ratio.GetXaxis().SetLabelSize(0.17) if mcIsData: ratio.GetYaxis().SetTitle("Data 2017 / Data 2016") elif dataIsMC: ratio.GetYaxis().SetTitle("MC 2017 / MC 2016") ratio.GetXaxis().SetTitle("p_{T} (\mu^{\pm}) (GeV)") ratio.GetYaxis().SetRangeUser(0.5,1.5) ratio.GetXaxis().SetRangeUser(ptbins[0],ptbins[len(ptda)]) ratio.GetYaxis().SetTitleOffset(0.55) ratio.GetYaxis().SetTitleSize(0.12) ratio.GetYaxis().SetTitleFont(42) ratio.GetYaxis().SetLabelSize(0.14) ratio.GetYaxis().SetLabelOffset(0.007) ratio.GetYaxis().SetLabelFont(42) ratio.GetYaxis().SetNdivisions(505) ratio.Draw("A P E2") pad2.Update() line = TLine(ptbins[0],1,ptbins[len(ptda)],1) line.SetLineColor(kBlue+1) line.SetLineWidth(2) line.Draw() pad1.RedrawAxis() saveas = "/MassResolutionVsPt_%s_%s" %(trackType,rapidity) c2.SaveAs(output+saveas+".png") c2.SaveAs(output+saveas+".pdf") c2.SaveAs(output+saveas+".root") c2.SaveAs(output+saveas+".C")
def promptRateCentral(path, selection, plots, runRange, cmsExtra): f = TFile("promptRates.root", "RECREATE") ptBins = [20, 25, 30, 35, 40, 50, 60, 70, 10000] etaBins = [0, 0.3, 0.6, 0.9, 1.2, 1.442, 1.562, 1.9, 2.2, 2.4] promptRateE = ROOT.TH2F("promptRateE", "", len(ptBins) - 1, array("f", ptBins), len(etaBins) - 1, array("f", etaBins)) promptRateM = ROOT.TH2F("promptRateM", "", len(ptBins) - 1, array("f", ptBins), len(etaBins) - 1, array("f", etaBins)) plot = getPlot("trailingPtPlot") plot.addRegion(selection) plot.cuts = plot.cuts % runRange.runCut #~ plot.variable = "pt1" plot.cuts = plot.cuts + "*(ht > 80 && id1 < 1.0 && id2 < 0.15 && nLightLeptons == 2 && p4.M() > 76 && p4.M() < 106 && met < 20)" histsLoose = get2DHistogramsPrompt(path, plot.cuts, ptBins, etaBins) plot.cuts = plot.cuts + "*(ht > 80 && id1 < 0.15 && id2 < 0.15 && nLightLeptons == 2 && p4.M() > 76 && p4.M() < 106 && met < 20)" histsTight = get2DHistogramsPrompt(path, plot.cuts, ptBins, etaBins) histsTight[0].Divide(histsLoose[0]) histsTight[1].Divide(histsLoose[1]) promptRateE.Add(histsTight[0].Clone()) promptRateM.Add(histsTight[1].Clone()) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() style.SetPadRightMargin(0.2) plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() logScale = plot.log plotPad.DrawFrame(0., 0., 200, 2.4, "; %s ; %s" % ("trailing p_{T} [GeV]", "trailing #eta")) histsTight[0].Draw("samecolz") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.89, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.82 else: yLabelPos = 0.85 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() hCanvas.Print("fig/promptRate_ele.pdf") plotPad.DrawFrame(0., 0., 200, 2.4, "; %s ; %s" % ("trailing p_{T} [GeV]", "trailing #eta")) histsTight[1].Draw("samecolz") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.89, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.82 else: yLabelPos = 0.85 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() hCanvas.Print("fig/promptRate_mu.pdf") f.Write() f.Close()
def compareMassRes(trackType): fileEOYBB = open("MassResolutionVsMass_TunePNew_BB_EOY.pkl", "rb") fileEOYBE = open("MassResolutionVsMass_TunePNew_BE_EOY.pkl", "rb") fileULBB = open("default/MassResolutionVsMass_TunePNew_BB.pkl", "rb") fileULBE = open("default/MassResolutionVsMass_TunePNew_BE.pkl", "rb") resultsEOYBB = pickle.load(fileEOYBB) resultsEOYBE = pickle.load(fileEOYBE) resultsULBB = pickle.load(fileULBB) resultsULBE = pickle.load(fileULBE) graphEOYBB = getGraph(resultsEOYBB, "EOYBB") graphEOYBE = getGraph(resultsEOYBE, "EOYBE") graphULBB = getGraph(resultsULBB, "ULBB") graphULBE = getGraph(resultsULBE, "ULBE") ratioBB = getRatio(resultsEOYBB, resultsULBB, "ratioBB") ratioBE = getRatio(resultsEOYBE, resultsULBE, "ratioBE") canv = TCanvas("c1", "c1", 800, 800) plotPad = TPad("plotPad", "plotPad", 0.01, 0.01, 0.99, 0.99) ratioPad = TPad("ratioPad", "ratioPad", 0.01, 0.01, 0.99, 0.29) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.cd() # ~ plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) plotPad.SetTopMargin(0.05) plotPad.SetLeftMargin(0.13) plotPad.SetRightMargin(0.045) plotPad.SetBottomMargin(0.3) ratioPad.SetTopMargin(0) ratioPad.SetTopMargin(0.05) ratioPad.SetLeftMargin(0.13) ratioPad.SetRightMargin(0.045) ratioPad.SetBottomMargin(0.4) #~ xMax = 0.08 #~ if trackType == "Inner": #~ xMax = 0.2 #~ if trackType == "Outer": #~ xMax = 0.4 graphEOYBB.SetMarkerStyle(22) graphEOYBB.SetMarkerSize(2) graphEOYBB.SetMarkerColor(kBlack) graphEOYBB.SetLineColor(kBlack) graphEOYBB.SetLineWidth(2) graphEOYBB.SetFillColor(0) graphEOYBB.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType) graphEOYBB.GetYaxis().SetTitle("Mass resolution") # ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") graphEOYBB.GetYaxis().SetTitleFont(42) graphEOYBB.GetYaxis().SetTitleSize(0.05) graphEOYBB.GetYaxis().SetTitleOffset(1.35) graphEOYBB.GetYaxis().SetLabelFont(42) graphEOYBB.GetYaxis().SetLabelSize(0.038) graphEOYBB.GetYaxis().SetRangeUser(0, 0.1) graphEOYBB.GetXaxis().SetTitleSize(0.0) graphEOYBB.GetXaxis().SetLabelSize(0.0) graphEOYBB.GetXaxis().SetRangeUser(0, 6500) graphEOYBB.Draw("AP E0") graphULBB.Draw("samepe") graphEOYBB.SetMarkerSize(2) graphULBB.SetMarkerSize(2) graphEOYBB.SetLineWidth(2) graphULBB.SetLineWidth(2) graphEOYBB.SetMarkerStyle(20) graphULBB.SetMarkerStyle(21) graphULBB.SetLineColor(kRed) graphULBB.SetMarkerColor(kRed) latex = TLatex() # ~ latex.SetTextFont(42) # ~ latex.SetTextAlign(31) # ~ latex.SetTextSize(0.04) # ~ latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(.03 / 0.7) latexCMSExtra.SetNDC(True) latex.DrawLatexNDC( 0.50, 0.96, "#scale[0.8]{#font[42]{ 2017, 42.1 fb^{-1} (13 TeV)}}") cmsExtra = "Preliminary" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.5, 0.65, 0.95, 0.90, "Both muons |#eta| < 1.2", "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graphEOYBB, "EOY ReReco", "l") leg.AddEntry(graphULBB, "Legacy ReReco", "l") leg.Draw() plotPad.RedrawAxis() ratioPad.cd() ratioBB.GetYaxis().SetTitle("#splitline{EOY ReReco/}{Legacy ReReco}") ratioBB.GetXaxis().SetNoExponent(0) ratioBB.GetXaxis().SetTitleFont(42) ratioBB.GetXaxis().SetTitleOffset(0.85) ratioBB.GetXaxis().SetTitleSize(0.2) ratioBB.GetXaxis().SetLabelColor(1) ratioBB.GetXaxis().SetLabelOffset(0.01) ratioBB.GetXaxis().SetLabelFont(42) ratioBB.GetXaxis().SetLabelSize(0.17) ratioBB.GetXaxis().SetTitle("GEN dimuon mass (GeV)") ratioBB.GetYaxis().SetRangeUser(0.5, 1.5) ratioBB.GetXaxis().SetRangeUser(0, 6500) ratioBB.GetYaxis().SetTitleOffset(0.475) ratioBB.GetYaxis().SetTitleSize(0.12) ratioBB.GetYaxis().SetTitleFont(42) ratioBB.GetYaxis().SetLabelSize(0.14) ratioBB.GetYaxis().SetLabelOffset(0.007) ratioBB.GetYaxis().SetLabelFont(42) ratioBB.GetYaxis().SetNdivisions(505) ratioBB.SetMarkerColor(kRed) ratioBB.SetLineColor(kRed) ratioBB.SetLineWidth(2) ratioBB.SetMarkerStyle(20) ratioBB.SetMarkerSize(2) line = TLine(10, 1, 6500, 1) line.SetLineColor(kBlack) line.SetLineStyle(kDashed) line.SetLineWidth(2) ratioBB.Draw("A P E") ratioBB.GetXaxis().SetRangeUser(0, 6500) line.Draw() ratioBB.Draw("samePE") ratioPad.RedrawAxis() canv.Print("massResolutionCompareUL_%s_BB.pdf" % trackType) canv = TCanvas("c1", "c1", 800, 800) plotPad = TPad("plotPad", "plotPad", 0.01, 0.01, 0.99, 0.99) ratioPad = TPad("ratioPad", "ratioPad", 0.01, 0.01, 0.99, 0.29) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.cd() # ~ plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) plotPad.SetTopMargin(0.05) plotPad.SetLeftMargin(0.13) plotPad.SetRightMargin(0.045) plotPad.SetBottomMargin(0.3) ratioPad.SetTopMargin(0) ratioPad.SetTopMargin(0.05) ratioPad.SetLeftMargin(0.13) ratioPad.SetRightMargin(0.045) ratioPad.SetBottomMargin(0.4) #~ xMax = 0.08 #~ if trackType == "Inner": #~ xMax = 0.2 #~ if trackType == "Outer": #~ xMax = 0.4 graphEOYBE.SetMarkerStyle(22) graphEOYBE.SetMarkerSize(2) graphEOYBE.SetMarkerColor(kBlack) graphEOYBE.SetLineColor(kBlack) graphEOYBE.SetLineWidth(2) graphEOYBE.SetFillColor(0) graphEOYBE.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType) graphEOYBE.GetYaxis().SetTitle("Mass resolution") # ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") graphEOYBE.GetYaxis().SetTitleFont(42) graphEOYBE.GetYaxis().SetTitleSize(0.05) graphEOYBE.GetYaxis().SetTitleOffset(1.35) graphEOYBE.GetYaxis().SetLabelFont(42) graphEOYBE.GetYaxis().SetLabelSize(0.038) graphEOYBE.GetYaxis().SetRangeUser(0, .2) graphEOYBE.GetXaxis().SetTitleSize(0.0) graphEOYBE.GetXaxis().SetLabelSize(0.0) graphEOYBE.GetXaxis().SetRangeUser(0, 6500) graphEOYBE.Draw("AP E0") graphULBE.Draw("samepe") graphEOYBE.SetMarkerSize(2) graphULBE.SetMarkerSize(2) graphEOYBE.SetLineWidth(2) graphULBE.SetLineWidth(2) graphEOYBE.SetMarkerStyle(20) graphULBE.SetMarkerStyle(21) graphULBE.SetLineColor(kRed) graphULBE.SetMarkerColor(kRed) latex = TLatex() # ~ latex.SetTextFont(42) # ~ latex.SetTextAlign(31) # ~ latex.SetTextSize(0.04) # ~ latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(.03 / 0.7) latexCMSExtra.SetNDC(True) latex.DrawLatexNDC( 0.50, 0.96, "#scale[0.8]{#font[42]{ 2017, 42.1 fb^{-1} (13 TeV)}}") cmsExtra = "Preliminary" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.5, 0.65, 0.95, 0.90, "At least one muon |#eta| > 1.2", "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graphEOYBE, "EOY ReReco", "lp") leg.AddEntry(graphULBE, "Legacy ReReco", "lp") leg.Draw() plotPad.RedrawAxis() ratioPad.cd() ratioBE.GetYaxis().SetTitle("#splitline{EOY ReReco/}{Legacy ReReco}") ratioBE.GetXaxis().SetNoExponent(0) ratioBE.GetXaxis().SetTitleFont(42) ratioBE.GetXaxis().SetTitleOffset(0.85) ratioBE.GetXaxis().SetTitleSize(0.2) ratioBE.GetXaxis().SetLabelColor(1) ratioBE.GetXaxis().SetLabelOffset(0.01) ratioBE.GetXaxis().SetLabelFont(42) ratioBE.GetXaxis().SetLabelSize(0.17) ratioBE.GetXaxis().SetTitle("GEN dimuon mass (GeV)") ratioBE.GetYaxis().SetRangeUser(0.5, 1.5) ratioBE.GetXaxis().SetRangeUser(0, 6500) ratioBE.GetYaxis().SetTitleOffset(0.475) ratioBE.GetYaxis().SetTitleSize(0.12) ratioBE.GetYaxis().SetTitleFont(42) ratioBE.GetYaxis().SetLabelSize(0.14) ratioBE.GetYaxis().SetLabelOffset(0.007) ratioBE.GetYaxis().SetLabelFont(42) ratioBE.GetYaxis().SetNdivisions(505) ratioBE.SetMarkerColor(kRed) ratioBE.SetLineColor(kRed) ratioBE.SetLineWidth(2) ratioBE.SetMarkerStyle(20) ratioBE.SetMarkerSize(2) line = TLine(10, 1, 6500, 1) line.SetLineColor(kBlack) line.SetLineStyle(kDashed) line.SetLineWidth(2) ratioBE.Draw("A P E") ratioBE.GetXaxis().SetRangeUser(0, 6500) line.Draw() ratioBE.Draw("samePE") ratioPad.RedrawAxis() ratioBE.Draw("samepe") canv.Print("massResolutionCompareUL_%s_BE.pdf" % trackType)
class Plot(object): """Structural class for representing, accessing, and maintaining references to ROOT graphical elements forming a plot, potentially with a ratio subplot. """ # Plotting 'constants' for the plot class. Ideally, one would allow these # to be flexible, but unfortunately ROOT's coordinate system is extremely # inconsistent and fragile, so it is best to fix these values here. You # can change them dynamically with Plot.Whatever = value, but it is # probably best to leave them alone. PLOT_WIDTH = 1280 # px PLOT_HEIGHT = 1024 # px PLOT_MARGINS = (0.125, 0.05, 0.1, 0.1) # Left, Right, Bottom, Top PLOT_MARGINS_WITH_RATIO = (0.125, 0.05, 0.025, 0.1) PLOT_RATIO_MARGINS = (0.125, 0.05, 0.325, 0.05) PLOT_LEFT_MARGIN = 0.1 PLOT_HEADER_HEIGHT = 400 # px PLOT_LEGEND_HEIGHT = 250 # px PLOT_LEGEND_LEFT = 0.45 PLOT_LEGEND_RIGHT = 0.95 PLOT_LEGEND_BOTTOM = 0.7 PLOT_LEGEND_BOTTOM_WITH_RATIO = 0.63 PLOT_LEGEND_TOP = 0.88 PLOT_LEGEND_TOP_WITH_RATIO = 0.88 PLOT_LEGEND_TEXT_SIZE = 0.03 PLOT_LEGEND_TEXT_SIZE_WITH_RATIO = 0.045 PLOT_LEGEND_N_COLUMNS = 2 PLOT_RATIO_FRACTION = 0.3 # fraction of canvas height PLOT_X_AXIS_TITLE_SIZE = 0.045 PLOT_X_AXIS_TITLE_SIZE_WITH_RATIO = 0.13 PLOT_X_AXIS_TITLE_OFFSET = 0.95 PLOT_X_AXIS_TITLE_OFFSET_WITH_RATIO = 0.96 PLOT_X_AXIS_LABEL_SIZE_WITH_RATIO = 0.12 PLOT_Y_AXIS_TITLE_SIZE = PLOT_X_AXIS_TITLE_SIZE PLOT_Y_AXIS_TITLE_SIZE_WITH_RATIO = 0.06 PLOT_Y_AXIS_TITLE_OFFSET = 1.0 PLOT_Y_AXIS_TITLE_OFSET_WITH_RATIO = 0.95 PLOT_Y_AXIS_LABEL_SIZE_WITH_RATIO = 0.05 PLOT_RATIO_Y_AXIS_TITLE_SIZE = 0.09 PLOT_RATIO_Y_AXIS_TITLE_OFFSET = 0.575 PLOT_RATIO_Y_AXIS_LABEL_SIZE = 0.12 PLOT_RATIO_Y_AXIS_MINIMUM = 0.6 PLOT_RATIO_Y_AXIS_MAXIMUM = 1.4 PLOT_ERROR_BAND_FILL_STYLE = 3254 # Diagonal lines PLOT_ERROR_BAND_FILL_COLOR = 13 # Gray PLOT_ERROR_BAND_LINE_WIDTH = 0 PLOT_ERROR_BAND_LINE_COLOR = 0 PLOT_RATIO_ERROR_BAND_FILL_STYLE = 3254 # Diagonal lines PLOT_RATIO_ERROR_BAND_FILL_COLOR = 807 # Orange PLOT_RATIO_ERROR_BAND_LINE_WIDTH = 0 PLOT_RATIO_ERROR_BAND_LINE_COLOR = 0 PLOT_ATLAS_STAMP_LUMINOSITY_SIZE = 0.035 PLOT_ATLAS_STAMP_LUMINOSITY_SIZE_WITH_RATIO = 0.05 PLOT_ATLAS_STAMP_TITLE_SIZE = 0.04 PLOT_ATLAS_STAMP_TITLE_SIZE_WITH_RATIO = 0.055 PLOT_ATLAS_STAMP_TEXT_COLOR = 1 PLOT_ATLAS_STAMP_TEXT_FONT = 42 PLOT_ATLAS_STAMP_ATLAS_TEXT_FONT = 72 PLOT_ATLAS_STAMP_LEFT = 0.18 PLOT_ATLAS_STAMP_LUMINOSITY_LEFT = 0.185 PLOT_ATLAS_STAMP_LUMINOSITY_TOP = 0.78 PLOT_ATLAS_STAMP_LUMINOSITY_TOP_WITH_RATIO = 0.75 PLOT_ATLAS_STAMP_SQRT_S_TOP = 0.71 PLOT_ATLAS_STAMP_SQRT_S_TOP_WITH_RATIO = 0.65 PLOT_ATLAS_STAMP_LABEL_LEFT_ADDITION = 0.105 PLOT_ATLAS_STAMP_LABEL_LEFT_ADDITION_WITH_RATIO = 0.102 PLOT_ATLAS_STAMP_ATLAS_TOP = 0.84 PLOT_ATLAS_STAMP_ATLAS_TOP_WITH_RATIO = 0.845 def __init__(self, title='', x_title=None, y_title=None, plot_header=True, ratio=False, x_range=None, y_max=None): """Initializes a new instance of the Plot class. Args: title: The title to set for the histogram plot_header: Whether or not to include whitespace at the top of the plot for the ATLAS label and legend ratio: Whether or not to include a ratio plot x_range: A tuple of (x_min, x_max) y_max: The maximum Y axis value """ # Store the title self._title = title self._x_title, self._y_title = x_title, y_title # Store whether or not the user wants to create a plot header self._plot_header = plot_header # Calculate a unique name for the plot components name = _rand_uuid() # Create a canvas self._canvas = TCanvas(name + '_canvas', name, int(self.PLOT_WIDTH), int(self.PLOT_HEIGHT)) SetOwnership(self._canvas, False) # Create the main plot and draw it self._plot = TPad(name + '_plot', name, 0.0, (self.PLOT_RATIO_FRACTION if ratio else 0.0), 1.0, 1.0) SetOwnership(self._plot, False) self._plot.SetMargin( *(self.PLOT_MARGINS_WITH_RATIO if ratio else self.PLOT_MARGINS)) self._plot.Draw() # Store ranges self._x_range = x_range if y_max is not None: self._set_maximum_value(y_max) # Switch back to the context of the canvas self._canvas.cd() # Create a ratio plot and draw it if requested if ratio: self._ratio_plot = TPad(name + '_ratio', name, 0.0, 0.0, 1.0, self.PLOT_RATIO_FRACTION) SetOwnership(self._ratio_plot, False) self._ratio_plot.SetMargin(*self.PLOT_RATIO_MARGINS) self._ratio_plot.SetGridy(True) self._ratio_plot.Draw() else: self._ratio_plot = None # Track whether or not we've already drawn to the main pad self._drawn = False # Track whether or not we've already drawn to the ratio pad self._ratio_drawn = False # Track that object which sets up the axes in the main plot self._axes_object = None # Create a structure to track any histograms we generate internally # which need to be added to any legends created self._legend_extras = [] def save(self, path): """Saves this plot to file. Args: path: The path where the plot should be saved. """ # Force an update of the canvas self._canvas.Update() # Save to file self._canvas.SaveAs(path) def _get_maximum_value(self): """Returns the currently set maximum value (possibly None). """ if hasattr(self, '_maximum_value'): return self._maximum_value return None def _set_maximum_value(self, value): """Sets the current maximum value, possibly including room for a plot header. Args: value: The value to set """ # Check if the current value is not None, and if so, throw an error # because this property should not be set twice if self._get_maximum_value() is not None: raise RuntimeError('maximum value should not be set twice') # If the value is None, ignore it if value is None: return # If the user wants a plot header, then add space for one if self._plot_header: # Grab the plot pad height (in pixels) plot_height = (self.PLOT_HEIGHT * (self._plot.GetY2() - self._plot.GetY1())) # Adjust the height value *= (plot_height + self.PLOT_HEADER_HEIGHT) / plot_height # Set the value self._maximum_value = value def set_log_scale(self, log_scale=True): """Set log scale on the Y axis for this plot.""" self._plot.SetLogy(int(log_scale)) def draw(self, *drawables_options): """Plots a collection of plottables to the main plot pad. All TH1 objects are drawn with error bars. THStack elements are only drawn with an error band if one is provided. This method may only be called once Args: drawables_options: Each argument of this function must be of the form (object, options), where object is one of the following: - A TH1 object - A THStack object - A tuple of the form (THStack, TGraph) where the latter represents error bars - A TGraph object - A TLine object and options is a string which will be used for the options argument of the object's Draw method. Plottables will be rendered in the order provided. Axes drawing options (e.g. 'a' or 'same' should not be provided and will be set automatically). A TLine may not be the first drawable element. """ # Make sure there are drawables if len(drawables_options) == 0: raise ValueError('must provide at least one plottable') # Check if we've already drawn if self._drawn: raise RuntimeError('cannot draw twice to a plot') self._drawn = True # Extract drawables drawables, _ = zip(*drawables_options) # Check if there is a maximum value set, and if not, set it if self._get_maximum_value() is None: self._set_maximum_value(maximum_value(drawables)) # Move to the context of the plot pad self._plot.cd() # Iterate through and draw drawables based on type first = True for drawable, option in drawables_options: # Check if this a tuple of histogram, error_band if isinstance(drawable, tuple): drawable, error_band = drawable else: error_band = None # Make a clone of the drawable so we don't modify it drawable = drawable.Clone(_rand_uuid()) SetOwnership(drawable, False) # Set the maximum value of the drawable if supported # HACK: I wish this could go into _handle_axes, but apparently it # can't because ROOT sucks and this has to be set on EVERY # drawable, not just the one with the axes. if not is_line(drawable): drawable.SetMaximum(self._get_maximum_value()) # Include axes if we need if first: if is_line(drawable): raise ValueError('TLine may not be first drawable') if is_graph(drawable): option += 'a' else: option += 'same' first = False # Draw the histogram drawable.Draw(option) # Handle axes if not is_line(drawable): self._handle_axes(drawable, option) # If there is an error band, draw it if error_band is not None: self._draw_error_band(error_band) # HACK: Need to force a redraw of plot axes due to issue with ROOT: # http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=14034 self._plot.RedrawAxis() def _handle_axes(self, drawable, option): """If there is no object currently registered as the owner of the axes drawn on the main plot, then this will set it. Args: drawable: The graph, histogram or stack whose axes were ALREADY drawn option: The option with which to draw the axes """ # If we already have an axes object, ignore this one if self._axes_object is not None: return # Grab the histogram used for axes style/range manipulation if is_stack(drawable) or is_graph(drawable): axes_histogram = drawable.GetHistogram() else: axes_histogram = drawable # Grab the histogram used for title manipulation if is_stack(drawable): title_histogram = drawable.GetHists()[0] else: title_histogram = drawable # Set the plot title title_histogram.SetTitle(self._title) # Grab axes x_axis, y_axis = axes_histogram.GetXaxis(), axes_histogram.GetYaxis() # Grab titles from first histogram if not set explicitly if self._x_title is None: self._x_title = title_histogram.GetXaxis().GetTitle() if self._y_title is None: self._y_title = title_histogram.GetYaxis().GetTitle() # Style x-axis, or hide it if this plot has a ratio plot if self._x_range is not None: x_axis.SetRangeUser(*self._x_range) if self._ratio_plot: x_axis.SetLabelOffset(999) x_axis.SetTitleOffset(999) else: x_axis.SetTitle(self._x_title) x_axis.SetTitleSize(self.PLOT_X_AXIS_TITLE_SIZE) x_axis.SetTitleOffset(self.PLOT_X_AXIS_TITLE_OFFSET) # Style y-axis if self._ratio_plot: y_axis.SetLabelSize(self.PLOT_Y_AXIS_LABEL_SIZE_WITH_RATIO) y_axis.SetTitle(self._y_title) y_axis.SetTitleSize( (self.PLOT_Y_AXIS_TITLE_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_Y_AXIS_TITLE_SIZE)) y_axis.SetTitleOffset( (self.PLOT_Y_AXIS_TITLE_OFSET_WITH_RATIO if self._ratio_plot else self.PLOT_Y_AXIS_TITLE_OFFSET)) # Redraw the drawable with the new style drawable.Draw(option) def _draw_error_band(self, error_band): """Draws an error band on top of histogram objects. Args: error_band: The error band to draw (a TGraphAsymmErrors) """ # Style it # HACK: Setting the marker style to 0 specifies this should be filled # in the legend error_band.SetMarkerStyle(0) error_band.SetMarkerSize(0) error_band.SetFillStyle(self.PLOT_ERROR_BAND_FILL_STYLE) error_band.SetFillColor(self.PLOT_ERROR_BAND_FILL_COLOR) error_band.SetLineWidth(self.PLOT_ERROR_BAND_LINE_WIDTH) error_band.SetLineColor(self.PLOT_ERROR_BAND_LINE_COLOR) # Draw it error_band.Draw('e2same') # Add it to the list of things we need to add to the legend self._legend_extras.append(error_band) def draw_ratio_histogram(self, histogram, draw_unity=True, error_band=None): """Draws a ratio histogram to the ratio pad. Args: histogram: The ratio histogram to draw (use ratio_histogram) draw_unity: Whether or not to draw a line at 1 error_band: An error band to draw under the ratio histogram (see owls_hep.uncertainty.ratio_uncertainty_band) The histogram X axis title is set by draw_histogram if not set explicitly. draw_ratio_histogram should therefore be called after draw_histogram. """ # Check if we've already drawn if self._ratio_drawn: raise RuntimeError('cannot draw twice to a plot') self._ratio_drawn = True # Switch to the context of the ratio pad self._ratio_plot.cd() # Clone the histogram histogram = histogram.Clone(_rand_uuid()) SetOwnership(histogram, False) # Style it x_axis, y_axis = histogram.GetXaxis(), histogram.GetYaxis() x_axis.SetTitleSize(self.PLOT_X_AXIS_TITLE_SIZE_WITH_RATIO) x_axis.SetTitleOffset(self.PLOT_X_AXIS_TITLE_OFFSET_WITH_RATIO) x_axis.SetLabelSize(self.PLOT_X_AXIS_LABEL_SIZE_WITH_RATIO) x_axis.SetTitle(self._x_title) if self._x_range: x_axis.SetRangeUser(*self._x_range) y_axis.SetTitleSize(self.PLOT_RATIO_Y_AXIS_TITLE_SIZE) y_axis.SetTitleOffset(self.PLOT_RATIO_Y_AXIS_TITLE_OFFSET) y_axis.SetLabelSize(self.PLOT_RATIO_Y_AXIS_LABEL_SIZE) y_axis.SetRangeUser(self.PLOT_RATIO_Y_AXIS_MINIMUM, self.PLOT_RATIO_Y_AXIS_MAXIMUM) y_axis.SetNdivisions(504, False) # Draw it # NOTE: Have to specify E0 or points out of the vertical range won't # have their error bars drawn: # https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=13329 histogram.Draw('e0p') # Draw a line at unity if requested if draw_unity: # Calculate the line coordinates line_min = histogram.GetBinLowEdge(1) max_bin = histogram.GetNbinsX() line_max = (histogram.GetBinLowEdge(max_bin) + histogram.GetBinWidth(max_bin)) # Create and draw the line unit_line = TLine(line_min, 1.0, line_max, 1.0) SetOwnership(unit_line, False) unit_line.SetLineColor(2) # Red unit_line.SetLineWidth(2) unit_line.Draw('same') # If an error band was provided, draw it and add it to our legend # elements if error_band: # Keep ownership of the error band SetOwnership(error_band, False) # Style it error_band.SetMarkerSize(0) error_band.SetFillStyle(self.PLOT_RATIO_ERROR_BAND_FILL_STYLE) error_band.SetFillColor(self.PLOT_RATIO_ERROR_BAND_FILL_COLOR) error_band.SetLineWidth(self.PLOT_RATIO_ERROR_BAND_LINE_WIDTH) error_band.SetLineColor(self.PLOT_RATIO_ERROR_BAND_LINE_COLOR) # Draw it error_band.Draw('e2same') # Now, if we've drawn unity or an error band, redraw our ratio # histogram so that its point lie on top of the unity line or error # band, but use 'same' so that the axes/ticks don't cover the red line if draw_unity or error_band: histogram.Draw('e0psame') def draw_atlas_label(self, luminosity, sqrt_s, ks_test=None, custom_label=None, atlas_label=None): """Draws an ATLAS stamp on the plot, with an optional categorization label. It is recommended that you construct the Plot with plot_header = True in order to make space for the label. Args: luminosity: The integrated luminosity, in pb^-1 sqrt_s: The center of mass energy, in MeV label: The label to put after 'ATLAS', None to exclude the 'ATLAS' categorization entirely """ # Change context to the plot pad self._plot.cd() # Create the latex object stamp = TLatex() # Style it stamp.SetTextColor(self.PLOT_ATLAS_STAMP_TEXT_COLOR) stamp.SetTextFont(self.PLOT_ATLAS_STAMP_TEXT_FONT) stamp.SetNDC() # Draw the luminosity stamp.SetTextSize( (self.PLOT_ATLAS_STAMP_LUMINOSITY_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_LUMINOSITY_SIZE)) text = '#int L dt = {0:.1f} fb^{{-1}}'.format(luminosity / 1000.0) stamp.DrawLatex( self.PLOT_ATLAS_STAMP_LUMINOSITY_LEFT, (self.PLOT_ATLAS_STAMP_LUMINOSITY_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_LUMINOSITY_TOP), text) # Draw the center of mass energy and the result of the KS-test, if # requested text = '#sqrt{{s}} = {0:.1f} TeV'.format(sqrt_s / 1000000.0) if ks_test is not None: text += ', KS = {0:.2f}'.format(ks_test) stamp.DrawLatex( self.PLOT_ATLAS_STAMP_LEFT, (self.PLOT_ATLAS_STAMP_SQRT_S_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_SQRT_S_TOP), text) # If requested, draw the custom label or the 'ATLAS' label, # preferring the former if custom_label is not None: # Draw the label stamp.DrawLatex( self.PLOT_ATLAS_STAMP_LEFT, (self.PLOT_ATLAS_STAMP_ATLAS_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_ATLAS_TOP), custom_label) elif atlas_label is not None: # Draw the label stamp.SetTextSize( (self.PLOT_ATLAS_STAMP_TITLE_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_TITLE_SIZE)) stamp.DrawLatex( self.PLOT_ATLAS_STAMP_LEFT + (self.PLOT_ATLAS_STAMP_LABEL_LEFT_ADDITION_WITH_RATIO if self. _ratio_plot else self.PLOT_ATLAS_STAMP_LABEL_LEFT_ADDITION), (self.PLOT_ATLAS_STAMP_ATLAS_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_ATLAS_TOP), atlas_label) # Draw 'ATLAS' stamp.SetTextFont(self.PLOT_ATLAS_STAMP_ATLAS_TEXT_FONT) stamp.DrawLatex( self.PLOT_ATLAS_STAMP_LEFT, (self.PLOT_ATLAS_STAMP_ATLAS_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_ATLAS_STAMP_ATLAS_TOP), 'ATLAS') def draw_legend(self, *drawables): """Draws a legend onto the plot with the specified histograms. It is recommended that you construct the Plot with plot_header = True in order to make space for the legend. Args: drawables: The elements to include in the legend (via AddEntry) """ # Check if we already have a legend if hasattr(self, '_legend'): raise RuntimeError('legend already exists on this plot') # Switch to the context of the main plot self._plot.cd() # Create the legend self._legend = TLegend(self.PLOT_LEGEND_LEFT, (self.PLOT_LEGEND_BOTTOM_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_BOTTOM), self.PLOT_LEGEND_RIGHT, (self.PLOT_LEGEND_TOP_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_TOP)) SetOwnership(self._legend, False) # Style it self._legend.SetTextSize( (self.PLOT_LEGEND_TEXT_SIZE_WITH_RATIO if self._ratio_plot else self.PLOT_LEGEND_TEXT_SIZE)) self._legend.SetBorderSize(0) self._legend.SetFillStyle(0) # transparent self._legend.SetNColumns(self.PLOT_LEGEND_N_COLUMNS) # Create a chained list of all drawables. We decompose THStack # objects in reverse order, i.e. top-to-bottom. drawables = \ list(chain(*(drawable_iterable(h, True, True) for h in drawables))) # Add anything to this list that we created internally drawables.extend(self._legend_extras) # Because ROOT draws legend entries from left-to-right across rows and # not top-to-bottom along columns, we need to do a bit of a pivot on # the list so that the histograms appear in the vertical order of the # stack n_entries = len(drawables) n_col = self.PLOT_LEGEND_N_COLUMNS n_row = int(ceil(float(n_entries) / n_col)) legend_order = [] for r in xrange(0, n_row): for c in xrange(0, n_col): if (r * n_col + c) == n_entries: # Don't need an outer break, this would only happen on the # last row if n_row * n_col != n_entries break legend_order.append(drawables[r + c * n_row]) # Add the drawables for drawable in legend_order: SetOwnership(drawable, False) title = drawable.GetTitle() # HACK: Convention: legend for drawables with a non-default # marker style (data) to be drawn as line with point, and with # empty fill (signal) to be drawn as line if drawable.GetMarkerStyle() != 0: self._legend.AddEntry(drawable, title, 'lp') elif drawable.GetFillColor() == 0: self._legend.AddEntry(drawable, title, 'l') else: self._legend.AddEntry(drawable, title, 'f') # Draw the legend self._legend.Draw()
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3) parser.add_option("-x", "--exclusive", action="store_true",\ dest="isExclusive", default=False) parser.add_option("-l", "--label", dest="label", type="string", default="") parser.add_option("-z", "--zeyneplabel", action="store_true", dest="zeynep", default=True) (options, args) = parser.parse_args() N = options.N isExclusive = options.isExclusive label_text = options.label zeynep = options.zeynep if isExclusive and not (N == 2 or N == 3): parser.error("Exclusive plot only for N =2 or 3") import configurations as config from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath from ModelParser import ModelKey gStyle.SetPadTopMargin(0.05) gStyle.SetPadRightMargin(0.05) gStyle.SetPadBottomMargin(0.20) gStyle.SetErrorX(0.) suffix = "" if not isExclusive: suffix = "up" sm_files = [] for model in config.sm_models: f = TFile("%s/%s.root" % (config.sm_dir, model), "READ") sm_files.append(f) bh_weights = [] bh_files = [] from BHXsec import BHXsec xsec = BHXsec() for model in config.bh_showcase: f = TFile("%s/%s.root" % (config.bh_dir, model), "READ") bh_files.append(f) h = f.Get("plotsNoCut/ST") nEvents = h.GetEntries() bh_weights.append( xsec.get(model) / nEvents * config.integrated_luminosity) c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500, 600) hs = THStack() hs1 = THStack() infile = TFile(options.inputfile, "READ") hBkg = infile.Get("Background_N%d%s" % (N, suffix)) #hnewBkg = infile.Get("histoTemplateN3_0") hnewBkg = infile.Get("ReferenceTemplateN3_0") gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix)) hData = infile.Get("Data_N%d%s" % (N, suffix)) hBkg = infile.Get("Background_N%d%s" % (N, suffix)) hBkg.SetMarkerSize(0) hBkg_ = hBkg.Clone("BkgLine") hBkg.SetFillColor(33) hBkg.SetLineColor(33) hBkg_.SetLineWidth(3) hBkg_.SetLineColor(862) hs.Add(hBkg, "e3") hnewBkg.SetLineWidth(3) hnewBkg.Scale(10 * 3.407) hs.Add(hnewBkg, "l") legend = TLegend(0.2826613, 0.4819492, 0.6094355, 0.9416102) # - only for N >= 2 and 3 #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919... #legend.SetTextSize(0.041); #was 0.02966102 legend.SetTextSize(0.037) legend.SetTextFont(42) legend.SetFillColor(0) legend.SetLineColor(0) if isExclusive: legend.SetHeader("Multiplicity N = %d" % N) else: legend.SetHeader("Multiplicity N #geq %d" % N) legend.AddEntry(hData, "Data", "lep") #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l") legend.AddEntry(hBkg_, "Background", "l") legend.AddEntry(hBkg, "Uncertainty", "f") legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186) # legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186) # legend_sm.SetTextSize(0.037); legend_sm.SetTextSize(0.037) legend_sm.SetTextFont(42) legend_sm.SetFillColor(0) legend_sm.SetLineColor(0) for i, f in enumerate(bh_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(bh_weights[i]) # Add background for ibin in range(h.GetNbinsX()): h.SetBinContent(ibin+1,\ h.GetBinContent(ibin+1)\ + hBkg.GetBinContent(ibin+1)) h.SetLineWidth(3) #h.SetLineColor(i+2) h.SetLineStyle(i + 2) #if i == 0: #h.SetLineColor(814) if i == 0: h.SetLineStyle(5) h.SetLineColor(899) if i == 1: h.SetLineStyle(9) h.SetLineColor(4) if i == 2: h.SetLineStyle(3) h.SetLineColor(614) hs.Add(h, "hist") model = ModelKey(config.bh_showcase[i]) bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\ model.parameter["MD"], model.parameter["M"], model.parameter["n"]) if i == 3: bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4" legend.AddEntry(h, bh_legend, "l") # qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5" # legend.AddEntry(h, qbh_legend, "l") #if isExclusive: zeynep = True if zeynep: for i, f in enumerate(sm_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(config.integrated_luminosity) h.SetFillColor(config.sm_colors[i]) h.SetLineColor(config.sm_colors[i]) hs1.Add(h, "hist") legend_sm.AddEntry(h, config.sm_models[i], "f") #hs.Add(hData, "e") hs.Draw("nostack") hs1.Draw("same") c.SetLogy(1) hs.GetXaxis().SetTitle("S_{T} (GeV)") hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle()) hs.GetYaxis().SetTitleOffset(1.25) hs.GetYaxis().SetTitleSize(0.04) hs.GetYaxis().SetLabelSize(0.04) hs.GetXaxis().SetTitleSize(0.01) hs.GetXaxis().SetLabelSize(0.01) ibin = 0 #if isExclusive: # hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST) # ibin = hData.FindBin(config.fit_range[0]) #else: # hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST) # ibin = hData.FindBin(config.norm_range[0]) if isExclusive: hs.GetXaxis().SetRangeUser(1800, config.maxST) ibin = hData.FindBin(1800) else: hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST) ibin = hData.FindBin(config.norm_range[0]) from Styles import formatUncertainty formatUncertainty(gBkg) gBkg.Draw("LX") hData.Draw("sameex0") hs.SetMinimum(5e-1) if isExclusive: hs.SetMaximum(1e7) # hs.SetMaximum(hData.GetBinContent(ibin) * 40) else: #hs.SetMaximum(1e8) hs.SetMaximum(hData.GetBinContent(ibin) * 20) # or 1e7 for N>=3 and use 4 models legend.Draw("plain") #if isExclusive: if zeynep: legend_sm.Draw("plain") if isExclusive: cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC") else: cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC") cmslabel.AddText(config.cmsTitle) #cmslabel.AddText(config.cmsSubtitle) cmslabel.SetFillColor(0) cmslabel.SetTextSize(0.041) cmslabel.Draw("plain") label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC") label.SetFillColor(0) #label.SetTextSize(0.0529661); label.SetTextSize(0.0529661) label.AddText(label_text) label.Draw("plain") c.RedrawAxis() #Divide ibin = hData.FindBin(config.norm_range[0]) #print ibin fbin = hData.FindBin(config.maxST) #print fbin hData.Sumw2() hBkg_.Sumw2() Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100) Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100) Ratio = hData.Clone() Ratio.Add(hBkg_, -1) #Ratio.Divide(hBkg_) Band = TGraphAsymmErrors(fbin - ibin + 1) for i in range(ibin - 1, fbin + 1): i += 1 if hData.GetBinContent(i) != 0: value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) * hBkg_.GetBinError(i)) #print Ratio.GetBinError(i), value**(0.5) #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i) Pull.SetBinContent( i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) / Ratio.GetBinError(i)) #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05 #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i)) #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i))) Pull.SetBinError(i - 19, Ratio.GetBinError(i)) #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i)) if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)): #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05 Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) / (hBkg_.GetBinContent(i) * 0.05)) else: Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) / hBkg_.GetBinError(i)) #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05 #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i) else: Pull.SetBinContent(i - 19, 0) Pull2.SetBinContent( i - 19, (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) / hBkg_.GetBinError(i)) Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0) #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i) up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) / hBkg_.GetBinContent(i))) down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) / hBkg_.GetBinContent(i))) Band.SetPointError(i, 0., 0., down, up) #Band.Print() pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0) pad.SetTopMargin(0.799999) pad.SetRightMargin(0.05) pad.SetBottomMargin(0.09) pad.SetFillColor(0) #pad.SetGridy(1) pad.SetFillStyle(0) pad.Draw("same") pad.cd(0) Ratio.SetMarkerStyle(20) Pull.SetMarkerStyle(20) Pull.SetLineColor(1) Pull.SetMarkerSize(0.9) #Pull.SetMaximum(3) #Pull.SetMinimum(-1) Pull.SetMaximum(2.5) Pull.SetMinimum(-2.5) Pull.GetYaxis().SetNdivisions(5, 1) Pull.GetXaxis().SetTitle('S_{T} (GeV)') Pull.GetXaxis().SetLabelSize(0.04) Pull.GetYaxis().SetTitleOffset(1.05) Pull.GetYaxis().SetLabelSize(0.02) Pull.GetYaxis().SetTitleSize(0.025) Pull.GetYaxis().CenterTitle(1) Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)') Pull.SetFillColor(2) Pull.Draw("HIST") Pull2.SetLineColor(862) Pull2.SetLineWidth(3) Pull2.SetLineStyle(2) #Pull2.Draw("SAME") formatUncertainty(Band) Band.SetFillStyle(3001) # Band.Draw("le3") # Pull.Draw("ex0same") pad.RedrawAxis() gStyle.SetOptStat(0) #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC"); #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC") #FOR n=3 only block1.SetFillColor(0) block1.Draw("plain") #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC"); #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC") #FOR n=3 only block2.SetFillColor(0) block2.Draw("plain") if isExclusive: c.Print("ST_Mul%d.pdf" % N) c.Print("ST_Mul%d.png" % N) else: c.Print("ST_Mul%dup.pdf" % N) c.Print("ST_Mul%dup.png" % N) c.Update() raw_input("Press Enter to continue...")
def PlotRatio(h_reco_unfolded,h_ptcl_or,h_reco_unfolded_roof, h_reco_unfolded_svd, h_reco_unfolded_T,h_reco_unfolded_Ids, svd_par, Ids_par ,outputname="test.png"): gStyle.SetPadLeftMargin(0.12) gStyle.SetPadRightMargin(0.12) c = TCanvas("canvas_"+outputname,"canvas_"+outputname,0,0,800, 800) c.cd() pad1 = TPad("pad1","pad1",0,0.40,1,1) pad1.SetTopMargin(0.15) pad1.SetBottomMargin(0.01) pad1.SetFillStyle(0) pad1.SetTicks(1,1) pad1.SetBorderMode(0) pad1.Draw() c.cd() pad2 = TPad("pad2","pad2",0,0.01,1,0.422) pad2.SetFillStyle(0) pad2.SetTopMargin(0.043) pad2.SetBottomMargin(0.2) pad2.SetBorderMode(0) pad2.SetTicks(1,1) pad2.Draw() pad2.Modified() c.cd() pad1.cd() gStyle.SetOptStat(0) h_ptcl_or.SetTitle("") h_ptcl_or.SetLineColor(2) #h_ptcl_or.GetYaxis().SetRangeUser(0,h_ptcl_or.GetMaximum()*1.5) h_ptcl_or.GetXaxis().SetTitleSize(34) h_ptcl_or.GetXaxis().SetTitleFont(43) h_ptcl_or.GetYaxis().SetTitleSize(27) h_ptcl_or.GetYaxis().SetTitleFont(43) h_ptcl_or.GetYaxis().SetTitleOffset(1.5) h_ptcl_or.GetYaxis().SetTitle("Events") h_ptcl_or.GetYaxis().SetLabelFont(43) h_ptcl_or.GetYaxis().SetLabelSize(25) legend = TLegend(0.55,0.5,0.85,0.8) legend.SetFillStyle(0) legend.AddEntry(h_ptcl_or,"Simulation") legend.AddEntry(h_reco_unfolded,"Fully Bayesian Unfolding","p") legend.AddEntry(h_reco_unfolded_roof,"D'Agostini RooUnfold, par. 4","p") legend.AddEntry(h_reco_unfolded_svd,"SVD RooUnfold, par. " + str(svd_par),"p") legend.AddEntry(h_reco_unfolded_T,"T RooUnfold","p") legend.AddEntry(h_reco_unfolded_Ids,"Ids RooUnfold, par. " + str(Ids_par),"p") legend.SetBorderSize(0) h_reco_unfolded.SetLineColor(1) h_reco_unfolded.SetMarkerColor(1) h_reco_unfolded.SetMarkerStyle(22) h_reco_unfolded_roof.SetMarkerColor(6) h_reco_unfolded_roof.SetLineColor(6) h_reco_unfolded_roof.SetMarkerStyle(20) h_reco_unfolded_svd.SetMarkerColor(4) h_reco_unfolded_svd.SetLineColor(4) h_reco_unfolded_svd.SetMarkerStyle(5) h_reco_unfolded_T.SetMarkerColor(7) h_reco_unfolded_T.SetLineColor(7) h_reco_unfolded_T.SetMarkerStyle(34) h_reco_unfolded_Ids.SetMarkerColor(8) h_reco_unfolded_Ids.SetLineColor(8) h_reco_unfolded_Ids.SetMarkerStyle(3) h_ptcl_or.Draw("hist") h_reco_unfolded.Draw("same p x0") h_reco_unfolded_roof.Draw("same p x0") h_reco_unfolded_svd.Draw("same p x0") h_reco_unfolded_T.Draw("same p x0") h_reco_unfolded_Ids.Draw("same p x0") legend.Draw("same") pad1.RedrawAxis() pad2.cd() h_ptcl_or_clone = h_ptcl_or.Clone(h_ptcl_or.GetName()+"_clone") h_reco_unfolded_clone = h_reco_unfolded.Clone(h_reco_unfolded.GetName()+"_clone") h_reco_unfolded_roof_clone = h_reco_unfolded_roof.Clone(h_reco_unfolded_roof.GetName()+"_clone") h_reco_unfolded_svd_clone = h_reco_unfolded_svd.Clone(h_reco_unfolded_svd.GetName()+"_clone") h_reco_unfolded_T_clone = h_reco_unfolded_T.Clone(h_reco_unfolded_T.GetName()+"_clone") h_reco_unfolded_Ids_clone = h_reco_unfolded_Ids.Clone(h_reco_unfolded_Ids.GetName()+"_clone") h_ptcl_or_clone.Divide(h_ptcl_or) h_reco_unfolded_clone.Divide(h_ptcl_or) h_reco_unfolded_roof_clone.Divide(h_ptcl_or) h_reco_unfolded_svd_clone.Divide(h_ptcl_or) h_reco_unfolded_T_clone.Divide(h_ptcl_or) h_reco_unfolded_Ids_clone.Divide(h_ptcl_or) h_ptcl_or_clone.GetXaxis().SetTitleSize(27) h_ptcl_or_clone.GetXaxis().SetTitleFont(43) h_ptcl_or_clone.GetYaxis().SetTitleSize(27) h_ptcl_or_clone.GetYaxis().SetTitleFont(43) h_ptcl_or_clone.GetXaxis().SetLabelFont(43) h_ptcl_or_clone.GetXaxis().SetLabelSize(25) h_ptcl_or_clone.GetYaxis().SetLabelFont(43) h_ptcl_or_clone.GetYaxis().SetLabelSize(25) h_ptcl_or_clone.SetMaximum(1.3) h_ptcl_or_clone.SetMinimum(0.7) h_ptcl_or_clone.GetXaxis().SetTitleOffset(2.5) h_ptcl_or_clone.GetXaxis().SetTitle(args.title) h_ptcl_or_clone.GetYaxis().SetTitle("#frac{Unfolded}{Simulation} ") h_ptcl_or_clone.Draw("hist") h_reco_unfolded_clone.Draw("same p x0") h_reco_unfolded_roof_clone.Draw("same p x0") h_reco_unfolded_svd_clone.Draw("same p x0") h_reco_unfolded_T_clone.Draw("same p x0") h_reco_unfolded_Ids_clone.Draw("same p x0") pad2.RedrawAxis() c.Update() histograms.append(c) # here is the crash probably PrintCan(c, outputname)
def signalRegion(path, selection, plots, runRange, isMC, backgrounds, cmsExtra): plots = ["mllPlotRMuESignal"] for name in plots: plot = getPlot(name) plot.addRegion(selection) #~ plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut if not "Forward" in selection.name: corr = rSFOF.central.val corrErr = rSFOF.central.err if "Central" in selection.name: region = "central" else: region = "inclusive" else: corr = rSFOF.forward.val corrErr = rSFOF.forward.err region = "forward" histEE, histMM, histEM = getHistograms(path, plot, runRange, isMC, backgrounds, region, EM=True) rMuEMeasured = rMuEMeasure(histEE, histMM) rMuE, rMuEUncert = rMuEFromSFOF(histEE, histMM, histEM, corr, corrErr) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, 5, "; %s ; %s" % (plot.xaxis, "r_{#mu e}")) latex = ROOT.TLatex() latex.SetTextSize(0.04) latex.SetNDC(True) if "Central" in selection.name: centralName = "ZPeakControlCentral" elif "Forward" in selection.name: centralName = "ZPeakControlForward" else: centralName = "ZPeakControl" if os.path.isfile("shelves/rMuE_%s_%s.pkl" % (centralName, runRange.label)): centralVals = pickle.load( open("shelves/rMuE_%s_%s.pkl" % (centralName, runRange.label), "rb")) else: centralVals = centralValues(path, getRegion(centralName), runRange, False, backgrounds) x = array("f", [plot.firstBin, plot.lastBin]) y = array("f", [centralVals["rMuE"], centralVals["rMuE"]]) ex = array("f", [0., 0.]) ey = array("f", [centralVals["rMuESystErr"], centralVals["rMuESystErr"]]) ge = ROOT.TGraphErrors(2, x, y, ex, ey) ge.SetFillColor(ROOT.kOrange - 9) ge.SetFillStyle(1001) ge.SetLineColor(ROOT.kWhite) ge.Draw("SAME 3") rmueLine = ROOT.TF1("rmueline", "%f" % centralVals["rMuE"], plot.firstBin, plot.lastBin) rmueLine.SetLineColor(ROOT.kOrange + 3) rmueLine.SetLineWidth(3) rmueLine.SetLineStyle(2) rmueLine.Draw("SAME") arrayRMuEHigh = array("f", rMuE["up"]) arrayRMuELow = array("f", rMuE["down"]) arrayRMuEMeasured = array("f", rMuEMeasured["vals"]) arrayRMuEHighUncert = array("f", rMuEUncert["up"]) arrayRMuELowUncert = array("f", rMuEUncert["down"]) arrayRMuEMeasuredUncert = array("f", rMuEMeasured["errs"]) xValues = [] xValuesUncert = [] for x in range(0, histEE.GetNbinsX()): xValues.append(plot.firstBin + (plot.lastBin - plot.firstBin) / plot.nBins + x * ((plot.lastBin - plot.firstBin) / plot.nBins)) xValuesUncert.append(0) arrayXValues = array("f", xValues) arrayXValuesUncert = array("f", xValuesUncert) graphHigh = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues, arrayRMuEHigh, arrayXValuesUncert, arrayRMuEHighUncert) graphLow = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues, arrayRMuELow, arrayXValuesUncert, arrayRMuEHighUncert) graphMeasured = ROOT.TGraphErrors(histEE.GetNbinsX(), arrayXValues, arrayRMuEMeasured, arrayXValuesUncert, arrayRMuEMeasuredUncert) graphHigh.SetMarkerStyle(21) graphLow.SetMarkerStyle(22) graphMeasured.SetMarkerStyle(23) graphHigh.SetMarkerColor(ROOT.kRed) graphLow.SetMarkerColor(ROOT.kBlue) graphHigh.SetLineColor(ROOT.kRed) graphLow.SetLineColor(ROOT.kBlue) graphHigh.Draw("sameEP0") graphLow.Draw("sameEP0") graphMeasured.Draw("sameEP0") legend = TLegend(0.5, 0.6, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(0) entryHist = TH1F() entryHist.SetFillColor(ROOT.kWhite) legend.AddEntry(entryHist, selection.latex, "h") legend.AddEntry( graphHigh, "r_{#mu e} = N_{SF}/N_{OF} + #sqrt{(N_{SF}/N_{OF})^{2} -1}", "p") legend.AddEntry( graphLow, "r_{#mu e} = N_{SF}/N_{OF} - #sqrt{(N_{SF}/N_{OF})^{2} -1}", "p") legend.AddEntry(rmueLine, "r_{#mu e} from Z peak", "l") legend.AddEntry(ge, "Syst. Uncert. of r_{#mu e}", "f") legend.AddEntry( graphMeasured, "r_{#mu e} = #sqrt{N_{#mu#mu}/N_{ee}} in SF signal region", "p") legend.Draw("same") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() if isMC: hCanvas.Print("fig/rMuESignal_%s_%s_%s_%s_MC.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName)) else: hCanvas.Print("fig/rMuESignal_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName))
def compareMassRes(trackType): file2016BB = open("default/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb") file2016BE = open("default/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb") file2017BB = open("cruijff/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb") file2017BE = open("cruijff/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb") fileCBB = open("crystal/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb") fileCBE = open("crystal/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb") results2016BB = pickle.load(file2016BB) results2016BE = pickle.load(file2016BE) results2017BB = pickle.load(file2017BB) results2017BE = pickle.load(file2017BE) resultsCBB = pickle.load(fileCBB) resultsCBE = pickle.load(fileCBE) graph2016BB = getGraph(results2016BB, "DCBBB") graph2016BE = getGraph(results2016BE, "DCBBE") graph2017BB = getGraph(results2017BB, "CruijffBB") graph2017BE = getGraph(results2017BE, "CruijffBE") graphCBB = getGraph(resultsCBB, "CBB") graphCBE = getGraph(resultsCBE, "CBE") ratioBB = getRatio(results2016BB, results2017BB, "ratioBB") ratioBE = getRatio(results2016BE, results2017BE, "ratioBE") ratioCBB = getRatio(results2016BB, resultsCBB, "ratioCBB") ratioCBE = getRatio(results2016BE, resultsCBE, "ratioCBE") canv = TCanvas("c1", "c1", 800, 1200) plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) xMax = 0.08 if trackType == "Inner": xMax = 0.2 if trackType == "Outer": xMax = 0.4 plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution") graph2016BB.Draw("samepe") graph2017BB.Draw("samepe") graphCBB.Draw("samepe") graph2017BB.SetLineColor(kRed) graph2017BB.SetMarkerColor(kRed) graphCBB.SetLineColor(kBlue) graphCBB.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graph2016BB, "Cruijff", "l") leg.AddEntry(graph2017BB, "Double CB", "l") leg.AddEntry(graphCBB, "Crystal Ball", "l") leg.Draw() plotPad.RedrawAxis() ratioPad.cd() ratioBB.SetLineColor(kRed) ratioCBB.SetLineColor(kBlue) ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";ratio") ratioBB.Draw("samepe") ratioCBB.Draw("samepe") canv.Print("massResolutionCompareFunc_%s_BB.pdf" % trackType) canv = TCanvas("c1", "c1", 800, 1200) plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) style = setTDRStyle() gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.cd() plotPad.SetGrid() gStyle.SetTitleXOffset(1.45) gStyle.SetTitleYOffset(1.55) xMax = 0.08 if trackType == "Inner": xMax = 0.2 if trackType == "Outer": xMax = 0.4 plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution") graph2016BE.Draw("samepe") graph2017BE.Draw("samepe") graphCBE.Draw("samepe") graph2017BE.SetLineColor(kRed) graph2017BE.SetMarkerColor(kRed) graphCBE.SetLineColor(kBlue) graphCBE.SetMarkerColor(kBlue) latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "#splitline{Preliminary}{}" latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BE" % trackType, "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) leg.AddEntry(graph2016BE, "Cruijff", "l") leg.AddEntry(graph2017BE, "Double CB", "l") leg.AddEntry(graphCBE, "Crystal Ball", "l") leg.Draw() plotPad.RedrawAxis() ratioPad.cd() ratioBE.SetLineColor(kRed) ratioCBE.SetLineColor(kBlue) ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";;ratio") ratioBE.Draw("samepe") ratioCBE.Draw("samepe") canv.Print("massResolutionCompareFunc_%s_BE.pdf" % trackType)
def plotMllSpectra(SFhist, EMuhist, runRange, selection, suffix, cmsExtra, additionalLabel): SFhist.Rebin(5) EMuhist.Rebin(5) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() style.SetTitleYOffset(1.6) style.SetPadLeftMargin(0.19) plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() plotPad.DrawFrame(20, 0, 300, SFhist.GetBinContent(SFhist.GetMaximumBin()) * 1.5, "; %s ; %s" % ("m_{ll} [GeV]", "Events / 5 GeV")) SFhist.SetMarkerStyle(20) SFhist.SetMarkerColor(ROOT.kBlack) EMuhist.Draw("samehist") SFhist.Draw("samepe") EMuhist.SetFillColor(855) legend = TLegend(0.6, 0.7, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(0) ROOT.gStyle.SetOptStat(0) legend.AddEntry(SFhist, "%s events" % suffix, "p") legend.AddEntry(EMuhist, "OF events", "f") legend.Draw("same") line1 = ROOT.TLine(mllBins.lowMass.low, 0, mllBins.lowMass.low, SFhist.GetBinContent(SFhist.GetMaximumBin())) line2 = ROOT.TLine(mllBins.lowMass.high, 0, mllBins.lowMass.high, SFhist.GetBinContent(SFhist.GetMaximumBin())) line3 = ROOT.TLine(mllBins.onZ.low, 0, mllBins.onZ.low, SFhist.GetBinContent(SFhist.GetMaximumBin())) line4 = ROOT.TLine(mllBins.onZ.high, 0, mllBins.onZ.high, SFhist.GetBinContent(SFhist.GetMaximumBin())) line5 = ROOT.TLine(mllBins.highMass.low, 0, mllBins.highMass.low, SFhist.GetBinContent(SFhist.GetMaximumBin())) line1.SetLineColor(ROOT.kBlack) line2.SetLineColor(ROOT.kBlack) line3.SetLineColor(ROOT.kRed + 2) line4.SetLineColor(ROOT.kRed + 2) line5.SetLineColor(ROOT.kBlack) line1.SetLineWidth(2) line2.SetLineWidth(2) line3.SetLineWidth(2) line4.SetLineWidth(2) line5.SetLineWidth(2) line1.Draw("same") line2.Draw("same") line3.Draw("same") line4.Draw("same") line5.Draw("same") Labelin = ROOT.TLatex() Labelin.SetTextAlign(12) Labelin.SetTextSize(0.04) Labelin.SetTextColor(ROOT.kRed + 2) Labelout = ROOT.TLatex() Labelout.SetTextAlign(12) Labelout.SetTextSize(0.04) Labelout.SetTextColor(ROOT.kBlack) Labelin.DrawLatex(80.75, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5, "In") Labelout.DrawLatex(27.25, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5, "Out") Labelout.DrawLatex(150.25, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 1.5, "Out") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval) latexCMS.DrawLatex(0.21, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.21, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() if additionalLabel is not "": hCanvas.Print( "fig/rOutIn_NoLog_%s_%s_%s_%s.pdf" % (selection.name, suffix, runRange.label, additionalLabel)) else: hCanvas.Print("fig/rOutIn_NoLog_%s_%s_%s.pdf" % (selection.name, suffix, runRange.label)) hCanvas.Clear() plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() plotPad.DrawFrame(mllBins.lowMass.low, 1, 300, SFhist.GetBinContent(SFhist.GetMaximumBin()) * 10, "; %s ; %s" % ("m_{ll} [GeV]", "Events / 5 GeV")) plotPad.SetLogy() EMuhist.Draw("samehist") SFhist.Draw("samepe") legend.Draw("same") line1.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin())) line2.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin())) line3.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin())) line4.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin())) line5.SetY2(SFhist.GetBinContent(SFhist.GetMaximumBin())) line1.Draw("same") line2.Draw("same") line3.Draw("same") line4.Draw("same") line5.Draw("same") Labelin.SetTextAngle(90) Labelin.DrawLatex(89.35, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18, "on Z") Labelout.SetTextAngle(90) Labelout.DrawLatex(47.25, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18, "low mass") #~ Labelout.DrawLatex(75.25,SFhist.GetBinContent(SFhist.GetMaximumBin())/18,"below Z") #~ Labelout.DrawLatex(109.25,SFhist.GetBinContent(SFhist.GetMaximumBin())/18,"above Z") Labelout.DrawLatex(150.25, SFhist.GetBinContent(SFhist.GetMaximumBin()) / 18, "high mass") latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % runRange.printval) latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.825 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() if additionalLabel is not "": hCanvas.Print( "fig/rOutIn_%s_%s_%s_%s.pdf" % (suffix, selection.name, runRange.label, additionalLabel)) else: hCanvas.Print("fig/rOutIn_%s_%s_%s.pdf" % (suffix, selection.name, runRange.label))
def makePlot(trees, cut, variable, combination, name, title=None, datasetName="Data"): from ROOT import TCanvas, TPad, TLegend, kBlue, kRed, TLatex from src.ratios import RatioGraph from src.histos import getHisto from math import sqrt from random import random if title is None: title = name cut = cut.replace("inv", "p4.M()") if "iso" in variable: cut = cut.replace("id1 < 0.15", "id1 < 10") cut = cut.replace("id2 < 0.15", "id2 < 10") print cut baseColor = kBlue if "jzb" in name: baseColor = kRed rmue = 1.21 trigger = {"EE": 0.970, "EMu": 0.942, "MuMu": 0.964} histos = { "MuMu": getHisto(trees["MuMu"], cut, variable), "EE": getHisto(trees["EE"], cut, variable), "EMu": getHisto(trees["EMu"], cut, variable), "EMu_MuLead": getHisto(trees["EMu"], "(%s) * (pt2 > pt1)" % cut, variable), } rmueSys = 0 predictionSrc = "EMu" if combination == "Both": sameFlavour = histos["MuMu"].Clone("sameFlavourSum") sameFlavour.Add(histos["EE"]) #~ nllPredictionScale = 0.5* sqrt(trigger["EE"]*trigger["MuMu"])*1./trigger["EMu"] *(rmue+1./(rmue)) #~ rmueSys = sqrt(sum(i**2 for i in [0.5*(1-(1./rmue**2))*0.1 + (1./trigger["EMu"] + 0.5*(1./trigger["EE"]+1./trigger["MuMu"]))*0.05])) nllPredictionScale = 1.02 rmueSys = 0.07 #0.5*(1-1./rmue**2)*0.1 elif combination in ["EE", "MuMu"]: rmueFactor = rmue if combination == "EE": rmueFactor = 1. / rmue nllPredictionScale = 0.5 * sqrt( trigger["EE"] * trigger["MuMu"]) * 1. / trigger["EMu"] * rmueFactor rmueSys = sqrt(0.1**2 + (0.67 / 1.025)**2) * nllPredictionScale sameFlavour = histos[combination].Clone("sameFlavourSum") elif combination == "MuMuSF": predictionSrc = "MuMu" rmueFactor = 1. / rmue nllPredictionScale = trigger["EE"] * 1. / trigger["MuMu"] * (rmueFactor **2) rmueSys = (2 * rmue) * 0.1 sameFlavour = histos["EE"].Clone("sameFlavourSum") else: raise StandardError, "unknown combination' %s'" % combination prediction = histos[predictionSrc].Clone("ofPrediction") predictionMuLead = histos["EMu_MuLead"].Clone("ofPrediction_MuLeading") prediction.Scale(nllPredictionScale) predictionMuLead.Scale(nllPredictionScale) rooTex = { "Both": "ee + #mu#mu", "EE": "ee", "MuMu": "#mu#mu", "MuMuSF": "ee", "EMu_Prediction": "OF-Prediciton", "MuMu_Prediction": "SF(#mu#mu)-Prediciton" } canv = TCanvas("canv", "", 800, 800) canv.Draw() pad = TPad("main_%x" % (1e16 * random()), "main", 0.01, 0.25, 0.99, 0.99) pad.SetNumber(1) pad.Draw() canv.cd() resPad = TPad("residual_%x" % (1e16 * random()), "residual", 0.01, 0.01, 0.99, 0.25) resPad.SetNumber(2) resPad.Draw() pad.cd() #~ if "iso" in variable: #~ canv.SetLogy(1) #~ pad.SetLogy(1) sameFlavour.SetMarkerStyle(20) sameFlavour.SetLineColor(1) sameFlavour.Draw("E P") sameFlavour.SetTitle(title) import ROOT histos["MuMu"].SetLineColor(ROOT.kBlack) histos["MuMu"].SetFillColor(ROOT.kWhite) prediction.SetLineColor(1) prediction.SetFillColor(baseColor - 7) prediction.Draw("SAME Hist") if predictionSrc == "EMu": predictionMuLead.SetLineColor(1) predictionMuLead.SetFillColor(baseColor - 9) predictionMuLead.Draw("SAME Hist") sameFlavour.Draw("E P SAME") histos["MuMu"].Draw("SAME Hist") pad.RedrawAxis() canv.RedrawAxis() leg = TLegend(0.75, 0.65, 1, 0.9) leg.SetFillColor(0) leg.AddEntry(sameFlavour, rooTex[combination], "P") leg.AddEntry(histos["MuMu"], "#mu#mu events", "l") leg.AddEntry(prediction, rooTex[predictionSrc + "_Prediction"], "F") if predictionSrc == "EMu": leg.AddEntry(predictionMuLead, "#mu leading", "F") leg.Draw() # print "_".join([name,variable]), # print "EE",histos["EE"].GetEntries(), "MuMu:", histos["MuMu"].GetEntries(), "EMu:", histos["EMu"].GetEntries(), # print " SF:", sameFlavour.GetEntries(), "OF:", prediction.GetEntries() # tex = TLatex() # tex.SetNDC() # tex.SetTextSize() # tex.DrawLatex(0.6, 0.7, title) residuals = RatioGraph(sameFlavour, prediction) residuals.addErrorBySize(rmueSys, rmueSys, add=False, color=kBlue - 9) residuals.draw(resPad, yMin=0.5, yMax=1.5) canv.Update() variable = variable.replace("(", "").replace(")", "") plotPath = "fig/%s.pdf" % ("_".join( [datasetName, name, combination, variable])) canv.Print(plotPath) pad.Delete() resPad.Delete() canv.Delete() # raw_input() return plotPath
def fakeRate(path, selection, plots, runRange, cmsExtra): for name in plots: plot = getPlot(name) plot.addRegion(selection) plot.cuts = plot.cuts % runRange.runCut if "Pt" in name: plot.variable = "pt" elif "Eta" in name: plot.variable = "eta" if "met" in name: plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 && nLept == 1 && pfIso < 1.0" else: plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 && nLept == 1 && pfIso < 1.0 && met < 20" if not "Forward" in selection.name: corr = rSFOF.central.val corrErr = rSFOF.central.err if "Central" in selection.name: region = "central" else: region = "inclusive" else: corr = rSFOF.forward.val corrErr = rSFOF.forward.err region = "forward" histsLoose = getHistograms(path, plot, runRange) if "met" in name: plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 && nLept == 1 && pfIso < 0.15" else: plot.cuts = "abs(eta) < 2.4 && (abs(eta) < 1.4 || abs(eta) > 1.6) && ptJet1 > 50 && mT < 20 && nLept == 1 && pfIso < 0.15 && met < 20 " histsTight = getHistograms(path, plot, runRange) for index, histLoose in enumerate(histsLoose): histTight = histsTight[index] print histTight.GetEntries(), histLoose.GetEntries() hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() logScale = plot.log plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, 1, "; %s ; %s" % (plot.xaxis, "fake rate")) fakeRate = TGraphAsymmErrors(histTight, histLoose, "cp") fakeRate.SetMarkerStyle(20) fakeRate.Draw("samep") latex = ROOT.TLatex() latex.SetTextSize(0.04) latex.SetNDC(True) legend = TLegend(0.55, 0.825, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(0) entryHist = TH1F() entryHist.SetFillColor(ROOT.kWhite) #~ legend.AddEntry(entryHist,selection.latex,"h") legend.AddEntry(fakeRate, "fake rate", "pe") #~ legend.Draw("same") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.89, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.82 else: yLabelPos = 0.85 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() if index == 0: hCanvas.Print("fig/fakeRate_ele_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName)) else: hCanvas.Print("fig/fakeRate_mu_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName))
def plotter(plotdir, plot, xTitle, logY, channels=['VV'], includeData=False, scaleSignal=0, UserRange=[None, None, None, None], initPath=''): # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'} channelTex = {'ZZ': 'ZZ'} # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)] plotstyle = [(1, 1)] # 0 1 2 3 4 5 6 # Backgrounds=['QCD', 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'TT', 'WW', 'WZ', 'ZZ'] # BGColors= [rt.kAzure+7, rt.kRed-4, rt.kOrange-2, rt.kGreen+2, rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] # BGTeX= ['QCD', 'W+JetsToQQ', 'Z+JetsToQQ', 'TTbar'], 'WW', 'WZ', 'ZZ'] #stackOrder= [4,5,6,2,1,3,0] Backgrounds = [ 'QCD' ] # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ'] 'TT', 'WW', 'WZ', 'ZZ'] BGColors = [ rt.kAzure + 7 ] #, rt.kOrange-2, rt.kGreen+2], rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] BGTeX = ['QCD'] # stackOrder = [0] PreSelection = [ 'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr', 'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel', 'AK8N2sel' ] Selection = [ 'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8' ] cutnames = [ 'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel', 'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0' ] cuts = { 'cleaner': '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}', 'AK8N2sel': 'N_{AK8} #geq 2', 'invMAk8sel': 'M_{jj-AK8} > 1050 GeV', 'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3', 'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV', 'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45', # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0', 'AK4cleaner': '', 'AK4N2sel': 'N_{AK4} #geq 2', 'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0', 'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0', 'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV' } VV = ('VV' in channels) seperate = (not VV) if VV: #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"] channels = ["ZZ"] plottitle = plotdir + '_' + plot lumi = 36.814 xLabelSize = 18. yLabelSize = 18. xTitleSize = 20. yTitleSize = 22. xTitleOffset = 4. yTitleOffset = 1.3 printout = False Portrait = True cutname = False ratio = includeData if ('highbin' in plot): binning = 'dijetbinning' else: binning = 'default' if (Portrait): canvX = 600 canvY = 600 else: canvX = 900 canvY = 675 if (plotdir in PreSelection): region = 'PreSelection' initPath = '' referenceHistPath = 'detaAk8sel/N_pv' if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)): return 'SofdropMass not filled yet!' else: region = 'SignalRegion' referenceHistPath = 'tau21sel/N_pv' referenceHistPath = plotdir + '/' + plot if (initPath == ''): path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region else: path = initPath outputPath = path.replace( '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion', 'plots/') if (plotdir in PreSelection): CutNumber = PreSelection.index(plotdir) else: CutNumber = Selection.index(plotdir) outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/' if (printout): print('InputPath:', path) print('OutputPath:', outputPath) #check if OutputPath exists - and if not create it! if not os.path.exists(outputPath): os.makedirs(outputPath) # path='/home/albrec/Master/signal/' scaleVV = (scaleSignal != 0) VVScale = scaleSignal if (UserRange[2] == None or UserRange[3] == None): YRangeUser = False Ymin = UserRange[2] Ymax = UserRange[3] else: YRangeUser = True Ymin = UserRange[2] Ymax = UserRange[3] if (UserRange[0] == None or UserRange[1] == None): XRangeUser = False Xmin = UserRange[0] Xmax = UserRange[1] else: XRangeUser = True Xmin = UserRange[0] Xmax = UserRange[1] # YRangeUser=False # Ymin=0.11 # Ymax=9*10**3 # XRangeUser=False # Xmin=0 # Xmax=6000. gROOT.ProcessLine("gErrorIgnoreLevel = 2001;") SFiles = [] for i in range(len(channels)): SFiles.append( TFile( path + "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root" % channels[i])) #uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root ##Open Files to get BackgroundHist: BFiles = [] for i in range(len(Backgrounds)): BFiles.append( TFile(path + "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i])) #Open File to get DataHist: # DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root") #gROOT.ProcessLine( "gErrorIgnoreLevel = 0;") if (includeData == True): #calculate QCDscale with Integrals from the following Histogram: # referenceHistPath = 'tau21sel/N_AK4' # referenceHistPath = 'detaAk8sel/N_pv' # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2' QCDscale = float(DataFile.Get(referenceHistPath).Integral()) QCDNorm = 1 for i in range(len(BFiles)): if ('QCD' in BFiles[i].GetName()): QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral()) else: QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral()) QCDscale /= QCDNorm else: QCDscale = 1.0 if (printout): print('using QCDscale:', QCDscale) SHists = [] for i in range(len(channels)): SHists.append(SFiles[i].Get(plotdir + '/' + plot)) BHists = [] for i in range(len(BFiles)): BHists.append(BFiles[i].Get(plotdir + '/' + plot)) if ('QCD' in BFiles[i].GetName()): BHists[-1].Scale(QCDscale) #if(includeData): # DataHist=DataFile.Get(plotdir+'/'+plot) if (binning == 'dijetbinning'): fitbinning = array('d') binwidth = 200 NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) NBins = int(NBins) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) for i in range(len(channels)): SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning) for i in range(len(Backgrounds)): BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning) if (includeData): DataHist = DataHist.Rebin(NBins, "new binning", fitbinning) canv = TCanvas(plottitle, plottitle, canvX, canvY) yplot = 0.7 yratio = 0.3 ymax = 1.0 xmax = 1.0 xmin = 0.0 if (ratio): plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax) ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax, ymax - yplot) else: plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax, ymax) plotpad.SetTopMargin(0.08) plotpad.SetLeftMargin(0.1) plotpad.SetRightMargin(0.05) plotpad.SetTicks() plotpad.Draw() if (ratio): plotpad.SetBottomMargin(0.016) ratiopad.SetTopMargin(0.016) ratiopad.SetBottomMargin(0.35) ratiopad.SetLeftMargin(0.1) ratiopad.SetRightMargin(0.05) ratiopad.SetTicks() ratiopad.Draw() else: plotpad.SetBottomMargin(0.1) if (logY): plotpad.SetLogy() canv.SetLogy() if ('-logX' in xTitle): plotpad.SetLogx() if (ratio): ratiopad.SetLogx() canv.SetLogx() drawOptions = "HE" stack = THStack(plottitle, plottitle) BHist = THStack(plottitle, plottitle) # for i in range(len(Backgrounds)): for i in stackOrder: # BHists[i].SetFillColor(BGColors[i]) BHists[i].SetLineColor(BGColors[i]) BHist.Add(BHists[i], 'Hist') BHist.SetTitle(plottitle) BHistErr = BHists[0].Clone() for i in range(1, len(Backgrounds)): BHistErr.Add(BHists[i]) BHistErr.SetFillStyle(3204) BHistErr.SetFillColor(rt.kGray + 2) BHistErr.SetLineColor(1) BGMax = BHist.GetMaximum() SIGMax = 0 #if(VV): #new # SIGMax=VVsum.GetMaximum() #else: for i in range(len(channels)): tmpmax = SHists[i].GetMaximum() if (tmpmax > SIGMax): SIGMax = tmpmax if (scaleVV): SIGMax = SIGMax * VVScale if (logY): MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1)) MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5)) MIN += float(10**(magnitude(MIN))) legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX) else: MAX = (1.0 / 0.8) * max(BGMax, SIGMax) legendMIN = 0.7 MIN = 0. legendMIN = (legendMIN * 0.7) + 0.3 - 0.016 legend = TLegend(0.5, 0.75, 0.85, 0.89) legend.SetFillStyle(0) legend.SetTextSize(0.02) legend.SetMargin(0.4) legend.SetNColumns(2) legend.SetColumnSeparation(0.3) if (includeData): DataHist.SetMarkerStyle(8) DataHist.SetLineColor(1) DataHist.SetTitle(plottitle) if VV: for i in range(len(channels)): if (i == 0): VVsum = SHists[i].Clone() else: VVsum.Add(SHists[i]) legentry = 'VVjj' if (scaleVV): VVsum.Scale(VVScale) legentry += ' *%0.f' % VVScale VVsum.SetLineColor(1) VVsum.SetLineStyle(plotstyle[0][1]) VVsum.SetLineWidth(2) legend.AddEntry(VVsum, legentry) else: for i in range(len(channels)): SHists[i].SetLineColor(plotstyle[i][0]) SHists[i].SetLineStyle(plotstyle[i][1]) SHists[i].SetLineWidth(2) legentry = "%sjj" % channelTex[channels[i]] if (scaleVV): SHists[i].Scale(VVScale) legentry += ' *%.2E' % VVScale legend.AddEntry(SHists[i], legentry) for i in stackOrder: legend.AddEntry(BHists[i], BGTeX[i], "f") legend.AddEntry(BHistErr, "stat. Uncertainty", "f") if (includeData): legend.AddEntry(DataHist, "Data", "lep") canv.SetTitle(plottitle) BHistErr.GetYaxis().SetTitle('Events') BHistErr.GetYaxis().SetRangeUser(MIN, MAX) BHistErr.GetYaxis().SetTitleFont(43) BHistErr.GetYaxis().SetTitleSize(yTitleSize) BHistErr.GetYaxis().SetTitleOffset(yTitleOffset) BHistErr.GetYaxis().SetLabelFont(43) BHistErr.GetYaxis().SetLabelSize(yLabelSize) if (ratio): BHistErr.GetXaxis().SetTitleSize(0.0) BHistErr.GetXaxis().SetLabelSize(0.0) else: BHistErr.GetXaxis().SetTitle(xTitle) BHistErr.GetXaxis().SetTitleFont(43) BHistErr.GetXaxis().SetTitleSize(xTitleSize) # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset) BHistErr.GetXaxis().SetTitleOffset(1.2) BHistErr.GetXaxis().SetLabelFont(43) BHistErr.GetXaxis().SetLabelSize(xLabelSize) # BHistErr.GetXaxis().SetTickLength(0.08) # BHistErr.GetXaxis().SetNdivisions(506) if (YRangeUser): BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax) if (XRangeUser): BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax) plotpad.cd() BHistErr.Draw("E2") BHist.Draw("HistSAME") BHistErr.Draw("E2SAME") if (VV): VVsum.Draw("SAME" + drawOptions) elif ('-noSig' not in xTitle): for i in range(len(channels)): SHists[i].Draw("SAME" + drawOptions) if (includeData): DataHist.Draw("APE1SAME") plotpad.RedrawAxis() if (ratio): ratiopad.cd() if (includeData): ratioHist = DataHist.Clone() else: ratioHist = BHistErr.Clone() ratioHist.SetLineColor(rt.kBlack) # ratioHist.Sumw2() ratioHist.SetStats(0) ratioHist.Divide(BHistErr) ratioHist.SetMarkerStyle(21) ratioHist.SetMarkerSize(0.7) #Yaxis ratioHist.GetYaxis().SetRangeUser(0.3, 1.7) ratioHist.GetYaxis().SetTitle("Data/BG") ratioHist.GetYaxis().CenterTitle() ratioHist.GetYaxis().SetTitleFont(43) ratioHist.GetYaxis().SetTitleSize(yTitleSize) ratioHist.GetYaxis().SetTitleOffset(yTitleOffset) ratioHist.GetYaxis().SetLabelFont(43) ratioHist.GetYaxis().SetLabelSize(yLabelSize) ratioHist.GetYaxis().SetNdivisions(506) #Xaxis ratioHist.GetXaxis().SetTitle(xTitle) ratioHist.GetXaxis().SetTitleFont(43) ratioHist.GetXaxis().SetTitleSize(xTitleSize) ratioHist.GetXaxis().SetTitleOffset(xTitleOffset) ratioHist.GetXaxis().SetLabelFont(43) ratioHist.GetXaxis().SetLabelSize(xLabelSize) ratioHist.GetXaxis().SetTickLength(0.08) ratioHist.GetXaxis().SetNdivisions(506) # if(YRangeUser): # ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax) if (XRangeUser): ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax) ratioXMin = Xmin ratioXMax = Xmax else: ratioXMin = ratioHist.GetXaxis().GetXmin() ratioXMax = ratioHist.GetXaxis().GetXmax() ratioHist.Draw("ep") zeropercent = TLine(ratioXMin, 1, ratioXMax, 1) zeropercent.Draw() plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1) plus10percent.SetLineStyle(rt.kDashed) plus10percent.Draw() minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9) minus10percent.SetLineStyle(rt.kDashed) minus10percent.Draw() canv.cd() gPad.RedrawAxis() legend.Draw() latex = TLatex() latex.SetNDC(kTRUE) latex.SetTextSize(20) latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi) latex.DrawLatex(0.1, 0.953, "private work") lastcut = 'nocuts' for cut in cutnames: if cut in plotdir: lastcut = cut if (not (lastcut == 'nocuts') and cutname): # latex.SetTextSize(0.03) latex.SetTextSize(15) for l in range(cutnames.index(lastcut) + 1): latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]]) canv.Update() canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot)) #prevents memory leak in Canvas Creation/Deletion #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html gSystem.ProcessEvents() if (ratio): del ratiopad del plotpad, canv # gc.collect() return 'done!'
def signalRegion(path, selection, plots, runRange, backgrounds, cmsExtra): plots = ["mllPlot"] for name in plots: plot = getPlot(name) plot.addRegion(selection) #~ plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut #~ plot.cuts = plot.cuts.replace("2.4","1.4") #~ plot.cuts = plot.cuts.replace("weight*","") print runRange.lumi if "Signal" in selection.name: plot.nBins = int(plot.nBins / 2) plot.yaxis = "Events / 10 GeV" fake = "!(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13)" dilep = "(motherPdgIdETH1*motherPdgIdETH2==-24*24 || motherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*motherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*grandMotherPdgIdETH2==-24*24)" #~ plot.cuts = plot.cuts+"*!(!(motherPdgIdETH1*motherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || motherPdgIdETH1*grandMotherPdgIdETH2==-24*24 || grandMotherPdgIdETH1*motherPdgIdETH2==-24*24) || !(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13))" #~ plot.cuts = plot.cuts+"*!((motherPdgIdETH1 == grandMotherPdgIdETH1) || (motherPdgIdETH2 == grandMotherPdgIdETH2))" #~ plot.cuts = plot.cuts+"*!((motherPdgIdETH1 == grandMotherPdgIdETH1) || (motherPdgIdETH2 == grandMotherPdgIdETH2) || (abs(motherPdgIdETH1) == 24 && abs(motherPdgIdETH2) == 24 )) " #~ plot.cuts = plot.cuts+"*!((abs(motherPdgIdETH1) == 15 && abs(motherPdgIdETH2) == 24) || (abs(motherPdgIdETH2) == 15 && abs(motherPdgIdETH1) == 24) || (abs(motherPdgIdETH1) == 15 && abs(motherPdgIdETH2) == 15) || (abs(motherPdgIdETH1) == 24 && abs(motherPdgIdETH2) == 24 )) " #~ plot.cuts = plot.cuts+"*(!(abs(motherPdgIdETH1*motherPdgIdETH2)==24*24 || abs(motherPdgIdETH1*motherPdgIdETH2)==15*24 || abs(motherPdgIdETH1*motherPdgIdETH2)==15*15) || !(pdgIdETH1*pdgIdETH2==-11*11 || pdgIdETH1*pdgIdETH2==-13*13 || pdgIdETH1*pdgIdETH2==-11*13))" #~ plot.cuts = plot.cuts+"*(!(abs(motherPdgId1*motherPdgId2)==24*24 || abs(motherPdgId1*motherPdgId2)==15*24 || abs(motherPdgId1*motherPdgId2)==15*15) || !(pdgId1*pdgId2==-11*11 || pdgId1*pdgId2==-13*13 || pdgId1*pdgId2==-11*13))" #~ plot.cuts = plot.cuts+"*!(%s && !%s)"%(dilep,fake) plot.cuts = plot.cuts + "*!(%s && !%s)" % (dilep, fake) print plot.cuts if not "Forward" in selection.name: corr = rSFOF.central.val corrErr = rSFOF.central.err if "Central" in selection.name: region = "central" else: region = "inclusive" else: corr = rSFOF.forward.val corrErr = rSFOF.forward.err region = "forward" #~ eventCounts = totalNumberOfGeneratedEvents(path) print eventCounts #~ for background in backgrounds: #~ process = Process(getattr(Backgrounds,background),eventCounts) #~ for subprocess in process.samples: #~ #~ print subprocess #~ treeEE, treeMM, treeEM = getTrees(path,plot,runRange, subprocess,region) #~ for ev in treeMM: #~ print ev.pdgIdETH1, ev.motherPdgIdETH1, ev.grandMotherPdgIdETH1, "--", ev.pdgIdETH2, ev.motherPdgIdETH2, ev.grandMotherPdgIdETH2 #~ print treeEE.GetEntries(), treeMM.GetEntries(), treeEM.GetEntries() histEE, histMM, histOF = getHistograms(path, plot, runRange, backgrounds, region) print histEE.Integral(1, histEE.GetNbinsX()), histMM.Integral( 1, histEE.GetNbinsX()), histOF.Integral(1, histEE.GetNbinsX()) print histEE.GetEntries(), histMM.GetEntries(), histOF.GetEntries() nEEScaledErr = ROOT.Double() nMMScaledErr = ROOT.Double() nEMScaledErr = ROOT.Double() nEEScaled = histEE.IntegralAndError(1, histEE.GetNbinsX(), nEEScaledErr) nMMScaled = histMM.IntegralAndError(1, histEE.GetNbinsX(), nMMScaledErr) nEMScaled = histOF.IntegralAndError(1, histEE.GetNbinsX(), nEMScaledErr) result = { "nEE": histEE.GetEntries(), "nMM": histMM.GetEntries(), "nEM": histOF.GetEntries(), "nEEScaled": nEEScaled, "nEEScaledErr": float(nEEScaledErr), "nMMScaled": nMMScaled, "nMMScaledErr": float(nMMScaledErr), "nEMScaled": nEMScaled, "nEMScaledErr": float(nEMScaledErr) } outFilePkl = open( "shelves/nonPromptMC_%s_%s" % (selection.name, runRange.label), "w") pickle.dump(result, outFilePkl) outFilePkl.close() hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1) style = setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() logScale = plot.log if plot.variable == "met" or plot.variable == "type1Met" or plot.variable == "tcMet" or plot.variable == "caloMet" or plot.variable == "mht": logScale = True yMax = histEE.GetBinContent( histEE.GetMaximumBin()) + histMM.GetBinContent( histMM.GetMaximumBin()) if logScale: yMax = yMax * 1.5 else: yMax = yMax * 1.5 #~ plotPad.DrawFrame(plot.firstBin, plot.yMin, plot.lastBin, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) histSF = histEE.Clone("histSF") histSF.Add(histMM.Clone()) histSF.SetMarkerStyle(20) histOF.SetLineColor(ROOT.kBlue) histOF.SetMarkerSize(0) histEE.SetLineColor(ROOT.kRed) histMM.SetLineColor(ROOT.kGreen + 3) histEE.SetLineStyle(ROOT.kDashed) histMM.SetLineStyle(ROOT.kDashed) histSF.Draw("samep") histOF.Draw("samehiste") histEE.Draw("samehist") histMM.Draw("samehist") latex = ROOT.TLatex() latex.SetTextSize(0.04) latex.SetNDC(True) legend = TLegend(0.5, 0.55, 0.95, 0.9) legend.SetFillStyle(0) legend.SetBorderSize(0) entryHist = TH1F() entryHist.SetFillColor(ROOT.kWhite) legend.AddEntry(entryHist, selection.latex, "h") legend.AddEntry(histSF, "SF", "p") legend.AddEntry(histEE, "EE", "l") legend.AddEntry(histMM, "MM", "l") legend.AddEntry(histOF, "OF", "l") legend.Draw("same") latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetNDC(True) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (8 TeV)" % runRange.printval) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) latexCMS.DrawLatex(0.19, 0.88, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) plotPad.RedrawAxis() hCanvas.Print("fig/nonPromptMC_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName))