示例#1
0
 def drawIndividually(self):
     for i in range(0, len(self._systNameList)):
         myPlotName = "shapeSystRatioOnlyIndividual_%s_syst_%s" % (
             self._dsetName, self._systNameList[i])
         plot = self._ratioPlotList[i]
         backup = ROOT.gErrorIgnoreLevel
         ROOT.gErrorIgnoreLevel = ROOT.kError
         c = ROOT.TCanvas("", "", 600, 240)
         ROOT.gErrorIgnoreLevel = backup
         c.SetLeftMargin(0.12)
         c.SetBottomMargin(0.3)
         plot.getFrame2().GetXaxis().SetTitleOffset(.85)
         plot.getFrame2().GetYaxis().SetLabelSize(26)
         plot.getFrame2().GetYaxis().SetTitleOffset(.36)
         plot.getFrame2().Draw(
         )  # Clone needed because otherwise plot.getFrame2() becomes None after Draw()
         plot.ratioHistoMgr.draw()
         plot.ratioLine.Draw("L")
         c.RedrawAxis()
         tb = histograms.PlotText(x=0.18,
                                  y=0.82,
                                  text=self._systNameList[i],
                                  size=30)
         tb.Draw()
         backup = ROOT.gErrorIgnoreLevel
         ROOT.gErrorIgnoreLevel = ROOT.kError
         for suffix in [".png", ".C", ".eps"]:
             c.Print("%s/%s%s" % (opts.dirName, myPlotName, suffix))
         ROOT.gErrorIgnoreLevel = backup
     return
def MtComparisonBaseline(datasets):
    mt = plots.PlotBase(getHistos(datasets,"ForQCDNormalization/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive", "ForQCDNormalizationEWKFakeTaus/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive", "ForQCDNormalizationEWKGenuineTaus/NormalizationMETBaselineTauAfterStdSelections/NormalizationMETBaselineTauAfterStdSelectionsInclusive"))
#    mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity())
    mt._setLegendStyles()
    st1 = styles.StyleCompound([styles.styles[2]])
    st2 = styles.StyleCompound([styles.styles[1]])
    st3 = styles.StyleCompound([styles.styles[3]])
    st1.append(styles.StyleLine(lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=2, lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=3, lineWidth=3))
    mt.histoMgr.forHisto("transverseMass", st1)
    mt.histoMgr.forHisto("transverseMassTriangleCut", st2)
    mt.histoMgr.forHisto("transverseMass3JetCut", st3)

    mt.histoMgr.setHistoLegendLabelMany({
            "transverseMass": "All baseline Taus",
            "transverseMassTriangleCut": "Baseline Fake Taus",
            "transverseMass3JetCut": "Baseline Genuine Taus"
            })
#    mt.histoMgr.setHistoDrawStyleAll("P")

    mt.appendPlotObject(histograms.PlotText(50, 1, "3-prong Taus", size=20))
    xlabel = "E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f"
    plots.drawPlot(mt, "MtComparisonBaseline", xlabel=xlabel, ylabel=ylabel, rebinX=1, log=True,
                   createLegend={"x1": 0.4, "y1": 0.75, "x2": 0.8, "y2": 0.9},
                   ratio=False, opts2={"ymin": 0.5, "ymax": 1.5})
示例#3
0
def doPlot(opts, signif, lumi, pvalue=False):
    grObs = None
    histos = []
    if opts.unblinded:
        grObs = signif.observedGraph(pvalue)
        histos.append(histograms.HistoGraph(grObs, "Observed", drawStyle="LP"))
    grExp = signif.expectedGraph(pvalue)
    histos.append(histograms.HistoGraph(grExp, "Expected", drawStyle="L"))

    expData = "#it{B}#times#it{B}=%s %%" % signif.lightExpectedSignal()
    if signif.isHeavyStatus():
        expData = "#sigma#times#it{B}=%s pb" % signif.heavyExpectedSignal()

    plot = plots.PlotBase(histos)
    plot.setLuminosity(lumi)
    if pvalue:
        plot.histoMgr.setHistoLegendLabelMany({
            "Expected": "Expected p-value",
            "Observed": "Observed p-value"
        })
        plot.appendPlotObject(histograms.PlotText(0.6, 0.68, expData, size=18))
        drawPlot(plot,
                 "pvalue",
                 ylabel="P-value",
                 log=True,
                 moveLegend={"dx": -0.2},
                 opts={
                     "ymin": 1e-10,
                     "ymax": 1
                 })
    else:
        plot.histoMgr.setHistoLegendLabelMany({
            "Expected":
            "Expected significance",
            "Observed":
            "Observed significance"
        })
        plot.appendPlotObject(histograms.PlotText(0.2, 0.68, expData, size=18))
        drawPlot(plot,
                 "significance",
                 ylabel="Significance",
                 moveLegend={"dx": -0.55})
