Beispiel #1
0
def doTreeScan(datasets, HistoList, MyCuts, SaveExtension):

    print "*** Warning! This TreeScan module is in testing phase."

    ### Define the event "weight" to be used
    EvtWeight = GetEventWeight(MyCuts)

    treePath = myAnalysis + "/tree"
    treeDraw = dataset.TreeDraw(treePath, weight=EvtWeight)

    f = open("treeEvents.txt", "w")

    def printTreeEvent(tree):
        expr = tree.event
        print "*** ", expr
        f.write("%d\n" % (expr))

    ts1 = dataset.TreeScan(treeDraw.tree,
                           function=printTreeEvent,
                           selection=And(BtagCut))
    ts2 = dataset.TreeScan(treeDraw.tree,
                           function=printTreeEvent,
                           selection=And(BtagCut, Met + ">=60"))
    ts3 = dataset.TreeScan(treeDraw.tree,
                           function=printTreeEvent,
                           selection=And(BtagCut, Met + ">=60",
                                         DeltaPhiLooseCuts))
    datasets.getDataset("Data").getDatasetRootHisto(ts1)
    f.close()

    return
Beispiel #2
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
#    datasets.loadLuminosities()
    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(datasets)

    style = tdrstyle.TDRStyle()
    td = dataset.TreeDraw(analysis+"/tree", weight="weightPileup*weightTrigger*weightPrescale", 
                          selection="genMet_p4.Et() > 20"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 1"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 2"
#                          selection="genMet_p4.Et() > 20 && [email protected]() >= 3"
                          )

    kwargs = {}
    kwargs["normalizeToLumi"] = 1150

    dist=">>dist(25,0,5)"
    for q in ["Et", "X", "Y", "Phi"]:
        rawRes = plots.DataMCPlot(datasets, td.clone(varexp="met_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        type1Res = plots.DataMCPlot(datasets, td.clone(varexp="metType1_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), **kwargs)
        #type1Res = plots.DataMCPlot(datasets, td.clone(varexp="tcMet_p4.%s()/genMet_p4.%s() %s" % (q, q, dist)), normalizeToLumi=1150)

        compare(rawRes, type1Res, q, "TTJets")
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 doPlots(datasets, histoDict, xLabelDict, yLabelDict, MyCuts,
            SaveExtension):
    ''' 
    def doPlots(datasets, histoDict, xLabelDict, yLabelDict,  MyCuts, SaveExtension):
    '''

    ### Create a progress bar to inform user of progress status
    maxValue = len(histoDict)
    print "\n*** Preparing %s histogram(s) for the cut group:\n    \"%s\"" % (
        maxValue, MyCuts)
    pBar = StartProgressBar(maxValue)

    drawPlot = plots.PlotDrawer(bStackHistos,
                                addMCUncertainty=bAddMCUncertainty,
                                log=bLogY,
                                ratio=bRatioPlot,
                                addLuminosityText=bAddLumiText,
                                ratioYlabel="Ratio",
                                opts={
                                    "ymin": yMin,
                                    "ymax": yMax
                                },
                                optsLog={
                                    "ymin": yMinLog,
                                    "ymax": yMaxLog
                                })

    ### Define the event "weight" to be used
    if "passedBTagging" in MyCuts:
        EvtWeight = "(weightPileup*weightTrigger*weightPrescale*weightBTagging)"
    else:
        EvtWeight = "weightPileup*weightTrigger*weightPrescale"

    print "*** And Event weight:\n    \"%s\"" % (EvtWeight)
    treeDraw = dataset.TreeDraw("tree", weight=EvtWeight)
    MyTreeDraw = treeDraw.clone(selection=MyCuts)

    ### Loop over all hName and expressions in the histogram dictionary "histoDict". Create & Draw plot
    counter = 0
    for key in histoDict:
        hName = key
        histo = MyTreeDraw.clone(varexp=histoDict[hName])
        fileName = "%s_%s" % (hName, SaveExtension)
        xLabel = xLabelDict[hName]
        yLabel = yLabelDict[hName]

        ### Go ahead and draw the plot
        p = createPlot(datasets, histo, normalizeToOne=bNormalizeToOne)
        drawPlot(p, fileName, rebin=1, xlabel=xLabel, ylabel=yLabel)

        ### Increment counter and pdate progress bar
        counter = counter + 1
        pBar.update(counter)

    ### Stop pbar once done with the loop
    pBar.finish()

    return
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()
Beispiel #6
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    # 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()))
    datasets.remove(filter(lambda name: "HplusTB" 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)"))

    # Rebin before subtracting
    mT.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(20))

    # Create the data-EWK histogram and draw it
    dataEwkDiff(mT)

    # Draw the mT distribution
    transverseMass(mT)
def doPlotsData(datasetsEmb):
    def createPlot(name):
        name2Emb = name

        if isinstance(name, basestring):
            name2Emb = analysisEmb + "/" + name
        else:
            name2Emb = name.clone(tree=analysisEmb + "/tree")

        (embData, embDataVar) = datasetsEmb.getHistogram("Data", name2Emb)
        embHistos = datasetsEmb.getHistograms("Data", name2Emb)

        p = plots.ComparisonManyPlot(embData, embHistos)
        p.setLuminosity(datasetsEmb.getLuminosity())

        p.histoMgr.forEachHisto(
            styles.Generator([styles.dataStyle] + styles.styles))
        #p.histoMgr.setHistoDrawStyleAll("P")
        #p.histoMgr.setHistoLegendStyleAll("P")
        p.histoMgr.setHistoDrawStyle("Average", "PE")
        p.histoMgr.setHistoLegendStyle("Average", "P")

        return p

    treeDraw = dataset.TreeDraw("dummy", weight=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)"
    )

    # After all cuts
    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)"
    selection = "&&".join([metCut, bTaggingCut, deltaPhi160Cut])
    prefix = "mcembsig_data"

    #    drawPlot(createPlot(treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), prefix+"_selectedTauPt_4AfterDeltaPhi160", "#tau-jet p_{T} (GeV/c)", 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", opts2={"ymin": 0, "ymax": 3})
    drawPlotData(createPlot(tdMt.clone(selection=selection)),
                 prefix + "_transverseMass_4AfterDeltaPhi160",
                 "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})",
                 opts2={
                     "ymin": 0,
                     "ymax": 3
                 },
                 ylabel="Events / %.0f GeV/c^{2}",
                 log=False)
Beispiel #8
0
import sys
import copy
import re

import HiggsAnalysis.HeavyChHiggsToTauNu.tools.dataset as dataset
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.counter as counter
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.crosssection as xsect

analysis = "signalAnalysis"
counters = analysis + "Counters"

treeDraw = dataset.TreeDraw(analysis + "/tree", weight="weightPileup")


def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()
    datasets.loadLuminosities()

    plots.mergeRenameReorderForDataMC(datasets)
    print "Int.Lumi", datasets.getDataset("Data").getLuminosity()
    #    datasets.remove(filter(lambda name: "TTToHplus" in name and not "M120" in name, datasets.getAllDatasetNames()))
    #    datasets.remove(filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    style = tdrstyle.TDRStyle()

    plot(datasets)
Beispiel #9
0
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
Beispiel #10
0
def doTH2Plots(datasets, histoDict, xLabelDict, yLabelDict,  MyCuts, SaveExtension):
    ''' 
    def doTH2Plots(datasets, histoDict, xLabelDict, yLabelDict,  MyCuts, SaveExtension):
    '''
    if McTypesPresent>1:
        print "*** WARNING: More than one MC-type histo found present (McTypesPresent=%s). This is not allowed for a TH2. Aboring plotting of TH2." %(McTypesPresent)
        return

    if bMcOnly==False:
        print "*** NOTE: bMcOnly is set to %s. Disabling all MC samples for the TH2 plots. Only \"Data\" is available." % (bMcOnly)
        bMergeEwk     = True
        bRemoveSignal = True
        bRemoveEwk    = True
        bRemoveQcd    = True

    ### Create a progress bar to inform user of progress status. Calculate the number of TH1 histos only
    maxValue = 0
    for key in histoDict:
        if not "_Vs_" in key:
            continue
        else:
            maxValue += 1
    if maxValue==0:
        print "*** NOTE! No TH2 histos to plot. Exiting doTH2Plots() module."
        return
    print "\n*** Preparing %s TH2 histogram(s) for the cut group:\n    \"%s\"" % (maxValue, MyCuts)
    pBar = StartProgressBar(maxValue)

    if bCustomRange:
        drawPlot = plots.PlotDrawer(stackMCHistograms=False, addMCUncertainty=bAddMCUncertainty, log=false, ratio=False, addLuminosityText=bAddLumiText, ratioYlabel="Ratio", opts={"ymin": yMin, "ymax": yMax}, optsLog={"ymin": yMinLog, "ymax": yMaxLog})
    else:
        drawPlot = plots.PlotDrawer(stackMCHistograms=False, addMCUncertainty=bAddMCUncertainty, log=False, ratio=False, addLuminosityText=bAddLumiText, ratioYlabel="Ratio")

    ### Define the event "weight" to be used
    if "passedBTagging" in MyCuts:
        #EvtWeight = "(weightPileup*weightTrigger*weightPrescale*weightBTagging)"
        EvtWeight = "(weightPileup*weightTauTrigger*weightPrescale*weightBTagging)"
    else:
        #EvtWeight = "weightPileup*weightTrigger*weightPrescale"
        EvtWeight = "weightPileup*weightTauTrigger*weightPrescale"
        
    print "*** And Event weight:\n    \"%s\"" % (EvtWeight)
    treeDraw = dataset.TreeDraw("tree", weight=EvtWeight)
    MyTreeDraw = treeDraw.clone(selection=MyCuts)
    
    ### Loop over all hName and expressions in the histogram dictionary "histoDict". Create & Draw plot
    counter=0        
    for key in histoDict:
        if not "_Vs_" in key:
            continue
        else:
            hName = key
            histo = MyTreeDraw.clone(varexp=histoDict[hName])
            fileName = "%s_%s" % (hName, SaveExtension)
            xLabel = xLabelDict[hName]
            yLabel = yLabelDict[hName]
            
        ### Go ahead and draw the plot
        p = createTH2Plot(datasets, histo, normalizeToOne = bNormalizeToOne)
        drawPlot(p, fileName, rebin=1, xlabel=xLabel, ylabel=yLabel)
        
        ### Increment counter and pdate progress bar
        counter = counter+1
        pBar.update(counter)
        
    ### Stop pbar once done with the loop
    pBar.finish()    

    return
