コード例 #1
0
ファイル: plotMet.py プロジェクト: EricBAdamsUMDCP/cmssw-1
def compare(raw, type1, quantity, name):
    rawTh1 = raw.histoMgr.getHisto(name).getRootHisto().Clone("Raw")
    type1Th1 = type1.histoMgr.getHisto(name).getRootHisto().Clone("Type1")

    styles.dataStyle.apply(rawTh1)
    styles.mcStyle.apply(type1Th1)

    plot = plots.ComparisonPlot(
        histograms.Histo(rawTh1, "Raw"),
        histograms.Histo(type1Th1, "Type 1")
        )
    q = " "+quantity
    if quantity == "Et":
        q = ""

    plot.setLegend(histograms.moveLegend(histograms.createLegend(), dh=0.15))
    plot.createFrame("metres_%s_%s" % (name, quantity))
    plot.frame.GetXaxis().SetTitle("MET%s/genMET%s" % (q, q))
    plot.frame.GetYaxis().SetTitle("Events / %.2f" % raw.binWidth())
    plot.draw()
    l = ROOT.TLatex()
    l.SetNDC()
    x = 0.5
    y = 0.7
    dy = 0.05
    l.DrawLatex(x, y, name); y -= dy
    l.SetTextSize(l.GetTextSize()*0.7)
    l.SetTextColor(rawTh1.GetLineColor())
    l.DrawLatex(x, y, "Raw mean %.2f, stddev %.2f" % (rawTh1.GetMean(), rawTh1.GetRMS())); y -= dy
    l.SetTextColor(type1Th1.GetLineColor())
    l.DrawLatex(x, y, "Type 1 mean %.2f, stddev %.2f" % (type1Th1.GetMean(), type1Th1.GetRMS())); y -= dy

    plot.save()
コード例 #2
0
    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)
コード例 #3
0
    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)
コード例 #4
0
    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)
コード例 #5
0
    def createPlot(name):
        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)
        sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig)
        sig.normalizeToLuminosity(lumi)
        sig = sig.getHistogram()

        emb.SetName("Embedded")
        sig.SetName("Normal")

        p = plots.ComparisonPlot(emb, sig)
        p.histoMgr.forEachHisto(styles.generator())
        legLabel = plots._legendLabels.get(datasetName, datasetName)+" MC"
        p.histoMgr.setHistoLegendLabelMany({
                "Embedded": "Embedded "+legLabel,
                "Normal":   "Normal "+legLabel
                })

        return p
コード例 #6
0
    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)
コード例 #7
0
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()
コード例 #8
0
def plotTurnOnData(datasets,
                   name,
                   pathAll,
                   pathPassed1,
                   pathPassed2,
                   dataText1,
                   dataText2,
                   rebin=1,
                   ratio=False):
    dataLabel1 = "Data: " + dataText1
    dataLabel2 = "Data: " + dataText2

    dataset = datasets.getDataset("Data")
    all = dataset.getDatasetRootHisto(pathAll).getHistogram()
    passed1 = dataset.getDatasetRootHisto(pathPassed1).getHistogram()
    passed2 = dataset.getDatasetRootHisto(pathPassed2).getHistogram()

    data_eff_gr1 = ROOT.TGraphAsymmErrors(passed1, all,
                                          "cp")  # 0.683 cl is default
    data_eff_gr2 = ROOT.TGraphAsymmErrors(passed2, all,
                                          "cp")  # 0.683 cl is default

    p = plots.ComparisonPlot(
        histograms.HistoGraph(data_eff_gr1, "Data1", "p", "P"),
        histograms.HistoGraph(data_eff_gr2, "Data2", "p", "P"))
    p.histoMgr.forEachHisto(
        styles.generator2(styles.StyleMarker(markerSizes=[1.0, 2.0]),
                          [styles.dataStyle, styles.mcStyle2]))
    p.histoMgr.setHistoLegendLabelMany({
        "Data1": dataLabel1,
        "Data2": dataLabel2,
    })
    p.setLuminosity(dataset.getLuminosity())

    opts = {"ymin": 0.0, "ymax": 1.1}
    #opts2 = {"ymin": 0.5, "ymax": 1.5}
    opts2 = {"ymin": 0.8, "ymax": 1.2}

    name = "calomet_turnon_" + runs + "_data_" + name
    p.createFrame(name,
                  createRatio=ratio,
                  invertRatio=True,
                  opts=opts,
                  opts2=opts2)
    if ratio:
        p.getFrame2().GetYaxis().SetTitle("Ratio")

    p.setLegend(
        histograms.moveLegend(
            histograms.createLegend(y1=0.95, y2=0.85),
            #dx=-0.55, dy=-0.05
            dx=-0.44,
            dy=-0.58))

    common(p, "Uncorrected PF E_{T}^{miss} (GeV)", "Efficiency")
コード例 #9
0
    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"