示例#4
0
def MtComparison(datasets):
    mt = plots.PlotBase(
        getHistos(datasets, "transverseMass", "transverseMassTriangleCut",
                  "transverseMass3JetCut"))
    #    mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity())
    mt._setLegendStyles()
    st1 = styles.StyleCompound([styles.styles[2]])
    st2 = styles.StyleCompound([styles.styles[1]])
    st3 = styles.StyleCompound([styles.styles[3]])
    st1.append(styles.StyleLine(lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=2, lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=3, lineWidth=3))
    mt.histoMgr.forHisto("transverseMass", st1)
    mt.histoMgr.forHisto("transverseMassTriangleCut", st2)
    mt.histoMgr.forHisto("transverseMass3JetCut", st3)

    mt.histoMgr.setHistoLegendLabelMany({
        "transverseMass":
        "m_{T}(#tau jet, E_{T}^{miss})",
        "transverseMassTriangleCut":
        "m_{T}(#tau jet, E_{T}^{miss}) with Triangle Cut",
        "transverseMass3JetCut":
        "m_{T}(#tau jet, E_{T}^{miss}) with 3-jet Cut"
    })
    #    mt.histoMgr.setHistoDrawStyleAll("P")

    mt.appendPlotObject(
        histograms.PlotText(300, 50, "p_{T}^{jet} > 50 GeV/c", size=20))
    xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
    ylabel = "Events / %.2f"
    plots.drawPlot(mt,
                   "MtComparison",
                   xlabel=xlabel,
                   ylabel=ylabel,
                   rebinX=2,
                   log=False,
                   createLegend={
                       "x1": 0.4,
                       "y1": 0.75,
                       "x2": 0.8,
                       "y2": 0.9
                   },
                   ratio=False,
                   opts2={
                       "ymin": 0.5,
                       "ymax": 1.5
                   })
示例#5
0
def Plot2dHistograms(datasetsMgr, histoName):
    Verbose("Plotting Data-MC Histograms")

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]
    kwargs   = GetHistoKwargs(saveName, opts)

    # Create the 2d plot
    if opts.dataset == "Data":
        p = plots.DataMCPlot(datasetsMgr, histoName, saveFormats=[])
    else:
        if opts.normalizeToLumi:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[])
        elif opts.normalizeByCrossSection:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeByCrossSection=True, saveFormats=[], **{})
        elif opts.normalizeToOne:
            p = plots.MCPlot(datasetsMgr, histoName, normalizeToOne=True, saveFormats=[], **{})
        else:
            raise Exception("One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\").")
            
    # Customise z-axis
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle(kwargs["zlabel"]))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3))
    if kwargs.get("zmin") != None:
        zMin = float(kwargs.get("zmin"))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(zMin))
    if kwargs.get("zmax") != None:
        zMax = float(kwargs.get("zmax"))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(zMax))

    # Drawing style    
    p.histoMgr.setHistoDrawStyleAll("COLZ")

    # Add dataset name on canvas
    p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset], bold=True, size=22))

    # Draw the plot
    plots.drawPlot(p, saveName, **kwargs) #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder, opts.dataset), [".png", ".pdf"] )
    return
