示例#1
0
def main():
    effDir = "../multicrab_aodAnalysis_taumet_v53_3_131015_122226_triggerTestEff"
    bitDir = "."

    datasets = aux.MultiObject()
    datasets.add(
        "eff",
        dataset.getDatasetsFromMulticrabCfg(directory=effDir, dataEra=era))
    datasets.add(
        "bit",
        dataset.getDatasetsFromMulticrabCfg(directory=bitDir, dataEra=era))

    datasets.forEach(plots.mergeRenameReorderForDataMC)

    style = tdrstyle.TDRStyle()
    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    histograms.createLegend.setDefaults(y1=0.93, y2=0.8, x1=0.82, x2=0.93)
    histograms.createLegend.moveDefaults(dx=-0.05)
    plots._plotStyles["Ratio"].extend([
        styles.StyleMarker(markerColor=ROOT.kRed),
        styles.StyleLine(lineColor=ROOT.kRed)
    ])
    plots._plotStyles["RatioLine"].extend(
        [styles.StyleLine(lineColor=ROOT.kBlack)])

    plots.drawPlot.setDefaults(addLuminosityText=True)

    doPlots(*(datasets.getDataset("TTJets")))
示例#2
0
def doPlotsWTauMuRatio(dsetMgr, selectionName, ratios, unweighted,
                       fitFunction):
    prefix = era + "_" + selectionName + "_fitFunction%d" % fitFunction + unweighted + "_"

    st = [s.clone() for s in styles.getStyles()]
    st[0].marker = 33
    st[1].marker = 26
    st[2].marker = 32
    st = [
        styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)])
        for s in st
    ]

    # Do clone to get rid of statistics box
    p = plots.PlotBase([x[0].Clone() for x in ratios])
    p.setEnergy(dsetMgr.getEnergies())
    p.histoMgr.setHistoDrawStyleAll("P")
    p.histoMgr.setHistoLegendStyleAll("P")
    p.histoMgr.forEachHisto(styles.Generator(st))
    for i, x in enumerate(ratios):
        fitLine = x[1]
        st[i].apply(fitLine)
        p.appendPlotObject(fitLine)

    def customize(plot):
        xmin = plot.frame.GetXaxis().GetXmin()
        xmax = plot.frame.GetXaxis().GetXmax()

        val = 1
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

        val = 1 - 0.038479
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kBlue)
        l.SetLineStyle(4)
        plot.prependPlotObject(l)
        plot.appendPlotObject(
            histograms.PlotText(0.18, 0.57, "0.038", size=18,
                                color=ROOT.kBlue))

    plots.drawPlot(p,
                   prefix + "WMuFraction",
                   "Muon p_{T} (GeV/c)",
                   ylabel="W#rightarrow#mu fraction",
                   opts={
                       "ymin": 0.9,
                       "ymax": 1.02
                   },
                   moveLegend={
                       "dh": -0.15,
                       "dx": -0.5
                   },
                   customizeBeforeDraw=customize)
def plotTurnOnData(datasets,
                   name,
                   pathAll,
                   pathPassed1,
                   pathPassed2,
                   dataText1,
                   dataText2,
                   rebin=1,
                   ratio=False):
    dataLabel1 = "Data: " + dataText1
    dataLabel2 = "Data: " + dataText2

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

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

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

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

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

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

    common(p, "Uncorrected PF E_{T}^{miss} (GeV)", "Efficiency")
示例#4
0
    def __init__(self, datasets, dname, names, labels):
        plots.PlotBase.__init__(self, [])

        self.name = dname
        self.ylabel = "Efficiency"

        for hname, label in zip(names, labels):
            dh = datasets.getDataset(dname).getDatasetRootHisto(hname)
            dh.normalizeByCrossSection()
            dh = dataset.DatasetRootHisto(
                muonAnalysis.dist2eff(dh.getHistogram()), dh.getDataset())
            dh.setName(label)
            self.histoMgr.append(dh)

        self.histoMgr.forEachHisto(
            styles.generator2(styles.StyleMarker(markerSize=1.5), plotStyles))
        self.histoMgr.setHistoLegendStyleAll("l")