metSelection = "(pfMet_p4.Pt() > 50)"
jetSelection = "(jets_looseId && jets_p4.Pt() > 30 && abs(jets_p4.Eta()) < 2.4 && sqrt((jets_p4.Eta()-taus_p4[0].Eta())^2+(jets_p4.Phi()-taus_p4[0].Phi())^2) > 0.5)"
jetEventSelection = "(Sum$(%s) >= 3)" % jetSelection
btagSelection = "(jets_f_tche > 1.7)"
btagEventSelection = "(Sum$(%s && %s) >= 1)" % (jetSelection, btagSelection)
deltaPhi160Selection = "(acos( (taus_p4.Px()*pfMet_p4.Px()+taus_p4.Py()*pfMet_p4.Py())/(taus_p4.Pt()*pfMet_p4.Et()) )*57.3 <= 160)"

caloMetNoHF = "(tecalometNoHF_p4.Pt() > 60)"
caloMet = "(tecalomet_p4.Pt() > 60)"

weight = "weightPileup_Run2011A"
if era == "EPS":
    weight = "pileupWeightEPS"
elif era == "Run2011A-EPS":
    weight = "pileupWeight_Run2011AnoEPS"
treeDraw = dataset.TreeDraw(analysis + "/tree", weight=weight)

tauEmbedding.normalize = True
tauEmbedding.era = era


def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    if era == "EPS":
        datasets.remove([
            "SingleMu_Mu_170722-172619_Aug05",
            "SingleMu_Mu_172620-173198_Prompt",
            "SingleMu_Mu_173236-173692_Prompt",
        ])
    elif era == "Run2011A-EPS":
def doCounters(datasetsEmb, datasetsSig, datasetName, normalizeEmb=True):
    lumi = datasetsEmb.getLuminosity()

    # Counters
    eventCounterEmb = tauEmbedding.EventCounterMany(
        datasetsEmb,
        normalize=normalizeEmb)  #, counters=analysisEmb+"/counters")
    eventCounterSig = counter.EventCounter(datasetsSig)

    def isNotThis(name):
        return name != datasetName

    eventCounterEmb.removeColumns(
        filter(isNotThis, datasetsEmb.getAllDatasetNames()))
    eventCounterSig.removeColumns(
        filter(isNotThis, datasetsSig.getAllDatasetNames()))
    eventCounterSig.normalizeMCToLuminosity(lumi)

    tdCount = dataset.TreeDraw("dummy",
                               weight=tauEmbedding.signalNtuple.weightBTagging)
    tdCountMET = tdCount.clone(weight=tauEmbedding.signalNtuple.weight,
                               selection=tauEmbedding.signalNtuple.metCut)
    tdCountBTagging = tdCount.clone(
        selection=And(tauEmbedding.signalNtuple.metCut,
                      tauEmbedding.signalNtuple.bTaggingCut))
    tdCountDeltaPhi160 = tdCount.clone(selection=And(
        tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.
        bTaggingCut, tauEmbedding.signalNtuple.deltaPhi160Cut))
    tdCountDeltaPhi130 = tdCount.clone(selection=And(
        tauEmbedding.signalNtuple.metCut, tauEmbedding.signalNtuple.
        bTaggingCut, tauEmbedding.signalNtuple.deltaPhi130Cut))

    def addRow(name, td):
        tdEmb = td.clone(tree=analysisEmb + "/tree")
        tdSig = td.clone(tree=analysisSig + "/tree")
        eventCounterEmb.mainCounterAppendRow(name, tdEmb)
        eventCounterSig.getMainCounter().appendRow(name, tdSig)

    # addRow("JetsForEffs", tdCount.clone(weight=tauEmbedding.signalNtuple.weight))
    # addRow("METForEffs", tdCountMET)
    # addRow("BTagging (SF)", tdCountBTagging)
    # addRow("DeltaPhi < 160", tdCountDeltaPhi160)
    # addRow("BTagging (SF) again", tdCountBTagging)
    # addRow("DeltaPhi < 130", tdCountDeltaPhi130)

    table = counter.CounterTable()
    col = eventCounterEmb.getMainCounterTable().getColumn(name=datasetName)
    col.setName("Embedded")
    table.appendColumn(col)
    col = eventCounterSig.getMainCounterTable().getColumn(name=datasetName)
    col.setName("Normal")
    table.appendColumn(col)

    tableTau = counter.CounterTable()
    tmp = "TauIDPassedEvt::TauSelection_HPS"
    col = eventCounterEmb.getSubCounterTable(tmp).getColumn(name=datasetName)
    col.setName("Embedded")
    tableTau.appendColumn(col)
    col = eventCounterSig.getSubCounterTable(tmp).getColumn(name=datasetName)
    col.setName("Normal")
    tableTau.appendColumn(col)

    postfix = ""
    if not normalizeEmb:
        postfix = "_notEmbNormalized"

    fname = "counters_selections_%s%s.txt" % (datasetName, postfix)
    f = open(fname, "w")
    f.write(table.format())
    f.write("\n")
    f.write(tableTau.format())
    f.close()
    print "Printed selection counters to", fname

    if not normalizeEmb:
        return

    # Calculate efficiencies
    table.keepOnlyRows([
        "njets", "MET", "btagging", "btagging scale factor",
        "DeltaPhi(Tau,MET) upper limit"
    ])
    # btag SF efficiency w.r.t. MET
    row = table.getRow(name="MET")
    row.setName("METForEff")
    table.insertRow(3, row)

    tableEff = counter.CounterTable()
    tableEff.appendColumn(
        counter.efficiencyColumn("Embedded eff",
                                 table.getColumn(name="Embedded")))
    tableEff.appendColumn(
        counter.efficiencyColumn("Normal eff", table.getColumn(name="Normal")))
    tableEff.removeRow(name="METForEff")

    effFormat = counter.TableFormatText(
        counter.CellFormatTeX(valueFormat='%.4f', withPrecision=2))

    #    print table.format(effFormat)

    fname = "counters_selections_%s_eff.txt" % datasetName
    f = open(fname, "w")
    f.write(tableEff.format(effFormat))
    f.close()
    print "Printed selection efficiencies to", fname
Beispiel #13
0
def doCounters(datasets, MyCuts, MyCutsName):

    ### Define the counters to be used
    #eventCounter = counter.EventCounter(datasets, counters=myAnalysis + myDataEra + "/counters")
    eventCounter = counter.EventCounter(datasets)

    ### Normalise the MC sample to a luminosity before creating a table
    eventCounter.normalizeMCToLuminosity(GetLumi(datasets))

    myRowNames = []
    for iCut, iCutName in zip(MyCuts, MyCutsName):
        #print "*** Cut: %s\n*** CutName: %s" % (iCut, iCutName)
        print "*** Processing TCut with:\n    Name = \"%s\" \n    Expr = \"%s\"" % (
            iCutName, iCut)

        ### Define the event "weight" to be used
        EvtWeight = GetEventWeight(iCut)

        ### Define the TTree to be used
        treePath = "tree"  # treePath = myAnalysis+"/tree"
        treeDraw = dataset.TreeDraw(treePath, weight=EvtWeight, selection=iCut)

        ### Append custom rows to the event counter. An asterisk denotes that the counter row was added. Informative and makes things easier
        myRowName = iCutName  #"*" + iCutName
        myRowNames.append(myRowName)
        eventCounter.getMainCounter().appendRow(myRowName, treeDraw)

    ### Get table with all default rows removed and manage the table format
    myTable = GetCustomTable(eventCounter, myRowNames)

    if getBool("bMergeEwk"):
        DataMinusEwkMc = counter.subtractColumn(
            "DataMinusEwkMc", myTable.getColumn(name="Data"),
            myTable.getColumn(name="EWK MC"))
        QcdPurity = counter.divideColumn("QCD Purity", DataMinusEwkMc,
                                         myTable.getColumn(name="Data"))
        myTable.appendColumn(QcdPurity)

    ### See http://docs.python.org/2/library/string.html for string format
    cellTextFormat = counter.TableFormatText(
        counter.CellFormatTeX(valueFormat='%.2E', valueOnly=True))  #%.2e
    cellLaTeXFormat = counter.TableFormatLaTeX(
        counter.CellFormatTeX(valueFormat='%.2E', valueOnly=True))  #%.2e
    purityFormat = counter.CellFormatTeX(valueFormat='%.2f', valueOnly=True)

    ### Customise the "QCD Purity" column
    cellTextFormat.setColumnFormat(purityFormat,
                                   name="QCD Purity")  #does nothing
    cellLaTeXFormat.setColumnFormat(purityFormat,
                                    name="QCD Purity")  #does nothing

    # between construction of table format and table format

    ### Print the final table with the desired format
    print "============================================================"
    print "Data-Era: %s (%s pb-1)" % (myDataEra, GetLumi(datasets))
    print "============================================================"
    print myTable.format(cellTextFormat)

    print "============================================================"
    print "Data-Era: %s (%s pb-1)" % (myDataEra, GetLumi(datasets))
    print "============================================================"
    print myTable.format(cellLaTeXFormat)

    return