示例#6
0
def TauPtComparison(datasets):
    mt = plots.ComparisonPlot(*getHistos3(datasets, "tauPt", "tauPt"))

    mt._setLegendStyles()
    st1 = styles.StyleCompound([styles.styles[2]])
    st2 = styles.StyleCompound([styles.styles[1]])
    st1.append(styles.StyleLine(lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=2, lineWidth=3))
    mt.histoMgr.forHisto("Taupt_madgraph", st1)
    mt.histoMgr.forHisto("Taupt_pythia8", st2)
    mt.histoMgr.setHistoLegendLabelMany({
        "Taupt_madgraph": "Tau pt from Madgraph",
        "Taupt_pythia8": "Tau pt from Pythia8"
    })
    mt.histoMgr.setHistoDrawStyleAll("PE")

    mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20))
    xlabel = "p_{T}^{#tau jet} (GeV)"
    ylabel = "Events / %.2f"
    plots.drawPlot(mt,
                   "TauPtComparison",
                   xlabel=xlabel,
                   ylabel=ylabel,
                   rebinX=2,
                   log=True,
                   createLegend={
                       "x1": 0.6,
                       "y1": 0.75,
                       "x2": 0.8,
                       "y2": 0.9
                   },
                   ratio=False,
                   opts2={
                       "ymin": 0.5,
                       "ymax": 50
                   },
                   opts={
                       "xmax": 800,
                       "ymin": 1,
                       "ymax": 1000000
                   })
def MetComparison(datasets):
    mt = plots.ComparisonPlot(*getHistos2(datasets,"Met","Met"))
#    mt.histoMgr.normalizeMCToLuminosity(datasets.getDataset("Data").getLuminosity())                                                                                                                                                                                  
    mt._setLegendStyles()
    st1 = styles.StyleCompound([styles.styles[2]])
    st2 = styles.StyleCompound([styles.styles[1]])
    st1.append(styles.StyleLine(lineWidth=3))
    st2.append(styles.StyleLine(lineStyle=2, lineWidth=3))
    mt.histoMgr.forHisto("Met_madgraph", st1)
    mt.histoMgr.forHisto("Met_pythia8", st2)
    mt.histoMgr.setHistoLegendLabelMany({
            "Met_madgraph": "Met from Madgraph",
            "Met_pythia8": "Met from Pythia8"
            })
    mt.histoMgr.setHistoDrawStyleAll("PE")


    mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20))
    xlabel = "PF E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f"
    plots.drawPlot(mt, "MetComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True,
                   createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9},
                   ratio=False, opts2={"ymin": 0.5, "ymax": 50}, opts={"xmax": 500})
示例#8
0
def PlotHistograms(datasetsMgr, histoList, binLabels, opts):
    '''
    histoList contains all histograms for all bins for CR1 and CR2 
    
    '''
    # Get the root histos for all datasets and Control Regions (CRs)
    rhDict = GetRootHistos(datasetsMgr, histoList)

    # For-loop: All root-histo keys (All fake-B bins, all CRs, (CR1, CR2, ..)  and all folders (Data, EWKFakeB, EWKGenuineB)
    for key1 in rhDict:
        # Definitions
        region1 = "CRone"
        region2 = "CRtwo"
        key2 = key1.replace(region1, region2)
        dataset = key1.split("-")[0]
        region = key1.split("-")[1]
        bin = key1.split("-")[2]
        hName1 = rhDict[key1].GetName()
        hName2 = rhDict[key2].GetName()
        bInclusive = "Inclusive" in key1

        # Dataset and Region filter
        if dataset != "FakeB":
            continue
        # This gives CR1. can get CR2 by replacing CR1 with CR2 (histo-names are identical otherwise)
        if region != region1:
            continue

        Verbose("Accessing histogram %s" % key1, False)
        if bInclusive:
            Verbose(
                "The histo key is \"%s\" and its name is \"%s\"" %
                (key1, rhDict[key1].GetName()), True)

            rFakeB_CRone = rhDict[key1].Clone()
            rFakeB_CRone.Reset("ICES")

            rFakeB_CRtwo = rhDict[key2].Clone()
            rFakeB_CRtwo.Reset("ICES")

            # For-loop: All fakeB bins (to add-up all binned histos)
            for i, b in enumerate(binLabels, 1):
                if "Inclusive" in b:
                    Verbose("Skipping bin-label %s" % (b), False)
                    continue
                else:
                    Verbose("Adding bin %s" % (b), False)

                # Determine keys
                k1 = key1.replace("Inclusive", b)
                k2 = key2.replace("Inclusive", b)

                # Normalise bin histo to one (before adding to inclusive histo)
                Verbose("Cloning histogram %s" % (rhDict[k1].GetName()), False)
                h1 = rhDict[k1].Clone()
                h2 = rhDict[k2].Clone()

                # First normalise the histos
                h1.Scale(1.0 / h1.Integral())
                h2.Scale(1.0 / h2.Integral())

                # Add-up individual bins
                rFakeB_CRone.Add(h1, +1)
                rFakeB_CRtwo.Add(h2, +1)
        else:
            # Get the histos
            rFakeB_CRone = rhDict[key1]
            rFakeB_CRtwo = rhDict[key2]

        # Normalise the histos?
        if opts.normaliseToOne:
            rFakeB_CRone.Scale(1.0 / rFakeB_CRone.Integral())
            rFakeB_CRtwo.Scale(1.0 / rFakeB_CRtwo.Integral())

        # Apply histogram styles
        styles.getABCDStyle("CRone").apply(rFakeB_CRone)
        styles.getABCDStyle("CRtwo").apply(rFakeB_CRtwo)

        # Create the plot
        p = plots.ComparisonManyPlot(rFakeB_CRone, [rFakeB_CRtwo],
                                     saveFormats=[])
        p.setLuminosity(opts.intLumi)

        # Set draw/legend style
        p.histoMgr.setHistoDrawStyle(hName1, "AP")
        p.histoMgr.setHistoLegendStyle(hName1, "LP")

        p.histoMgr.setHistoDrawStyle(hName2, "HIST")
        p.histoMgr.setHistoLegendStyle(hName2, "F")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            hName1: "CR1",
            hName2: "CR2",
        })

        # Draw the plot and save it
        if bin == "Inclusive":
            histoName = histoList[0] + "_CR1vCR2_combined"
        else:
            histoName = histoList[0] + "_CR1vCR2_bin%s" % (bin)
        saveName = histoName.split("/")[-1].replace("CRone0_",
                                                    "").replace("CRtwo0_", "")

        # Get the histogram customisations (keyword arguments)
        p.appendPlotObject(
            histograms.PlotText(0.20,
                                0.88,
                                GetBinText(bin),
                                bold=True,
                                size=22))
        plots.drawPlot(p, saveName, **GetHistoKwargs(saveName))
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, opts.optMode),
                 saveFormats=[".png"])  #, ".pdf"])
    return