示例#5
0
    def finalize(self):
        def setLabel(histo):
            name = histo.getName()
            scic_re = re.compile("Sc(?P<sig>\d+)(Ic(?P<iso>\d+))?")
            ic_re = re.compile("Ic(?P<iso>\d+)")
            for tauIso in ["VLoose", "Loose", "Medium", "Tight"]:
                if "IsoTau" + tauIso in name:
                    histo.setLegendLabel('Counting iso "' + tauIso + '"')
                    break
                if "IsoTauLike" + tauIso in name:
                    m = scic_re.search(name)
                    sc = "0.1"
                    ic = "0.5"
                    if m:
                        sc = m.group("sig").replace("0", "0.")
                        if m.group("iso"):
                            ic = m.group("iso").replace("0", "0.")
                    else:
                        m = ic_re.search(name)
                        if m:
                            ic = m.group("iso").replace("0", "0.")
                    label = 'Counting iso "' + tauIso + '" %s < DR < %s' % (sc,
                                                                            ic)
                    print label
                    histo.setLegendLabel(label)

        self.histoMgr.setHistoLegendLabelMany({
            "sumIsoRel": "Rel iso",
            "pfSumIsoRel": "PF rel iso",
            "sumIsoRelFull": "Rel iso",
            "pfSumIsoRelFull": "PF rel iso",
        })
        self.histoMgr.forEachHisto(setLabel)

        self.histoMgr.forEachHisto(
            styles.generator2(styles.StyleMarker(markerSize=1.5), plotStyles))
        self.defaultStyle()
示例#6
0
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tdrstyle as tdrstyle
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.styles as styles
from HiggsAnalysis.HeavyChHiggsToTauNu.tools.cutstring import *  # And, Not, Or
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.crosssection as xsect
import HiggsAnalysis.HeavyChHiggsToTauNu.tools.tauEmbedding as tauEmbedding

analysisEmb = "signalAnalysisCaloMet60TEff"
analysisSig = "signalAnalysisGenuineTau"  # require that the selected tau is genuine, valid comparison after njets

plotStyles = [
    styles.StyleCompound([s, styles.StyleLine(lineWidth=4)])
    for s in styles.styles[0:2]
]
plotStyles[0] = styles.StyleCompound(
    [plotStyles[0],
     styles.StyleMarker(markerStyle=21, markerSize=1.2)])

#taujet = "#tau jet"
#taujetH = "#tau-jet"
taujet = "#tau_{h}"
taujetH = "#tau_{h}"


