def createMuon2Plot(dset, name, postfix): datasetName = dset.getName() treeDraw = dataset.TreeDraw("tree", selection="Obj2Type == 3 && LeptonVetoStatus == 0 && (TauIDStatus == 1 || TauIDStatus == 2 || TauIDStatus == 3)") # nothing passes lepton veto tdFullIsolation = treeDraw.clone(varexp="(muon2_f_chargedHadronIso + max(muon2_f_photonIso+muon2_f_neutralHadronIso-0.5*muon2_f_puChargedHadronIso, 0))/muon2_p4.Pt() >>tmp(50, 0, 0.5)") tdChargedIsolation = treeDraw.clone(varexp="(muon2_f_chargedHadronIso)/muon2_p4.Pt() >>tmp(50, 0, 0.5)") tdNeutralIsolation = treeDraw.clone(varexp="(max(muon2_f_photonIso+muon2_f_neutralHadronIso-0.5*muon2_f_puChargedHadronIso, 0))/muon2_p4.Pt() >>tmp(50, 0, 0.5)") h = dset.getDatasetRootHisto(tdFullIsolation).getHistogram() p = plots.PlotBase([histograms.Histo(h, "histo")]) p.createFrame("muon2fullIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save() h = dset.getDatasetRootHisto(tdChargedIsolation).getHistogram() integralAll = h.Integral(0, h.GetNbinsX()+1) integral = h.Integral(0, h.FindBin(0.1)+1) p = plots.PlotBase([histograms.Histo(h, "histo")]) p.appendPlotObject(histograms.PlotText(0.5, 0.55, "%d events in total" % int(integralAll))) p.appendPlotObject(histograms.PlotText(0.5, 0.5, "%d events in <= 0.1" % int(integral))) p.createFrame("muon2chargedIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save() h = dset.getDatasetRootHisto(tdNeutralIsolation).getHistogram() p = plots.PlotBase([histograms.Histo(h, "histo")]) p.createFrame("muon2neutralIsolation_"+datasetName+"_"+name+"_"+postfix) p.draw() p.save()
def createPlot(name, massbr_x=0.42, massbr_y=0.87, normone_x=0.25, normone_y=0.5, **kwargs): args = {} args.update(kwargs) if mcOnly: args["normalizeToLumi"] = mcOnlyLumi p = plots.DataMCPlot(datasets, name, **args) addMassBRText(p, massbr_x, massbr_y) if kwargs.get("normalizeToOne", False): p.appendPlotObject( histograms.PlotText(2 * normone_x, normone_y + 0.03, "Normalized to unit area", size=17)) if removeQCD: p.appendPlotObject( histograms.PlotText(2 * normone_x, normone_y, "QCD background not shown", size=17, color=2)) return p
def addMassBRText(plot, x, y): mass = "m_{H^{+}} = 120 GeV/c^{2}" br = "#it{B}(t #rightarrow H^{+}b)=0.05" size = 20 separation= 0.04 plot.appendPlotObject(histograms.PlotText(x, y, mass, size=size)) plot.appendPlotObject(histograms.PlotText(x, y-separation, br, size=size))
def createPlot(name, massbr_x=0.67, massbr_y=0.58, normone_x=0.67, normone_y=0.58, **kwargs): args = {} args.update(kwargs) if mcOnly: args["normalizeToLumi"] = mcOnlyLumi p = plots.DataMCPlot(datasets, name, **args) addMassBRText(p, massbr_x, massbr_y, lightHplusMassPoint) #p.addCutBoxAndLine(cutValue=0) if kwargs.get("normalizeToOne", False): p.appendPlotObject( histograms.PlotText(normone_x, normone_y + 0.03, "Normalized to unit area", size=17)) if removeQCD and not plotSignalOnly: #p.appendPlotObject(histograms.PlotText(2.7*normone_x, normone_y, "#splitline{QCD background}{not shown}", p.appendPlotObject( histograms.PlotText(normone_x, normone_y - 0.10, "#splitline{QCD background}{not shown}", size=17, color=2)) return p
def addMassBRText(plot, x, y): size = 20 separation = 0.04 massText = "m_{H^{+}} = %d GeV/c^{2}" % lightHplusMassPoint brText = "#it{B}(t #rightarrow bH^{+})=%.2f" % lightHplusTopBR plot.appendPlotObject(histograms.PlotText(x, y, massText, size=size)) plot.appendPlotObject( histograms.PlotText(x, y - separation, brText, size=size))
def createPlot(name, dyx=0.67, dyy=0.64): name2 = name if isinstance(name, basestring): name2 = analysisEmb + "/" + name rootHistos = [] for datasetName in datasetNames: (histo, tmp) = datasetsEmb.getHistogram(datasetName, name2) histo.SetName(datasetName) rootHistos.append(histo) p = plots.DataMCPlot2(rootHistos) histos = p.histoMgr.getHistos() for h in histos: if h.getName() == "Data": h.setIsDataMC(True, False) else: h.setIsDataMC(False, True) p.setLuminosity(datasetsEmb.getLuminosity()) p.setDefaultStyles() if isCorrected: p.appendPlotObject( histograms.PlotText(dyx, dyy, "DY correction applied", size=15)) return p
def createTransverseMassPlotInternal(dset, name, postfix, normalizeToOne, nominalSelection, compareSelection, nominalLegend="Nominal", compareLegend="Compare", moveLegend={}): datasetName = dset.getName() treeDraw = dataset.TreeDraw("tree", varexp="TauMETTransverseMass >>tmp(10,0,200)") tdNominal = treeDraw.clone(selection=nominalSelection)#selection="Obj2Type == 3 && LeptonVetoStatus == 0 && (TauIDStatus == 1 || TauIDStatus == 2 || TauIDStatus == 3)") # FIXME tdCompare = treeDraw.clone(selection=compareSelection) drhNominal = dset.getDatasetRootHisto(tdNominal) drhCompare = dset.getDatasetRootHisto(tdCompare) integrate = lambda h: h.Integral(0, h.GetNbinsX()+1) nNominal = integrate(drhNominal.getHistogram()) nCompare = integrate(drhCompare.getHistogram()) if normalizeToOne: drhNominal.normalizeToOne() drhCompare.normalizeToOne() drhNominal.setName("Nominal") drhCompare.setName("Compare") p = plots.ComparisonPlot(drhNominal, drhCompare) p.histoMgr.forEachHisto(styles.generator()) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3)) p.histoMgr.setHistoLegendLabelMany({ "Nominal": nominalLegend+ " (%d)" % int(nNominal), "Compare": compareLegend+ " (%d)" % int(nCompare) }) pfix = postfix if normalizeToOne: pfix += "_unit" p.createFrame("mt_"+datasetName+"_"+name+"_"+pfix, createRatio=normalizeToOne, invertRatio=True, opts2={"ymin": 0, "ymax": 2}) p.frame.GetXaxis().SetTitle("Transverse mass (GeV/c^{2})") if normalizeToOne: p.frame.GetYaxis().SetTitle("Arbitrary units") else: p.frame.GetYaxis().SetTitle("MC events") p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.93, y2=0.80, x1=0.45, x2=0.85), **moveLegend)) nomErr = p.histoMgr.getHisto("Nominal").getRootHisto().Clone("Nominal_err") nomErr.SetFillColor(ROOT.kBlue-7) nomErr.SetFillStyle(3004) nomErr.SetMarkerSize(0) p.prependPlotObject(nomErr, "E2") comErr = p.histoMgr.getHisto("Compare").getRootHisto().Clone("Compare_err") comErr.SetFillColor(ROOT.kRed-7) comErr.SetFillStyle(3013) comErr.SetMarkerSize(0) p.prependPlotObject(comErr, "E2") if normalizeToOne: p.appendPlotObject(histograms.PlotText(0.6, 0.75, "Normalized to unit area", size=17)) p.draw() p.save()
def doScaleFactorFit(p, outputDir): histos = filter( lambda h: "shapeTransverseMass" in h.getName() and not "_syst" in h. getName(), p.ratioHistoMgr.getHistos()) if len(histos) != 1: for h in histos: print h.getName() raise Exception("Expecting 1 ratio histogram, got %d" % len(histos)) ratio = histos[0] fitfunc = ROOT.TF1("sffit", "[0]*x+[1]", 0, 160) ratio.getRootHisto().Fit(fitfunc, "NR") fitfunc.SetLineColor(ROOT.kBlue) fitfunc.SetLineWidth(2) p.getPad2().cd() fitfunc.Draw("same") par0 = fitfunc.GetParameter(0) par1 = fitfunc.GetParameter(1) histograms.PlotText(0.2, 0.5, "f(x) = p_{0}x + p_{1}", size=17, color=ROOT.kBlue).Draw() histograms.PlotText(0.2, 0.35, "p_{0} = %.4g, p_{1} = %.4g" % (par0, par1), size=17, color=ROOT.kBlue).Draw() formula = "%.10g*x + %.10g" % (par0, par1) errors = "%.5g %.5g" % (fitfunc.GetParError(0) / par0, fitfunc.GetParError(1) / par1) tauEmbedding.writeToFile( outputDir, "mtcorrectionfit.txt", "formula %s relative fit uncertainties %s" % (formula, errors))
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))
def createPlot(name, massbr_x=0.42, massbr_y=0.9, normone_x=0.25, normone_y=0.5, **kwargs): # For MC-only mode (and only then), we have to set the luminosity to which MC is normalized explicitly args = {} args.update(kwargs) if mcOnly: args["normalizeToLumi"] = mcOnlyLumi p = plots.DataMCPlot(datasets, name, **args) p.appendPlotObject( histograms.createSignalText(xmin=massbr_x, ymax=massbr_y)) if kwargs.get("normalizeToOne", False): p.appendPlotObject( histograms.PlotText(normone_x, normone_y, "Normalized to unit area", size=17)) return p
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 doPlot(datasetsEmb, analyses, path, name, text): histos = [] legends = { "Plus": "#tau-jet energy scale variated by +3 %", "Minus": "#tau-jet energy scale variated 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:]) p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20)) styles.dataStyle(p.histoMgr.getHisto("Baseline")) styles.mcStyle(p.histoMgr.getHisto("Plus")) styles.mcStyle2(p.histoMgr.getHisto("Minus")) p.histoMgr.getHisto("Minus").getRootHisto().SetMarkerSize(2) p.setLuminosity(datasetsEmb.getLuminosity()) p.createFrame(name, createRatio=True, opts2={"ymax": 2}, opts={"ymax": 35}) yaxis = p.getFrame2().GetYaxis() yaxis.SetTitle("Ratio") #yaxis.SetTitleSize(yaxis.GetTitleSize()*0.8) p.setLegend(histograms.moveLegend(histograms.createLegend())) p.appendPlotObject(histograms.PlotText(0.5, 0.55, text, size=20)) p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})") p.frame.GetYaxis().SetTitle("Events / 20 GeV/c^{2}") p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.addLuminosityText() p.save()
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 plotMet(h, name, xlabel, rebin=1, ratio=False, opts={}, opts2={}): if rebin > 1: h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin)) ylabel = "Events / %.0f GeV" % h.binWidth() h.stackMCHistograms(stackSignal=False) h.addMCUncertainty() opts_ = {"ymin": 1e-2, "ymaxfactor": 2} #10} opts_.update(opts) #h.createFrameFraction(name, opts=opts) h.createFrame(name + "_" + runs, opts=opts_, createRatio=ratio, opts2=opts2) if ratio: h.getFrame2().GetYaxis().SetTitle("Ratio") ROOT.gPad.SetLogy(True) h.setLegend(histograms.moveLegend(histograms.createLegend(), dx=-0.04)) h.appendPlotObject( histograms.PlotText(0.42, 0.89, "Runs %s" % runs, size=17)) common(h, xlabel, ylabel)
def doPlots(datasets): def createPlot(name, **kwargs): return plots.DataMCPlot(datasets, analysis+"/"+name, **kwargs) def addMassBRText(plot, x, y): mass = "m_{H^{+}} = 120 GeV/c^{2}" br = "#it{B}(t #rightarrow H^{+}b)=0.05" size = 20 separation= 0.04 plot.appendPlotObject(histograms.PlotText(x, y, mass, size=size)) plot.appendPlotObject(histograms.PlotText(x, y-separation, br, size=size)) # Number of vertices (unit area) p = createPlot("Vertices/verticesTriggeredAfterWeight", normalizeToOne=True) p.appendPlotObject(histograms.PlotText(0.35, 0.9, "Normalized to unit area", size=17)) drawPlot(p, "verticesAfterWeightTriggered_log", "Number of good vertices", ylabel="Arbitrary units", opts={"ymin": 1e-10, "ymaxfactor": 10, "xmax": 30}, opts2 = {"ymin": 0.5, "ymax": 3}) # Selected tau jet pt p = createPlot("SelectedTau/SelectedTau_pT_AfterTauID") addMassBRText(p, x=0.31, y=0.22) drawPlot(p, "SelectedTau_pT_AfterTauID", "p_{T}^{#tau jet} (GeV/c)", rebin=10, opts={"xmax": 250}) # Selected tau jet eta p = createPlot("SelectedTau/SelectedTau_eta_AfterTauID") addMassBRText(p, x=0.3, y=0.85) drawPlot(p, "SelectedTau_eta_AfterTauID", "#eta^{#tau jet}", ylabel="Events / %.1f", rebin=10, opts={"ymin": 1e-1, "ymaxfactor": 40, "xmin": -2.5, "xmax": 2.5}, moveLegend={"dy":0.01, "dh":-0.06}) # Selected tau jet Rtau (without rtau cut) p = createPlot("tauID/TauID_RtauCut") addMassBRText(p, x=0.31, y=0.22) drawPlot(p, "TauID_Rtau", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", ylabel="Events / %.2f", rebin=2, opts={"ymin": 1e-2, "ymaxfactor": 20, "xmax": 1.1}, moveLegend={"dx": -0.5, "dy": 0.01, "dh": -0.04}, cutLine=0.7) # Identified electron pt p = createPlot("GlobalElectronVeto/GlobalElectronPt_identified_eta") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "electronPt", "p_{T}^{electron} (GeV/c)", rebin=15, ylabel="Identified electrons / %.0f GeV/c", opts={"xmax": 250}, cutLine=15) # Identified electron eta p = createPlot("GlobalElectronVeto/GlobalElectronEta_identified") addMassBRText(p, x=0.3, y=0.87) drawPlot(p, "electronEta", "#eta^{electron}", rebin=15, ylabel="Identified electrons / %.1f", opts={"xmin": -3, "xmax": 3, "ymaxfactor": 50}, moveLegend={"dy":0.01, "dx":-0.07, "dh":-0.06}, cutLine=[-2.5, 2.5]) # Identified muon pt p = createPlot("GlobalMuonVeto/GlobalMuonPt_identified_eta") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "muonPt", "p_{T}^{muon} (GeV/c)", ylabel="Identified muons / %.0f GeV/c", rebin=3, opts={"xmax": 250}, cutLine=15) # Identified muon eta p = createPlot("GlobalMuonVeto/GlobalMuonEta_identified") addMassBRText(p, x=0.3, y=0.87) drawPlot(p, "muonEta", "#eta^{muon}", ylabel="Identified muons / %.1f", rebin=3, opts={"xmin": -3, "xmax": 3, "ymaxfactor": 40}, moveLegend={"dy":0.01, "dx":-0.07, "dh":-0.06}, cutLine=[-2.5, 2.5]) # Jet pt p = createPlot("JetSelection/jet_pt_central") addMassBRText(p, x=0.3, y=0.87) drawPlot(p, "centralJetPt", "p_{T}^{jet} (GeV/c)", ylabel="Jets / %.0f GeV/c", rebin=5, opts={"xmax": 400}, cutLine=30) # Jet eta p = createPlot("JetSelection/jet_eta") addMassBRText(p, x=0.4, y=0.22) drawPlot(p, "jetEta", "#eta^{jet}", ylabel="Jets / %.1f", rebin=4, opts={"ymaxfactor": 110}, moveLegend={"dy":0.01, "dx":-0.2, "dh":-0.06}, cutLine=[-2.4, 2.4]) # Jet multiplicity p = createPlot("JetSelection/NumberOfSelectedJets") addMassBRText(p, x=0.67, y=0.6) drawPlot(p, "NumberOfJets", "Number of selected jets", ylabel="Events / %.0f", opts={"xmax": 10}, cutLine=3) # MET p = createPlot("Met") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "Met", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=25, ylabel="Events / %.0f GeV", opts={"xmax": 400}, cutLine=50) # B jet pt p = createPlot("Btagging/bjet_pt") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "bjetPt", "p_{T}^{b-tagged jet} (GeV/c)", rebin=15, ylabel="b-tagged jets / %.0f GeV/c", opts={"xmax": 400}) # B jet eta p = createPlot("Btagging/bjet_eta") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "bjetEta", "#eta^{b-tagged jet}", ylabel="b-tagged jets / %.1f", rebin=8, opts={"ymaxfactor": 30, "xmin": -2.4, "xmax": 2.4}, moveLegend={"dy":0.01, "dh":-0.06}) # B jet multiplicity p = createPlot("Btagging/NumberOfBtaggedJets") addMassBRText(p, x=0.45, y=0.87) drawPlot(p, "NumberOfBJets", "Number of selected b jets", ylabel="Events / %.0f", opts={"xmax": 6}, cutLine=1) # DeltaPhi p = createPlot("deltaPhi") addMassBRText(p, x=0.2, y=0.87) drawPlot(p, "DeltaPhiTauMet", "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})", ylabel="Events / %.0f^{o}", rebin=20, opts={"ymaxfactor": 20}, moveLegend={"dx":-0.21}, cutLine=[160, 130]) # Transverse mass p = createPlot("transverseMass") addMassBRText(p, x=0.4, y=0.87) drawPlot(p, "transverseMass", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", ylabel="Events / %.0f GeV/c^{2}", rebin=20, log=False) # Selection flow p = createPlot("SignalSelectionFlow") addMassBRText(p, 0.4, 0.87) def customiseFlow(plot): xaxis = plot.getFrame().GetXaxis() xaxis.SetBinLabel(1, "Trigger") xaxis.SetBinLabel(2, "#tau ID+R_{#tau}") xaxis.SetBinLabel(3, "e veto") xaxis.SetBinLabel(4, "#mu veto") xaxis.SetBinLabel(5, "N_{jets}") lastSelection = 4 # mu veto drawPlot(p, "SignalSelectionFlow", "", ylabel="Events", opts={"xmax": lastSelection, "ymin": 0.1, "ymaxfactor": 2, "nbins": lastSelection}, customise=customiseFlow)
def main(): # Read the datasets datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters, weightedCounters=False) if runRegion == 1: datasets.remove([ "SingleMu_Mu_170722-172619_Aug05", "SingleMu_Mu_172620-173198_Prompt", "SingleMu_Mu_173236-173692_Prompt" ]) elif runRegion == 2: datasets.remove([ "SingleMu_Mu_160431-163261_May10", "SingleMu_Mu_163270-163869_May10", "SingleMu_Mu_165088-166150_Prompt", "SingleMu_Mu_166161-166164_Prompt", "SingleMu_Mu_166346-166346_Prompt", "SingleMu_Mu_166374-167043_Prompt", "SingleMu_Mu_167078-167913_Prompt" ]) else: raise Exception("Unsupported run region %d" % runRegion) datasets.remove([ # "SingleMu_160431-163261_May10", # "SingleMu_163270-163869_May10", # "SingleMu_165088-166150_Prompt", # "SingleMu_166161-166164_Prompt", # "SingleMu_166346-166346_Prompt", # "SingleMu_166374-167043_Prompt", # "SingleMu_167078-167784_Prompt", # "SingleMu_167786-167913_Prompt_Wed", # "DYJetsToLL_M50_TuneZ2_Summer11", # "QCD_Pt20_MuEnriched_TuneZ2_Summer11", # "TTJets_TuneZ2_Summer11", # "WJets_TuneZ2_Summer11", ]) datasets.loadLuminosities() dataNames = datasets.getDataDatasetNames() datasets.mergeData() bins = range(0, 170, 10) + [180, 200, 250, 300, 400] th1 = ROOT.TH1D("foo", "foo", len(bins) - 1, array.array("d", bins)) th1.Sumw2() #th1 = ROOT.TH1D("foo", "foo", 40, 0, 400) binning = ">>tmp(40,0,400)" #binning=binningDist binningEff = ">>foo" treeDraw = dataset.TreeDraw( analysis + "/tree", #weight="pileupWeightEPS", varexp="pfMet_p4.Et()" + binning) # Apply TDR style style = tdrstyle.TDRStyle() plots._legendLabels["QCD_Pt20_MuEnriched"] = "QCD" print "Runs", runs passed = treeDraw.clone(selection="caloMetNoHF_p4.Et() > 60") dataText = "offline calo E_{T}^{miss} (excl. HF) > 60 GeV" mcText = "offline calo E_{T}^{miss} (excl. HF) > 60 GeV" if runRegion == 1: #printEfficienciesCalo(datasets, treeDraw.clone(varexp="caloMetNoHF.Et()"+binning)) pass elif runRegion == 2: passedData = treeDraw.clone( selection="l1Met.Et() > 30 && caloMet_p4.Et() > 60") #passedData = passed.clone() cut = "L1 E_{T}^{miss} > 30 &\n offline calo E_{T}^{miss} " if caloMetNoHF: passedData = treeDraw.clone( selection="l1Met.Et() > 30 && caloMetNoHF_p4.Et() > 60") cut += "(excl. HF) > 60 GeV" else: cut += "(incl. HF) > 60 GeV" if mcDataDefinition: passed = passedData dataText = cut mcText = cut else: dataText = cut tmp = {} for name in dataNames: tmp[name] = passedData passed = dataset.TreeDrawCompound(passed, tmp) #passed = dataset.TreeDrawCompound(passedData) #passed = passedData #passed = treeDraw.clone(selection="l1Met.Et() > 30 && caloMetNoHF.Et() > 60") printEfficienciesPF(datasets, pathAll=treeDraw.clone(), pathPassed=passed.clone(), bin=0) printEfficienciesPF(datasets, pathAll=treeDraw.clone(), pathPassed=passed.clone(), bin=5) #printEfficienciesPF(datasets, pathAll=treeDraw.clone(), pathPassed=passed.clone()) plotTurnOn(datasets, pathAll=treeDraw.clone(varexp="pfMet_p4.Et()" + binningEff), pathPassed=passed.clone(varexp="pfMet_p4.Et()" + binningEff), commonText=None, dataText=dataText, mcText=mcText, ratio=True) pfmet = treeDraw.clone(varexp="pfMet_p4.Et()" + binningEff) plotTurnOnData(datasets, name="l1met", pathAll=pfmet.clone(), pathPassed1=pfmet.clone(selection="caloMet_p4.Et() > 60"), pathPassed2=pfmet.clone( selection="l1Met.Et() > 30 && caloMet_p4.Et() > 60"), dataText1="CaloMET > 60 GeV", dataText2="L1 MET > 30 & CaloMET > 60 GeV", ratio=True) plotTurnOnData(datasets, name="l1met36", pathAll=pfmet.clone(), pathPassed1=pfmet.clone( selection="l1Met.Et() > 30 && caloMet_p4.Et() > 60"), pathPassed2=pfmet.clone( selection="l1Met.Et() > 36 && caloMet_p4.Et() > 60"), dataText1="L1 MET > 30 & CaloMET > 60 GeV", dataText2="L1 MET > 36 & CaloMET > 60 GeV", ratio=True) plotTurnOnData(datasets, name="l1met40", pathAll=pfmet.clone(), pathPassed1=pfmet.clone( selection="l1Met.Et() > 30 && caloMet_p4.Et() > 60"), pathPassed2=pfmet.clone( selection="l1Met.Et() > 40 && caloMet_p4.Et() > 60"), dataText1="L1 MET > 30 & CaloMET > 60 GeV", dataText2="L1 MET > 40 & CaloMET > 60 GeV", ratio=True) #plotTurnOn(datasets, pathAll=analysis+"/pfmet_et", pathPassed=afterCut+"/pfmet_et") plots.mergeRenameReorderForDataMC(datasets) datasets.remove("TTToHplusBWB_M120") # Set the signal cross sections to the ttbar # xsect.setHplusCrossSections(datasets, toTop=True) # Set the signal cross sections to a value from MSSM # xsect.setHplusCrossSections(datasets, tanbeta=20, mu=200) # Per-event weighting doesn't work with TEfficiency weight = "pileupWeightEPS" if runRegion == 2: weight = "weightPileup_Run2011AnoEPS" treeDraw = treeDraw.clone(weight=weight) passed = passed.clone(weight=weight) l1Met( plots.DataMCPlot(datasets, treeDraw.clone(varexp="l1Met.Et()" + binning)), "l1Met") caloMet(plots.DataMCPlot( datasets, treeDraw.clone(varexp="caloMetNoHF_p4.Et()" + binning)), "caloMetNoHF", hf=False) caloMet(plots.DataMCPlot( datasets, treeDraw.clone(varexp="caloMet_p4.Et()" + binning)), "caloMet", hf=True) pfMet(plots.DataMCPlot(datasets, treeDraw.clone(varexp="pfMet_p4.Et()" + binning)), "pfMet", ratio=True, opts={"ymax": 3e3}, opts2={ "ymin": 0.5, "ymax": 1.5 }) p = plots.DataMCPlot(datasets, passed.clone(varexp="pfMet_p4.Et()" + binning)) x = 0.2 y = 0.27 p.appendPlotObject(histograms.PlotText(x, y, "Data:", size=17)) y -= 0.03 p.appendPlotObject(histograms.PlotText(x, y, dataText, size=17)) y -= 0.04 p.appendPlotObject(histograms.PlotText(x, y, "Simulation:", size=17)) y -= 0.03 p.appendPlotObject(histograms.PlotText(x, y, mcText, size=17)) y -= 0.03 pfMet(p, "pfMet_afterCut", ratio=True, opts={"ymax": 3e3}, opts2={ "ymin": 0.5, "ymax": 1.5 })
def caloMet(h, name, hf, **kwargs): txt = "HF excluded" if hf: txt = "HF included" h.appendPlotObject(histograms.PlotText(0.42, 0.85, txt, size=17)) plotMet(h, name, "Uncorrected calo E_{T}^{miss} (GeV)", **kwargs)
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 plotTurnOn(datasets, pathAll, pathPassed, commonText, dataText=None, mcText=None, rebin=1, ratio=False): dataLabel = "Data" mcLabel = "Simulation" if dataText != None and mcText == None: raise Exception("mcText must not be None when dataText is not") if dataText == None and mcText != None: raise Exception("dataText must not be None when mcText is not") # if dataText != None: # dataLabel += ": "+dataText # mcLabel += ": "+mcText mc_effs = [] data_eff_gr = None binWidth = None luminosity = 0 for dataset in datasets.getAllDatasets(): all = dataset.getDatasetRootHisto(pathAll).getHistogram() passed = dataset.getDatasetRootHisto(pathPassed).getHistogram() if rebin > 1: all.Rebin(rebin) passed.Rebin(rebin) binWidth = all.GetBinWidth(1) if dataset.isMC() and not "TTTo" in dataset.getName(): #if dataset.isMC() and not "TTTo" in dataset.getName() and not "QCD" in dataset.getName(): #if dataset.isMC() and "QCD" in dataset.getName(): mc_effs.append(HistoEff(all, passed, dataset)) elif dataset.isData(): data_eff_gr = ROOT.TGraphAsymmErrors(passed, all, "cp") # 0.683 cl is default luminosity += dataset.getLuminosity() mc_eff_gr = combineHistoEffs(mc_effs) p = plots.ComparisonPlot( histograms.HistoGraph(data_eff_gr, "Data", "p", "P"), histograms.HistoGraph(mc_eff_gr, "Simulation", "p", "P")) p.histoMgr.forEachHisto( styles.generator2(styles.StyleMarker(markerSizes=[1.0, 1.5]), plotStyles)) p.histoMgr.setHistoLegendLabelMany({ "Data": dataLabel, "Simulation": mcLabel, }) p.setLuminosity(luminosity) #p.addGraph(data_eff_gr, "Data") #p.addGraph(mc_eff_gr, "Simulation") #p.finalize() opts = {"ymin": 0.0, "ymax": 1.1} #opts2 = {"ymin": 0.5, "ymax": 1.5} opts2 = {"ymin": 0.7, "ymax": 1.3} name = "calomet_turnon_" + runs if not mcDataDefinition: name += "_McSummer11" if caloMetNoHF: name += "_caloMetNoHF" p.createFrame(name, createRatio=ratio, opts=opts, opts2=opts2) if ratio: p.getFrame2().GetYaxis().SetTitle("Ratio") p.cf.canvas.cd(2) p.line1 = plots._createRatioLine(p.cf.frame.getXmin(), p.cf.frame.getXmax(), 0.9) p.line2 = plots._createRatioLine(p.cf.frame.getXmin(), p.cf.frame.getXmax(), 1.1) p.line1.SetLineColor(ROOT.kBlue) p.line2.SetLineColor(ROOT.kBlue) p.line1.Draw("L") p.line2.Draw("L") p.cf.canvas.cd(1) p.setLegend( histograms.moveLegend( histograms.createLegend(y1=0.95, y2=0.85), #dx=-0.55, dy=-0.05 #dx=-0.44, dy=-0.58 dx=-0.3, dy=-0.4)) x = 0.25 y = 0.3 dy = 0.035 mcColor = mc_eff_gr.GetMarkerColor() size = 17 p.appendPlotObject( histograms.PlotText(x, y, "Data (runs %s):" % runs, size=size)) y -= dy p.appendPlotObject(histograms.PlotText(x, y, dataText, size=size)) y -= dy y -= 0.01 p.appendPlotObject( histograms.PlotText(x, y, "Simulation:", size=size, color=mcColor)) y -= dy p.appendPlotObject( histograms.PlotText(x, y, mcText, size=size, color=mcColor)) y -= dy def text(): l = ROOT.TLatex() l.SetNDC() # l.SetTextFont(l.GetTextFont()-20) # bold -> normal l.SetTextSize(l.GetTextSize() * 0.65) #l.DrawLatex(0.35, 0.4, commonText) l.DrawLatex(0.48, 0.32, commonText) textFunction = text if dataText != None: textFunction = None #common(p, "PF E_{T}^{miss} (GeV)", "Efficiency / %.0f GeV"%binWidth, afterDraw=textFunction) common(p, "Uncorrected PF E_{T}^{miss} (GeV)", "Efficiency", afterDraw=textFunction)
def doPlots(datasets, mcLumi=None): createPlot = lambda name: createPlotCommon(name, datasets, mcLumi) #opts = {"xmin": 40, "xmax": 200, "ymaxfactor":10, "ymin": 1e-1} opts = {"xmin": 40, "xmax": 200, "ymaxfactor": 2, "ymin": 1e-1} opts2 = {"ymin": 0, "ymax": 2} rebin = 10 tdTauPt = treeDraw.clone(varexp="tau_p4.Pt()>>tmp(16, 40, 200)") tdTauP = treeDraw.clone(varexp="tau_p4.P()>>tmp(16, 40, 200)") tdTauLeadPt = treeDraw.clone( varexp="tau_leadPFChargedHadrCand_p4.Pt()>>tmp(16, 40, 200)") tdTauLeadP = treeDraw.clone( varexp="tau_leadPFChargedHadrCand_p4.P()>>tmp(16, 40, 200)") tdRtau = treeDraw.clone( varexp= "tau_leadPFChargedHadrCand_p4.P() / tau_p4.P() -1e-10 >>tmp(11, 0, 1.1)" ) tdDeltaPhi = treeDraw.clone( varexp= "acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 >>tmp(18, 0, 180)" ) drawPlot = tauEmbedding.drawPlot # Tau pt xlabel = "p_{T}^{#tau jet} (GeV/c)" drawPlot(createPlot("SelectedTau/SelectedTau_pT_AfterTauID"), "selectedTauPt_1AfterTauID", xlabel, opts=opts, rebin=rebin, ratio=False) drawPlot(createPlot(tdTauPt.clone()), "selectedTauPt_1AfterTauID_crosscheck", xlabel, opts=opts, ratio=False) drawPlot(createPlot(tdTauPt.clone(selection=metCut)), "selectedTauPt_2AfterMET", xlabel, opts=opts, ratio=False) optstmp = {} optstmp.update(opts) del optstmp["ymaxfactor"] optstmp["ymax"] = 60 drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut, weight=weightBTagging)), "selectedTauPt_3AfterBTagging", xlabel, opts=optstmp) drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut + "&&" + deltaPhi160Cut, weight=weightBTagging)), "selectedTauPt_4AfterDeltaPhi160", xlabel, opts=optstmp) drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut + "&&" + deltaPhi130Cut, weight=weightBTagging)), "selectedTauPt_4AfterDeltaPhi130", xlabel, opts=optstmp) drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut, weight="")), "selectedTauPt_3AfterBTagging_notNormalized", xlabel, opts=optstmp, normalize=False) drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut + "&&" + deltaPhi160Cut, weight="")), "selectedTauPt_4AfterDeltaPhi160_notNormalized", xlabel, opts=optstmp, normalize=False) drawPlot(createPlot( tdTauPt.clone(selection=metCut + "&&" + bTaggingCut + "&&" + deltaPhi130Cut, weight="")), "selectedTauPt_4AfterDeltaPhi130_notNormalized", xlabel, opts=optstmp, normalize=False) # Tau leading track pt xlabel = "p_{T}^{#tau leading track} (GeV/c)" drawPlot(createPlot(tdTauLeadPt.clone()), "selectedTauLeadPt_1AfterTauID", xlabel, opts=opts, ratio=False) # Tau p xlabel = "p^{#tau jet} (GeV/c)" drawPlot(createPlot(tdTauP.clone()), "selectedTauP_1AfterTauID", xlabel, opts=opts, ratio=False) # Tau leading track pt xlabel = "p^{#tau leading track} (GeV/c)" drawPlot(createPlot(tdTauLeadP.clone()), "selectedTauLeadP_1AfterTauID", xlabel, opts=opts, ratio=False) # Rtau xlabel = "R_{#tau}" drawPlot(createPlot(tdRtau.clone()), "selectedTauRtau_1AfterTauID", xlabel, ylabel="Events / %.f", opts={"ymin": 1e-1}, ratio=False) # DeltaPhi xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{#circ})" def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) drawPlot(createPlot(tdDeltaPhi.clone()), "deltaPhi_1AfterTauID", xlabel, ylabel="Events / %.f^{#circ}", opts={ "ymin": 1e-1, "ymaxfactor": 5 }, opts2=opts2, moveLegend={ "dx": -0.22, "dy": 0.01, "dh": -0.03 }, customise=customDeltaPhi, cutLine=[130, 160]) # Data-driven control plots def drawControlPlot(path, xlabel, **kwargs): drawPlot(createPlot("ControlPlots/" + path), "controlPlots_" + path, xlabel, opts2=opts2, **kwargs) drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 40, "greaterThan": True }) drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts={ "xmin": -2.2, "xmax": 2.2 }, ylabel="Events / %.1f", rebin=4, moveLegend={ "dy": -0.5, "dx": -0.1 }) drawControlPlot("SelectedTau_phi_AfterStandardSelections", "#tau-jet #phi", rebin=10, ylabel="Events / %.2f") drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts={ "xmin": 0.65, "xmax": 1.05, "ymin": 1e-1, "ymaxfactor": 10 }, rebin=5, ylabel="Events / %.2f", moveLegend={ "dx": -0.4, "dy": 0.01, "dh": -0.03 }, cutBox={ "cutValue": 0.7, "greaterThan": True }) drawControlPlot("SelectedTau_p_AfterStandardSelections", "#tau-jet p (GeV/c)", rebin=2) drawControlPlot("SelectedTau_LeadingTrackP_AfterStandardSelections", "#tau-jet ldg. charged particle p (GeV/c)", rebin=2) #drawControlPlot("IdentifiedElectronPt_AfterStandardSelections", "Electron p_{T} (GeV/c)") #drawControlPlot("IdentifiedMuonPt_AfterStandardSelections", "Muon p_{T} (GeV/c)") drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") drawControlPlot("MET", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50) drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", cutLine=1) # Number of EWK events for QCD measurement (not needed at the moment # del opts["xmin"] # del opts["xmax"] # f = ROOT.TFile.Open(tauPtOutput, "RECREATE") # bins = [40, 50, 60, 70, 80, 100, 120, 150, 300] # tauPtPrototype = ROOT.TH1F("tauPtHistoFoo", "Tau pt", len(bins)-1, array.array("d", bins)) # tauPtPrototype.SetDirectory(ROOT.gDirectory) # for name, an in [ # ("AllSelectionsNoRtau", analysisNoRtau), # ("AllSelections", analysis) # ]: # td = treeDraw.clone(tree=an+"/tree", varexp="tau_p4.Pt() >>tauPtHistoFoo", weight=weightBTagging, selection=metCut+"&&"+bTaggingCut) # tauPt(createPlot(td), "selectedTauPt_9"+name, opts=opts) # pt = createPlot(td) # scaleNormalization(pt) # pt_data = pt.histoMgr.getHisto("Data").getRootHisto().Clone("tauPt_ewk_"+name) # pt_data.SetDirectory(f) # pt_data.Write() # f.Close() opts = {"xmin": 70, "ymaxfactor": 10} rebin = 10 tdMet = treeDraw.clone(varexp="met_p4.Et()>>tmp(20,0,200)") tdMetOrig = treeDraw.clone(varexp="temet_p4.Et()>>tmp(20,0,200)") opts = {} #tdMt = treeDraw.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(40,0,400)") tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) #f = ROOT.TFile.Open(mtOutput, "RECREATE") ratio = True if normalize and not "Rtau0MET" in analysis: opts["ymax"] = 40 elif not normalize: opts["xmax"] = 200 deltaPhiLabel = "#Delta#phi(#tau jet, E_{T}^{miss})" for name, label, selection in [ ("1AfterTauID", "", ""), ("2AfterMETCut", "", metCut), ("3AfterBTagging", "Without %s cut" % deltaPhiLabel, metCut + "&&" + bTaggingCut), #("3AfterBTagging_calo", caloMetCut+"&&"+metCut+"&&"+bTaggingCut), #("3AfterBTagging_caloNoHF", caloMetNoHFCut+"&&"+metCut+"&&"+bTaggingCut), ("4AfterDeltaPhi160", "%s < 160^{o}" % deltaPhiLabel, metCut + "&&" + bTaggingCut + "&&" + deltaPhi160Cut), ("4AfterDeltaPhi130", "%s < 130^{o}" % deltaPhiLabel, metCut + "&&" + bTaggingCut + "&&" + deltaPhi130Cut), ("4AfterDeltaPhi90", "%s < 90^{o}" % deltaPhiLabel, metCut + "&&" + bTaggingCut + "&&" + deltaPhi90Cut), ]: w = weight if bTaggingCut in selection: w = weightBTagging td = tdMt.clone(selection=selection, weight=w) p = createPlot(td.clone()) p.appendPlotObject(histograms.PlotText(0.5, 0.55, label, size=20)) drawPlot(p, "transverseMass_" + name, "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", ylabel="Events / %.0f GeV/c^{2}", opts=opts, ratio=ratio, log=False) drawPlot(createPlot(td.clone(varexp="jets_btag >>tmp(30, 0, 3)")), "btagDiscriminator_" + name, "TCHE", ylabel="Jets / %.1f", ratio=ratio, opts={ "ymin": 1e-1, "ymax": 1e2 })
def doPlotsWTauMu(datasets, name, datasetName, ntupleCache, selectorName, unweighted, fitFunction, rebin=None): ds = datasets.getDataset(datasetName) # Take first unweighted histograms for the fraction plot drh_all = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection" + unweighted, selectorName)) drh_pure = ds.getDatasetRootHisto( ntupleCache.histogram( "selectedMuonPt_AfterJetSelection_MuFromW" + unweighted, selectorName)) def Rebin(th1, div=False): if rebin is None: return th1 else: h = th1.Rebin( len(rebin) - 1, th1.GetName(), array.array("d", rebin)) if div: h.Scale(1, "width") return h def createTEfficiency(drhAll, drhPure): hallUn = Rebin(drhAll.getHistogram()) hpureUn = Rebin(drhPure.getHistogram()) teff = ROOT.TEfficiency(hpureUn, hallUn) teff.SetDirectory(0) teff.SetWeight(drhAll.getDataset().getCrossSection()) return teff teffs = drh_all.forEach(createTEfficiency, drh_pure) #coll = ROOT.TList() #for o in teffs: # coll.AddLast(o) #ratio = ROOT.TEfficiency.Combine(coll) ratio = teffs[0] for e in teffs[1:]: ratio.Add(e) styles.getDataStyle().apply(ratio) ratio.SetName(datasetName) ROOT.gStyle.SetStatY(0.99) ROOT.gStyle.SetStatX(0.52) ROOT.gStyle.SetStatW(0.18) ROOT.gStyle.SetStatH(0.23) expFit = ROOT.TF1("purityFit", [ "1/(1+[0]*exp(-[1]*x))", "1-[0]*exp(-[1]*x)", "1-([0]/(x^[1]))", ][fitFunction], aux.th1Xmin(ratio.GetPassedHistogram()), aux.th1Xmax(ratio.GetPassedHistogram())) expFit.SetParameter(0, 0.05) ratio.Fit(expFit, "N") expFit.SetLineColor(ROOT.kRed) expFit.SetLineWidth(2) # expFit = None # Then the correctly weighted for the main plot drh_all = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection", selectorName)) drh_pure = ds.getDatasetRootHisto( ntupleCache.histogram("selectedMuonPt_AfterJetSelection_MuFromW", selectorName)) if mcOnly: lumi = mcLuminosity else: lumi = datasets.getDataset("Data").getLuminosity() drh_all.normalizeToLuminosity(lumi) drh_pure.normalizeToLuminosity(lumi) hall = Rebin(drh_all.getHistogram(), div=True) hpure = Rebin(drh_pure.getHistogram(), div=True) hall.SetName("All") hpure.SetName("Pure") p = plots.ComparisonPlot(hall, hpure) p.setLuminosity(lumi) p.setEnergy(ds.getEnergy()) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", # "Pure": "W#rightarrow#tau#rightarrow#mu" "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue - 7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed - 7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame(era + "_" + name + "_selectedMuonPt_AFterJetSelection_MuFromW_%s_fit%d" % (datasetName, fitFunction) + unweighted, createRatio=True, opts={ "ymin": 1e-1, "ymaxfactor": 2 }, opts2={ "ymin": 0.9, "ymax": 1.05 }) p.setRatios([ratio]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1 - 0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.appendPlotObjectToRatio( histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue)) if expFit is not None: p.appendPlotObjectToRatio(expFit) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.getPad().SetLogy(True) p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)") p.frame.GetYaxis().SetTitle("Events / #Deltap_{T} %.0f-%.0f GeV/c" % (min(p.binWidths()), max(p.binWidths()))) p.appendPlotObject( histograms.PlotText(0.5, 0.9, plots._legendLabels.get(datasetName, datasetName), size=18)) p.draw() p.addStandardTexts() p.save() # Clear list of functions ratio.GetListOfFunctions().Delete() return (ratio, expFit)
def doPlots(datasetsEmb, datasetsSig, datasetName, addData=False, postfix=""): lumi = datasetsEmb.getLuminosity() isCorrected = isinstance(datasetsEmb, result.DatasetsDYCorrection) or isinstance( datasetsEmb, result.DatasetsResidual) def createPlot(name, rebin=1, addVariation=False): name2Emb = name name2Sig = name if isinstance(name, basestring): name2Emb = analysisEmb + "/" + name name2Sig = analysisSig + "/" + name else: name2Emb = name.clone(tree=analysisEmb + "/tree") name2Sig = name.clone(tree=analysisSig + "/tree") (emb, embVar) = datasetsEmb.getHistogram(datasetName, name2Emb, rebin) sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig) sig.normalizeToLuminosity(lumi) sig = sig.getHistogram() if rebin > 1: sig.Rebin(rebin) emb.SetName("Embedded") sig.SetName("Normal") p = None sty = plotStyles if addData: (embData, embDataVar) = datasetsEmb.getHistogram("Data", name2Emb, rebin=rebin) embData.SetName("EmbeddedData") #p = plots.ComparisonManyPlot(embData, [emb, sig]) #p = plots.ComparisonPlot(embData, sig) p = plots.ComparisonManyPlot(sig, [embData, emb]) p.histoMgr.reorderDraw(["EmbeddedData", "Embedded", "Normal"]) p.histoMgr.reorderLegend(["EmbeddedData", "Embedded", "Normal"]) p.histoMgr.setHistoDrawStyle("EmbeddedData", "EP") p.histoMgr.setHistoLegendStyle("EmbeddedData", "P") p.histoMgr.setHistoLegendStyle("Embedded", "PL") p.setLuminosity(lumi) # sty = [styles.dataStyle, styles.styles[1]] #sty = [sty[0], styles.dataStyle, sty[1]] sty = [styles.dataStyle] + sty else: p = plots.ComparisonPlot(emb, sig) sty = styles.styles embedded = "Embedded " legLabel = plots._legendLabels.get(datasetName, datasetName) legLabelEmb = legLabel if legLabel != "Data": legLabel += " MC" residual = "" if isCorrected: embedded = "Emb. " residual = " + res. MC" else: lebLabelEmb += " MC" p.histoMgr.setHistoLegendLabelMany({ "Embedded": embedded + legLabelEmb + residual, "Normal": "Normal " + legLabel, #"EmbeddedData": "Embedded data"+residual, "EmbeddedData": embedded + "data" + residual, }) p.histoMgr.forEachHisto(styles.Generator(sty)) if addVariation: if addData: if embDataVar != None: plots.copyStyle( p.histoMgr.getHisto("EmbeddedData").getRootHisto(), embDataVar) embDataVar.SetMarkerStyle(2) p.embeddingDataVariation = embDataVar if embVar != None: plots.copyStyle( p.histoMgr.getHisto("Embedded").getRootHisto(), embVar) embVar.SetMarkerStyle(2) p.embeddingVariation = embVar return p def createDrawPlot(name, *args, **kwargs): p = createPlot(name) drawPlot(p, *args, **kwargs) prefix = "mcembsig" if addData: prefix = "embdatasigmc" prefix = prefix + postfix + "_" + datasetName + "_" #opts2def = {"DYJetsToLL": {"ymin":0, "ymax": 1.5}}.get(datasetName, {"ymin": 0.5, "ymax": 1.5}) opts2def = {"ymin": 0, "ymax": 2} def drawControlPlot(path, xlabel, rebin=None, opts2=None, **kwargs): opts2_ = opts2def if opts2 != None: opts2_ = opts2 cargs = {} if rebin != None: cargs["rebin"] = rebin drawPlot(createPlot("ControlPlots/" + path, **cargs), prefix + path, xlabel, opts2=opts2_, **kwargs) def update(d1, d2): tmp = {} tmp.update(d1) tmp.update(d2) return tmp # Control plots optsdef = {} opts = optsdef drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts=update(opts, {"xmax": 250}), rebin=2, cutBox={ "cutValue": 40, "greaterThan": 40 }) opts = optsdef moveLegend = {"dy": -0.6, "dx": -0.2} if analysisEmb != "signalAnalysis": opts = { "SingleTop": { "ymax": 1.8 } }.get(datasetName, {"ymaxfactor": 1.4}) if datasetName != "TTJets": moveLegend = {"dx": -0.32} drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts=update(opts, { "xmin": -2.2, "xmax": 2.2 }), ylabel="Events / %.1f", rebin=4, log=False, moveLegend=moveLegend) drawControlPlot("SelectedTau_phi_AfterStandardSelections", "#tau-jet #phi", rebin=10, ylabel="Events / %.2f", log=False) drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts=update(opts, {"xmax": 300}), rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) opts = {"ymin": 1e-1, "ymaxfactor": 5} moveLegend = {"dx": -0.3} if analysisEmb != "signalAnalysis": moveLegend = {"dx": -0.25} if datasetName == "Diboson": opts["ymin"] = 1e-2 drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts=update(opts, { "xmin": 0.65, "xmax": 1.05 }), rebin=5, ylabel="Events / %.2f", moveLegend=moveLegend, cutBox={ "cutValue": 0.7, "greaterThan": True }) opts = optsdef drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") # After Njets drawControlPlot("MET", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=5, opts=update(opts, {"xmax": 400}), cutLine=50) # after MET moveLegend = {"dx": -0.23, "dy": -0.5} moveLegend = { "WJets": {}, "DYJetsToLL": {}, "SingleTop": {}, "Diboson": {} }.get(datasetName, moveLegend) drawControlPlot("NBjets", "Number of selected b jets", opts=update(opts, {"xmax": 6}), ylabel="Events", moveLegend=moveLegend, cutLine=1) # Tree cut definitions treeDraw = dataset.TreeDraw("dummy", weight=weightBTagging) tdDeltaPhi = treeDraw.clone( varexp= "acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 >>tmp(18, 0, 180)" ) tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) # DeltapPhi xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})" def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) opts = { "WJets": { "ymax": 35 }, "DYJetsToLL": { "ymax": 12 }, "Diboson": { "ymax": 1 }, }.get(datasetName, {"ymaxfactor": 1.2}) opts2 = opts2def if analysisEmb != "signalAnalysis": opts = { "WJets": { "ymax": 20 }, "DYJetsToLL": { "ymax": 5 }, "SingleTop": { "ymax": 2 }, "Diboson": { "ymax": 0.6 }, }.get(datasetName, {"ymaxfactor": 1.2}) opts2 = {"WJets": {"ymin": 0, "ymax": 3}}.get(datasetName, opts2def) drawPlot(createPlot(tdDeltaPhi.clone(selection=And(metCut, bTaggingCut))), prefix + "deltaPhi_3AfterBTagging", xlabel, log=False, opts=opts, opts2=opts2, ylabel="Events / %.0f^{o}", function=customDeltaPhi, moveLegend={"dx": -0.22}, cutLine=[130, 160]) # After all cuts selection = "&&".join([metCut, bTaggingCut, deltaPhi160Cut]) #opts = {"ymaxfactor": 1.4} opts = {} drawPlot(createPlot( treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), prefix + "selectedTauPt_4AfterDeltaPhi160", "#tau-jet p_{T} (GeV/c)", opts=opts, opts2={ "ymin": 0, "ymax": 3 }) drawPlot(createPlot( treeDraw.clone(varexp="met_p4.Pt() >>tmp(16,0,400)", selection=selection)), prefix + "MET_4AfterDeltaPhi160", "E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", opts=opts, opts2={ "ymin": 0, "ymax": 3 }) opts = { "TTJets": { "ymax": 28 }, "SingleTop": { "ymax": 4.5 }, "DYJetsToLL": { "ymax": 18 }, "Diboson": { "ymax": 1.2 }, "WJets": { "ymax": 50 }, }.get(datasetName, {}) opts2 = {"ymin": 0, "ymax": 2} if analysisEmb != "signalAnalysis": opts = { "EWKMC": { "ymax": 40 }, "TTJets": { "ymax": 12 }, #"WJets": {"ymax": 35}, "WJets": { "ymax": 25 }, "SingleTop": { "ymax": 2.2 }, "DYJetsToLL": { "ymax": 6.5 }, #"Diboson": {"ymax": 0.9}, "Diboson": { "ymax": 0.8 }, "W3Jets": { "ymax": 5 } }.get(datasetName, {}) opts2 = { "TTJets": { "ymin": 0, "ymax": 1.2 }, "Diboson": { "ymin": 0, "ymax": 3.2 }, }.get(datasetName, opts2) p = createPlot(tdMt.clone(selection=selection)) p.appendPlotObject( histograms.PlotText(0.6, 0.7, "#Delta#phi(#tau jet, E_{T}^{miss}) < 160^{o}", size=20)) drawPlot(p, prefix + "transverseMass_4AfterDeltaPhi160", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False)
def doPlots(datasetsEmb, datasetsSig, datasetName): lumi = datasetsEmb.getLuminosity() isCorrected = isinstance(datasetsEmb, tauEmbedding.DatasetsResidual) postfix = "_residual" createPlot = tauEmbedding.PlotCreatorMany(analysisEmb, analysisSig, datasetsEmb, datasetsSig, datasetName, plotStyles, addData=True) drawPlot = tauEmbedding.PlotDrawerTauEmbeddingEmbeddedNormal( ratio=True, log=True, addLuminosityText=True) def createDrawPlot(name, *args, **kwargs): p = createPlot(name) drawPlot(p, *args, **kwargs) prefix = "embdatasigmc" + postfix + "_" + datasetName + "_" opts2def = {"ymin": 0, "ymax": 2} def drawControlPlot(path, xlabel, rebin=None, opts2=None, **kwargs): opts2_ = opts2def if opts2 != None: opts2_ = opts2 cargs = {} if rebin != None: cargs["rebin"] = rebin drawPlot(createPlot("ControlPlots/" + path, **cargs), prefix + path, xlabel, opts2=opts2_, **kwargs) def update(d1, d2): tmp = {} tmp.update(d1) tmp.update(d2) return tmp # Control plots optsdef = {} opts = optsdef drawControlPlot("SelectedTau_pT_AfterStandardSelections", taujetH + " ^{}p_{T} (GeV/c)", opts=update(opts, {"xmax": 250}), rebin=2, cutBox={ "cutValue": 40, "greaterThan": 40 }) moveLegend = {"dy": -0.6, "dx": -0.2} opts = {"SingleTop": {"ymax": 1.8}}.get(datasetName, {"ymaxfactor": 1.4}) if datasetName != "TTJets": moveLegend = {"dx": -0.32} drawControlPlot("SelectedTau_eta_AfterStandardSelections", taujetH + " #eta", opts=update(opts, { "xmin": -2.2, "xmax": 2.2 }), ylabel="Events / %.1f", rebin=4, log=False, moveLegend=moveLegend) drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", taujetH + " ldg. charged particle ^{}p_{T} (GeV/c)", opts=update(opts, {"xmax": 300}), rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) opts = {"ymin": 1e-1, "ymaxfactor": 5} moveLegend = {"dx": -0.22} if datasetName == "Diboson": opts["ymin"] = 1e-2 drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/^{}p^{%s}" % taujet, opts=update(opts, { "xmin": 0.65, "xmax": 1.05 }), rebin=5, ylabel="Events / %.2f", moveLegend=moveLegend, cutBox={ "cutValue": 0.7, "greaterThan": True }) opts = optsdef drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") # After Njets drawControlPlot("MET", "Uncorrected PF ^{}E_{T}^{miss} (GeV)", rebin=5, opts=update(opts, {"xmax": 400}), cutLine=50, moveLegend={ "dx": -0.2, "dy": -0.55 }) # after MET moveLegend = { "WJets": {}, "DYJetsToLL": {}, "SingleTop": {}, "Diboson": {} }.get(datasetName, { "dx": -0.2, "dy": -0.5 }) drawControlPlot("NBjets", "Number of selected b jets", opts=update(opts, {"xmax": 6}), ylabel="Events", moveLegend=moveLegend, cutLine=1) # Tree cut definitions treeDraw = dataset.TreeDraw( "dummy", weight=tauEmbedding.signalNtuple.weightBTagging) tdMt = treeDraw.clone(varexp="%s >>tmp(15,0,300)" % tauEmbedding.signalNtuple.mtExpression) tdDeltaPhi = treeDraw.clone(varexp="%s >>tmp(18, 0, 180)" % tauEmbedding.signalNtuple.deltaPhiExpression) # DeltapPhi xlabel = "#Delta#phi(^{}%s, ^{}E_{T}^{miss}) (^{o})" % taujet def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) opts = { "WJets": { "ymax": 20 }, "DYJetsToLL": { "ymax": 5 }, "SingleTop": { "ymax": 2 }, "Diboson": { "ymax": 0.6 }, }.get(datasetName, {"ymaxfactor": 1.2}) opts2 = {"WJets": {"ymin": 0, "ymax": 3}}.get(datasetName, opts2def) selection = And(*[ getattr(tauEmbedding.signalNtuple, cut) for cut in ["metCut", "bTaggingCut"] ]) drawPlot(createPlot(tdDeltaPhi.clone(selection=selection)), prefix + "deltaPhi_3AfterBTagging", xlabel, log=False, opts=opts, opts2=opts2, ylabel="Events / ^{}%.0f^{o}", function=customDeltaPhi, moveLegend={"dx": -0.22}, cutLine=[130, 160]) # After all cuts selection = And(*[ getattr(tauEmbedding.signalNtuple, cut) for cut in ["metCut", "bTaggingCut", "deltaPhi160Cut"] ]) #opts = {"ymaxfactor": 1.4} opts = {} opts = { "EWKMC": { "ymax": 40 }, "TTJets": { "ymax": 12 }, #"WJets": {"ymax": 35}, "WJets": { "ymax": 25 }, "SingleTop": { "ymax": 2.2 }, "DYJetsToLL": { "ymax": 6.5 }, #"Diboson": {"ymax": 0.9}, "Diboson": { "ymax": 0.8 }, "W3Jets": { "ymax": 5 } }.get(datasetName, {}) opts2 = { "TTJets": { "ymin": 0, "ymax": 1.2 }, "Diboson": { "ymin": 0, "ymax": 3.2 }, }.get(datasetName, { "ymin": 0, "ymax": 2 }) p = createPlot(tdMt.clone(selection=selection)) histograms.cmsTextMode = histograms.CMSMode.PRELIMINARY p.appendPlotObject( histograms.PlotText(0.6, 0.7, "#Delta#phi(^{}%s, ^{}E_{T}^{miss}) < ^{}160^{o}" % taujet, size=20)) drawPlot(p, prefix + "transverseMass_4AfterDeltaPhi160", "m_{T}(^{}%s, ^{}E_{T}^{miss}) (GeV/^{}c^{2})" % taujet, opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/^{}c^{2}", log=False) histograms.cmsTextMode = histograms.CMSMode.NONE
def doPlotsWTauMu(datasetsEmb, name, btag=True): if btag: selection = And(metCut, bTaggingCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw( analysisEmb + "/tree", weight="weightPileup*weightTrigger*weightBTagging") else: selection = And(metCut, deltaPhi130Cut) treeDraw = dataset.TreeDraw(analysisEmb + "/tree", weight="weightPileup*weightTrigger") tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) (hall, tmp) = datasetsEmb.getHistogram(name, tdMt.clone(selection=selection)) (hpure, tmp) = datasetsEmb.getHistogram( name, tdMt.clone(selection=And(selection, "abs(temuon_mother_pdgid) == 24"))) tdEff = tdMt.clone(weight="", varexp=tdMt.varexp.replace("tmp", "tmpeff")) heff = datasetsEmb.getEfficiency( name, tdEff.clone( selection=And(selection, "abs(temuon_mother_pdgid) == 24")), tdEff.clone(selection=selection)) hall.SetName("All") hpure.SetName("Pure") nall = hall.Integral(0, hall.GetNbinsX()) npure = hpure.Integral(0, hall.GetNbinsX()) print { True: "Btagging", False: "NoBTag" }[btag], npure / nall, (1 - npure / nall) * 100 p = plots.ComparisonPlot(hall, hpure) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) if btag: fname = "transverseMass_4AfterDeltaPhi160_wtaumu_" + name else: fname = "transverseMass_4AfterDeltaPhi160NoBTag_wtaumu_" + name hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue - 7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed - 7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame(fname, createRatio=True, opts2={"ymin": 0.9, "ymax": 1.05}) styles.getDataStyle().apply(heff) p.setRatios([heff]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1 - 0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) p.appendPlotObjectToRatio( histograms.PlotText(0.65, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})") p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c^{2}" % p.binWidth()) p.appendPlotObject( histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18)) p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.save()
def doPlotsWTauMu(datasets, name): selection = And(muonSelection, muonVeto, electronVeto, jetSelection) td = treeDraw.clone(varexp="muons_p4.Pt() >> tmp(40,0,400)") ds = datasets.getDataset(name) # Take first unweighted histograms for the fraction plot drh_all = ds.getDatasetRootHisto(td.clone(selection=selection, weight="")) drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24"), weight="")) hallUn = drh_all.getHistogram() hpureUn = drh_pure.getHistogram() # Then the correctly weighted for the main plot drh_all = ds.getDatasetRootHisto(td.clone(selection=selection)) drh_pure = ds.getDatasetRootHisto(td.clone(selection=And(selection, "abs(muons_mother_pdgid) == 24"))) lumi = datasets.getDataset("Data").getLuminosity() drh_all.normalizeToLuminosity(lumi) drh_pure.normalizeToLuminosity(lumi) hall = drh_all.getHistogram() hpure = drh_pure.getHistogram() hall.SetName("All") hpure.SetName("Pure") p = plots.ComparisonPlot(hall, hpure) p.histoMgr.setHistoLegendLabelMany({ "All": "All muons", "Pure": "W#rightarrow#tau#rightarrow#mu" # "Pure": "W#rightarrow#mu" }) p.histoMgr.forEachHisto(styles.generator()) hallErr = hall.Clone("AllError") hallErr.SetFillColor(ROOT.kBlue-7) hallErr.SetFillStyle(3004) hallErr.SetMarkerSize(0) p.prependPlotObject(hallErr, "E2") hpureErr = hpure.Clone("PureErr") hpureErr.SetFillColor(ROOT.kRed-7) hpureErr.SetFillStyle(3005) hpureErr.SetMarkerSize(0) p.prependPlotObject(hpureErr, "E2") p.createFrame("muonPt_wtaumu_"+name, createRatio=True, opts={"ymin": 1e-1, "ymaxfactor": 2}, opts2={"ymin": 0.9, "ymax": 1.05} ) p.setRatios([plots._createRatio(hpureUn, hallUn, "", isBinomial=True)]) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() val = 1-0.038479 l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(4) p.prependPlotObjectToRatio(l) #p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "1-0.038", size=18, color=ROOT.kBlue)) p.appendPlotObjectToRatio(histograms.PlotText(0.18, 0.61, "0.038", size=18, color=ROOT.kBlue)) p.getFrame2().GetYaxis().SetTitle("W#rightarrow#mu fraction") p.getPad().SetLogy(True) p.setLegend(histograms.moveLegend(histograms.createLegend())) tmp = hpureErr.Clone("tmp") tmp.SetFillColor(ROOT.kBlack) tmp.SetFillStyle(3013) tmp.SetLineColor(ROOT.kWhite) p.legend.AddEntry(tmp, "Stat. unc.", "F") p.frame.GetXaxis().SetTitle("Muon p_{T} (GeV/c)") p.frame.GetYaxis().SetTitle("Events / %.0f GeV/c" % p.binWidth()) p.appendPlotObject(histograms.PlotText(0.5, 0.9, plots._legendLabels.get(name, name), size=18)) p.draw() histograms.addCmsPreliminaryText() histograms.addEnergyText() p.save()
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 doPlots(datasetsEmb, datasetsSig, datasetName): lumi = datasetsEmb.getLuminosity() createPlot = tauEmbedding.PlotCreatorMany(analysisEmb, analysisSig, datasetsEmb, datasetsSig, datasetName, styles.getStyles()) def drawPlot(plot, name, *args, **kwargs): drawPlotCommon(plot, "mcembsig_" + datasetName + "_" + name, *args, **kwargs) def createDrawPlot(name, *args, **kwargs): p = createPlot(name) drawPlot(plot, *args, **kwargs) opts2def = {"ymin": 0, "ymax": 2} def drawControlPlot(path, xlabel, rebin=None, opts2=None, **kwargs): opts2_ = opts2def if opts2 != None: opts_ = opts2 cargs = {} if rebin != None: cargs["rebin"] = rebin drawPlot(createPlot("ControlPlots/" + path, **cargs), path, xlabel, opts2=opts2_, **kwargs) def update(d1, d2): tmp = {} tmp.update(d1) tmp.update(d2) return tmp # Control plots optsdef = {} opts = optsdef moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts=update(opts, {"xmax": 250}), rebin=2, cutBox={ "cutValue": 40, "greaterThan": 40 }, moveLegend=moveLegend) opts = {"SingleTop": {"ymax": 1.8}}.get(datasetName, {"ymaxfactor": 1.4}) moveLegend = { "TTJets": { "dy": -0.6, "dx": -0.2 }, }.get(datasetName, {"dx": -0.32}) drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts=update(opts, { "xmin": -2.2, "xmax": 2.2 }), ylabel="Events / %.1f", rebin=4, log=False, moveLegend=moveLegend) moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts=update(opts, {"xmax": 300}), rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }, moveLegend=moveLegend) opts = {"ymin": 1e-1, "ymaxfactor": 5} if datasetName == "Diboson": opts["ymin"] = 1e-2 moveLegend = {"dx": -0.25} drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts=update(opts, { "xmin": 0.65, "xmax": 1.05 }), rebin=5, ylabel="Events / %.2f", moveLegend=moveLegend, cutBox={ "cutValue": 0.7, "greaterThan": True }) opts = optsdef moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events", moveLegend=moveLegend) # After Njets moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawControlPlot("MET", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=5, opts=update(opts, {"xmax": 400}), cutLine=50, moveLegend=moveLegend) # after MET moveLegend = {"dx": -0.23, "dy": -0.5} moveLegend = { "WJets": {}, "DYJetsToLL": { "dx": -0.02 }, "SingleTop": {}, "Diboson": {} }.get(datasetName, moveLegend) drawControlPlot("NBjets", "Number of selected b jets", opts=update(opts, {"xmax": 6}), ylabel="Events", moveLegend=moveLegend, cutLine=1) # After BTag xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})" def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) opts2 = opts2def opts = { # "WJets": {"ymax": 20}, # "DYJetsToLL": {"ymax": 5}, # "SingleTop": {"ymax": 2}, # "Diboson": {"ymax": 0.6}, }.get(datasetName, {"ymaxfactor": 1.2}) opts2 = { # "WJets": {"ymin": 0, "ymax": 3} }.get(datasetName, opts2def) moveLegend = {"DYJetsToLL": {"dx": -0.24}}.get(datasetName, {"dx": -0.22}) drawPlot(createPlot("deltaPhi", rebin=10), "deltaPhi_3AfterBTagging", xlabel, log=False, opts=opts, opts2=opts2, ylabel="Events / %.0f^{o}", function=customDeltaPhi, moveLegend=moveLegend, cutLine=[130, 160]) # After deltaPhi opts = { # "EWKMC": {"ymax": 40}, # "TTJets": {"ymax": 12}, # #"WJets": {"ymax": 35}, # "WJets": {"ymax": 25}, # "SingleTop": {"ymax": 2.2}, # "DYJetsToLL": {"ymax": 6.5}, # #"Diboson": {"ymax": 0.9}, # "Diboson": {"ymax": 0.8}, # "W3Jets": {"ymax": 5} }.get(datasetName, {}) opts2 = { # "TTJets": {"ymin": 0, "ymax": 1.2}, # "Diboson": {"ymin": 0, "ymax": 3.2}, }.get(datasetName, opts2) moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawPlot(createPlot("transverseMass", rebin=10), "transverseMass_4AfterDeltaPhi160", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False, moveLegend=moveLegend) return # Tree cut definitions treeDraw = dataset.TreeDraw( "dummy", weight=tauEmbedding.signalNtuple.weightBTagging) tdDeltaPhi = treeDraw.clone(varexp="%s >>tmp(18, 0, 180)" % tauEmbedding.signalNtuple.deltaPhiExpression) tdMt = treeDraw.clone(varexp="%s >>tmp(15,0,300)" % tauEmbedding.signalNtuple.mtExpression) # DeltapPhi xlabel = "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})" def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) opts2 = opts2def opts = { "WJets": { "ymax": 20 }, "DYJetsToLL": { "ymax": 5 }, "SingleTop": { "ymax": 2 }, "Diboson": { "ymax": 0.6 }, }.get(datasetName, {"ymaxfactor": 1.2}) opts2 = {"WJets": {"ymin": 0, "ymax": 3}}.get(datasetName, opts2def) moveLegend = {"DYJetsToLL": {"dx": -0.24}}.get(datasetName, {"dx": -0.22}) drawPlot(createPlot( tdDeltaPhi.clone( selection=And(tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut))), "deltaPhi_3AfterBTagging", xlabel, log=False, opts=opts, opts2=opts2, ylabel="Events / %.0f^{o}", function=customDeltaPhi, moveLegend=moveLegend, cutLine=[160]) # Transverse mass selection = And(*[ tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple. bTaggingCut, tauEmbedding.signalNtuple.deltaPhi160Cut ]) opts = { "EWKMC": { "ymax": 40 }, "TTJets": { "ymax": 12 }, #"WJets": {"ymax": 35}, "WJets": { "ymax": 25 }, "SingleTop": { "ymax": 2.2 }, "DYJetsToLL": { "ymax": 6.5 }, #"Diboson": {"ymax": 0.9}, "Diboson": { "ymax": 0.8 }, "W3Jets": { "ymax": 5 } }.get(datasetName, {}) opts2 = { "TTJets": { "ymin": 0, "ymax": 1.2 }, "Diboson": { "ymin": 0, "ymax": 3.2 }, }.get(datasetName, opts2) p = createPlot(tdMt.clone(selection=selection)) p.appendPlotObject( histograms.PlotText(0.6, 0.7, "#Delta#phi(#tau jet, E_{T}^{miss}) < 160^{o}", size=20)) moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {}) drawPlot(p, "transverseMass_4AfterDeltaPhi160", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False, moveLegend=moveLegend)
def doPlots(datasetsEmb): datasetNames = datasetsEmb.getAllDatasetNames() isCorrected = isinstance(datasetsEmb, result.DatasetsDYCorrection) def createPlot(name, dyx=0.67, dyy=0.64): name2 = name if isinstance(name, basestring): name2 = analysisEmb + "/" + name rootHistos = [] for datasetName in datasetNames: (histo, tmp) = datasetsEmb.getHistogram(datasetName, name2) histo.SetName(datasetName) rootHistos.append(histo) p = plots.DataMCPlot2(rootHistos) histos = p.histoMgr.getHistos() for h in histos: if h.getName() == "Data": h.setIsDataMC(True, False) else: h.setIsDataMC(False, True) p.setLuminosity(datasetsEmb.getLuminosity()) p.setDefaultStyles() if isCorrected: p.appendPlotObject( histograms.PlotText(dyx, dyy, "DY correction applied", size=15)) return p prefix = "embdatamc_" opts2 = {"ymin": 0, "ymax": 2} # Control plots def drawControlPlot(path, xlabel, **kwargs): drawPlot(createPlot("ControlPlots/" + path), prefix + path, xlabel, opts2=opts2, **kwargs) drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 40, "greaterThan": True }) drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts={ "xmin": -2.2, "xmax": 2.2 }, ylabel="Events / %.1f", rebin=4, moveLegend={ "dy": -0.52, "dx": -0.2 }) drawControlPlot("SelectedTau_phi_AfterStandardSelections", "#tau-jet #phi", rebin=10, ylabel="Events / %.2f") drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", opts={ "xmin": 0.65, "xmax": 1.05, "ymin": 1e-1, "ymaxfactor": 10 }, rebin=5, ylabel="Events / %.2f", moveLegend={ "dx": -0.4, "dy": 0.01, "dh": -0.03 }, cutBox={ "cutValue": 0.7, "greaterThan": True }) #drawControlPlot("SelectedTau_p_AfterStandardSelections", "#tau-jet p (GeV/c)", rebin=2) #drawControlPlot("SelectedTau_LeadingTrackP_AfterStandardSelections", "#tau-jet ldg. charged particle p (GeV/c)", rebin=2) #drawControlPlot("IdentifiedElectronPt_AfterStandardSelections", "Electron p_{T} (GeV/c)") #drawControlPlot("IdentifiedMuonPt_AfterStandardSelections", "Muon p_{T} (GeV/c)") #drawControlPlot("Njets_AfterStandardSelections", "Number of jets", ylabel="Events") drawControlPlot("MET", "Uncorrected PF E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50) # After MET drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", cutLine=1) treeDraw = dataset.TreeDraw(analysisEmb + "/tree", weight="weightPileup*weightTrigger") tdMet = treeDraw.clone(varexp="met_p4.Phi() >> tmp(16, -3.2, 3.2)") drawPlot(createPlot(tdMet.clone()), prefix + "METPhi_1AfterTauID", "\MET #phi", log=False, ylabel="Events / %.1f", opts={"ymaxfactor": 2}, opts2={ "ymin": 0, "ymax": 2 }) # After b-tagging treeDraw = treeDraw.clone( weight="weightPileup*weightTrigger*weightBTagging") tdMt = treeDraw.clone( varexp= "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi()))) >>tmp(20,0,400)" ) tdDeltaPhi = treeDraw.clone( varexp= "acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 >>tmp(18, 0, 180)" ) metCut = "(met_p4.Et() > 50)" bTaggingCut = "passedBTagging" deltaPhi160Cut = "(acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 <= 160)" deltaPhi130Cut = "(acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 <= 130)" # DeltapPhi def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) drawPlot(createPlot(tdDeltaPhi.clone(selection=And(metCut, bTaggingCut))), prefix + "deltaPhi_3AfterBTagging", "#Delta#phi(#tau jet, E_{T}^{miss}) (^{o})", log=False, opts={"ymax": 30}, opts2=opts2, ylabel="Events / %.0f^{o}", function=customDeltaPhi, moveLegend={"dx": -0.22}, cutLine=[130, 160]) # mT for name, label, selection in [ ("3AfterBTagging", "Without #Delta#phi(#tau jet, E_{T}^{miss}) cut", [metCut, bTaggingCut]), ("4AfterDeltaPhi160", "#Delta#phi(#tau jet, E_{T}^{miss}) < 160^{o}", [metCut, bTaggingCut, deltaPhi160Cut]), ("5AfterDeltaPhi130", "#Delta#phi(#tau jet, E_{T}^{miss}) < 130^{o}", [metCut, bTaggingCut, deltaPhi130Cut]) ]: p = createPlot(tdMt.clone(selection=And(*selection))) h = p.histoMgr.getHisto("Data").getRootHisto() s = "" for bin in xrange(1, h.GetNbinsX() + 1): val = h.GetBinContent(bin) err = h.GetBinError(bin) if val != 0: s += "%.2f " % (err / val * 100) else: s += "0 " print "%s rel. stat. unc. %s" % (name, s) p.appendPlotObject(histograms.PlotText(0.5, 0.62, label, size=20)) drawPlot(p, prefix + "transverseMass_" + name, "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts={"ymax": 32}, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False) return prefix = "avg10" if isCorrected: prefix += "_dycorrected" opts2 = {"ymin": 0, "ymax": 3} drawPlot(createPlot( treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), prefix + "_selectedTauPt_4AfterDeltaPhi160", "#tau-jet p_{T} (GeV/c)", opts2=opts2) drawPlot(createPlot( treeDraw.clone(varexp="met_p4.Pt() >>tmp(16,0,400)", selection=selection)), prefix + "_MET_4AfterDeltaPhi160", "E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", opts2=opts2) #opts = {"ymaxfactor": 1.2} opts = {"ymax": 40} p = createPlot(tdMt.clone(selection=selection)) addAN = False if addAN: mtAN = ROOT.TH1F("mt_AN", "mt_AN", 20, 0, 400) mtAN.SetDirectory(0) mtAN.SetBinContent(1, 27.70106) mtAN.SetBinContent(2, 15.93031) mtAN.SetBinContent(3, 11.06969) mtAN.SetBinContent(4, 4.613092) mtAN.SetBinContent(5, 5.13239) mtAN.SetBinContent(6, 3.998591) mtAN.SetBinContent(7, 1.497308) mtAN.SetBinContent(9, 0.7270167) mtAN.SetBinError(1, 5.035656) mtAN.SetBinError(2, 3.771818) mtAN.SetBinError(3, 3.058925) mtAN.SetBinError(4, 2.107709) mtAN.SetBinError(5, 2.15077) mtAN.SetBinError(6, 2.023928) mtAN.SetBinError(7, 1.090971) mtAN.SetBinError(9, 0.7270168) styles.mcStyle2.apply(mtAN) h = histograms.Histo(mtAN, "Data in AN v4", "p", "EP") h.setIsDataMC(False, False) p.histoMgr.insertHisto(1, h, legendIndex=1) p.setDataDatasetNames(["Data", h.getName()]) drawPlot(p, prefix + "_transverseMass_4AfterDeltaPhi160", "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})", opts=opts, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}", log=False)
def doPlots(table, onlyWjets, mcEvents, normalize, lumi): nrows = table.getNrows() function = ROOT.TF1("fitFunction", "[0]") function.SetParameter(0, 0) f2 = ROOT.TF1("fitG", "gaus") f2.SetLineColor(ROOT.kRed) f2.SetLineWidth(2) binning = { "Data": (8, 60, 100), "Diboson": (8, 0, 2), "DYJetsToLL": (8, 1, 5), "EWKMCsum": (8, 40, 120), "SingleTop": (8, 3, 6), "TTJets": (10, 25, 35), "W3Jets": (10, 6, 11), "WJets": (14, 10, 80), } if onlyWjets: binning["WJets"] = (24, 10, 90) if not normalize: binning["Data"] = (10, 70, 120) binning["EWKMCsum"] = (6, 60, 120) binning["SingleTop"] = (8, 4, 6) binning["TTJets"] = (10, 32, 42) binning["W3Jets"] = (12, 6, 12) if onlyWjets: binning["WJets"] = (10, 20, 60) if mcEvents: binning["TTJets"] = (12, 320, 440) binning["WJets"] = (24, 30, 90) for icol in xrange(table.getNcolumns()): name = table.getColumnNames()[icol] label = plots._legendLabels.get(name, name) if name != "Data": label += " simulation" h = ROOT.TH1F(name, name, nrows, 0, nrows) h2 = ROOT.TH1F(name+"_dist", name, *(binning.get(name, (10, 0, 100)))) mean = dataset.Count(0, 0) for irow in xrange(nrows): count = table.getCount(irow, icol) h.SetBinContent(irow+1, count.value()) h.SetBinError(irow+1, count.uncertainty()) h2.Fill(count.value()) mean.add(count) mean = dataset.Count(mean.value()/nrows, mean.uncertainty()/nrows) h.Fit("fitFunction") value = function.GetParameter(0) error = function.GetParError(0) # function.SetParameters(1., 40., 1.); # function.SetParLimits(0, 0.0, 1.0); # fitResult = graph.Fit(function, "NRSE+EX0"); # print "Fit status", fitResult.Status() # #fitResult.Print("V"); # #fitResult.GetCovarianceMatrix().Print(); # function.SetLineColor(graph.GetMarkerColor()); # function.SetLineWidth(2); function.Draw("same") ROOT.gPad.Update() stat = h.FindObject("stats") if stat: stat.SetX1NDC(0.2) stat.SetX2NDC(0.44) stat.SetY1NDC(0.2) stat.SetY2NDC(0.3) stat.SetTextColor(ROOT.kRed) stat.SetLineColor(ROOT.kRed) # return (function, fitResult) styles.dataStyle.apply(h) p = plots.PlotBase([h]) p.histoMgr.setHistoDrawStyle(name, "EP") p.createFrame("fluctuation_"+name, opts={"ymin": 0, "ymaxfactor": 1.2, "nbins": nrows}) p.frame.GetXaxis().SetTitle("Embedding trial number") ylabel = "Simulation" if name == "Data": ylabel = "Data" ylabel += " events" p.frame.GetYaxis().SetTitle(ylabel) step = 1 start = 0 if onlyWjets: start = 4 step = 5 for irow in xrange(start, nrows, step): p.frame.GetXaxis().SetBinLabel(irow+1, "%d"%(irow+1)) xmin = p.frame.GetXaxis().GetXmin() xmax = p.frame.GetXaxis().GetXmax() leg = histograms.moveLegend(histograms.createLegend(), dx=-0.07, dy=-0.6, dh=-0.15) leg.AddEntry(h, "Trial values", "P") def createLine(val, st=1, col=ROOT.kRed): l = ROOT.TLine(xmin, val, xmax, val) l.SetLineWidth(2) l.SetLineStyle(st) l.SetLineColor(col) return l fv = createLine(value) leg.AddEntry(fv, "Fitted value", "L") p.appendPlotObject(fv) # fe = createLine(value+error, ROOT.kDashed) # leg.AddEntry(fe, "Fit uncertainty", "L") # p.appendPlotObject(fe) # p.appendPlotObject(createLine(value-error, ROOT.kDashed)) v = createLine(mean.value(), col=ROOT.kBlue) leg.AddEntry(v, "Mean", "L") p.appendPlotObject(v) ve = createLine(mean.value()+mean.uncertainty(), st=ROOT.kDashed, col=ROOT.kBlue) leg.AddEntry(ve, "Mean uncertainty", "L") p.appendPlotObject(ve) p.appendPlotObject(createLine(mean.value()-mean.uncertainty(), st=ROOT.kDashed, col=ROOT.kBlue)) p.legend = leg p.appendPlotObject(histograms.PlotText(0.65, 0.33, label, size=20)) p.draw() if name != "Data": histograms.addCmsPreliminaryText(text="Simulation") histograms.addEnergyText() histograms.addLuminosityText(None, None, lumi) p.save() ############### f2.SetParameter(1, value) h2.Fit("fitG") # f2.Draw("same") ROOT.gPad.Update() stat = h2.FindObject("stats") if stat: stat.SetX1NDC(0.62) stat.SetX2NDC(0.9) stat.SetY1NDC(0.7) stat.SetY2NDC(0.85) stat.SetTextColor(ROOT.kRed) stat.SetLineColor(ROOT.kRed) styles.dataStyle.apply(h2) p = plots.PlotBase([h2]) p.histoMgr.setHistoDrawStyle(name+"_dist", "HIST") p.createFrame("fluctuation_"+name+"_dist", opts={"ymin": 0, "ymaxfactor": 1.4, "nbins": nrows}) p.frame.GetXaxis().SetTitle(ylabel) p.frame.GetYaxis().SetTitle("Occurrances") ymin = p.frame.GetYaxis().GetXmin() ymax = p.frame.GetYaxis().GetXmax() leg = histograms.moveLegend(histograms.createLegend(), dx=-0.07, dy=-0.25, dh=-0.15) leg.AddEntry(h2, "Trials", "F") leg.AddEntry(f2, "Gaussian fit", "L") def createLine2(val, st=1): l = ROOT.TLine(val, ymin, val, ymax) l.SetLineWidth(1) l.SetLineColor(ROOT.kBlue) l.SetLineStyle(st) return l p.appendPlotObject(h2, "FUNC") p.appendPlotObject(stat) p.appendPlotObject(histograms.PlotText(0.65, 0.88, label, size=20)) # fv = createLine2(value) # leg.AddEntry(fv, "Fit of values", "L") # p.appendPlotObject(fv) # fe = createLine2(value+error, ROOT.kDashed) # leg.AddEntry(fe, "Fit of values unc.", "L") # p.appendPlotObject(fe) # p.appendPlotObject(createLine2(value-error, ROOT.kDashed)) p.legend = leg p.draw() if name != "Data": histograms.addCmsPreliminaryText(text="Simulation") histograms.addEnergyText() histograms.addLuminosityText(None, None, lumi) p.save()
def doPlots(datasetsEmb): datasetNames = datasetsEmb.getAllDatasetNames() def createPlot(name): name2 = name if isinstance(name, basestring): name2 = analysisEmb + "/" + name rootHistos = [] for datasetName in datasetNames: (histo, tmp) = datasetsEmb.getHistogram(datasetName, name2) histo.SetName(datasetName) rootHistos.append(histo) p = plots.DataMCPlot2(rootHistos) histos = p.histoMgr.getHistos() for h in histos: if h.getName() == "Data": h.setIsDataMC(True, False) else: h.setIsDataMC(False, True) p.setLuminosity(datasetsEmb.getLuminosity()) p.setDefaultStyles() return p drawPlot = tauEmbedding.drawPlot drawPlot.setDefaults( ratio=True, addLuminosityText=True, ratioYlabel="Ratio", #normalize=False, ) prefix = "embdatamc_" opts2 = {"ymin": 0, "ymax": 2} def drawControlPlot(path, xlabel, **kwargs): postfix = "" if kwargs.get("log", True): postfix = "_log" drawPlot(createPlot("ControlPlots/" + path), prefix + path + postfix, xlabel, opts2=opts2, **kwargs) # After tau ID drawControlPlot("SelectedTau_pT_AfterStandardSelections", taujetH + " ^{}p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 40, "greaterThan": True }) drawControlPlot("SelectedTau_eta_AfterStandardSelections", taujetH + " #eta", opts={ "xmin": -2.2, "xmax": 2.2 }, ylabel="Events / %.1f", rebin=4, moveLegend={ "dy": -0.52, "dx": -0.2 }) drawControlPlot("SelectedTau_LeadingTrackPt_AfterStandardSelections", taujetH + " ldg. charged particle ^{}p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={ "cutValue": 20, "greaterThan": True }) drawControlPlot("SelectedTau_Rtau_AfterStandardSelections", "R_{#tau} = p^{ldg. charged particle}/^{}p^{%s}" % taujet, opts={ "xmin": 0.65, "xmax": 1.05, "ymin": 1e-1, "ymaxfactor": 10 }, rebin=5, ylabel="Events / %.2f", moveLegend={ "dx": -0.4, "dy": 0.01, "dh": -0.03 }, cutBox={ "cutValue": 0.7, "greaterThan": True }) drawControlPlot("MET", "Uncorrected PF ^{}E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50) # After MET cut drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", cutLine=1) # After b tagging treeDraw = dataset.TreeDraw( analysisEmb + "/tree", weight=tauEmbedding.signalNtuple.weightBTagging) tdMt = treeDraw.clone(varexp="%s >>tmp(15,0,300)" % tauEmbedding.signalNtuple.mtExpression) tdDeltaPhi = treeDraw.clone(varexp="%s >>tmp(18, 0, 180)" % tauEmbedding.signalNtuple.deltaPhiExpression) # DeltaPhi def customDeltaPhi(h): yaxis = h.getFrame().GetYaxis() yaxis.SetTitleOffset(0.8 * yaxis.GetTitleOffset()) drawPlot(createPlot( tdDeltaPhi.clone( selection=And(tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut))), prefix + "deltaPhi_3AfterBTagging", "#Delta#phi(^{}%s, ^{}E_{T}^{miss}) (^{o})" % taujet, log=False, opts={"ymax": 30}, opts2=opts2, ylabel="Events / ^{}%.0f^{o}", function=customDeltaPhi, moveLegend={"dx": -0.22}, cutLine=[130, 160]) # Transverse mass for name, label, selection in [ ("3AfterBTagging", "Without #Delta#phi(^{}%s, ^{}E_{T}^{miss}) selection" % taujet, [ tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut ]), ("4AfterDeltaPhi160", "#Delta#phi(^{}%s, ^{}E_{T}^{miss}) < ^{}160^{o}" % taujet, [ tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut, tauEmbedding.signalNtuple.deltaPhi160Cut ]), ("5AfterDeltaPhi130", "#Delta#phi(^{}%s, ^{}E_{T}^{miss}) < ^{}130^{o}" % taujet, [ tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.bTaggingCut, tauEmbedding.signalNtuple.deltaPhi130Cut ]) ]: p = createPlot(tdMt.clone(selection=And(*selection))) p.appendPlotObject(histograms.PlotText(0.42, 0.62, label, size=20)) if "DeltaPhi160": histograms.cmsTextMode = histograms.CMSMode.PRELIMINARY else: histograms.cmsTextMode = histograms.CMSMode.NONE drawPlot(p, prefix + "transverseMass_" + name, "m_{T}(^{}%s, ^{}E_{T}^{miss}) (GeV/^{}c^{2})" % taujet, opts={"ymax": 35}, opts2=opts2, ylabel="Events / %.0f GeV/^{}c^{2}", log=False)