Beispiel #1
0
def getCustomisedHisto(datasets, h, bIsTH2):

    if bIsTH2:
        print "*** Disabling bMCUncertainty and bStackHistos for TH2 plots"
        bAddMCUncertainty = False
        bStackHistos = False
    else:
        bAddMCUncertainty = True
        bStackHistos = True

    # Determine number of Data/MC datasets present
    nDataDatasets = len(datasets.getDataDatasets())
    nMCDatasets = len(datasets.getMCDatasets())

    # Sanity check for Ratio plot. If no MC datasets are found disable it (overwrite user-defined options)
    if nMCDatasets < 1:
        h.bRatio == False
        #print "%snMCDatasets = %i" % (" "*0, nMCDatasets)
    if h.yMin is not None and h.yMax is not None:
        drawPlot = plots.PlotDrawer(stackMCHistograms=bStackHistos,
                                    addMCUncertainty=bAddMCUncertainty,
                                    log=h.bLogY,
                                    ratio=h.bRatio,
                                    addLuminosityText=True,
                                    ratioYlabel="Ratio",
                                    opts={
                                        "ymin": h.yMin,
                                        "ymax": h.yMax
                                    },
                                    opts2={
                                        "ymin": yMinRatio,
                                        "ymax": yMaxRatio
                                    },
                                    optsLog={
                                        "ymin": h.yMin,
                                        "ymax": h.yMax
                                    })
    else:
        drawPlot = plots.PlotDrawer(stackMCHistograms=bStackHistos,
                                    addMCUncertainty=bAddMCUncertainty,
                                    log=h.bLogY,
                                    ratio=h.bRatio,
                                    addLuminosityText=True,
                                    ratioYlabel="Ratio",
                                    opts={"ymaxfactor": yMaxFactor},
                                    opts2={
                                        "ymin": yMinRatio,
                                        "ymax": yMaxRatio
                                    },
                                    optsLog={
                                        "ymin": 1E-01,
                                        "ymaxfactor": yMaxFactorLog
                                    })

    return drawPlot
def dataMCExample(datasets):
    # Create data-MC comparison plot, with the default
    # - legend labels (defined in plots._legendLabels)
    # - plot styles (defined in plots._plotStyles, and in styles)
    # - drawing styles ('HIST' for MC, 'EP' for data)
    # - legend styles ('L' for MC, 'P' for data)
    plot = plots.DataMCPlot(datasets,
                            #"ForDataDrivenCtrlPlots/SelectedTau_pT_AfterStandardSelections"
                            "tauPt",
                            # Since the data datasets were removed, we have to set the luminosity by hand
                             normalizeToLumi=20000
    )

    # Same as below, but more compact
    plots.drawPlot(plot, "taupt", xlabel="Tau p_{T} (GeV/c)", ylabel="Number of events",
                   rebin=10, stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True,
                   opts={"ymin": 1e-1, "ymaxfactor": 10}, log=True)


    drawPlot = plots.PlotDrawer(stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True, opts={"ymin": 1e-1, "ymaxfactor": 10})

    def createDrawPlot(name, **kwargs):
        drawPlot( plots.DataMCPlot(datasets, name, normalizeToLumi=20000), name, **kwargs)

    createDrawPlot("tauEta", xlabel="", ylabel="Number of events", rebin=1, log=False)
    createDrawPlot("Met", xlabel="E_{T}^{miss} (GeV)", ylabel="Number of events", rebin=1, log=True)
    createDrawPlot("MetPhi", xlabel="#Phi^{miss} ", ylabel="Number of events", rebin=1, log=False)
    createDrawPlot("jetPt", xlabel="p_{T}^{jet} (GeV/c)", ylabel="Number of events", rebin=1, log=True)
    createDrawPlot("jetEta", xlabel="", ylabel="Number of events", rebin=1, log=False)
    createDrawPlot("jetPhi", xlabel="#Phi^{jet}", ylabel="Number of events", rebin=1, log=False)
def 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
Beispiel #4
0
def doQcdPurPlots(p, drawPlot, datasets, hExpr, hName, xLabel, yLabel,
                  SaveExtension):

    if getBool("bRemoveEwk"):
        print "*** WARNING: No Ewk samples found. Skipping QCD Purity plots."
        return

    histograms.createLegend.setDefaults(x1=xLegMin * (0.90),
                                        x2=xLegMax * (0.95),
                                        y1=yLegMin,
                                        y2=yLegMax * 1.2)
    saveName = "%s_%s" % (hName, SaveExtension + "_QcdPurity")

    ### Setup the histogram text mode and create plot
    p2 = createTH1Plot(datasets, hExpr, normalizeToOne=False)

    ### Define the purity histogram binning
    Bins = [40.0, 50.0, 60.0, 70.0, 80.0, 100.0, 120.0, 150.0, 200.0]
    myBins = array.array('d', Bins)

    ### Loop over all histograms to determine the number of signal and bkg events to calculate qcdPurity
    for htmp in p.histoMgr.getHistos():
        name = htmp.getName()
        h = htmp.getRootHisto().Rebin(len(myBins) - 1, name, myBins)
        htmp.setRootHisto(h)

        if (name in "Data"):
            hQcdPur = p.histoMgr.getHisto("Data").getRootHisto().Clone(
                "hQcdPur")
            p2.histoMgr.removeHisto(name)
        elif (name in ["TTToHplus", "QCD"]):
            p2.histoMgr.removeHisto(name)
        else:
            hQcdPur.Add(h, -1)
            p2.histoMgr.removeHisto(name)

    hQcdPur.Divide(p.histoMgr.getHisto("Data").getRootHisto())
    Purity = histograms.Histo(setQcdPurityHistoStyle(hQcdPur),
                              "Purity = #frac{Data-Ewk MC}{Data}", "", "")
    p2.histoMgr.appendHisto(Purity)

    ### Draw the plot with custom options and save
    drawPlot = plots.PlotDrawer(stackMCHistograms=getBool("bStackHistos"),
                                addMCUncertainty=getBool("bAddMCUncertainty"),
                                log=False,
                                ratio=getBool("bStackHistos"),
                                addLuminosityText=getBool("bAddLumiText"),
                                opts={
                                    "ymin": yMinPurity,
                                    "ymax": yMaxPurity
                                })
    drawPlot(p2, saveName, rebin=1, xlabel=xLabel, ylabel=yLabel)

    return
def doPlots(datasets):
    def createPlot(name, **kwargs):
        return plots.DataMCPlot(datasets, name, **kwargs)

    drawPlot = plots.PlotDrawer(stackMCHistograms=True,
                                addMCUncertainty=True,
                                log=True,
                                ratio=True,
                                addLuminosityText=True,
                                ratioYlabel="Ratio",
                                optsLog={"ymin": 1e-1},
                                opts2={
                                    "ymin": 0,
                                    "ymax": 2
                                })

    selections = [
        ("Full_", And(muonSelection, muonVeto, electronVeto, jetSelection)),
        #        ("FullNoIso_", And(muonSelectionNoIso, muonVetoNoIso, electronVeto, jetSelectionNoIso)),
        #        ("Analysis_", "&&".join([muonSelection, muonVeto, electronVeto, jetSelection, metcut, btagging])),
    ]

    for name, selection in selections:
        tdMuon = treeDraw.clone(selection=selection)

        histograms.cmsTextMode = histograms.CMSMode.PRELIMINARY
        td = tdMuon.clone(varexp="muons_p4.Pt() >>tmp(40,0,400)")
        drawPlot(createPlot(td),
                 name + "muon_pt_log",
                 "Muon ^{}p_{T} (GeV/c)",
                 ylabel="Events / %.0f GeV/c",
                 cutBox={
                     "cutValue": 40,
                     "greaterThan": True
                 })

        histograms.cmsTextMode = histograms.CMSMode.NONE
        td = tdMuon.clone(varexp="pfMet_p4.Pt() >>tmp(40,0,400)")
        drawPlot(createPlot(td),
                 name + "met_log",
                 "Uncorrected PF ^{}E_{T}^{miss} (GeV)",
                 ylabel="Events / %.0f GeV")

        td = tdMuon.clone(
            varexp=
            "sqrt(2 * muons_p4.Pt() * pfMet_p4.Et() * (1-cos(muons_p4.Phi()-pfMet_p4.Phi()))) >>tmp(40,0,400)"
        )
        drawPlot(createPlot(td),
                 name + "mt_log",
                 "m_{T}(#mu, ^{}E_{T}^{miss}) (GeV/^{}c^{2})",
                 ylabel="Events / %.0f GeV/^{}c^{2}")
Beispiel #6
0
        if outputDir is not None:
            outputDir += "_embdatamc"
        doPlots(datasetsEmb, outputDir)

        tauEmbedding.writeToFile(outputDir, "input.txt",
                                 "Embedded: %s\n" % os.getcwd())