def main():
    # Adjust paths such that this script can be run inside the first embedding trial directory
    dirEmbs = ["."] + [os.path.join("..", d) for d in tauEmbedding.dirEmbs[1:]]
    dirSig = "../" + tauEmbedding.dirSig

    # Create the dataset objects
    datasetsEmb = tauEmbedding.DatasetsMany(dirEmbs,
                                            analysisEmb + "Counters",
示例#7
0
    def Save(self, name):

        hObserved = self.CreateGraph("Observed")
        hExpected = self.CreateGraph("Expected")
        hExpected1s = self.CreateGraph("Expected1")
        hExpected1s.SetFillColor(ROOT.kYellow)
        hExpected2s = self.CreateGraph("Expected2")
        hExpected2s.SetFillColor(ROOT.kOrange)

        style = tdrstyle.TDRStyle()

        plot = plots.ComparisonManyPlot(
            histograms.HistoGraph(hObserved, "Observed"), [
                histograms.HistoGraph(hExpected, "Expected"),
                histograms.HistoGraph(hExpected1s, "Expected1"),
                histograms.HistoGraph(hExpected2s, "Expected2")
            ])

        obsStyle = styles.getDataStyle().clone()
        plot.histoMgr.forHisto("Observed", styles.getDataStyle().clone())
        plot.histoMgr.setHistoDrawStyle("Observed", "PL")

        expStyle = styles.getDataStyle().clone()
        expStyle.append(styles.StyleLine(lineStyle=2))
        expStyle.append(styles.StyleLine(lineColor=ROOT.kRed))
        expStyle.append(styles.StyleMarker(markerStyle=ROOT.kFullSquare))
        expStyle.append(styles.StyleMarker(markerColor=ROOT.kRed))
        plot.histoMgr.forHisto("Expected", expStyle)
        plot.histoMgr.setHistoDrawStyle("Expected", "PL")
        plot.histoMgr.setHistoDrawStyle("Expected1", "PL3")
        plot.histoMgr.setHistoDrawStyle("Expected2", "PL3")

        plot.createFrame(name,
                         opts={
                             "xmin": 70.1,
                             "xmax": 169.9,
                             "ymin": 0,
                             "ymax": 0.2
                         })
        plot.frame.GetXaxis().SetTitle(self.xtitle)
        plot.frame.GetYaxis().SetTitle(self.ytitle)

        plot.histoMgr.setHistoLegendStyle("Observed", "PL")
        plot.histoMgr.setHistoLegendStyle("Expected", "PL")
        plot.histoMgr.setHistoLegendStyle("Expected1", "F")
        plot.histoMgr.setHistoLegendStyle("Expected2", "F")

        plot.histoMgr.setHistoLegendLabelMany({
            "Expected":
            "Expected median",
            "Expected1":
            "Expected median #pm1#sigma",
            "Expected2":
            "Expected median #pm2#sigma"
        })
        plot.setLegend(histograms.createLegend(0.55, 0.68, 0.9, 0.93))

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

        textSize = 16
        textX = 0.19
        textY = 0.8
        textDY = 0.038
        histograms.addText(textX, textY + 2 * textDY,
                           "t#rightarrowbH^{#pm}, H^{#pm}#rightarrow#tau#nu",
                           textSize)
        histograms.addText(textX, textY + textDY, "Fully hadronic final state",
                           textSize)
        histograms.addText(textX, textY,
                           "BR(H^{#pm}#rightarrow#tau^{#pm} #nu) = 1",
                           textSize)

        plot.draw()
        plot.save()
示例#8
0
        return self._cache[dsetName].histogram(name)
systematicsSigMC = SystematicsSigMC()

systematicsEmbData = dataset.Systematics(shapes=[
    "SystVarMuonIdDataEff",
    "SystVarMuonTrgDataEff",
    "SystVarWTauMu",
    "SystVarEmbMTWeight",
], additionalNormalizations = {
    "CaloMETApproximation": 0.12,
    "QCDContamination": 0.02,
})


plotStyles = styles.styles[0:2]
plotStyles[0] = styles.StyleCompound([plotStyles[0], styles.StyleMarker(markerStyle=21, markerSize=1.2)])

def main():
    parser = OptionParser(usage="Usage: %prog [options]")
    parser.add_option("--dirSig", dest="dirSig", default=None,
                      help="Path to signalAnalysisGenTau multicrab directory")

    (opts, args) = parser.parse_args()
    if opts.dirSig is None:
        parser.error("--dirSig missing")

    dirEmb = "."
    dirSig = opts.dirSig

    # Apply TDR style
    style = tdrstyle.TDRStyle()
def main():
    parser = OptionParser(usage="Usage: %prog [options]")
    parser.add_option("--dirSig",
                      dest="dirSig",
                      default=None,
                      help="Path to signalAnalysisGenTau multicrab directory")
    parser.add_option("--nortau",
                      dest="nortau",
                      default=False,
                      action="store_true",
                      help="Is Rtau cut disabled?")
    parser.add_option("--notrigger",
                      dest="notrigger",
                      default=False,
                      action="store_true",
                      help="Is tau+MET trigger disabled?")
    parser.add_option("--dofit",
                      dest="dofit",
                      default=False,
                      action="store_true",
                      help="Do the fit on mT slope on ttbar?")

    (opts, args) = parser.parse_args()
    if opts.dirSig is None:
        parser.error("--dirSig missing")

    dirEmb = "."
    dirSig = opts.dirSig

    global analysisSig, systematicsSigMC
    if opts.notrigger:
        analysisSig = analysisSig.replace("Triggered", "")
        systematicsSigMC = dataset.Systematics()

    # Apply TDR style
    style = tdrstyle.TDRStyle()

    styles.styles[1] = styles.StyleCompound(
        [styles.styles[1],
         styles.StyleMarker(markerStyle=25)])

    histograms.cmsTextMode = histograms.CMSMode.SIMULATION_PRELIMINARY
    #    histograms.cmsTextMode = histograms.CMSMode.SIMULATION
    #    histograms.cmsTextMode = histograms.CMSMode.SIMULATION_UNPUBLISHED
    #    histograms.cmsTextMode = histograms.CMSMode.UNPUBLISHED
    #histograms.createLegend.setDefaults(y1=0.93, y2=0.75, x1=0.52, x2=0.93)
    histograms.createLegend.setDefaults(textSize=0.04)
    histograms.createLegend.moveDefaults(dx=-0.25, dh=-0.2, dy=-0.12)

    histograms.createLegendRatio.setDefaults(ncolumns=2,
                                             textSize=0.08,
                                             columnSeparation=0.6)
    histograms.createLegendRatio.moveDefaults(dx=-0.48, dh=-0.1, dw=0.25)

    if opts.dofit:
        histograms.uncertaintyMode.set(histograms.uncertaintyMode.StatOnly)
        histograms.createLegendRatio.moveDefaults(dw=-0.25)
        plots._legendLabels["BackgroundStatError"] = "Emb. stat. unc."
        plots._legendLabels[
            "BackgroundStatSystError"] = "Emb. stat.#oplussyst. unc."
    else:
        histograms.uncertaintyMode.set(histograms.uncertaintyMode.StatAndSyst)
        #        plots._legendLabels["BackgroundStatError"] = "Norm. stat. unc."
        #        plots._legendLabels["BackgroundStatSystError"] = "Norm. stat.#oplussyst. unc."
        plots._legendLabels["BackgroundStatError"] = "Non-emb. stat. unc."
        plots._legendLabels[
            "BackgroundStatSystError"] = "Non-emb. stat.#oplussyst. unc."
    plots._legendLabels["Data"] = "Embedded data"
    plots._legendLabels["EWKMC"] = "EWK+t#bar{t}"
    #    plots._legendLabels["EWKMC"] = "Non-emb. EWK+t#bar{t} with ^{}#tau_{h}"

    postfix = ""
    if opts.dofit:
        postfix = "_fit"

    for optMode in [
            #        "OptQCDTailKillerNoCuts",
            "OptQCDTailKillerLoosePlus",
            #        "OptQCDTailKillerMediumPlus",
            #        "OptQCDTailKillerTightPlus",
            #            None
    ]:
        datasetsEmb = dataset.getDatasetsFromMulticrabCfg(
            directory=dirEmb,
            dataEra=dataEra,
            analysisName=analysisEmb,
            optimizationMode=optMode)
        datasetsSig = dataset.getDatasetsFromMulticrabCfg(
            directory=dirSig,
            dataEra=dataEra,
            analysisName=analysisSig,
            optimizationMode=optMode)
        doDataset(datasetsEmb, datasetsSig, optMode + postfix, opts)
        datasetsEmb.close()
        datasetsSig.close()

        tauEmbedding.writeToFile(
            optMode + postfix, "input.txt",
            "Embedded: %s\nSignal analysis (GenTau): %s\n" %
            (os.getcwd(), dirSig))
示例#10
0
    def cutefficiency(self, histo1, histo2):

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

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

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

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

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

            iBin = iBin + 1

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

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

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

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

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

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

            iBin = iBin + 1

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

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

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

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

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

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

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

        plot.draw()
        plot.save()

        ######

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

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

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

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

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

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

        numberOfParameters = 2

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

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

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

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

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

        plot2.draw()
        plot2.save()
示例#11
0
    def comparison(self, histo1, histo2, norm=1):

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

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

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

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

            iBin = iBin + 1

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

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

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

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

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

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

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

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

        plot.draw()
        plot.save()
def plotTurnOn(datasets,
               pathAll,
               pathPassed,
               commonText,
               dataText=None,
               mcText=None,
               rebin=1,
               ratio=False):
    dataLabel = "Data"
    mcLabel = "Simulation"
    if dataText != None and mcText == None:
        raise Exception("mcText must not be None when dataText is not")
    if dataText == None and mcText != None:
        raise Exception("dataText must not be None when mcText is not")


#    if dataText != None:
#        dataLabel += ": "+dataText
#        mcLabel += ": "+mcText

    mc_effs = []
    data_eff_gr = None
    binWidth = None
    luminosity = 0
    for dataset in datasets.getAllDatasets():
        all = dataset.getDatasetRootHisto(pathAll).getHistogram()
        passed = dataset.getDatasetRootHisto(pathPassed).getHistogram()

        if rebin > 1:
            all.Rebin(rebin)
            passed.Rebin(rebin)
        binWidth = all.GetBinWidth(1)

        if dataset.isMC() and not "TTTo" in dataset.getName():
            #if dataset.isMC() and not "TTTo" in dataset.getName() and not "QCD" in dataset.getName():
            #if dataset.isMC() and "QCD" in dataset.getName():
            mc_effs.append(HistoEff(all, passed, dataset))

        elif dataset.isData():
            data_eff_gr = ROOT.TGraphAsymmErrors(passed, all,
                                                 "cp")  # 0.683 cl is default
            luminosity += dataset.getLuminosity()

    mc_eff_gr = combineHistoEffs(mc_effs)

    p = plots.ComparisonPlot(
        histograms.HistoGraph(data_eff_gr, "Data", "p", "P"),
        histograms.HistoGraph(mc_eff_gr, "Simulation", "p", "P"))
    p.histoMgr.forEachHisto(
        styles.generator2(styles.StyleMarker(markerSizes=[1.0, 1.5]),
                          plotStyles))
    p.histoMgr.setHistoLegendLabelMany({
        "Data": dataLabel,
        "Simulation": mcLabel,
    })
    p.setLuminosity(luminosity)
    #p.addGraph(data_eff_gr, "Data")
    #p.addGraph(mc_eff_gr, "Simulation")
    #p.finalize()

    opts = {"ymin": 0.0, "ymax": 1.1}
    #opts2 = {"ymin": 0.5, "ymax": 1.5}
    opts2 = {"ymin": 0.7, "ymax": 1.3}

    name = "calomet_turnon_" + runs
    if not mcDataDefinition:
        name += "_McSummer11"
    if caloMetNoHF:
        name += "_caloMetNoHF"

    p.createFrame(name, createRatio=ratio, opts=opts, opts2=opts2)
    if ratio:
        p.getFrame2().GetYaxis().SetTitle("Ratio")
        p.cf.canvas.cd(2)
        p.line1 = plots._createRatioLine(p.cf.frame.getXmin(),
                                         p.cf.frame.getXmax(), 0.9)
        p.line2 = plots._createRatioLine(p.cf.frame.getXmin(),
                                         p.cf.frame.getXmax(), 1.1)
        p.line1.SetLineColor(ROOT.kBlue)
        p.line2.SetLineColor(ROOT.kBlue)
        p.line1.Draw("L")
        p.line2.Draw("L")
        p.cf.canvas.cd(1)

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

    x = 0.25
    y = 0.3
    dy = 0.035
    mcColor = mc_eff_gr.GetMarkerColor()
    size = 17
    p.appendPlotObject(
        histograms.PlotText(x, y, "Data (runs %s):" % runs, size=size))
    y -= dy
    p.appendPlotObject(histograms.PlotText(x, y, dataText, size=size))
    y -= dy

    y -= 0.01
    p.appendPlotObject(
        histograms.PlotText(x, y, "Simulation:", size=size, color=mcColor))
    y -= dy
    p.appendPlotObject(
        histograms.PlotText(x, y, mcText, size=size, color=mcColor))
    y -= dy

    def text():
        l = ROOT.TLatex()
        l.SetNDC()
        #        l.SetTextFont(l.GetTextFont()-20) # bold -> normal
        l.SetTextSize(l.GetTextSize() * 0.65)
        #l.DrawLatex(0.35, 0.4, commonText)
        l.DrawLatex(0.48, 0.32, commonText)

    textFunction = text
    if dataText != None:
        textFunction = None
    #common(p, "PF E_{T}^{miss} (GeV)", "Efficiency / %.0f GeV"%binWidth, afterDraw=textFunction)
    common(p,
           "Uncorrected PF E_{T}^{miss} (GeV)",
           "Efficiency",
           afterDraw=textFunction)
示例#13
0
def doPlotsWTauMuRatioUncertaintyEstimate(dsetMgr, ratios, analysisName):
    prefix = era + "_"

    st = [s.clone() for s in styles.getStyles()]
    st[0].marker = 33
    st = [
        styles.StyleCompound(styles=[s, styles.StyleMarker(markerSize=1.5)])
        for s in st
    ]

    # Nominal
    p = plots.PlotBase([ratios[analysisName][0].Clone()])
    p.setEnergy(dsetMgr.getEnergies())
    p.histoMgr.setHistoDrawStyleAll("P")
    p.histoMgr.setHistoLegendStyleAll("P")
    p.histoMgr.forEachHisto(styles.Generator(st))

    fitLine = ratios[analysisName][1]
    st[0].apply(fitLine)
    p.appendPlotObject(fitLine)

    # Stat. unc. from parameters
    pars = [fitLine.GetParameter(i) for i in xrange(0, fitLine.GetNpar())]
    parErrors = [fitLine.GetParError(i) for i in xrange(0, fitLine.GetNpar())]

    def evalPar(x, i, shift):
        pars_ = pars[:]
        pars_[i] += shift
        return fitLine.EvalPar(x, array.array("d", pars_))

    # Fit function
    fits = [
        ratios[analysisName + "SystFunc0"][1],
        ratios[analysisName + "SystFunc1"][1]
    ]

    def maxDiff(x, tf1s, nominal):
        return max([abs(tf1.Eval(x[0]) - nominal) for tf1 in tf1s])

    # Sample
    samples = [
        ratios[analysisName + "SystWJets"][1],
        ratios[analysisName + "SystSingleTop"][1]
    ]

    # Weight systematic variations
    keys = filter(lambda n: "SystVar" in n, ratios.keys())
    weightSources = {}
    for key in keys:
        src = key[key.find("SystVar") + 7:].replace("Plus",
                                                    "").replace("Minus", "")
        #        if src != "TopPtWeight":
        #            continue
        #        if src != "PUWeight":
        #            continue
        #        print src

        if not src in weightSources:
            weightSources[src] = [ratios[key][1]]
        else:
            weightSources[src].append(ratios[key][1])

    def comb(plus, x, p):
        nominal = fitLine.Eval(x[0])
        diff = 0

        # stat unc
        uncStat = 0.0
        for i, parErr in enumerate(parErrors):
            diffI = max(abs(evalPar(x, i, parErr) - nominal),
                        abs(evalPar(x, i, -parErr)) - nominal)
            uncStat += diffI**2
        diff += uncStat

        # Fit function
        diffFit = maxDiff(x, fits, nominal)
        diff += diffFit**2

        # Sample
        diffSample = maxDiff(x, samples, nominal)
        diff += diffSample**2

        # Weights
        for src, tf1s in weightSources.iteritems():
            diffWeight = maxDiff(x, tf1s, nominal)
            diff += diffWeight**2

        diff = math.sqrt(diff)
        if plus:
            ret = nominal + diff
        else:
            ret = nominal - diff

        if ret > 1:
            ret = 1.0
        if ret < 0:
            ret = 0.0


#        if ret > 0:
#            print x[0], (ret-nominal)/ret

        return ret

    p.appendPlotObject(
        ROOT.TF1("combPlus", lambda x, p: comb(True, x, p), fitLine.GetXmin(),
                 fitLine.GetXmax(), fitLine.GetNpar()))
    p.appendPlotObject(
        ROOT.TF1("combMinus", lambda x, p: comb(False, x, p),
                 fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar()))

    # Simple relative uncertainty
    def rel(x):
        return 0.012

    def relUnc(plus, x, p):
        nominal = fitLine.Eval(x[0])
        if plus:
            f = 1 + rel(x[0])
        else:
            f = 1 - rel(x[0])
        return nominal * f

    relPlus = ROOT.TF1("relPlus", lambda x, p: relUnc(True, x, p),
                       fitLine.GetXmin(), fitLine.GetXmax(), fitLine.GetNpar())
    relMinus = ROOT.TF1("relMinus", lambda x, p: relUnc(False, x, p),
                        fitLine.GetXmin(), fitLine.GetXmax(),
                        fitLine.GetNpar())
    relPlus.SetLineColor(ROOT.kGreen)
    relMinus.SetLineColor(ROOT.kGreen)
    p.appendPlotObject(relPlus)
    p.appendPlotObject(relMinus)

    def customize(plot):
        xmin = plot.frame.GetXaxis().GetXmin()
        xmax = plot.frame.GetXaxis().GetXmax()
        ymin = plot.frame.GetYaxis().GetXmin()
        ymax = plot.frame.GetYaxis().GetXmax()

        val = 1
        l = ROOT.TLine(xmin, val, xmax, val)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

        l = ROOT.TLine(41, ymin, 41, ymax)
        l.SetLineWidth(2)
        l.SetLineColor(ROOT.kRed)
        l.SetLineStyle(2)
        plot.prependPlotObject(l)

    plots.drawPlot(
        p,
        prefix + "WMuFractionUncertainty",
        "Muon p_{T} (GeV/c)",
        ylabel="W#rightarrow#mu fraction",
        opts={
            "ymin": 0.9,
            "ymax": 1.02
        },
        createLegend=None,
        #moveLegend={"dh": -0.15, "dx": -0.5},
        customizeBeforeDraw=customize)