コード例 #10
0
def plotClosure(mt_nom, mt_var, name, optMode):
    style = tdrstyle.TDRStyle()
    plot = plots.ComparisonPlot(mt_var, mt_nom)
    plot.createFrame(optMode.replace("Opt", "mT_Closure_" + name + "_"),
                     createRatio=True,
                     opts2={
                         "ymin": 0.7,
                         "ymax": 1.3
                     })  #0.73,1.27
    #plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True, opts2={"ymin": 0.73, "ymax": 1.27}, ratio = True, ratioType = "errorScale")
    plot.frame.GetXaxis().SetTitle("m_{T}(tau,MET), GeV")
    plot.frame.GetYaxis().SetTitle("#LT Events / bin #GT")
    moveLegend = {"dx": -0.3, "dy": 0.04}
    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegend))
    histograms.addStandardTexts()
    plot.draw()
    plot.save()
コード例 #11
0
def MetComparison(datasets):
    mt = plots.ComparisonPlot(*getHistos(datasets,"MetJetInHole","MetNoJetInHole"))
#    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("PE")

    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=1, log=True,
                   createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9},
                   ratio=True, opts2={"ymin": 0.5, "ymax": 50}, opts={"xmax": 200})
コード例 #12
0
    def createPlot(name):
        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 = datasetsEmb.getDataset(datasetName).getDatasetRootHisto(name2Emb)
        emb.setName("Embedded")
        sig = datasetsSig.getDataset(datasetName).getDatasetRootHisto(name2Sig)
        sig.setName("Normal")
        p = plots.ComparisonPlot(emb, sig)
        p.histoMgr.normalizeMCToLuminosity(lumi)
        p.histoMgr.setHistoLegendLabelMany({
                "Embedded": "Embedded "+plots._legendLabels[datasetName],
                "Normal":   "Normal "+plots._legendLabels[datasetName],
                })
        p.histoMgr.forEachHisto(styles.generator())

        return p
コード例 #13
0
    def __call__(self, name, rebin=1):
        drh1 = self.datasets.getDataset(self.datasetName).getDatasetRootHisto(
            self.ntupleCache.histogram(name + "_AfterTauID"))
        drh2 = self.datasets.getDataset(self.datasetName).getDatasetRootHisto(
            self.ntupleCache.histogram(name + "_AfterMuonIsolation"))

        h1_raw = drh1.getHistogram()
        h2_raw = drh2.getHistogram()

        drh1.normalizeToLuminosity(mcLuminosity)
        drh2.normalizeToLuminosity(mcLuminosity)

        h1 = drh1.getHistogram()
        h2 = drh2.getHistogram()
        if rebin > 1:
            h1_raw.Rebin(rebin)
            h2_raw.Rebin(rebin)
            h1.Rebin(rebin)
            h2.Rebin(rebin)

        h1.SetName("TauID")
        h2.SetName("TauIDMuIso")
        sty = self.styles[:]
        p = plots.ComparisonPlot(h1, h2)

        legLabel = plots._legendLabels.get(self.datasetName, self.datasetName)
        legLabel += " sim. "

        p.setLuminosity(mcLuminosity)
        p.histoMgr.setHistoLegendLabelMany({
            "TauID": "tau ID",
            "TauIDMuIso": "tau ID + mu iso"
        })
        p.histoMgr.forEachHisto(styles.Generator(sty))

        p.numeratorRaw = h2_raw
        p.denominatorRaw = h1_raw

        return p
コード例 #14
0
    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)
コード例 #15
0
    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)