drawPlotCommon = plots.PlotDrawer(
    ylabel="Events / %.0f",
    stackMCHistograms=True,
    log=True,
    addMCUncertainty=True,
    opts2={
        "ymin": 0,
        "ymax": 2
    },
    ratio=True,
    ratioType="errorScale",
    ratioCreateLegend=True,
    ratioYlabel="Data/Sim.",
    ratioErrorOptions={"numeratorStatSyst": False},
    addLuminosityText=True)


def doPlots(datasetsEmb, outputDir):
    lumi = datasetsEmb.getDataset("Data").getLuminosity()

    def createPlot(name):
        #        p = plots.DataMCPlot(datasetsEmb, systematicsEmbMC.histogram(name), normalizeToLumi=lumi)
        drhData = datasetsEmb.getDataset("Data").getDatasetRootHisto(name)
def doPlots(datasets, datasetName, selectionName, ntupleCache):
    createPlot = PlotCreator(datasets, datasetName, ntupleCache)

    drawPlot = plots.PlotDrawer(addMCUncertainty=True,
                                log=True,
                                stackMCHistograms=False,
                                ratio=True,
                                ratioInvert=True,
                                optsLog={"ymin": 1e-1},
                                opts2={
                                    "ymin": 0.9,
                                    "ymax": 1.02
                                })

    def customize(p):
        p.setRatios([
            plots._createRatio(p.numeratorRaw,
                               p.denominatorRaw,
                               ytitle="Fraction",
                               isBinomial=True)
        ])

    def createDrawPlot(histo, fname, xlabel, **kwargs):
        p = createPlot(histo)
        drawPlot(p, fname, xlabel, customizeBeforeDraw=customize, **kwargs)

    #opts2def = {"DYJetsToLL": {"ymin":0, "ymax": 1.5}}.get(datasetName, {"ymin": 0.9, "ymax": 1.02})
    #moveLegend = {"DYJetsToLL": {"dx": -0.02}}.get(datasetName, {})
    opts2def = {}
    moveLegend = {}

    if selectionName != "TauLike":
        opts2def["ymin"] = 0.98
        opts2def["ymax"] = 1.005

    prefix = "muiso_" + selectionName + "_"
    postfix = "_" + datasetName

    opts2 = opts2def
    createDrawPlot("tauPt",
                   prefix + "TauPt" + postfix,
                   "#tau-jet p_{T} (GeV/c)",
                   ylabel="Events / %.0f GeV/c",
                   opts2=opts2,
                   cutLine=40,
                   moveLegend=moveLegend)

    createDrawPlot("tauEta",
                   prefix + "TauEta" + postfix,
                   "#tau-jet #eta",
                   ylabel="Events / %.1f",
                   opts2=opts2,
                   cutLine=[-2.1, 2.1],
                   moveLegend=moveLegend)

    createDrawPlot("tauPhi",
                   prefix + "TauPhi" + postfix,
                   "#tau-jet #phi",
                   ylabel="Events / %.1f",
                   opts2=opts2,
                   moveLegend=moveLegend)

    createDrawPlot("tauLeadingTrackPt",
                   prefix + "TauLeadingTrackPt" + postfix,
                   "#tau-jet leading ch. cand. p_{T} (GeV/c)",
                   ylabel="Events / %.0f GeV/c",
                   opts2=opts2,
                   cutLine=20,
                   moveLegend=moveLegend)

    createDrawPlot("tauRtau",
                   prefix + "TauRtau" + postfix,
                   "#tau-jet R_{#tau}",
                   ylabel="Events / %.1f",
                   opts2=opts2,
                   cutLine=0.7,
                   moveLegend=moveLegend)

    createDrawPlot("vertexCount",
                   prefix + "VertexCount" + postfix,
                   "Number of good PV",
                   ylabel="Events / %.0f",
                   opts2=opts2,
                   moveLegend=moveLegend)
Beispiel #8
0
def doSignifPlots(p, drawPlot, datasets, histo, hName, xLabel, yLabel,
                  saveName, cutDir):
    '''
    def doSignifPlots(p, drawPlot, datasets, histo, hName, xLabel, yLabel, saveName, CutDir):
    '''

    nDataDatasets = len(datasets.getDataDatasets())
    nMCDatasets = len(datasets.getMCDatasets())

    if nMCDatasets < 1:
        print "*** WARNING: No MC datasets found. Skipping significance plots."
        return

    if cutDir == "<":
        saveName = saveName + "_SignifLessThan"
        saveName = saveName.replace("/", "_")
        MyIntegral = lambda h, bin: h.Integral(0, bin)
    elif cutDir == ">":
        saveName = saveName + "_SignifGreaterThan"
        saveName = saveName.replace("/", "_")
        MyIntegral = lambda h, bin: h.Integral(bin, nBins)
    else:
        print "%sERROR! Unsupported cut-direction string %s used. Exiting ROOT" % (
            cutDir)
        sys.exit()
    yLabel = "Significance" + "(" + cutDir + ")"

    # Legend and save-name
    histograms.createLegend.setDefaults(x1=0.65, x2=0.90, y1=0.8, y2=0.92)

    ### Setup the histogram text mode and create plot
    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    p2 = createTH1Plot(datasets, hName, normalizeToOne=False)

    ### Construct an empty histogram (same binning as variable distribution)
    hBinSignif = p.histoMgr.getHisto(
        "TTToHplus_M" + signalMass).getRootHisto().Clone(saveName + "_Clone")
    hBinSignif.Reset()
    nBinsX = hBinSignif.GetNbinsX()
    nBins = nBinsX + 1

    ### Loop over all histogram bins
    for iBin in xrange(0, nBins):
        ### Initialise variables to be used in Significance calculation
        nSignal = 0
        nBackgr = 0
        signifError = 0
        signifValue = 0
        # Loop over all histograms to determine the number of signal and bkg events to calculate significance
        for htmp in p.histoMgr.getHistos():
            h = htmp.getRootHisto()
            name = htmp.getName()
            if ("Data" in name or "sum_errors" in name):
                continue
            elif ("TTToHplus_M" + signalMass in name):
                #print "*** Signal-Histo = ", (name)
                nSignal = MyIntegral(h, iBin)
            else:
                if name == "StackedMC":
                    hStackedMC = p.histoMgr.getHisto(
                        "StackedMC").getRootHisto().Clone("hStackedMC_Clone")
                    for htmp in hStackedMC.GetHists():
                        name = htmp.GetName()
                        if ("MCuncertainty") in name:
                            continue
                        #print "*** Bkg-Histo = ", (name)
                        nBackgr += MyIntegral(htmp, iBin)
                        eBackgr = 0  #FIXME
                else:
                    if ("MCuncertainty") in name:
                        continue
                    #print "*** Bkg-Histo = ", (name)
                    nBackgr += MyIntegral(h, iBin)
                    eBackgr = 0  #FIXME

        if nSignal < 9e-04:
            nSignal = 0.0
        if nBackgr > 0:  #FIXME
            signifValue = math.sqrt(
                2 * ((nSignal + nBackgr) * math.log(1 + (nSignal / nBackgr)) -
                     nSignal))  #G. Cowan (sysErrorBackgr=0)
            signifError = 0.0001  #FIXME
        else:
            signifValue = 0
            signifError = 0.0001  #FIXME

        # Calculate error on significance
        if nSignal > 0 and nBackgr > 0:
            #signifErrorSquared = ( (1+2*math.log(1+nSignal/nBackgr)/(2*signifValue) )**2)*nSignal + ( ( (2*math.log(1+nSignal/nBackgr) - 2*nSignal/nBackgr)/(2*signifValue**2) )**2)**nBackgr
            #signifErrorSquared = ((signifValue/nSignal)**2)*nSignal + ((0.5*(signifValue/nBackgr))**2)*nBackgr
            #signifError = math.sqrt(signifErrorSquared)
            signifError = 0.0001
        else:
            signifError = 0.0001
        #print " nSignal = %s, nBackgr = %s, signifValue = %s, signifError = %s" % (nSignal, nBackgr, signifValue, signifError) #attikis
        #print "*** iBin=%s ; Sig=%s ; S=%s ; B=%s" % (iBin, signifValue, nSignal, nBackgr)
        hBinSignif.SetBinContent(iBin, signifValue)
        hBinSignif.SetBinError(iBin, signifError)

    # Loop over histograms and remove all histos
    for htmp in p2.histoMgr.getHistos():
        h = htmp.getRootHisto()
        name = htmp.getName()
        if name == "StackedMC":
            hStackedMC = p.histoMgr.getHisto("StackedMC").getRootHisto().Clone(
                "hStackedMC_Clone")
            for htmp in hStackedMC.GetHists():
                p2.histoMgr.removeHisto(name)
        else:
            p2.histoMgr.removeHisto(name)

    ### Add the significance plots to the histo-manager
    h = histograms.Histo(setSignificanceHistoStyle(hBinSignif),
                         "      m_{H^{#pm}} = " + signalMass + " GeV/c^{2}",
                         "HP", "HP")
    h.setIsDataMC(False, True)
    p2.histoMgr.appendHisto(h)

    ### Draw the plot with custom options and save
    drawPlot = plots.PlotDrawer(stackMCHistograms=False,
                                addMCUncertainty=False,
                                log=False,
                                ratio=False,
                                addLuminosityText=True,
                                opts={"ymaxfactor": 1.2})
    drawPlot(p2,
             saveName,
             xlabel=histo.xlabel,
             ylabel=yLabel,
             rebinToWidthX=histo.binWidthX,
             cutLine=getHistoCutLines(histo))

    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()
    dop("SingleTop", mtOnly=False)
    dop("Diboson", mtOnly=False)