Beispiel #14
0
def main():
    # Create all datasets from a multicrab task
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    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)"))
    met5060 = plots.DataMCPlot(datasets,
                               analysis + "/QCD_MET_AfterJetsBtagging5060")
    met6070 = plots.DataMCPlot(datasets,
                               analysis + "/QCD_MET_AfterJetsBtagging6070")
    met7080 = plots.DataMCPlot(datasets,
                               analysis + "/QCD_MET_AfterJetsBtagging7080")
    met80100 = plots.DataMCPlot(datasets,
                                analysis + "/QCD_MET_AfterJetsBtagging80100")
    met100120 = plots.DataMCPlot(datasets,
                                 analysis + "/QCD_MET_AfterJetsBtagging100120")
    met120150 = plots.DataMCPlot(datasets,
                                 analysis + "/QCD_MET_AfterJetsBtagging120150")
    met150 = plots.DataMCPlot(datasets,
                              analysis + "/QCD_MET_AfterJetsBtagging150")

    # Rebin before subtracting
    met5060.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met6070.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met7080.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met80100.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met100120.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met120150.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))
    met150.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(1))

    data5060 = met5060.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    data6070 = met6070.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    data7080 = met7080.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    data80100 = met80100.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    data100120 = met100120.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Data")
    data120150 = met120150.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Data")
    data150 = met150.histoMgr.getHisto("Data").getRootHisto().Clone("Data")

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

    # Draw the MET distribution
    #    transverseMass(metBase,"MET_base")
    #    transverseMass(metInver,"MET_inverted")

    # Set the styles
    #    dataset._normalizeToOne(diffBase)
    #    dataset._normalizeToOne(diffInverted)
    plot = plots.PlotBase()
    plot.histoMgr.appendHisto(
        histograms.Histo(data5060, "50 < p_{T}^{#tau jet} < 60 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data6070, "60 < p_{T}^{#tau jet} < 70 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data7080, "70 < p_{T}^{#tau jet} < 80 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data80100, "80 < p_{T}^{#tau jet} < 100 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data100120, "100 < p_{T}^{#tau jet} < 120 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data120150, "120 < p_{T}^{#tau jet} < 150 GeV"))
    plot.histoMgr.appendHisto(
        histograms.Histo(data150, "p_{T}^{#tau jet} > 150 GeV"))

    st1 = styles.getDataStyle().clone()
    st2 = st1.clone()
    st2.append(styles.StyleLine(lineColor=ROOT.kRed))
    st3 = st1.clone()
    st3.append(styles.StyleLine(lineColor=ROOT.kBlue))
    st4 = st1.clone()
    st4.append(styles.StyleLine(lineColor=ROOT.kGreen))
    st5 = st1.clone()
    st5.append(styles.StyleLine(lineColor=ROOT.kMagenta, lineStyle=2))
    st6 = st1.clone()
    st6.append(styles.StyleLine(lineColor=ROOT.kPink,
                                lineStyle=8))  # lineWidth=6))
    st7 = st1.clone()
    st7.append(styles.StyleLine(lineColor=ROOT.kBlue - 2, lineStyle=3))

    plot.histoMgr.forHisto("50 < p_{T}^{#tau jet} < 60 GeV", st1)
    plot.histoMgr.forHisto("60 < p_{T}^{#tau jet} < 70 GeV", st2)
    plot.histoMgr.forHisto("70 < p_{T}^{#tau jet} < 80 GeV", st3)
    plot.histoMgr.forHisto("80 < p_{T}^{#tau jet} < 100 GeV", st4)
    plot.histoMgr.forHisto("100 < p_{T}^{#tau jet} < 120 GeV", st5)
    plot.histoMgr.forHisto("120 < p_{T}^{#tau jet} < 150 GeV", st6)
    plot.histoMgr.forHisto("p_{T}^{#tau jet} > 150 GeV", st7)

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

    plot.getPad().SetLogy(True)
    plot.setLegend(histograms.createLegend(0.6, 0.68, 0.8, 0.93))
    plot.frame.GetXaxis().SetTitle("MET (GeV)")
    plot.frame.GetYaxis().SetTitle("Data")

    # Draw the plot
    plot.draw()
    plot.save()
def process(datasets, datasetName, postfix, countName):
    # Handle counter
    eventCounter = counter.EventCounter(datasets)
    mainTable = eventCounter.getMainCounterTable()

    neventsCount = mainTable.getCount(rowName=countName, colName=datasetName)
    nevents = neventsCount.value()
#    column = eventCounter.getSubCounterTable("Classification"+postfix).getColumn(name=datasetName)
#
#    columnFraction = column.clone()
#    columnFraction.setName("Fraction (%)")
#
#    # Consistency check, and do the division
#    tmp = 0
#    for irow in xrange(column.getNrows()):
#        tmp += column.getCount(irow).value()
#
#        frac = dataset.divideBinomial(columnFraction.getCount(irow), neventsCount)
#        frac.multiply(dataset.Count(100))
#        columnFraction.setCount(irow, frac)
#
#    if int(nevents) != int(tmp):
#        raise Exception("Consistency check failed: nevents = %d, tmp = %d" % (int(nevents), int(tmp)))
#
    table = counter.CounterTable()
#    table.appendColumn(column)
#    table.appendColumn(columnFraction)
#
    cellFormat = counter.CellFormatText(valueFormat='%.4f', withPrecision=2)
    tableFormat = counter.TableFormatText(cellFormat)

    print
    print "Dataset %s, step %s, nevents %d" % (datasetName, postfix, int(nevents))
    print table.format(tableFormat)

    # Make plots
    dset = datasets.getDataset(datasetName)
    tmp = Counts()
    oldCanvasDefW = ROOT.gStyle.GetCanvasDefW()
    ROOT.gStyle.SetCanvasDefW(int(oldCanvasDefW*1.5))

    # (tauID, leptonVeto)
    def usualRejected(obj2):
        _tauIDLabels = tauIDLabels(obj2)
        ret = [("None", "None"), ("None", "#tau_{1}")]
        ret.extend([(x, "#tau_{1}") for x in _tauIDLabels[4:]])
        ret.extend([(x, obj2) for x in _tauIDLabels])
        ret.extend([(x, "Other") for x in _tauIDLabels])
        return ret
    usualEmbedding = [("#tau_{1}", "None"), ("#tau_{1}+other (corr. sel.)", "None")]
    def usualFakeTau(obj2):
        return [(x, "None") for x in tauIDLabels(obj2)[4:]]
    doubleFakeTau = [("Other", "None")]
    usualCase1 = [(x, "#tau_{1}") for x in tauIDLabels("")[1:4]]
    usualCase3 = [("#tau_{1}+other (wrong sel.)", "None")]
    embCase4 = [(x, "None") for x in tauIDLabels("")[1:4]]
    def doubleCase2(obj2):
        return [(obj2, "None"), (obj2+"+other", "None")]

    selectionStep = {"Before": "",
                     "AfterJetSelection": "passJetSelection",
                     "AfterMET": "passMET",
                     "AfterBTag": "passBTag",
                     "AfterAllSelections": "passDeltaPhi"}[postfix]

    treeDraw = dataset.TreeDraw("tree", varexp="LeptonVetoStatus:TauIDStatus >>htemp(%d,0,%d, %d,0,%d" % (Enum.tauSize, Enum.tauSize, Enum.leptonSize, Enum.leptonSize))

    for name, obj2, obj2Type in [
        ("tau1_electron2", "e_{2}", Enum.obj2Electron),
        ("tau1_quark2", "q_{2}", Enum.obj2Quark),
        ("tau1_muon2_nonEmb", "#mu_{2}", Enum.obj2Muon),
        ]:
        tmp += calculatePlot(dset, neventsCount, name, postfix,
                             treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%obj2Type, selectionStep), binLabelsX=tauIDLabels(obj2), binLabelsY=leptonVetoLabels(obj2)),
                             rejected=usualRejected(obj2), embedding=usualEmbedding, faketau=usualFakeTau(obj2),
                             case1=usualCase1, case3=usualCase3)

    tmp += calculatePlot(dset, neventsCount, "tau1_muon2_Emb", postfix,
                         treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%Enum.obj2MuonEmb, selectionStep), binLabelsX=tauIDLabels("#mu_{2}"), binLabelsY=leptonVetoLabels("#mu_{2}")),
                         rejected=usualRejected("#mu_{2}")+usualCase1,
                         faketau=usualFakeTau("#mu_{2}"),
                         case4=embCase4)
#    createMuon2Plot(dset, "tau1_muon2_Emb", postfix)

    for name, obj2, obj2Type in [
        ("tau1_tau2_notInAcceptance", "#tau_{2}", Enum.obj2TauNotInAcceptance),
        ("tau1_tauh2", "#tau_{h,2}", Enum.obj2Tauh),
        ("tau1_taue2", "#tau_{e,2}", Enum.obj2Taue),
        ("tau1_taumu2_nonEmb", "#tau_{#mu,2}", Enum.obj2Taumu),
        ]:
        tmp += calculatePlot(dset, neventsCount, name, postfix,
                             treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%obj2Type, selectionStep), binLabelsX=tauIDLabels(obj2), binLabelsY=leptonVetoLabels(obj2)),
                             rejected=usualRejected(obj2), embedding=usualEmbedding, faketau=doubleFakeTau,
                             case1=usualCase1, case3=usualCase3,
                             case2=doubleCase2(obj2))

    tmp += calculatePlot(dset, neventsCount, "tau1_taumu2_Emb", postfix,
                         treeDraw=treeDraw.clone(selection=And("Obj2Type==%d"%Enum.obj2TaumuEmb, selectionStep), binLabelsX=tauIDLabels("#tau_{#mu,2}"), binLabelsY=leptonVetoLabels("#tau_{#mu,2}")),
                         rejected=usualRejected("#tau_{#mu,2}")+usualCase1,
                         faketau=doubleFakeTau,
                         case4=embCase4)

    ROOT.gStyle.SetCanvasDefW(oldCanvasDefW)


    ## Ntuple stuff

    embeddingSelection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonNone, Or(*["TauIDStatus == %d" % x for x in [Enum.tauTau1, Enum.tauTau1OtherCorrect]]))
                              for obj2 in [Enum.obj2Electron, Enum.obj2Quark, Enum.obj2Muon, Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]])
    case1Selection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonTau1, Or(*["TauIDStatus == %d" % x for x in [Enum.tauTau1, Enum.tauTau1OtherCorrect, Enum.tauTau1OtherWrong]]))
                              for obj2 in [Enum.obj2Electron, Enum.obj2Quark, Enum.obj2Muon, Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]])
    case2Selection = Or(*[And("Obj2Type == %d"%obj2, "LeptonVetoStatus == %d"%Enum.leptonNone, Or(*["TauIDStatus == %d" % x for x in [Enum.tauObj2, Enum.tauObj2Other]]))
                              for obj2 in [Enum.obj2TauNotInAcceptance, Enum.obj2Tauh, Enum.obj2Taue, Enum.obj2Taumu]])

    embeddingSelection = And(selectionStep, embeddingSelection)
    case1Selection = And(selectionStep, case1Selection)
    case2Selection = And(selectionStep, case2Selection)
    
    createTransverseMassPlot(dset, "case1", postfix, nominalSelection=embeddingSelection, compareSelection=case1Selection,
                             nominalLegend="Embedding (correct)", compareLegend="Case 1")
    createTransverseMassPlot(dset, "case2", postfix, nominalSelection=embeddingSelection, compareSelection=case2Selection,
                             nominalLegend="Embedding (correct)", compareLegend="Case 2")

    # plotNames = [
    #             "tau1_electron2",
    #             "tau1_quark2",
    #             "tau1_muon2_nonEmb",     
    #             "tau1_muon2_Emb",
    #             "tau1_tau2_notInAcceptance",
    #             "tau1_tauh2", 
    #             "tau1_taue2",
    #             "tau1_taumu2_nonEmb",
    #             "tau1_taumu2_Emb"
    #             ]
    # for name in plotNames:
    #     tmp += calculatePlot(dset, neventsCount, name, postfix)

    if int(nevents) != int(tmp.all):
        raise Exception("Consistency check failed: nevents = %d, tmp = %d" % (int(nevents), int(tmp.all)))

    tmp.printResults()
    print
    tmp.printLegend()
    tmp.crossCheck()

    allEmbeddingIncluded = int(tmp.embedding) + int(tmp.case1) + int(tmp.case3)

    print
    print "So, the number of events included by embedding is %d" % allEmbeddingIncluded
    print "Of these,"
 
    frac = dataset.divideBinomial(dataset.Count(int(tmp.embedding)), dataset.Count(allEmbeddingIncluded))
    frac.multiply(dataset.Count(100))
    print "  * %d (%s %%) are included correctly" % (int(tmp.embedding), cellFormat.format(frac))

    frac = dataset.divideBinomial(dataset.Count(int(tmp.case3)), dataset.Count(allEmbeddingIncluded))
    frac.multiply(dataset.Count(100))
    print "  * %d (%s %%) are included correctly, but wrong object is chosen as tau_h" % (int(tmp.case3), cellFormat.format(frac))

    frac = dataset.divideBinomial(dataset.Count(int(tmp.case1)), dataset.Count(allEmbeddingIncluded))
    frac.multiply(dataset.Count(100))
    print "  * %d (%s %%) are included incorrectly (tau_1 identified in lepton veto)" % (int(tmp.case1), cellFormat.format(frac))

    print "In addition, the following events are incorrectly rejected"
    # Note that these ratios are NOT binomial!
    # Although apparently, in practice, the result is the same
    
    #frac = dataset.divideBinomial(dataset.Count(int(tmp.case2)), dataset.Count(allEmbeddingIncluded))
    frac = dataset.Count(tmp.case2, math.sqrt(tmp.case2))
    frac.divide(dataset.Count(allEmbeddingIncluded, math.sqrt(allEmbeddingIncluded)))
    frac.multiply(dataset.Count(100))
    print "  * %d (%s %%): tau_1 not identified as tau_h, but decay of tau_2 would be" % (int(tmp.case2), cellFormat.format(frac))

    #frac = dataset.divideBinomial(dataset.Count(int(tmp.case4)), dataset.Count(allEmbeddingIncluded))
    frac = dataset.Count(tmp.case4, math.sqrt(tmp.case4))
    frac.divide(dataset.Count(allEmbeddingIncluded, math.sqrt(allEmbeddingIncluded)))
    frac.multiply(dataset.Count(100))
    print "  * %d (%s %%): mu_2 would be accepted for embedding, and is not identified in lepton veto" % (int(tmp.case4), cellFormat.format(frac))