コード例 #16
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    # As we use weighted counters for MC normalisation, we have to
    # update the all event count to a separately defined value because
    # the analysis job uses skimmed pattuple as an input
    datasets.updateNAllEventsToPUWeighted()

    # Read integrated luminosities of data datasets from lumi.json
    datasets.loadLuminosities()

    # Include only 120 mass bin of HW and HH datasets
    datasets.remove(
        filter(lambda name: "TTToHplus" in name and not "M120" in name,
               datasets.getAllDatasetNames()))

    # Default merging nad ordering of data and MC datasets
    # All data datasets to "Data"
    # All QCD datasets to "QCD"
    # All single top datasets to "SingleTop"
    # WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasets)

    # Set BR(t->H) to 0.2, keep BR(H->tau) in 1
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)

    # Merge WH and HH datasets to one (for each mass bin)
    # TTToHplusBWB_MXXX and TTToHplusBHminusB_MXXX to "TTToHplus_MXXX"
    plots.mergeWHandHH(datasets)

    # Merge EWK datasets
    datasets.merge("EWK",
                   ["WJets", "TTJets", "DYJetsToLL", "SingleTop", "Diboson"])

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Create the normalized plot of transverse mass
    # Read the histogram from the file
    #mT = plots.DataMCPlot(datasets, analysis+"/transverseMass")

    # Create the histogram from the tree (and see the selections explicitly)
    td = dataset.TreeDraw(
        analysis + "/tree",
        weight="weightPileup*weightTrigger*weightPrescale",
        selection="met_p4.Et() > 70 && Max$(jets_btag) > 1.7")
    #    mT = plots.DataMCPlot(datasets, td.clone(varexp="sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))>>dist(400, 0, 400)"))
    #    met = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.Et()>>dist(400, 0, 400)"))
    metBase = plots.DataMCPlot(datasets, analysis + "/MET_BaseLineTauIdJets")
    metInver = plots.DataMCPlot(datasets, analysis + "/MET_InvertedTauIdJets")

    metBase4050 = plots.DataMCPlot(datasets,
                                   analysis + "/MET_BaseLineTauIdJet4070")
    metInver4050 = plots.DataMCPlot(datasets,
                                    analysis + "/MET_InvertedTauIdJets4070")
    metBase5060 = plots.DataMCPlot(datasets,
                                   analysis + "/MET_BaseLineTauIdJets5060")
    metInver5060 = plots.DataMCPlot(datasets,
                                    analysis + "/MET_InvertedTauIdJets5060")
    metBase6070 = plots.DataMCPlot(datasets,
                                   analysis + "/MET_BaseLineTauIdJets6070")
    metInver6070 = plots.DataMCPlot(datasets,
                                    analysis + "/MET_InvertedTauIdJets6070")
    metBase7080 = plots.DataMCPlot(datasets,
                                   analysis + "/MET_BaseLineTauIdJets7080")
    metInver7080 = plots.DataMCPlot(datasets,
                                    analysis + "/MET_InvertedTauIdJets7080")
    metBase80100 = plots.DataMCPlot(datasets,
                                    analysis + "/MET_BaseLineTauIdJets80100")
    metInver80100 = plots.DataMCPlot(datasets,
                                     analysis + "/MET_InvertedTauIdJets80100")
    metBase100120 = plots.DataMCPlot(datasets,
                                     analysis + "/MET_BaseLineTauIdJets100120")
    metInver100120 = plots.DataMCPlot(
        datasets, analysis + "/MET_InvertedTauIdJets100120")
    metBase120150 = plots.DataMCPlot(datasets,
                                     analysis + "/MET_BaseLineTauIdJets120150")
    metInver120150 = plots.DataMCPlot(
        datasets, analysis + "/MET_InvertedTauIdJets120150")
    metBase150 = plots.DataMCPlot(datasets,
                                  analysis + "/MET_BaseLineTauIdJets150")
    metInver150 = plots.DataMCPlot(datasets,
                                   analysis + "/MET_InvertedTauIdJets150")

    #    metInver = plots.DataMCPlot(datasets, analysis+"/MET_InvertedTauIdLoose")

    # Rebin before subtracting
    metBase.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    metInver.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    metBase4050.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    metInver4050.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    metInverted_data = metInver.histoMgr.getHisto("Data").getRootHisto().Clone(
        analysis + "/MET_InvertedTauIdJets")
    metInverted_data4050 = metInver.histoMgr.getHisto(
        "Data").getRootHisto().Clone(analysis + "/MET_InvertedTauIdJets4050")
    print "print inverted met"
    print metInverted_data.GetEntries()

    # Create the data-EWK histogram and draw it
    diffBase = dataEwkDiff(metBase, "MET_base_data-ewk")
    #    diffInverted = dataEwkDiff(metInver,"MET_inverted_data-ewk")
    diffInverted = dataEwkNoDiff(metInver, "MET_inverted_data-ewk")

    diffBase4050 = dataEwkDiff(metBase, "MET_base_data-ewk-4050")
    #    diffInverted4070 = dataEwkDiff(metInver,"MET_inverted_data-ewk-4070")
    diffInverted4050 = dataEwkNoDiff(metInver, "MET_inverted_data-ewk-4050")

    # Draw the MET distribution
    transverseMass(metBase, "MET_base")
    transverseMass(metInver, "MET_inverted")
    # Draw the MET distribution
    transverseMass(metBase4050, "MET_base4050")
    transverseMass(metInver4050, "MET_inverted4050")

    # Set the styles
    dataset._normalizeToOne(diffBase)
    dataset._normalizeToOne(diffInverted)
    plot = plots.ComparisonPlot(histograms.Histo(diffBase, "Baseline"),
                                histograms.Histo(diffInverted, "Inverted"))

    dataset._normalizeToOne(diffBase4050)
    dataset._normalizeToOne(diffInverted4050)
    plot2 = plots.ComparisonPlot(
        histograms.Histo(diffBase4050, "Baseline4050"),
        histograms.Histo(diffInverted4050, "Inverted4050"))

    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    plot.histoMgr.forHisto("Baseline", st1)
    plot.histoMgr.forHisto("Inverted", st2)

    plot.createFrame(
        "METbaseVSinverted-ewk",
        opts={
            "xmax": 400,
            "ymin": 1e-5,
            "ymaxfactor": 1.5
        },
        createRatio=True,
        opts2={
            "ymin": -5,
            "ymax": 6
        },  # bounds of the ratio plot
    )

    plot.getPad().SetLogy(True)
    plot.setLegend(histograms.createLegend(0.7, 0.68, 0.9, 0.93))
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Data - EWK")

    # Draw the plot
    plot.draw()
    plot.save()

    plot2.createFrame(
        "METbaseVSinverted-ewk-4070",
        opts={
            "xmax": 400,
            "ymin": 1e-5,
            "ymaxfactor": 1.5
        },
        createRatio=True,
        opts2={
            "ymin": -5,
            "ymax": 6
        },  # bounds of the ratio plot
    )

    plot2.getPad().SetLogy(True)
    plot2.setLegend(histograms.createLegend(0.7, 0.68, 0.9, 0.93))
    plot2.frame.GetXaxis().SetTitle("MET (GeV)")
    plot2.frame.GetYaxis().SetTitle("Data - EWK")

    # Draw the plot
    plot2.draw()
    plot2.save()
