def doPlotRecoMu(quantity, step, **kwargs): if step != "": step = step+"_" genDrh = muonDataset.getDatasetRootHisto(ntupleCacheMuon.histogram("genmuon_"+step+quantity)) recoDrh = muonDataset.getDatasetRootHisto(ntupleCacheMuon.histogram("recomuon_"+step+quantity)) genDrh.setName("Gen") recoDrh.setName("Reco") p = plots.ComparisonPlot(recoDrh, genDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Reco", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Gen", lambda h: doStyle(h, ROOT.kBlue)) args = { "opts2": {"ymin": 0.9, "ymax": 1.1} } args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recogenmuon_"%pc)+step+quantity, xlabel="Reco/gen "+quantity, ratio=True, ratioYlabel="Reco/Gen", addLuminosityText=True, **args)
def doSinglePlot(histograms, myDir, histoName, luminosity): plot = plots.PlotBase(histograms) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) mySplit = histoName.split("/") histoName = mySplit[len(mySplit) - 1] myPlotName = "%s/QCDInv_Purity_%s" % (myDir, histoName) print myPlotName myParams = {} if "EWKGenuineTaus" in histoName: myParams["ylabel"] = "Fake #tau purity" myParams["moveLegend"] = {"dx": -0.05, "dy": -0.46} else: myParams["ylabel"] = "QCD purity" myParams["moveLegend"] = {"dx": -0.05, "dy": 0.0} myParams["xlabel"] = "m_{T}(tau,MET), GeV" myParams["log"] = False #myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["opts"] = {"ymin": 0.0, "ymax": 1.2} #myParams["ratio"] = True #myParams["ratioType"] = "errorScale" #myParams["ratioYlabel"] = "Var./Nom." #myParams["cmsText"] = "CMS" myParams["addLuminosityText"] = True #myParams["createLegend"] = None #myParams["divideByBinWidth"] = True myParams["errorBarsX"] = True plots.drawPlot(plot, myPlotName, **myParams)
def doSinglePlot(histograms, myDir, histoName, luminosity): plot = plots.PlotBase(histograms) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) mySplit = histoName.split("/") histoName = mySplit[len(mySplit)-1] myPlotName = "%s/QCDInv_Purity_%s"%(myDir, histoName) print myPlotName myParams = {} if "EWKGenuineTaus" in histoName: myParams["ylabel"] = "Fake #tau purity" myParams["moveLegend"] = {"dx": -0.05, "dy": -0.46} else: myParams["ylabel"] = "QCD purity" myParams["moveLegend"] = {"dx": -0.05, "dy": 0.0} myParams["xlabel"] = "m_{T}(tau,MET), GeV" myParams["log"] = False #myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["opts"] = {"ymin": 0.0, "ymax":1.2} #myParams["ratio"] = True #myParams["ratioType"] = "errorScale" #myParams["ratioYlabel"] = "Var./Nom." #myParams["cmsText"] = "CMS" myParams["addLuminosityText"] = True #myParams["createLegend"] = None #myParams["divideByBinWidth"] = True myParams["errorBarsX"] = True plots.drawPlot(plot, myPlotName, **myParams)
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") maxBin = h.GetXaxis().GetBinUpEdge(h.GetNbinsX()) if maxBin < myBinning[-1]: print WarningLabel()+"Adjust rebinning last bin from %.0f to %.0f because that is the up edge of last bin in the historam" % (myBinning[-1], maxBin) myBinning[-1] = 500 myArray = array.array("d",myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning)-1,"",myArray) histogramsExtras.makeFlowBinsVisible(h) return h #hbase.SetFillColor(ROOT.kGray) hbase.SetLineColor(ROOT.kGray) hbase.SetFillColor(hbase.GetLineColor()) hinv.SetLineColor(ROOT.kBlue) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events"%(hbase.Integral(), hinv.Integral()) toUnitArea = True if toUnitArea: hbase.Scale(1.0 / hbase.Integral()) hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="F") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST E", legendStyle="l") plot = plots.ComparisonPlot(invHisto, baseHisto) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) if toUnitArea: plot.appendPlotObject(histograms.PlotText(0.5, 0.6, "Normalized to unit area", size=20)) myPlotName = "%s/QCDInv_ClosureTest_%s"%(myDir, histoName) myParams = {} if toUnitArea: myParams["ylabel"] = "A.u. " else: myParams["ylabel"] = "< Events / GeV >" myParams["xlabel"] = "m_{T} (GeV)" myParams["log"] = False myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Anti-isol./Isol." myParams["ratioCreateLegend"] = True myParams["ratioMoveLegend"] = {"dx": -0.05, "dy": -0.4, "dh": -0.1} myParams["cmsTextPosition"] = "right" myParams["addLuminosityText"] = True myParams["divideByBinWidth"] = True plots._legendLabels["BackgroundStatError"] = "Isol. stat. unc." plots.drawPlot(plot, myPlotName, **myParams)
def compare(step): path = "CommonPlots/AtEveryStep/%s/MET_Calo" % step drhNormal = dsetNormal.getDatasetRootHisto(path) drhEmb = dsetEmb.getDatasetRootHisto(path) drhNormal.setName("Normal ttbar") drhEmb.setName("Embedded ttbar") p = plots.ComparisonManyPlot(drhNormal, [drhEmb]) p.histoMgr.normalizeMCToLuminosity(lumi) p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack)) p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Embedded ttbar", lambda h: tauEmbedding.scaleTauBRNormalization(h.getRootHisto())) p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, 1.1, 500, 1.1))) p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, 0.9, 500, 0.9))) global ind ind += 1 bins = range(0, 200, 20) + [200, 250, 300, 500] plots.drawPlot(p, "calometComparison/%02d_calomet_%s"%(ind, step), xlabel="Calo MET (GeV)", ylabel="Events / #DeltaMET / %.0f-%.0f GeV", #rebinToWidthX=20, rebin=bins, divideByBinWidth=True, ratio=True, ratioYlabel="Emb./Norm.", ratioType="errorScale", ratioCreteLegend=True, opts2={"ymin": 0.5, "ymax": 1.5}, addLuminosityText=True, moveLegend={"dx": -0.2})
def doSinglePlot(histograms, myDir, histoName, luminosity, suffix): plot = plots.PlotBase(histograms) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) mySplit = histoName.split("/") histoNameShort = mySplit[len(mySplit) - 1] myPlotName = "%s/signalShapes_%s_%s" % (myDir, suffix, histoNameShort) print myPlotName myParams = {} myParams["ylabel"] = "Events" if histoName.startswith("shape"): myParams["log"] = False else: myParams["log"] = True #myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} #myParams["opts"] = {"ymin": 0.0, "ymax":1.0} #myParams["ratio"] = True #myParams["ratioType"] = "errorScale" #myParams["ratioYlabel"] = "Var./Nom." myParams["cmsText"] = "CMS simulation" myParams["addLuminosityText"] = True myParams["moveLegend"] = {"dx": -0.05, "dy": 0.0} #myParams["createLegend"] = None #myParams["divideByBinWidth"] = True plots.drawPlot(plot, myPlotName, **myParams)
def doPlotRecoMuGenTauEff(quantity, **kwargs): # this has 1/eff normalization, but no jet selection despite its name muonDrh = muonDataset.getDatasetRootHisto("recomuon_afterjet_" + quantity) tauDrh = tauDataset.getDatasetRootHisto("gentau_" + quantity) muonDrh.setName("Muon (reco)") tauDrh.setName("Tau (gen)") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon (reco)", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau (gen)", lambda h: doStyle(h, ROOT.kBlue)) args = {"opts2": {"ymin": 0.9, "ymax": 1.1}} args.update(kwargs) plots.drawPlot(p, "recomuongentau_id_" + quantity, xlabel="Reco/gen " + quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args)
def doPlotMuEff(quantity, **kwargs): genDrh = muonDataset.getDatasetRootHisto("genmuon_" + quantity) idDrh = muonDataset.getDatasetRootHisto( "genmuon_afterjet_" + quantity ) # this has 1/eff normalization, but no jet selection despite its name genDrh.setName("Gen") idDrh.setName("Identified") p = plots.ComparisonPlot(idDrh, genDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Identified", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Gen", lambda h: doStyle(h, ROOT.kBlue)) plots.drawPlot(p, "genmuon_id_" + quantity, xlabel="Gen " + quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="ID'd/Gen", opts2={ "ymin": 0.9, "ymax": 1.1 }, addLuminosityText=True, **kwargs)
def dataMCExample(datasets): # Create data-MC comparison plot, with the default # - legend labels (defined in plots._legendLabels) # - plot styles (defined in plots._plotStyles, and in styles) # - drawing styles ('HIST' for MC, 'EP' for data) # - legend styles ('L' for MC, 'P' for data) plot = plots.DataMCPlot(datasets, #"ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections" "tauPt", # Since the data datasets were removed, we have to set the luminosity by hand normalizeToLumi=20000 ) # Same as below, but more compact plots.drawPlot(plot, "taupt", xlabel="Tau p_{T} (GeV/c)", ylabel="Number of events", rebin=10, stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True, opts={"ymin": 1e-1, "ymaxfactor": 10}, log=True) drawPlot = plots.PlotDrawer(stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True, opts={"ymin": 1e-1, "ymaxfactor": 10}) def createDrawPlot(name, **kwargs): drawPlot( plots.DataMCPlot(datasets, name, normalizeToLumi=20000), name, **kwargs) createDrawPlot("tauEta", xlabel="", ylabel="Number of events", rebin=1, log=False) createDrawPlot("Met", xlabel="E_{T}^{miss} (GeV)", ylabel="Number of events", rebin=1, log=True) createDrawPlot("MetPhi", xlabel="#Phi^{miss} ", ylabel="Number of events", rebin=1, log=False) createDrawPlot("jetPt", xlabel="p_{T}^{jet} (GeV/c)", ylabel="Number of events", rebin=1, log=True) createDrawPlot("jetEta", xlabel="", ylabel="Number of events", rebin=1, log=False) createDrawPlot("jetPhi", xlabel="#Phi^{jet}", ylabel="Number of events", rebin=1, log=False)
def dataMCExample(datasets): # Create data-MC comparison plot, with the default # - legend labels (defined in plots._legendLabels) # - plot styles (defined in plots._plotStyles, and in styles) # - drawing styles ('HIST' for MC, 'EP' for data) # - legend styles ('L' for MC, 'P' for data) plot = plots.DataMCPlot( datasets, #"ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections" "tauPt", # Since the data datasets were removed, we have to set the luminosity by hand normalizeToLumi=20000) # Same as below, but more compact plots.drawPlot(plot, "taupt", xlabel="Tau p_{T} (GeV/c)", ylabel="Number of events", rebin=10, stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True, opts={ "ymin": 1e-1, "ymaxfactor": 10 }, log=True)
def doPlotMuTau(quantity, step, stepTau="", **kwargs): if step != "": step = step + "_" if stepTau != "": stepTau = stepTau + "_" muonDrh = muonDataset.getDatasetRootHisto( ntupleCacheMuon.histogram("genmuon_" + step + quantity)) tauDrh = tauDataset.getDatasetRootHisto( ntupleCacheTau.histogram("gentau_" + stepTau + quantity)) muonDrh.setName("Muon") tauDrh.setName("Tau") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau", lambda h: doStyle(h, ROOT.kBlue)) args = {"opts2": {"ymin": 0.96, "ymax": 1.04}} args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_genmuontau_" % pc) + step + quantity, xlabel="Gen " + quantity, ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args)
def doPlotMuTau(quantity, step, stepTau="", **kwargs): if step != "": step = step+"_" if stepTau != "": stepTau = stepTau+"_" muonDrh = muonDataset.getDatasetRootHisto(ntupleCacheMuon.histogram("genmuon_"+step+quantity)) tauDrh = tauDataset.getDatasetRootHisto(ntupleCacheTau.histogram("gentau_"+stepTau+quantity)) muonDrh.setName("Muon") tauDrh.setName("Tau") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau", lambda h: doStyle(h, ROOT.kBlue)) args = { "opts2": {"ymin": 0.96, "ymax": 1.04} } args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_genmuontau_"%pc)+step+quantity, xlabel="Gen "+quantity, ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args)
def doPlotRecoMu(quantity, step, **kwargs): if step != "": step = step + "_" genDrh = muonDataset.getDatasetRootHisto( ntupleCacheMuon.histogram("genmuon_" + step + quantity)) recoDrh = muonDataset.getDatasetRootHisto( ntupleCacheMuon.histogram("recomuon_" + step + quantity)) genDrh.setName("Gen") recoDrh.setName("Reco") p = plots.ComparisonPlot(recoDrh, genDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Reco", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Gen", lambda h: doStyle(h, ROOT.kBlue)) args = {"opts2": {"ymin": 0.9, "ymax": 1.1}} args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recogenmuon_" % pc) + step + quantity, xlabel="Reco/gen " + quantity, ratio=True, ratioYlabel="Reco/Gen", addLuminosityText=True, **args)
def doPlotsWTauMuRatio(dsetMgr, selectionName, ratios, unweighted, fitFunction): prefix = era + "_" + selectionName + "_fitFunction%d" % fitFunction + unweighted + "_" st = [s.clone() for s in styles.getStyles()] st[0].marker = 33 st[1].marker = 26 st[2].marker = 32 st = [ styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)]) for s in st ] # Do clone to get rid of statistics box p = plots.PlotBase([x[0].Clone() for x in ratios]) p.setEnergy(dsetMgr.getEnergies()) p.histoMgr.setHistoDrawStyleAll("P") p.histoMgr.setHistoLegendStyleAll("P") p.histoMgr.forEachHisto(styles.Generator(st)) for i, x in enumerate(ratios): fitLine = x[1] st[i].apply(fitLine) p.appendPlotObject(fitLine) def customize(plot): xmin = plot.frame.GetXaxis().GetXmin() xmax = plot.frame.GetXaxis().GetXmax() val = 1 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kRed) l.SetLineStyle(2) plot.prependPlotObject(l) val = 1 - 0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) plot.prependPlotObject(l) plot.appendPlotObject( histograms.PlotText(0.18, 0.57, "0.038", size=18, color=ROOT.kBlue)) plots.drawPlot(p, prefix + "WMuFraction", "Muon p_{T} (GeV/c)", ylabel="W#rightarrow#mu fraction", opts={ "ymin": 0.9, "ymax": 1.02 }, moveLegend={ "dh": -0.15, "dx": -0.5 }, customizeBeforeDraw=customize)
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") #myBinning = [0,20,40,60,80,100,120,140,160,200,400] elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") myArray = array.array("d",myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning)-1,"",myArray) h.SetBinContent(1, h.GetBinContent(0)+h.GetBinContent(1)) h.SetBinError(1, math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2)) h.SetBinContent(h.GetNbinsX()+1, h.GetBinContent(h.GetNbinsX()+1)+h.GetBinContent(h.GetNbinsX()+2)) h.SetBinError(h.GetNbinsX()+1, math.sqrt(h.GetBinError(h.GetNbinsX()+1)**2 + h.GetBinError(h.GetNbinsX()+2)**2)) h.SetBinContent(0, 0.0) h.SetBinError(0, 0.0) h.SetBinContent(h.GetNbinsX()+2, 0.0) h.SetBinError(h.GetNbinsX()+2, 0.0) return h hbase.SetLineColor(ROOT.kBlack) hinv.SetLineColor(ROOT.kRed) hinv.SetLineStyle(2) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events"%(hbase.Integral(), hinv.Integral()) hbase.Scale(1.0 / hbase.Integral()) hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="l") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST", legendStyle="l") plot = plots.ComparisonPlot(baseHisto, invHisto) #plot.setLuminosity(luminosity) #plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(2)) myPlotName = "%s/QCDInv_ClosureTest_%s"%(myDir, histoName) myParams = {} #myParams["ylabel"] = "Events/#Deltam_{T}, normalized to 1" myParams["ylabel"] = "#LT Events / bin #GT, normalized to 1" myParams["xlabel"] = "m_{T}(tau,MET), GeV" myParams["log"] = False #myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["opts2"] = {"ymin": 0.3, "ymax":1.7} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Ratio"#"Var./Nom." myParams["cmsText"] = myCMSText #myParams["addLuminosityText"] = False myParams["divideByBinWidth"] = True plots.drawPlot(plot, myPlotName, **myParams)
def massPoint(br, mass, n_hh, n_hw, n_ww): gr_hh = createGraph("HH", br, lambda b: b*b*n_hh) gr_hw = createGraph("HW", br, lambda b: 2*b*(1-b)*n_hw) gr_ww = createGraph("WW", br, lambda b: (1-b)*(1-b)*n_ww) gr_sum = ROOT.TGraph(len(br)) for i in xrange(len(br)): gr_sum.SetPoint(i, br[i], sum([gr_hh.GetY()[i], gr_hw.GetY()[i], gr_ww.GetY()[i]])) gr_sum.SetName("Sum") gr_hh.SetLineColor(3) gr_hh.SetLineStyle(7) gr_hh.SetLineWidth(3) gr_hw.SetLineColor(2) gr_hw.SetLineStyle(2) gr_hw.SetLineWidth(3) gr_ww.SetLineColor(4) gr_ww.SetLineStyle(3) gr_ww.SetLineWidth(3) gr_sum.SetLineColor(6) gr_sum.SetLineStyle(1) gr_sum.SetLineWidth(4) p = plots.PlotBase([ gr_sum, gr_ww, gr_hw, gr_hh, ]) p.histoMgr.setHistoLegendLabelMany({ "Sum": "t#bar{t} (WW + WH^{#pm} + H^{+}H^{-})", "WW": "WW (t#bar{t} #rightarrow W^{+}bW^{-}#bar{b})", "HW": "WH^{#pm} (t#bar{t} #rightarrow W^{+}bH^{-}#bar{b})", "HH": "H^{+}H^{-} (t#bar{t} #rightarrow H^{+}bH^{-}#bar{b})"}) p.appendPlotObject(histograms.PlotText(x1, 0.68, "m_{H^{#pm}} = %d GeV/c^{2}"%mass, size=17)) p.appendPlotObject(histograms.PlotText(x1, 0.64, "#tau_{h}+jets final state", size=17)) opts = {} if mass == 150: opts["ymaxfactor"] = 1.2 elif mass == 160: opts["ymaxfactor"] = 1.4 p.histoMgr.luminosity = 2300 # ugly hack, only for display plots.drawPlot(p, "nevents_ttbar_br_mass%d"%mass, "#it{B}(t#rightarrowH^{+}b)", ylabel="Events", opts=opts, addLuminosityText=True, cmsText="Simulation")
def doPlotMuTau(quantity, **kwargs): muonDrh = muonDataset.getDatasetRootHisto("genmuon_"+quantity) tauDrh = tauDataset.getDatasetRootHisto("gentau_"+quantity) muonDrh.setName("Muon") tauDrh.setName("Tau") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau", lambda h: doStyle(h, ROOT.kBlue)) plots.drawPlot(p, "genmuontau_"+quantity, xlabel="Gen "+quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="Muon/Tau", opts2={"ymin": 0.96, "ymax": 1.04}, addLuminosityText=True, **kwargs)
def doPlotMuEff(quantity, **kwargs): genDrh = muonDataset.getDatasetRootHisto("genmuon_"+quantity) idDrh = muonDataset.getDatasetRootHisto("genmuon_afterjet_"+quantity) # this has 1/eff normalization, but no jet selection despite its name genDrh.setName("Gen") idDrh.setName("Identified") p = plots.ComparisonPlot(idDrh, genDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Identified", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Gen", lambda h: doStyle(h, ROOT.kBlue)) plots.drawPlot(p, "genmuon_id_"+quantity, xlabel="Gen "+quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="ID'd/Gen", opts2={"ymin": 0.9, "ymax": 1.1}, addLuminosityText=True, **kwargs)
def doPlotRecoMu2(quantity, step, **kwargs): if step != "": step = step+"_" drh = muonDataset.getDatasetRootHisto(ntupleCacheMuon.histogram("recomuon_"+step+quantity)) p = plots.PlotBase([drh]) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.setHistoDrawStyleAll("COLZ") args = { "opts": {"ymin": -1, "ymax": 1} } args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recogenmuon_"%pc)+step+quantity, addLuminosityText=True, createLegend=None, backgroundColor=ROOT.kGray, **args)
def doPlotRecoMuGenTau(quantity, step, stepTau="", saveCorrection=False, **kwargs): if step != "": step = step + "_" if stepTau != "": stepTau = stepTau + "_" muonDrh = muonDataset.getDatasetRootHisto( ntupleCacheMuon.histogram("recomuon_" + step + quantity)) tauDrh = tauDataset.getDatasetRootHisto( ntupleCacheTau.histogram("gentau_" + stepTau + quantity)) muonDrh.setName("Muon (reco)") tauDrh.setName("Tau (gen)") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon (reco)", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau (gen)", lambda h: doStyle(h, ROOT.kBlue)) args = {"opts2": {"ymin": 0.9, "ymax": 1.1}} args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recomuongentau_" % pc) + step + stepTau + quantity, xlabel="Reco/gen " + quantity, ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args) if saveCorrection: ratio = p.ratioHistoMgr.getHistos()[0] tf = ROOT.TFile.Open("muonptcorrection.root", "RECREATE") corr = ratio.getRootHisto().Clone("correction_pt") for i in xrange(0, corr.GetNbinsX() + 2): val = corr.GetBinContent(i) if val != 0.0: corr.SetBinContent(i, 1 / val) corr.SetDirectory(tf) tf.Write() tf.Close() print "Saved muon pt correction to muonptcorrection.root"
def createDrawPlot(name, **kwargs): drhs = datasets.getDatasetRootHisto(name) drhs[0].setName("Efficiency") drhs[1].setName("Bit") p = plots.ComparisonPlot(drhs[0], drhs[1]) p.setEnergy(datasets.getEnergy()) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Efficiency", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Bit", lambda h: doStyle(h, ROOT.kBlack)) p.appendPlotObject(histograms.PlotText(0.8, 0.75, effDataset.getName(), size=17)) global plotIndex filename = "%02d_%s" % (plotIndex, name.replace("/", "_")) plotIndex += 1 plots.drawPlot(p, filename, ratio=True, ratioType="errorScale", ratioYlabel="Efficiency/Bit", **kwargs)
def doPlotRecoMu2(quantity, step, **kwargs): if step != "": step = step + "_" drh = muonDataset.getDatasetRootHisto( ntupleCacheMuon.histogram("recomuon_" + step + quantity)) p = plots.PlotBase([drh]) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.setHistoDrawStyleAll("COLZ") args = {"opts": {"ymin": -1, "ymax": 1}} args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recogenmuon_" % pc) + step + quantity, addLuminosityText=True, createLegend=None, backgroundColor=ROOT.kGray, **args)
def compare(step): path = "CommonPlots/AtEveryStep/%s/MET_Calo" % step drhNormal = dsetNormal.getDatasetRootHisto(path) drhEmb = dsetEmb.getDatasetRootHisto(path) drhNormal.setName("Normal ttbar") drhEmb.setName("Embedded ttbar") p = plots.ComparisonManyPlot(drhNormal, [drhEmb]) p.histoMgr.normalizeMCToLuminosity(lumi) p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack)) p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto( "Embedded ttbar", lambda h: tauEmbedding.scaleTauBRNormalization(h.getRootHisto())) p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, 1.1, 500, 1.1))) p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, 0.9, 500, 0.9))) global ind ind += 1 bins = range(0, 200, 20) + [200, 250, 300, 500] plots.drawPlot( p, "calometComparison/%02d_calomet_%s" % (ind, step), xlabel="Calo MET (GeV)", ylabel="Events / #DeltaMET / %.0f-%.0f GeV", #rebinToWidthX=20, rebin=bins, divideByBinWidth=True, ratio=True, ratioYlabel="Emb./Norm.", ratioType="errorScale", ratioCreteLegend=True, opts2={ "ymin": 0.5, "ymax": 1.5 }, addLuminosityText=True, moveLegend={"dx": -0.2})
def doPlotRecoMuGenTauEff(quantity, **kwargs): # this has 1/eff normalization, but no jet selection despite its name muonDrh = muonDataset.getDatasetRootHisto("recomuon_afterjet_"+quantity) tauDrh = tauDataset.getDatasetRootHisto("gentau_"+quantity) muonDrh.setName("Muon (reco)") tauDrh.setName("Tau (gen)") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon (reco)", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau (gen)", lambda h: doStyle(h, ROOT.kBlue)) args = { "opts2": {"ymin": 0.9, "ymax": 1.1} } args.update(kwargs) plots.drawPlot(p, "recomuongentau_id_"+quantity, xlabel="Reco/gen "+quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args)
def doPlotRecoMuGenTau(quantity, step, stepTau="", saveCorrection=False, **kwargs): if step != "": step = step+"_" if stepTau != "": stepTau = stepTau+"_" muonDrh = muonDataset.getDatasetRootHisto(ntupleCacheMuon.histogram("recomuon_"+step+quantity)) tauDrh = tauDataset.getDatasetRootHisto(ntupleCacheTau.histogram("gentau_"+stepTau+quantity)) muonDrh.setName("Muon (reco)") tauDrh.setName("Tau (gen)") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon (reco)", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau (gen)", lambda h: doStyle(h, ROOT.kBlue)) args = { "opts2": {"ymin": 0.9, "ymax": 1.1} } args.update(kwargs) global pc pc += 1 plots.drawPlot(p, ("%02d_recomuongentau_"%pc)+step+stepTau+quantity, xlabel="Reco/gen "+quantity, ratio=True, ratioYlabel="Muon/Tau", addLuminosityText=True, **args) if saveCorrection: ratio = p.ratioHistoMgr.getHistos()[0] tf = ROOT.TFile.Open("muonptcorrection.root", "RECREATE") corr = ratio.getRootHisto().Clone("correction_pt") for i in xrange(0, corr.GetNbinsX()+2): val = corr.GetBinContent(i) if val != 0.0: corr.SetBinContent(i, 1/val) corr.SetDirectory(tf) tf.Write() tf.Close() print "Saved muon pt correction to muonptcorrection.root"
def plotEfficiency(datasets, datasetNames, allPath, passedPath, name, xlabel, rebinBins=None, **kwargs): if mcOnly: return def rebin(h): return h.Rebin( len(rebinBins) - 1, h.GetName(), array.array("d", rebinBins)) for dname in datasetNames: dset = datasets.getDataset(dname) allHisto = dset.getDatasetRootHisto(allPath).getHistogram() passedHisto = dset.getDatasetRootHisto(passedPath).getHistogram() if allHisto.Integral() < 1: continue if rebinBins != None: allHisto = rebin(allHisto) passedHisto = rebin(passedHisto) eff = ROOT.TGraphAsymmErrors(passedHisto, allHisto, "cp") # 0.683 cl is default p = plots.PlotBase([histograms.HistoGraph(eff, dname, "p", "P")]) if dset.isData(): p.setLuminosity(dset.getLuminosity()) opts = {"ymin": 0.0, "ymax": 1.1} plots.drawPlot(p, name + "_" + dname, xlabel, addLuminosityText=dset.isData(), opts=opts, **kwargs)
def MetComparison(datasets): mt = plots.PlotBase(getHistos(datasets,"MetNoJetInHole", "MetJetInHole")) # mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity()) mt._setLegendStyles() st1 = styles.StyleCompound([styles.styles[2]]) st2 = styles.StyleCompound([styles.styles[1]]) st1.append(styles.StyleLine(lineWidth=3)) st2.append(styles.StyleLine(lineStyle=2, lineWidth=3)) mt.histoMgr.forHisto("MetNoJetInHole", st1) mt.histoMgr.forHisto("MetJetInHole", st2) mt.histoMgr.setHistoLegendLabelMany({ "MetNoJetInHole": "Jets outside dead cells", "MetJetInHole": "Jets within dead cells" }) # mt.histoMgr.setHistoDrawStyleAll("P") mt.appendPlotObject(histograms.PlotText(300, 300, "p_{T}^{jet} > 50 GeV/c", size=20)) xlabel = "PF E_{T}^{miss} (GeV)" ylabel = "Events / %.2f" plots.drawPlot(mt, "MetComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True, createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9}, ratio=False, opts2={"ymin": 0.5, "ymax": 1.5})
def createDrawPlot(name, **kwargs): drhs = datasets.getDatasetRootHisto(name) drhs[0].setName("Efficiency") drhs[1].setName("Bit") p = plots.ComparisonPlot(drhs[0], drhs[1]) p.setEnergy(datasets.getEnergy()) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Efficiency", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Bit", lambda h: doStyle(h, ROOT.kBlack)) p.appendPlotObject( histograms.PlotText(0.8, 0.75, effDataset.getName(), size=17)) global plotIndex filename = "%02d_%s" % (plotIndex, name.replace("/", "_")) plotIndex += 1 plots.drawPlot(p, filename, ratio=True, ratioType="errorScale", ratioYlabel="Efficiency/Bit", **kwargs)
def doPlotMuTau(quantity, **kwargs): muonDrh = muonDataset.getDatasetRootHisto("genmuon_" + quantity) tauDrh = tauDataset.getDatasetRootHisto("gentau_" + quantity) muonDrh.setName("Muon") tauDrh.setName("Tau") p = plots.ComparisonPlot(muonDrh, tauDrh) p.histoMgr.normalizeMCToLuminosity(mcLumi) p.histoMgr.forHisto("Muon", lambda h: doStyle(h, ROOT.kRed)) p.histoMgr.forHisto("Tau", lambda h: doStyle(h, ROOT.kBlue)) plots.drawPlot(p, "genmuontau_" + quantity, xlabel="Gen " + quantity, ylabel="Events / %.2f", ratio=True, ratioYlabel="Muon/Tau", opts2={ "ymin": 0.96, "ymax": 1.04 }, addLuminosityText=True, **kwargs)
def doPlot(datasetsEmb, analyses, path, name, text): histos = [] legends = {"Plus": taujetH+" energy scale varied by +3 %", "Minus": taujetH+" energy scale varied by -3 %"} for aname, analysis in analyses: (rootHisto, tmp) = datasetsEmb.getHistogram("Data", analysis+"/"+path) h = histograms.Histo(rootHisto, aname) h.setLegendLabel(legends.get(aname, aname)) h.setDrawStyle("EP") h.setLegendStyle("p") histos.append(h) p = plots.ComparisonManyPlot(histos[0], histos[1:]) styles.dataStyle(p.histoMgr.getHisto("Nominal")) styles.mcStyle(p.histoMgr.getHisto("Plus")) styles.mcStyle2(p.histoMgr.getHisto("Minus")) p.histoMgr.getHisto("Minus").getRootHisto().SetMarkerSize(2) p.setLuminosity(datasetsEmb.getLuminosity()) p.appendPlotObject(histograms.PlotText(0.45, 0.55, text, size=20)) plots.drawPlot(p, name, "m_{T}(^{}%s, ^{}E_{T}^{miss}) (GeV/^{}c^{2})"%taujet, ylabel="Events / %d GeV/^{}c^{2}", rebin=20, ratio=True, opts={"ymax": 35, "xmax": 300}, opts2={"ymax": 2}, addLuminosityText=True)
def massPoint(br, mass, n_hh, n_hw, n_ww): gr_hh = createGraph("HH", br, lambda b: b * b * n_hh) gr_hw = createGraph("HW", br, lambda b: 2 * b * (1 - b) * n_hw) gr_ww = createGraph("WW", br, lambda b: (1 - b) * (1 - b) * n_ww) gr_sum = ROOT.TGraph(len(br)) for i in xrange(len(br)): gr_sum.SetPoint( i, br[i], sum([gr_hh.GetY()[i], gr_hw.GetY()[i], gr_ww.GetY()[i]])) gr_sum.SetName("Sum") gr_hh.SetLineColor(3) gr_hh.SetLineStyle(7) gr_hh.SetLineWidth(3) gr_hw.SetLineColor(2) gr_hw.SetLineStyle(2) gr_hw.SetLineWidth(3) gr_ww.SetLineColor(4) gr_ww.SetLineStyle(3) gr_ww.SetLineWidth(3) gr_sum.SetLineColor(6) gr_sum.SetLineStyle(1) gr_sum.SetLineWidth(4) p = plots.PlotBase([ gr_sum, gr_ww, gr_hw, gr_hh, ]) p.histoMgr.setHistoLegendLabelMany({ "Sum": "t#bar{t} (WW + WH^{#pm} + H^{+}H^{-})", "WW": "WW (t#bar{t} #rightarrow W^{+}bW^{-}#bar{b})", "HW": "WH^{#pm} (t#bar{t} #rightarrow W^{+}bH^{-}#bar{b})", "HH": "H^{+}H^{-} (t#bar{t} #rightarrow H^{+}bH^{-}#bar{b})" }) p.appendPlotObject( histograms.PlotText(x1, 0.68, "m_{H^{#pm}} = %d GeV/c^{2}" % mass, size=17)) p.appendPlotObject( histograms.PlotText(x1, 0.64, "#tau_{h}+jets final state", size=17)) opts = {} if mass == 150: opts["ymaxfactor"] = 1.2 elif mass == 160: opts["ymaxfactor"] = 1.4 p.histoMgr.luminosity = 2300 # ugly hack, only for display plots.drawPlot(p, "nevents_ttbar_br_mass%d" % mass, "#it{B}(t#rightarrowH^{+}b)", ylabel="Events", opts=opts, addLuminosityText=True, cmsText="Simulation")
def compare(step): if step is None: path = "shapeTransverseMass" else: path = "CommonPlots/AtEveryStep/%s/MET_MET" % step #bins = range(0, 200, 20) + [200, 250, 300, 500] bins = systematics.getBinningForPlot("shapeTransverseMass") def getTH1(ds): drh = ds.getDatasetRootHisto(path) drh.normalizeToLuminosity(lumi) th1 = drh.getHistogram() #th1.Rebin(2) #return th1 return th1.Rebin( len(bins) - 1, th1.GetName(), array.array("d", bins)) th1NormalNum = getTH1(dsetNormalNum) th1NormalDenom = getTH1(dsetNormalDenom) #print th1NormalNum.Integral(0, th1NormalNum.GetNbinsX()+1), th1NormalDenom.Integral(0, th1NormalDenom.GetNbinsX()+1) th1EmbNum = getTH1(dsetEmbNum) th1EmbDenom = getTH1(dsetEmbDenom) #print th1EmbNum.Integral(0, th1EmbNum.GetNbinsX()+1), th1EmbDenom.Integral(0, th1EmbDenom.GetNbinsX()+1) effNormal = ROOT.TGraphAsymmErrors(th1NormalNum, th1NormalDenom, "n") effEmb = ROOT.TGraphAsymmErrors(th1EmbNum, th1EmbDenom, "n") effNormal.SetName("Normal ttbar") effEmb.SetName("Embedded ttbar") p = plots.ComparisonManyPlot(effNormal, [effEmb]) p.setLuminosity(lumi) p.histoMgr.forEachHisto(styles.generator()) #p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack, ROOT.kFullCircle)) #p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed, ROOT.kFullSquare)) p.histoMgr.setHistoDrawStyleAll("EP") p.histoMgr.setHistoLegendStyleAll("EPL") unc1 = 1.12 unc2 = 0.88 p.prependPlotObjectToRatio( doLineStyle(ROOT.TLine(0, unc1, bins[-1], unc1))) p.prependPlotObjectToRatio( doLineStyle(ROOT.TLine(0, unc2, bins[-1], unc2))) p.appendPlotObject( histograms.PlotText(x=0.6, y=0.6, text="CaloMET > 70 GeV", size=20)) global ind ind += 1 # plots.drawPlot(p, "calometComparison/eff_%02d_calomet_%s"%(ind, step), xlabel="Type I PF MET (GeV)", ylabel="CaloMET cut efficiency", # ratio=True, ratioYlabel="Norm./emb.", ratioType="errorScale", # opts={"xmin": 0, "xmax": 500}, # opts2={"ymin": 0.8, "ymax": 1.2}, # addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5}) plots.drawPlot(p, "calometComparison/eff_%d_calomet_shapeTransverseMass" % ind, xlabel="Transverse mass (GeV)", ylabel="CaloMET cut efficiency", ratio=True, ratioYlabel="Emb./Norm.", ratioCreateLegend=True, ratioType="errorScale", opts={"ymax": 1.2}, opts2={ "ymin": 0.8, "ymax": 1.2 }, addLuminosityText=True, moveLegend={ "dx": -0.2, "dy": -0.5 })
def doPlotsWTauMuRatioUncertaintyEstimate(dsetMgr, ratios, analysisName): prefix = era + "_" st = [s.clone() for s in styles.getStyles()] st[0].marker = 33 st = [ styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)]) for s in st ] # Nominal p = plots.PlotBase([ratios[analysisName][0].Clone()]) p.setEnergy(dsetMgr.getEnergies()) p.histoMgr.setHistoDrawStyleAll("P") p.histoMgr.setHistoLegendStyleAll("P") p.histoMgr.forEachHisto(styles.Generator(st)) fitLine = ratios[analysisName][1] st[0].apply(fitLine) p.appendPlotObject(fitLine) # Stat. unc. from parameters pars = [fitLine.GetParameter(i) for i in xrange(0, fitLine.GetNpar())] parErrors = [fitLine.GetParError(i) for i in xrange(0, fitLine.GetNpar())] def evalPar(x, i, shift): pars_ = pars[:] pars_[i] += shift return fitLine.EvalPar(x, array.array("d", pars_)) # Fit function fits = [ ratios[analysisName + "SystFunc0"][1], ratios[analysisName + "SystFunc1"][1] ] def maxDiff(x, tf1s, nominal): return max([abs(tf1.Eval(x[0]) - nominal) for tf1 in tf1s]) # Sample samples = [ ratios[analysisName + "SystWJets"][1], ratios[analysisName + "SystSingleTop"][1] ] # Weight systematic variations keys = filter(lambda n: "SystVar" in n, ratios.keys()) weightSources = {} for key in keys: src = key[key.find("SystVar") + 7:].replace("Plus", "").replace("Minus", "") # if src != "TopPtWeight": # continue # if src != "PUWeight": # continue # print src if not src in weightSources: weightSources[src] = [ratios[key][1]] else: weightSources[src].append(ratios[key][1]) def comb(plus, x, p): nominal = fitLine.Eval(x[0]) diff = 0 # stat unc uncStat = 0.0 for i, parErr in enumerate(parErrors): diffI = max(abs(evalPar(x, i, parErr) - nominal), abs(evalPar(x, i, -parErr)) - nominal) uncStat += diffI**2 diff += uncStat # Fit function diffFit = maxDiff(x, fits, nominal) diff += diffFit**2 # Sample diffSample = maxDiff(x, samples, nominal) diff += diffSample**2 # Weights for src, tf1s in weightSources.iteritems(): diffWeight = maxDiff(x, tf1s, nominal) diff += diffWeight**2 diff = math.sqrt(diff) if plus: ret = nominal + diff else: ret = nominal - diff if ret > 1: ret = 1.0 if ret < 0: ret = 0.0 # if ret > 0: # print x[0], (ret-nominal)/ret return ret p.appendPlotObject( ROOT.TF1("combPlus", lambda x, p: comb(True, x, p), fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar())) p.appendPlotObject( ROOT.TF1("combMinus", lambda x, p: comb(False, x, p), fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar())) # Simple relative uncertainty def rel(x): return 0.012 def relUnc(plus, x, p): nominal = fitLine.Eval(x[0]) if plus: f = 1 + rel(x[0]) else: f = 1 - rel(x[0]) return nominal * f relPlus = ROOT.TF1("relPlus", lambda x, p: relUnc(True, x, p), fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar()) relMinus = ROOT.TF1("relMinus", lambda x, p: relUnc(False, x, p), fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar()) relPlus.SetLineColor(ROOT.kGreen) relMinus.SetLineColor(ROOT.kGreen) p.appendPlotObject(relPlus) p.appendPlotObject(relMinus) def customize(plot): xmin = plot.frame.GetXaxis().GetXmin() xmax = plot.frame.GetXaxis().GetXmax() ymin = plot.frame.GetYaxis().GetXmin() ymax = plot.frame.GetYaxis().GetXmax() val = 1 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kRed) l.SetLineStyle(2) plot.prependPlotObject(l) l = ROOT.TLine(41, ymin, 41, ymax) l.SetLineWidth(2) l.SetLineColor(ROOT.kRed) l.SetLineStyle(2) plot.prependPlotObject(l) plots.drawPlot( p, prefix + "WMuFractionUncertainty", "Muon p_{T} (GeV/c)", ylabel="W#rightarrow#mu fraction", opts={ "ymin": 0.9, "ymax": 1.02 }, createLegend=None, #moveLegend={"dh": -0.15, "dx": -0.5}, customizeBeforeDraw=customize)
def doPlots(datasetsAve, datasetsSeeds, datasetName, plotter): dsetAve = datasetsAve.getDataset(datasetName) dsetSeeds = [d.getDataset(datasetName) for d in datasetsSeeds] lumi = datasetsAve.getDataset("Data").getLuminosity() addEventCounts = False compatTests = [] compatTestsAve = [] def createPlot(name): drhAve = dsetAve.getDatasetRootHisto(name) drhAve.setName("Average") if drhAve.isMC(): drhAve.normalizeToLuminosity(lumi) drhSeeds = [] for i, d in enumerate(dsetSeeds): drh = d.getDatasetRootHisto(name) drh.setName("Seed %d" % i) if drh.isMC(): drh.normalizeToLuminosity(lumi) drhSeeds.append(drh) if name == "shapeTransverseMass": tha = drhAve.getHistogram() for i, di in enumerate(drhSeeds): thi = di.getHistogram() chi2 = tha.Chi2Test(thi, "WW") kolmo = tha.KolmogorovTest(thi) compatTestsAve.append(("a+%d" % i, chi2, kolmo)) for j in xrange(i + 1, len(drhSeeds)): thj = drhSeeds[j].getHistogram() chi2 = thi.Chi2Test(thj, "WW") kolmo = thi.KolmogorovTest(thj) compatTests.append(("%d+%d" % (i, j), chi2, kolmo)) p = plots.ComparisonManyPlot(drhAve, drhSeeds) p.setLuminosity(lumi) legLabel = plots._legendLabels.get(datasetName, datasetName) leg = "Average " + legLabel if addEventCounts: leg += " (" + tauEmbedding.strIntegral(drhAve.getHistogram()) + ")" p.histoMgr.setHistoLegendLabelMany({"Average": leg}) for i, drh in enumerate(drhSeeds): leg = ("Seed %d " % i) + legLabel if addEventCounts: leg += " (" + tauEmbedding.strIntegral( drh.getHistogram()) + ")" p.histoMgr.setHistoLegendLabelMany({"Seed %d" % i: leg}) p.histoMgr.forEachHisto(styles.Generator(styles=myStyles)) p.setDrawOptions(ratioYlabel="Seed/Average") return p plotter.plot(datasetName, createPlot) print "Chi2-probability and Kolmogorov-probability of all pair-wise comparisons" hchi2 = ROOT.TH1F("chi2", "chi2;#chi^{2} probability;Entries", 100, 0, 1) hchi2a = ROOT.TH1F("chi2_ave", "chi2;#chi^{2} probability;Entries", 100, 0, 1) hkolmo = ROOT.TH1F("kolmogorov", "kolmo;Kolmogorov probability;Entries", 100, 0, 1) hkolmoa = ROOT.TH1F("kolmogorov_ave", "kolmo;Kolmogorov probability;Entries", 100, 0, 1) for pair, chi2, kolmo in compatTests: print "%s: %f %f" % (pair, chi2, kolmo) hchi2.Fill(chi2) hkolmo.Fill(kolmo) for pair, chi2, kolmo in compatTestsAve: print "%s: %f %f" % (pair, chi2, kolmo) hchi2a.Fill(chi2) hkolmoa.Fill(kolmo) for th1 in [hchi2, hchi2a, hkolmo, hkolmoa]: p = plots.PlotBase([th1]) p.setLuminosity(lumi) plots.drawPlot(p, os.path.join(plotter.getOutputDirectory(), datasetName + "_" + th1.GetName()), ylabel="Entries", createLegend=None)
def doPlots(datasetsAve, datasetsSeeds, datasetName, plotter): dsetAve = datasetsAve.getDataset(datasetName) dsetSeeds = [d.getDataset(datasetName) for d in datasetsSeeds] lumi = datasetsAve.getDataset("Data").getLuminosity() addEventCounts = False compatTests = [] compatTestsAve = [] def createPlot(name): drhAve = dsetAve.getDatasetRootHisto(name) drhAve.setName("Average") if drhAve.isMC(): drhAve.normalizeToLuminosity(lumi) drhSeeds = [] for i, d in enumerate(dsetSeeds): drh = d.getDatasetRootHisto(name) drh.setName("Seed %d" % i) if drh.isMC(): drh.normalizeToLuminosity(lumi) drhSeeds.append(drh) if name == "shapeTransverseMass": tha = drhAve.getHistogram() for i, di in enumerate(drhSeeds): thi = di.getHistogram() chi2 = tha.Chi2Test(thi, "WW") kolmo = tha.KolmogorovTest(thi) compatTestsAve.append( ("a+%d" % i, chi2, kolmo) ) for j in xrange(i+1, len(drhSeeds)): thj = drhSeeds[j].getHistogram() chi2 = thi.Chi2Test(thj, "WW") kolmo = thi.KolmogorovTest(thj) compatTests.append( ("%d+%d" % (i, j), chi2, kolmo) ) p = plots.ComparisonManyPlot(drhAve, drhSeeds) p.setLuminosity(lumi) legLabel = plots._legendLabels.get(datasetName, datasetName) leg = "Average "+legLabel if addEventCounts: leg += " ("+tauEmbedding.strIntegral(drhAve.getHistogram())+")" p.histoMgr.setHistoLegendLabelMany({"Average": leg}) for i, drh in enumerate(drhSeeds): leg = ("Seed %d "%i)+legLabel if addEventCounts: leg += " ("+tauEmbedding.strIntegral(drh.getHistogram())+")" p.histoMgr.setHistoLegendLabelMany({"Seed %d"%i: leg}) p.histoMgr.forEachHisto(styles.Generator(styles=myStyles)) p.setDrawOptions(ratioYlabel="Seed/Average") return p plotter.plot(datasetName, createPlot) print "Chi2-probability and Kolmogorov-probability of all pair-wise comparisons" hchi2 = ROOT.TH1F("chi2", "chi2;#chi^{2} probability;Entries", 100, 0, 1) hchi2a = ROOT.TH1F("chi2_ave", "chi2;#chi^{2} probability;Entries", 100, 0, 1) hkolmo = ROOT.TH1F("kolmogorov", "kolmo;Kolmogorov probability;Entries", 100, 0, 1) hkolmoa = ROOT.TH1F("kolmogorov_ave", "kolmo;Kolmogorov probability;Entries", 100, 0, 1) for pair, chi2, kolmo in compatTests: print "%s: %f %f" % (pair, chi2, kolmo) hchi2.Fill(chi2) hkolmo.Fill(kolmo) for pair, chi2, kolmo in compatTestsAve: print "%s: %f %f" % (pair, chi2, kolmo) hchi2a.Fill(chi2) hkolmoa.Fill(kolmo) for th1 in [hchi2, hchi2a, hkolmo, hkolmoa]: p = plots.PlotBase([th1]) p.setLuminosity(lumi) plots.drawPlot(p, os.path.join(plotter.getOutputDirectory(), datasetName+"_"+th1.GetName()), ylabel="Entries", createLegend=None)
def compare(step): if step is None: path = "shapeTransverseMass" else: path = "CommonPlots/AtEveryStep/%s/MET_MET" % step #bins = range(0, 200, 20) + [200, 250, 300, 500] bins = systematics.getBinningForPlot("shapeTransverseMass") def getTH1(ds): drh = ds.getDatasetRootHisto(path) drh.normalizeToLuminosity(lumi) th1 = drh.getHistogram() #th1.Rebin(2) #return th1 return th1.Rebin(len(bins)-1, th1.GetName(), array.array("d", bins)) th1NormalNum = getTH1(dsetNormalNum) th1NormalDenom = getTH1(dsetNormalDenom) #print th1NormalNum.Integral(0, th1NormalNum.GetNbinsX()+1), th1NormalDenom.Integral(0, th1NormalDenom.GetNbinsX()+1) th1EmbNum = getTH1(dsetEmbNum) th1EmbDenom = getTH1(dsetEmbDenom) #print th1EmbNum.Integral(0, th1EmbNum.GetNbinsX()+1), th1EmbDenom.Integral(0, th1EmbDenom.GetNbinsX()+1) effNormal = ROOT.TGraphAsymmErrors(th1NormalNum, th1NormalDenom, "n") effEmb = ROOT.TGraphAsymmErrors(th1EmbNum, th1EmbDenom, "n") effNormal.SetName("Normal ttbar") effEmb.SetName("Embedded ttbar") p = plots.ComparisonManyPlot(effNormal, [effEmb]) p.setLuminosity(lumi) p.histoMgr.forEachHisto(styles.generator()) #p.histoMgr.forHisto("Normal ttbar", lambda h: doStyle(h, ROOT.kBlack, ROOT.kFullCircle)) #p.histoMgr.forHisto("Embedded ttbar", lambda h: doStyle(h, ROOT.kRed, ROOT.kFullSquare)) p.histoMgr.setHistoDrawStyleAll("EP") p.histoMgr.setHistoLegendStyleAll("EPL") unc1 = 1.12 unc2 = 0.88 p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, unc1, bins[-1], unc1))) p.prependPlotObjectToRatio(doLineStyle(ROOT.TLine(0, unc2, bins[-1], unc2))) p.appendPlotObject(histograms.PlotText(x=0.6, y=0.6, text="CaloMET > 70 GeV", size=20)) global ind ind += 1 # plots.drawPlot(p, "calometComparison/eff_%02d_calomet_%s"%(ind, step), xlabel="Type I PF MET (GeV)", ylabel="CaloMET cut efficiency", # ratio=True, ratioYlabel="Norm./emb.", ratioType="errorScale", # opts={"xmin": 0, "xmax": 500}, # opts2={"ymin": 0.8, "ymax": 1.2}, # addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5}) plots.drawPlot(p, "calometComparison/eff_%d_calomet_shapeTransverseMass"%ind, xlabel="Transverse mass (GeV)", ylabel="CaloMET cut efficiency", ratio=True, ratioYlabel="Emb./Norm.", ratioCreateLegend=True, ratioType="errorScale", opts={"ymax": 1.2}, opts2={"ymin": 0.8, "ymax": 1.2}, addLuminosityText=True, moveLegend={"dx": -0.2, "dy": -0.5})
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") #myBinning = [0,20,40,60,80,100,120,140,160,200,400] elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") myArray = array.array("d", myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning) - 1, "", myArray) h.SetBinContent(1, h.GetBinContent(0) + h.GetBinContent(1)) h.SetBinError(1, math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2)) h.SetBinContent( h.GetNbinsX() + 1, h.GetBinContent(h.GetNbinsX() + 1) + h.GetBinContent(h.GetNbinsX() + 2)) h.SetBinError( h.GetNbinsX() + 1, math.sqrt( h.GetBinError(h.GetNbinsX() + 1)**2 + h.GetBinError(h.GetNbinsX() + 2)**2)) h.SetBinContent(0, 0.0) h.SetBinError(0, 0.0) h.SetBinContent(h.GetNbinsX() + 2, 0.0) h.SetBinError(h.GetNbinsX() + 2, 0.0) return h hbase.SetLineColor(ROOT.kBlack) hinv.SetLineColor(ROOT.kRed) hinv.SetLineStyle(2) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events" % (hbase.Integral(), hinv.Integral()) hbase.Scale(1.0 / hbase.Integral()) hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="l") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST", legendStyle="l") plot = plots.ComparisonPlot(baseHisto, invHisto) #plot.setLuminosity(luminosity) #plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(2)) myPlotName = "%s/QCDInv_ClosureTest_%s" % (myDir, histoName) myParams = {} #myParams["ylabel"] = "Events/#Deltam_{T}, normalized to 1" myParams["ylabel"] = "#LT Events / bin #GT, normalized to 1" myParams["xlabel"] = "m_{T}(tau,MET), GeV" myParams["log"] = False #myParams["opts2"] = {"ymin": 0.0, "ymax":2.0} myParams["opts2"] = {"ymin": 0.3, "ymax": 1.7} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Ratio" #"Var./Nom." myParams["cmsText"] = myCMSText #myParams["addLuminosityText"] = False myParams["divideByBinWidth"] = True plots.drawPlot(plot, myPlotName, **myParams)
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity): def rebin(h, name): myBinning = [] if name.startswith("MT"): myBinning = systematics.getBinningForPlot("shapeTransverseMass") elif name.startswith("INVMASS"): myBinning = systematics.getBinningForPlot("shapeInvariantMass") else: raise Exception("Unknown binning information") maxBin = h.GetXaxis().GetBinUpEdge(h.GetNbinsX()) if maxBin < myBinning[-1]: print WarningLabel( ) + "Adjust rebinning last bin from %.0f to %.0f because that is the up edge of last bin in the historam" % ( myBinning[-1], maxBin) myBinning[-1] = 500 myArray = array.array("d", myBinning) # Rebin and move under/overflow bins to visible bins h = h.Rebin(len(myBinning) - 1, "", myArray) histogramsExtras.makeFlowBinsVisible(h) return h #hbase.SetFillColor(ROOT.kGray) hbase.SetLineColor(ROOT.kGray) hbase.SetFillColor(hbase.GetLineColor()) hinv.SetLineColor(ROOT.kBlue) # Rebin hbase = rebin(hbase, histoName) hinv = rebin(hinv, histoName) # Normalize print "baseline: %.1f events, inverted %.1f events" % (hbase.Integral(), hinv.Integral()) toUnitArea = True if toUnitArea: hbase.Scale(1.0 / hbase.Integral()) hinv.Scale(1.0 / hinv.Integral()) # Plot baseHisto = histograms.Histo(hbase, "Isolated", drawStyle="HIST", legendStyle="F") invHisto = histograms.Histo(hinv, "Anti-isolated", drawStyle="HIST E", legendStyle="l") plot = plots.ComparisonPlot(invHisto, baseHisto) plot.setLuminosity(luminosity) plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) if toUnitArea: plot.appendPlotObject( histograms.PlotText(0.5, 0.6, "Normalized to unit area", size=20)) myPlotName = "%s/QCDInv_ClosureTest_%s" % (myDir, histoName) myParams = {} if toUnitArea: myParams["ylabel"] = "A.u. " else: myParams["ylabel"] = "< Events / GeV >" myParams["xlabel"] = "m_{T} (GeV)" myParams["log"] = False myParams["opts2"] = {"ymin": 0.0, "ymax": 2.0} myParams["opts"] = {"ymin": 0.0} myParams["ratio"] = True myParams["ratioType"] = "errorScale" myParams["ratioYlabel"] = "Anti-isol./Isol." myParams["ratioCreateLegend"] = True myParams["ratioMoveLegend"] = {"dx": -0.05, "dy": -0.4, "dh": -0.1} myParams["cmsTextPosition"] = "right" myParams["addLuminosityText"] = True myParams["divideByBinWidth"] = True plots._legendLabels["BackgroundStatError"] = "Isol. stat. unc." plots.drawPlot(plot, myPlotName, **myParams)