def doPlots(datasetsEmb, datasetsSig, datasetName):
    lumi = datasetsEmb.getLuminosity()

    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

    treeDraw = dataset.TreeDraw("dummy", weight=weight)

    def drawPlot(plot, name, *args, **kwargs):
        tauEmbedding.drawPlot(plot, "mcembsig_"+datasetName+"_"+name, *args, **kwargs)

    opts2def = {"DYJetsToLL": {"ymin":0, "ymax": 1.5}}.get(datasetName, {"ymin": 0.5, "ymax": 1.5})

    # Decay mode finding
    postfix = "_1AfterDecayModeFindingIsolationPtPre"
    td = treeDraw.clone(selection=And(tauEmbedding.tauNtuple.decayModeFinding, tauEmbedding.tauNtuple.tightIsolation, tauEmbedding.tauNtuple.tauPtPreCut))
    opts2 = opts2def
    drawPlot(createPlot(td.clone(varexp="taus_p4.Eta()>>tmp(25,-2.5,2.5")),
             "tauEta"+postfix, "#tau-jet candidate #eta", ylabel="Events / %.1f", opts={"ymin": 1e-1}, opts2=opts2, moveLegend={"dx": -0.2, "dy": -0.45}, cutLine=[-2.1, 2.1])
    drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
             "tauPt"+postfix, "#tau-jet candidate p_{T} (GeV/c)", opts2=opts2, cutLine=40)

    # Eta cut
    postfix = "_2AfterEtaCut"
    td = treeDraw.clone(selection=And(tauEmbedding.tauNtuple.decayModeFinding, tauEmbedding.tauNtuple.tightIsolation, tauEmbedding.tauNtuple.tauPtPreCut, tauEmbedding.tauNtuple.tauEtaCut))
    drawPlot(createPlot(td.clone(varexp="taus_p4.Eta()>>tmp(25,-2.5,2.5")),
             "tauEta"+postfix, "#tau-jet candidate #eta", ylabel="Events / %.1f", opts={"ymin": 1e-1}, opts2=opts2, moveLegend={"dx": -0.2, "dy": -0.45}, cutLine=[-2.1, 2.1])
    drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
             "tauPt"+postfix, "#tau-jet candidate p_{T} (GeV/c)", opts2=opts2, cutLine=40)

    # Pt cut
    postfix = "_3AfterPtCut"
    td = treeDraw.clone(selection=And(tauEmbedding.tauNtuple.decayModeFinding, tauEmbedding.tauNtuple.tightIsolation, tauEmbedding.tauNtuple.tauEtaCut, tauEmbedding.tauNtuple.tauPtCut))
    drawPlot(createPlot(td.clone(varexp="taus_p4.Phi()>>tmp(32,-3.2,3.2")),
             "tauPhi"+postfix, "#tau-jet candidate #phi (rad)", ylabel="Events / %.1f", opts={"ymin": 1e-1}, opts2=opts2, moveLegend={"dx": -0.2, "dy": -0.45})
    opts2 = {"Diboson": {"ymin": 0, "ymax": 1.5}}.get(datasetName, opts2def)
    drawPlot(createPlot(td.clone(varexp="taus_leadPFChargedHadrCand_p4.Pt()>>tmp(25,0,250)")),
             "tauLeadingTrackPt"+postfix, "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts2=opts2, cutLine=20)
    opts2 = opts2def

    # Tau candidate selection
    postfix = "_4AfterTauCandidateSelection"
    td = treeDraw.clone(selection=tauEmbedding.tauNtuple.tauCandidateSelection)
    opts2 = {"EWKMC": {"ymin": 0.5, "ymax": 2}}.get(datasetName, opts2def)
    drawPlot(createPlot(td.clone(varexp=tauEmbedding.tauNtuple.decayModeExpression)),
             "tauDecayMode"+postfix+"", "", opts={"ymin": 1e-2, "ymaxfactor": 20, "nbins":5}, opts2=opts2,
             #moveLegend={"dy": 0.02, "dh": -0.02},
             function=tauEmbedding.tauNtuple.decayModeCustomize)
    opts2 = opts2def

    # One prong
    postfix = "_5AfterOneProng"
    td = treeDraw.clone(selection=And(tauEmbedding.tauNtuple.tauCandidateSelection, tauEmbedding.tauNtuple.oneProng))
    #drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
    #         "tauPt"+postfix, "#tau-jet candidate p_{T} (GeV/c)", opts2={"ymin": 0, "ymax": 2})
    #drawPlot(createPlot(td.clone(varexp="taus_p4.P()>>tmp(25,0,250)")),
    #         "tauP"+postfix, "#tau-jet candidate p (GeV/c)", opts2={"ymin": 0, "ymax": 2})
    #drawPlot(createPlot(td.clone(varexp="taus_leadPFChargedHadrCand_p4.Pt()>>tmp(25,0,250)")),
    #         "tauLeadingTrackPt"+postfix, "#tau-jet ldg. charged particle p_{T} (GeV/c)", opts2={"ymin":0, "ymax": 2})
    #drawPlot(createPlot(td.clone(varexp="taus_leadPFChargedHadrCand_p4.P()>>tmp(25,0,250)")),
    #         "tauLeadingTrackP"+postfix, "#tau-jet ldg. charged particle p (GeV/c)", opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp=tauEmbedding.tauNtuple.rtauExp+">>tmp(22, 0, 1.1)")),
             "rtau"+postfix, "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}", ylabel="Events / %.1f", opts={"ymin": 1e-2, "ymaxfactor": 5}, opts2=opts2, moveLegend={"dx":-0.34}, cutLine=0.7)

    # Full ID
    postfix = "_6AfterTauID"
    td = treeDraw.clone(selection=And(tauEmbedding.tauNtuple.tauCandidateSelection, tauEmbedding.tauNtuple.tauID))
    drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
             "tauPt"+postfix, "#tau-jet p_{T} (GeV/c)", opts2=opts2)
def doCounters(datasetsEmb, datasetsSig, datasetName):
    lumi = datasetsEmb.getLuminosity()
    treeDraw = dataset.TreeDraw("dummy", weight=weight)

    # Counters
    eventCounterEmb = tauEmbedding.EventCounterMany(datasetsEmb, counters=analysisEmb+"Counters")
    eventCounterSig = counter.EventCounter(datasetsSig, counters=analysisSig+"Counters")

    def isNotThis(name):
        return name != datasetName

    eventCounterEmb.removeColumns(filter(isNotThis, datasetsEmb.getAllDatasetNames()))
    eventCounterSig.removeColumns(filter(isNotThis, datasetsSig.getAllDatasetNames()))
    eventCounterSig.normalizeMCToLuminosity(lumi)

    #effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.4f'))
    #effFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat='%.4f'))
    effFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.4f'))

    tdEmb = treeDraw.clone(tree=analysisEmb+"/tree")
    tdSig = treeDraw.clone(tree=analysisSig+"/tree")
    selectionsCumulative = []
    tauSelectionsCumulative = []
    def sel(name, selection):
        selectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        eventCounterEmb.mainCounterAppendRow(name, tdEmb.clone(selection=sel))
        eventCounterSig.getMainCounter().appendRow(name, tdSig.clone(selection=sel))
    def tauSel(name, selection):
        tauSelectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        eventCounterEmb.mainCounterAppendRow(name, tdEmb.clone(selection=sel))
        eventCounterSig.getMainCounter().appendRow(name, tdSig.clone(selection=sel))