コード例 #17
0
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)
コード例 #18
0
#drh_gen = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(analysis+"/FullHiggsMass/TrueHiggsMass")
#drh_gen = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(analysis+"/GenParticleAnalysis/genFullHiggsMass")

drh_correctId.normalizeToLuminosity(mcOnlyLumi)
drh_incorrectId.normalizeToLuminosity(mcOnlyLumi)

h_correctId = drh_correctId.getHistogram()  # returns TH1
h_incorrectId = drh_incorrectId.getHistogram()

#h_reco.SetName("Reco")
#h_gen.SetName("Gen")
h_correctId.SetName("#splitline{ID good}{#Delta R < 0.4}")
h_incorrectId.SetName("#splitline{ID bad}{#Delta R > 0.4}")

h = plots.ComparisonPlot(
    h_correctId,
    h_incorrectId)  # QUESTION: how does rebinning work in a comparison plot?
h.histoMgr.forEachHisto(styles.generator())

# Stack MC histograms
#h.stackMCHistograms()
#h.stackMCHistograms(stackSignal=True)

#h.addMCUncertainty()

# # Create canvas and frame for only the distributions
h.createFrame("Full_Higgs_mass")
h.frame.GetXaxis().SetTitle("m(b, #tau, #nu_{#tau}) (GeV)")
h.frame.GetYaxis().SetTitle("Events")

# # Create legend
コード例 #19
0
def distComparison(datasets):
    # Create a comparison plot of two distributions (must have the same binning)
    # Set the names of DatasetRootHisto objects in order to be able easily reference them later
    drh1 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/MET_BaseLineTauId")
    drh1.setName("Base")
    drh1.normalizeToOne()
    drh2 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/MET_InvertedTauId")
    drh2.setName("Inv")
    drh2.normalizeToOne()
    plot = plots.ComparisonPlot(drh1, drh2)

    # Set the styles
    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    plot.histoMgr.forHisto("Base", st1)
    plot.histoMgr.forHisto("Inv", st2)

    # Set the legend labels
    plot.histoMgr.setHistoLegendLabelMany({
        "Base": "Baseline Tau ID",
        "Inv": "Inverted Tau ID"
    })
    # Set the legend styles
    plot.histoMgr.setHistoLegendStyleAll("L")

    plot.histoMgr.setHistoLegendStyle("Base",
                                      "P")  # exception to the general rule

    # Set the drawing styles
    plot.histoMgr.setHistoDrawStyleAll("HIST")
    plot.histoMgr.setHistoDrawStyle("Base",
                                    "EP")  # exception to the general rule

    # Rebin, if necessary
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Create frame with a ratio pad
    plot.createFrame(
        "METbaseVSinvertedTauID",
        opts={
            "ymin": 1e-5,
            "ymaxfactor": 1.5
        },
        createRatio=True,
        opts2={
            "ymin": -10,
            "ymax": 50
        },  # bounds of the ratio plot
    )

    # Set Y axis of the upper pad to logarithmic
    plot.getPad1().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())

    # Set the X/Y axis labels
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")

    # Draw the plot
    plot.draw()

    # Add the various texts to
    plot.setLuminosity(datasets.getDataset("Data").getLuminosity())
    plot.addStandardTexts()

    # Save the plot to files
    plot.save()