def doPlot(name, genuineBDataset, fakeBDataset, errorlevel, optimizationMode, lumi):
    btagWP = "CSVv2-" + name.split("_")[-1]
    Verbose("Generating efficiency for discriminator WP \"%s\"" % (btagWP), True)

    # Definitions
    s = optimizationMode.split("BjetDiscrWorkingPoint")
    discrName      = s[0].replace("OptBjetDiscr", "")
    discrWP        = s[1]
    myPartons      = ["B", "C", "Light"]
    myPartonLabels = ["b#rightarrowb", "c#rightarrowb", "guds#rightarrowb"]
    histoObjects   = []
    results        = []
        
    # For-loop: All partons
    for i, parton in enumerate(myPartons, 0):
        counter = i+1
        msg = "{:<9} {:>3} {:<1} {:<3} {:<50}".format("Histogram", "%d" % counter, "/", "%s:" % (len(myPartons)), "%s->b for %s" % (parton.lower(), btagWP))
        Print(ShellStyles.SuccessStyle() + msg + ShellStyles.NormalStyle(), counter==1)
            
        n = "All%sjets" % parton
        if parton == "B":
            dsetHisto = genuineBDataset.getDatasetRootHisto(n)
        elif (parton == "C" or parton == "Light"):
            dsetHisto = fakeBDataset.getDatasetRootHisto(n)
        else:
             raise Exception("This should never be reached")

        dsetHisto.normalizeToLuminosity(lumi)
        hAll = dsetHisto.getHistogram()

        if hAll == None:
            raise Exception("Error: could not find histogram '%s'!"%n)
        treatNegativeBins(hAll)

        n = "Selected%sjets" % parton
        if parton == "B":  
            dsetHisto = genuineBDataset.getDatasetRootHisto(n)

        if (parton == "C" or parton == "G" or parton == "Light"):
            dsetHisto = fakeBDataset.getDatasetRootHisto(n)

        # Normalise to luminosity
        dsetHisto.normalizeToLuminosity(lumi)

        # Get Numerator. Treate -ve bins
        hPassed = dsetHisto.getHistogram()
        if hPassed == None:
            raise Exception("Error: could not find histogram '%s'!"%n)
        treatNegativeBins(hPassed)

        # Find proper binning
        myBinEdges = []
        for k in range(1, hPassed.GetNbinsX()+1):
            if len(myBinEdges) > 0 or hPassed.GetBinContent(k) > 0:
                myBinEdges.append(hPassed.GetXaxis().GetBinLowEdge(k))
        myBinEdges.append(hPassed.GetXaxis().GetBinUpEdge(hPassed.GetNbinsX()))
        myArray    = array.array("d", myBinEdges)
        hAllNew    = hAll.Rebin(len(myArray)-1, "", myArray)
        hPassedNew = hPassed.Rebin(len(myArray)-1, "", myArray)
        (hPassed, hAll) = findProperBinning(hPassedNew, hAllNew, myBinEdges, errorlevel)

        # For-loop: All x-axis bins
        for k in range(hPassed.GetNbinsX()+2):
            # Treat fluctuations
            if hPassed.GetBinContent(k) > hAll.GetBinContent(k):
                hPassed.SetBinContent(k, hAll.GetBinContent(k))

        # Construct efficiency plot
        eff = ROOT.TEfficiency(hPassed, hAll)
        eff.SetStatisticOption(ROOT.TEfficiency.kFNormal)

        # For-loop: All x-axis bins
        for k in range(hPassed.GetNbinsX()):
            resultObject = {}
            resultObject["flavor"]       = parton
            resultObject["ptMin"]        = hPassed.GetXaxis().GetBinLowEdge(k+1)
            resultObject["ptMax"]        = hPassed.GetXaxis().GetBinUpEdge(k+1)
            resultObject["eff"]          = eff.GetEfficiency(k+1)
            resultObject["effUp"]        = eff.GetEfficiencyErrorUp(k+1)
            resultObject["effDown"]      = eff.GetEfficiencyErrorLow(k+1)
            resultObject["discr"]        = discrName
            resultObject["workingPoint"] = discrWP
            results.append(resultObject)

        # Apply style
        styles.styles[i].apply(eff)
        hobj = histograms.HistoEfficiency(eff, myPartonLabels[i], legendStyle="P", drawStyle="P")
        hobj.setIsDataMC(False, True)
        histoObjects.append(hobj)

    # Create the plot
    myPlot = plots.PlotBase(histoObjects, saveFormats=[])
    myPlot.setLuminosity(lumi)
    myPlot.setEnergy("13")
    #myPlot.setDefaultStyles()

    # Add btag WP to canvas
    myPlot.appendPlotObject(histograms.PlotText(0.70, 0.48-0.16, btagWP, bold=True, size=20))

    # Create the plotting object  
    drawPlot = plots.PlotDrawer(ratio=False, addLuminosityText=False, cmsTextPosition="outframe")

    # Create the plotting object
    drawPlot(myPlot, "%s_%s" % ("Hybrid", name), **GetKwargs(name, btagWP, opts))
    
    # Save the plot in custom formats
    SavePlot(myPlot, name, opts.saveDir, saveFormats = [".C", ".png", ".pdf"])
    return results