#    sel("Primary vertex", tauEmbedding.tauNtuple.pvSelection)
    sel(">= 1 tau candidate", "Length$(taus_p4) >= 1")
    tauSel("Decay mode finding", tauEmbedding.tauNtuple.decayModeFinding)
    tauSel("pT > 15", tauEmbedding.tauNtuple.tauPtPreCut)
    tauSel("pT > 40", tauEmbedding.tauNtuple.tauPtCut)
    tauSel("eta < 2.1", tauEmbedding.tauNtuple.tauEtaCut)
    tauSel("leading track pT > 20", tauEmbedding.tauNtuple.tauLeadPt)
    tauSel("ECAL fiducial", tauEmbedding.tauNtuple.ecalFiducial)
    tauSel("againstElectron", tauEmbedding.tauNtuple.electronRejection)
    tauSel("againstMuon", tauEmbedding.tauNtuple.muonRejection)
    tauSel("isolation", tauEmbedding.tauNtuple.tightIsolation)
    tauSel("oneProng", tauEmbedding.tauNtuple.oneProng)
    tauSel("Rtau", tauEmbedding.tauNtuple.rtau)
    sel("3 jets", tauEmbedding.tauNtuple.jetEventSelection)
    sel("MET", tauEmbedding.tauNtuple.metSelection)
    sel("btag", tauEmbedding.tauNtuple.btagEventSelection)

    table = counter.CounterTable()
    col = eventCounterEmb.getMainCounterTable().getColumn(name=datasetName)
    col.setName("Embedded")
    table.appendColumn(col)
    col = eventCounterSig.getMainCounterTable().getColumn(name=datasetName)
    col.setName("Normal")
    table.appendColumn(col)

    col = table.getColumn(name="Embedded")
    table.insertColumn(1, counter.efficiencyColumn(col.getName()+" eff", col))
    col = table.getColumn(name="Normal")
    table.appendColumn(counter.efficiencyColumn(col.getName()+" eff", col))

    print "%s counters" % datasetName
    print table.format(effFormat)

    f = open("counters_"+datasetName+".txt", "w")
    f.write(table.format(effFormat))
    f.write("\n")
    f.close()
Beispiel #18
0
def doTH1Plots(datasets, HistoList, MyCuts, SaveExtension):
    ''' 
    def doTH1Plots(datasets, HistoList, MyCuts, SaveExtension):
    Loops over all histograms defined in HistoHelper.py and customises 
    each plot accordingly. Global booleans and other options are also
    taken care of (including x- and y- min, max, ratio, logY, etc..). See
    the beginning of the file for all available options.
    '''

    if getBool("bCustomRange"):
        drawPlot = plots.PlotDrawer(
            stackMCHistograms=getBool("bStackHistos"),
            addMCUncertainty=getBool("bAddMCUncertainty"),
            log=getBool("bLogY"),
            ratio=getBool("bRatio"),
            addLuminosityText=getBool("bAddLumiText"),
            ratioYlabel="Ratio",
            opts={
                "ymin": yMin,
                "ymax": yMax
            },
            opts2={
                "ymin": yMinRatio,
                "ymax": yMaxRatio
            },
            optsLog={
                "ymin": yMinLog,
                "ymax": yMaxLog
            })
    else:
        drawPlot = plots.PlotDrawer(
            stackMCHistograms=getBool("bStackHistos"),
            addMCUncertainty=getBool("bAddMCUncertainty"),
            log=getBool("bLogY"),
            ratio=getBool("bRatio"),
            addLuminosityText=getBool("bAddLumiText"),
            opts={"ymaxfactor": yMaxFactor},
            opts2={
                "ymin": yMinRatio,
                "ymax": yMaxRatio
            },
            optsLog={"ymaxfactor": yMaxFactorLog})

    ### Define the event "weight" to be used
    if "passedBTagging" in MyCuts:
        EvtWeight = "(weightPileup*weightTauTrigger*weightPrescale*weightBTagging)"
    else:
        EvtWeight = "weightPileup*weightTauTrigger*weightPrescale"

    print "*** Cuts applied: \"%s\"" % (MyCuts)
    print "*** Weight applied: \"%s\"" % (EvtWeight)
    treeDraw = dataset.TreeDraw("tree", weight=EvtWeight)
    MyTreeDraw = treeDraw.clone(selection=MyCuts)

    ### Go ahead and draw the plot
    histograms.createLegend.setDefaults(x1=xLegMin,
                                        x2=xLegMax,
                                        y1=yLegMin,
                                        y2=yLegMax)

    ### Loop over all hName and expressions in the histogram list. Create & Draw plot
    counter = 0
    for h in HistoList:
        hName = h.name
        hExpr = MyTreeDraw.clone(varexp=h.expr)
        saveName = "TH1_%s" % (hName)
        xLabel = h.xlabel
        yLabel = h.ylabel
        iBinWidth = h.binWidthX
        ### Consider hName with "_Vs_" in the name as a TH2 histogram
        if "_Vs_" in hName:
            continue

        p = createTH1Plot(datasets,
                          hExpr,
                          normalizeToOne=getBool("bNormalizeToOne"))
        if not getBool("bStackHistos"):
            drawPlot(p,
                     saveName + SaveExtension,
                     xlabel=xLabel,
                     ylabel=yLabel,
                     rebinToWidthX=iBinWidth)
        else:
            drawPlot(p,
                     saveName + "_Stacked" + SaveExtension,
                     xlabel=xLabel,
                     ylabel=yLabel,
                     rebinToWidthX=iBinWidth)

        ### Do Data plots with QCD=Data-EwkMc. Only executed if certain (boolean) conditions are met.
        if getBool("bDataMinusEwk") and not getBool("bRemoveData"):

            if getBool("bCustomRange"):
                drawPlot2 = plots.PlotDrawer(
                    stackMCHistograms=getBool("bStackHistos"),
                    addMCUncertainty=False,
                    log=getBool("bLogY"),
                    ratio=False,
                    addLuminosityText=getBool("bAddLumiText"),
                    ratioYlabel="Ratio",
                    opts={
                        "ymin": yMin,
                        "ymax": yMax
                    },
                    optsLog={
                        "ymin": yMinLog,
                        "ymax": yMaxLog
                    })
            else:
                drawPlot2 = plots.PlotDrawer(
                    stackMCHistograms=getBool("bStackHistos"),
                    addMCUncertainty=False,
                    log=getBool("bLogY"),
                    ratio=False,
                    addLuminosityText=getBool("bAddLumiText"),
                    opts={"ymaxfactor": yMaxFactor},
                    optsLog={"ymaxfactor": yMaxFactorLog})

            doDataMinusEwk(p,
                           drawPlot2,
                           datasets,
                           hExpr,
                           hName,
                           xLabel,
                           yLabel,
                           iBinWidth,
                           SaveExtension,
                           hType={"TH1": True})

        ### Do QCD Purity plots
        if getBool("bQcdPurity"):
            doQcdPurPlots(p, drawPlot, datasets, hExpr, hName, xLabel,
                          "Purity", SaveExtension)

    return
def doPlots(datasets, histoDict, MyCuts, SaveExtension):
    ''' doPlots(datasets, histoDict, MyCuts, SaveExtension):
    This module takes the "histoDict" dictionary (which maps the histogram names and tree expressions)
    and the TCut expression "MyCuts" to first create and then plot the histograms, using the given "datasets". 
    The "SaveExtension" is the string attached to the name all plotted histograms, primarily to distinguish 
    the plot type.
    '''
    
    def createPlot(name, **kwargs):
        ''' createPlot(name, **kwargs):
    This module is used to create the histograms for the given "name". The user can pass 
    arguments including the histogram name, expression, labels, cut boxes etc..    
    '''
        if mcOnly:
            ### If 'normalizeToOne' is given in kwargs, we don't need the normalizeToLumi (or actually the library raises an Exception)
            args = {}
            args.update(kwargs)
            if not ("normalizeToOne" in args and args["normalizeToOne"]):
                args["normalizeToLumi"] = mcOnlyLumi
            p = plots.MCPlot(datasets, name, **args)
            p.histoMgr.setHistoLegendStyleAll("L")
            return p
        else:
            p = plots.DataMCPlot(datasets, name, **kwargs)
            return p
        p.setDefaultStyles()
        return p

    ### Function returns a progress bar object (pBar) and a CallBack(int, int) function
    maxValue = len(histoDict)
    print "*** Preparing %s histogram(s) for the cut group:\n    %s" % (maxValue, MyCuts)

    ### Create a progress bar to inform user of progress status
    pBar = StartProgressBar(maxValue)

    ### Customise my plots
    if mcOnly:
        drawPlot = plots.PlotDrawer(stackMCHistograms=False, addMCUncertainty=True, log=bLogY, ratio=False, addLuminosityText= not bNormalizeToOne, ratioYlabel="Ratio", optsLog={"ymin": yMin}, opts2={"ymin": yMinRatio, "ymax": yMaxRatio})
    else:
        drawPlot = plots.PlotDrawer(stackMCHistograms=True, addMCUncertainty=True, log=bLogY, ratio=True, addLuminosityText=True, ratioYlabel="Ratio", optsLog={"ymin": yMin}, opts2={"ymin": yMinRatio, "ymax": yMaxRatio})


    ### Define the tree to be used with the given cuts
    if "passedBTagging" in MyCuts:
        EvtWeight = "(weightPileup*weightTrigger*weightPrescale*weightBTagging)";
    else:
        EvtWeight = "weightPileup*weightTrigger*weightPrescale"
    print "*** Drawing tree with event weight:\n    %s" % (EvtWeight)
    treeDraw = dataset.TreeDraw("tree", weight=EvtWeight)
    MyTreeDraw = treeDraw.clone(selection=MyCuts)
    
    ### Loop over all hName and expressions in the dictionary "histoDict"
    counter=0
    for hName in histoDict:
        #print "*** Plotting \"%s\": %s" % (hName, histoDict[hName])
        histo = MyTreeDraw.clone(varexp=histoDict[hName])
        if mcOnly:
            drawPlot(createPlot(histo, normalizeToOne = bNormalizeToOne), "%s_%s" % (hName, SaveExtension), hName, ylabel="Events / %.1f ", cutBox={"cutValue":0.0, "greaterThan":True})
        else:
            drawPlot(createPlot(histo, normalizeToOne = False), "%s_%s" % (hName, SaveExtension), hName, ylabel="Events / %.1f ", cutBox={"cutValue":0.0, "greaterThan":True})

        # Increment counter and pdate progress bar
        counter = counter+1
        pBar.update(counter)
    
    ### Stop pbar once done with the loop
    pBar.finish()