コード例 #20
0
def distComparison(datasets):
    # Create a comparison plot of two distributions (must have the same binning)
    # Set the names of DatasetRootHisto objects in order to be able easily reference them later
    drh1 = datasets.getDataset("Data").getDatasetRootHisto(
        "ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections")
    drh1.setName("AfterStandardSelections")
    drh2 = datasets.getDataset("Data").getDatasetRootHisto(
        "ForDataDrivenCtrlPlots/SelectedTau_pT_AfterMtSelections")
    drh2.setName("AfterMtSelections")
    plot = plots.ComparisonPlot(drh1, drh2)

    # Set the styles
    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    plot.histoMgr.forHisto("AfterStandardSelections", st1)
    plot.histoMgr.forHisto("AfterMtSelections", st2)

    # Set the legend labels
    plot.histoMgr.setHistoLegendLabelMany({
        "AfterStandardSelections":
        "After standard selections",
        "AfterMtSelections":
        "After all selections"
    })
    # Set the legend styles
    plot.histoMgr.setHistoLegendStyleAll("L")
    #plot.histoMgr.setHistoLegendStyle("afterTauID", "P") # exception to the general rule

    # Set the drawing styles
    plot.histoMgr.setHistoDrawStyleAll("HIST")
    #plot.histoMgr.setHistoDrawStyleAll("afterTauID", "EP") # exception to the general rule

    # Rebin, if necessary
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))

    # Create frame with a ratio pad
    plot.createFrame(
        "tauPtComparison",
        opts={
            "ymin": 1e-1,
            "ymaxfactor": 10
        },
        createRatio=True,
        opts2={
            "ymin": 0,
            "ymax": 150
        },  # bounds of the ratio plot
    )

    # Set Y axis of the upper pad to logarithmic
    plot.getPad1().SetLogy(True)

    # Create legend to the default position
    plot.setLegend(histograms.createLegend())

    # Set the X/Y axis labels
    plot.frame.GetXaxis().SetTitle("Tau p_{T} (GeV/c)")
    plot.frame.GetYaxis().SetTitle("Number of events")

    # Draw the plot
    plot.draw()

    # Add the various texts to
    histograms.addStandardTexts(
        lumi=datasets.getDataset("Data").getLuminosity())

    # Save the plot to files
    plot.save()
コード例 #21
0
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)
コード例 #22
0
    def comparison(self, histo1, histo2, norm=1):

        h1 = histo1.Clone("h1")
        h2 = histo2.Clone("h2")
        if norm == 1:
            h1.Scale(1 / h1.GetMaximum())
            h2.Scale(1 / h2.GetMaximum())

        # check that no bin has negative value, negative values possible after subtracting EWK from data
        iBin = 1
        nBins = h1.GetNbinsX()
        while iBin < nBins:
            value1 = h1.GetBinContent(iBin)
            value2 = h2.GetBinContent(iBin)

            if value1 < 0:
                h1.SetBinContent(iBin, 0)

            if value2 < 0:
                h2.SetBinContent(iBin, 0)

            iBin = iBin + 1

        if norm > 0:
            h1.GetYaxis().SetTitle("Arbitrary units")

        plot = plots.ComparisonPlot(
            histograms.Histo(h1, "Inv"),
            histograms.Histo(h2, "Base"),
        )
        # Set the styles
        st1 = styles.getDataStyle().clone()
        st2 = st1.clone()
        st2.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Base", st1)
        plot.histoMgr.forHisto("Inv", st2)

        # Set the legend labels
        plot.histoMgr.setHistoLegendLabelMany({
            "Inv": h1.GetTitle(),
            "Base": h2.GetTitle()
        })
        # Set the legend styles
        plot.histoMgr.setHistoLegendStyleAll("P")

        # Set the drawing styles
        plot.histoMgr.setHistoDrawStyleAll("EP")

        # Create frame with a ratio pad
        plot.createFrame(
            "comparison" + self.label,
            opts={
                "ymin": 1e-5,
                "ymaxfactor": 2
            },
            createRatio=True,
            opts2={
                "ymin": 0,
                "ymax": 2
            },  # bounds of the ratio plot
        )

        # Set Y axis of the upper pad to logarithmic
        plot.getPad1().SetLogy(True)

        plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.draw()
        plot.save()