示例#10
0
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    rootHistos = []
    bdiscList  = ["Loose", "Medium"]
    saveName   = histoName.rsplit("/")[-1]
    kwargs     = GetHistoKwargs(saveName, opts)
    myBdiscs   = []
    histoName  = histoName.replace(opts.folder, "")
    stylesList = [styles.FakeBStyle1, styles.FakeBStyle3, styles.FakeBStyle2, styles.FakeBStyle4] 
    #stylesList = [styles.fakeBLineStyle1, styles.FakeBStyle2, styles.FakeBStyle3, styles.FakeBStyle4] 

    # For-loop: All histograms in all regions
    for bdisc in bdiscList:
        
        hName_ = histoName.replace(opts.refBdisc, bdisc)
        hName = opts.folder + "/" + hName_

        if "Data" in datasetsMgr.getAllDatasetNames():
            p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])
        else:
            p = plots.MCPlot(datasetsMgr, hName, normalizeToLumi=opts.intLumi, saveFormats=[])
            
        # Append (non-empty) dataset ROOT histos to a list for plotting
        h = p.histoMgr.getHisto(opts.dataset).getRootHisto()
        if h.GetEntries() > 0:
            h.SetName(bdisc)
            rootHistos.append(h)
            myBdiscs.append(bdisc)

    # Create a comparison plot for a given dataset in all CRs
    if len(rootHistos) < 2:
        Print("Cannot plot comparison due to too few non-empty histograms present (=%i)" % (len(rootHistos)), False)
        return

    # Move ref histo to top of rootHisto list
    for rh in rootHistos:
        if opts.refBdisc in rh.GetName():
            s = rootHistos.pop( rootHistos.index(rh) )
            #rootHistos.insert(0, s)
            rootHistos.insert(len(rootHistos), s)

    # Draw the comparison plot (first argument the reference histo for ratio purposes)
    p = plots.ComparisonManyPlot(rootHistos[-1], rootHistos[:-1], saveFormats=[])
    # p = plots.ComparisonManyPlot(rootHistos[0], rootHistos[1:], saveFormats=[])
    p.setLuminosity(opts.intLumi)

    if opts.normalizeToOne:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(1.0/h.getRootHisto().Integral()))

    # Apply drawing/legend styles
    for i, bdisc in enumerate(myBdiscs, 0):
        stylesList[i].apply(p.histoMgr.getHisto(bdisc).getRootHisto())
        if bdisc == opts.refBdisc:
            p.histoMgr.setHistoDrawStyle(bdisc, "AP")
            p.histoMgr.setHistoLegendStyle(bdisc,"LP")
        else:
            p.histoMgr.setHistoDrawStyle(bdisc, "AP")
            p.histoMgr.setHistoLegendStyle(bdisc, "LP")
            #p.histoMgr.setHistoDrawStyle(bdisc, "HIST")
            #p.histoMgr.setHistoLegendStyle(bdisc, "F")
            
    # Add dataset name on canvas
    p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset], bold=True, size=22))
    #p.appendPlotObject(histograms.PlotText(0.18, 0.88, plots._legendLabels[opts.dataset + " (%s)" % ], bold=True, size=22))

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            "Loose" : "Loose (%s)"  % (GetCRLabel(histoName)),
            "Medium": "Medium (%s)" % (GetCRLabel(histoName)),
            })
    
    # Draw the plot
    plots.drawPlot(p, saveName, **kwargs) #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"] )
    return