Beispiel #20
0
def main():
    # Read the datasets
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)

    if era == "EPS":
        datasets.remove([
            "SingleMu_Mu_170722-172619_Aug05",
            "SingleMu_Mu_172620-173198_Prompt",
            "SingleMu_Mu_173236-173692_Prompt",
        ])
    elif era == "Run2011A-EPS":
        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",

            #"SingleMu_Mu_170722-172619_Aug05",
            #"SingleMu_Mu_172620-173198_Prompt",
            #"SingleMu_Mu_173236-173692_Prompt",

            ])
    elif era == "Run2011A":
        pass
    else:
        raise Exception("Unsupported era "+era)
    datasets.loadLuminosities()
    plots.mergeRenameReorderForDataMC(datasets)
    datasets.remove(filter(lambda name: "TTToHplus" in name, datasets.getAllDatasetNames()))

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    histograms.createLegend.moveDefaults(dx=-0.04)
    datasets.remove(["QCD_Pt20_MuEnriched"])
    histograms.createLegend.moveDefaults(dh=-0.05)

    def createPlot(name):
        name2 = name
        if isinstance(name, basestring):
            name2 = analysis+"/"+name
        return plots.DataMCPlot(datasets, name2)

    weight = "weightPileup"
    weightBTagging = weight+"*weightBTagging"
    #weight = ""
    #weightBTagging = weight
    if normalize:
        weight = "weightPileup*weightTrigger"
        weightBTagging = weight+"*weightBTagging"
    treeDraw = dataset.TreeDraw(analysis+"/tree", weight=weight)

    tauEmbedding.normalize=False
    drawPlot = tauEmbedding.drawPlot

    caloMetCut = "(tecalomet_p4.Et() > 60)"
    caloMetNoHFCut = "(tecalometNoHF_p4.Et() > 60)"
    metCut = "(met_p4.Et() > 50)"
    bTaggingCut = "passedBTagging"
    #deltaPhi160Cut = "abs(tau_p4.Phi() - met_p4.Phi())*57.3 <= 160"
    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)"
    deltaPhi90Cut = "(acos( (tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/(tau_p4.Pt()*met_p4.Et()) )*57.3 <= 90)"


    mt = "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))"
    mtOriginal = "sqrt(2 * temuon_p4.Pt() * temet_p4.Et() * (1-cos(temuon_p4.Phi()-temet_p4.Phi())))"
    #mtCut = " (0 <= %s)" % mt
    mtCut = "(80 < %s && %s < 120)" % (mt, mt)
    #mtCut = "(60 < tau_p4.Pt() && tau_p4.Pt() < 80)"

    td = treeDraw.clone(selection="&&".join([metCut, bTaggingCut, mtCut]))
    drawPlot(createPlot(td.clone(varexp="met_p4.Pt() >>tmp(40,0,400)")),
             "met", "Raw PF E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="goodPrimaryVertices_n >>tmp(20,0,20)")),
             "vertices_n", "Number of good primary vertices", ylabel="Events", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="tau_p4.Pt() >>tmp(25,0,250)")),
             "tauPt", "#tau-jet p_{T} (GeV/c)", ylabel="Events / %.0f GeV/c", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="tau_p4.Eta() >>tmp(25, -2.5, 2.5)")),
             "tauEta", "#tau-jet #eta (GeV/c)", ylabel="Events / %.1f", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="tau_p4.Phi() >>tmp(32, -3.2, 3.2)")),
             "tauPhi", "#tau-jet #phi (rad)", ylabel="Events / %.1f", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.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)")),
             "deltaPhi", "#Delta#phi(#tau jet, E_{T}^{miss}) (^{#circ})", ylabel="Events / %.0f^#{circ}", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="%s >>tmp(20,0,200)"%mt)),
             "mt", "m_{T}(#tau jet, E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})

    drawPlot(createPlot(td.clone(varexp="temuon_p4.Pt() >>tmp(25,0,250)")),
             "muonPt", "Muon p_{T} (GeV/c)", ylabel="Events / %.0f GeV/c", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="temet_p4.Pt() >>tmp(40,0,400)")),
             "metOriginal", "Original E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="acos( (temuon_p4.Px()*temet_p4.Px()+temuon_p4.Py()*temet_p4.Py())/(temuon_p4.Pt()*temet_p4.Et()) )*57.3 >> tmp(18,0,180)")),
             "deltaPhiOriginal", "#Delta#phi(#mu, E_{T,orig}^{miss}) (^{#circ})", ylabel="Events / %.0f^#{circ}", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="%s >>tmp(20,0,200)"%mtOriginal)),
             "mtOriginal", "m_{T}(#mu, E_{T,orig}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    

    print td.selection

    beamHaloEvents = [
        (167676, 191, 175029501),
        (167281, 131, 169702989),
        (171178, 585, 622286805),
        (171578, 353, 342125646),
        (171876, 116, 164854215),
        (170854, 109, 112747742),
        (172822, 2241, 2818902364),
        (172822, 697, 946580712),
        (172868, 462, 625761643),
        (172791, 182, 223810661),
        (173692, 745, 1067744681),
        ]

    td = treeDraw.clone(selection="||".join(["(run==%d && lumi==%d && event==%d)" % eventId for eventId in beamHaloEvents]))
    drawPlot(createPlot(td.clone(varexp="tau_p4.Pt() >>tmp(25,0,250)")),
             "beamHalo_tauPt", "#tau-jet p_{T} (GeV/c)", ylabel="Events / %.0f GeV/c", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="met_p4.Pt() >>tmp(40,0,400)")),
             "beamHalo_met", "Raw PF E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
    drawPlot(createPlot(td.clone(varexp="%s >>tmp(20,0,200)"%mt)),
             "beamHalo_mt", "m_{T}(#tau jet, E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", addMCUncertainty=True, ratio=False, opts2={"ymin":0, "ymax": 2})
Beispiel #21
0
def main():
    datasets = dataset.getDatasetsFromMulticrabCfg(counters=counters)
    datasets.updateNAllEventsToPUWeighted()

    # remove data datasets
    datasets.remove(
        filter(lambda name: "Tau_" in name, datasets.getAllDatasetNames()))
    # remove heavy H+ datasets
    datasets.remove(
        filter(lambda name: "HplusTB" in name, datasets.getAllDatasetNames()))

    plots.mergeRenameReorderForDataMC(datasets)
    xsect.setHplusCrossSectionsToBR(datasets, br_tH=0.05, br_Htaunu=1)
    plots.mergeWHandHH(
        datasets
    )  # merging of WH and HH signals must be done after setting the cross section

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Define variables and cuts
    tauPt = "tau_p4.Pt()"
    tauPtCut = tauPt + " > 40"
    tauLeadingCandPt = "tau_leadPFChargedHadrCand_p4.Pt()"
    tauLeadingCandPtCut = tauLeadingCandPt + " > 20"

    met = "met_p4.Et()"
    metCut = met + " > 70"

    btagMax = "Max$(jets_btag)"
    btagCut = btagMax + " > 1.7"
    btagJetNum17 = "Sum$(jets_btag > 1.7"
    btag2ndMax = "MaxIf(kets_btag, jets_btag < Max$(jets_btag))"

    rtau = "tau_leadPFChargedHadrCand_p4.P()/tau_p4.P()"
    rtauCut = rtau + " > 0.65"
    mt = "sqrt(2 * tau_p4.Pt() * met_p4.Et() * (1-cos(tau_p4.Phi()-met_p4.Phi())))"
    mtCut = mt + " > 80"
    deltaPhi = "acos((tau_p4.Px()*met_p4.Px()+tau_p4.Py()*met_p4.Py())/tau_p4.Pt()/met_p4.Et())*57.2958"
    deltaPhiCut = deltaPhi + " < 160"

    npv = "goodPrimaryVertices_n"

    td = dataset.TreeDraw(analysis + "/tree",
                          weight="weightPileup*weightTrigger*weightPrescale")
    lumi = 1145

    def createResult(varexp, selection, weight=None, **kwargs):
        args = {"varexp": varexp, "selection": selection}
        if weight != None:
            args["weight"] = weight
        return Result(datasets,
                      td.clone(**args),
                      normalizeToLumi=lumi,
                      **kwargs)

    # metRes = createResult(met+">>dist(100,0,200)", btagCut, greaterThan=True)
    # metRes.save("met", "MET (GeV)", rebin=10, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # btagRes = createResult(btagMax+">>dist(80, 0, 8)", metCut, greaterThan=True)
    # btagRes.save("btag", "TCHE", rebin=5, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # rtauRes = createResult(rtau+">>dist(110,0,1.1)", metCut+"&&"+btagCut, greaterThan=True)
    # rtauRes.save("rtau", "R_{#tau}", rebin=10, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # mtRes = createResult(mt+">>dist(50,0,200)", metCut+"&&"+btagCut, greaterThan=True)
    # mtRes.save("mt", "M_{T}(#tau, MET) (GeV)", rebin=2, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    # deltaPhiRes = createResult(deltaPhi+">>dist(90,0,180)", metCut+"&&"+btagCut, lessThan=True)
    # deltaPhiRes.save("deltaPhi", "#Delta#Phi(#tau, MET) (#circ)", rebin=5, logy=True, opts={"ymin": 0.01, "ymaxfactor": 10})

    pileupRes = createResult(npv + ">>dist(4,1,17)",
                             metCut + "&&" + btagCut,
                             weight="",
                             doPassed=False,
                             lessThan=True)
    pileupRes.save("goodPV", "N(good primary vertices)")