コード例 #23
0
    def cutefficiency(self, histo1, histo2):

        h1 = histo1.Clone("h1")
        h2 = histo2.Clone("h2")

        h1.Scale(1 / h1.GetMaximum())
        h2.Scale(1 / h2.GetMaximum())

        # check that no bin has negative value, negative values possible after subtracting EWK from data
        iBin = 1
        nBins = h1.GetNbinsX()
        while iBin < nBins:
            value1 = h1.GetBinContent(iBin)
            value2 = h2.GetBinContent(iBin)

            if value1 < 0:
                h1.SetBinContent(iBin, 0)

            if value2 < 0:
                h2.SetBinContent(iBin, 0)

            iBin = iBin + 1

        h1cut = h1.Clone("h1cut")
        h1cut.Reset()
        h1cut.GetYaxis().SetTitle("Efficiency")
        h1cut.GetXaxis().SetTitle("PF MET cut (GeV)")

        h2cut = h2.Clone("h2cut")
        h2cut.Reset()
        h2cut.SetLineColor(2)

        integralError = ROOT.Double(0.0)
        integralValue = h1.IntegralAndError(1, h1cut.GetNbinsX(),
                                            integralError)

        h1_integral = h1.Integral(0, h1.GetNbinsX())
        h2_integral = h2.Integral(0, h2.GetNbinsX())

        iBin = 1
        nBins = h1cut.GetNbinsX()
        while iBin < nBins:
            error = ROOT.Double(0.0)
            selected1 = h1.IntegralAndError(iBin, nBins, error)
            if selected1 > 0:
                error = error / selected1
            else:
                error = integralError / integralValue
            efficiency1 = selected1 / h1_integral
            h1cut.SetBinContent(iBin, efficiency1)
            if self.errorBars:
                h1cut.SetBinError(iBin, error)

            error = ROOT.Double(0.0)
            selected2 = h2.IntegralAndError(iBin, nBins, error)
            if selected2 > 0:
                error = error / selected2
            else:
                error = integralError / integralValue
            efficiency2 = selected2 / h2_integral
            h2cut.SetBinContent(iBin, efficiency2)
            if self.errorBars:
                h2cut.SetBinError(iBin, error)

            iBin = iBin + 1

        plot = plots.ComparisonPlot(
            histograms.Histo(h1cut, "Inv"),
            histograms.Histo(h2cut, "Base"),
        )
        # Set the styles
        st1 = styles.getDataStyle().clone()
        st2 = st1.clone()
        st2.append(styles.StyleLine(lineColor=ROOT.kRed))
        st2.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Base", st1)
        plot.histoMgr.forHisto("Inv", st2)

        # Set the legend labels
        plot.histoMgr.setHistoLegendLabelMany({
            "Inv": h1.GetTitle(),
            "Base": h2.GetTitle()
        })
        # Set the legend styles
        #plot.histoMgr.setHistoLegendStyleAll("L")
        plot.histoMgr.setHistoLegendStyleAll("P")

        # Set the drawing styles
        #plot.histoMgr.setHistoDrawStyleAll("HIST")
        plot.histoMgr.setHistoDrawStyleAll("EP")

        # Create frame with a ratio pad
        plot.createFrame(
            "cuteff" + self.label,
            opts={
                "ymin": 1e-5,
                "ymaxfactor": 2
            },
            createRatio=True,
            opts2={
                "ymin": 0,
                "ymax": 2
            },  # bounds of the ratio plot
        )

        # Set Y axis of the upper pad to logarithmic
        plot.getPad().SetLogy(True)

        plot.setLegend(histograms.createLegend(0.4, 0.82, 0.9, 0.93))

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        plot.draw()
        plot.save()

        ######

        hError = h1cut.Clone("hError")
        hError.Divide(h2cut)

        iBin = 1
        nBins = hError.GetNbinsX()
        while iBin < nBins:
            hError.SetBinContent(iBin, abs(hError.GetBinContent(iBin) - 1))
            iBin = iBin + 1

        hError.GetYaxis().SetTitle(
            "abs( (#varepsilon^{Inverted} - #varepsilon^{Baseline})/#varepsilon^{Baseline} )"
        )
        hError.GetXaxis().SetTitle("PF MET cut (GeV)")

        plot2 = plots.PlotBase()
        plot2.histoMgr.appendHisto(histograms.Histo(hError,
                                                    "ShapeUncertainty"))
        plot2.histoMgr.forHisto("ShapeUncertainty", st1)
        plot2.histoMgr.setHistoDrawStyleAll("EP")
        #        plot2.createFrame("shapeUncertainty"+self.label, opts={"ymin":-1, "ymax": 1})
        plot2.createFrame("shapeUncertainty" + self.label,
                          opts={
                              "ymin": -0.1,
                              "ymax": 1.1
                          })

        histograms.addCmsPreliminaryText()
        histograms.addEnergyText()
        histograms.addLuminosityText(x=None, y=None, lumi=self.lumi)

        rangeMin = hError.GetXaxis().GetXmin()
        rangeMax = hError.GetXaxis().GetXmax()
        #	rangeMax = 80
        rangeMax = 120
        #	rangeMax = 380

        numberOfParameters = 2

        class FitFunction:
            def __call__(self, x, par):
                #                return Linear(x,par)
                return ErrorFunction(x, par)

        theFit = TF1('theFit', FitFunction(), rangeMin, rangeMax,
                     numberOfParameters)
        theFit.SetParLimits(0, 0.01, 0.03)
        theFit.SetParLimits(1, 50, 150)

        #	theFit.FixParameter(0,0.02)
        #	theFit.FixParameter(1,100)

        hError.Fit(theFit, "LRN")
        print "Error MET > 40", theFit.Eval(40)
        print "Error MET > 50", theFit.Eval(50)
        print "Error MET > 70", theFit.Eval(70)

        plot2.histoMgr.appendHisto(histograms.Histo(theFit, "Fit"))

        plot2.draw()
        plot2.save()
コード例 #24
0
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()
コード例 #25
0
    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
