def plotReRecoComparison(path, selection, plots, runRange, isMC, backgrounds, cmsExtra, doLog=True): for name in plots: plot = getPlot(name) plot.addRegion(selection) plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut hists = {} histsPrompt = {} hists["EE"], hists["MM"], hists["EM"] = getHistograms( path, plot, runRange, isMC, backgrounds) histsPrompt["EE"], histsPrompt["MM"], histsPrompt[ "EM"] = getHistograms("/home/jan/Trees/sw538v0477", plot, runRange, isMC, backgrounds) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() legend = TLegend(0.6, 0.65, 0.95, 0.95) legend.SetFillStyle(0) legend.SetBorderSize(0) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) for combination in ["EE", "MM", "EM"]: hCanvas.Clear() legend.Clear() plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) style = setTDRStyle() style.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() hists[combination].SetMarkerStyle(21) histsPrompt[combination].SetMarkerStyle(22) hists[combination].SetMarkerColor(ROOT.kGreen + 3) histsPrompt[combination].SetMarkerColor(ROOT.kBlack) hists[combination].SetLineColor(ROOT.kGreen + 3) histsPrompt[combination].SetLineColor(ROOT.kBlack) if doLog: yMin = 0.1 yMax = max( hists[combination].GetBinContent( hists[combination].GetMaximumBin()), histsPrompt[combination].GetBinContent( histsPrompt[combination].GetMaximumBin())) * 10 plotPad.SetLogy() else: yMin = 0 yMax = max( hists[combination].GetBinContent( hists[combination].GetMaximumBin()), histsPrompt[combination].GetBinContent( histsPrompt[combination].GetMaximumBin())) * 1.5 plotPad.DrawFrame(plot.firstBin, yMin, plot.lastBin, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) hists[combination].Draw("samep") histsPrompt[combination].Draw("samep") legend.AddEntry(histsPrompt[combination], "Prompt reconstruction", "p") legend.AddEntry(hists[combination], "Jan22 ReReco", "p") #~ #~ legend.Draw("same") latex.DrawLatex(0.94, 0.96, "19.4-%s fb^{-1} (8 TeV)" % runRange.printval) 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)) latex.DrawLatex( 0.9, 0.25, "yield ReReco: %d#pm%d yield prompt: %d#pm%d ratio: %.3f" % (hists[combination].Integral(), hists[combination].Integral()** 0.5, histsPrompt[combination].Integral(), histsPrompt[combination].Integral()** 0.5, hists[combination].Integral() / histsPrompt[combination].Integral())) print hists[combination].Integral( ), "+/-", hists[combination].Integral( )**0.5, histsPrompt[combination].Integral(), "+/-", histsPrompt[ combination].Integral()**0.5, hists[combination].Integral( ) / histsPrompt[combination].Integral() ratioPad.cd() #~ ratio = ROOT.TGraphAsymmErrors(hists[combination],histsPrompt[combination],"cp") #~ ratio.SetMarkerStyle(20) #~ ratio.SetMarkerColor(ROOT.kGreen+3) #~ ratio.SetLineColor(ROOT.kGreen+3) ratioGraphs = ratios.RatioGraph(hists[combination], histsPrompt[combination], plot.firstBin, plot.lastBin, title="ReReco/Prompt", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kGreen + 3, adaptiveBinning=0.25, labelSize=0.135) #~ ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) #~ ratioPad.DrawFrame(plot.firstBin,0,plot.lastBin,2,"; %s ; %s" %("","ReReco/Prompt")) #~ ratio.Draw("saeme") logLabel = "Log" if not doLog: logLabel = "NoLog" hCanvas.Print( "fig/reRecoCompare_%s_%s_%s_%s_%s_%s.pdf" % (selection.name, runRange.label, plot.variablePlotName, plot.additionalName, combination, logLabel))
def main(): ### for data histos = ["BB", "BE"] labels = ["dimuon_Moriond2017_BB", "dimuon_Moriond2017_BE"] lambdas = [10, 16, 22, 28, 34] models = ["ConLL", "ConLR", "ConRR", "DesLL", "DesLR", "DesRR"] bins = [4, 7] massPlot = getPlot("massPlotForLimit") massPlotSmeared = getPlot("massPlotSmeared") massPlotUp = getPlot("massPlotUp") massPlotDown = getPlot("massPlotDown") massPlotWeighted = getPlot("massPlotWeighted") binning = [400, 500, 700, 1100, 1900, 3500] name = "CITo2Mu_Lam10TeVConLL" signal = Process(getattr(Signals, name)) sigHistRaw = deepcopy(signal.loadHistogramProjected(massPlot, 1)) sigHistWeightedRaw = deepcopy( signal.loadHistogramProjected(massPlotWeighted, 1)) sigHist = ROOT.TH1F("sigHist", "sigHist", len(binning) - 1, array('f', binning)) sigHistWeighted = ROOT.TH1F("sigHistWeighted", "sigHistWeighted", len(binning) - 1, array('f', binning)) sigHist.Sumw2() sigHistWeighted.Sumw2() for index, lower in enumerate(binning): if index < len(binning) - 1: sigHist.SetBinContent( index + 1, max( 0, sigHistRaw.Integral( sigHistRaw.FindBin(lower), sigHistRaw.FindBin(binning[index + 1] - 0.001)))) sigHistWeighted.SetBinContent( index + 1, max( 0, sigHistWeightedRaw.Integral( sigHistWeightedRaw.FindBin(lower), sigHistWeightedRaw.FindBin(binning[index + 1] - 0.001)))) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(400, 0, 3500, 3500, "; m [GeV]; Events") sigHist.Draw("samehist") sigHistWeighted.Draw("samehist") sigHistWeighted.SetLineColor(kRed) ratioPad.cd() ratioGraphs = ratios.RatioGraph(sigHist, sigHistWeighted, xMin=400, xMax=3500, title="Default/Weighted", yMin=0.8, yMax=1.2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("weighting.pdf") name = "CITo2Mu_Lam10TeVConLL" signal = Process(getattr(Signals, name)) sigHistRaw = deepcopy(signal.loadHistogramProjected(massPlot, 4)) sigHistWeightedRaw = deepcopy( signal.loadHistogramProjected(massPlotWeighted, 4)) sigHist = ROOT.TH1F("sigHist", "sigHist", len(binning) - 1, array('f', binning)) sigHistWeighted = ROOT.TH1F("sigHistWeighted", "sigHistWeighted", len(binning) - 1, array('f', binning)) sigHist.Sumw2() sigHistWeighted.Sumw2() for index, lower in enumerate(binning): if index < len(binning) - 1: sigHist.SetBinContent( index + 1, max( 0, sigHistRaw.Integral( sigHistRaw.FindBin(lower), sigHistRaw.FindBin(binning[index + 1] - 0.001)))) sigHistWeighted.SetBinContent( index + 1, max( 0, sigHistWeightedRaw.Integral( sigHistWeightedRaw.FindBin(lower), sigHistWeightedRaw.FindBin(binning[index + 1] - 0.001)))) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(400, 0, 3500, 3500, "; m [GeV]; Events") sigHist.Draw("samehist") sigHistWeighted.Draw("samehist") sigHistWeighted.SetLineColor(kRed) ratioPad.cd() ratioGraphs = ratios.RatioGraph(sigHist, sigHistWeighted, xMin=400, xMax=3500, title="Default/Weighted", yMin=0.8, yMax=1.2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("weightingBB.pdf") name = "CITo2Mu_Lam10TeVConLL" signal = Process(getattr(Signals, name)) sigHistRaw = deepcopy(signal.loadHistogramProjected(massPlot, 7)) sigHistWeightedRaw = deepcopy( signal.loadHistogramProjected(massPlotWeighted, 7)) sigHist = ROOT.TH1F("sigHist", "sigHist", len(binning) - 1, array('f', binning)) sigHistWeighted = ROOT.TH1F("sigHistWeighted", "sigHistWeighted", len(binning) - 1, array('f', binning)) sigHist.Sumw2() sigHistWeighted.Sumw2() for index, lower in enumerate(binning): if index < len(binning) - 1: sigHist.SetBinContent( index + 1, max( 0, sigHistRaw.Integral( sigHistRaw.FindBin(lower), sigHistRaw.FindBin(binning[index + 1] - 0.001)))) sigHistWeighted.SetBinContent( index + 1, max( 0, sigHistWeightedRaw.Integral( sigHistWeightedRaw.FindBin(lower), sigHistWeightedRaw.FindBin(binning[index + 1] - 0.001)))) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(400, 0, 3500, 3500, "; m [GeV]; Events") sigHist.Draw("samehist") sigHistWeighted.Draw("samehist") sigHistWeighted.SetLineColor(kRed) ratioPad.cd() ratioGraphs = ratios.RatioGraph(sigHist, sigHistWeighted, xMin=400, xMax=3500, title="Default/Weighted", yMin=0.8, yMax=1.2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("weightingBE.pdf") name = "CITo2Mu_Lam10TeVConLL" signal = Process(getattr(Signals, name)) sigHistRaw = deepcopy(signal.loadHistogramProjected(massPlot, 10)) sigHistWeightedRaw = deepcopy( signal.loadHistogramProjected(massPlotWeighted, 10)) sigHist = ROOT.TH1F("sigHist", "sigHist", len(binning) - 1, array('f', binning)) sigHistWeighted = ROOT.TH1F("sigHistWeighted", "sigHistWeighted", len(binning) - 1, array('f', binning)) sigHist.Sumw2() sigHistWeighted.Sumw2() for index, lower in enumerate(binning): if index < len(binning) - 1: sigHist.SetBinContent( index + 1, max( 0, sigHistRaw.Integral( sigHistRaw.FindBin(lower), sigHistRaw.FindBin(binning[index + 1] - 0.001)))) sigHistWeighted.SetBinContent( index + 1, max( 0, sigHistWeightedRaw.Integral( sigHistWeightedRaw.FindBin(lower), sigHistWeightedRaw.FindBin(binning[index + 1] - 0.001)))) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(400, 0, 3500, 3500, "; m [GeV]; Events") sigHist.Draw("samehist") sigHistWeighted.Draw("samehist") sigHistWeighted.SetLineColor(kRed) ratioPad.cd() ratioGraphs = ratios.RatioGraph(sigHist, sigHistWeighted, xMin=400, xMax=3500, title="Default/Weighted", yMin=0.8, yMax=1.2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("weightingEE.pdf")
def plotDataMC(args, plot): hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) args.ratio = True if args.ratio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() colors = createMyColors() data = Process(Data) data2016 = Process(Data2016) data2018 = Process(Data2018) legend = TLegend(0.55, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) #~ legend.SetNColumns(2) legendEta = TLegend(0.15, 0.75, 0.7, 0.9) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() plotPad.cd() plotPad.SetLogy(0) plotPad.SetLogy(0) logScale = plot.log if logScale == True: plotPad.SetLogy() datahist = data.loadHistogram(plot) datahist2016 = data2016.loadHistogram(plot) datahist2018 = data2018.loadHistogram(plot) datahist.Scale( datahist2018.Integral(datahist2018.FindBin(60), datahist2018.FindBin(120)) / datahist.Integral(datahist.FindBin(60), datahist.FindBin(120))) datahist2016.Scale( datahist2018.Integral(datahist2018.FindBin(60), datahist2018.FindBin(120)) / datahist2016.Integral(datahist2016.FindBin(60), datahist2016.FindBin(120))) bng = binning() #~ print bng datahist = datahist.Rebin( len(bng) - 1, 'hist_' + uuid.uuid4().hex, array('d', bng)) datahist2016 = datahist2016.Rebin( len(bng) - 1, 'hist_' + uuid.uuid4().hex, array('d', bng)) datahist2018 = datahist2018.Rebin( len(bng) - 1, 'hist_' + uuid.uuid4().hex, array('d', bng)) for i in range(0, datahist.GetNbinsX()): datahist.SetBinContent( i, datahist.GetBinContent(i) / datahist.GetBinWidth(i)) datahist.SetBinError(i, datahist.GetBinError(i) / datahist.GetBinWidth(i)) datahist2016.SetBinContent( i, datahist2016.GetBinContent(i) / datahist2016.GetBinWidth(i)) datahist2016.SetBinError( i, datahist2016.GetBinError(i) / datahist2016.GetBinWidth(i)) datahist2018.SetBinContent( i, datahist2018.GetBinContent(i) / datahist2018.GetBinWidth(i)) datahist2018.SetBinError( i, datahist2018.GetBinError(i) / datahist2018.GetBinWidth(i)) datahist2016.SetLineColor(ROOT.kBlue) datahist2016.SetMarkerColor(ROOT.kBlue) datahist.SetLineColor(ROOT.kRed) datahist.SetMarkerColor(ROOT.kRed) legend.AddEntry(datahist2016, "Data 2016 ReReco", "pe") legendEta.AddEntry(datahist2016, "Data 2016 ReReco", "pe") legend.AddEntry(datahist, "Data 2017 ReReco", "pe") legendEta.AddEntry(datahist, "Data 2017 ReReco", "pe") legend.AddEntry(datahist2018, "Data 2018 ReReco + PromptReco", "pe") legendEta.AddEntry(datahist2018, "Data 2018 ReReco + PromptReco", "pe") yMax = datahist.GetBinContent(datahist.GetMaximumBin()) yMin = 0.1 xMax = datahist.GetXaxis().GetXmax() xMin = datahist.GetXaxis().GetXmin() if plot.yMax == None: if logScale: yMax = yMax * 10 else: yMax = yMax * 1.5 else: yMax = plot.yMax if not plot.yMin == None: yMin = plot.yMin if not plot.xMin == None: xMin = plot.xMin if not plot.xMax == None: xMax = plot.xMax yMin = 0.00001 plotPad.DrawFrame(xMin, yMin, xMax, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) plotPad.SetLogx() datahist2016.Draw("samepe") datahist.Draw("samepe") datahist2018.Draw("samepe") legend.Draw() print datahist.Integral() latex.DrawLatex(0.95, 0.96, "36.3 - 52.7 fb^{-1} (13 TeV)") yLabelPos = 0.85 cmsExtra = "Preliminary" #~ if not args.data: #~ cmsExtra = "#splitline{Private Work}{Simulation}" #~ yLabelPos = 0.82 latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if args.ratio: try: ratioPad.cd() ratioPad.SetLogx() except AttributeError: print "Plot fails. Look up in errs/failedPlots.txt" outFile = open("errs/failedPlots.txt", "a") outFile.write('%s\n' % plot.filename % ("_" + run.label + "_" + dilepton)) outFile.close() plot.cuts = baseCut return 1 ratioGraphs2 = ratios.RatioGraph(datahist2016, datahist2018, xMin=xMin, xMax=xMax, title="Ratio", yMin=0.5, yMax=1.5, ndivisions=10, color=datahist2016.GetLineColor(), adaptiveBinning=100000000000) ratioGraphs2.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ratioGraphs = ratios.RatioGraph(datahist, datahist2018, xMin=xMin, xMax=xMax, title="Ratio", yMin=0.5, yMax=1.5, ndivisions=10, color=datahist.GetLineColor(), adaptiveBinning=100000000000) ratioGraphs.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) if not os.path.exists("plots"): os.makedirs("plots") hCanvas.Print("plots/" + plot.fileName + ".pdf")
def closure(fileName, opts, scale): ################################## fakeRate = 0.0084 fakeRateError = 0.0006 # stat # correct fake rate, if it is estimated with yutaros method fakeRateError = fakeRateError / (1 - fakeRate)**2 fakeRate = fakeRate / (1 - fakeRate) ################################## # dataset name is from beginning till first '_' datasetAffix = re.match(".*slim([^_]*)_.*", fileName).groups()[0] label, unit, binning = readAxisConf(opts.plot) commonCut = "photon[0].pt>80 && @photon.size() && met>100" gTree = readTree(fileName, "photonTree").CopyTree(commonCut) eTree = readTree(fileName, "photonElectronTree").CopyTree(commonCut) if opts.plot == "nVertex": nBins = 6 firstBin = 3 lastBin = 35 else: nBins = 20 firstBin = None lastBin = None recE = getHisto(eTree, opts.plot, color=2, weight="1", nBins=nBins, firstBin=firstBin, lastBin=lastBin) recE.SetFillColor(recE.GetLineColor()) recE.SetFillStyle(3254) recE = applyFakeRate(recE, fakeRate, fakeRateError) gamma = getHisto(gTree, opts.plot, color=1, weight="1", cut="!photon[0].isGenPhoton()", nBins=nBins, firstBin=firstBin, lastBin=lastBin) for h in [gamma, recE]: h.SetMarkerSize(0) h.Scale(scale) if opts.alternativeStatistics: #error_hist = extractHisto( Dataset( fileName, "photonTree", "weight*(1)","name", 1), opts.plot ) scale_for_points = 3.66 # mean weight for w-jets photonTree for bin in range(gamma.GetNbinsX() + 1): #gamma.SetBinError( bin, error_hist.GetBinError( bin ) ) if not gamma.GetBinContent(bin) and bin > 10: gamma.SetBinError( bin, 1.14 * scale_for_points / gamma.GetBinWidth(bin)) multihisto = Multihisto() multihisto.leg.SetHeader(datasetAffix) multihisto.addHisto(recE, "e#upoint#tildef_{e#rightarrow#gamma}", draw="e2") multihisto.addHisto(gamma, "#gamma", draw="e0 hist") can = ROOT.TCanvas() hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1) hPad.cd() multihisto.Draw() ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2) ratioPad.cd() ratioPad.SetLogy(0) ratioGraph = ratios.RatioGraph(gamma, recE) ratioGraph.draw(ROOT.gPad, yMin=0.5, yMax=1.5, adaptiveBinning=False, errors="yx") ratioGraph.hAxis.SetYTitle("#gamma/(e#upoint#tilde{f})") if opts.alternativeStatistics: for point in range(ratioGraph.graph.GetN()): if not ratioGraph.graph.GetErrorY(point): # read out point+1, since histograms start with bin 1 ratioGraph.graph.SetPointEYhigh( point, ratioGraph.numerator.GetBinError(point + 11) / ratioGraph.denominator.GetBinContent(point + 11)) ratioGraph.graph.Draw("same p e1") # draw systematic uncertanty in ratio: syst = recE.Clone("hist_ratio_syst") for bin in range(syst.GetNbinsX() + 1): if syst.GetBinContent(bin): syst.SetBinError(bin, syst.GetBinError(bin) / syst.GetBinContent(bin)) syst.SetBinContent(bin, 1) syst.Draw("same e2") can.cd() hPad.Draw() ratioPad.Draw() can.SaveAs("plots/%s_%s_%s.pdf" % (datasetAffix, opts.plot.replace(".", ""), opts.save)) # avoid segmentation violation due to python garbage collector ROOT.SetOwnership(hPad, False) ROOT.SetOwnership(ratioPad, False)
def drawRatioPlots(self): if self.hasRatio or self.hasEfficiency or self.hasResidual: self.ratioPad.cd() if self.hasRatio: self.ratioGraphs = [] self.plotPad.Update() # So that Uxmin and Uxmax are retrievable for nominator, denominator, color, markerstyle in self.ratioPairs: self.ratioGraphs.append(ratios.RatioGraph(nominator, denominator, xMin=self.plotPad.GetUxmin(), xMax=self.plotPad.GetUxmax(),title=self.ratioLabel,yMin=self.ratioMin,yMax=self.ratioMax,ndivisions=10,color=color, adaptiveBinning=1000 )) for err in self.ratioErrsSize: self.ratioGraphs[err[5]].addErrorBySize(err[0],err[1],err[2],err[3],err[4]) for err in self.ratioErrsHist: self.ratioGraphs[err[5]].addErrorByHistograms(err[0],err[1],err[2],err[3],err[4]) for number,graph in enumerate(self.ratioGraphs): if number == 0: graph.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) if self.nDivX == None: graph.hAxis.GetXaxis().SetNdivisions(self.primaryPlot[0].GetXaxis().GetNdivisions()) else: graph.hAxis.GetXaxis().SetNdivisions(self.nDivX) graph.hAxis.GetYaxis().SetNdivisions(408) if self.ratioLabelSize !=None: graph.hAxis.GetYaxis().SetLabelSize(self.ratioLabelSize) if self.ratioTitleSize !=None: graph.hAxis.GetYaxis().SetTitleSize(self.ratioTitleSize) if self.ratioTitleOffset !=None: graph.hAxis.GetYaxis().SetTitleOffset(self.ratioTitleOffset) graph.hAxis.GetYaxis().CenterTitle() else: graph.draw(self.ratioPad,False,False,True,chi2Pos=0.8) graph.graph.SetMarkerStyle(markerstyle) elif self.hasEfficiency: self.ratioGraphs = [] self.plotPad.Update() # So that Uxmin and Uxmax are retrievable self.hAxis = ROOT.TH2F("hAxis%d"%(countNumbersUp()), "", 20, self.plotPad.GetUxmin(), self.plotPad.GetUxmax(), 10, self.efficiencyMin, self.efficiencyMax) self.hAxis.GetYaxis().SetNdivisions(408) self.hAxis.GetYaxis().SetTitleOffset(0.4) self.hAxis.GetYaxis().SetTitleSize(0.15) self.hAxis.GetXaxis().SetLabelSize(0.0) self.hAxis.GetYaxis().SetLabelSize(0.15) if self.nDivX == None: self.hAxis.GetXaxis().SetNdivisions(self.primaryPlot[0].GetXaxis().GetNdivisions()) else: self.hAxis.GetXaxis().SetNdivisions(self.nDivX) self.hAxis.GetYaxis().SetTitle(self.efficiencyLabel) self.hAxis.Draw("AXIS") for nominator, denominator, color, markerstyle in self.ratioPairs: tmp = ROOT.TGraphAsymmErrors(nominator,denominator, self.efficiencyOption) tmp.SetMarkerColor(color) tmp.SetLineColor(color) tmp.SetMarkerStyle(markerstyle) self.ratioGraphs.append(tmp) self.ratioGraphs[len(self.ratioGraphs)-1].Draw("same P") elif self.hasResidual: low = self.residualRangeLow if (self.residualRangeLow != None) else -self.residualRangeUp up = self.residualRangeUp minRes = 100000000000.0 maxRes = -100000000000.0 self.plotPad.Update() # So that Uxmin and Uxmax are retrievable self.hAxis = ROOT.TH2F("hAxis%d"%(countNumbersUp()), "", 20, self.plotPad.GetUxmin(), self.plotPad.GetUxmax(), 10, low, up) self.hAxis.GetYaxis().SetNdivisions(408) self.hAxis.GetYaxis().SetTitleOffset(0.4) self.hAxis.GetYaxis().SetTitleSize(0.15) self.hAxis.GetXaxis().SetLabelSize(0.0) self.hAxis.GetYaxis().SetLabelSize(0.15) if self.nDivX == None: self.hAxis.GetXaxis().SetNdivisions(self.primaryPlot[0].GetXaxis().GetNdivisions()) else: self.hAxis.GetXaxis().SetNdivisions(self.nDivX) self.hAxis.GetYaxis().SetTitle(self.residualLabel) self.hAxis.Draw("AXIS") if self.residualZeroLineDo: self.residualZeroLine = ROOT.TLine(self.plotPad.GetUxmin(),0,self.plotPad.GetUxmax(),0) self.residualZeroLine.SetLineColor(self.residualZeroLineColor) self.residualZeroLine.SetLineWidth(self.residualZeroLineWidth) self.residualZeroLine.SetLineStyle(self.residualZeroLineStyle) self.residualZeroLine.Draw("same") self.residualGraphs = [] for h1, h2, resRange, color, markerstyle, markersize, fillcolor, errList, options in self.residualPlots: tmp = ROOT.TGraphAsymmErrors() tmp.SetMarkerColor(color) tmp.SetMarkerSize(markersize) tmp.SetLineColor(color) tmp.SetFillColor(fillcolor) tmp.SetMarkerStyle(markerstyle) self.residualGraphs.append(tmp) xpos = [] minu = [] subt = [] minu_err = [] subt_err = [] if h1.InheritsFrom(ROOT.TH1.Class()): slope = 0 for i in range(1, h1.GetNbinsX()+1): xPos = h1.GetBinCenter(i) if resRange != None: if xPos > resRange[1] or xPos < resRange[0]: #tmp.SetPoint(i, xPos, 0) #tmp.SetPointError(i, 0, 0, 0, 0) continue minuent = h1.GetBinContent(i) minuent_err = (h1.GetBinErrorLow(i), h1.GetBinErrorUp(i)) if h2.InheritsFrom(ROOT.TH1.Class()): subtrahent = h2.GetBinContent(h2.FindBin(xPos)) subtrahent_err = (h2.GetBinErrorLow(h2.FindBin(xPos)), h2.GetBinErrorUp(h2.FindBin(xPos))) elif h2.InheritsFrom(ROOT.TF1.Class()): subtrahent = h2.Eval(xPos) slope = h2.Derivative(xPos) subtrahent_err = (0,0) else: print "Error in drawResiduals: Invalid type of subtrahent", h1 exit() xpos.append(xPos) minu.append(minuent) subt.append(subtrahent) minu_err.append(minuent_err) subt_err.append(subtrahent_err) elif h1.InheritsFrom(ROOT.TGraphErrors.Class()): for i in range(h1.GetN()): xPos = h1.GetX()[i] if resRange != None: if xPos > resRange[1] or xPos < resRange[0]: #tmp.SetPoint(i, xPos, 0) #tmp.SetPointError(i, 0, 0, 0, 0) continue minuent = h1.GetY()[i] if h1.InheritsFrom(ROOT.TGraphAsymmErrors.Class()): minuent_err = (h1.GetEYlow()[i], h1.GetEYhigh()[i]) else: minuent_err = (h1.GetEY()[i], h1.GetEY()[i]) if h2.InheritsFrom(ROOT.TH1.Class()): subtrahent = h2.GetBinContent(h2.FindBin(xPos)) subtrahent_err = h2.GetBinError(h2.FindBin(xPos)) elif h2.InheritsFrom(ROOT.TGraphErrors.Class()): subtrahent = h2.GetY()[i] if h2.InheritsFrom(ROOT.TGraphAsymmErrors.Class()): subtrahent_err = (h2.GetEYlow()[i], h2.GetEYhigh()[i]) else: subtrahent_err = (h2.GetEY()[i], h2.GetEY()[i]) elif h2.InheritsFrom(ROOT.TF1.Class()): subtrahent = h2.Eval(xPos) subtrahent_err = (0,0) xpos.append(xPos) minu.append(minuent) subt.append(subtrahent) minu_err.append(minuent_err) subt_err.append(subtrahent_err) else: print "plotTemplate Error: in drawResiduals: Invalid type of minuent ", h2 exit() for i, (xPos, minuent, subtrahent, minuent_err, subtrahent_err) in enumerate(zip(xpos, minu, subt, minu_err, subt_err)): residual = minuent - subtrahent if residual >= 0: i_m = 0 i_s = 1 else: i_m = 1 i_s = 0 residual_err = (minuent_err[i_m]**2 + subtrahent_err[i_s]**2 )**0.5 if errList != None: residual_err = errList[i] if "P" in options: if residual_err > 0: residual /= residual_err residual_err = 1 else: residual = 0 residual_err = 0 if "-" in options: residual = -residual if residual < minRes: minRes = residual if residual > maxRes: maxRes = residual tmp.SetPoint(i, xPos, residual) tmp.SetPointError(i, 0, 0, residual_err, residual_err) if "H" in options: tmp.Draw("same BX") else: tmp.Draw("same P") if self.residualRangeMode.upper() == "AUTO": boundaries = max(abs(minRes), maxRes) boundLow = -boundaries * self.residualRangeScale boundUp = boundaries * self.residualRangeScale self.hAxis.GetYaxis().SetLimits(boundLow, boundUp) elif self.residualRangeMode.upper() == "AUTOASYMM": boundLow = minRes * self.residualRangeScale boundUp = maxRes * self.residualRangeScale self.hAxis.GetYaxis().SetLimits(boundLow, boundUp)
def plotDataMC(datahist,mchist,usedata, label1, label2,name,filename): hCanvas = TCanvas("hCanvas", "Distribution", 800,800) if usedata==True: plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw("hist") ratioPad.Draw("hist") plotPad.cd() else: plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() colors = createMyColors() legend = TLegend(0.55, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legendEta = TLegend(0.45, 0.75, 0.925, 0.925) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) legendEta.SetNColumns(2) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] legendHistData = ROOT.TH1F() category = ROOT.TLatex() category.SetNDC(True) category.SetTextSize(0.04) if usedata==True: legend.AddEntry(legendHistData,label1,"pe") legendEta.AddEntry(legendHistData,label1,"pe") #process.label = process.label.replace("#mu^{+}#mu^{-}","e^{+^{*}}e^{-}") temphist = ROOT.TH1F() temphist.SetFillColor(3) legendHists.append(temphist.Clone) #legend.AddEntry(temphist,label2,"l") #legendEta.AddEntry(temphist,process.label,"f") # Modify plot pad information nEvents=-1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() # Luminosity information plotPad.cd() plotPad.SetLogy(0) plotPad.SetLogy() if usedata==True: yMax = datahist.GetBinContent(datahist.GetMaximumBin())*1000 yMin = 0.00000001 xMax = datahist.GetXaxis().GetXmax() xMin = datahist.GetXaxis().GetXmin() else: yMax = mchist.GetBinContent(datahist.GetMaximumBin()) yMin = 0.00000001 xMax = mchist.GetXaxis().GetXmax() xMin = mchist.GetXaxis().GetXmin() yMax = yMax*10000 if name.find("dimuon")!=-1: plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{#mu#mu}[GeV] ;Events/GeV") else: plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; m_{ee}[GeV] ;Events/GeV") # Draw signal information # Draw background from stack mchist.SetFillColor(0) mchist.SetLineColor(2) legend.AddEntry(mchist,label2,"l") mchist.Draw("samehist") # Draw data datahist.SetMinimum(0.0001) if usedata==True: datahist.SetMarkerStyle(8) datahist.Draw("samepehist") # Draw legend legend.Draw() plotPad.SetLogx() latex.DrawLatex(0.95,0.96,"13 TeV") yLabelPos = 0.85 cmsExtra = "Preliminary" if not usedata==True: cmsExtra = "#splitline{Preliminary}{Simulation}" yLabelPos = 0.82 latexCMS.DrawLatex(0.19,0.89,"CMS") category.DrawLatex(0.3,0.7,name) latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra)) #~ print datahist.Integral() if usedata==True: try: ratioPad.cd() ratioPad.SetLogx() except AttributeError: print ("Plot fails. Look up in errs/failedPlots.txt") outFile =open("errs/failedPlots.txt","a") outFile.write('%s\n'%plot.filename%("_"+run.label+"_"+dilepton)) outFile.close() #plot.cuts=baseCut return 1 ratioGraphs = ratios.RatioGraph(datahist,mchist, xMin=xMin, xMax=xMax,title="R_{mumu}/R_{ee}",yMin=0,yMax=2.0,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000000000000,labelSize=0.125,pull=False) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if usedata==True: ratioPad.RedrawAxis() if not os.path.exists("plots"): os.makedirs("plots") hCanvas.Print("plots/%s.pdf"%filename)
def plotsingle(model, heli, lambdaT): # read in histograms signalHists = getMassDistro(model, heli, lambdaT, isMuon) for histi in signalHists: histi.Scale(0.02) # read in DY histograms dyHist = getMassDistroDY(isMuon) dyHist.Scale(0.02) # set up canvas canv = TCanvas("c1", "c1", 800, 800) 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.SetLogy() plotPad.DrawFrame(120, 1e-7, 7000, 2.5e3, ";mass [GeV];Events / 50 GeV") # plotting for (i, sigHist) in enumerate(signalHists): sigHist.SetLineColor(i + 2) sigHist.Draw("histsame") dyHist.Draw("histsame") # draw CMS prelim 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) latexCMSlepton = "ee" if isMuon: latexCMSlepton = "#mu#mu" latex.DrawLatex(0.95, 0.96, "35.9 fb^{-1} (13 TeV, %s)" % latexCMSlepton) cmsExtra = "#splitline{Private Work}{Simulation}" 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)) # draw legend leg = TLegend(0.4, 0.71, 0.94, 0.92, "", "brNDC") leg.SetFillColor(10) leg.SetFillStyle(0) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) if resolution: leg.AddEntry(dyHist, "Drell-Yan smeared (#Lambda = %d)" % lambdaT, "l") for (i, helicity) in enumerate(heli): leg.AddEntry( signalHists[i], "Drell-Yan x %s%s smeared (#Lambda = %d)" % (model, helicity, lambdaT), "l") #leg.AddEntry(signalHists[1],"Drell-Yan x %s Des smeared (#Lambda = %d)"%(model, lambdaT),"l") else: leg.AddEntry(dyHist, "Drell-Yan (#Lambda = %d)" % lambdaT, "l") for (i, helicity) in enumerate(heli): leg.AddEntry( signalHists[i], "Drell-Yan x %s%s (#Lambda = %d)" % (model, helicity, lambdaT), "l") #leg.AddEntry(signalHists[1],"Drell-Yan x %s Des (#Lambda = %d)"%(model, lambdaT),"l") leg.Draw("same") # draw ratio pad ratioPad.cd() if model == "ADD": ratio = ratios.RatioGraph(signalHists[0], signalHists[1], 120, 7000, title="S+B Con / S+B Des", yMin=0.5, yMax=2.0, ndivisions=10, color=signalHists[0].GetLineColor(), adaptiveBinning=0.25) ratio.draw(gPad, True, False, True, chi2Pos=0.7) else: # model == "CI": ratio = ratios.RatioGraph(signalHists[0], signalHists[3], 120, 7000, title="ConLL / DesLL", yMin=0.5, yMax=2.0, ndivisions=10, color=signalHists[0].GetLineColor(), adaptiveBinning=0.25) ratio.draw(gPad, True, False, True, chi2Pos=0.7) # save graphs if resolution: if isMuon: canv.Print("rawDataPlots/%s_MassHist_LambdaT%d_Muon.pdf" % (model, lambdaT)) else: canv.Print("rawDataPlots/%s_MassHist_LambdaT%d_Electron.pdf" % (model, lambdaT)) else: canv.Print("rawDataPlots/%s_MassHist_LambdaT%d.pdf" % (model, lambdaT))
def plotDataMC(args, plot): hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) if args.ratio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() # Data load processes colors = createMyColors() if args.use2016: data = Process(Data2016, normalized=True) elif args.use2018: data = Process(Data2018, normalized=True) elif args.useRun2: data2016 = Process(Data2016, normalized=True) data2017 = Process(Data, normalized=True) data2018 = Process(Data2018, normalized=True) else: data = Process(Data, normalized=True) eventCounts = totalNumberOfGeneratedEvents(path, plot.muon) negWeights = negWeightFractions(path, plot.muon) #print negWeights # Background load processes backgrounds = copy(args.backgrounds) if plot.useJets: if "Wjets" in backgrounds: backgrounds.remove("Wjets") if not "Jets" in backgrounds: backgrounds.insert(0, "Jets") if args.use2016 and not plot.muon and "Other" in backgrounds: backgrounds.remove("Other") backgrounds.insert(1, "OtherEle") processes = [] processes2016 = [] processes2017 = [] processes2018 = [] for background in backgrounds: if args.use2016: if background == "Jets": processes.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights, normalized=True)) else: processes.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights)) elif args.use2018: if background == "Jets": processes.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights, normalized=True)) else: processes.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights)) elif args.useRun2: if background == "Jets": processes.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights, normalized=True)) processes2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights, normalized=True)) processes2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) processes2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights, normalized=True)) elif background == "Other" and not plot.muon: processes.append( Process(getattr(Backgrounds2016, "OtherEle"), eventCounts, negWeights)) processes2016.append( Process(getattr(Backgrounds2016, "OtherEle"), eventCounts, negWeights)) processes2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) processes2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights)) else: processes.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights)) processes2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights)) processes2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) processes2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights)) else: if background == "Jets": processes.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) else: processes.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) # Signal load processes signals = [] signals2016 = [] signals2017 = [] signals2018 = [] for signal in args.signals: if args.use2016: if args.ADD: signals.append( Process(getattr(Signals2016ADD, signal), eventCounts, negWeights)) else: signals.append( Process(getattr(Signals2016, signal), eventCounts, negWeights)) elif args.use2018: if args.ADD: signals.append( Process(getattr(Signals2018ADD, signal), eventCounts, negWeights)) else: signals.append( Process(getattr(Signals2018, signal), eventCounts, negWeights)) elif args.useRun2: if args.ADD: signals.append( Process(getattr(Signals2016ADD, signal), eventCounts, negWeights)) signals2016.append( Process(getattr(Signals2016ADD, signal), eventCounts, negWeights)) signals2017.append( Process(getattr(SignalsADD, signal), eventCounts, negWeights)) signals2018.append( Process(getattr(Signals2018ADD, signal), eventCounts, negWeights)) else: signals.append( Process(getattr(Signals2016, signal), eventCounts, negWeights)) signals2016.append( Process(getattr(Signals2016, signal), eventCounts, negWeights)) signals2017.append( Process(getattr(Signals, signal), eventCounts, negWeights)) signals2018.append( Process(getattr(Signals2018, signal), eventCounts, negWeights)) else: if args.ADD: signals.append( Process(getattr(SignalsADD, signal), eventCounts, negWeights)) else: signals.append( Process(getattr(Signals, signal), eventCounts, negWeights)) legend = TLegend(0.55, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legendEta = TLegend(0.45, 0.75, 0.925, 0.925) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) legendEta.SetNColumns(2) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] # Modify legend information legendHistData = ROOT.TH1F() if args.data: legend.AddEntry(legendHistData, "Data", "pe") legendEta.AddEntry(legendHistData, "Data", "pe") for process in reversed(processes): if not plot.muon and "#mu^{+}#mu^{-}" in process.label: process.label = process.label.replace("#mu^{+}#mu^{-}", "e^{+^{*}}e^{-}") temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") legendEta.AddEntry(temphist, process.label, "f") if args.signals != 0: processesWithSignal = [] for process in processes: processesWithSignal.append(process) for Signal in signals: processesWithSignal.append(Signal) temphist = ROOT.TH1F() temphist.SetFillColor(Signal.theColor) temphist.SetLineColor(Signal.theLineColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, Signal.label, "l") legendEta.AddEntry(temphist, Signal.label, "l") # Modify plot pad information nEvents = -1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() # Luminosity information plotPad.cd() plotPad.SetLogy(0) logScale = plot.log if logScale == True: plotPad.SetLogy() if args.use2016: lumi = 35.9 * 1000 if plot.muon: lumi = 36294.6 elif args.use2018: lumi = 59401 if plot.muon: lumi = 61298.775231718995 elif args.useRun2: lumi2016 = 35.9 * 1000 lumi2017 = 41.529 * 1000 lumi2018 = 59401 if plot.muon: lumi2016 = 36294.6 lumi2018 = 61298.775231718995 lumi2017 = 42079.880396 else: lumi = 41.529 * 1000 if plot.muon: lumi = 42079.880396 if args.use2016: zScaleFac = zScale2016["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale2016["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale2016["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale2016["electrons"][2] else: zScaleFac = zScale2016["electrons"][0] elif args.use2018: zScaleFac = zScale2018["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale2018["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale2018["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale2018["electrons"][2] else: zScaleFac = zScale2018["electrons"][0] elif args.useRun2: zScaleFac2016 = zScale2016["muons"] zScaleFac2017 = zScale["muons"] zScaleFac2018 = zScale2018["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac2016 = zScale2016["electrons"][0] zScaleFac2017 = zScale["electrons"][0] zScaleFac2018 = zScale2018["electrons"][0] elif "bb" in plot.histName: zScaleFac2016 = zScale2016["electrons"][1] zScaleFac2017 = zScale["electrons"][1] zScaleFac2018 = zScale2018["electrons"][1] elif "be" in plot.histName: zScaleFac2016 = zScale2016["electrons"][2] zScaleFac2017 = zScale["electrons"][2] zScaleFac2018 = zScale2018["electrons"][2] else: zScaleFac2016 = zScale2016["electrons"][0] zScaleFac2017 = zScale["electrons"][0] zScaleFac2018 = zScale2018["electrons"][0] else: zScaleFac = zScale["muons"] if not plot.muon: if "bbbe" in plot.histName: zScaleFac = zScale["electrons"][0] elif "bb" in plot.histName: zScaleFac = zScale["electrons"][1] elif "be" in plot.histName: zScaleFac = zScale["electrons"][2] else: zScaleFac = zScale["electrons"][0] # Data and background loading if plot.plot2D: if args.useRun2: datahist = data2016.loadHistogramProjected(plot, lumi2016, zScaleFac2016) datahist.Add( data2017.loadHistogramProjected(plot, lumi2017, zScaleFac2017)) datahist.Add( data2016.loadHistogramProjected(plot, lumi2018, zScaleFac2018)) stack = TheStack2DRun2( [processes2016, processes2017, processes2018], [lumi2016, lumi2017, lumi2018], plot, [zScaleFac2016, zScaleFac2017, zScaleFac2018]) else: datahist = data.loadHistogramProjected(plot, lumi, zScaleFac) stack = TheStack2D(processes, lumi, plot, zScaleFac) else: if args.useRun2: datahist = data2016.loadHistogram(plot, lumi2016, zScaleFac2016) datahist.Add(data2017.loadHistogram(plot, lumi2017, zScaleFac2017)) datahist.Add(data2018.loadHistogram(plot, lumi2018, zScaleFac2018)) stack = TheStackRun2([processes2016, processes2017, processes2018], [lumi2016, lumi2017, lumi2018], plot, [zScaleFac2016, zScaleFac2017, zScaleFac2018]) else: datahist = data.loadHistogram(plot, lumi, zScaleFac) stack = TheStack(processes, lumi, plot, zScaleFac) if args.data: yMax = datahist.GetBinContent(datahist.GetMaximumBin()) if "Mass" in plot.fileName: yMin = 0.00001 else: yMin = 0.01 xMax = datahist.GetXaxis().GetXmax() xMin = datahist.GetXaxis().GetXmin() else: yMax = stack.theHistogram.GetBinContent(datahist.GetMaximumBin()) yMin = 0.01 xMax = stack.theHistogram.GetXaxis().GetXmax() xMin = stack.theHistogram.GetXaxis().GetXmin() if plot.yMax == None: if logScale: yMax = yMax * 10000 else: yMax = yMax * 1.5 else: yMax = plot.yMax if "Mass" in plot.fileName: yMax = 20000000 if not plot.yMin == None: yMin = plot.yMin if not plot.xMin == None: xMin = plot.xMin if not plot.xMax == None: xMax = plot.xMax #if args.ADD and args.use2016: # xMin = 1700 # xMax = 4000 # yMax = 1.0 if "CosThetaStarBBM1800" in plot.fileName: yMax = 3 plotPad.DrawFrame(xMin, yMin, xMax, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) drawStack = stack #~ print datahist.Integral(datahist.FindBin(60),datahist.FindBin(120))/drawStack.theHistogram.Integral(drawStack.theHistogram.FindBin(60),drawStack.theHistogram.FindBin(120)) #~ low = 900 #~ high = 1300 #~ print datahist.Integral(datahist.FindBin(low),datahist.FindBin(high)) #~ print drawStack.theHistogram.Integral(datahist.FindBin(low),datahist.FindBin(high)) # Draw signal information if len(args.signals) != 0: if args.useRun2: signalhists = [] for index, Signal in enumerate(signals2016): if plot.plot2D: # plot collins-soper angle signalhist = Signal.loadHistogramProjected( plot, lumi2016, zScaleFac2016) signalhist.Add(signals2017[index].loadHistogramProjected( plot, lumi2017, zScaleFac2017)) signalhist.Add(signals2018[index].loadHistogramProjected( plot, lumi2018, zScaleFac2018)) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove("DrellYan") signalProcesses2016 = [] signalProcesses2017 = [] signalProcesses2018 = [] for background in signalBackgrounds: if background == "Jets": signalProcesses2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights, normalized=True)) signalProcesses2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) signalProcesses2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights, normalized=True)) else: signalProcesses2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights)) signalProcesses2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) signalProcesses2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights)) signalStack = TheStack2DRun2( [ signalProcesses2016, signalProcesses2017, signalProcesses2018 ], [lumi2016, lumi2017, lumi2018], plot, [zScaleFac2016, zScaleFac2017, zScaleFac2018]) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.1) signalhist.Draw("samehist") signalhists.append(signalhist) else: signalhist = Signal.loadHistogram(plot, lumi2016, zScaleFac2016) signalhist.Add(signals2017[index].loadHistogram( plot, lumi2017, zScaleFac2017)) signalhist.Add(signals2018[index].loadHistogram( plot, lumi2018, zScaleFac2018)) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove( "DrellYan") # signalBackgrounds = ["Jets", "Other"] signalProcesses2016 = [] signalProcesses2017 = [] signalProcesses2018 = [] for background in signalBackgrounds: if background == "Jets": signalProcesses2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights, normalized=True)) signalProcesses2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) if plot.muon: signalProcesses2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights, normalized=True)) else: signalProcesses2018.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) else: signalProcesses2016.append( Process(getattr(Backgrounds2016, background), eventCounts, negWeights)) signalProcesses2017.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) signalProcesses2018.append( Process(getattr(Backgrounds2018, background), eventCounts, negWeights)) signalStack = TheStackRun2( [ signalProcesses2016, signalProcesses2017, signalProcesses2018 ], [lumi2016, lumi2017, lumi2018], plot, [zScaleFac2016, zScaleFac2017, zScaleFac2018]) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.0001) signalhist.Draw("samehist") signalhists.append(signalhist) else: signalhists = [] for Signal in signals: if plot.plot2D: # plot collins-soper angle signalhist = Signal.loadHistogramProjected( plot, lumi, zScaleFac) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove("DrellYan") signalProcesses = [] for background in signalBackgrounds: if background == "Jets": signalProcesses.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) else: signalProcesses.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) signalStack = TheStack2D(signalProcesses, lumi, plot, zScaleFac) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.1) signalhist.Draw("samehist") signalhists.append(signalhist) else: signalhist = Signal.loadHistogram(plot, lumi, zScaleFac) signalhist.SetLineWidth(2) signalBackgrounds = deepcopy(backgrounds) signalBackgrounds.remove( "DrellYan") # signalBackgrounds = ["Jets", "Other"] signalProcesses = [] for background in signalBackgrounds: if background == "Jets": signalProcesses.append( Process(getattr(Backgrounds, background), eventCounts, negWeights, normalized=True)) else: signalProcesses.append( Process(getattr(Backgrounds, background), eventCounts, negWeights)) signalStack = TheStack(signalProcesses, lumi, plot, zScaleFac) signalhist.Add(signalStack.theHistogram) signalhist.SetMinimum(0.0001) signalhist.Draw("samehist") signalhists.append(signalhist) # Draw background from stack drawStack.theStack.Draw("samehist") # Draw data datahist.SetMinimum(0.0001) if args.data: datahist.Draw("samep") # Draw legend if "Eta" in plot.fileName or "CosTheta" in plot.fileName: legendEta.Draw() else: legend.Draw() plotPad.SetLogx(plot.logX) if args.useRun2: if plot.muon: latex.DrawLatex(0.95, 0.96, "139.7 fb^{-1} (13 TeV)") else: latex.DrawLatex(0.95, 0.96, "136.8 fb^{-1} (13 TeV)") else: latex.DrawLatex(0.95, 0.96, "%.1f fb^{-1} (13 TeV)" % (float(lumi) / 1000, )) yLabelPos = 0.85 cmsExtra = "Preliminary" if not args.data: cmsExtra = "#splitline{Preliminary}{Simulation}" yLabelPos = 0.82 latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) #~ print datahist.Integral() if args.ratio: try: ratioPad.cd() ratioPad.SetLogx(plot.logX) except AttributeError: print("Plot fails. Look up in errs/failedPlots.txt") outFile = open("errs/failedPlots.txt", "a") outFile.write('%s\n' % plot.filename % ("_" + run.label + "_" + dilepton)) outFile.close() plot.cuts = baseCut return 1 ratioGraphs = ratios.RatioGraph(datahist, drawStack.theHistogram, xMin=xMin, xMax=xMax, title="(Data - Bkg) / Bkg", yMin=-1.0, yMax=1.0, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=10000000000000, labelSize=0.125, pull=True) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if args.ratio: ratioPad.RedrawAxis() if not os.path.exists("plots"): os.makedirs("plots") if args.use2016: hCanvas.Print("plots/" + plot.fileName + "_2016.pdf") elif args.use2018: hCanvas.Print("plots/" + plot.fileName + "_2018.pdf") elif args.useRun2: hCanvas.Print("plots/" + plot.fileName + "_Run2.pdf") else: hCanvas.Print("plots/" + plot.fileName + "_2017.pdf")
def makePlot(sfHist,ofHist,selection,plot,runRange,region,cmsExtra,combination,dyHist=None): colors = createMyColors() hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() ROOT.gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: yMax = yMax*1.35 else: yMax = plot.yMax yMax = 15 plotPad.DrawFrame(plot.firstBin,0,plot.lastBin, yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis)) bkgHist = ofHist.Clone("bkgHist") if dyHist is not None: bkgHist.Add(dyHist) sfHist.SetMarkerStyle(20) bkgHist.SetLineColor(ROOT.kBlue+3) bkgHist.SetLineWidth(2) dyHist.SetLineColor(ROOT.kGreen+3) dyHist.SetFillColor(ROOT.kGreen+3) dyHist.SetFillStyle(3002) 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} (8 TeV)"%"19.4") 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)) if combination == "SF": rSFOFErr = getattr(rSFOF,region).err elif combination == "EE": rSFOFErr = getattr(rEEOF,region).err elif combination == "MM": rSFOFErr = getattr(rMMOF,region).err errGraph, histUp, histDown = getErrHist(plot,combination,region,ofHist,dyHist,rSFOFErr) errGraph.SetFillColor(myColors["MyBlue"]) errGraph.SetFillStyle(3001) #~ errGraph.SetLineColor(myColors["MyDarkBlue"]) #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"]) errGraph.Draw("SAME02") bkgHist.Draw("samehist") dyHist.Draw("samehist") sfHist.Draw("samepe") lines = getLines(0, sfHist.GetBinContent(sfHist.GetMaximumBin())+10,xPos=[mllBins.lowMass.high,mllBins.onZ.low,mllBins.onZ.high, mllBins.highMass.low ]) for line in lines: line.Draw() leg = TLegend(0.62, 0.51, 0.89, 0.92,"","brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F,kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if region == "inclusive": leg.AddEntry(legendHistDing,"ATLAS signal region","h") elif region == "central": leg.AddEntry(legendHistDing,"Central signal region","h") elif region == "forward": leg.AddEntry(legendHistDing,"Forward signal region","h") leg.AddEntry(sfHist,"Data","PL") leg.AddEntry(bkgHist, "Total backgrounds","l") leg.AddEntry(dyHist,"Drell--Yan", "f") leg.AddEntry(errGraph,"Total uncert.", "f") leg.Draw("same") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist,bkgHist, xMin=plot.firstBin, xMax=plot.lastBin,title="Data / Bgnd",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=1000) ratioGraphs.addErrorByHistograms( "rSFOF", histUp, histDown,color= myColors["MyBlue"],fillStyle=3001) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC") leg2.SetFillColor(10) leg2.SetLineColor(10) leg2.SetShadowColor(0) leg2.SetBorderSize(1) leg2.AddEntry(errGraph,"Systematic uncert.", "f") leg2.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("fig/mllResult_%s_%s_%s.pdf"%(selection.name,runRange.label,combination))
def plotDataMC(mainConfig, dilepton): import gc gc.enable() from ROOT import TCanvas, TPad, TH1F, TH1I, THStack, TLegend, TMath, gROOT, TFile, TH2F import ratios from defs import Backgrounds from defs import Backgrounds2011 from defs import Signals from defs import defineMyColors from defs import myColors from defs import Region from defs import Regions from defs import Plot from corrections import triggerEffs, rSFOFTrig from setTDRStyle import setTDRStyle gROOT.SetBatch(True) from helpers import * import math ### file to normalize signal MC signalDenominatorFile = TFile( "../SignalScan/T6bbllsleptonDenominatorHisto4.root") signalDenominatorHisto = TH2F(signalDenominatorFile.Get("massScan")) if mainConfig.forPAS: hCanvas = TCanvas("hCanvas", "Distribution", 600, 800) else: hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) if mainConfig.plotRatio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() colors = createMyColors() eventCounts = totalNumberOfGeneratedEvents(mainConfig.dataSetPath) processes = [] for background in mainConfig.backgrounds: processes.append(Process(getattr(Backgrounds, background), eventCounts)) ### get the signal if any is to be plotted signalEventCounts = {} signals = [] signalNameLabel = "" for signal in mainConfig.signals: m_b = int(signal.split("_")[2]) m_n_2 = int(signal.split("_")[4]) signalEventCounts[signal] = signalDenominatorHisto.GetBinContent( signalDenominatorHisto.GetXaxis().FindBin(m_b), signalDenominatorHisto.GetYaxis().FindBin(m_n_2)) signals.append(Process(getattr(Signals, signal), signalEventCounts)) if signalNameLabel == "": signalNameLabel = "Signal" signalNameLabel += "_m_b_%s_m_n_%s" % (signal.split("_")[2], signal.split("_")[4]) #~ legend = TLegend(0.45, 0.6, 0.925, 0.925) legend = TLegend(0.55, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) #~ legend.SetNColumns(2) legendEta = TLegend(0.15, 0.75, 0.7, 0.9) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] legendHistData = ROOT.TH1F() if mainConfig.plotData: legend.AddEntry(legendHistData, "Data", "pe") legendEta.AddEntry(legendHistData, "Data", "pe") ### loop over the background processes, add them in iverse order to the legend if mainConfig.plotMC: for process in reversed(processes): temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) ### Do not add a seperate legend entry for DY to tautau if new legend scheme is used if not process.label == "DY+jets non resonant": legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") legendEta.AddEntry(temphist, process.label, "f") if mainConfig.plotRatio: temphist = ROOT.TH1F() temphist.SetFillColor(myColors["MyGreen"]) legendHists.append(temphist.Clone) #~ legend.AddEntry(temphist,"Syst. uncert.","f") temphist2 = ROOT.TH1F() temphist2.SetFillColor(myColors["DarkRed"], ) temphist2.SetFillStyle(3002) legendHists.append(temphist2.Clone) if mainConfig.plotSignal: for Signal in signals: temphist = ROOT.TH1F() temphist.SetFillColor(Signal.theColor) temphist.SetLineColor(Signal.theLineColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, Signal.label, "l") legendEta.AddEntry(temphist, Signal.label, "l") nEvents = -1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.03) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() treeEE = readTrees(mainConfig.dataSetPath, "EE") treeMuMu = readTrees(mainConfig.dataSetPath, "MuMu") treeEMu = readTrees(mainConfig.dataSetPath, "EMu") mainConfig.plot.addDilepton(dilepton) plotPad.cd() plotPad.SetLogy(0) logScale = mainConfig.plot.log #~ logScale = True if mainConfig.plot.variable == "met" or mainConfig.plot.variable == "type1Met" or mainConfig.plot.variable == "tcMet" or mainConfig.plot.variable == "caloMet" or mainConfig.plot.variable == "mht": logScale = True if logScale == True: plotPad.SetLogy() scaleTree1 = 1.0 scaleTree2 = 1.0 if mainConfig.plot.tree1 == "EE": tree1 = treeEE if mainConfig.useDataTrigEff: scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effEE.val #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val**2 print "ee trigger Eff:" print scaleTree1 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val/getattr(triggerEffs,mainConfig.etaRegion).effEE.valMC elif mainConfig.plot.tree1 == "MuMu": tree1 = treeMuMu if mainConfig.useDataTrigEff: scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effMM.val #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val**2 print "mumu trigger Eff:" print scaleTree1 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val/getattr(triggerEffs,mainConfig.etaRegion).effMM.valMC elif mainConfig.plot.tree1 == "EMu": tree1 = treeEMu if mainConfig.useDataTrigEff: scaleTree1 = getattr(triggerEffs, mainConfig.etaRegion).effEM.val print "emu trigger Eff:" print scaleTree1 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree1 = getattr(triggerEffs,mainConfig.etaRegion).effEM.val/getattr(triggerEffs,mainConfig.etaRegion).effEM.valMC else: print "Unknown Dilepton combination! %s not created!" % ( mainConfig.plot.filename, ) return if mainConfig.plot.tree2 != "None": if mainConfig.plot.tree2 == "EE": tree2 = treeEE if mainConfig.useDataTrigEff: #~ scaleTree2 = mainConfig.selection.trigEffs.effEE.val scaleTree2 = mainConfig.selection.trigEffs.effEE.val**2 print "ee trigger Eff:" print scaleTree2 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effEE.val/getattr(triggerEffs,mainConfig.etaRegion).effEE.valMC elif mainConfig.plot.tree2 == "MuMu": tree2 = treeMuMu if mainConfig.useDataTrigEff: #~ scaleTree2 = mainConfig.selection.trigEffs.effMM.val scaleTree2 = mainConfig.selection.trigEffs.effMM.val**2 print "mumu trigger Eff:" print scaleTree2 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effMM.val/getattr(triggerEffs,mainConfig.etaRegion).effMM.valMC elif mainConfig.plot.tree2 == "EMu": tree2 = treeEMu if mainConfig.useDataTrigEff: scaleTree2 = mainConfig.selection.trigEffs.effEM.val print "emu trigger Eff:" print scaleTree2 #~ elif mainConfig.useTriggerEmulation: #~ scaleTree2 = getattr(triggerEffs,mainConfig.etaRegion).effEM.val/getattr(triggerEffs,mainConfig.etaRegion).effEM.valMC else: print "Unknown Dilepton combination! %s not created!" % ( mainConfig.plot.filename, ) return else: tree2 = "None" if mainConfig.normalizeToData: pickleName = mainConfig.plot.filename % ( "_normalizedToData_" + mainConfig.runRange.label + "_" + dilepton) elif mainConfig.useTriggerEmulation: pickleName = mainConfig.plot.filename % ( "_TriggerEmulation_" + mainConfig.runRange.label + "_" + dilepton) elif mainConfig.DontScaleTrig: pickleName = mainConfig.plot.filename % ( "_NoTriggerScaling_" + mainConfig.runRange.label + "_" + dilepton) elif mainConfig.useDataTrigEff: pickleName = mainConfig.plot.filename % ( "_dataTriggerEffs_" + mainConfig.runRange.label + "_" + dilepton) else: pickleName = mainConfig.plot.filename % ( "_" + mainConfig.runRange.label + "_" + dilepton) counts = {} import pickle print mainConfig.plot.cuts if mainConfig.plotData: datahist = getDataHist( mainConfig.plot, tree1, tree2, normalizeToBinWidth=mainConfig.normalizeToBinWidth) counts["Data"] = { "val": datahist.Integral(0, datahist.GetNbinsX() + 1), "err": math.sqrt(datahist.Integral(0, datahist.GetNbinsX() + 1)) } print datahist.GetEntries() if mainConfig.plotMC: #~ stack = TheStack(processes,mainConfig.runRange.lumi,mainConfig.plot,tree1,tree2,1.0,scaleTree1,scaleTree2,saveIntegrals=True,counts=counts,doTopReweighting=mainConfig.doTopReweighting,theoUncert=mainConfig.theoUncert,doPUWeights=mainConfig.doPUWeights,normalizeToBinWidth=mainConfig.normalizeToBinWidth) stack = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, counts=counts, doTopReweighting=mainConfig.doTopReweighting, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) ### get the number of MC events and the uncertainty errIntMC = ROOT.Double() intMC = stack.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) val = float(intMC) err = float(errIntMC) counts["Total Background"] = {"val": val, "err": err} ### scale the stack if MC is to be normalzed to data if mainConfig.normalizeToData: scalefac = datahist.Integral( datahist.FindBin(mainConfig.plot.firstBin), datahist.FindBin( mainConfig.plot.lastBin)) / stack.theHistogram.Integral( stack.theHistogram.FindBin(mainConfig.plot.firstBin), stack.theHistogram.FindBin(mainConfig.plot.lastBin)) drawStack = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) stackJESUp = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 0.955, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) stackJESDown = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.045, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) else: drawStack = stack if mainConfig.plotSyst: mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "met ", "metJESUp ") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( " ht", " htJESUp") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( " nJets ", " nShiftedJetsJESUp ") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "(nJets ", "(nShiftedJetsJESUp ") stackJESUp = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, JESUp=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "metJESUp", "metJESDown") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "htJESUp", "htJESDown") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "nShiftedJetsJESUp", "nShiftedJetsJESDown") stackJESDown = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, JESDown=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "metJESDown", "met") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "htJESDown", "ht") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "nShiftedJetsJESDown", "nJets") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "*(", "Up*(") stackPileUpUp = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, PileUpUp=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "Up*(", "Down*(") stackPileUpDown = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, PileUpDown=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "Down*(", "*(") errIntMC = ROOT.Double() intMCPileUpUp = stackPileUpUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCPileUpDown = stackPileUpDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valPileUpUp = float(intMCPileUpUp) valPileUpDown = float(intMCPileUpDown) pileUpUp = abs(counts["Total Background"]["val"] - valPileUpUp) pileUpDown = abs(counts["Total Background"]["val"] - valPileUpDown) counts["Total Background"]["pileUpDown"] = pileUpDown counts["Total Background"]["pileUpUp"] = pileUpUp if mainConfig.doTopReweighting: stackReweightDown = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, TopWeightDown=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) stackReweightUp = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, TopWeightUp=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights, normalizeToBinWidth=mainConfig.normalizeToBinWidth, useTriggerEmulation=mainConfig.useTriggerEmulation) errIntMC = ROOT.Double() intMCTopWeightUp = stackReweightUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCTopWeightDown = stackReweightDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valTopWeightUp = float(intMCTopWeightUp) valTopWeightDown = float(intMCTopWeightDown) topWeightUp = abs(counts["Total Background"]["val"] - valTopWeightUp) topWeightDown = abs(counts["Total Background"]["val"] - valTopWeightDown) counts["Total Background"]["topWeightDown"] = topWeightDown counts["Total Background"]["topWeightUp"] = topWeightUp errIntMC = ROOT.Double() intMCJESUp = stackJESUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCJESDown = stackJESDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valJESUp = float(intMCJESUp) valJESDown = float(intMCJESDown) jesUp = abs(counts["Total Background"]["val"] - valJESUp) jesDown = abs(counts["Total Background"]["val"] - valJESDown) counts["Total Background"]["jesDown"] = jesDown counts["Total Background"]["jesUp"] = jesUp xSec = abs( stack.theHistogramXsecUp.Integral( 0, stack.theHistogram.GetNbinsX() + 1) - counts["Total Background"]["val"]) counts["Total Background"]["xSec"] = xSec #~ theoUncert = abs(stack.theHistogramTheoUp.Integral(0,stack.theHistogram.GetNbinsX()+1)-counts["Total Background"]["val"]) #~ counts["Total Background"]["theo"]=theoUncert outFilePkl = open("shelves/%s.pkl" % (pickleName), "w") pickle.dump(counts, outFilePkl) outFilePkl.close() if mainConfig.plotSignal: signalhists = [] signalLabels = [] ymaxSignal = 0 for Signal in signals: signalhist = Signal.createCombinedHistogram( mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2) signalhist.SetLineWidth(2) if mainConfig.stackSignal: signalhist.Add(drawStack.theHistogram) signalhist.SetMinimum(0.1) signalhists.append(signalhist) signalLabels.append(Signal.label) tmpYmaxSignal = signalhist.GetBinContent( signalhist.GetMaximumBin()) if tmpYmaxSignal > ymaxSignal: ymaxSignal = tmpYmaxSignal ### set the maximum of the y-axis yMax = 0 yMin = 0 if mainConfig.plotData: yMax = datahist.GetBinContent(datahist.GetMaximumBin()) if (mainConfig.plotMC and yMax < drawStack.theHistogram.GetBinContent( drawStack.theHistogram.GetMaximumBin())): yMax = drawStack.theHistogram.GetBinContent( drawStack.theHistogram.GetMaximumBin()) if (mainConfig.plotSignal and yMax < ymaxSignal): yMax = ymaxSignal if mainConfig.plot.yMax == 0: if logScale: yMax = yMax * 200 if datahist.GetBinContent(datahist.GetMinimumBin()) > 0: yMin = datahist.GetBinContent(datahist.GetMinimumBin()) / 5. else: yMin = 0.1 #~ yMin = 0.5 #~ yMin = 5 else: yMax = yMax * 1.5 else: yMax = plot.yMax #~ yMax = 1200 #~ yMax = 130 plotPad.DrawFrame( mainConfig.plot.firstBin, yMin, mainConfig.plot.lastBin, yMax, "; %s ; %s" % (mainConfig.plot.xaxis, mainConfig.plot.yaxis)) ### draw the stack if mainConfig.plotMC: drawStack.theStack.Draw("samehist") lineHistogram = drawStack.theHistogram lineHistogram.Draw("same l") ### Draw signal if mainConfig.plotSignal: for signalhist in signalhists: signalhist.Draw("samehist") dileptonLabel = "" if dilepton == "SF": dileptonLabel = "ee + #mu#mu" if dilepton == "OF": dileptonLabel = "e#mu" if dilepton == "EE": dileptonLabel = "ee" if dilepton == "MuMu": dileptonLabel = "#mu#mu" if mainConfig.plotData: #~ datahist.SetMinimum(0.1) datahist.Draw("samep") if mainConfig.normalizeToData: scalelabel.DrawLatex(0.6, 0.4, "Background scaled by %.2f" % (scalefac)) if mainConfig.plot.variable == "eta1" or mainConfig.plot.variable == "eta2": legendEta.SetNColumns(2) legendEta.Draw() intlumi.DrawLatex( 0.2, 0.7, "#splitline{" + mainConfig.plot.label + " " + dileptonLabel + "}{#splitline{" + mainConfig.plot.label2 + "}{" + mainConfig.plot.label3 + "}}") else: legend.Draw() intlumi.DrawLatex( 0.4, 0.55, "#splitline{%s}{%s}" % (mainConfig.plot.label2, dileptonLabel)) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % (mainConfig.runRange.printval, )) yLabelPos = 0.85 #~ yLabelPos = 0.88 cmsExtra = "" if mainConfig.personalWork: cmsExtra = "Private Work" if not mainConfig.plotData: cmsExtra = "#splitline{Private Work}{Simulation}" yLabelPos = 0.82 #~ yLabelPos = 0.85 elif not mainConfig.plotData: cmsExtra = "Simulation" elif mainConfig.preliminary: cmsExtra = "Preliminary" elif mainConfig.forTWIKI: cmsExtra = "Unpublished" if mainConfig.forPAS: latexCMS.DrawLatex(0.15, 0.955, "CMS") latexCMSExtra.DrawLatex(0.26, 0.955, "%s" % (cmsExtra)) else: latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) if mainConfig.plotRatio: ratioPad.cd() ratioGraphs = ratios.RatioGraph(datahist, drawStack.theHistogram, xMin=mainConfig.plot.firstBin, xMax=mainConfig.plot.lastBin, title="Data / MC", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=0.25) if mainConfig.plotSyst: ratioGraphs.addErrorByHistograms("Pileup", stackPileUpUp.theHistogram, stackPileUpDown.theHistogram, color=myColors["MyGreen"]) ratioGraphs.addErrorByHistograms("JES", stackJESUp.theHistogram, stackJESDown.theHistogram, color=myColors["MyGreen"]) if mainConfig.doTopReweighting: ratioGraphs.addErrorByHistograms( "TopWeight", stackReweightUp.theHistogram, stackReweightDown.theHistogram, color=myColors["MyGreen"]) ratioGraphs.addErrorBySize("Effs", getattr(rSFOFTrig, mainConfig.etaRegion).err, color=myColors["MyGreen"], add=True) ratioGraphs.addErrorByHistograms("Xsecs", drawStack.theHistogramXsecUp, drawStack.theHistogramXsecDown, color=myColors["MyGreen"], add=True) #~ ratioGraphs.addErrorByHistograms( "Theo", drawStack.theHistogramTheoUp, drawStack.theHistogramTheoDown,color=myColors["MyGreen"],add=True) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) if mainConfig.plotSignal and mainConfig.stackSignal: signalRatios = [] legendRatio = TLegend(0.175, 0.725, 0.65, 0.95) legendRatio.SetFillStyle(0) legendRatio.SetBorderSize(0) legendRatio.SetTextFont(42) backgroundHist = ROOT.TH1F() legendRatio.AddEntry(backgroundHist, "Data / background", "pe") temphist = ROOT.TH1F() temphist.SetFillColor(myColors["MyGreen"]) if mainConfig.plotSyst: legendRatio.AddEntry(temphist, "Syst. uncert.", "f") legendRatio.SetNColumns(2) for index, signalhist in enumerate(signalhists): signalRatios.append( ratios.RatioGraph(datahist, signalhist, xMin=mainConfig.plot.firstBin, xMax=mainConfig.plot.lastBin, title="Data / MC", yMin=0.0, yMax=2, ndivisions=10, color=signalhist.GetLineColor(), adaptiveBinning=0.25)) signalRatios[index].draw(ROOT.gPad, False, False, True, chi2Pos=0.7 - index * 0.1) signalhist.SetMarkerColor(signalhist.GetLineColor()) legendRatio.AddEntry( signalhist, "Data / Background + Signal (%s)" % signalLabels[index], "p") legendRatio.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if mainConfig.plotRatio: ratioPad.RedrawAxis() nameModifier = mainConfig.runRange.label + "_" + dilepton if mainConfig.doTopReweighting: nameModifier += "_TopReweighted" if mainConfig.plotData == False: nameModifier += "_MCOnly" if mainConfig.plotMC == False: nameModifier += "_NoBkgMC" if mainConfig.plotSignal: nameModifier += "_" + signalNameLabel if mainConfig.stackSignal: nameModifier += "_stackedSignal" if mainConfig.normalizeToData: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_scaled_" + nameModifier), ) elif mainConfig.useTriggerEmulation: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_TriggerEmulation_" + nameModifier), ) elif mainConfig.DontScaleTrig: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_NoTriggerScaling_" + nameModifier), ) else: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_" + nameModifier), )
latexCentral.SetNDC(True) #~ latexCentral.DrawLatex(0.4,0.45,"Central") latexForward = ROOT.TLatex() latexForward.SetTextFont(42) latexForward.SetTextAlign(31) latexForward.SetTextSize(0.07) latexForward.SetNDC(True) #~ latexForward.DrawLatex(0.88,0.45,"Forward") ratioPad.cd() ratioGraphs = ratios.RatioGraph(eeHist, emHist, 0, 5, title="SF / OF", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kRed, adaptiveBinning=0.25) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) line2 = ROOT.TLine(0.3, 0, 0.3, 2) line2.SetLineColor(ROOT.kBlue + 3) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.Draw("same") hCanvas.Print("dRJustification_miniIso_Mll20.pdf")
def doPlot(source,modifier,path,selection,plots,runRange,isMC,backgrounds,cmsExtra): for name in plots: plot = getPlot(name) plot.addRegion(selection) plot.cleanCuts() plot.cuts = plot.cuts % runRange.runCut if "Forward" in selection.name: label = "forward" elif "Central" in selection.name: label = "central" else: label = "inclusive" histsEE, histsMM, histsEM = getHistograms(path,source,modifier,plot,runRange,isMC, backgrounds,label) histsSF = [] for hist in histsEE: histsSF.append(hist.Clone()) for index, hist in enumerate(histsMM): histsSF[index].Add(hist.Clone()) hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.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 if logScale == True: plotPad.SetLogy() yMax = histsSF[0].GetBinContent(histsSF[0].GetMaximumBin()) if plot.yMax == 0: if logScale: yMax = yMax*1000 else: yMax = yMax*1.5 else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin,0.1,plot.lastBin,yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis)) from ROOT import TH1F,kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) legend = ROOT.TLegend(0.5,0.6,0.95,0.9) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.AddEntry(legendHistDing,"%s"%selection.latex,"h") for index, hist in enumerate(histsSF): hist.SetLineColor(ROOT.kBlue+2*index) #~ hist.SetLineStyle(1+2*index) hist.Draw("samehist") legend.AddEntry(hist,backgrounds[index],"l") #~ legend.AddEntry(histEE,"R_{EE/OF}","p") #~ legend.AddEntry(histMM,"R_{MM/OF}","p") legend.Draw("same") 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.03) intlumi.SetNDC(True) 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.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra)) #~ if fit: #~ fit = TF1("dataFit","pol1",0,300) #~ fit.SetLineColor(ROOT.kBlack) #~ histRSFOF.Fit("dataFit") #~ #~ latex = ROOT.TLatex() #~ latex.SetTextSize(0.035) #~ latex.SetNDC() #~ latex.DrawLatex(0.2, 0.25, "Fit: %.2f #pm %.2f %.5f #pm %.5f * m_{ll}"%(fit.GetParameter(0),fit.GetParError(0),fit.GetParameter(1),fit.GetParError(1))) ratioPad.cd() ratioGraphs = ratios.RatioGraph(histsSF[1],histsSF[0], xMin=plot.firstBin, xMax=plot.lastBin,title="X / Madgraph",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlue+2,adaptiveBinning=0.25) ratioGraphs2 = ratios.RatioGraph(histsSF[2],histsSF[0], xMin=plot.firstBin, xMax=plot.lastBin,title="X / Madgraph",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlue+4,adaptiveBinning=0.25) ratioGraphs3 = ratios.RatioGraph(histsSF[3],histsSF[0], xMin=plot.firstBin, xMax=plot.lastBin,title="X / Madgraph",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlue+6,adaptiveBinning=0.25) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) ratioGraphs2.draw(ROOT.gPad,False,False,True,chi2Pos=0.8) ratioGraphs3.draw(ROOT.gPad,False,False,True,chi2Pos=0.8) hCanvas.Print("fig/ttbarCompare_%s_%s_%s_%s_MC.pdf"%(selection.name,runRange.label,plot.variablePlotName,plot.additionalName))
def plotDataMC(args, plot): hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) if args.ratio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() colors = createMyColors() eventCounts = totalNumberOfGeneratedEvents("filesM300/mc") mcTrees = readTrees("filesM300/mc") dataTrees = readTrees("filesM300") print eventCounts processes = [] for background in args.backgrounds: processes.append(Process(getattr(Backgrounds, background), eventCounts)) signals = [] for signal in args.signals: signals.append(Process(getattr(Signals, signal), eventCounts)) legend = TLegend(0.375, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) #~ legend.SetNColumns(2) legendEta = TLegend(0.15, 0.75, 0.7, 0.9) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] legendHistData = ROOT.TH1F() if args.data: legend.AddEntry(legendHistData, "Data", "pe") legendEta.AddEntry(legendHistData, "Data", "pe") for process in reversed(processes): temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") legendEta.AddEntry(temphist, process.label, "f") if args.signals != 0: processesWithSignal = [] for process in processes: processesWithSignal.append(process) for Signal in signals: processesWithSignal.append(Signal) temphist = ROOT.TH1F() temphist.SetFillColor(Signal.theColor) temphist.SetLineColor(Signal.theLineColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, Signal.label, "l") legendEta.AddEntry(temphist, Signal.label, "l") nEvents = -1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() plotPad.cd() plotPad.SetLogy(0) logScale = plot.log if logScale == True: plotPad.SetLogy() datahist = getDataHist(plot, dataTrees, fromTree=True) print datahist.GetEntries() lumi = 36400 print "-----" stack = TheStack(processes, lumi, plot, mcTrees, fromTree=True) if args.data: yMax = datahist.GetBinContent(datahist.GetMaximumBin()) yMin = 0.1 xMax = datahist.GetXaxis().GetXmax() xMin = datahist.GetXaxis().GetXmin() else: yMax = stack.theHistogram.GetBinContent( stack.theHistogram.GetMaximumBin()) yMin = 0.1 xMax = stack.theHistogram.GetXaxis().GetXmax() xMin = stack.theHistogram.GetXaxis().GetXmin() print yMax, yMin, xMax, xMin if plot.yMax == None: if logScale: yMax = yMax * 1000 else: yMax = yMax * 1.5 else: yMax = plot.yMax print plot.xMin, plot.xMax if not plot.yMin == None: yMin = plot.yMin if not plot.xMin == None: xMin = plot.xMin if not plot.xMax == None: xMax = plot.xMax print yMax, yMin, xMax, xMin plotPad.DrawFrame(xMin, yMin, xMax, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) drawStack = stack drawStack.theStack.Draw("samehist") datahist.SetMinimum(0.1) if args.data: datahist.Draw("samep") if len(args.signals) != 0: signalhists = [] for Signal in signals: signalhist = Signal.loadHistogramFromTree(lumi, mcTrees, plot) signalhist.SetLineWidth(2) #~ signalhist.Add(stack.theHistogram) signalhist.SetMinimum(0.1) signalhist.Draw("samehist") signalhists.append(signalhist) legend.Draw() latex.DrawLatex(0.95, 0.96, "%.2f fb^{-1} (13 TeV)" % (lumi / 1000, )) yLabelPos = 0.85 cmsExtra = "Private Work" if not args.data: cmsExtra = "#splitline{Private Work}{Simulation}" yLabelPos = 0.82 latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) if args.ratio: try: ratioPad.cd() except AttributeError: print "Plot fails. Look up in errs/failedPlots.txt" outFile = open("errs/failedPlots.txt", "a") outFile.write('%s\n' % plot.filename % ("_" + run.label + "_" + dilepton)) outFile.close() plot.cuts = baseCut return 1 ratioGraphs = ratios.RatioGraph(datahist, drawStack.theHistogram, xMin=xMin, xMax=xMax, title="Data / MC", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=0.25) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if args.ratio: ratioPad.RedrawAxis() if not os.path.exists("plots"): os.makedirs("plots") print plot.fileName hCanvas.Print("plots/" + plot.fileName + "_fromTree.pdf")
latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) ratioPad.cd() xMin = 0 xMax = 5000 yMax = 1.1 yMin = 0.9 # ~ if "BE" in label: # ~ yMax = 1.2 # ~ yMin = 0.8 ratioGraphs2 = ratios.RatioGraph(dyHist, dyHistScaleDown, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kBlue, adaptiveBinning=10000) ratioGraphs2.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) if antype[2] == 'Mu': ratioGraphs3 = ratios.RatioGraph(dyHist, dyHistWeighted, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kGreen + 2,
def makePlot(sfHist, ofHist, selection, plot, runRange, region, cmsExtra, combination, dyHist=None, edgeShape=False, edgeShapeMC=False, differentEdgePositions=False): colors = createMyColors() hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) style = setTDRStyle() style.SetPadTopMargin(0.07) ROOT.gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: #~ yMax = yMax*2.15 if edgeShape or edgeShapeMC or differentEdgePositions: yMax = yMax * 1.75 else: yMax = yMax * 1.5 else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) #set overflow bin #~ print sfHist.GetBinContent(sfHist.GetNbinsX()), sfHist.GetBinContent(sfHist.GetNbinsX()+1) #~ sfHist.SetBinContent(sfHist.GetNbinsX(),sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1)) #~ sfHist.SetBinError(sfHist.GetNbinsX(),(sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))**0.5) #~ ofHist.SetBinContent(ofHist.GetNbinsX(),ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1)) #~ ofHist.SetBinError(ofHist.GetNbinsX(),(ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))**0.5) bkgHist = ofHist.Clone("bkgHist") if dyHist is not None: bkgHist.Add(dyHist) sfHist.SetMarkerStyle(20) sfHist.SetLineColor(ROOT.kBlack) bkgHist.SetLineColor(ROOT.kBlue + 3) bkgHist.SetLineWidth(2) dyHist.SetLineColor(ROOT.kGreen + 2) dyHist.SetFillColor(ROOT.kGreen + 2) #~ dyHist.SetFillStyle(3002) #~ dyOnlyHist = dyHist.Clone("dyOnlyHist") #~ dyOnlyHist.Scale(getattr(getattr(OnlyZPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val) #~ #~ rareBGHist = dyHist.Clone("rareBGHist") #~ rareBGHist.Scale(getattr(getattr(OtherPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val) #~ #~ rareBGHist.SetLineColor(ROOT.kViolet+2) #~ rareBGHist.SetFillColor(ROOT.kViolet+2) from ROOT import THStack #~ stack = THStack() #~ stack.Add(rareBGHist) #~ stack.Add(dyOnlyHist) #~ bkgHistForLegend = bkgHist.Clone("bkgHistForLegend") bkgHistForLegend.SetLineColor(ROOT.kBlue + 3) bkgHistForLegend.SetFillColor(ROOT.kWhite) bkgHistForLegend.SetLineWidth(2) latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.055) latex.SetLineWidth(2) latex.SetNDC(True) latexCMS = ROOT.TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.05) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.0375) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.93, 0.942, "%s fb^{-1} (13 TeV)" % runRange.printval) latexCMS.DrawLatex(0.19, 0.86, "CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.81 latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) if combination == "SF": rSFOFErr = getattr(rSFOF, region).err elif combination == "EE": rSFOFErr = getattr(rEEOF, region).err elif combination == "MM": rSFOFErr = getattr(rMMOF, region).err errGraph, histUp, histDown = getErrHist(plot, combination, region, ofHist, dyHist, rSFOFErr) errGraph.SetFillColor(myColors["MyBlueOverview"]) errGraph.SetFillStyle(3001) #~ errGraph.SetLineColor(myColors["MyDarkBlue"]) #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"]) if edgeShape: edgeFile = ROOT.TFile("edgeShape.root", "READ") edgeHist = ROOT.TH1F() edgeHist = edgeFile.Get("edgeHist300__inv") edgeHist.Scale(1. / edgeHist.Integral()) edgeHist500 = edgeFile.Get("edgeHist500__inv") edgeHist500.Scale(1. / edgeHist500.Integral()) edgeHist700 = edgeFile.Get("edgeHist700__inv") edgeHist700.Scale(1. / edgeHist700.Integral()) edgeHist.Scale(342) edgeHist.Add(bkgHist.Clone()) edgeHist.SetLineColor(ROOT.kRed) edgeHist.SetLineWidth(2) edgeHist500.Scale(484) edgeHist500.Add(bkgHist.Clone()) edgeHist500.SetLineColor(ROOT.kRed) edgeHist500.SetLineWidth(2) edgeHist500.SetLineStyle(ROOT.kDashed) edgeHist700.Scale(654) edgeHist700.Add(bkgHist.Clone()) edgeHist700.SetLineColor(ROOT.kRed) edgeHist700.SetLineStyle(ROOT.kDotted) edgeHist700.SetLineWidth(2) for i in range(1, edgeHist.GetNbinsX() + 1): if i >= edgeHist.GetXaxis().FindBin(70.01): edgeHist.SetBinContent(i, 0) edgeHist500.SetBinContent(i, 0) edgeHist700.SetBinContent(i, 0) if edgeShapeMC: signalPath = locations.signalDataSetPath denominatorFile = TFile( "../SignalScan/T6bbllsleptonDenominatorHisto.root") denominatorHisto = TH2F(denominatorFile.Get("massScan")) cutsWithoutSignalScaleFactors = plot.cuts plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)" % plot.cuts if "Central" in selection.name: EETriggerEff = 0.945 EMuTriggerEff = 0.937 MuMuTriggerEff = 0.929 RSFOF = 1.032 elif "Forward" in selection.name: EETriggerEff = 0.943 EMuTriggerEff = 0.938 MuMuTriggerEff = 0.916 RSFOF = 1.092 else: EETriggerEff = 0.949 EMuTriggerEff = 0.921811 MuMuTriggerEff = 0.929178 RSFOF = 1.05 EEHistSignal450, MMHistSignal450, EMHistSignal450 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_450_mneutralino_175") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(450), denominatorHisto.GetYaxis().FindBin(175)) xsection = getattr(sbottom_masses, "m_b_450").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal450.Scale(EETriggerEff * scalingLumi) MMHistSignal450.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal450.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist450 = EEHistSignal450.Clone() edgeHist450.Add(MMHistSignal450.Clone()) edgeHist450.Add(EMHistSignal450.Clone(), -1) if combination == "EE": edgeHist450 = EEHistSignal450.Clone() edgeHist450.Add(EMHistSignal450.Clone(), -0.5) if combination == "MM": edgeHist450 = MMHistSignal450.Clone() edgeHist450.Add(EMHistSignal450.Clone(), -0.5) for i in range(0, edgeHist450.GetNbinsX()): if edgeHist450.GetBinContent(i) < 0: edgeHist450.SetBinContent(i, 0.) edgeHist450.Add(bkgHist.Clone()) edgeHist450.SetLineColor(ROOT.kRed) edgeHist450.SetLineWidth(2) EEHistSignal550, MMHistSignal550, EMHistSignal550 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_550_mneutralino_175") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(550), denominatorHisto.GetYaxis().FindBin(175)) xsection = getattr(sbottom_masses, "m_b_550").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal550.Scale(EETriggerEff * scalingLumi) MMHistSignal550.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal550.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist550 = EEHistSignal550.Clone() edgeHist550.Add(MMHistSignal550.Clone()) edgeHist550.Add(EMHistSignal550.Clone(), -1) if combination == "EE": edgeHist550 = EEHistSignal550.Clone() edgeHist550.Add(EMHistSignal550.Clone(), -0.5) if combination == "MM": edgeHist550 = MMHistSignal550.Clone() edgeHist550.Add(EMHistSignal550.Clone(), -0.5) for i in range(0, edgeHist550.GetNbinsX()): if edgeHist550.GetBinContent(i) < 0: edgeHist550.SetBinContent(i, 0.) edgeHist550.Add(bkgHist.Clone()) edgeHist550.SetLineColor(ROOT.kRed) edgeHist550.SetLineWidth(2) edgeHist550.SetLineStyle(ROOT.kDashed) EEHistSignal650, MMHistSignal650, EMHistSignal650 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_650_mneutralino_175") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(650), denominatorHisto.GetYaxis().FindBin(175)) xsection = getattr(sbottom_masses, "m_b_650").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal650.Scale(EETriggerEff * scalingLumi) MMHistSignal650.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal650.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist650 = EEHistSignal650.Clone() edgeHist650.Add(MMHistSignal650.Clone()) edgeHist650.Add(EMHistSignal650.Clone(), -1) if combination == "EE": edgeHist650 = EEHistSignal650.Clone() edgeHist650.Add(EMHistSignal650.Clone(), -0.5) if combination == "MM": edgeHist650 = MMHistSignal650.Clone() edgeHist650.Add(EMHistSignal650.Clone(), -0.5) for i in range(0, edgeHist650.GetNbinsX()): if edgeHist650.GetBinContent(i) < 0: edgeHist650.SetBinContent(i, 0.) edgeHist650.Add(bkgHist.Clone()) edgeHist650.SetLineColor(ROOT.kRed) edgeHist650.SetLineWidth(2) edgeHist650.SetLineStyle(ROOT.kDotted) plot.cuts = cutsWithoutSignalScaleFactors if differentEdgePositions: signalPath = locations.signalDataSetPath denominatorFile = TFile( "../SignalScan/T6bbllsleptonDenominatorHisto.root") denominatorHisto = TH2F(denominatorFile.Get("massScan")) cutsWithoutSignalScaleFactors = plot.cuts plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)" % plot.cuts if "Central" in selection.name: EETriggerEff = 0.945 EMuTriggerEff = 0.937 MuMuTriggerEff = 0.929 RSFOF = 1.032 elif "Forward" in selection.name: EETriggerEff = 0.943 EMuTriggerEff = 0.938 MuMuTriggerEff = 0.916 RSFOF = 1.092 else: EETriggerEff = 0.949 EMuTriggerEff = 0.921811 MuMuTriggerEff = 0.929178 RSFOF = 1.05 EEHistSignal75, MMHistSignal75, EMHistSignal75 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_500_mneutralino_175") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(500), denominatorHisto.GetYaxis().FindBin(175)) xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal75.Scale(EETriggerEff * scalingLumi) MMHistSignal75.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal75.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist75 = EEHistSignal75.Clone() edgeHist75.Add(MMHistSignal75.Clone()) edgeHist75.Add(EMHistSignal75.Clone(), -1) if combination == "EE": edgeHist75 = EEHistSignal75.Clone() edgeHist75.Add(EMHistSignal75.Clone(), -0.5) if combination == "MM": edgeHist75 = MMHistSignal75.Clone() edgeHist75.Add(EMHistSignal75.Clone(), -0.5) for i in range(0, edgeHist75.GetNbinsX()): if edgeHist75.GetBinContent(i) < 0: edgeHist75.SetBinContent(i, 0.) edgeHist75.Add(bkgHist.Clone()) edgeHist75.SetLineColor(ROOT.kRed) edgeHist75.SetLineWidth(2) EEHistSignal125, MMHistSignal125, EMHistSignal125 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_500_mneutralino_225") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(500), denominatorHisto.GetYaxis().FindBin(225)) xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal125.Scale(EETriggerEff * scalingLumi) MMHistSignal125.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal125.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist125 = EEHistSignal125.Clone() edgeHist125.Add(MMHistSignal125.Clone()) edgeHist125.Add(EMHistSignal125.Clone(), -1) if combination == "EE": edgeHist125 = EEHistSignal125.Clone() edgeHist125.Add(EMHistSignal125.Clone(), -0.5) if combination == "MM": edgeHist125 = MMHistSignal125.Clone() edgeHist125.Add(EMHistSignal125.Clone(), -0.5) for i in range(0, edgeHist125.GetNbinsX()): if edgeHist125.GetBinContent(i) < 0: edgeHist125.SetBinContent(i, 0.) edgeHist125.Add(bkgHist.Clone()) edgeHist125.SetLineColor(ROOT.kRed) edgeHist125.SetLineWidth(2) edgeHist125.SetLineStyle(ROOT.kDashed) EEHistSignal200, MMHistSignal200, EMHistSignal200 = getSignalMCHistograms( signalPath, plot, runRange, "T6bbllslepton_msbottom_500_mneutralino_300") denominator = denominatorHisto.GetBinContent( denominatorHisto.GetXaxis().FindBin(500), denominatorHisto.GetYaxis().FindBin(300)) xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV scalingLumi = runRange.lumi * xsection / denominator EEHistSignal200.Scale(EETriggerEff * scalingLumi) MMHistSignal200.Scale(MuMuTriggerEff * scalingLumi) EMHistSignal200.Scale(EMuTriggerEff * scalingLumi * RSFOF) if combination == "SF": edgeHist200 = EEHistSignal200.Clone() edgeHist200.Add(MMHistSignal200.Clone()) edgeHist200.Add(EMHistSignal200.Clone(), -1) if combination == "EE": edgeHist200 = EEHistSignal200.Clone() edgeHist200.Add(EMHistSignal200.Clone(), -0.5) if combination == "MM": edgeHist200 = MMHistSignal200.Clone() edgeHist200.Add(EMHistSignal200.Clone(), -0.5) for i in range(0, edgeHist200.GetNbinsX()): if edgeHist200.GetBinContent(i) < 0: edgeHist200.SetBinContent(i, 0.) edgeHist200.Add(bkgHist.Clone()) edgeHist200.SetLineColor(ROOT.kRed) edgeHist200.SetLineWidth(2) edgeHist200.SetLineStyle(ROOT.kDotted) plot.cuts = cutsWithoutSignalScaleFactors #~ lines = getLines(0, sfHist.GetBinContent(sfHist.GetMaximumBin())+10,xPos=[mllBins.lowMass.high,mllBins.onZ.low,mllBins.onZ.high, mllBins.highMass.low ]) #~ for line in lines: #~ line.Draw() if edgeShape or edgeShapeMC: leg = TLegend(0.55, 0.4, 0.92, 0.91, "", "brNDC") elif differentEdgePositions: leg = TLegend(0.55, 0.4, 0.95, 0.92, "", "brNDC") else: leg = TLegend(0.6, 0.5, 0.95, 0.92, "", "brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F, kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if region == "inclusive": leg.AddEntry(legendHistDing, "Inclusive signal region", "h") elif region == "central": leg.AddEntry(legendHistDing, "Legacy signal region", "h") elif region == "forward": leg.AddEntry(legendHistDing, "Forward signal region", "h") leg.AddEntry(sfHist, "Data", "pe1") #~ leg.AddEntry(bkgHist, "Total background","l") leg.AddEntry(bkgHistForLegend, "Flavor symmetric", "f") leg.AddEntry(dyHist, "Drell-Yan", "f") #~ leg.AddEntry(dyOnlyHist,"Z+jets", "f") #~ leg.AddEntry(rareBGHist,"Other SM", "f") leg.AddEntry(errGraph, "Total uncertainty", "f") if edgeShape: leg.AddEntry(legendHistDing, "Scaled 8 TeV signal fit:", "h") leg.AddEntry(edgeHist, "m_{#tilde{b}} = 300 GeV hypothesis", "l") leg.AddEntry(edgeHist500, "m_{#tilde{b}} = 500 GeV hypothesis", "l") leg.AddEntry(edgeHist700, "m_{#tilde{b}} = 700 GeV hypothesis", "l") if edgeShapeMC: leg.AddEntry(legendHistDing, "Slepton signal model", "h") leg.AddEntry( edgeHist450, "m_{#tilde{b}} = 450 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l") leg.AddEntry( edgeHist550, "m_{#tilde{b}} = 550 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l") leg.AddEntry( edgeHist650, "m_{#tilde{b}} = 650 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l") if differentEdgePositions: leg.AddEntry(legendHistDing, "Slepton signal model, m_{#tilde{b}} = 500 GeV", "h") leg.AddEntry(edgeHist75, "75 GeV edge position", "l") leg.AddEntry(edgeHist125, "125 GeV edge position", "l") leg.AddEntry(edgeHist200, "200 GeV edge position", "l") leg.Draw("same") errGraph.Draw("SAME02") if edgeShape: edgeHist.Draw("samehist") edgeHist500.Draw("samehist") edgeHist700.Draw("samehist") if edgeShapeMC: edgeHist450.Draw("samehist") edgeHist550.Draw("samehist") edgeHist650.Draw("samehist") if differentEdgePositions: edgeHist75.Draw("samehist") edgeHist125.Draw("samehist") edgeHist200.Draw("samehist") bkgHist.Draw("samehist") dyHist.Draw("samehist") #~ stack.Draw("samehist") sfHist.Draw("samepe1") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist, bkgHist, xMin=plot.firstBin, xMax=plot.lastBin, title="#frac{Data}{Prediction} ", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=1000) ratioGraphs.addErrorByHistograms("rSFOF", histUp, histDown, color=myColors["MyBlue"], fillStyle=3001) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) #~ leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC") #~ leg2.SetFillColor(10) #~ leg2.SetLineColor(10) #~ leg2.SetShadowColor(0) #~ leg2.SetBorderSize(1) #~ leg2.AddEntry(errGraph,"Systematic uncert.", "f") #~ leg2.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() if edgeShape: hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShape.pdf" % (selection.name, runRange.label, combination)) elif edgeShapeMC: hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShapeMC.pdf" % (selection.name, runRange.label, combination)) elif differentEdgePositions: hCanvas.Print( "fig/mllResult_%s_%s_%s_edgeShapeMC_differentEdgePositions.pdf" % (selection.name, runRange.label, combination)) else: hCanvas.Print("fig/mllResult_%s_%s_%s.pdf" % (selection.name, runRange.label, combination))
latexCentral.SetTextAlign(31) latexCentral.SetTextSize(0.07) latexCentral.SetNDC(True) #~ latexCentral.DrawLatex(0.4,0.45,"Central") latexForward = ROOT.TLatex() latexForward.SetTextFont(42) latexForward.SetTextAlign(31) latexForward.SetTextSize(0.07) latexForward.SetNDC(True) #~ latexForward.DrawLatex(0.88,0.45,"Forward") ratioPad.cd() #~ ratioGraphs = ratios.RatioGraph(datahist,drawStack.theHistogram, xMin=mainConfig.plot.firstBin, xMax=mainConfig.plot.lastBin,title="Data / MC",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=0.25) ratioGraphs = ratios.RatioGraph(histoSF,histoEM, plot.firstBin, plot.lastBin,title="SF / OF",yMin=0.5,yMax=1.5,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=0.25) x= array("f",[plot.firstBin, plot.lastBin]) y= array("f", [1.0,1.0]) ex= array("f", [0.,0.]) ey= array("f", [0.014,0.014]) ge= ROOT.TGraphErrors(2, x, y, ex, ey) ge.SetFillColor(ROOT.kBlue+2) ge.SetFillStyle(3001) ge.SetLineColor(ROOT.kWhite) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) ge.Draw("SAME 3") #~ line2 = ROOT.TLine(0.3,0,0.3,2) line2.SetLineColor(ROOT.kBlue+3)
def makeDependencyPlot(path, selection, plots, useMC, backgrounds, runRange, cmsExtra): colors = createMyColors() for plotName in plots: plot = getPlot(plotName) plot.addRegion(selection) plot.cuts = plot.cuts % runRange.runCut if "Forward" in selection.name: region = "forward" elif "Central" in selection.name: region = "central" else: region = "inclusive" tmpCuts = plot.cuts for binName in ["lowMass", "highMass"]: plot.cuts = tmpCuts plot.cuts += "*(p4.M() > %f && p4.M() < %f)" % (getattr( mllBins, binName).low, getattr(mllBins, binName).high) histEE, histMM, histEM = getHistograms(path, plot, runRange, False, []) histSF = histEE.Clone("histSF") histSF.Add(histMM.Clone()) histOFSF = histEM.Clone("histOFSF") histOFEE = histEM.Clone("histOFEE") histOFMM = histEM.Clone("histOFMM") histOFSF.Scale(getattr(rSFOF, region).val) histOFEE.Scale(getattr(rEEOF, region).val) histOFMM.Scale(getattr(rMMOF, region).val) if useMC: histEEMC, histMMMC, histEMMC = getHistograms( path, plot, runRange, True, backgrounds) histSFMC = histEEMC.Clone("histSFMC") histSFMC.Add(histMMMC.Clone()) histOFSFMC = histEMMC.Clone("histOFSFMC") histOFEEMC = histEMMC.Clone("histOFEEMC") histOFMMMC = histEMMC.Clone("histOFMMMC") histOFSFMC.Scale(getattr(rSFOF, region).valMC) histOFEEMC.Scale(getattr(rEEOF, region).valMC) histOFMMMC.Scale(getattr(rMMOF, region).valMC) histsSFMC = {} histsOFMC = {} histsSFMC["SF"] = histSFMC histsSFMC["EE"] = histEEMC histsSFMC["MM"] = histMMMC histsOFMC["SF"] = histOFSFMC histsOFMC["EE"] = histOFEEMC histsOFMC["MM"] = histOFMMMC histsSF = {} histsOF = {} histsSF["SF"] = histSF histsSF["EE"] = histEE histsSF["MM"] = histMM histsOF["SF"] = histOFSF histsOF["EE"] = histOFEE histsOF["MM"] = histOFMM for combination in ["SF", "EE", "MM"]: hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) style = setTDRStyle() style.SetPadTopMargin(0.07) ROOT.gStyle.SetOptStat(0) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() sfHist = histsSF[combination] bkgHist = histsOF[combination] sfHist.SetMarkerStyle(20) bkgHist.SetLineColor(ROOT.kBlue + 3) bkgHist.SetLineWidth(2) yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: yMax = yMax * 1.35 else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin, 0, plot.lastBin, yMax, "; %s ; %s" % (plot.xaxis, plot.yaxis)) 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)) if combination == "SF": rSFOFErr = getattr(rSFOF, region).err elif combination == "EE": rSFOFErr = getattr(rEEOF, region).err elif combination == "MM": rSFOFErr = getattr(rMMOF, region).err errGraph, histUp, histDown = getErrHist( plot, combination, region, bkgHist, None, rSFOFErr) errGraph.SetFillColor(myColors["MyBlue"]) errGraph.SetFillStyle(3001) #~ errGraph.SetLineColor(myColors["MyDarkBlue"]) #~ errGraph.SetMarkerColor(myColors["MyDarkBlue"]) errGraph.Draw("SAME02") bkgHist.Draw("samehist") sfHist.Draw("samepe") leg = TLegend(0.62, 0.51, 0.89, 0.92, "", "brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F, kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if region == "inclusive": leg.AddEntry(legendHistDing, "Inclusive signal region", "h") elif region == "central": leg.AddEntry(legendHistDing, "Central signal region", "h") elif region == "forward": leg.AddEntry(legendHistDing, "Forward signal region", "h") leg.AddEntry(sfHist, "Data", "PE") leg.AddEntry(bkgHist, "Flav. Sym. backgrounds", "l") leg.AddEntry(errGraph, "Background uncert.", "f") leg.Draw("same") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist, bkgHist, xMin=plot.firstBin, xMax=plot.lastBin, title="%s / OF" % combination, yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=1000) ratioGraphs.addErrorByHistograms("rSFOF", histUp, histDown, color=myColors["MyBlue"], fillStyle=3001) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) leg2 = TLegend(0.175, 0.78, 0.475, 0.9, "", "brNDC") leg2.SetFillColor(10) leg2.SetLineColor(10) leg2.SetShadowColor(0) leg2.SetBorderSize(1) leg2.AddEntry(errGraph, "Systematic uncert.", "f") leg2.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("fig/rSFOFDependency_%s_%s_%s_%s_%s.pdf" % (selection.name, plot.variablePlotName, runRange.label, combination, binName))
def main(): ### for data histos = ["BB", "BE"] labels = ["dimuon_Moriond2017_BB", "dimuon_Moriond2017_BE"] bins = [4, 7] massPlot = getPlot("massPlotForLimit") massPlotSmeared = getPlot("massPlotSmeared") massPlotUp = getPlot("massPlotUp") massPlotDown = getPlot("massPlotDown") massPlotPUUp = getPlot("massPlotPUUp") massPlotPUDown = getPlot("massPlotPUDown") massPlotWeighted = getPlot("massPlotWeighted") for i, histo in enumerate(histos): label = labels[i] drellyan = Process(getattr(Backgrounds, "DrellYan")) other = Process(getattr(Backgrounds, "Other")) #~ drellyan = Process(getattr(Signals,"CITo2Mu_Lam34TeVConLL")) dyHist = deepcopy(drellyan.loadHistogramProjected(massPlot, bins[i])) dyHistSmear = deepcopy( drellyan.loadHistogramProjected(massPlotSmeared, bins[i])) dyHistScaleUp = deepcopy( drellyan.loadHistogramProjected(massPlotUp, bins[i])) dyHistScaleDown = deepcopy( drellyan.loadHistogramProjected(massPlotDown, bins[i])) dyHistPUUp = deepcopy( drellyan.loadHistogramProjected(massPlotPUUp, bins[i])) dyHistPUDown = deepcopy( drellyan.loadHistogramProjected(massPlotPUDown, bins[i])) dyHistWeighted = deepcopy( drellyan.loadHistogramProjected(massPlotWeighted, bins[i])) if "_BE" in label: dyHist.Add(deepcopy(drellyan.loadHistogramProjected(massPlot, 10))) dyHistSmear.Add( deepcopy(drellyan.loadHistogramProjected(massPlotSmeared, 10))) dyHistScaleUp.Add( deepcopy(drellyan.loadHistogramProjected(massPlotUp, 10))) dyHistScaleDown.Add( deepcopy(drellyan.loadHistogramProjected(massPlotDown, 10))) dyHistPUUp.Add( deepcopy(drellyan.loadHistogramProjected(massPlotPUUp, 10))) dyHistPUDown.Add( deepcopy(drellyan.loadHistogramProjected(massPlotPUDown, 10))) dyHistWeighted.Add( deepcopy(drellyan.loadHistogramProjected(massPlotWeighted, 10))) dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, bins[i]))) dyHistSmear.Add( deepcopy(other.loadHistogramProjected(massPlotSmeared, bins[i]))) dyHistScaleUp.Add( deepcopy(other.loadHistogramProjected(massPlotUp, bins[i]))) dyHistScaleDown.Add( deepcopy(other.loadHistogramProjected(massPlotDown, bins[i]))) dyHistPUUp.Add( deepcopy(other.loadHistogramProjected(massPlotPUUp, bins[i]))) dyHistPUDown.Add( deepcopy(other.loadHistogramProjected(massPlotPUDown, bins[i]))) dyHistWeighted.Add( deepcopy(other.loadHistogramProjected(massPlotWeighted, bins[i]))) if "_BE" in label: dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, 10))) dyHistSmear.Add( deepcopy(other.loadHistogramProjected(massPlotSmeared, 10))) dyHistScaleUp.Add( deepcopy(other.loadHistogramProjected(massPlotUp, 10))) dyHistScaleDown.Add( deepcopy(other.loadHistogramProjected(massPlotDown, 10))) dyHistPUUp.Add( deepcopy(other.loadHistogramProjected(massPlotPUUp, 10))) dyHistPUDown.Add( deepcopy(other.loadHistogramProjected(massPlotPUDown, 10))) dyHistWeighted.Add( deepcopy(other.loadHistogramProjected(massPlotWeighted, 10))) rebin = 500 dyHist.Rebin(rebin) dyHistSmear.Rebin(rebin) dyHistPUUp.Rebin(rebin) dyHistPUDown.Rebin(rebin) dyHistScaleDown.Rebin(rebin) dyHistWeighted.Rebin(rebin) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(0, 0.0001, 5000, 500000, "; dimuon mass [GeV]; Events / 500 GeV") plotPad.SetLogy() dyHist.Draw("samehist") dyHist.SetFillColor(kWhite) dyHistSmear.SetFillColor(kWhite) dyHistScaleDown.SetFillColor(kWhite) dyHistWeighted.SetFillColor(kWhite) dyHistPUUp.SetFillColor(kWhite) dyHistPUDown.SetFillColor(kWhite) dyHistSmear.SetLineColor(kRed) dyHistScaleDown.SetLineColor(kBlue) dyHistWeighted.SetLineColor(kGreen + 2) dyHistPUUp.SetLineColor(kOrange + 2) dyHistSmear.Draw("samehist") dyHistScaleDown.Draw("samehist") dyHistWeighted.Draw("samehist") dyHistPUUp.Draw("samehist") legend = TLegend(0.375, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.AddEntry(dyHist, "Default", "l") legend.AddEntry(dyHistSmear, "Resolution Uncertainty", "l") legend.AddEntry(dyHistScaleDown, "Scale Uncertainty", "l") legend.AddEntry(dyHistWeighted, "ID Uncertainty", "l") legend.AddEntry(dyHistPUUp, "PU Uncertainty", "l") legend.Draw() ratioPad.cd() xMin = 0 xMax = 5000 yMax = 1.1 yMin = 0.9 if "BE" in label: yMax = 1.2 yMin = 0.8 ratioGraphs = ratios.RatioGraph(dyHist, dyHistSmear, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=yMin, yMax=yMax, ndivisions=10, color=kRed, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ratioGraphs2 = ratios.RatioGraph(dyHist, dyHistScaleDown, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kBlue, adaptiveBinning=10000) ratioGraphs2.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) ratioGraphs3 = ratios.RatioGraph(dyHist, dyHistWeighted, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kGreen + 2, adaptiveBinning=10000) ratioGraphs3.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) ratioGraphs4 = ratios.RatioGraph(dyHist, dyHistPUUp, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kOrange + 2, adaptiveBinning=10000) ratioGraphs4.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) hCanvas.Print("uncertainties_%s.pdf" % label)
def plotDataMC(mainConfig, dilepton): import gc gc.enable() from ROOT import TCanvas, TPad, TH1F, TH1I, THStack, TLegend, TMath, gROOT import ratios from defs import Backgrounds from defs import Backgrounds2011 from defs import Signals from defs import defineMyColors from defs import myColors from defs import Region from defs import Regions from defs import Plot from setTDRStyle import setTDRStyle gROOT.SetBatch(True) from helpers import * import math if mainConfig.forPAS: hCanvas = TCanvas("hCanvas", "Distribution", 600, 800) else: hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) if mainConfig.plotRatio: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() else: plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1) setTDRStyle() plotPad.UseCurrentStyle() plotPad.Draw() plotPad.cd() colors = createMyColors() eventCounts = totalNumberOfGeneratedEvents(mainConfig.dataSetPath) processes = [] for background in mainConfig.backgrounds: processes.append(Process(getattr(Backgrounds, background), eventCounts)) signals = [] for signal in mainConfig.signals: signals.append(Process(getattr(Signals, signal), eventCounts)) legend = TLegend(0.375, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetNColumns(2) legendEta = TLegend(0.15, 0.75, 0.7, 0.9) legendEta.SetFillStyle(0) legendEta.SetBorderSize(0) legendEta.SetTextFont(42) 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.06) latexCMS.SetNDC(True) latexCMSExtra = ROOT.TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.045) latexCMSExtra.SetNDC(True) legendHists = [] legendHistData = ROOT.TH1F() if mainConfig.plotData: legend.AddEntry(legendHistData, "Data", "pe") legendEta.AddEntry(legendHistData, "Data", "pe") for process in reversed(processes): temphist = ROOT.TH1F() temphist.SetFillColor(process.theColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, process.label, "f") legendEta.AddEntry(temphist, process.label, "f") #~ if mainConfig.plotSignal: #~ processes.append(Signal) if mainConfig.plotRatio: temphist = ROOT.TH1F() temphist.SetFillColor(myColors["MyGreen"]) legendHists.append(temphist.Clone) #~ legend.AddEntry(temphist,"Syst. uncert.","f") temphist2 = ROOT.TH1F() temphist2.SetFillColor(myColors["DarkRed"], ) temphist2.SetFillStyle(3002) legendHists.append(temphist2.Clone) #~ legend.AddEntry(temphist2,"JEC & Pileup Uncert.","f") if mainConfig.plotSignal: processesWithSignal = [] for process in processes: processesWithSignal.append(process) for Signal in signals: processesWithSignal.append(Signal) temphist = ROOT.TH1F() temphist.SetFillColor(Signal.theColor) temphist.SetLineColor(Signal.theLineColor) legendHists.append(temphist.Clone) legend.AddEntry(temphist, Signal.label, "l") legendEta.AddEntry(temphist, Signal.label, "l") nEvents = -1 ROOT.gStyle.SetOptStat(0) intlumi = ROOT.TLatex() intlumi.SetTextAlign(12) intlumi.SetTextSize(0.045) intlumi.SetNDC(True) intlumi2 = ROOT.TLatex() intlumi2.SetTextAlign(12) intlumi2.SetTextSize(0.07) intlumi2.SetNDC(True) scalelabel = ROOT.TLatex() scalelabel.SetTextAlign(12) scalelabel.SetTextSize(0.03) scalelabel.SetNDC(True) metDiffLabel = ROOT.TLatex() metDiffLabel.SetTextAlign(12) metDiffLabel.SetTextSize(0.03) metDiffLabel.SetNDC(True) chi2Label = ROOT.TLatex() chi2Label.SetTextAlign(12) chi2Label.SetTextSize(0.03) chi2Label.SetNDC(True) hCanvas.SetLogy() treeEE = readTrees(mainConfig.dataSetPath, "EE") treeMuMu = readTrees(mainConfig.dataSetPath, "MuMu") treeEMu = readTrees(mainConfig.dataSetPath, "EMu") mainConfig.plot.addDilepton(dilepton) plotPad.cd() plotPad.SetLogy(0) logScale = mainConfig.plot.log if mainConfig.plot.variable == "met" or mainConfig.plot.variable == "type1Met" or mainConfig.plot.variable == "tcMet" or mainConfig.plot.variable == "caloMet" or mainConfig.plot.variable == "mht": logScale = True if logScale == True: plotPad.SetLogy() scaleTree1 = 1.0 scaleTree2 = 1.0 if mainConfig.plot.tree1 == "EE": tree1 = treeEE scaleTree1 = mainConfig.selection.trigEffs.effEE.val elif mainConfig.plot.tree1 == "MuMu": tree1 = treeMuMu scaleTree1 = mainConfig.selection.trigEffs.effMM.val elif mainConfig.plot.tree1 == "EMu": tree1 = treeEMu scaleTree1 = mainConfig.selection.trigEffs.effEM.val else: print "Unknown Dilepton combination! %s not created!" % ( mainConfig.plot.filename, ) return if mainConfig.plot.tree2 != "None": if mainConfig.plot.tree2 == "EE": tree2 = treeEE scaleTree2 = mainConfig.selection.trigEffs.effEE.val elif mainConfig.plot.tree2 == "MuMu": tree2 = treeMuMu scaleTree2 = mainConfig.selection.trigEffs.effMM.val elif mainConfig.plot.tree2 == "EMu": tree2 = treeEMu scaleTree2 = mainConfig.selection.trigEffs.effEM.val else: print "Unknown Dilepton combination! %s not created!" % ( mainConfig.plot.filename, ) return else: tree2 = "None" if mainConfig.useTriggerEmulation or mainConfig.DontScaleTrig: scaleTree2 = 1.0 scaleTree1 = 1.0 if mainConfig.normalizeToData: pickleName = mainConfig.plot.filename % ( "_scaled_" + mainConfig.runRange.label + "_" + dilepton) elif mainConfig.useTriggerEmulation: pickleName = mainConfig.plot.filename % ( "_TriggerEmulation_" + mainConfig.runRange.label + "_" + dilepton) elif mainConfig.DontScaleTrig: pickleName = mainConfig.plot.filename % ( "_NoTriggerScaling_" + mainConfig.runRange.label + "_" + dilepton) else: pickleName = mainConfig.plot.filename % ( "_" + mainConfig.runRange.label + "_" + dilepton) #~ mainConfig.plot.cuts = mainConfig.plot.cuts.replace("chargeProduct < 0","chargeProduct > 0") counts = {} import pickle print mainConfig.plot.cuts datahist = getDataHist(mainConfig.plot, tree1, tree2) print datahist.GetEntries() #~ print mainConfig.plot.variable #~ mainConfig.plot.cuts = mainConfig.plot.cuts.replace("met","patPFMet") #~ print mainConfig.plot.cuts stack = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, counts=counts, doTopReweighting=mainConfig.doTopReweighting, theoUncert=mainConfig.theoUncert, doPUWeights=mainConfig.doPUWeights) errIntMC = ROOT.Double() intMC = stack.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) val = float(intMC) err = float(errIntMC) counts["Total Background"] = {"val": val, "err": err} counts["Data"] = { "val": datahist.Integral(0, datahist.GetNbinsX() + 1), "err": math.sqrt(datahist.Integral(0, datahist.GetNbinsX() + 1)) } if mainConfig.plotData: yMax = datahist.GetBinContent(datahist.GetMaximumBin()) else: yMax = stack.theHistogram.GetBinContent(datahist.GetMaximumBin()) if mainConfig.plot.yMax == 0: if logScale: yMax = yMax * 1000 else: yMax = yMax * 1.5 else: yMax = plot.yMax plotPad.DrawFrame( mainConfig.plot.firstBin, mainConfig.plot.yMin, mainConfig.plot.lastBin, yMax, "; %s ; %s" % (mainConfig.plot.xaxis, mainConfig.plot.yaxis)) if mainConfig.normalizeToData: scalefac = datahist.Integral(datahist.FindBin( plot.firstBin), datahist.FindBin( plot.lastBin)) / stack.theHistogram.Integral( stack.theHistogram.FindBin(plot.firstBin), stack.theHistogram.FindBin(plot.lastBin)) drawStack = TheStack(processes, lumi, plot, tree1, tree2, 1.0, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights) stackJESUp = TheStack(processes, lumi, plot, tree1, tree2, 0.955, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights) stackJESDown = TheStack(processes, lumi, plot, tree1, tree2, 1.045, scalefac * scaleTree1, scalefac * scaleTree2, doPUWeights=mainConfig.doPUWeights) else: drawStack = stack if mainConfig.plotSyst: mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "met", "metJESUp") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( " ht", "htJESUp") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "nJets", "nShiftedJetsJESUp") stackJESUp = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, JESUp=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "metJESUp", "metJESDown") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "htJESUp", "htJESDown") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "nShiftedJetsJESUp", "nShiftedJetsJESDown") stackJESDown = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, JESDown=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "metJESDown", "met") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "htJESDown", "ht") mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "nShiftedJetsJESDown", "nJets") mainConfig.plot.cuts = mainConfig.plot.cuts.replace("*(", "Up*(") stackPileUpUp = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, PileUpUp=True, counts=counts, doPUWeights=mainConfig.doPUWeights) mainConfig.plot.cuts = mainConfig.plot.cuts.replace( "Up*(", "Down*(") stackPileUpDown = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, saveIntegrals=True, PileUpDown=True, counts=counts, doPUWeights=mainConfig.doPUWeights) mainConfig.plot.cuts = mainConfig.plot.cuts.replace("Down*(", "*(") if mainConfig.doTopReweighting: stackReweightDown = TheStack( processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, TopWeightDown=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights) stackReweightUp = TheStack(processes, mainConfig.runRange.lumi, mainConfig.plot, tree1, tree2, 1.0, scaleTree1, scaleTree2, TopWeightUp=True, saveIntegrals=True, counts=counts, doPUWeights=mainConfig.doPUWeights) if mainConfig.plotSyst: errIntMC = ROOT.Double() intMCJESUp = stackJESUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCJESDown = stackJESDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valJESUp = float(intMCJESUp) valJESDown = float(intMCJESDown) jesUp = abs(counts["Total Background"]["val"] - valJESUp) jesDown = abs(counts["Total Background"]["val"] - valJESDown) counts["Total Background"]["jesDown"] = jesDown counts["Total Background"]["jesUp"] = jesUp errIntMC = ROOT.Double() intMCPileUpUp = stackPileUpUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCPileUpDown = stackPileUpDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valPileUpUp = float(intMCPileUpUp) valPileUpDown = float(intMCPileUpDown) pileUpUp = abs(counts["Total Background"]["val"] - valPileUpUp) pileUpDown = abs(counts["Total Background"]["val"] - valPileUpDown) counts["Total Background"]["pileUpDown"] = pileUpDown counts["Total Background"]["pileUpUp"] = pileUpUp if mainConfig.doTopReweighting: errIntMC = ROOT.Double() intMCTopWeightUp = stackReweightUp.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) errIntMC = ROOT.Double() intMCTopWeightDown = stackReweightDown.theHistogram.IntegralAndError( 0, stack.theHistogram.GetNbinsX() + 1, errIntMC) valTopWeightUp = float(intMCTopWeightUp) valTopWeightDown = float(intMCTopWeightDown) topWeightUp = abs(counts["Total Background"]["val"] - valTopWeightUp) topWeightDown = abs(counts["Total Background"]["val"] - valTopWeightDown) counts["Total Background"]["topWeightDown"] = topWeightDown counts["Total Background"]["topWeightUp"] = topWeightUp xSec = abs( stack.theHistogramXsecUp.Integral(0, stack.theHistogram.GetNbinsX() + 1) - counts["Total Background"]["val"]) counts["Total Background"]["xSec"] = xSec theoUncert = abs( stack.theHistogramTheoUp.Integral(0, stack.theHistogram.GetNbinsX() + 1) - counts["Total Background"]["val"]) counts["Total Background"]["theo"] = theoUncert outFilePkl = open("shelves/%s.pkl" % (pickleName), "w") pickle.dump(counts, outFilePkl) outFilePkl.close() if mainConfig.plotSignal: signalhists = [] for Signal in signals: signalhist = Signal.createCombinedHistogram(lumi, plot, tree1, tree2, signal=True) signalhist.SetLineWidth(2) signalhist.Add(stack.theHistogram) signalhist.SetMinimum(0.1) signalhist.Draw("samehist") signalhists.append(signalhist) drawStack.theStack.Draw("samehist") dileptonLabel = "" if dilepton == "SF": dileptonLabel = "ee + #mu#mu" if dilepton == "OF": dileptonLabel = "e#mu" if dilepton == "EE": dileptonLabel = "ee" if dilepton == "MuMu": dileptonLabel = "#mu#mu" datahist.SetMinimum(0.1) if mainConfig.plotData: datahist.Draw("samep") if mainConfig.normalizeToData: scalelabel.DrawLatex(0.6, 0.4, "Background scaled by %.2f" % (scalefac)) if mainConfig.plot.variable == "eta1" or mainConfig.plot.variable == "eta2": legendEta.SetNColumns(2) legendEta.Draw() intlumi.DrawLatex( 0.2, 0.7, "#splitline{" + mainConfig.plot.label + " " + dileptonLabel + "}{#splitline{" + mainConfig.plot.label2 + "}{" + mainConfig.plot.label3 + "}}") else: legend.Draw() intlumi.DrawLatex( 0.45, 0.55, "#splitline{%s}{%s}" % (mainConfig.plot.label2, dileptonLabel)) latex.DrawLatex(0.95, 0.96, "%s fb^{-1} (13 TeV)" % (mainConfig.runRange.printval, )) yLabelPos = 0.85 cmsExtra = "" if mainConfig.personalWork: cmsExtra = "Private Work" if not mainConfig.plotData: cmsExtra = "#splitline{Private Work}{Simulation}" yLabelPos = 0.82 elif not mainConfig.plotData: cmsExtra = "Simulation" elif mainConfig.preliminary: cmsExtra = "Preliminary" elif mainConfig.forTWIKI: cmsExtra = "Unpublished" if mainConfig.forPAS: latexCMS.DrawLatex(0.15, 0.955, "CMS") latexCMSExtra.DrawLatex(0.26, 0.955, "%s" % (cmsExtra)) else: latexCMS.DrawLatex(0.19, 0.89, "CMS") latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra)) if mainConfig.plotRatio: try: ratioPad.cd() except AttributeError: print "Plot fails. Look up in errs/failedPlots.txt" outFile = open("errs/failedPlots.txt", "a") outFile.write('%s\n' % plot.filename % ("_" + run.label + "_" + dilepton)) outFile.close() plot.cuts = baseCut return 1 ratioGraphs = ratios.RatioGraph(datahist, drawStack.theHistogram, xMin=mainConfig.plot.firstBin, xMax=mainConfig.plot.lastBin, title="Data / MC", yMin=0.0, yMax=2, ndivisions=10, color=ROOT.kBlack, adaptiveBinning=0.25) if mainConfig.plotSyst: ratioGraphs.addErrorByHistograms("Pileup", stackPileUpUp.theHistogram, stackPileUpDown.theHistogram, color=myColors["MyGreen"]) ratioGraphs.addErrorByHistograms("JES", stackJESUp.theHistogram, stackJESDown.theHistogram, color=myColors["MyGreen"]) if mainConfig.doTopReweighting: ratioGraphs.addErrorByHistograms( "TopWeight", stackReweightUp.theHistogram, stackReweightDown.theHistogram, color=myColors["MyGreen"]) ratioGraphs.addErrorBySize("Effs", 0.06726812023536856, color=myColors["MyGreen"], add=True) ratioGraphs.addErrorByHistograms("Xsecs", drawStack.theHistogramXsecUp, drawStack.theHistogramXsecDown, color=myColors["MyGreen"], add=True) ratioGraphs.addErrorByHistograms("Theo", drawStack.theHistogramTheoUp, drawStack.theHistogramTheoDown, color=myColors["MyGreen"], add=True) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) if mainConfig.plotSignal: signalRatios = [] legendRatio = TLegend(0.175, 0.725, 0.65, 0.95) legendRatio.SetFillStyle(0) legendRatio.SetBorderSize(0) legendRatio.SetTextFont(42) backgroundHist = ROOT.TH1F() legendRatio.AddEntry(backgroundHist, "Data / background", "pe") temphist = ROOT.TH1F() temphist.SetFillColor(myColors["MyGreen"]) if mainConfig.plotSyst: legendRatio.AddEntry(temphist, "Syst. uncert.", "f") legendRatio.SetNColumns(2) for index, signalhist in enumerate(signalhists): signalRatios.append( ratios.RatioGraph(datahist, signalhist, xMin=plot.firstBin, xMax=plot.lastBin, title="Data / MC", yMin=0.0, yMax=2, ndivisions=10, color=signalhist.GetLineColor(), adaptiveBinning=0.25)) signalRatios[index].draw(ROOT.gPad, False, False, True, chi2Pos=0.7 - index * 0.1) signalhist.SetMarkerColor(signalhist.GetLineColor()) legendRatio.AddEntry(signalhist, "Data / Background + Signal", "p") legendRatio.Draw("same") ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() if mainConfig.plotRatio: ratioPad.RedrawAxis() nameModifier = mainConfig.runRange.label + "_" + dilepton if mainConfig.doTopReweighting: nameModifier += "_TopReweighted" if mainConfig.plotData == False: nameModifier += "_MCOnly" if mainConfig.normalizeToData: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_scaled_" + nameModifier), ) elif mainConfig.useTriggerEmulation: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_TriggerEmulation_" + nameModifier), ) elif mainConfig.DontScaleTrig: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_NoTriggerScaling_" + nameModifier), ) else: hCanvas.Print( "fig/DataMC/" + mainConfig.plot.filename % ("_" + nameModifier), )
def main(): ### for data histos = ["BBBE"] #~ labels = ["dielectron_Moriond2017_BB","dielectron_Moriond2017_BE"] labels = ["dielectron_Moriond2017_BBBE"] #~ bins = [4,7] bins = [4] massPlot = getPlot("massPlotForLimit") #~ massPlotSmeared = getPlot("massPlotSmeared") massPlotUp = getPlot("massPlotUp") massPlotDown = getPlot("massPlotDown") massPlotPUUp = getPlot("massPlotPUUp") massPlotPUDown = getPlot("massPlotPUDown") #~ massPlotWeighted = getPlot("massPlotWeighted") for i, histo in enumerate(histos): label = labels[i] drellyan = Process(getattr(Backgrounds, "DrellYan")) other = Process(getattr(Backgrounds, "Other")) #~ drellyan = Process(getattr(Signals,"CITo2Mu_Lam34TeVConLL")) dyHist = deepcopy(drellyan.loadHistogramProjected(massPlot, bins[i])) dyHistScaleUp = deepcopy( drellyan.loadHistogramProjected(massPlotUp, bins[i])) dyHistScaleDown = deepcopy( drellyan.loadHistogramProjected(massPlotDown, bins[i])) dyHistPUUp = deepcopy( drellyan.loadHistogramProjected(massPlotPUUp, bins[i])) dyHistPUDown = deepcopy( drellyan.loadHistogramProjected(massPlotPUDown, bins[i])) dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, bins[i]))) dyHistScaleUp.Add( deepcopy(other.loadHistogramProjected(massPlotUp, bins[i]))) dyHistScaleDown.Add( deepcopy(other.loadHistogramProjected(massPlotDown, bins[i]))) dyHistPUUp.Add( deepcopy(other.loadHistogramProjected(massPlotPUUp, bins[i]))) dyHistPUDown.Add( deepcopy(other.loadHistogramProjected(massPlotPUDown, bins[i]))) dyHist.Add(deepcopy(other.loadHistogramProjected(massPlot, 7))) dyHistScaleUp.Add(deepcopy(other.loadHistogramProjected(massPlotUp, 7))) dyHistScaleDown.Add( deepcopy(other.loadHistogramProjected(massPlotDown, 7))) dyHistPUUp.Add(deepcopy(other.loadHistogramProjected(massPlotPUUp, 7))) dyHistPUDown.Add( deepcopy(other.loadHistogramProjected(massPlotPUDown, 7))) dyHist.Add(deepcopy(drellyan.loadHistogramProjected(massPlot, 7))) dyHistScaleUp.Add( deepcopy(drellyan.loadHistogramProjected(massPlotUp, 7))) dyHistScaleDown.Add( deepcopy(drellyan.loadHistogramProjected(massPlotDown, 7))) dyHistPUUp.Add( deepcopy(drellyan.loadHistogramProjected(massPlotPUUp, 7))) dyHistPUDown.Add( deepcopy(drellyan.loadHistogramProjected(massPlotPUDown, 7))) #~ rebin = 250 binningEle = binning(channel="electron") dyHist = rebin(dyHist, binningEle) dyHistScaleUp = rebin(dyHistScaleUp, binningEle) dyHistScaleDown = rebin(dyHistScaleDown, binningEle) dyHistPUUp = rebin(dyHistPUUp, binningEle) dyHistPUDown = rebin(dyHistPUDown, binningEle) #~ dyHist.Rebin(rebin) #~ dyHistPUUp.Rebin(rebin) #~ dyHistPUDown.Rebin(rebin) #~ dyHistScaleUp.Rebin(rebin) #~ dyHistScaleDown.Rebin(rebin) hCanvas = TCanvas("hCanvas", "Distribution", 800, 800) plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1) ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3) setTDRStyle() plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() plotPad.DrawFrame(250, 0.00001, 5000, 500000000, "; dielectron mass [GeV]; Events / 250 GeV") plotPad.SetLogy() dyHist.Draw("samehist") dyHist.SetFillColor(kWhite) dyHistScaleUp.SetFillColor(kWhite) dyHistScaleDown.SetFillColor(kWhite) dyHistPUUp.SetFillColor(kWhite) dyHistPUDown.SetFillColor(kWhite) dyHistScaleUp.SetLineColor(kBlue) dyHistScaleDown.SetLineColor(kBlue) dyHistPUUp.SetLineColor(kOrange + 2) dyHistPUDown.SetLineColor(kOrange + 2) dyHistScaleDown.Draw("samehist") dyHistScaleUp.Draw("samehist") dyHistPUUp.Draw("samehist") dyHistPUDown.Draw("samehist") legend = TLegend(0.375, 0.6, 0.925, 0.925) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.AddEntry(dyHist, "Default", "l") legend.AddEntry(dyHistScaleDown, "Scale Uncertainty", "l") legend.AddEntry(dyHistPUUp, "PU Uncertainty", "l") legend.Draw() ratioPad.cd() xMin = 250 xMax = 5000 yMax = 1.5 yMin = 0 if "BE" in label: yMax = 1.5 yMin = 0.5 ratioGraphs = ratios.RatioGraph(dyHist, dyHistScaleUp, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=yMin, yMax=yMax, ndivisions=10, color=kBlue, adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) ratioGraphs2 = ratios.RatioGraph(dyHist, dyHistScaleDown, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kBlue, adaptiveBinning=10000) ratioGraphs2.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) ratioGraphs3 = ratios.RatioGraph(dyHist, dyHistPUDown, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kOrange + 2, adaptiveBinning=10000) ratioGraphs3.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) ratioGraphs4 = ratios.RatioGraph(dyHist, dyHistPUUp, xMin=xMin, xMax=xMax, title="Default / Uncert", yMin=0.8, yMax=1.3, ndivisions=10, color=kOrange + 2, adaptiveBinning=10000) ratioGraphs4.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) #~ ratio = ratioGraphs.getGraph() ratio = dyHist.Clone() ratio.Divide(dyHistScaleUp) ratio.GetXaxis().SetRangeUser(0, 5000) ratio.GetYaxis().SetRangeUser(0, 2) func = TF1("f1", "pol4", 250, 5000) #~ func.SetParameter(0,1.1) ratio.Fit("f1", "R") #~ func.Draw("sameL") plotF1 = TF1("plotF1", "pol4", 250, 5000) plotF1.SetParameter(0, f1.GetParameter(0)) plotF1.SetParameter(1, f1.GetParameter(1)) plotF1.SetParameter(2, f1.GetParameter(2)) plotF1.SetParameter(3, f1.GetParameter(3)) plotF1.SetParameter(4, f1.GetParameter(4)) ratio2 = dyHist.Clone() #~ ratio2 = ratioGraphs2.getGraph() ratio2.GetXaxis().SetRangeUser(0, 5000) ratio2.GetYaxis().SetRangeUser(0, 2) ratio2.Divide(dyHistScaleDown) func2 = TF1("f2", "pol4", 250, 5000) #~ func2.SetParameter(0,0.9) ratio2.Fit("f2", "R") #~ func2.Draw("sameL") plotF2 = TF1("plotF1", "pol4", 250, 5000) plotF2.SetParameter(0, f2.GetParameter(0)) plotF2.SetParameter(1, f2.GetParameter(1)) plotF2.SetParameter(2, f2.GetParameter(2)) plotF2.SetParameter(3, f2.GetParameter(3)) plotF2.SetParameter(4, f2.GetParameter(4)) #~ ratioGraphs = ratios.RatioGraph(dyHist,dyHistScaleUp, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=yMin,yMax=yMax,ndivisions=10,color=kBlue,adaptiveBinning=10000) ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8) #~ ratioGraphs2 = ratios.RatioGraph(dyHist,dyHistScaleDown, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kBlue,adaptiveBinning=10000) ratioGraphs2.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) #~ ratioGraphs3 = ratios.RatioGraph(dyHist,dyHistPUDown, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kOrange+2,adaptiveBinning=10000) ratioGraphs3.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) #~ ratioGraphs4 = ratios.RatioGraph(dyHist,dyHistPUUp, xMin=xMin, xMax=xMax,title="Default / Uncert",yMin=0.8,yMax=1.3,ndivisions=10,color=kOrange+2,adaptiveBinning=10000) ratioGraphs4.draw(ROOT.gPad, False, False, True, chi2Pos=0.8) plotF1.Draw("sameL") plotF2.Draw("sameL") hCanvas.Print("uncertainties_%s.pdf" % label)
hist.SetLineColor(dataset.color) hist.SetLineWidth(2) multihisto.addHisto(hist, dataset.label) histForRatio[dataset.label] = hist can = ROOT.TCanvas() hPad = ROOT.TPad("hPad", "Histogram", 0, 0, 1, 1) #hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1) hPad.cd() multihisto.Draw("hist") ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2) ratioPad.cd() ratioPad.SetLogy(0) ratioGraph = ratios.RatioGraph(histForRatio["e"], histForRatio["e_{gen}"]) ratioGraph.draw(ROOT.gPad, yMin=0.5, yMax=1.5, adaptiveBinning=False, errors="x") ratioGraph.hAxis.SetYTitle("e/e_{gen}") ratioGraph.graph.Draw("same p") can.cd() hPad.Draw() #ratioPad.Draw() can.SaveAs("plots/%s_%s_%s.pdf" % (opts.input[0:5], opts.plot.replace(".", ""), opts.savePrefix)) del can
latexCentral = ROOT.TLatex() latexCentral.SetTextFont(42) latexCentral.SetTextAlign(31) latexCentral.SetTextSize(0.07) latexCentral.SetNDC(True) #~ latexCentral.DrawLatex(0.4,0.45,"Central") latexForward = ROOT.TLatex() latexForward.SetTextFont(42) latexForward.SetTextAlign(31) latexForward.SetTextSize(0.07) latexForward.SetNDC(True) #~ latexForward.DrawLatex(0.88,0.45,"Forward") ratioPad.cd() ratioGraphs = ratios.RatioGraph(eeHist,mmHist, 0, 5,title="e^{#pm}e^{#mp} / #mu^{#pm}#mu^{#mp}",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kRed,adaptiveBinning=0.25) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) line2 = ROOT.TLine(0.3,0,0.3,2) line2.SetLineColor(ROOT.kBlue+3) line2.SetLineWidth(2) line2.SetLineStyle(2) line2.Draw("same") hCanvas.Print("dRJustification_eeVSmm.pdf")
def makePlot(sfHist,ofHist,selection,plot,runRange,cmsExtra): colors = createMyColors() hCanvas = TCanvas("hCanvas", "Distribution", 800,800) plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1) ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3) style = setTDRStyle() ROOT.gStyle.SetOptStat(0) style.SetPadTopMargin(0.07) plotPad.UseCurrentStyle() ratioPad.UseCurrentStyle() plotPad.Draw() ratioPad.Draw() plotPad.cd() yMax = sfHist.GetBinContent(sfHist.GetMaximumBin()) if plot.yMax == 0: yMax = yMax*1.5 else: yMax = plot.yMax plotPad.DrawFrame(plot.firstBin,0,plot.lastBin, yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis)) #set overflow bin print sfHist.GetBinContent(sfHist.GetNbinsX()), sfHist.GetBinContent(sfHist.GetNbinsX()+1) sfHist.SetBinContent(sfHist.GetNbinsX(),sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1)) sfHist.SetBinError(sfHist.GetNbinsX(),(sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))**0.5) ofHist.SetBinContent(ofHist.GetNbinsX(),ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1)) ofHist.SetBinError(ofHist.GetNbinsX(),(ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))**0.5) rSFOFErr = rSFOF.inclusive.err errGraph, histUp, histDown = getErrHist(plot,ofHist,rSFOFErr) sfHist.SetMarkerStyle(20) sfHist.SetLineColor(ROOT.kBlack) ofHist.SetLineColor(ROOT.kBlue+3) ofHist.SetLineWidth(2) latex = ROOT.TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.055) latex.SetLineWidth(2) 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.93, 0.942, "%s fb^{-1} (13 TeV)"%runRange.printval) latexCMS.DrawLatex(0.19,0.86,"CMS") if "Simulation" in cmsExtra: yLabelPos = 0.81 else: yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra)) leg = TLegend(0.55, 0.6, 0.95, 0.92,"","brNDC") leg.SetFillColor(10) leg.SetLineColor(10) leg.SetShadowColor(0) leg.SetBorderSize(1) from ROOT import TH1F,kWhite legendHistDing = TH1F() legendHistDing.SetFillColor(kWhite) if "default" in selection: leg.AddEntry(legendHistDing,"Baseline signal region","h") elif selection == "lowNLL": leg.AddEntry(legendHistDing,"ttbar like signal region","h") elif selection == "highNLL": leg.AddEntry(legendHistDing,"non-ttbar like signal region","h") elif selection == "lowMll": leg.AddEntry(legendHistDing,"Low mass signal region","h") elif selection == "highMll": leg.AddEntry(legendHistDing,"High mass signal region","h") leg.AddEntry(sfHist,"observed SF ttbar","pe1") leg.AddEntry(ofHist, "prediction from OF ttbar","l") leg.Draw("same") ofHist.Draw("samehist") sfHist.Draw("samepe1") plotPad.RedrawAxis() ratioPad.cd() ratioGraphs = ratios.RatioGraph(sfHist,ofHist, xMin=plot.firstBin, xMax=plot.lastBin,title="#frac{Simul.}{Pred.} ",yMin=0.75,yMax=1.25,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=1000) ratioGraphs.addErrorByHistograms( "rSFOF", histUp, histDown,color= myColors["MyBlue"],fillStyle=3001) ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8) ROOT.gPad.RedrawAxis() plotPad.RedrawAxis() ratioPad.RedrawAxis() hCanvas.Print("fig/rSFOFClosure_%s_%s.pdf"%(selection,runRange.label))