Beispiel #22
0
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)
Beispiel #23
0
def doTH1Plots(datasets, histoDict, xLabelDict, yLabelDict,  MyCuts, SaveExtension):
    ''' 
    def doTH1Plots(datasets, histoDict, xLabelDict, yLabelDict,  MyCuts, SaveExtension):
    '''

    ### Create a progress bar to inform user of progress status. Calculate the number of TH1 histos only
    maxValue = 0
    for key in histoDict:
        if "_Vs_" in key:
            continue
        else:
            maxValue += 1
    if bDataMinusEwk==True and bMcOnly==False:
        maxValue= maxValue*2
    if maxValue==0:
        print "*** NOTE! No TH1 histos to plot. Exiting doTH1Plots() module."
        return
    print "\n*** Preparing %s TH1 histogram(s) for the cut group:\n    \"%s\"" % (maxValue, MyCuts)
    pBar = StartProgressBar(maxValue)
    
    if bCustomRange:
        drawPlot = plots.PlotDrawer(stackMCHistograms=bStackHistos, addMCUncertainty=bAddMCUncertainty, log=bLogY, ratio=not bMcOnly, addLuminosityText=bAddLumiText, ratioYlabel="Ratio", opts={"ymin": yMin, "ymax": yMax}, opts2={"ymin": yMinRatio, "ymax": yMaxRatio}, optsLog={"ymin": yMinLog, "ymax": yMaxLog})
    else:
        drawPlot = plots.PlotDrawer(stackMCHistograms=bStackHistos, addMCUncertainty=bAddMCUncertainty, log=bLogY, ratio=bStackHistos, addLuminosityText=bAddLumiText, opts={"ymaxfactor": yMaxFactor}, opts2={"ymin": yMinRatio, "ymax": yMaxRatio}, optsLog={"ymin": yMinLog, "ymaxfactor": yMaxFactor})
    
    ### Define the event "weight" to be used
    if "passedBTagging" in MyCuts:
        #EvtWeight = "(weightPileup*weightTrigger*weightPrescale*weightBTagging)"
        EvtWeight = "(weightPileup*weightTauTrigger*weightPrescale*weightBTagging)"
    else:
        #EvtWeight = "weightPileup*weightTrigger*weightPrescale"
        EvtWeight = "weightPileup*weightTauTrigger*weightPrescale"
        
    print "*** And Event weight:\n    \"%s\"" % (EvtWeight)
    treeDraw = dataset.TreeDraw("tree", weight=EvtWeight)
    MyTreeDraw = treeDraw.clone(selection=MyCuts)
    
    ### Loop over all hName and expressions in the histogram dictionary "histoDict". Create & Draw plot
    counter=0        
    for key in histoDict:
        if "_Vs_" in key:
            continue
        hName = key
        histo = MyTreeDraw.clone(varexp=histoDict[hName])
        fileName = "%s_%s" % (hName, SaveExtension)
        xLabel = xLabelDict[hName]
        yLabel = yLabelDict[hName]
            
        ### Go ahead and draw the plot
        p = createTH1Plot(datasets, histo, normalizeToOne = bNormalizeToOne)
        drawPlot(p, fileName, rebin=1, xlabel=xLabel, ylabel=yLabel)

        ### Increment counter and pdate progress bar
        counter = counter+1
        pBar.update(counter)
    
        ### Do Data plots with QCD= Data-Ewk_MC. Only executed if certain (boolean) conditions are met.
        doDataMinusEWk(p, drawPlot, datasets, counter, histo, hName, xLabel, yLabel, SaveExtension)
        pBar.update(counter)
        
    ### Stop pbar once done with the loop
    pBar.finish()    

    return
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 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)
Beispiel #26
0
def doPlots(datasetsEmb, datasetsSig, datasetName):
    lumi = datasetsEmb.getDataset("Data").getLuminosity()

    plots._legendLabels[datasetName+"_Embedded"] = "Embedded "+plots._legendLabels[datasetName]
    plots._legendLabels[datasetName+"_Normal"]   = "Normal "+plots._legendLabels[datasetName]

    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

    opts2 = {"ymin": 0, "ymax": 2}
    def drawControlPlot(path, xlabel, **kwargs):
        drawPlot(createPlot("ControlPlots/"+path), "mcembsig_"+datasetName+"_"+path, xlabel, opts2=opts2, **kwargs)

    # Control plots
    drawControlPlot("SelectedTau_pT_AfterStandardSelections", "#tau-jet p_{T} (GeV/c)", opts={"xmax": 250}, rebin=2, cutBox={"cutValue": 40, "greaterThan": 40})
    drawControlPlot("SelectedTau_eta_AfterStandardSelections", "#tau-jet #eta", opts={"xmin": -2.2, "xmax": 2.2}, ylabel="Events / %.1f", rebin=4, log=False, moveLegend={"dy":-0.6, "dx":-0.2})
    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={"xmax": 300}, 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": 5}, rebin=5, ylabel="Events / %.2f", moveLegend={"dx":-0.3}, 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", "Uncorredted PF E_{T}^{miss} (GeV)", rebin=5, opts={"xmax": 400}, cutLine=50)
    drawControlPlot("NBjets", "Number of selected b jets", opts={"xmax": 6}, ylabel="Events", moveLegend={"dx":-0.3, "dy":-0.5}, cutLine=1)

    treeDraw = dataset.TreeDraw("dummy", weight="weightPileup")

    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,200)")

    # DeltaPhi
    xlabel = "#Delta#phi(#tau, MET) (^{#circ})"
    def customDeltaPhi(h):
        yaxis = h.getFrame().GetYaxis()
        yaxis.SetTitleOffset(0.8*yaxis.GetTitleOffset())
    drawPlot(createPlot(tdDeltaPhi.clone()), "mcembsig_"+datasetName+"_deltaPhi_1AfterTauID", xlabel, log=False, opts2=opts2, ylabel="Events / %.0f^{#circ}", function=customDeltaPhi, moveLegend={"dx":-0.22}, cutLine=[130, 160])

    # mT
    xlabel = "m_{T} (#tau jet, E_{T}^{miss}) (GeV/c^{2})"
    drawPlot(createPlot(tdMt.clone()), "mcembsig_"+datasetName+"_transverseMass_1AfterTauID", xlabel, opts2=opts2, ylabel="Events / %.0f GeV/c^{2}")


    # After all cuts
    metCut = "(met_p4.Et() > 50)"
    bTaggingCut = "passedBTagging"
    selection = "&&".join([metCut, bTaggingCut])
    drawPlot(createPlot(treeDraw.clone(varexp="tau_p4.Pt() >>tmp(20,0,200)", selection=selection)), "mcembsig_"+datasetName+"_selectedTauPt_3AfterBTagging", "#tau-jet p_{T} (GeV/c)", opts2={"ymin": 0, "ymax": 2})
    drawPlot(createPlot(treeDraw.clone(varexp="met_p4.Pt() >>tmp(16,0,400)", selection=selection)), "mcembsig_"+datasetName+"_MET_3AfterBTagging", "E_{T}^{miss} (GeV)", ylabel="Events / %.0f GeV", opts2={"ymin": 0, "ymax": 2})
    drawPlot(createPlot(tdMt.clone(selection=selection)), "mcembsig_"+datasetName+"_transverseMass_3AfterBTagging", xlabel, opts2={"ymin": 0, "ymax": 2}, ylabel="Events / %.0f GeV/c^{2}")
                        


    eventCounterEmb = counter.EventCounter(datasetsEmb, counters=analysisEmb+"Counters")
    eventCounterSig = counter.EventCounter(datasetsSig, counters=analysisSig+"Counters")
    eventCounterEmb.normalizeMCToLuminosity(lumi)
    eventCounterSig.normalizeMCToLuminosity(lumi)

    #effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.4f'))
    #effFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat='%.4f'))
    effFormat = counter.TableFormatText(counter.CellFormatTeX(valueFormat='%.4f'))

    for function, cname in [
        (lambda c: c.getMainCounterTable(), "Main"),
        (lambda c: c.getSubCounterTable("TauIDPassedEvt::tauID_HPSTight"), "Tau")
        ]:
        tableEmb = function(eventCounterEmb)
        tableSig = function(eventCounterSig)

        table = counter.CounterTable()
        col = tableEmb.getColumn(name=datasetName)
        col.setName("Embedded")
        table.appendColumn(col)
        col = tableSig.getColumn(name=datasetName)
        col.setName("Normal")
        table.appendColumn(col)

        print "%s counters" % cname
        print table.format()

        if cname == "Main":
            #map(lambda t: t.keepOnlyRows([
            table.keepOnlyRows([
                        "All events",
                        "Trigger and HLT_MET cut",
                        "taus == 1",
                        #"trigger scale factor",
                        "electron veto",
                        "muon veto",
                        "MET",
                        "njets",
                        "btagging",
                        "btagging scale factor",
                        "JetsForEffs",
                        "METForEffs",
                        "BTagging",
                        "DeltaPhi < 160",
                        "DeltaPhi < 130"
                        ])#, [tableEmb, tableSig])
        else:
            #map(lambda t: t.keepOnlyRows([
            table.keepOnlyRows([
                        "AllTauCandidates",
                        "DecayModeFinding",
                        "TauJetPt",
                        "TauJetEta",
                        #"TauLdgTrackExists",
                        "TauLdgTrackPtCut",
                        "TauECALFiducialCutsCracksAndGap",
                        "TauAgainstElectronCut",
                        "TauAgainstMuonCut",
                        #"EMFractionCut",
                        "HPS",
                        "TauOneProngCut",
                        "TauRtauCut",
                        ])#, [tableEmb, tableSig])

        col = table.getColumn(name="Embedded")
        table.insertColumn(1, counter.efficiencyColumn(col.getName()+" eff", col))
        col = table.getColumn(name="Normal")
        table.appendColumn(counter.efficiencyColumn(col.getName()+" eff", col))

        print "%s counters" % cname
        print table.format(effFormat)
Beispiel #27
0
from HiggsAnalysis.HeavyChHiggsToTauNu.tools.myArrays import *
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.crosssection as xsect
from InvertedTauID import *

# Configuration
analysis = "signalAnalysisInvertedTau"
#analysis = "signalAnalysisInvertedTauOptQCDTailKillerLoose"
#analysis = "signalOptimisation"
#analysis = "signalAnalysisJESMinus03eta02METMinus10"
#analysis = "EWKFakeTauAnalysisJESMinus03eta02METMinus10"
#analysis = "signalOptimisation/QCDAnalysisVariation_tauPt40_rtau0_btag2_METcut60_FakeMETCut0"
#analysis = "signalAnalysisTauSelectionHPSTightTauBased2"
#analysis = "signalAnalysisBtaggingTest2"
counters = analysis + "/counters"

treeDraw = dataset.TreeDraw(analysis + "/tree",
                            weight="weightPileup*weightTrigger*weightPrescale")

#QCDfromData = True
QCDfromData = False

lastPtBin150 = False
lastPtBin120 = True

mcOnly = False
#mcOnly = True
mcOnlyLumi = 5000  # pb

searchMode = "Light"
#searchMode = "Heavy"