コード例 #26
0
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)
コード例 #27
0
ファイル: plotQCDmet.py プロジェクト: sorda/HiggsAnalysis
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    datasets.remove([
        "WJets_TuneD6T_Winter10",
        "TTJets_TuneD6T_Winter10",
        "TTToHplusBWB_M140_Spring11",
        "TTToHplusBWB_M80_Spring11",
        "TTToHplusBWB_M90_Spring11",
        "TTToHplusBWB_M155_Spring11",
        "TTToHplusBWB_M150_Spring11",
        "TTToHplusBWB_M160_Spring11",
        "TTToHplusBWB_M100_Spring11",
        "TTToHplusBHminusB_M80_Spring11",
        "TTToHplusBHminusB_M100_Spring11",
        "TTToHplusBHminusB_M160_Spring11",
        "TTToHplusBHminusB_M150_Spring11",
        "TTToHplusBHminusB_M140_Spring11",
        "TTToHplusBHminusB_M155_Spring11",
        "TauPlusX_160431-161016_Prompt",
        "TauPlusX_162803-162828_Prompt",
        "QCD_Pt30to50_TuneZ2_Spring11",
        "QCD_Pt50to80_TuneZ2_Spring11",
        "QCD_Pt80to120_TuneZ2_Spring11",
        "QCD_Pt120to170_TuneZ2_Spring11",
        "QCD_Pt170to300_TuneZ2_Spring11",
        "QCD_Pt300to470_TuneZ2_Spring11",
        "HplusTB_M180_Summer11",
        "HplusTB_M190_Summer11",
        "HplusTB_M250_Summer11",
        "HplusTB_M300_Summer11",
        "HplusTB_M220_Summer11",
        "HplusTB_M200_Summer11",
        #                     "Tau_165970-166164_Prompt", "Tau_166374-167043_Prompt", "Tau_167078-167784_Prompt", "Tau_165088-165633_Prompt"
        #                     "Tau_163270-163869_May10","Tau_161217-163261_May10", "Tau_160431-161176_May10"
    ])

    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()

    # Take signals from 42X
    datasets.remove(
        filter(lambda name: "TTToHplus" in name and not "M120" in name,
               datasets.getAllDatasetNames()))
    #    datasetsSignal = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_2_4_patch1/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/multicrab_110621_150040/multicrab.cfg", counters=counters)
    #Rtau =0
    #    datasetsSignal = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_2_5/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/multicrab_110804_104313/multicrab.cfg", counters=counters)

    #    datasetsSignal.selectAndReorder(["HplusTB_M200_Summer11"])
    #    datasetsSignal = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_2_4_patch1/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/multicrab_110622_112321/multicrab.cfg", counters=counters)
    #datasetsSignal = dataset.getDatasetsFromMulticrabCfg(cfgfile="/home/rkinnune/signalAnalysis/CMSSW_4_1_5/src/HiggsAnalysis/HeavyChHiggsToTauNu/test/Signal_v11f_scaledb_424/multicrab.cfg", counters=counters)

    #datasetsSignal.selectAndReorder(["TTToHplusBWB_M120_Summer11", "TTToHplusBHminusB_M120_Summer11"])
    #datasetsSignal.renameMany({"TTToHplusBWB_M120_Summer11" :"TTToHplusBWB_M120_Spring11",
    #                           "TTToHplusBHminusB_M120_Summer11": "TTToHplusBHminusB_M120_Spring11"})
    #datasets.extend(datasetsSignal)

    plots.mergeRenameReorderForDataMC(datasets)

    # Set the signal cross sections to the ttbar
    #    xsect.setHplusCrossSectionsToTop(datasets)

    # Set the signal cross sections to a given BR(t->H), BR(h->taunu)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.2, br_Htaunu=1)

    # Set the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSectionsToMSSM(datasets, tanbeta=20, mu=200)

    plots.mergeWHandHH(
        datasets
    )  # merging of WH and HH signals must be done after setting the cross section

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Create the plot objects and pass them to the formatting
    # functions to be formatted, drawn and saved to files

    #    selectionFlow(plots.DataMCPlot(datasets, analysis+"/SignalSelectionFlow"), "SignalSelectionFlow")

    #   met(plots.DataMCPlot(datasets, analysis+"/TauEmbeddingAnalysis_afterTauId_embeddingMet"), ratio=True)
    #   met(plots.DataMCPlot(datasets, analysis+"/TauEmbeddingAnalysis_begin_embeddingMet"), ratio=True)

    #    met2(plots.DataMCPlot(datasets, analysis+"/Met_BeforeTauId"), "MetBeforeTauId", rebin=40)

    met2(plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetSelection"),
         "QCD_MET_AfterJetSelection",
         rebin=1)
    met2(plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetsBtagging"),
         "QCD_MET_AfterJetsBtagging",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging4050"),
         "QCD_MET_AfterJetsBtagging4050",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging5060"),
         "QCD_MET_AfterJetsBtagging5060",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging6070"),
         "QCD_MET_AfterJetsBtagging6070",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging7080"),
         "QCD_MET_AfterJetsBtagging7080",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging80100"),
         "QCD_MET_AfterJetsBtagging80100",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging100120"),
         "QCD_MET_AfterJetsBtagging100120",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging120150"),
         "QCD_MET_AfterJetsBtagging120150",
         rebin=1)
    met2(plots.DataMCPlot(datasets,
                          analysis + "/QCD_MET_AfterJetsBtagging150"),
         "QCD_MET_AfterJetsBtagging150",
         rebin=1)

    # Set temporarily the signal cross sections to a value from MSSM
    #    xsect.setHplusCrossSections(datasets, tanbeta=20, mu=200)
    #    datasets.getDataset("TTToHplusBHminusB_M120").setCrossSection(0.2*165)
    #    datasets.getDataset("TTToHplusBWB_M120").setCrossSection(0.2*165)

    ####################
    datasets_tm = datasets
    #    datasets_tm = datasets.deepCopy()
    #    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.2, br_Htaunu=1)
    #    xsect.setHplusCrossSectionsToBR(datasets_tm, br_tH=0.2, br_Htaunu=1)
    #    datasets_tm.merge("TTToHplus_M120", ["TTToHplusBWB_M120", "TTToHplusBHminusB_M120"])

    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterJetSelection"),
                    "QCD_TransverseMass_AfterJetSelection",
                    rebin=1)
    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterJetSelectionMetCut"),
                    "QCD_TransverseMass_AfterJetSelectionMetCut",
                    rebin=1)
    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterJetsBtagging"),
                    "QCD_TransverseMass_AfterJetsBtagging",
                    rebin=1)

    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterBigBox"),
                    "QCD_TransverseMass_AfterBigBox",
                    rebin=1)
    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterBigBoxAndMet"),
                    "QCD_TransverseMass_AfterBigBoxAndMet",
                    rebin=1)
    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterBigBoxAndBtag"),
                    "QCD_TransverseMass_AfterBigBoxAndBtag",
                    rebin=1)
    transverseMass2(plots.DataMCPlot(
        datasets, analysis + "/QCD_TransverseMass_AfterBigBoxAndTauID"),
                    "QCD_TransverseMass_AfterBigBoxAndTauID",
                    rebin=1)
    #    xsect.setHplusCrossSections(datasets, toTop=True)

    #    genComparison(datasets)
    #    zMassComparison(datasets)
    #    topMassComparison(datasets)
    #    topPtComparison(datasets)
    #    vertexComparison(datasets)

    eventCounter = counter.EventCounter(datasets)

    eventCounter.normalizeMCByLuminosity()
    #    eventCounter.normalizeMCToLuminosity(73)
    print "============================================================"
    print "Main counter (MC normalized by collision data luminosity)"
    print eventCounter.getMainCounterTable().format()

    #    print eventCounter.getSubCounterTable("GlobalMuon_ID").format()

    #    print eventCounter.getSubCounterTable("tauIDTauSelection").format()
    #    print eventCounter.getSubCounterTable("TauIDPassedEvt::tauID_HPSTight").format()
    #    print eventCounter.getSubCounterTable("TauIDPassedJets::tauID_HPSTight").format()
    print eventCounter.getSubCounterTable("b-tagging").format()
    print eventCounter.getSubCounterTable("Jet selection").format()
    print eventCounter.getSubCounterTable("Jet main").format()

    drh1 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/QCD_MET_AfterJetSelection")
    drh2 = datasets.getDataset("Data").getDatasetRootHisto(
        analysis + "/QCD_MET_AfterJetsBtagging7080")
    drh1.setName("Base")
    drh1.normalizeToOne()
    drh2.normalizeToOne()
    #    drh1.normalizeMCByLuminosity()
    plot = plots.ComparisonPlot(drh1, drh2)
    #    plot = plots.PlotBase(drh1)
    #    plot = plots.MCPlot(drh1)
    # Rebin, if necessary
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    #    drh1.normalizeMCByLuminosity()
    #    plot = plots.PlotBase(drh1)
    #    plot = plots.MCPlot(drh
    # Create frame with a ratio pad
    plot.createFrame("distribution", opts={"ymin": 1e-5, "ymaxfactor": 1.5})
    #                     createRatio=True, opts2={"ymin": -10, "ymax": 50}, # bounds of the ratio plot
    #                     )

    plot.draw()
    plot.save()

    mt = plots.DataMCPlot(datasets, analysis + "/QCD_MET_AfterJetSelection")
    mt.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(10))
    mt_data = mt.histoMgr.getHisto("Data").getRootHisto().Clone("mt_data")
コード例 #28
0
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)
コード例 #29
0
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()
コード例 #30
0
# TTJets
drh_reco = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(
    analysis + "/FullHiggsMass/HiggsMass")
drh_gen = datasets.getDataset("TTToHplusBWB_M120").getDatasetRootHisto(
    analysis + "/GenParticleAnalysis/genFullHiggsMass")

drh_reco.normalizeToLuminosity(mcOnlyLumi)
drh_gen.normalizeToLuminosity(mcOnlyLumi)

h_reco = drh_reco.getHistogram()  # returns TH1
h_gen = drh_gen.getHistogram()

h_reco.SetName("Reco")
h_gen.SetName("Gen")

h = plots.ComparisonPlot(h_reco, h_gen)
h.histoMgr.forEachHisto(styles.generator())

# Stack MC histograms
#h.stackMCHistograms()
#h.stackMCHistograms(stackSignal=True)

#h.addMCUncertainty()

# # Create canvas and frame for only the distributions
h.createFrame("Full_Higgs_mass")
# h.frame.GetXaxis().SetTitle("m_H (GeV)")
# h.frame.GetYaxis().SetTitle("events / ? GeV")

# # Create legend
h.setLegend(histograms.createLegend())