def PlotHistograms(datasetsMgr, histoName):

    # Get Histogram name and its kwargs
    rootHistos = []
    regionsList = ["SR", "VR", "CRone", "CRtwo"]
    hRegion = histoName.split("_")[-1]
    saveName = histoName.rsplit("/")[-1]
    saveName = saveName.replace("_" + hRegion, "")
    kwargs = GetHistoKwargs(saveName, opts)
    myRegions = []

    # For-loop: All histograms in all regions
    for region in regionsList:
        hName = histoName.replace(hRegion, region)
        if "Data" in datasetsMgr.getAllDatasetNames():
            p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])
        else:
            p = plots.MCPlot(datasetsMgr,
                             hName,
                             normalizeToLumi=opts.intLumi,
                             saveFormats=[])

        # Append (non-empty) dataset ROOT histos to a list for plotting
        h = p.histoMgr.getHisto(opts.dataset).getRootHisto()
        if h.GetEntries() > 0:
            h.SetName(region)
            rootHistos.append(h)
            myRegions.append(region)

    # Create a comparison plot for a given dataset in all CRs
    if len(rootHistos) == 0:
        return
    else:
        p = plots.ComparisonManyPlot(rootHistos[0],
                                     rootHistos[1:],
                                     saveFormats=[])
        p.setLuminosity(opts.intLumi)

    if opts.normalizeToOne:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(
            1.0 / h.getRootHisto().Integral()))

    # Drawing style
    p.histoMgr.setHistoDrawStyleAll("AP")
    p.histoMgr.setHistoLegendStyleAll("LP")

    # Apply styles
    for h in rootHistos:
        region = h.GetName()
        if region == "SR":
            styles.fakeBLineStyle1.apply(
                p.histoMgr.getHisto(region).getRootHisto())
            p.histoMgr.setHistoDrawStyle(region, "HIST")
            p.histoMgr.setHistoLegendStyle(region, "L")
        else:
            styles.getABCDStyle(region).apply(
                p.histoMgr.getHisto(region).getRootHisto())

    # Add dataset name on canvas
    p.appendPlotObject(
        histograms.PlotText(0.18,
                            0.88,
                            plots._legendLabels[opts.dataset],
                            bold=True,
                            size=22))

    # Set legend labels
    if "CRone" in myRegions:
        p.histoMgr.setHistoLegendLabelMany({
            "CRone": "CR1",
        })
    if "CRtwo" in myRegions:
        p.histoMgr.setHistoLegendLabelMany({
            "CRtwo": "CR2",
        })

    # Draw the plot
    plots.drawPlot(p, saveName,
                   **kwargs)  #the "**" unpacks the kwargs_ dictionary

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"])
    return