#    dop("DYJetsToLL", mtOnly=True)
#    dop("SingleTop", mtOnly=True)
#    dop("Diboson", mtOnly=True)

#drawPlotCommon = tauEmbedding.PlotDrawerTauEmbeddingEmbeddedNormal(ylabel="Events / %.0f GeV", stackMCHistograms=False, log=True, addMCUncertainty=True, ratio=True, addLuminosityText=True)
drawPlotCommon = plots.PlotDrawer(ylabel="Events / %.0f",
                                  stackMCHistograms=False,
                                  log=True,
                                  addMCUncertainty=True,
                                  ratio=True,
                                  ratioType="errorScale",
                                  ratioCreateLegend=True,
                                  opts2={
                                      "ymin": 0,
                                      "ymax": 2
                                  },
                                  addLuminosityText=True,
                                  errorBarsX=True)


def strIntegral(th1):
    return "%.1f" % aux.th1Integral(th1)


def doPlots(datasetsEmb,
            datasetsSig,
            datasetName,
def doPlots(myDsetMgr, opts, mySuffix):
    # Create the plot objects and pass them to the formatting
    # functions to be formatted, drawn and saved to files
    drawPlot = plots.PlotDrawer(ylabel="N_{events}",
                                log=True,
                                ratio=True,
                                ratioYlabel="Data/MC",
                                opts2={
                                    "ymin": 0,
                                    "ymax": 2
                                },
                                stackMCHistograms=True,
                                addMCUncertainty=True,
                                addLuminosityText=True)

    global plotIndex
    plotIndex = 1

    def createDrawPlot(name,
                       moveSignalText={},
                       fullyBlinded=False,
                       addBlindedText=True,
                       moveBlindedText={},
                       **kwargs):
        # Create the plot object
        print "Creating plot:", name
        args = {}
        if mcOnly:
            args["normalizeToLumi"] = mcOnlyLumi
        p = plots.DataMCPlot(myDsetMgr, name, **args)

        # Remove data if fully blinded
        if not mcOnly and fullyBlinded and p.histoMgr.hasHisto("Data"):
            p.histoMgr.removeHisto("Data")
            if addBlindedText:
                tb = histograms.PlotTextBox(xmin=0.4,
                                            ymin=None,
                                            xmax=0.6,
                                            ymax=0.84,
                                            size=17)
                tb.addText("Data blinded")
                tb.move(**moveBlindedText)
                p.appendPlotObject(tb)

        # Add the signal information text box
        if not opts.noSignal:
            st = histograms.createSignalText()
            st.move(**moveSignalText)
            p.appendPlotObject(st)

        # Set the file name
        global plotIndex
        filename = "%s/%03d_%s" % (mySuffix, plotIndex, name.replace("/", "_"))
        plotIndex += 1

        # Draw the plot
        drawPlot(p, filename, **kwargs)

    # common arguments for plots which make sense only for MC
    mcArgs = {"fullyBlinded": True, "addBlindedText": False}

    # Common plots
    myCommonPlotDirs = [
        "VertexSelection", "TauSelection", "TauWeight", "ElectronVeto",
        "MuonVeto", "JetSelection", "MET", "BTagging", "Selected",
        "FakeTaus_BTagging", "FakeTaus_Selected"
    ]

    def createDrawCommonPlot(path, **kwargs):
        for plotDir in myCommonPlotDirs:
            args = {}
            args.update(kwargs)
            if "transverseMass" in path:
                if "BTagging" in plotDir or "Selected" in plotDir:
                    args[
                        "customizeBeforeFrame"] = lambda p: plots.partiallyBlind(
                            p, maxShownValue=60)
            elif "Selected" in plotDir:
                args["fullyBlinded"] = True
            if "FakeTaus" in plotDir:
                args.update(mcArgs)
            createDrawPlot(path % plotDir, **args)

    #phiBinWidth = 2*3.14159/72
    phiBinWidth = 2 * 3.14159 / 36

    myDirs = [
        "NormalisationAnalysis/DYEnrichedWithGenuineTaus",
        "NormalisationAnalysis/DYEnrichedWithFakeTaus",
        "NormalisationAnalysis/WJetsEnrichedWithGenuineTaus",
        "NormalisationAnalysis/WJetsEnrichedWithFakeTaus",
        "NormalisationAnalysis/TTJetsEnrichedWithGenuineTaus",
        "NormalisationAnalysis/TTJetsEnrichedWithFakeTaus"
    ]
    for myDir in myDirs:
        createDrawPlot(myDir + "/tauPt", xlabel="#tau p_{T}, GeV/c")
        createDrawPlot(myDir + "/nJets", xlabel="N_{jets}")
        createDrawPlot(myDir + "/met", xlabel="E_{T}^{miss}, GeV")
        createDrawPlot(myDir + "/metPhi", xlabel="E_{T}^{miss} #phi, GeV")
        createDrawPlot(myDir + "/nBJets", xlabel="N_{b jets}")
        createDrawPlot(myDir + "/transverseMass",
                       xlabel="m_T(#tau,E_{T}^{miss}), GeV/c^{2}")
        createDrawPlot(myDir + "/zMass", xlabel="m_Z(#ell#ell), GeV/c^{2}")
        createDrawPlot(myDir + "/fakeTauTauPt", xlabel="#tau p_{T}, GeV/c")
        createDrawPlot(myDir + "/fakeTauNJets", xlabel="N_{jets}")
        createDrawPlot(myDir + "/fakeTauMet", xlabel="E_{T}^{miss}, GeV")
        createDrawPlot(myDir + "/fakeTauMetPhi",
                       xlabel="E_{T}^{miss} #phi, GeV")
        createDrawPlot(myDir + "/fakeTauNBJets", xlabel="N_{b jets}")
        createDrawPlot(myDir + "/fakeTauTransverseMass",
                       xlabel="m_T(#tau,E_{T}^{miss}), GeV/c^{2}")
        createDrawPlot(myDir + "/fakeTauZMass",
                       xlabel="m_Z(#ell#ell), GeV/c^{2}")
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.
    '''

    # Function to create the plots
    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..    
    '''
        p = plots.DataMCPlot(datasets, name, **kwargs)
        p.setDefaultStyles()
        return p

    print "\n*** Cuts to be applied: %s" % (MyCuts)

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

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

    # Customise my plots
    drawPlot = plots.PlotDrawer(stackMCHistograms=True,
                                addMCUncertainty=True,
                                log=True,
                                ratio=False,
                                addLuminosityText=True,
                                ratioYlabel="Ratio",
                                optsLog={"ymin": 1e-1},
                                opts2={
                                    "ymin": 0,
                                    "ymax": 2
                                })

    # Define the tree to be used with the standard cuts
    MyTreeDraw = treeDraw.clone(selection=MyCuts)

    # Loop over all hName and expressions in the dictionary "histoDict"
    counter = 0
    for hName in histoDict:
        #print "*** Plotted \"%s\": %s" % (hName, histoDict[hName])
        histo = MyTreeDraw.clone(varexp=histoDict[hName])
        drawPlot(createPlot(histo),
                 "%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 #13
0
def doPlots(myDsetMgr, opts, mySuffix, isSystematicVariation):
    # Create the plot objects and pass them to the formatting
    # functions to be formatted, drawn and saved to files
    drawPlot = plots.PlotDrawer(ylabel="N_{events}", log=True, ratio=True, ratioYlabel="Data/MC", opts2={"ymin": 0, "ymax": 2}, stackMCHistograms=True, addMCUncertainty=True, addLuminosityText=True)

    global plotIndex
    plotIndex = 1
    def createDrawPlot(name, moveSignalText={}, fullyBlinded=False, addBlindedText=True, moveBlindedText={}, forSystVar=False, **kwargs):
        if isSystematicVariation and not forSystVar:
            return
        # Create the plot object
        print "Creating plot:",name
        args = {}
        if mcOnly:
            args["normalizeToLumi"] = mcOnlyLumi
        p = plots.DataMCPlot(myDsetMgr, name, **args)

        # Remove data if fully blinded
        if not mcOnly and fullyBlinded and p.histoMgr.hasHisto("Data"):
            p.histoMgr.removeHisto("Data")
            if addBlindedText:
                tb = histograms.PlotTextBox(xmin=0.4, ymin=None, xmax=0.6, ymax=0.84, size=17)
                tb.addText("Data blinded")
                tb.move(**moveBlindedText)
                p.appendPlotObject(tb)

        # Add the signal information text box
        if not opts.noSignal:
            st = histograms.createSignalText()
            st.move(**moveSignalText)
            p.appendPlotObject(st)

        # Set the file name
        global plotIndex
        filename = "%s/%03d_%s"%(mySuffix, plotIndex, name.replace("/", "_"))
        plotIndex += 1

        # Draw the plot
        drawPlot(p, filename, **kwargs)

    # common arguments for plots which make sense only for MC
    mcArgs = {"fullyBlinded": True, "addBlindedText": False, "ratio": False}

    # Common plots
    myCommonPlotDirs = ["TauSelection","TauWeight","ElectronVeto","MuonVeto","JetSelection","MET","BTagging","Selected","FakeTaus_BTagging","FakeTaus_Selected"]
    def createDrawCommonPlot(path, **kwargs):
        for plotDir in myCommonPlotDirs:
            args = {}
            
            if opts.blind:
                if "transverseMass" in path:
                    if "BTagging" in plotDir or "Selected" in plotDir:
                        args["customizeBeforeFrame"] = lambda p: plots.partiallyBlind(p, maxShownValue=60)
                elif "fullMass" in path:
                    if "JetSelection" in plotDir or "MET" in plotDir or "BTagging" in plotDir or "Selected" in plotDir:
                        args["customizeBeforeFrame"] = lambda p: plots.partiallyBlind(p, minShownValue=80, maxShownValue=180, invert=True)
                elif "Selected" in plotDir:
                    args["fullyBlinded"] = True
            if "FakeTaus" in plotDir:
                args.update(mcArgs)
            args.update(kwargs)
            createDrawPlot(path%plotDir, **args)

    #phiBinWidth = 2*3.14159/72
    phiBinWidth = 2*3.14159/36

    #createDrawPlot("CommonPlots/AtEveryStep/Trigger/nVertices", xlabel="N_{Vertices}")
    if True:
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/nVertices", xlabel="N_{Vertices}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/tau_fakeStatus", xlabel="Fake tau status", **mcArgs)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/tau_pT", xlabel="#tau p_{T}, GeV/c", rebinToWidthX=20)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/tau_eta", xlabel="#tau #eta")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/tau_phi", xlabel="#tau #phi", rebinToWidthX=phiBinWidth)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/tau_Rtau", xlabel="R_{#tau}", rebinToWidthX=0.05, opts={"xmin": 0.5, "xmax": 1}, moveLegend={"dx": -0.5})
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/electrons_N", xlabel="N_{electrons}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/muons_N", xlabel="N_{muons}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/jets_N", xlabel="N_{jets}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/jets_N_allIdentified", xlabel="N_{all identified jets}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/MET_Raw", xlabel="Raw MET, GeV", rebinToWidthX=20)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/MET_MET", xlabel="MET, GeV", rebinToWidthX=20)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/MET_phi", xlabel="MET #phi", rebinToWidthX=phiBinWidth)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/bjets_N", xlabel="N_{b jets}", opts={"xmax": 8})
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/DeltaPhi_TauMET", xlabel="#Delta#phi(#tau,MET)")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/hDeltaR_TauMETJet1MET", xlabel="#sqrt{(180^{o}-#Delta#phi(#tau,MET))^{2} + #Delta#phi(MET,jet_{1})^{2}}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/hDeltaR_TauMETJet2MET", xlabel="#sqrt{(180^{o}-#Delta#phi(#tau,MET))^{2} + #Delta#phi(MET,jet_{2})^{2}}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/hDeltaR_TauMETJet3MET", xlabel="#sqrt{(180^{o}-#Delta#phi(#tau,MET))^{2} + #Delta#phi(MET,jet_{3})^{2}}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/hDeltaR_TauMETJet4MET", xlabel="#sqrt{(180^{o}-#Delta#phi(#tau,MET))^{2} + #Delta#phi(MET,jet_{4})^{2}}")
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/transverseMass", xlabel="m_{T}(#tau,MET)", rebinToWidthX=20)
        createDrawCommonPlot("CommonPlots/AtEveryStep/%s/fullMass", xlabel="m_{T}(#tau,MET)", rebinToWidthX=20)

    myDir = "Vertices"
    createDrawPlot(myDir+"/verticesBeforeWeight", xlabel="N_{vertices}")
    createDrawPlot(myDir+"/verticesAfterWeight", xlabel="N_{vertices}")
    #createDrawPlot(myDir+"/verticesTriggeredBeforeWeight", xlabel="N_{vertices}")
    #createDrawPlot(myDir+"/verticesTriggeredAfterWeight", xlabel="N_{vertices}")
    myDir = "TauSelection"
    createDrawPlot(myDir+"/N_TriggerMatchedTaus", xlabel="N_{trg. matched taus}")
    createDrawPlot(myDir+"/N_TriggerMatchedSeparateTaus", xlabel="N_{trg. matched separate taus}")
    createDrawPlot(myDir+"/TauCand_DecayModeFinding", xlabel="HPS Decay Mode", opts={"xmax": 16, "nbinsx": 16}, customizeBeforeDraw=tauEmbedding.decayModeCheckCustomize)
    createDrawPlot(myDir+"/TauSelection_all_tau_candidates_N", xlabel="N_{tau candidates}", opts={"xmax": 8})
    createDrawPlot(myDir+"/TauSelection_all_tau_candidates_pt", xlabel="p_{T} of all tau candidates, GeV/c", rebinToWidthX=10)
    createDrawPlot(myDir+"/TauSelection_all_tau_candidates_eta", xlabel="#eta of all tau candiates", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/TauSelection_all_tau_candidates_phi", xlabel="#phi of all tau candidates", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/TauSelection_all_tau_candidates_MC_purity", xlabel="MC purity of all tau candidates", **mcArgs)
    createDrawPlot(myDir+"/TauCand_JetPt", xlabel="p_{T} of tau candidates, GeV/c", rebinToWidthX=10)
    createDrawPlot(myDir+"/TauCand_JetEta", xlabel="#eta of tau candidates", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/TauCand_LdgTrackPtCut", xlabel="p_{T}^{ldg.ch.particle} of tau candidates, GeV/c", rebinToWidthX=10)
    #createDrawPlot(myDir+"/TauCand_EMFractionCut", xlabel="EM energy fraction of tau candidates")
    createDrawPlot(myDir+"/TauSelection_cleaned_tau_candidates_N", xlabel="N_{cleaned tau candidates}", opts={"xmax": 8})
    createDrawPlot(myDir+"/TauSelection_cleaned_tau_candidates_pt", xlabel="p_{T} of cleaned tau candidates, GeV/c", rebinToWidthX=10)
    createDrawPlot(myDir+"/TauSelection_cleaned_tau_candidates_eta", xlabel="#eta of cleaned tau candidates", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/TauSelection_cleaned_tau_candidates_phi", xlabel="#phi of cleaned tau candidates", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/TauSelection_cleaned_tau_candidates_MC_purity", xlabel="MC purity of cleaned tau candidates", **mcArgs)
    createDrawPlot(myDir+"/IsolationPFChargedHadrCandsPtSum", xlabel="#sum p_{T} of PF ch. hadr. candidates, GeV/c", opts={"xmax": 40})
    createDrawPlot(myDir+"/IsolationPFGammaCandEtSum", xlabel="#sum p_{T} of PF gamma candidates, GeV/c", opts={"xmax": 40})
    createDrawPlot(myDir+"/TauID_NProngsCut", xlabel="N_{prongs}", opts={"xmax": 5})
    #createDrawPlot(myDir+"/TauID_ChargeCut", xlabel="Q_{tau}")
    createDrawPlot(myDir+"/TauID_RtauCut", xlabel="R_{#tau}", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/TauSelection_selected_taus_N", xlabel="N_{selected taus}", opts={"xmax": 8})
    createDrawPlot(myDir+"/TauSelection_selected_taus_pt", xlabel="p_{T} of selected taus", rebinToWidthX=10)
    createDrawPlot(myDir+"/TauSelection_selected_taus_eta", xlabel="#eta of selected taus", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/TauSelection_selected_taus_phi", xlabel="#phi of selected taus", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/TauSelection_selected_taus_MC_purity", xlabel="MC purity of selected taus", **mcArgs)
    myDir = "FakeTauIdentifier_TauID"
    createDrawPlot(myDir+"/TauMatchType", xlabel="MC #tau decay", **mcArgs)
    createDrawPlot(myDir+"/TauOrigin", xlabel="MC #tau origin", **mcArgs)
    createDrawPlot(myDir+"/MuOrigin", xlabel="MC #mu origin", **mcArgs)
    createDrawPlot(myDir+"/ElectronOrigin", xlabel="MC e origin", **mcArgs)
    myDir = "SelectedTau"
    createDrawPlot(myDir+"/SelectedTau_pT_AfterTauID", xlabel="p_{T} of selected taus, GeV/c", rebinToWidthX=10)
    createDrawPlot(myDir+"/SelectedTau_eta_AfterTauID", xlabel="#eta of selected taus", rebinToWidthX=0.1, opts={"xmin": -2.4, "xmax": 2.4})
    createDrawPlot(myDir+"/SelectedTau_phi_AfterTauID", xlabel="#phi of selected taus", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/SelectedTau_Rtau_AfterTauID", xlabel="R_{#tau} of selected taus", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/SelectedTau_pT_AfterCuts", xlabel="p_{T} of tau after selections, GeV/c", rebinToWidthX=10)
    createDrawPlot(myDir+"/SelectedTau_eta_AfterCuts", xlabel="#eta of tau after selections", rebinToWidthX=0.1)
    createDrawPlot(myDir+"/SelectedTau_Rtau_AfterCuts", xlabel="R_{#tau} of tau after selections", rebinToWidthX=0.1, moveLegend={"dx": -0.5})
    myDir = "ElectronSelection"
    createDrawPlot(myDir+"/ElectronPt_all", xlabel="p_{T} of electron candidates, GeV/c", rebinToWidthX=5)
    createDrawPlot(myDir+"/ElectronEta_all", xlabel="#eta of electron candidates")
    createDrawPlot(myDir+"/ElectronPt_veto", xlabel="p_{T}^{veto electron} (GeV/c)", ylabel="Identified electrons / %.0f GeV/c", opts={"xmax": 250,"xmin": 0, "ymaxfactor": 2}, cutLine=15)
    createDrawPlot(myDir+"/ElectronEta_veto", xlabel="#eta^{veto electron}", ylabel="Identified electrons / %.1f", opts={"xmin": -3,"ymin": 0.1, "xmax": 3, "ymaxfactor": 10}, moveLegend={"dy":0.01, "dx":-0.07, "dh":-0.06}, cutLine=[-2.5, 2.5])
    createDrawPlot(myDir+"/NumberOfVetoElectrons", xlabel="Number of selected veto electrons", ylabel="Events", opts={"xmax": 6,"ymaxfactor": 2})
    createDrawPlot(myDir+"/ElectronPt_tight", xlabel="p_{T}^{tight electron} (GeV/c)", ylabel="Identified electrons / %.0f GeV/c", opts={"xmax": 250,"xmin": 0, "ymaxfactor": 2}, cutLine=15)
    createDrawPlot(myDir+"/ElectronEta_tight", xlabel="#eta^{tight electron}", ylabel="Identified electrons / %.1f", opts={"xmin": -3,"ymin": 0.1, "xmax": 3, "ymaxfactor": 10}, moveLegend={"dy":0.01, "dx":-0.07, "dh":-0.06}, cutLine=[-2.5, 2.5])
    createDrawPlot(myDir+"/NumberOfTightElectrons", xlabel="Number of selected tight electrons", ylabel="Events", opts={"xmax": 6,"ymaxfactor": 2}, cutLine=1)
    myDir = "MuonSelection"
    createDrawPlot(myDir+"/LooseMuonPt", xlabel="p_{T} of #mu candidates, GeV/c", ylabel="N_{muons}", rebinToWidthX=5)
    createDrawPlot(myDir+"/LooseMuonEta", xlabel="#eta of #mu candidates", ylabel="N_{muons}")
    createDrawPlot(myDir+"/MuonTransverseImpactParameter", xlabel="IP_{T} of #mu candidates, mm", ylabel="N_{muons}")
    createDrawPlot(myDir+"/MuonDeltaIPz", xlabel="IP_{z} - PV_{z} of #mu candidates, cm", ylabel="N_{muons}")
    createDrawPlot(myDir+"/MuonRelIsol", xlabel="#mu rel. isol.", ylabel="N_{muons}")
    createDrawPlot(myDir+"/NumberOfLooseMuons", xlabel="Number of loose #mus", opts={"xmax": 8})
    createDrawPlot(myDir+"/NumberOfTightMuons", xlabel="Number of tight #mus", opts={"xmax": 8})
    createDrawPlot(myDir+"/MuonPt_BeforeIsolation", xlabel="#mu p_{T} before isolation, GeV/c")
    createDrawPlot(myDir+"/MuonEta_BeforeIsolation", xlabel="#mu #eta before isolation")
    myDir = "JetSelection"
    createDrawPlot(myDir+"/jet_pt", xlabel="p_{T} of jet candidates, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_pt_central", xlabel="p_{T} of central jet candidates, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_eta", xlabel="#eta of jet candidates", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_phi", xlabel="#phi of jet candidates", ylabel="N_{jets}", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/firstJet_pt", xlabel="p_{T} of first jet, GeV/c")
    createDrawPlot(myDir+"/firstJet_eta", xlabel="#eta of first jet")
    createDrawPlot(myDir+"/firstJet_phi", xlabel="#phi of first jet", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/secondJet_pt", xlabel="p_{T} of second jet, GeV/c")
    createDrawPlot(myDir+"/secondJet_eta", xlabel="#eta of second jet")
    createDrawPlot(myDir+"/secondJet_phi", xlabel="#phi of second jet", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/thirdJet_pt", xlabel="p_{T} of third jet, GeV/c")
    createDrawPlot(myDir+"/thirdJet_eta", xlabel="#eta of third jet")
    createDrawPlot(myDir+"/thirdJet_phi", xlabel="#phi of third jet", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/NumberOfSelectedJets", xlabel="N_{selected jets}")
    createDrawPlot(myDir+"/jet_PUIDmva", xlabel="Jet PU ID MVA output")
    myDir = "JetSelection/SelectedJets"
    createDrawPlot(myDir+"/jet_pt", xlabel="p_{T} of accepted jets, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_eta", xlabel="#eta of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_phi", xlabel="#phi of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralEmEnergyFraction", xlabel="NeutralEmEnergyFraction of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralHadronEnergyFraction", xlabel="NeutralHadronEnergyFraction of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_PhotonEnergyFraction", xlabel="PhotonEnergyFraction of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_ChargedHadronEnergyFraction", xlabel="ChargedEnergyFraction of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralHadronMultiplicity", xlabel="NeutralHadronMultiplicity of accepted jets", ylabel="N_{jets}", opts={"xmax": 10})
    createDrawPlot(myDir+"/jet_PhotonMultiplicity", xlabel="PhotonMultiplicity of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_ChargedMultiplicity", xlabel="ChargedMultiplicity of accepted jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_PartonFlavour", xlabel="PartonFlavour of accepted jets", ylabel="N_{jets}", **mcArgs)
    myDir = "JetSelection/ExcludedJets"
    createDrawPlot(myDir+"/jet_pt", xlabel="p_{T} of rejected jets, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_eta", xlabel="#eta of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_phi", xlabel="#phi of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralEmEnergyFraction", xlabel="NeutralEmEnergyFraction of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralHadronEnergyFraction", xlabel="NeutralHadronEnergyFraction of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_PhotonEnergyFraction", xlabel="PhotonEnergyFraction of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_ChargedHadronEnergyFraction", xlabel="ChargedEnergyFraction of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_NeutralHadronMultiplicity", xlabel="NeutralHadronMultiplicity of rejected jets", ylabel="N_{jets}", opts={"xmax": 10})
    createDrawPlot(myDir+"/jet_PhotonMultiplicity", xlabel="PhotonMultiplicity of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_ChargedMultiplicity", xlabel="ChargedMultiplicity of rejected jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/jet_PartonFlavour", xlabel="PartonFlavour of rejected jets", ylabel="N_{jets}", **mcArgs)
    myDir = "JetSelection/ReferenceJetToTau"
    createDrawPlot(myDir+"/MatchingDeltaR", xlabel="#DeltaR(#tau,ref.jet)", ylabel="N_{jets}")
    createDrawPlot(myDir+"/PartonFlavour", xlabel="pdgID", ylabel="N_{jets}", **mcArgs)
    createDrawPlot(myDir+"/PtRatio", xlabel="p_{T}^{#tau} / p_{T}^{ref.jet}", ylabel="N_{jets}")
    myDir = "MET"
    createDrawPlot(myDir+"/met", xlabel="MET, GeV", ylabel="N_{events}", rebin=4)
    createDrawPlot(myDir+"/metPhi", xlabel="MET #phi", rebinToWidthX=phiBinWidth)
    createDrawPlot(myDir+"/metSignif", xlabel="MET significance")
    createDrawPlot(myDir+"/metSumEt", xlabel="MET #sum E_{T}, GeV")
    myDir = "Btagging"
    createDrawPlot(myDir+"/NumberOfBtaggedJets", xlabel="N_{selected b jets}")
    createDrawPlot(myDir+"/jet_bdiscriminator", xlabel="b-taggind discriminator", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet_pt", xlabel="p_{T} of selected b jets, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet_eta", xlabel="#eta of selected b jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet1_pt", xlabel="p_{T} of first b jets, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet1_eta", xlabel="#eta of first b jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet2_pt", xlabel="p_{T} of second b jets, GeV/c", ylabel="N_{jets}")
    createDrawPlot(myDir+"/bjet2_eta", xlabel="#eta of second b jets", ylabel="N_{jets}")
    createDrawPlot(myDir+"/MCMatchForPassedJets", xlabel="MCMatchForPassedJets", ylabel="N_{jets}")
    myDir = "TauFakeRate/eToTau"
    createDrawPlot(myDir+"/etotau_mZ_all", xlabel="m_{ee} / GeV/c^{2}")
    createDrawPlot(myDir+"/etotau_mZ_decayMode0", xlabel="m_{ee} / GeV/c^{2}")
    createDrawPlot(myDir+"/etotau_mZ_decayMode1", xlabel="m_{ee} / GeV/c^{2}")
    createDrawPlot(myDir+"/etotau_mZ_decayMode2", xlabel="m_{ee} / GeV/c^{2}")
    createDrawPlot(myDir+"/etotau_taupT_all", xlabel="#tau p_{T} / GeV/c")
    createDrawPlot(myDir+"/etotau_taupT_decayMode0", xlabel="#tau p_{T} / GeV/c")
    createDrawPlot(myDir+"/etotau_taupT_decayMode1", xlabel="#tau p_{T}/ GeV/c")
    createDrawPlot(myDir+"/etotau_taupT_decayMode2", xlabel="#tau p_{T} / GeV/c")
    # Data driven control plots
    myDir = "ForDataDrivenCtrlPlots"
    createDrawPlot(myDir+"/Njets", forSystVar=True, xlabel="N_{jets}")
    createDrawPlot(myDir+"/NjetsAfterJetSelectionAndMETSF", forSystVar=True, xlabel="N_{jets}")
    for i in range (1,4):
        createDrawPlot(myDir+"/ImprovedDeltaPhiCutsJet%dCollinear"%i, forSystVar=True, xlabel="#sqrt{(#Delta#phi(#tau,MET))^{2}+(180^{o}-#Delta#phi(jet_{%d},MET))^{2}}"%i)
    createDrawPlot(myDir+"/SelectedTau_pT_AfterStandardSelections", xlabel="#tau p_{T} / GeV/c")
    createDrawPlot(myDir+"/SelectedTau_eta_AfterStandardSelections", xlabel="#tau #eta")
    createDrawPlot(myDir+"/SelectedTau_phi_AfterStandardSelections", xlabel="#tau #phi")
    createDrawPlot(myDir+"/SelectedTau_LeadingTrackPt_AfterStandardSelections", xlabel="#tau ldg. ch. particle p_{T} / GeV/c")
    createDrawPlot(myDir+"/SelectedTau_Rtau_AfterStandardSelections", xlabel="R_{#tau}")
    createDrawPlot(myDir+"/SelectedTau_pT_AfterStandardSelections", xlabel="#tau p_{T} / GeV/c")
    createDrawPlot(myDir+"/SelectedTau_p_AfterStandardSelections", xlabel="#tau p / GeV/c")
    createDrawPlot(myDir+"/SelectedTau_LeadingTrackP_AfterStandardSelections", xlabel="#tau ldg. ch. particle p / GeV/c")
    createDrawPlot(myDir+"/Njets_AfterStandardSelections", xlabel="N_{jets}")
    createDrawPlot(myDir+"/MET", forSystVar=True, xlabel="MET / GeV", rebinToWidthX=20)
    createDrawPlot(myDir+"/NBjets", forSystVar=True, xlabel="N_{b jets}")
    for i in range (1,4):
        createDrawPlot(myDir+"/ImprovedDeltaPhiCutsJet%dBackToBack"%i, forSystVar=True, xlabel="#sqrt{(180^{o}-#Delta#phi(#tau,MET))^{2}+(#Delta#phi(jet_{%d},MET))^{2}}"%i)
    # Final shapes
    createDrawPlot("shapeTransverseMass", forSystVar=True, xlabel="Transverse mass, GeV/c^{2}", ylabel="N_{events}", rebinToWidthX=20, customizeBeforeFrame=lambda p: plots.partiallyBlind(p, maxShownValue=60))
    createDrawPlot("shapeEWKFakeTausTransverseMass", forSystVar=True, xlabel="Transverse mass EWK fake taus, GeV/c^{2}", ylabel="N_{events}", rebin=10, **mcArgs)
    createDrawPlot("shapeInvariantMass", forSystVar=True, xlabel="Invariant mass, GeV/c^{2}", ylabel="N_{events}", rebin=4, fullyBlinded=True)
    createDrawPlot("shapeEWKFakeTausInvariantMass", forSystVar=True, xlabel="Invariant mass EWK fake taus, GeV/c^{2}", ylabel="N_{events}", rebin=4, **mcArgs)
    # main directory
    createDrawPlot("deltaPhi", xlabel="#Delta#phi(#tau jet, MET), ^{o}", ylabel="N_{events}", rebin=20)
    createDrawPlot("alphaT", xlabel="#alpha_{T}", opts={"xmax": 2}, customizeBeforeFrame=lambda p: plots.partiallyBlind(p, maxShownValue=0.5))
    #createDrawPlot("deltaPhiJetMet", xlabel="min #Delta#phi(jet, MET), ^{o}", fullyBlinded=True)
    #createDrawPlot("maxDeltaPhiJetMet", xlabel="max #Delta#phi(#tau jet, MET), ^{o}", fullyBlinded=True)
    createDrawPlot("SignalSelectionFlow", xlabel="Step", opts={"xmax": 7})
    #createDrawPlot("SignalSelectionFlowVsVertices"", xlabel="N_{vertices}", ylabel="Step",)
    #createDrawPlot("SignalSelectionFlowVsVerticesFakeTaus", xlabel="N_{vertices}", ylabel="Step")

    # Normalization plots
    myNormalizationPlotDirs = myDsetMgr.getDataset("Data").getDirectoryContent("NormalisationAnalysis")
    def createDrawNormalizationPlots(path, **kwargs):
        for plotDir in myNormalizationPlotDirs:
            args = {}
            args.update(kwargs)
            createDrawPlot(path%plotDir, **args)

    createDrawNormalizationPlots("NormalisationAnalysis/%s/tauPt", xlabel="#tau p_{T} / GeV/c")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/nJets", xlabel="N_{jets}")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/met", xlabel="MET / GeV")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/metPhi", xlabel="MET #phi")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/nBJets", xlabel="N_{b jets}")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/transverseMass", xlabel="m_{T}(#tau,MET) / GeV/c^{2}")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/zMass", xlabel="m_{Z} / GeV/c^{2}")
    createDrawNormalizationPlots("NormalisationAnalysis/%s/HplusPt", xlabel="p_{T}(H+) / GeV/c")
Beispiel #14
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
Beispiel #15
0
def doPlots(datasets, selectionName, ntupleCache, selectorName):
    def createPlot(name, **kwargs):
        args = kwargs.copy()
        if mcOnly:
            args["normalizeToLumi"] = mcLuminosity
        return plots.DataMCPlot(datasets,
                                ntupleCache.histogram(name, selectorName),
                                **args)

    drawPlot = plots.PlotDrawer(
        stackMCHistograms=True,
        addMCUncertainty=True,
        log=True,
        ratio=not mcOnly,
        addLuminosityText=True,
        ratioYlabel="Ratio",
        optsLog={"ymin": 1e-1},
        opts2={
            "ymin": 0,
            "ymax": 2
        },
        #opts2={"ymin": 0.6, "ymax": 1.4},
    )

    metBinning = range(0, 200, 10) + range(200, 300, 20) + [300, 350, 400]
    ptBinning = range(0, 40, 10) + [41] + range(50, 200, 10) + range(
        200, 400, 20)
    zoomedOpts2 = {"ymin": 0.6, "ymax": 1.4}

    prefix = era + "_" + selectionName + "_"
    drawPlot(createPlot("selectedMuonPt_AfterJetSelection"),
             prefix + "muon_pt_log",
             "Muon p_{T} (GeV/c)",
             ylabel="dN/dp_{T} / %.0f-%.0f GeV/c",
             cutBox={
                 "cutValue": 41,
                 "greaterThan": True
             },
             rebin=ptBinning,
             divideByBinWidth=True,
             opts2=zoomedOpts2)
    drawPlot(createPlot("selectedMuonEta_AfterJetSelection"),
             prefix + "muon_eta",
             "Muon #eta",
             ylabel="Events / %.1f",
             cutLine=[-2.1, 2.1],
             log=False,
             rebin=5)
    drawPlot(createPlot("selectedMuonPhi_AfterJetSelection"),
             prefix + "muon_phi",
             "Muon #phi",
             ylabel="Events / %.1f",
             log=False,
             rebin=8)

    drawPlot(createPlot("uncorrectedMet_AfterJetSelection"),
             prefix + "rawmet_pt_log",
             "Uncorrected PF E_{T}^{miss} (GeV)",
             ylabel="dN/dE_{T}^{miss} / %.0f-%.0f 1/GeV",
             rebin=metBinning,
             divideByBinWidth=True)

    drawPlot(createPlot("transverseMassUncorrectedMet_AfterJetSelection"),
             prefix + "rawmt_log",
             "m_{T}(#mu, E_{T}^{miss}) (GeV/c^{2})",
             ylabel="dN/dm_{T} / %.0f-%.0f 1/GeV/c^{2}",
             rebin=metBinning,
             divideByBinWidth=True)

    drawPlot(createPlot("type1Met_AfterJetSelection"),
             prefix + "met_pt_log",
             "Type-1 PF E_{T}^{miss} (GeV)",
             ylabel="dN/dE_{T}^{miss} / %.0f-%.0f 1/GeV",
             rebin=metBinning,
             divideByBinWidth=True,
             opts2=zoomedOpts2)
    drawPlot(createPlot("type1MetPhi_AfterJetSelection"),
             prefix + "met_phi",
             "Type-1 PF E_{T}^{miss} #phi",
             ylabel="Events / %.2f",
             log=False,
             rebin=2,
             moveLegend={"dy": -0.4})

    drawPlot(createPlot("transverseMassType1Met_AfterJetSelection"),
             prefix + "mt_log",
             "m_{T}(#mu, E_{T}^{miss}) (GeV/c^{2})",
             ylabel="dN/dm_{T} / %.0f-%.0f 1/GeV/c^{2}",
             rebin=metBinning,
             divideByBinWidth=True,
             opts2=zoomedOpts2)

    drawPlot(createPlot("nbjets_AfterJetSelection"),
             prefix + "nbjets_log",
             "Number of b jets",
             ylabel="Events")

    for x in ["0", "1", "2", "ging"]:
        drawPlot(createPlot("selectedMuonPt_AfterBTag%s" % x),
                 prefix + "muon_pt_btag%s_log" % x,
                 "Muon p_{T} (GeV/c)",
                 ylabel="dN/dp_{T} / %.0f-%.0f GeV/c",
                 cutBox={
                     "cutValue": 41,
                     "greaterThan": True
                 },
                 rebin=ptBinning,
                 divideByBinWidth=True)
        drawPlot(createPlot("type1Met_AfterBTag%s" % x),
                 prefix + "met_pt_btag%s_log" % x,
                 "Type-1 PF E_{T}^{miss} (GeV)",
                 ylabel="dN/dE_{T}^{miss} / %.0f-%.0f GeV",
                 rebin=metBinning,
                 divideByBinWidth=True)
        drawPlot(createPlot("transverseMassType1Met_AfterBTag%s" % x),
                 prefix + "mt_btag%s_log" % x,
                 "m_{T}(#mu, E_{T}^{miss}) (GeV/c^{2})",
                 ylabel="dN/dm_{T} / %.0f-%.0f 1/GeV/c^{2}",
                 rebin=metBinning,
                 divideByBinWidth=True)

    drawPlot(createPlot("type1MetPhi_AfterBTagging"),
             prefix + "met_phi_btagging",
             "Type-1 PF E_{T}^{miss} #phi ",
             ylabel="Events / %.2f",
             log=False,
             rebin=2,
             moveLegend={"dy": -0.4})

    # plotEfficiency(datasets, ["Data", "TTJets", "WJets", "QCD_Pt20_MuEnriched"],
    #                allPath=ntupleCache.histogram("muonVertexCount_AfterDB"),
    #                passedPath=ntupleCache.histogram("muonVertexCount_AfterIsolation"),
    #                name=prefix+"muonIsolationEfficiency", xlabel="Number of good vertices", ylabel="Muon selection efficiency",
    #                rebinBins=range(0, 25)+[25, 30, 35, 40, 50]
    #                )

    # plotEfficiency(datasets, ["TTJets", "WJets"],
    #                allPath=ntupleCache.histogram("muonVertexCount_AfterDB_MuFromW"),
    #                passedPath=ntupleCache.histogram("muonVertexCount_AfterIsolation_MuFromW"),
    #                name=prefix+"muonIsolationEfficiency_MuFromW", xlabel="Number of good vertices", ylabel="Muon selection efficiency",
    #                rebinBins=range(0, 25)+[25, 30, 35, 40, 50]
    #                )

    if "NoIso" in selectionName:
        drawPlot(
            createPlot("selectedMuonChargedHadronEmbIso_AfterJetSelection"),
            prefix + "chargedHadronIso_log",
            "Charged hadron #Sigma p_{T} (GeV/c)",
            ylabel="Events / %.1f GeV/c")
        drawPlot(
            createPlot("selectedMuonPuChargedHadronEmbIso_AfterJetSelection"),
            prefix + "puChargedHadronIso_log",
            "Charged hadron #Sigma p_{T} (GeV/c)",
            ylabel="Events / %.1f GeV/c")
        drawPlot(
            createPlot("selectedMuonNeutralHadronEmbIso_AfterJetSelection"),
            prefix + "neutralHadronIso_log",
            "Neutral hadron #Sigma p_{T} (GeV/c)",
            ylabel="Events / %.1f GeV/c")
        drawPlot(createPlot("selectedMuonPhotonEmbIso_AfterJetSelection"),
                 prefix + "photonIso_log",
                 "Photon #Sigma p_{T} (GeV/c)",
                 ylabel="Events / %.1f GeV/c")

        drawPlot(createPlot("selectedMuonEmbIso_AfterJetSelection"),
                 prefix + "embeddingIso_log",
                 "Isolation variable (GeV/c)",
                 ylabel="Events / %.1f GeV/c")

        drawPlot(createPlot("selectedMuonStdIso_AfterJetSelection"),
                 prefix + "standardIso_log",
                 "Isolation variable",
                 ylabel="Events / %.1f GeV/c")
Beispiel #16
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
Beispiel #17
0
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.crosssection as xsect
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.systematics as systematics
import HiggsAnalysis.HeavyChHiggsToTauNu.qcdInverted.fakeRateWeighting as fakeRateWeighting
import HiggsAnalysis.HeavyChHiggsToTauNu.qcdInverted.qcdInvertedResult as qcdInvertedResult

from HiggsAnalysis.HeavyChHiggsToTauNu.tools.ShellStyles import *

era = "Run2012ABCD"
searchMode = "Light"

drawPlot1 = plots.PlotDrawer(
    ylabel="w",
    cmsTextPosition="left",
    createLegend=None,
)

drawPlot2 = plots.PlotDrawer(
    ylabel="Fake rate probability",
    cmsTextPosition="left",
    moveLegend={
        "dx": -0.05,
        "dy": 0.02
    },
    opts={
        "ymin": 0.0,
        "ymax": 0.2
    },
)
Beispiel #18
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
Beispiel #19
0
    # names = datasetMgr.getAllDatasetNames()
    #d_ttjets = datasets.getDataset("TTJets")
    #print d_ttjets.getNAllEvents()

    # Create plots
    doPlots(datasets)

    if interactiveMode:
        raw_input("*** Press \"Enter\" to exit pyROOT: ")


# Default plot drawing options, all of these can be overridden in the
# individual drawPlot() calls
drawPlot = plots.PlotDrawer(log=True,
                            addLuminosityText=True,
                            stackMCHistograms=True,
                            addMCUncertainty=True)


# Define plots to draw
def doPlots(datasets):
    def createPlot(name,
                   massbr_x=0.42,
                   massbr_y=0.87,
                   normone_x=0.25,
                   normone_y=0.5,
                   **kwargs):
        args = {}
        args.update(kwargs)
        if mcOnly:
            args["normalizeToLumi"] = mcOnlyLumi
Beispiel #20
0
#!/usr/bin/env python

import array

import ROOT
ROOT.gROOT.SetBatch(True)

import HiggsAnalysis.HeavyChHiggsToTauNu.tools.histograms as histograms
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.plots as plots
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.aux as aux

drawPlot = plots.PlotDrawer(
    #                   ylabel="Normalization coefficient ^{}w_{j}",
    #                   ylabel="Fake rate probability ^{}w_{j}",
    ylabel="Fake rate probability",
    cmsTextPosition="right",
    createLegend=None,
)


def main():
    style = tdrstyle.TDRStyle()

    # hand-picked values from an output from Lauri
    th1 = ROOT.TH1F("factors", "factors", 7, 0, 7)
    th1.SetBinContent(1, 0.0614187118715)
    th1.SetBinContent(2, 0.0579929858899)
    th1.SetBinContent(3, 0.0502462685164)
    th1.SetBinContent(4, 0.0524329776127)
    th1.SetBinContent(5, 0.0519288842156)
Beispiel #21
0
    plots._legendLabels["TTToHplus_M120"] = "with H^{#pm}#rightarrow#tau^{#pm}#nu"

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    # Create plots
    doPlots(datasets)

    # Print counters
    massPoints = [80, 90, 100, 120, 140, 150, 155, 160]
    doCounters(datasetsAllSignals, massPoints)

    # Signal efficiency plots for WH
#    doEfficiencyPlots(datasetsAllSignals, massPoints)

drawPlot = plots.PlotDrawer(ylabel="Events / %.0f (GeV/c^{2})", log=True, addLuminosityText=True, stackMCHistograms=True, addMCUncertainty=True)

def doPlots(datasets):
    def createPlot(name, **kwargs):
        return plots.DataMCPlot(datasets, analysis+"/"+name, **kwargs)

    def addMassBRText(plot, x, y):
        mass = "m_{H^{+}} = 120 GeV/c^{2}"
        br = "#it{B}(t #rightarrow H^{+}b)=0.05"
        size = 20
        separation= 0.04
        plot.appendPlotObject(histograms.PlotText(x, y, mass, size=size))
        plot.appendPlotObject(histograms.PlotText(x, y-separation, br, size=size))

    # Number of vertices (unit area)
    p = createPlot("Vertices/verticesTriggeredAfterWeight", normalizeToOne=True)
def doTH1Plots(datasets, HistoTemplateList, SaveExtension):
    ''' 
    def doTH1Plots(datasets, HistoTemplateList, SaveExtension):
    Loops over all histograms defined in HistoHelper.py and customises each plot accordingly. 
    The global boolean options are also taken care of including x- and y- min, max, ratio, logY, etc..
    '''

    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})

    ### 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 HistoTemplateList:
        hName = h.name
        hPath = h.path
        fileName = "%s_%s" % (hName, SaveExtension)
        xLabel = h.xlabel
        yLabel = h.ylabel
        iBinWidth = h.binWidthX
        if "_Vs_" in hName:
            continue

        p = createTH1Plot(datasets,
                          hPath,
                          normalizeToOne=getBool("bNormalizeToOne"))
        if not getBool("bStackHistos"):
            drawPlot(p, fileName, rebinToWidthX=iBinWidth)
        else:
            drawPlot(p,
                     fileName + "_Stacked",
                     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,
                       hPath,
                       hName,
                       xLabel,
                       yLabel,
                       iBinWidth,
                       SaveExtension,
                       hType={"TH1": True})

    return
Beispiel #23
0
def efficiencyplot(opts, dsetMgr, luminosity, myDir):
    myDirInRootFile = "BTaggingEfficiencyInMC"
    myAllJetsTemplate = "genuine%sJet%s"
    myBJetsTemplate = "genuine%sJetWithBTag%s"

    myPartonList = ["B","C","G","UDS","L"]
    mySuffixList = ["Pt","Eta"]

    # Specify output histogram binning
    myHistoSpecsPt = {
      "rangeMin": 0.0,
      "rangeMax": 500.0,
      # if an empty list is given, then uniform bin width is used:
      #"variableBinSizeLowEdges": [20,30,40,50,60,70,80,90,100,120,140,160,200,250,300,350,400], # B and C
      "variableBinSizeLowEdges": [20,30,60,100,150,250], # G and UDS
      "xtitle": "Jet p_{T} / GeV/c",
      "ytitle": "dN_{jets}/dp_{T}, arb. normalization"
    }
    myHistoSpecsEta = {
      "rangeMin": -2.5,
      "rangeMax": 2.5,
      "variableBinSizeLowEdges": [-2.5,-2.0,-1.5,-1.0,-0.5,0.0,0.5,1.0,1.5,2.0], # if an empty list is given, then uniform bin width is used
      "xtitle": "Jet #eta",
      "ytitle": "dN_{jets}/d#eta, arb. normalization"
    }
    myHistoSpecsList = {"Pt": myHistoSpecsPt,
                        "Eta": myHistoSpecsEta }
    drawPlot = plots.PlotDrawer(log=True, ratio=False, addLuminosityText=False, optsLog={"ymin": 1e-4, "ymax": 300}, cmsText="CMS preliminary")
    drawPlotEfficiency = plots.PlotDrawer(log=False, ratio=False, addLuminosityText=False, cmsText="CMS preliminary", opts={"ymin": 0, "ymax": 1}, ylabel="Efficiency")

    # Loop over variables
    myResult = BtagEfficiencyResult()
    for suffix in mySuffixList:
        # Store binning to result
        myResult.addGeneralInfo(myDir.replace("btagEfficiency_",""))
        myResult.addBinning(suffix, myHistoSpecsList[suffix]["variableBinSizeLowEdges"])
        # Initialize lists for histograms.Histo objects
        hAllJetsList = []
        hBJetsList = []
        hEfficiencyList = []
        # Loop over partons
        for parton in myPartonList:
            print HighlightStyle()+"Creating plots for parton %s, variable %s%s"%(parton,suffix,NormalStyle())
            # Obtain histograms
            myAllJetsDsetHisto = dsetMgr.getDataset(opts.dset).getDatasetRootHisto("%s/%s"%(myDirInRootFile,myAllJetsTemplate%(parton,suffix)))
            myAllJetsDsetHisto.normalizeToLuminosity(luminosity)
            hAllJets = myAllJetsDsetHisto.getHistogram().Clone()
            myBJetsDsetHisto = dsetMgr.getDataset(opts.dset).getDatasetRootHisto("%s/%s"%(myDirInRootFile,myBJetsTemplate%(parton,suffix)))
            myBJetsDsetHisto.normalizeToLuminosity(luminosity)
            hBJets = myBJetsDsetHisto.getHistogram().Clone()
            # Setup histogramming
            myModifier = ShapeHistoModifier(myHistoSpecsList[suffix])
            # Make plot for all jets
            myPlotName = "%sForAll%sJets"%(suffix,parton)
            myLabel = "All %s jets"%(parton.replace("L","udsg").lower())
            hBinnedAllJets = myModifier.createEmptyShapeHistogram(myPlotName)
            myModifier.addShape(source=hAllJets,dest=hBinnedAllJets)
            myModifier.finaliseShape(dest=hBinnedAllJets)
            rootHistoObjectAll = histograms.Histo(hBinnedAllJets.Clone(),myLabel,legendStyle="LV",drawStyle="E")
            hAllJetsList.append(rootHistoObjectAll)
            plot = plots.PlotBase([rootHistoObjectAll])
            styles.dataStyle(plot.histoMgr.getHisto(myLabel))
            drawPlot(plot,"%s/%s"%(myDir,myPlotName),divideByBinWidth=True,xlabel=myHistoSpecsList[suffix]["xtitle"],ylabel=myHistoSpecsList[suffix]["ytitle"])
            plot.save()
            # Make plot for b jets
            myPlotName = "%sForBtagged%sJets"%(suffix,parton)
            myLabel = "All btagged %s jets"%(parton.replace("L","udsg").lower())
            hBinnedBJets = myModifier.createEmptyShapeHistogram(myPlotName)
            myModifier.addShape(source=hBJets,dest=hBinnedBJets)
            myModifier.finaliseShape(dest=hBinnedBJets)
            rootHistoObjectB = histograms.Histo(hBinnedBJets.Clone(),myLabel,legendStyle="LV",drawStyle="E")
            hBJetsList.append(rootHistoObjectB)
            plot = plots.PlotBase([rootHistoObjectB])
            styles.dataStyle(plot.histoMgr.getHisto(myLabel))
            drawPlot(plot,"%s/%s"%(myDir,myPlotName),divideByBinWidth=True,xlabel=myHistoSpecsList[suffix]["xtitle"],ylabel=myHistoSpecsList[suffix]["ytitle"])
            plot.save()
            # Make efficiency plot and convert it to TH1
            myEff = ROOT.TEfficiency(hBinnedBJets,hBinnedAllJets)
            myResult.addEffObject(myEff, myDir.replace("btagEfficiency_",""), "%stoB_by%s"%(parton.replace("L","UDSG"),suffix))
            myPlotName = "Efficiency_%sForBtagged%sJets"%(suffix,parton)
            myLabel = "%s#rightarrowb"%(parton.replace("L","udsg").lower())
            rootHistoObjectEff = histograms.HistoEfficiency(myEff,myLabel,legendStyle="LV",drawStyle="")
            hEfficiencyList.append(rootHistoObjectEff)
            plot = plots.PlotBase([rootHistoObjectEff])
            styles.dataStyle(plot.histoMgr.getHisto(myLabel))
            drawPlotEfficiency(plot,"%s/%s"%(myDir,myPlotName),xlabel=myHistoSpecsList[suffix]["xtitle"]) # opts={"log":False}
            plot.save()
        # Set plotting styles
        for i in range(0,len(hAllJetsList)):
            styles.applyStyle(hAllJetsList[i].getRootHisto(),i)
            styles.applyStyle(hBJetsList[i].getRootHisto(),i)
            styles.applyStyle(hEfficiencyList[i].getRootHisto(),i)
        # Do plots with different parton flavors on same canvas
        plot = plots.PlotBase(hAllJetsList)
        drawPlot(plot,"%s/%s"%(myDir,"Combined_%sForAllJets"%suffix),xlabel=myHistoSpecsList[suffix]["xtitle"],ylabel=myHistoSpecsList[suffix]["ytitle"])
        plot.save()
        plot = plots.PlotBase(hBJetsList)
        drawPlot(plot,"%s/%s"%(myDir,"Combined_%sForBTaggedJets"%suffix),xlabel=myHistoSpecsList[suffix]["xtitle"],ylabel=myHistoSpecsList[suffix]["ytitle"])
        plot.save()
        plot = plots.PlotBase(hEfficiencyList)
        drawPlotEfficiency(plot,"%s/%s"%(myDir,"Combined_Efficiency_%s"%suffix),xlabel=myHistoSpecsList[suffix]["xtitle"])
        plot.save()
    # Save to disk the efficiency results
    myResult.writeResultToDisk(myDir)