#dataEra = "Run2011A"
def doCounters(datasetsEmb2, datasetsSig2, datasetName):
    lumi = datasetsEmb2.getDataset("Data").getLuminosity()

    datasetsEmb = datasetsEmb2.deepCopy()
    datasetsSig = datasetsSig2.deepCopy()

    datasetsEmb.remove(
        filter(lambda name: name != datasetName,
               datasetsEmb.getAllDatasetNames()))
    datasetsSig.remove(
        filter(lambda name: name != datasetName,
               datasetsSig.getAllDatasetNames()))
    # Counters
    eventCounterEmb = counter.EventCounter(datasetsEmb,
                                           counters=analysisEmb + "Counters")
    eventCounterSig = counter.EventCounter(datasetsSig,
                                           counters=analysisSig + "Counters")
    eventCounterEmb.normalizeMCToLuminosity(lumi)
    eventCounterSig.normalizeMCToLuminosity(lumi)

    #effFormat = counter.TableFormatText(counter.CellFormatText(valueFormat='%.4f'))
    #effFormat = counter.TableFormatConTeXtTABLE(counter.CellFormatTeX(valueFormat='%.4f'))
    effFormat = counter.TableFormatText(
        counter.CellFormatTeX(valueFormat='%.4f'))

    counterEmb = eventCounterEmb.getMainCounter()
    counterSig = eventCounterSig.getMainCounter()
    treeDraw = dataset.TreeDraw("dummy")
    tdEmb = treeDraw.clone(tree=analysisEmb + "/tree")
    tdSig = treeDraw.clone(tree=analysisSig + "/tree")
    selectionsCumulative = []
    tauSelectionsCumulative = []

    def sel(name, selection):
        selectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        counterEmb.appendRow(name, tdEmb.clone(selection=sel))
        counterSig.appendRow(name, tdSig.clone(selection=sel))

    def tauSel(name, selection):
        tauSelectionsCumulative.append(selection)
        sel = selectionsCumulative[:]
        if len(tauSelectionsCumulative) > 0:
            sel += ["Sum$(%s) >= 1" % "&&".join(tauSelectionsCumulative)]
        sel = "&&".join(sel)
        counterEmb.appendRow(name, tdEmb.clone(selection=sel))
        counterSig.appendRow(name, tdSig.clone(selection=sel))


#    sel("Primary vertex", tauPlot.pvSelection)

    sel(">= 1 tau candidate", "Length$(taus_p4) >= 1")
    tauSel("Decay mode finding", tauPlot.decayModeFinding)
    tauSel("pT > 15", "(taus_p4.Pt() > 15)")
    tauSel("pT > 40", tauPlot.tauPtCut)
    tauSel("eta < 2.1", tauPlot.tauEtaCut)
    tauSel("leading track pT > 20", tauPlot.tauLeadPt)
    tauSel("ECAL fiducial", tauPlot.ecalFiducial)
    tauSel("againstElectron", tauPlot.electronRejection)
    tauSel("againstMuon", tauPlot.muonRejection)
    tauSel("isolation", tauPlot.tightIsolation)
    tauSel("oneProng", tauPlot.oneProng)
    tauSel("Rtau", tauPlot.rtau)
    sel("3 jets", tauPlot.jetEventSelection)
    sel("MET", tauPlot.metSelection)
    sel("btag", tauPlot.btagEventSelection)

    table = counter.CounterTable()
    col = counterEmb.getTable().getColumn(name=datasetName)
    col.setName("Embedded")
    table.appendColumn(col)
    col = counterSig.getTable().getColumn(name=datasetName)
    col.setName("Normal")
    table.appendColumn(col)

    col = table.getColumn(name="Embedded")
    table.insertColumn(1, counter.efficiencyColumn(col.getName() + " eff",
                                                   col))
    col = table.getColumn(name="Normal")
    table.appendColumn(counter.efficiencyColumn(col.getName() + " eff", col))

    print "%s counters" % datasetName
    print table.format(effFormat)
Beispiel #29
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()
def doPlots(datasetsEmb2, datasetsSig2, datasetName):
    lumi = datasetsEmb2.getDataset("Data").getLuminosity()

    datasetsEmb = datasetsEmb2.deepCopy()
    datasetsSig = datasetsSig2.deepCopy()

    datasetsEmb.remove(
        filter(lambda name: name != datasetName,
               datasetsEmb.getAllDatasetNames()))
    datasetsSig.remove(
        filter(lambda name: name != datasetName,
               datasetsSig.getAllDatasetNames()))

    plots._legendLabels[
        datasetName +
        "_Embedded"] = "Embedded " + plots._legendLabels[datasetName]
    plots._legendLabels[
        datasetName + "_Normal"] = "Normal " + plots._legendLabels[datasetName]

    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

    treeDraw = dataset.TreeDraw("dummy")

    opts2 = {"ymin": 0, "ymax": 2}

    def drawPlot(plot, name, *args, **kwargs):
        tauEmbedding.drawPlot(plot, "mcembsig_" + datasetName + "_" + name,
                              *args, **kwargs)

    # Decay mode finding
    td = treeDraw.clone(
        selection=And(tauPlot.decayModeFinding, tauPlot.tightIsolation))
    postfix = "_1AfterDecayModeFindingIsolation"
    drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
             "tauPt" + postfix,
             "#tau-jet candidate p_{T} (GeV/c)",
             cutLine=40)
    drawPlot(createPlot(td.clone(varexp="taus_decayMode>>tmp(16,0,16)")),
             "tauDecayMode" + postfix + "_check",
             "",
             opts={"nbins": 16},
             opts2={
                 "ymin": 0.9,
                 "ymax": 1.4
             },
             function=tauPlot.decayModeCheckCustomize)
    drawPlot(createPlot(td.clone(varexp=tauPlot.decayModeExp)),
             "tauDecayMode" + postfix + "",
             "",
             opts={
                 "ymin": 1,
                 "ymaxfactor": 20,
                 "nbins": 5
             },
             opts2={
                 "ymin": 0.9,
                 "ymax": 1.4
             },
             moveLegend={
                 "dy": 0.02,
                 "dh": -0.02
             },
             function=tauPlot.decayModeCustomize)

    # Pt
    postfix = "_2AfterPtCut"
    td = treeDraw.clone(selection=And(
        tauPlot.decayModeFinding, tauPlot.tightIsolation, tauPlot.tauPtCut))
    drawPlot(createPlot(td.clone(varexp=tauPlot.decayModeExp)),
             "tauDecayMode" + postfix + "",
             "",
             opts={
                 "ymin": 1,
                 "ymaxfactor": 20,
                 "nbins": 5
             },
             opts2={
                 "ymin": 0.9,
                 "ymax": 1.4
             },
             moveLegend={
                 "dy": 0.02,
                 "dh": -0.02
             },
             function=tauPlot.decayModeCustomize)
    drawPlot(createPlot(td.clone(varexp="taus_p4.Eta()>>tmp(25,-2.5,2.5")),
             "tauEta" + postfix,
             "#tau-jet candidate #eta",
             ylabel="Events / %.1f",
             opts={"ymin": 1e-1},
             moveLegend={
                 "dx": -0.2,
                 "dy": -0.45
             },
             cutLine=[-2.1, 2.1])
    drawPlot(createPlot(td.clone(varexp="taus_p4.Phi()>>tmp(32,-3.2,3.2")),
             "tauPhi" + postfix,
             "#tau-jet candidate #phi (rad)",
             ylabel="Events / %.1f",
             opts={"ymin": 1e-1},
             moveLegend={
                 "dx": -0.2,
                 "dy": -0.45
             })

    # Eta
    td = treeDraw.clone(
        selection=And(tauPlot.decayModeFinding, tauPlot.tightIsolation,
                      tauPlot.tauPtCut, tauPlot.tauEtaCut))
    postfix = "_3AfterEtaCut"
    drawPlot(createPlot(
        td.clone(varexp="taus_leadPFChargedHadrCand_p4.Pt()>>tmp(25,0,250)")),
             "tauLeadingTrackPt" + postfix,
             "#tau-jet ldg. charged particle p_{T} (GeV/c)",
             opts2={
                 "ymin": 0,
                 "ymax": 2
             },
             cutLine=20)

    # Tau candidate selection
    td = treeDraw.clone(selection=tauPlot.tauCandidateSelection)
    postfix = "_4AfterTauCandidateSelection"
    drawPlot(createPlot(td.clone(varexp=tauPlot.decayModeExp)),
             "tauDecayMode" + postfix + "",
             "",
             opts={
                 "ymin": 1e-2,
                 "ymaxfactor": 20,
                 "nbins": 5
             },
             opts2={
                 "ymin": 0,
                 "ymax": 2
             },
             moveLegend={
                 "dy": 0.02,
                 "dh": -0.02
             },
             function=tauPlot.decayModeCustomize)

    # Isolation + one prong
    td = treeDraw.clone(
        selection=And(tauPlot.tauCandidateSelection, tauPlot.oneProng))
    postfix = "_5AfterOneProng"
    drawPlot(createPlot(td.clone(varexp="taus_p4.Pt()>>tmp(25,0,250)")),
             "tauPt" + postfix,
             "#tau-jet candidate p_{T} (GeV/c)",
             opts2={
                 "ymin": 0,
                 "ymax": 2
             })
    drawPlot(createPlot(td.clone(varexp="taus_p4.P()>>tmp(25,0,250)")),
             "tauP" + postfix,
             "#tau-jet candidate p (GeV/c)",
             opts2={
                 "ymin": 0,
                 "ymax": 2
             })
    drawPlot(createPlot(
        td.clone(varexp="taus_leadPFChargedHadrCand_p4.Pt()>>tmp(25,0,250)")),
             "tauLeadingTrackPt" + postfix,
             "#tau-jet ldg. charged particle p_{T} (GeV/c)",
             opts2={
                 "ymin": 0,
                 "ymax": 2
             })
    drawPlot(createPlot(
        td.clone(varexp="taus_leadPFChargedHadrCand_p4.P()>>tmp(25,0,250)")),
             "tauLeadingTrackP" + postfix,
             "#tau-jet ldg. charged particle p (GeV/c)",
             opts2={
                 "ymin": 0,
                 "ymax": 2
             })
    drawPlot(createPlot(td.clone(varexp=tauPlot.rtauExp +
                                 ">>tmp(22, 0, 1.1)")),
             "rtau" + postfix,
             "R_{#tau} = p^{ldg. charged particle}/p^{#tau jet}",
             ylabel="Events / %.1f",
             opts={
                 "ymin": 1e-2,
                 "ymaxfactor": 5
             },
             moveLegend={"dx": -0.4},
             cutLine=0.7)

    # Full id
    td = treeDraw.clone(
        selection=And(tauPlot.tauCandidateSelection, tauPlot.tauID))
    postfix = "_6AfterTauID"
    drawPlot(createPlot(td.clone(varexp=tauPlot.decayModeExp)),
             "tauDecayMode" + postfix + "",
             "",
             opts={
                 "ymin": 1e-2,
                 "ymaxfactor": 20,
                 "nbins": 5
             },
             opts2={
                 "ymin": 0,
                 "ymax": 3
             },
             moveLegend={
                 "dy": 0.02,
                 "dh": -0.02
             },
             function=tauPlot.decayModeCustomize)