示例#12
0
def PlotHistograms(datasetsMgr, histoList, binLabels, opts):
    '''
    histoList contains all histograms for all bins for CR1 and CR2 
    
    '''
    # Get the root histos for all datasets and Control Regions (CRs)
    rhDict = GetRootHistos(datasetsMgr, histoList)

    # Get unique a style for each region
    for key1 in rhDict:

        # Definitions
        region1 = "CRone"
        region2 = "CRtwo"
        key2 = key1.replace(region1, region2)
        dataset = key1.split("-")[0]
        region = key1.split("-")[1]
        bin = key1.split("-")[2]
        hName1 = rhDict[key1].GetName()
        hName2 = rhDict[key2].GetName()
        bInclusive = "Inclusive" in key1

        # Dataset and Region filter
        if dataset != "FakeB":
            continue
        if region != region1:
            continue

        # Normalise to unity
        if bInclusive:
            rFakeB_CRone = rhDict[key1].Clone()
            w1 = rFakeB_CRone.Integral()
            rFakeB_CRone.Reset()

            rFakeB_CRtwo = rhDict[key2].Clone()
            w2 = rFakeB_CRtwo.Integral()
            rFakeB_CRtwo.Reset()

            for i, b in enumerate(binLabels, 1):
                if "Inclusive" in b:
                    continue
                # Determine keys
                k1 = key1.replace("Inclusive", b)
                k2 = key2.replace("Inclusive", b)

                # Normalise bin histo to one (before adding to inclusive histo)
                h1 = rhDict[k1].Clone()
                h2 = rhDict[k2].Clone()
                h1.Scale(1.0 / h1.Integral())
                h2.Scale(1.0 / h2.Integral())

                # Add this binned histo to the inclusive histo
                Verbose("Adding %s" % k1, True)
                rFakeB_CRone += h1  #rhDict[k1]
                rFakeB_CRtwo += h2  #rhDict[k2]
        else:
            # Get the histos
            rFakeB_CRone = rhDict[key1]
            rFakeB_CRtwo = rhDict[key2]

        # Normalise the histos?
        if opts.normaliseToOne:
            rFakeB_CRone.Scale(1.0 / rFakeB_CRone.Integral())
            rFakeB_CRtwo.Scale(1.0 / rFakeB_CRtwo.Integral())

        # Apply histogram styles
        styles.getABCDStyle("CRone").apply(rFakeB_CRone)
        styles.getABCDStyle("CRtwo").apply(rFakeB_CRtwo)

        # Create the plot
        p = plots.ComparisonManyPlot(rFakeB_CRone, [rFakeB_CRtwo],
                                     saveFormats=[])
        p.setLuminosity(opts.intLumi)

        # Set draw/legend style
        p.histoMgr.setHistoDrawStyle(hName1, "AP")
        p.histoMgr.setHistoDrawStyle(hName2, "HIST")
        p.histoMgr.setHistoLegendStyle(hName1, "LP")
        p.histoMgr.setHistoLegendStyle(hName2, "F")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            hName1: "CR1",
            hName2: "CR2",
        })

        # Draw the plot and save it
        if bin == "Inclusive":
            histoName = histoList[0] + "_CR1vCR2"
        else:
            histoName = histoList[0] + "_CR1vCR2_bin%s" % (bin)
        saveName = histoName.split("/")[-1].replace("CRone0_",
                                                    "").replace("CRtwo0_", "")

        # Get the histogram customisations (keyword arguments)
        p.appendPlotObject(
            histograms.PlotText(0.20,
                                0.88,
                                GetBinText(bin),
                                bold=True,
                                size=22))
        plots.drawPlot(p, saveName, **GetHistoKwargs(saveName))
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, opts.optMode),
                 saveFormats=[".png", ".pdf"])
    return
示例#13
0
def doPlot(tree):
    #    tree.Draw("BRT:BRH >>htemp(100,0,1, 100,0,1)", "deltaNLL * (deltaNLL < 0.5", "colz goff")
    #    sigma1 = ROOT.gDirectory.Get("htemp").Clone("sigma1")

    tree.Draw("BRT:BRH >>htemp(100,0,1, 100,0,1)",
              "deltaNLL * (deltaNLL <= 2)", "colz")
    sigma2 = ROOT.gDirectory.Get("htemp").Clone("sigma2")

    bfBRT = None
    bfBRH = None

    for entry in tree:
        if entry.quantileExpected == 1:
            bfBRT = entry.BRT
            bfBRH = entry.BRH
            break

    print "Best fit B(t->H+) %.8f, B(H+->tau) %.8f" % (bfBRT, bfBRH)

    bestFit = ROOT.TGraph(1, array.array("d", [bfBRH]),
                          array.array("d", [bfBRT]))
    bestFit.SetMarkerStyle(34)
    bestFit.SetMarkerSize(2)
    histos = [
        histograms.HistoGraph(bestFit,
                              "bestFit",
                              drawStyle="P",
                              legendLabel="Best fit",
                              legendStyle="P"),
        histograms.Histo(sigma2, "sigma2", drawStyle="COLZ", legendLabel=None),
    ]

    brt = "#it{B}_{t#rightarrow bH^{+}}"
    brh = "#it{B}_{H^{+}#rightarrow#tau#nu}"
    legend_h = 0.1

    if opts.bxblimit is not None:
        limit_tf = ROOT.TF1("bxblimit", "%s/x" % opts.bxblimit)
        limit_tf.SetLineWidth(2)
        limit_tf.SetLineStyle(2)
        limit_tf.SetLineColor(ROOT.kBlack)
        histos.insert(
            1,
            histograms.Histo(
                limit_tf,
                "bxblimit",
                legendLabel="Exp. limit on {brt}#times{brh}\n={limit:.2f}%".
                format(brt=brt, brh=brh, limit=float(opts.bxblimit) * 100)))
        legend_h += 0.03

    plot = plots.PlotBase(histos)

    x = 0.4
    y = 0.87
    dy = 0.05
    plot.appendPlotObject(
        histograms.PlotText(x,
                            y,
                            "HH: {brt}^{{2}} #times {brh}^{{2}}".format(
                                brt=brt, brh=brh),
                            bold=False,
                            size=20))
    y -= dy
    #plot.appendPlotObject(histograms.PlotText(x, y, "HW: 2(1-{brt}){brt} #times {brh}".format(brt=brt, brh=brh), bold=False, size=20))
    plot.appendPlotObject(
        histograms.PlotText(x,
                            y,
                            "HW: 2(1-{brt}{brh}){brt}{brh}".format(brt=brt,
                                                                   brh=brh),
                            bold=False,
                            size=20))  # mod1
    y -= dy
    #plot.appendPlotObject(histograms.PlotText(x, y, "WW: (1-{brt})^{{2}}".format(brt=brt), bold=False, size=20))
    plot.appendPlotObject(
        histograms.PlotText(x,
                            y,
                            "WW: (1-{brt}{brh})^{{2}}".format(brt=brt,
                                                              brh=brh),
                            bold=False,
                            size=20))  # mod2
    y -= dy * 2
    if opts.mass is not None:
        plot.appendPlotObject(
            histograms.PlotText(x,
                                y,
                                "m_{H^{+}} = %s GeV" % opts.mass,
                                bold=False,
                                size=20))
        y -= dy
    plot.appendPlotObject(
        histograms.PlotText(x,
                            y,
                            "Fit to bkg-only Asimov dataset",
                            bold=False,
                            size=20))

    y -= 0.01
    plots.drawPlot(plot,
                   opts.name,
                   xlabel=brh,
                   ylabel=brt,
                   zlabel="#DeltaLL",
                   zhisto="sigma2",
                   opts={"ymax": 1.0},
                   createLegend={
                       "x1": x,
                       "y2": y,
                       "x2": x + 0.2,
                       "y1": y - legend_h
                   })