Esempio n. 1
0
def plotgraph(histolist,lumi,j,name=""):

    name = os.path.basename(name)

    p = plots.DataMCPlot2(histolist)
    opts = {}
    if "opts" in j:
        opts = j["opts"]
    opts2 = {}
    if "opts2" in j:
        opts2 = j["opts2"]
    p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)
    if "xlabel" in j:
        p.getFrame().GetXaxis().SetTitle(j["xlabel"])
    if "ylabel" in j:
        p.getFrame().GetYaxis().SetTitle(j["ylabel"])
#    p.setDrawOptions("COLZ")
    if "drawStyle" in j:
        p.histoMgr.setHistoDrawStyleAll(j["drawStyle"])
    if "rebinx" in j:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"]))
    if "rebiny" in j:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"]))

    p.draw()

    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    print "Saved plot",os.path.join(plotDir, name)
Esempio n. 2
0
    def plot(self, plotDir):

        histolist = []
        #        self.h_data.SetMarkerStyle(21)
        #        self.h_data.SetMarkerSize(2)
        styles.dataStyle.apply(self.h_data)
        hhd = histograms.Histo(self.h_data,
                               "Data",
                               legendStyle="PL",
                               drawStyle="E1P")
        hhd.setIsDataMC(isData=True, isMC=False)
        histolist.append(hhd)
        for hname in self.histonames:
            hhp = histograms.Histo(self.histograms[hname],
                                   hname,
                                   legendStyle="F",
                                   drawStyle="HIST",
                                   legendLabel=self.labels[hname])
            hhp.setIsDataMC(isData=False, isMC=True)
            histolist.append(hhp)

        name = "postFitMt_" + self.name
        #        name = "preFitMt_"+self.name

        style = tdrstyle.TDRStyle()

        p = plots.DataMCPlot2(histolist)
        p.setDefaultStyles()
        p.stackMCHistograms()
        p.setLuminosity(lumi)

        p.addMCUncertainty(postfit=True)
        #        p.addText(0.7, 0.84, "2016", size=20) #FIXME
        p.setLegendHeader("2016")

        myParams = {}
        myParams["xlabel"] = "m_{T} (GeV)"
        myParams["ylabel"] = "< Events / bin >"
        myParams["ratio"] = True
        myParams["ratioYlabel"] = "Data/Bkg. "
        myParams["logx"] = True
        myParams["ratioType"] = "errorScale"
        myParams["ratioErrorOptions"] = {
            "numeratorStatSyst": False,
            "denominatorStatSyst": True
        }
        myParams["opts"] = self.opts
        myParams["optsLogx"] = self.optsLogx
        myParams["opts2"] = self.opts2
        myParams["errorBarsX"] = True
        myParams["xlabelsize"] = 25
        myParams["ylabelsize"] = 25
        myParams["addMCUncertainty"] = True
        myParams["addLuminosityText"] = True  #FIXME
        myParams["moveLegend"] = self.moveLegend
        plots.drawPlot(p, os.path.join(plotDir, name), **myParams)
        print "Saved plot", os.path.join(plotDir, name)
Esempio n. 3
0
 def makePlot(self, dirname, m, index, luminosity):
     if self._data == None:
         return
     myStackList = []
     # expected
     for i in range(0, len(self._expectedList)):
         myRHWU = RootHistoWithUncertainties(self._expectedList[i])
         myRHWU.addShapeUncertaintyRelative(
             "syst",
             th1Plus=self._expectedListSystUp[i],
             th1Minus=self._expectedListSystDown[i])
         myRHWU.makeFlowBinsVisible()
         if self._expectedLabelList[i] == "QCD":
             myHisto = histograms.Histo(myRHWU,
                                        self._expectedLabelList[i],
                                        legendLabel=_legendLabelQCD)
         elif self._expectedLabelList[i] == "Embedding":
             myHisto = histograms.Histo(myRHWU,
                                        self._expectedLabelList[i],
                                        legendLabel=_legendLabelEmbedding)
         elif self._expectedLabelList[i] == "EWKfakes":
             myHisto = histograms.Histo(myRHWU,
                                        self._expectedLabelList[i],
                                        legendLabel=_legendLabelEWKFakes)
         else:
             myHisto = histograms.Histo(myRHWU, self._expectedLabelList[i])
         myHisto.setIsDataMC(isData=False, isMC=True)
         myStackList.append(myHisto)
     # data
     myRHWU = RootHistoWithUncertainties(self._data)
     myRHWU.makeFlowBinsVisible()
     myHisto = histograms.Histo(myRHWU, "Data")
     myHisto.setIsDataMC(isData=True, isMC=False)
     myStackList.insert(0, myHisto)
     # Make plot
     myStackPlot = plots.DataMCPlot2(myStackList)
     myStackPlot.setLuminosity(luminosity)
     myStackPlot.setEnergy("%d" % self._config.OptionSqrtS)
     myStackPlot.setDefaultStyles()
     myParams = {}
     myParams["ylabel"] = "Events"
     myParams["log"] = True
     myParams["cmsTextPosition"] = "right"
     myParams["opts"] = {"ymin": 0.9}
     myParams["opts2"] = {"ymin": 0.3, "ymax": 1.7}
     #myParams["moveLegend"] = {"dx": -0.08, "dy": -0.12, "dh": 0.1} # for MC EWK+tt
     #myParams["moveLegend"] = {"dx": -0.15, "dy": -0.12, "dh":0.05} # for data-driven
     myParams["moveLegend"] = {
         "dx": -0.53,
         "dy": -0.52,
         "dh": 0.05
     }  # for data-driven
     myParams["ratioMoveLegend"] = {"dx": -0.51, "dy": 0.03}
     drawPlot(
         myStackPlot, "%s/DataDrivenCtrlPlot_M%d_%02d_SelectionFlow" %
         (dirname, m, index), **myParams)
def plotgraph(histolist, lumi, j, name=""):

    name = os.path.basename(name)

    p = plots.DataMCPlot2(histolist)
    opts = {}
    if "opts" in j:
        opts = j["opts"]
    opts2 = {}
    if "opts2" in j:
        opts2 = j["opts2"]
    opts = str2bool(opts)
    opts2 = str2bool(opts2)

    p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)
    if "xlabel" in j:
        p.getFrame().GetXaxis().SetTitle(j["xlabel"])
    if "ylabel" in j:
        p.getFrame().GetYaxis().SetTitle(j["ylabel"])
    if "drawStyle" in j:
        p.histoMgr.setHistoDrawStyleAll(j["drawStyle"])
    if "rebinx" in j:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(j["rebinx"]))
    if "rebiny" in j:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(j["rebiny"]))
    if "markerStyle" in j:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetMarkerStyle(j["markerStyle"]))
    if "markerColor" in j:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetMarkerColor(j["markerColor"]))
    if "markerSize" in j:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetMarkerSize(j["markerSize"]))

    if "useBeachPalette" in j and j["useBeachPalette"]:
        ROOT.gStyle.SetPalette(69)
        ROOT.TColor.InvertPalette()  # invert color palette if asked

    p.draw()

    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    print "Saved plot", os.path.join(plotDir, name)

    if "useBeachPalette" in j and j["useBeachPalette"]:
        ROOT.TColor.InvertPalette(
        )  # re-invert back to nominal, because the above line will invert for the next histogram again
Esempio n. 5
0
def printSummaryInfo(columnNames, myNuisanceInfo, cachedHistos, hObs, m,
                     luminosity, opts):

    config = aux.load_module(opts.settings)

    def addOrReplace(dictionary, key, newItem):
        if not key in dictionary.keys():
            dictionary[key] = newItem.Clone()
        else:
            dictionary[key].Add(newItem)

    def getHisto(cachedHistos, name):
        for h in cachedHistos:
            if h.GetName() == name:
                return h
        raise Exception("Cannot find histogram '%s'!" % name)

    # Create for each column a root histo with uncertainties
    myDict = OrderedDict()
    myTotal = None

    # Loop over columns (datasets)
    for c in columnNames:

        # Bugfix to prevent crashing with blacklisted datasets
        if c in config.Blacklist:
            continue

        hRate = aux.Clone(getHisto(cachedHistos, c))
        myRHWU = RootHistoWithUncertainties(hRate)
        for n in myNuisanceInfo:
            # Add shape uncertainties
            if n["name"] != "observation" and n[
                    "distribution"] == "shape" and n[
                        c] == "1" and not "statBin" in n["name"]:
                hUp = aux.Clone(
                    getHisto(cachedHistos, "%s_%sUp" % (c, n["name"])))
                hDown = aux.Clone(
                    getHisto(cachedHistos, "%s_%sDown" % (c, n["name"])))
                myRHWU.addShapeUncertaintyFromVariation(n["name"], hUp, hDown)
            # Add constant uncertainties
            elif n["name"] != "observation" and n["name"] != "rate" and n[
                    "name"] != "process" and n[c] != "-" and n[
                        c] != "1" and not "statBin" in n[
                            "name"] and not "BinByBin" in n["name"]:
                diffUp = 0.0
                diffDown = 0.0
                if "/" in n[c]:
                    mySplit = n[c].split("/")
                    diffDown = float(mySplit[0]) - 1.0
                    diffUp = float(mySplit[1]) - 1.0
                else:
                    diffDown = float(n[c]) - 1.0
                    diffUp = float(n[c]) - 1.0
                myRHWU.addNormalizationUncertaintyRelative(
                    n["name"], diffUp, diffDown)
        # Store column info
        _myBr = 0.01
        myAddToTotalStatus = False
        if c.startswith("HH") or c.startswith("CMS_Hptntj_HH"):
            myRHWU.Scale(_myBr**2)
            addOrReplace(myDict, "Hp", myRHWU)
        elif c.startswith("HW") or c.startswith("CMS_Hptntj_HW"):
            myRHWU.Scale(2.0 * _myBr * (1.0 - _myBr))
            addOrReplace(myDict, "Hp", myRHWU)
        elif c.startswith("Hp") or c.startswith("CMS_Hptntj_Hp"):
            addOrReplace(myDict, "Hp", myRHWU)
        elif c == "EWK_Tau" or c.startswith("CMS_Hptntj_EWK_Tau"):
            addOrReplace(myDict, "EWKtau", myRHWU)
            myAddToTotalStatus = True
        elif c.endswith("genuinetau"):
            addOrReplace(myDict, c.replace("CMS_Hptntj_", ""), myRHWU)
            myAddToTotalStatus = True
        elif c.endswith("faketau"):
            addOrReplace(myDict, "EWKfakes", myRHWU)
            myAddToTotalStatus = True
        elif c.startswith("QCD") or c.startswith("CMS_Hptntj_QCD"):
            addOrReplace(myDict, "QCD", myRHWU)
            myAddToTotalStatus = True
        else:
            myDict[c] = myRHWU
            myAddToTotalStatus = True
        if myAddToTotalStatus:
            if myTotal == None:
                myTotal = myRHWU.Clone()
            else:
                myTotal.Add(myRHWU.Clone())

    myDict["Totalbkg"] = myTotal
    # Make table
    print "\nEvent yields:"
    myTotal = None
    for item in myDict.keys():
        if myDict[item] != None:
            myDict[item].makeFlowBinsVisible()
            rate = myDict[item].getRate()
            stat = myDict[item].getRateStatUncertainty()
            (systUp, systDown) = myDict[item].getRateSystUncertainty()
            #myDict[item].Debug()
            print "%11s: %.1f +- %.1f (stat.) + %.1f - %.1f (syst.)" % (
                item, rate, stat, systUp, systDown)
    print "Observation: %d\n\n" % hObs.Integral(0, hObs.GetNbinsX() + 2)

    def setTailFitUncToStat(rhwu):
        tailfitNames = filter(lambda n: "_TailFit_" in n,
                              rhwu.getShapeUncertaintyNames())
        rhwu.setShapeUncertaintiesAsStatistical(tailfitNames)
        #rhwu.printUncertainties()
        #print rhwu.getShapeUncertaintiesAsStatistical()
        return rhwu

    myLogList = [False, True]
    for l in myLogList:

        # Create post fit shape
        myStackList = []
        if "QCD" in myDict.keys():
            myHisto = histograms.Histo(
                setTailFitUncToStat(myDict["QCD"].Clone()),
                "QCD",
                legendLabel=ControlPlotMaker._legendLabelQCD)
            myHisto.setIsDataMC(isData=False, isMC=True)
            myStackList.append(myHisto)
        if "EWKtau" in myDict.keys():
            myHisto = histograms.Histo(
                setTailFitUncToStat(myDict["EWKtau"].Clone()),
                "Embedding",
                legendLabel=ControlPlotMaker._legendLabelEmbedding)
            myHisto.setIsDataMC(isData=False, isMC=True)
            myStackList.append(myHisto)
        for c in myDict.keys():
            if c.endswith("genuinetau"):
                histoID = c.replace("CMS_Hptntj_",
                                    "").replace("_genuinetau", "")
                lookupTable = {  # Map column name to style in plots.py
                    "tt": "TT",
                    "W": "WJets",
                    "t": "SingleTop",
                    "DY": "DYJetsToLL",
                    "VV": "Diboson",
                    "tt_and_singleTop": "TTandSingleTop",
                    "EWK": "EWK"
                }
                histoString = lookupTable[histoID]
                myHisto = histograms.Histo(
                    setTailFitUncToStat(myDict[c].Clone()),
                    histoString,
                    legendLabel=c.replace("CMS_Hptntj_", ""))
                myHisto.setIsDataMC(isData=False, isMC=True)
                myStackList.append(myHisto)
        if "EWKfakes" in myDict.keys() and myDict["EWKfakes"] != None:
            myHisto = histograms.Histo(
                myDict["EWKfakes"].Clone(),
                "EWKfakes",
                legendLabel=ControlPlotMaker._legendLabelEWKFakes)
            myHisto.setIsDataMC(isData=False, isMC=True)
            myStackList.append(myHisto)
        myBlindedStatus = not opts.unblinded
        myBlindingString = None
        hObsLocal = aux.Clone(hObs)
        if myBlindedStatus:
            myBlindingString = "%d-%d GeV" % (hObs.GetXaxis().GetBinLowEdge(1),
                                              hObs.GetXaxis().GetBinUpEdge(
                                                  hObs.GetNbinsX()))
            for i in range(0, hObs.GetNbinsX()):
                hObsLocal.SetBinContent(i, -1.0)
                hObsLocal.SetBinError(i, 0.0)
        # Add data
        myDataHisto = histograms.Histo(hObsLocal, "Data")
        myDataHisto.setIsDataMC(isData=True, isMC=False)
        myStackList.insert(0, myDataHisto)
        # Add signal
        mySignalLabel = "TTToHplus_M%d" % float(m)
        if float(m) > 179:
            mySignalLabel = "HplusTB_M%d" % float(m)
        myHisto = histograms.Histo(myDict["Hp"].Clone(), mySignalLabel)
        myHisto.setIsDataMC(isData=False, isMC=True)
        myStackList.insert(1, myHisto)

        # Make plot
        myStackPlot = plots.DataMCPlot2(myStackList)
        myStackPlot.setLuminosity(luminosity)
        #myStackPlot.setEnergy("%d"%self._config.OptionSqrtS)
        myStackPlot.setDefaultStyles()
        myParams = {}
        if myBlindedStatus:
            myParams["blindingRangeString"] = myBlindingString
        myParams["cmsTextPosition"] = "right"
        myParams["ratio"] = True
        myParams["ratioType"] = "errorScale"
        myParams["ratioYlabel"] = "Data/Bkg. "
        myParams["stackMCHistograms"] = True
        myParams["addMCUncertainty"] = True
        myParams["addLuminosityText"] = True
        myParams["moveLegend"] = {"dx": -0.14, "dy": -0.10}
        myParams["ratioErrorOptions"] = {"numeratorStatSyst": False}
        myParams["ratioCreateLegend"] = True
        #myParams["ratioMoveLegend"] = {"dx": -0.51, "dy": 0.03}
        myParams["ratioMoveLegend"] = {"dx": -0.06, "dy": -0.1}
        myParams["opts2"] = {"ymin": 0.0, "ymax": 2.5}
        myParams["xlabel"] = "m_{T} (GeV)"
        #if l:
        #    myParams["ylabel"] = "< Events / bin >"
        #else:
        myParams["ylabel"] = "Events / 20 GeV"
        a = hObsLocal.GetXaxis().GetBinWidth(1)
        b = hObsLocal.GetXaxis().GetBinWidth(hObsLocal.GetNbinsX())
        #if abs(a-b) < 0.0001:
        #myParams["ylabel"]  += "%d GeV"%a
        #else:
        #myParams["ylabel"]  += "%d-%d GeV"%(a,b)
        #myParams["divideByBinWidth"] = l
        myParams["log"] = l
        myPlotName = "PostTailFitShape_M%d" % float(m)
        if l:
            # scale ymin by 20 in order to compare the rebinned mT with same y-scale
            # ymax(factor) takes care of max automatically
            myParams["opts"] = {"ymin": 20 * 1e-5}
        else:
            myParams["opts"] = {"ymin": 0.0}
            myPlotName += "_Linear"
        plots.drawPlot(myStackPlot, myPlotName, **myParams)
Esempio n. 6
0
def PlotHistogram(dsetMgr, histoName, opts):

    # Get kistogram argumetns
    kwargs   = GetHistoKwargs(histoName, opts)
    saveName = histoName.replace(opts.folder + "/", "")

    # Create the plotting object (Data, "FakeB")
    p1 = plots.DataMCPlot(dsetMgr, histoName, saveFormats=[])

    # Copy dataset manager before changing datasets. Keep only EWK (GenuineB) datasets
    datasetMgr = dsetMgr.deepCopy()
    datasetMgr.selectAndReorder(aux.GetListOfEwkDatasets())
        
    # Create the MCPlot for the EWKGenuineB histograms
    if opts.useMC:
        p2 = plots.MCPlot(datasetMgr, histoName, normalizeToLumi=opts.intLumi, saveFormats=[])
    else:
        histoNameGenuineB = histoName.replace(opts.folder, opts.folder + "EWKGenuineB")
        p2 = plots.MCPlot(datasetMgr, histoNameGenuineB, normalizeToLumi=opts.intLumi, saveFormats=[])

    # Add the datasets to be included in the plot
    myStackList = []

    # Data-driven FakeB background
    if not opts.useMC:
        hFakeB  = p1.histoMgr.getHisto("FakeB").getRootHisto()
        hhFakeB = histograms.Histo(hFakeB, "FakeB", legendLabel="Fake-b")
        hhFakeB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhFakeB)
    else:
        hQCD  = p1.histoMgr.getHisto("QCD").getRootHisto()
        hhQCD = histograms.Histo(hQCD, "QCD", legendLabel="QCD")
        hhQCD.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhQCD)

    # EWK GenuineB background (Replace all EWK histos with GenuineB histos)
    ewkHistoList = []
    # For-loop: All EWK datasets 
    for dataset in aux.GetListOfEwkDatasets():
        h = p2.histoMgr.getHisto(dataset).getRootHisto()
        hh = histograms.Histo(h, dataset,  plots._legendLabels[dataset])
        hh.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hh)

    # Collision data
    hData  = p1.histoMgr.getHisto("Data").getRootHisto()
    hhData = histograms.Histo(hData, "Data")
    hhData.setIsDataMC(isData=True, isMC=False)
    myStackList.insert(0, hhData)

    # Signal
    hSignal  = p1.histoMgr.getHisto(opts.signal).getRootHisto()
    hhSignal = histograms.Histo(hSignal, opts.signal, plots._legendLabels[opts.signal])
    hhSignal.setIsDataMC(isData=False, isMC=True)
    myStackList.insert(1, hhSignal)

    # Create the final plot by passing the histogram list
    p3 = plots.DataMCPlot2(myStackList, saveFormats=[])
    p3.setLuminosity(opts.intLumi)
    p3.setDefaultStyles()

    # Apply blinding of data in Signal Region (After creating the plot)
    if "blindingRangeString" in kwargs:
        startBlind = float(kwargs["blindingRangeString"].split("-")[1])
        endBlind   = float(kwargs["blindingRangeString"].split("-")[0])
        plots.partiallyBlind(p3, maxShownValue=startBlind, minShownValue=endBlind, invert=True, moveBlindedText=kwargs["moveBlindedText"])

    # Draw and save the plot
    plots.drawPlot(p3, saveName, **kwargs)
    SavePlot(p3, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"])
    return
Esempio n. 7
0
    def __init__(self, opts, config, dirname, luminosity, observation, datasetGroups):
        plots._legendLabels["MCStatError"] = "Bkg. stat."
        plots._legendLabels["MCStatSystError"] = "Bkg. stat.#oplussyst."
        plots._legendLabels["BackgroundStatError"] = "Bkg. stat. unc"
        plots._legendLabels["BackgroundStatSystError"] = "Bkg. stat.#oplussyst. unc."
        if config.ControlPlots == None:
            return
        myStyle = tdrstyle.TDRStyle()
        myStyle.setOptStat(False)

        self._opts = opts
        self._config = config
        if config.OptionSqrtS == None:
            raise Exception(ShellStyles.ErrorLabel()+"Please set the parameter OptionSqrtS = <integer_value_in_TeV> in the config file!"+ShellStyles.NormalStyle())
        self._dirname = dirname
        self._luminosity = luminosity
        self._observation = observation
        self._datasetGroups = datasetGroups

        #myEvaluator = SignalAreaEvaluator()

        # Make control plots
        print "\n"+ShellStyles.HighlightStyle()+"Generating control plots"+ShellStyles.NormalStyle()
        # Loop over mass points
        massPoints = []
        massPoints.extend(self._config.MassPoints)
        massPoints.append(-1) # for plotting with no signal
        for m in massPoints:
            print "... mass = %d GeV"%m
            # Initialize flow plot
            selectionFlow = SelectionFlowPlotMaker(self._opts, self._config, m)
            myBlindedStatus = False
            for i in range(0,len(self._config.ControlPlots)):
                if observation.getControlPlotByIndex(i) != None:
                    myCtrlPlot = self._config.ControlPlots[i]
                    print "......", myCtrlPlot.title
                    myMassSuffix = "_M%d"%m
                    # Initialize histograms
                    hSignal = None
                    hQCD = None
                    hQCDdata = None
                    hEmbedded = None
                    hEWKfake = None
                    hData = None
                    # Loop over dataset columns to find histograms
                    myStackList = []
                    for c in self._datasetGroups:
                        if (m < 0 or c.isActiveForMass(m,self._config)) and not c.typeIsEmptyColumn() and not c.getControlPlotByIndex(i) == None:
                            h = c.getControlPlotByIndex(i)["shape"].Clone()
                            if c.typeIsSignal():
                                #print "signal:",c.getLabel()
                                # Scale light H+ signal
                                if m < 179:
                                    if c.getLabel()[:2] == "HH":
                                        h.Scale(self._config.OptionBr**2)
                                    elif c.getLabel()[:2] == "HW":
                                        h.Scale(2.0*self._config.OptionBr*(1.0-self._config.OptionBr))
                                if hSignal == None:
                                    hSignal = h.Clone()
                                else:
                                    hSignal.Add(h)
                            elif c.typeIsQCDinverted():
				print "------------"
				print "ollaanko nyt vaarassa paikassa"
                                if hQCDdata == None:
                                    hQCDdata = h.Clone()
                                else:
                                    hQCDdata.Add(h)
                            elif c.typeIsQCD():
                                if hQCD == None:
				    print "hQCD add kai onnistuu"
                                    hQCD = h.Clone()
                                else:
				    print "hQCD add onnistuu"
                                    hQCD.Add(h)
                            elif c.typeIsEWK():
                                #print "EWK genuine:",c.getLabel(),h.getRootHisto().Integral(0,h.GetNbinsX()+2)
                                if not self._config.OptionGenuineTauBackgroundSource == "DataDriven":
                                    myHisto = histograms.Histo(h,c._datasetMgrColumn)
                                    myHisto.setIsDataMC(isData=False, isMC=True)
                                    myStackList.append(myHisto)
                                else:
                                    if hEmbedded == None:
                                        hEmbedded = h.Clone()
                                    else:
                                        hEmbedded.Add(h)
                            elif c.typeIsEWKfake():
                                #print "EWK fake:",c.getLabel(),h.getRootHisto().Integral(0,h.GetNbinsX()+2)
                                if hEWKfake == None:
                                    hEWKfake = h.Clone()
                                else:
                                    hEWKfake.Add(h)
                    if len(myStackList) > 0 or self._config.OptionGenuineTauBackgroundSource == "DataDriven":
                        if hQCDdata != None:
                            myHisto = histograms.Histo(hQCDdata,"QCDdata",legendLabel=_legendLabelQCDdata)
                            myHisto.setIsDataMC(isData=False, isMC=True)
                            myStackList.insert(0, myHisto)
                        elif hQCD != None:
                            myHisto = histograms.Histo(hQCD,"QCDdata",legendLabel=_legendLabelQCD)
                            myHisto.setIsDataMC(isData=False, isMC=True)
                            myStackList.insert(0, myHisto)
                        if hEmbedded != None:
                            myHisto = histograms.Histo(hEmbedded,"Embedding",legendLabel=_legendLabelEmbedding)
                            myHisto.setIsDataMC(isData=False, isMC=True)
                            myStackList.append(myHisto)
                        if hEWKfake != None:
                            myHisto = histograms.Histo(hEWKfake,"EWKfakes",legendLabel=_legendLabelEWKFakes)
                            myHisto.setIsDataMC(isData=False, isMC=True)
                            myStackList.append(myHisto)
                        hData = observation.getControlPlotByIndex(i)["shape"].Clone()
                        hDataUnblinded = hData.Clone()
                        # Apply blinding
                        myBlindingString = None
                        if self._config.BlindAnalysis:
                            if len(myCtrlPlot.blindedRange) > 0:
                                myBlindingString = self._applyBlinding(hData,myCtrlPlot.blindedRange)
                            if self._config.OptionBlindThreshold != None:
                                for k in xrange(1, hData.GetNbinsX()+1):
                                    myExpValue = 0.0
                                    for item in myStackList:
                                        myExpValue += item.getRootHisto().GetBinContent(k)
                                    if hSignal.getRootHisto().GetBinContent(k) >= myExpValue * self._config.OptionBlindThreshold:
                                        hData.getRootHisto().SetBinContent(k, -1.0)
                                        hData.getRootHisto().SetBinError(k, 0.0)
                        # Data
                        myDataHisto = histograms.Histo(hData,"Data")
                        myDataHisto.setIsDataMC(isData=True, isMC=False)
                        myStackList.insert(0, myDataHisto)
                        # Add signal
                        if m > 0:
                            mySignalLabel = "TTToHplus_M%d"%m
                            if m > 179:
                                mySignalLabel = "HplusTB_M%d"%m
                            myHisto = histograms.Histo(hSignal,mySignalLabel)
                            myHisto.setIsDataMC(isData=False, isMC=True)
                            myStackList.insert(1, myHisto)
                        # Add data to selection flow plot
                        #if myBlindedStatus:
                        #    selectionFlow.addColumn(myCtrlPlot.flowPlotCaption,None,myStackList[1:])
                        #else:
                        selectionFlow.addColumn(myCtrlPlot.flowPlotCaption,hDataUnblinded,myStackList[1:])
                        if len(myCtrlPlot.blindedRange) > 0:
                            myBlindedStatus = True
                        else:
                            myBlindedStatus = False
                        # Make plot
                        myStackPlot = None
                        myParams = myCtrlPlot.details.copy()
                        #if not isinstance(hData, ROOT.TH2):
                            #for j in range(1,myStackList[0].getRootHisto().GetNbinsY()+1):
                                #for i in range(1,myStackList[0].getRootHisto().GetNbinsX()+1):
                                    #mySum = 0.0
                                    #for h in range(2, len(myStackList)):
                                        #mySum += myStackList[h].getRootHisto().GetBinContent(i,j)
                                    #if mySum > 0.0:
                                        #myStackList[0].getRootHisto().SetBinContent(i,j,myStackList[0].getRootHisto().GetBinContent(i,j) / mySum)
                                    #else:
                                        #myStackList[0].getRootHisto().SetBinContent(i,j,-10.0)
                            #myStackList[0].getRootHisto().SetMinimum(-1.0)
                            #myStackList[0].getRootHisto().SetMaximum(1.0)
                            #myStackList = [myStackList[0]]
                            #myStackPlot = plots.PlotBase(myStackList)
                            #if "ylabelBinInfo" in myParams:
                                #del myParams["ylabelBinInfo"]
                            #del myParams["unit"]
                            #drawPlot2D(myStackPlot, "%s/DataDrivenCtrlPlot_M%d_%02d_%s"%(self._dirname,m,i,myCtrlPlot.title), **myParams)

                        myStackPlot = plots.DataMCPlot2(myStackList)
                        myStackPlot.setLuminosity(self._luminosity)
                        myStackPlot.setEnergy("%d"%self._config.OptionSqrtS)
                        myStackPlot.setDefaultStyles()

                        # Tweak paramaters
                        if not "unit" in myParams.keys():
                            myParams["unit"] = ""
                        if myParams["unit"] != "":
                            myParams["xlabel"] = "%s (%s)"%(myParams["xlabel"],myParams["unit"])

                        ylabelBinInfo = True
                        if "ylabelBinInfo" in myParams:
                            ylabelBinInfo = myParams["ylabelBinInfo"]
                            del myParams["ylabelBinInfo"]
                        if ylabelBinInfo:
                            myMinWidth = 10000.0
                            myMaxWidth = 0.0
                            for j in range(1,hData.getRootHisto().GetNbinsX()+1):
                                w = hData.getRootHisto().GetBinWidth(j)
                                if w < myMinWidth:
                                    myMinWidth = w
                                if w > myMaxWidth:
                                    myMaxWidth = w
                            myWidthSuffix = ""
                            myMinWidthString = "%d"%myMinWidth
                            myMaxWidthString = "%d"%myMaxWidth
                            if myMinWidth < 1.0:
                                myFormat = "%%.%df"%(abs(int(log10(myMinWidth)))+1)
                                myMinWidthString = myFormat%myMinWidth
                            if myMaxWidth < 1.0:
                                myFormat = "%%.%df"%(abs(int(log10(myMaxWidth)))+1)
                                myMaxWidthString = myFormat%myMaxWidth
                            myWidthSuffix = "%s-%s"%(myMinWidthString,myMaxWidthString)
                            if abs(myMinWidth-myMaxWidth) < 0.001:
                                myWidthSuffix = "%s"%(myMinWidthString)
                            if not (myParams["unit"] == "" and myWidthSuffix == "1"):
                                myParams["ylabel"] = "%s / %s %s"%(myParams["ylabel"],myWidthSuffix,myParams["unit"])
                        if myBlindingString != None:
                            if myParams["unit"] != "" and myParams["unit"][0] == "^":
                                myParams["blindingRangeString"] = "%s%s"%(myBlindingString, myParams["unit"])
                            else:
                                myParams["blindingRangeString"] = "%s %s"%(myBlindingString, myParams["unit"])
                        if "legendPosition" in myParams.keys():
                            if myParams["legendPosition"] == "NE":
                                myParams["moveLegend"] = {"dx": -0.10, "dy": -0.02}
                            elif myParams["legendPosition"] == "SE":
                                myParams["moveLegend"] = {"dx": -0.10, "dy": -0.56}
                            elif myParams["legendPosition"] == "SW":
                                myParams["moveLegend"] = {"dx": -0.53, "dy": -0.56}
                            elif myParams["legendPosition"] == "NW":
                                myParams["moveLegend"] = {"dx": -0.53, "dy": -0.02}
                            else:
                                raise Exception("Unknown value for option legendPosition: %s!", myParams["legendPosition"])
                            del myParams["legendPosition"]
                        elif not "moveLegend" in myParams:
                                myParams["moveLegend"] = {"dx": -0.10, "dy": -0.02} # default: NE
                        if "ratioLegendPosition" in myParams.keys():
                            if myParams["ratioLegendPosition"] == "left":
                                myParams["ratioMoveLegend"] = {"dx": -0.51, "dy": 0.03}
                            elif myParams["ratioLegendPosition"] == "right":
                                myParams["ratioMoveLegend"] = {"dx": -0.08, "dy": 0.03}
                            elif myParams["ratioLegendPosition"] == "SE":
                                myParams["ratioMoveLegend"] = {"dx": -0.08, "dy": -0.33}
                            else:
                                raise Exception("Unknown value for option ratioLegendPosition: %s!", myParams["ratioLegendPosition"])
                            del myParams["ratioLegendPosition"]
                        else:
                            if not "ratioMoveLegend" in myParams:
                                myParams["ratioMoveLegend"] = {"dx": -0.51, "dy": 0.03} # default: left
                        # Remove non-dientified keywords
                        del myParams["unit"]
                        # Ratio axis
                        if not "opts2" in myParams.keys():
                            myParams["opts2"] = {"ymin": 0.3, "ymax": 1.7}
                        # Do plotting
                        if m > 0:
                            drawPlot(myStackPlot, "%s/DataDrivenCtrlPlot_M%d_%02d_%s"%(self._dirname,m,i,myCtrlPlot.title), **myParams)
                        else:
                            drawPlot(myStackPlot, "%s/DataDrivenCtrlPlot_%02d_%s"%(self._dirname,i,myCtrlPlot.title), **myParams)

            # Do selection flow plot
            selectionFlow.makePlot(self._dirname,m,len(self._config.ControlPlots),self._luminosity)
        #myEvaluator.save(dirname)
        print "Control plots done"
    def __init__(self,
                 opts,
                 config,
                 dirname,
                 luminosity,
                 observation,
                 datasetGroups,
                 verbose=False):
        self._validateDatacard(config)
        self._config = config
        self._verbose = verbose
        self._opts = opts
        self._dirname = dirname
        self._luminosity = luminosity
        self._observation = observation
        self._datasetGroups = datasetGroups

        # Define label options
        myStyle = tdrstyle.TDRStyle()
        myStyle.setOptStat(False)
        plots._legendLabels["MCStatError"] = "Bkg. stat."
        plots._legendLabels["MCStatSystError"] = "Bkg. stat.#oplussyst."
        plots._legendLabels["BackgroundStatError"] = "Bkg. stat. unc"
        plots._legendLabels[
            "BackgroundStatSystError"] = "Bkg. stat.#oplussyst. unc."

        # Make control plots
        self.Verbose(
            ShellStyles.HighlightStyle() + "Generating control plots" +
            ShellStyles.NormalStyle(), True)

        # Definitions
        massPoints = []
        massPoints.extend(self._config.MassPoints)
        if self._config.OptionDoWithoutSignal:
            massPoints.append(-1)  # for plotting with no signal
        nMasses = len(massPoints)
        nPlots = len(self._config.ControlPlots)
        counter = 0

        # For-loop: All mass points
        for m in massPoints:

            # Initialize flow plot
            selectionFlow = SelectionFlowPlotMaker(self._opts, self._config, m)

            # For-loop: All control plots
            for i in range(0, nPlots):
                counter += 1

                # Skip if control plot does not exist
                if observation.getControlPlotByIndex(i) == None:
                    continue

                # Get the control plot
                myCtrlPlot = self._config.ControlPlots[i]

                # The case m < 0 is for plotting hitograms without any signal
                if m > 0:
                    # saveName = "%s/DataDrivenCtrlPlot_M%d_%02d_%s" % (self._dirname, m, i, myCtrlPlot.title)
                    saveName = "%s/DataDrivenCtrlPlot_M%d_%s" % (
                        self._dirname, m, myCtrlPlot.title)
                    msg = "Control Plot %d/%d (m=%s GeV)" % (counter, nMasses *
                                                             nPlots, str(m))
                else:
                    # saveName = "%s/DataDrivenCtrlPlot_%02d_%s" % (self._dirname, i, myCtrlPlot.title)
                    saveName = "%s/DataDrivenCtrlPlot_%s" % (self._dirname,
                                                             myCtrlPlot.title)
                    msg = "Control Plot %d/%d (no signal)" % (counter,
                                                              nMasses * nPlots)

                # Inform the user of progress
                self.PrintFlushed(
                    ShellStyles.AltStyle() + msg + ShellStyles.NormalStyle(),
                    counter == 1)
                if counter == len(massPoints) * nPlots:
                    print

                # Initialize histograms
                hData = None
                hSignal = None
                hFakeB = None
                hQCDMC = None
                myStackList = []

                # For-loop: All dataset columns (to find histograms)
                for c in self._datasetGroups:
                    self.Verbose(
                        "Dataset is %s for plot %s" %
                        (myCtrlPlot.title, c.getLabel()), False)

                    # Skip plot?
                    bDoPlot = (m < 0 or c.isActiveForMass(
                        m, self._config)) and not c.typeIsEmptyColumn(
                        ) and not c.getControlPlotByIndex(i) == None
                    if not bDoPlot:
                        continue

                    # Clone histo
                    h = c.getControlPlotByIndex(i)["shape"].Clone()

                    if c.typeIsSignal():
                        self.Verbose(
                            "Scaling histogram labelled \"%s\" with BR=%.2f" %
                            (c.getLabel(), self._config.OptionBr), False)
                        h.Scale(self._config.OptionBr)

                        if hSignal == None:
                            hSignal = h.Clone()
                        else:
                            hSignal.Add(h)
                    elif c.typeIsFakeB():
                        if hFakeB == None:
                            hFakeB = h.Clone()
                        else:
                            hFakeB.Add(h)
                    elif c.typeIsQCDMC():
                        if hQCD == None:
                            hQCDMC = h.Clone()
                        else:
                            hQCDMC.Add(h)
                    elif c.typeIsEWKMC() or c.typeIsGenuineB():
                        myHisto = histograms.Histo(h, c._datasetMgrColumn)
                        myHisto.setIsDataMC(isData=False, isMC=True)
                        myStackList.append(myHisto)

                # FIXME: what's this exactly?
                if len(
                        myStackList
                ) < 1 or self._config.OptionFakeBMeasurementSource != "DataDriven":
                    continue

                # Stack all the histograms
                if hFakeB != None:
                    myHisto = histograms.Histo(hFakeB,
                                               "FakeB",
                                               legendLabel=_legendLabelFakeB)
                    myHisto.setIsDataMC(isData=False, isMC=True)
                    myStackList.insert(0, myHisto)
                elif hQCDMC != None:
                    myHisto = histograms.Histo(hQCDMC,
                                               "QCDMC",
                                               legendLabel=_legendLabelQCDMC)
                    myHisto.setIsDataMC(isData=False, isMC=True)
                    myStackList.insert(0, myHisto)

                hData = observation.getControlPlotByIndex(i)["shape"].Clone()
                hDataUnblinded = hData.Clone()

                # Apply blinding & Get blinding string
                myBlindingString = self._applyBlinding(myCtrlPlot, myStackList,
                                                       hData, hSignal)

                # Data
                myDataHisto = histograms.Histo(hData, "Data")
                myDataHisto.setIsDataMC(isData=True, isMC=False)
                myStackList.insert(0, myDataHisto)

                # Add signal
                if m > 0:
                    #mySignalLabel = "HplusTB_M%d" % m
                    mySignalLabel = "ChargedHiggs_HplusTB_HplusToTB_M_%d" % (m)
                    myHisto = histograms.Histo(hSignal, mySignalLabel)
                    myHisto.setIsDataMC(isData=False, isMC=True)
                    myStackList.insert(1, myHisto)

                # Add data to selection flow plot
                selectionFlow.addColumn(myCtrlPlot.flowPlotCaption,
                                        hDataUnblinded, myStackList[1:])

                # Make plot
                myStackPlot = None
                myParams = myCtrlPlot.details.copy()
                myStackPlot = plots.DataMCPlot2(myStackList)
                myStackPlot.setLuminosity(self._luminosity)
                myStackPlot.setEnergy("%d" % self._config.OptionSqrtS)
                myStackPlot.setDefaultStyles()

                # Tweak paramaters
                if not "unit" in myParams.keys():
                    myParams["unit"] = ""

                if myParams["unit"] != "":
                    myParams["xlabel"] = "%s (%s)" % (myParams["xlabel"],
                                                      myParams["unit"])

                # Apply various settings to my parameters
                self._setBlingingString(myBlindingString, myParams)
                self._setYlabelWidthSuffix(hData, myParams)
                self._setLegendPosition(myParams)
                self._setRatioLegendPosition(myParams)

                # Remove non-dientified keywords
                del myParams["unit"]

                # Ratio axis
                if not "opts2" in myParams.keys():
                    myParams["opts2"] = {"ymin": 0.3, "ymax": 1.7}

                # Make sure BR is indicated if anyting else but BR=1.0
                if m > 0 and self._config.OptionBr != 1.0:
                    myStackPlot.histoMgr.setHistoLegendLabelMany({
                        #mySignalLabel: "H^{+} m_{H^{+}}=%d GeV (x %s)" % (m, self._config.OptionBr)
                        mySignalLabel:
                        "m_{H^{+}}=%d GeV (x %s)" % (m, self._config.OptionBr)
                    })

                # Do plotting
                drawPlot(myStackPlot, saveName, **myParams)

            # Do selection flow plot
            selectionFlow.makePlot(self._dirname, m,
                                   len(self._config.ControlPlots),
                                   self._luminosity)

        return
    def plot(self):
        style = tdrstyle.TDRStyle()
        ROOT.gStyle.SetErrorX(
            0.5
        )  #required for x-axis error bars! (must be called AFTER tdrstyle.TDRStyle())

        histolist = []
        #styles.dataStyle.apply(self.h_data)
        hhd = histograms.Histo(self.h_data,
                               "Data",
                               legendStyle="PL",
                               drawStyle="E1P")
        hhd.setIsDataMC(isData=True, isMC=False)
        histolist.append(hhd)
        if 0:
            aux.PrintTH1Info(hhd.getRootHisto())

        # For-loop: All signal histo
        for i, hsignal in enumerate(self.h_signal, 1):
            mass = hsignal.GetName().replace("Hp", "")
            Verbose("Customing signal histogram for Mass = \"%s\"" % (mass),
                    i == 1)
            hhs = histograms.Histo(hsignal,
                                   hsignal.GetTitle(),
                                   legendStyle="L",
                                   drawStyle="HIST")
            hhs.setIsDataMC(isData=False, isMC=True)
            signalStyle = styles.getSignalStyleHToTB_M(mass)
            signalStyle.apply(hhs.getRootHisto())
            histolist.append(hhs)

        # For-loop: All bkg histos
        for i, hname in enumerate(self.histonames, 1):
            # Safety net for empty histos
            if hname in opts.empty:
                msg = "Skipping %s. Not a histogram!" % (hname)
                Print(
                    ShellStyles.ErrorStyle() + msg + ShellStyles.NormalStyle(),
                    True)
                continue
            else:
                #print hname
                pass

            myLabel = self.labels[hname]
            myHisto = self.histograms[hname]
            Verbose(
                "Creating histogram \"%s\" from ROOT file \"%s\" (Integral = %.1f)"
                % (hname, myHisto.GetName(), myHisto.Integral()), i == 1)
            hhp = histograms.Histo(myHisto,
                                   hname,
                                   legendStyle="F",
                                   drawStyle="HIST",
                                   legendLabel=myLabel)
            hhp.setIsDataMC(isData=False, isMC=True)
            histolist.append(hhp)
            if 0:
                aux.PrintTH1Info(hhp.getRootHisto())

        # Sanity check
        for i, h in enumerate(histolist, 1):
            hName = h.getRootHisto().GetName()
            Verbose(hName, i == 1)

        # Do the plot
        p = plots.DataMCPlot2(histolist)
        p.setDefaultStyles()
        p.stackMCHistograms()
        p.setLuminosity(opts.lumi)

        if opts.fitUncert:
            p.addMCUncertainty(
                postfit=not opts.prefit)  # boolean changes only the legend

        if opts.prefit:
            p.setLegendHeader("Pre-Fit")
        else:
            p.setLegendHeader("Post-Fit")

        # Customise histogram
        units = "GeV"  #(GeV/c^{2})
        myParams = {}
        myParams["xlabel"] = "m_{jjbb} (%s)" % (units)
        myParams["ylabel"] = "< Events / " + units + " >"
        myParams["ratio"] = True
        myParams["ratioYlabel"] = "Data/Bkg. "
        myParams["logx"] = self.gOpts.logX
        myParams["log"] = self.gOpts.logY
        myParams["ratioType"] = "errorScale"
        myParams["ratioErrorOptions"] = {
            "numeratorStatSyst": False,
            "denominatorStatSyst": True
        }
        myParams["opts"] = self.opts
        myParams["optsLogx"] = self.optsLogx
        myParams["opts2"] = self.opts2
        myParams[
            "divideByBinWidth"] = True  #not opts.fitUncert # Error when used for "TGraphAsymmErrors" (uncert.)
        myParams["errorBarsX"] = True
        myParams["xlabelsize"] = 25
        myParams["ylabelsize"] = 25
        myParams["addMCUncertainty"] = True
        myParams["addLuminosityText"] = True
        myParams["moveLegend"] = self.moveLegend
        #myParams["saveFormats"]       = []

        # Draw the plot
        if not os.path.exists(opts.saveDir):
            os.makedirs(opts.saveDir)
        plots.drawPlot(p, os.path.join(opts.saveDir, self.gOpts.saveName),
                       **myParams)

        # Save the plot (not needed - drawPlot saves the canvas already)
        SavePlot(p,
                 self.gOpts.saveName,
                 opts.saveDir,
                 saveFormats=[".png", ".pdf", ".C"])

        return
Esempio n. 10
0
def main():

    if len(sys.argv) < 2 and not os.path.isdir(sys.argv[1]):
        usage()

    multicrabdir = sys.argv[1]

    signalAnalysisDir = ""
    QCDAnalysisDir    = os.path.join(multicrabdir,"pseudoMulticrab_QCDMeasurement")

    candDirs = execute("ls %s"%multicrabdir)
    for d in candDirs:
        if "SignalAnalysis_" in d:
            signalAnalysisDir = os.path.join(multicrabdir,d)

    print "Using",signalAnalysisDir
    print "     ",QCDAnalysisDir

    style    = tdrstyle.TDRStyle()
    ROOT.gROOT.SetBatch(True)
    datasets    = dataset.getDatasetsFromMulticrabDirs([signalAnalysisDir], analysisName=analysis)

    datasetsQCD = dataset.getDatasetsFromMulticrabDirs([QCDAnalysisDir], analysisName="signalAnalysis")
    datasets.extend(datasetsQCD)

    plots.mergeRenameReorderForDataMC(datasets)
    luminosity = datasets.getDataset("Data").getLuminosity()

    # Semi-ugly hack for approval homework, remember improve for the next round
    totalErrorFile = ROOT.TFile("outputLight.root")
    #totalErrorFile = ROOT.TFile("outputHeavy.root")
    ## Remove superfluous shape variation uncertainties                                                                  
    totalErrorHistoUp = totalErrorFile.Get("total_background")
    rebin = [0,20,40,60,80,100,120,140,160,180,200,220,240,260,280,300,320,340,360,380,400,420,440,460,480,500,600,700,800]
    import array
    #totalErrorHistoUp.Sumw2()
    totalErrorHistoUp = totalErrorHistoUp.Rebin(len(rebin)-1,"foo",array.array("d",rebin))
    totalErrorHistoDown = totalErrorHistoUp.Clone("foo2")
    for i in xrange(1, totalErrorHistoUp.GetNbinsX()+1):
        #print i, totalErrorHistoUp.GetBinContent(i), totalErrorHistoUp.GetBinError(i)
        totalErrorHistoUp.SetBinContent(i, totalErrorHistoUp.GetBinError(i))
        totalErrorHistoDown.SetBinContent(i, -totalErrorHistoDown.GetBinError(i))
        #print i, totalErrorHistoUp.GetBinContent(i), totalErrorHistoDown.GetBinContent(i)
    # semi-ugly hack continues below in QCD

    myStackList = []
    h_data = datasets.getDataset("Data").getDatasetRootHisto("ForDataDrivenCtrlPlots/shapeTransverseMass_POSTFIT").getHistogram()
    myRHWU = dataset.RootHistoWithUncertainties(h_data)
    myRHWU.makeFlowBinsVisible()
    myHisto = histograms.Histo(myRHWU, "Data")
    myHisto.setIsDataMC(isData=True, isMC=False)
    myStackList.insert(0, myHisto)

    h_FakeTau = datasets.getDataset("QCDMeasurementMT").getDatasetRootHisto("ForDataDrivenCtrlPlots/shapeTransverseMass_POSTFIT").getHistogram()
    myRHWU = dataset.RootHistoWithUncertainties(h_FakeTau)
    # semi-ugly hack continues
    htemp=myRHWU.getRootHisto()
    myRHWU.addAbsoluteShapeUncertainty("toterr", totalErrorHistoUp, totalErrorHistoDown)
    #myRHWU.addShapeUncertaintyFromVariation("toterr", totalErrorHistoUp, totalErrorHistoDown)
    # semi-ugly hack ends
    myRHWU.makeFlowBinsVisible()
    myHisto = histograms.Histo(myRHWU, "QCDdata")
    myHisto.setIsDataMC(isData=False, isMC=True)
    myStackList.insert(1, myHisto)

    expectedList = []
    expectedList.append("TT")
    expectedList.append("WJets")
    expectedList.append("SingleTop")
    expectedList.append("DYJetsToLL")
    expectedList.append("Diboson")

    for i in range(0,len(expectedList)):
        drh = datasets.getDataset(expectedList[i]).getDatasetRootHisto("ForDataDrivenCtrlPlots/shapeTransverseMass_POSTFIT")
        h_bgr = drh.getHistogram()
        myRHWU = dataset.RootHistoWithUncertainties(h_bgr)
#        myRHWU.addShapeUncertaintyRelative("syst", th1Plus=self._expectedListSystUp[i], th1Minus=self._expectedListSystDown[i])
        myRHWU.makeFlowBinsVisible()
        myHisto = histograms.Histo(myRHWU, expectedList[i])
        myHisto.setIsDataMC(isData=False, isMC=True)
        myStackList.append(myHisto)

    #myStackList = divideByBinWidth(myStackList)

    # no, ugly hack continues here
    histograms.uncertaintyMode.set(histograms.Uncertainty.SystOnly)
    plots._legendLabels["MCSystError"] = "Bkg. stat.#oplus syst. unc."
    plots._legendLabels["BackgroundSystError"] = "Bkg. stat.#oplus syst. unc."
    # and stops again here
    myStackPlot = plots.DataMCPlot2(myStackList)
    myStackPlot.setLuminosity(luminosity)
    myStackPlot.setDefaultStyles()
    myParams = {}   
    myParams["ylabel"] = "Events / bin"
    myParams["ratioYlabel"] = "Data/Bkg."
    myParams["xlabel"] = "m_{T} (GeV)" 

    myParams["log"] = True
    myParams["ratio"] = True
    myParams["cmsTextPosition"] = "outframe"
    myParams["opts"] = {"ymin": 0.0001, "ymax": 3000.0}
    myParams["opts2"] = {"ymin": 0., "ymax":1.99}
    myParams["moveLegend"] = {"dx": -0.15, "dy": 0., "dh":0.05} # for data-driven
    myParams["ratioMoveLegend"] = {"dx": -0.51, "dy": 0.03}
    myParams["stackMCHistograms"] = True
    myParams["divideByBinWidth"] = True
    myParams["addMCUncertainty"] = True
    myParams["ratioType"] = "errorScale"
    myParams["ratioCreateLegend"] = True
    myParams["ratioMoveLegend"] = dict(dy=-0.45, dh=-0.1, dx=-0.5)
    plots.drawPlot(myStackPlot, "TransVerseMassPOSTFIT", **myParams)
Esempio n. 11
0
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts):

    # Get the histogram customisations (keyword arguments)
    _kwargs = GetHistoKwargs(histoList[0])

    # Get the root histos for all datasets and Control Regions (CRs)
    regions = ["SR", "VR", "CRone", "CRtwo"]
    rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels)

    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    manager = FakeBNormalization.FakeBNormalizationManager(binLabels,
                                                           opts.mcrab,
                                                           opts.optMode,
                                                           verbose=False)
    if opts.inclusiveOnly:
        #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"])
        binLabel = "Inclusive"
        manager.CalculateTransferFactor("Inclusive",
                                        rhDict["FakeB-CRone-Inclusive"],
                                        rhDict["FakeB-CRtwo-Inclusive"])
    else:
        for bin in binLabels:
            manager.CalculateTransferFactor(bin,
                                            rhDict["FakeB-CRone-%s" % bin],
                                            rhDict["FakeB-CRtwo-%s" % bin])

    # Get unique a style for each region
    for k in rhDict:
        dataset = k.split("-")[0]
        region = k.split("-")[1]
        styles.getABCDStyle(region).apply(rhDict[k])
        if "FakeB" in k:
            styles.getFakeBStyle().apply(rhDict[k])
        # sr.apply(rhDict[k])

    # =========================================================================================
    # Create the final plot object
    # =========================================================================================
    rData_SR = rhDict["Data-SR-Inclusive"]
    rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"]
    rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive")
    rBkgSum_SR.Reset()

    if opts.inclusiveOnly:
        bin = "Inclusive"
        # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
        binHisto_VR = rhDict["FakeB-VR-%s" % (bin)]
        VRtoSR_TF = manager.GetTransferFactor(bin)
        Print(
            "Applying TF = %s%0.6f%s to VR shape" %
            (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()),
            True)
        binHisto_VR.Scale(VRtoSR_TF)
        # Add the normalised histogram to the final Inclusive SR (predicted) histo
        rBkgSum_SR.Add(binHisto_VR, +1)
    else:
        # For-loop: All bins
        for i, bin in enumerate(binLabels, 1):
            if bin == "Inclusive":
                continue
            # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
            binHisto_VR = rhDict["FakeB-VR-%s" % (bin)]
            VRtoSR_TF = manager.GetTransferFactor(bin)
            Print(
                "Applying TF = %s%0.6f%s to VR shape" %
                (ShellStyles.NoteStyle(), VRtoSR_TF,
                 ShellStyles.NormalStyle()), i == 1)
            binHisto_VR.Scale(VRtoSR_TF)
            # Add the normalised histogram to the final Inclusive SR (predicted) histo
            rBkgSum_SR.Add(binHisto_VR, +1)

    #Print("Got Verification Region (VR) shape %s%s%s" % (ShellStyles.NoteStyle(), rFakeB_VR.GetName(), ShellStyles.NormalStyle()), True)

    # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
    #VRtoSR_TF = manager.GetTransferFactor("Inclusive")
    #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True)
    #rBkgSum_SR.Scale(VRtoSR_TF)

    # Plot histograms
    if opts.altPlot:
        # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] )
        rBkgSum_SR.Add(rEWKGenuineB_SR, +1)

        # Change style
        styles.getGenuineBStyle().apply(rBkgSum_SR)

        # Remove unsupported settings of kwargs
        _kwargs["stackMCHistograms"] = False
        _kwargs["addLuminosityText"] = False

        # Create the plot
        p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[])

        # Set draw / legend style
        p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P")
        p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive", "LP")
        p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST")
        p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive", "F")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            "Data-SR": "Data",
            "BkgSum-SR": "Fake-b + Gen-b",
        })
    else:
        # Create empty histogram stack list
        myStackList = []

        # Signal
        p2 = plots.DataMCPlot(datasetsMgr,
                              "ForTestQGLR/QGLR_SR/QGLR_SRInclusive",
                              saveFormats=[])

        hSignal_800 = p2.histoMgr.getHisto(
            'ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto()
        hhSignal_800 = histograms.Histo(
            hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800',
            "H^{+} m_{H^+}=800 GeV")
        hhSignal_800.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhSignal_800)

        hSignal_250 = p2.histoMgr.getHisto(
            'ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto()
        hhSignal_250 = histograms.Histo(
            hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250',
            "H^{+} m_{H^+}=250 GeV"
        )  #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250'])
        hhSignal_250.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_250)

        hSignal_500 = p2.histoMgr.getHisto(
            'ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto()
        hhSignal_500 = histograms.Histo(
            hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500',
            "H^{+} m_{H^+}=500 GeV"
        )  #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500'])
        hhSignal_500.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_500)

        hSignal_1000 = p2.histoMgr.getHisto(
            'ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto()
        hhSignal_1000 = histograms.Histo(
            hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000',
            "H^{+} m_{H^+}=1000 GeV"
        )  #plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500'])
        hhSignal_1000.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_1000)

        # Add the FakeB data-driven background to the histogram list
        hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b")
        hFakeB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hFakeB)

        # Add the EWKGenuineB MC background to the histogram list
        hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB",
                                     "EWK Genuine-b")
        hGenuineB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hGenuineB)

        # Add the collision datato the histogram list
        hData = histograms.Histo(rData_SR, "Data", "Data")
        hData.setIsDataMC(isData=True, isMC=False)
        myStackList.insert(0, hData)

        p = plots.DataMCPlot2(myStackList, saveFormats=[])
        p.setLuminosity(opts.intLumi)
        p.setDefaultStyles()

    # Draw the plot and save it
    hName = "test"
    plots.drawPlot(p, hName, **_kwargs)
    SavePlot(p,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf"])

    #==========================================================================================
    # Calculate Cut-Flow Efficiency
    #==========================================================================================
    kwargs = {
        "rebinX": 1,
        "xlabel": "QGLR",
        "ylabel": "Significance / %.02f ",
        "opts": {
            "ymin": 0.0,
            "ymaxfactor": 1.3
        },
        "createLegend": {
            "x1": 0.55,
            "y1": 0.70,
            "x2": 0.92,
            "y2": 0.92
        },
        #            "cutBox"           : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True},
    }

    efficiencyList = []
    xValues = []

    yValues_250 = []
    yValues_500 = []
    yValues_800 = []
    yValues_1000 = []
    yValues_Bkg = []

    nBins = hSignal_250.GetNbinsX() + 1

    hBkg = p.histoMgr.getHisto(
        "ChargedHiggs_HplusTB_HplusToTB_M_800").getRootHisto().Clone("Bkg")
    hBkg.Reset()

    # Bkg: FakeB + Genuine B
    hBkg.Add(hFakeB.getRootHisto(), +1)
    hBkg.Add(hGenuineB.getRootHisto(), +1)

    for i in range(0, nBins):

        # Cut value
        cut = hSignal_250.GetBinCenter(i)

        passed_250 = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins())
        passed_500 = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins())
        passed_800 = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins())
        passed_1000 = hSignal_1000.Integral(i,
                                            hSignal_1000.GetXaxis().GetNbins())

        passed_Bkg = hBkg.Integral(i, hBkg.GetXaxis().GetNbins())

        total_250 = hSignal_250.Integral()
        total_500 = hSignal_500.Integral()
        total_800 = hSignal_800.Integral()
        total_1000 = hSignal_1000.Integral()
        total_Bkg = hBkg.Integral()

        eff_250 = float(passed_250) / total_250
        eff_500 = float(passed_500) / total_500
        eff_800 = float(passed_800) / total_800
        eff_1000 = float(passed_1000) / total_1000

        eff_Bkg = float(passed_Bkg) / total_Bkg

        xValues.append(cut)
        yValues_250.append(eff_250)
        yValues_500.append(eff_500)
        yValues_800.append(eff_800)
        yValues_1000.append(eff_1000)

        yValues_Bkg.append(eff_Bkg)

    # Create the Efficiency Plot
    tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues),
                             array.array("d", yValues_250))
    tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues),
                             array.array("d", yValues_500))
    tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues),
                             array.array("d", yValues_800))
    tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues),
                              array.array("d", yValues_1000))
    tGraph_Bkg = ROOT.TGraph(len(xValues), array.array("d", xValues),
                             array.array("d", yValues_Bkg))

    styles.getSignalStyleHToTB_M("200").apply(tGraph_250)
    styles.getSignalStyleHToTB_M("500").apply(tGraph_500)
    styles.getSignalStyleHToTB_M("800").apply(tGraph_800)
    styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000)
    styles.getQCDLineStyle().apply(tGraph_Bkg)

    drawStyle = "CPE"
    effGraph_250 = histograms.HistoGraph(tGraph_250,
                                         "H^{+} m_{H^{+}} = 250 GeV", "lp",
                                         drawStyle)
    effGraph_500 = histograms.HistoGraph(tGraph_500,
                                         "H^{+} m_{H^{+}} = 500 GeV", "lp",
                                         drawStyle)
    effGraph_800 = histograms.HistoGraph(tGraph_800,
                                         "H^{+} m_{H^{+}} = 800 GeV", "lp",
                                         drawStyle)
    effGraph_1000 = histograms.HistoGraph(tGraph_1000,
                                          "H^{+} m_{H^{+}} = 1000 GeV", "lp",
                                          drawStyle)
    effGraph_Bkg = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle)

    efficiencyList.append(effGraph_250)
    efficiencyList.append(effGraph_500)
    efficiencyList.append(effGraph_800)
    efficiencyList.append(effGraph_1000)
    efficiencyList.append(effGraph_Bkg)

    # Efficiency plot
    pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"])
    pE.createFrame("QGLR_Efficiency")
    pE.setEnergy("13")
    pE.getFrame().GetYaxis().SetLabelSize(18)
    pE.getFrame().GetXaxis().SetLabelSize(20)

    pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01")
    pE.getFrame().GetXaxis().SetTitle("QGLR Cut")

    # Add Standard Texts to plot
    histograms.addStandardTexts()

    # Customise Legend
    moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1}
    pE.setLegend(histograms.moveLegend(histograms.createLegend(),
                                       **moveLegend))

    pE.draw()
    #    plots.drawPlot(pE, "QGLR_Efficiency", **kwargs)
    SavePlot(pE,
             "QGLR_Efficiency",
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf"])

    #==========================================================================================
    # Calculate Significance
    #==========================================================================================

    SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800"

    hSignif_250 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(
        SignalName)
    hSignif_500 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(
        SignalName)
    hSignif_800 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(
        SignalName)
    hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(
        SignalName)

    hSignif_250.Reset()
    hSignif_500.Reset()
    hSignif_800.Reset()
    hSignif_1000.Reset()

    hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg")
    hBkg.Reset()

    # Bkg: FakeB + Genuine B
    hBkg.Add(hFakeB.getRootHisto(), +1)
    hBkg.Add(hGenuineB.getRootHisto(), +1)

    nBins = hSignif_250.GetNbinsX() + 1

    # For-loop: All histo bins
    for i in range(1, nBins + 1):

        sigmaB = ROOT.Double(0)

        b = hBkg.IntegralAndError(i, nBins, sigmaB)

        s_250 = hSignal_250.Integral(i, nBins)
        s_500 = hSignal_500.Integral(i, nBins)
        s_800 = hSignal_800.Integral(i, nBins)
        s_1000 = hSignal_1000.Integral(i, nBins)

        # Calculate significance
        signif_250 = stat.significance(s_250, b, sigmaB,
                                       option="Simple")  #Asimov")
        signif_500 = stat.significance(s_500, b, sigmaB,
                                       option="Simple")  #Asimov")
        signif_800 = stat.significance(s_800, b, sigmaB,
                                       option="Simple")  #Asimov")
        signif_1000 = stat.significance(s_1000, b, sigmaB,
                                        option="Simple")  #"Asimov")

        # Set signif for this bin
        hSignif_250.SetBinContent(i, signif_250)
        hSignif_500.SetBinContent(i, signif_500)
        hSignif_800.SetBinContent(i, signif_800)
        hSignif_1000.SetBinContent(i, signif_1000)

        # Apply style
        s_250 = styles.getSignalStyleHToTB_M("200")
        s_250.apply(hSignif_250)

        s_500 = styles.getSignalStyleHToTB_M("500")
        s_500.apply(hSignif_500)

        s_800 = styles.getSignalStyleHToTB_M("800")
        s_800.apply(hSignif_800)

        s_1000 = styles.getSignalStyleHToTB_M("1000")
        s_1000.apply(hSignif_1000)

        hList = []
        hList.append(hSignif_250)
        hList.append(hSignif_500)
        hList.append(hSignif_800)
        hList.append(hSignif_1000)

        hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV")
        hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV")
        hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV")
        hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV")

    pS = plots.PlotBase(hList, saveFormats=["png", "pdf"])
    pS.setLuminosity(opts.intLumi)

    # Drawing style
    pS.histoMgr.setHistoDrawStyleAll("HIST")
    pS.histoMgr.setHistoLegendStyleAll("L")
    pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0))
    pS.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pS.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle))

    # Draw the plot
    name = "QGLR_Signif" + "GE"

    plots.drawPlot(pS, name, **kwargs)
    SavePlot(pS,
             name,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf"])

    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    Verbose("Write the normalisation factors to a python file", True)
    fileName = os.path.join(
        opts.mcrab, "FakeBTransferFactors%s.py" % (getModuleInfoString(opts)))
    manager.writeNormFactorFile(fileName, opts)
    return
Esempio n. 12
0
def PlotHistosAndCalculateTF(runRange, datasetsMgr, histoList, binLabels,
                             opts):

    # Get the histogram customisations (keyword arguments)
    _kwargs = GetHistoKwargs(histoList[0])

    # Get the root histos for all datasets and Control Regions (CRs)
    regions = ["SR", "VR", "CRone", "CRtwo", "CRthree", "CRfour"]
    rhDict = GetRootHistos(datasetsMgr, histoList, regions, binLabels)

    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    manager = FakeBNormalization.FakeBNormalizationManager(binLabels,
                                                           opts.mcrab,
                                                           opts.optMode,
                                                           verbose=False)
    if opts.inclusiveOnly:
        binLabel = "Inclusive"
        manager.CalculateTransferFactor("Inclusive",
                                        rhDict["FakeB-CRone-Inclusive"],
                                        rhDict["FakeB-CRtwo-Inclusive"],
                                        rhDict["FakeB-CRthree-Inclusive"],
                                        rhDict["FakeB-CRfour-Inclusive"])
    else:
        for bin in binLabels:
            manager.CalculateTransferFactor(bin,
                                            rhDict["FakeB-CRone-%s" % bin],
                                            rhDict["FakeB-CRtwo-%s" % bin],
                                            rhDict["FakeB-CRthree-%s" % bin],
                                            rhDict["FakeB-CRfour-%s" % bin])

    # Get unique a style for each region
    for k in rhDict:
        dataset = k.split("-")[0]
        region = k.split("-")[1]
        styles.getABCDStyle(region).apply(rhDict[k])
        if "FakeB" in k:
            styles.getFakeBStyle().apply(rhDict[k])
        # sr.apply(rhDict[k])

    # =========================================================================================
    # Create the final plot object
    # =========================================================================================
    rData_SR = rhDict["Data-SR-Inclusive"]
    rEWKGenuineB_SR = rhDict["EWK-SR-Inclusive-EWKGenuineB"]
    rBkgSum_SR = rhDict["FakeB-VR-Inclusive"].Clone("BkgSum-SR-Inclusive")
    rBkgSum_SR.Reset()

    if opts.inclusiveOnly:
        bin = "Inclusive"
        # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
        binHisto_VR = rhDict["FakeB-VR-%s" % (bin)]
        VRtoSR_TF = manager.GetTransferFactor(bin)
        Verbose(
            "Applying TF = %s%0.6f%s to VR shape" %
            (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()),
            True)
        binHisto_VR.Scale(VRtoSR_TF)
        # Add the normalised histogram to the final Inclusive SR (predicted) histo
        rBkgSum_SR.Add(binHisto_VR, +1)
    else:
        # For-loop: All bins
        for i, bin in enumerate(binLabels, 1):
            if bin == "Inclusive":
                continue
            # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
            binHisto_VR = rhDict["FakeB-VR-%s" % (bin)]
            VRtoSR_TF = manager.GetTransferFactor(bin)
            Verbose(
                "Applying TF = %s%0.6f%s to VR shape" %
                (ShellStyles.NoteStyle(), VRtoSR_TF,
                 ShellStyles.NormalStyle()), i == 1)
            binHisto_VR.Scale(VRtoSR_TF)
            # Add the normalised histogram to the final Inclusive SR (predicted) histo
            rBkgSum_SR.Add(binHisto_VR, +1)

    # Plot histograms
    if opts.altPlot:
        # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] )
        rBkgSum_SR.Add(rEWKGenuineB_SR, +1)

        # Change style
        styles.getGenuineBStyle().apply(rBkgSum_SR)

        # Remove unsupported settings of kwargs
        _kwargs["stackMCHistograms"] = False
        _kwargs["addLuminosityText"] = False

        # Create the plot
        p = plots.ComparisonManyPlot(rData_SR, [rBkgSum_SR], saveFormats=[])

        # Set draw / legend style
        p.histoMgr.setHistoDrawStyle("Data-SR-Inclusive", "P")
        p.histoMgr.setHistoLegendStyle("Data-SR-Inclusive", "LP")
        p.histoMgr.setHistoDrawStyle("BkgSum-SR-Inclusive", "HIST")
        p.histoMgr.setHistoLegendStyle("BkgSum-SR-Inclusive", "F")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            "Data-SR": "Data",
            "BkgSum-SR": "Fake-b + Gen-b",
        })
    else:
        # Create empty histogram stack list
        myStackList = []

        # Add the FakeB data-driven background to the histogram list
        hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b")
        hFakeB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hFakeB)

        # Add the EWKGenuineB MC background to the histogram list
        hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB",
                                     "EWK Genuine-b")
        hGenuineB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hGenuineB)

        # Add the collision datato the histogram list
        hData = histograms.Histo(rData_SR, "Data", "Data")
        hData.setIsDataMC(isData=True, isMC=False)
        myStackList.insert(0, hData)

        p = plots.DataMCPlot2(myStackList, saveFormats=[])
        p.setLuminosity(opts.intLumi)
        p.setDefaultStyles()

    # Draw the plot and save it
    hName = opts.histoKey
    plots.drawPlot(p, hName, **_kwargs)
    SavePlot(p,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png"])

    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    Verbose("Write the normalisation factors to a python file", True)
    fileName = os.path.join(opts.mcrab,
                            "FakeBTransferFactors_%s.py" % (runRange))
    manager.writeTransferFactorsToFile(fileName, opts)
    return
Esempio n. 13
0
def PlotHistos(noSF_datasetsMgr, withCR2SF_datasetsMgr, num_histoList, den_histoList,  opts):    
    
    # Get the histogram customisations (keyword arguments)
    _kwargs = GetHistoKwargs(num_histoList[0])
    
    # Get the root histos for all datasets and Control Regions (CRs)
    regions = ["SR", "VR", "CR1", "CR2"]
    labels  = ["Genuine", "Fake", "Inclusive"]
    
    #==========================================================================================
    # Get Dictionaries
    #==========================================================================================
    rhDict_den_noSF      = GetRootHistos(noSF_datasetsMgr,      den_histoList, regions)
    rhDict_num_noSF      = GetRootHistos(noSF_datasetsMgr,      num_histoList, regions)
    rhDict_num_withCR2SF = GetRootHistos(withCR2SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR2 are only applied in the Numerator on EWK+QCD+ST
    
    #=========================================================================================
    # Normalization Factors (see: getNormalization.py)
    #=========================================================================================
    # Marina
    #f1=0.610901; f2=0.889906; # (1)
    #f1=0.610901; f2=0.906343; # (2)
    #f1=0.610963; f2=0.903020; # (3)
    #f1=0.610901; f2=0.901711; # (4)
    #f1=0.603648; f2=0.907290; # (5)
    #f1=0.611682; f2=0.889619; # (6)
    #f1=0.613102; f2=0.902808; # (7)
    #f1=0.609202; f2=0.906565; # (8)
    #f1=0.613102; f2=0.906056; # (9)
    #f1=0.608068; f2=0.906713; # (10)
    #f1=0.610901; f2=0.889106; # (11)
    f1=0.616422; f2=0.905622; # (12)
    
    # =========================================================================================
    # (A) Apply Normalization Factors (see: getNormalizations.py)
    # =========================================================================================

    # Normalize all histograms (QCD and TT) to normalization factors
    for re in regions:
        
        rhDict_den_noSF["NormQCD-"+re+"-Inclusive"] = rhDict_den_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1)

        rhDict_num_noSF["NormQCD-"+re+"-Inclusive"] =rhDict_num_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1)

        rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"] = rhDict_num_withCR2SF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Scale(f1)
        
        for la in labels:
            
            rhDict_den_noSF["NormTT-"+re+"-"+la] = rhDict_den_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_den_noSF["NormTT-"+re+"-"+la].Scale(f2)
            
            rhDict_num_noSF["NormTT-"+re+"-"+la] = rhDict_num_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_num_noSF["NormTT-"+re+"-"+la].Scale(f2)
            
    # ==========================================================================================
    # (B) Make control plots with & without any SF applied in all regions
    # ==========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = True
    _kwargs["createLegend"]      = {"x1": 0.80, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    
    print "Denominator:"


    # (B1) Denominator
    for re in regions:

        hName = "Denominator_"+re+"_StackedMC"

        h0_Data      = rhDict_den_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h0_QCD       = rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h0_TT        = rhDict_den_noSF["NormTT-"+re+"-Inclusive"].Clone("t#bar{t}")
        h0_EWK       = rhDict_den_noSF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h0_ST        = rhDict_den_noSF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        
        styles.FakeBStyle6.apply(h0_TT)
        #styles.getFakeBStyle().apply(h0_TT)
        styles.ewkStyle.apply(h0_EWK)
        styles.genuineBAltStyle.apply(h0_ST)
        
        h0 = histograms.Histo(h0_Data, "Data", "Data")
        h1 = histograms.Histo(h0_TT, "t#bar{t}", "TT")
        h3 = histograms.Histo(h0_EWK, "EWK", "EWK")
        h4 = histograms.Histo(h0_QCD, "QCD", "QCD")
        h5 = histograms.Histo(h0_ST, "ST", "ST")
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)
        
        myStackList = []
        if re == "CR1" or re == "SR":
            myStackList.insert(0, h0)
            myStackList.append(h1)
            myStackList.append(h4)
            myStackList.append(h5)
            myStackList.append(h3)
        else:
            myStackList.insert(0, h0)
            myStackList.append(h4)
            myStackList.append(h1)
            myStackList.append(h5)
            myStackList.append(h3)
            
        pDen = plots.DataMCPlot2(myStackList, saveFormats=[])
        pDen.setLuminosity(opts.intLumi)
        pDen.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(pDen, hName, **_kwargs)
        SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])


    # (B2) Numerator
    for re in regions:
        
        hName = "Numerator_"+re+"_StackedMC_noSF"
        
        h1_Data      = rhDict_num_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h1_QCD       = rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h1_TT        = rhDict_num_noSF["NormTT-"+re+"-Inclusive"].Clone("t#bar{t}")
        h1_EWK       = rhDict_num_noSF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h1_ST        = rhDict_num_noSF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        
        styles.FakeBStyle6.apply(h1_TT)
        styles.ewkStyle.apply(h1_EWK)
        styles.genuineBAltStyle.apply(h1_ST)
        
        h0 = histograms.Histo(h1_Data, "Data", "Data")
        h1 = histograms.Histo(h1_TT, "t#bar{t}", "TT")
        h3 = histograms.Histo(h1_EWK, "EWK", "EWK")
        h4 = histograms.Histo(h1_QCD, "QCD", "QCD")
        h5 = histograms.Histo(h1_ST, "ST", "ST")
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)


        myStackList = []
        if re == "CR1" or re == "SR":
            myStackList.insert(0, h0)
            myStackList.append(h1)
            myStackList.append(h4)
            myStackList.append(h5)
            myStackList.append(h3)
        else:
            myStackList.insert(0, h0)
            myStackList.append(h4)
            myStackList.append(h1)
            myStackList.append(h5)
            myStackList.append(h3)
            
        pNum = plots.DataMCPlot2(myStackList, saveFormats=[])
        pNum.setLuminosity(opts.intLumi)
        pNum.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(pNum, hName, **_kwargs)
        SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])


    # (C3) Numerator with SF
    for re in regions:
        
        hName = "Numerator_"+re+"_StackedMC_withSF"
        
        h2_Data = rhDict_num_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h2_QCD  = rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h2_EWK  = rhDict_num_withCR2SF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h2_ST   = rhDict_num_withCR2SF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        h2_TT   = rhDict_num_noSF["NormTT-"+re+"-Inclusive"].Clone("t#bar{t}") 

        styles.FakeBStyle6.apply(h2_TT)
        styles.ewkStyle.apply(h2_EWK)
        styles.genuineBAltStyle.apply(h2_ST)
        
        h0 = histograms.Histo(h2_Data, "Data"     , "Data")
        h1 = histograms.Histo(h2_TT,   "t#bar{t}" , "TT"  )
        h3 = histograms.Histo(h2_EWK,  "EWK"      , "EWK" )
        h4 = histograms.Histo(h2_QCD,  "QCD"      , "QCD" )
        h5 = histograms.Histo(h2_ST,   "ST"       , "ST"  )
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)

        myStackList = []
        if re == "CR1" or re == "SR":
            myStackList.insert(0, h0)
            myStackList.append(h1)
            myStackList.append(h4)
            myStackList.append(h5)
            myStackList.append(h3)
        else:
            myStackList.insert(0, h0)
            myStackList.append(h4)
            myStackList.append(h1)
            myStackList.append(h5)
            myStackList.append(h3)

        
        p1 = plots.DataMCPlot2(myStackList, saveFormats=[])
        p1.setLuminosity(opts.intLumi)
        p1.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(p1, hName, **_kwargs)
        SavePlot(p1, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])

    
    return
def PlotHistos(noSF_datasetsMgr, withCR1SF_datasetsMgr, withCR2SF_datasetsMgr, num_histoList, den_histoList,  opts):    
    
    # Get the histogram customisations (keyword arguments)
    _kwargs = GetHistoKwargs(num_histoList[0])
    
    # Get the root histos for all datasets and Control Regions (CRs)
    regions = ["SR", "VR", "CR1", "CR2"]
    labels  = ["Genuine", "Fake", "Inclusive"]
    
    #==========================================================================================
    # Get Dictionaries
    #==========================================================================================
    rhDict_den_noSF      = GetRootHistos(noSF_datasetsMgr,      den_histoList, regions)
    rhDict_num_noSF      = GetRootHistos(noSF_datasetsMgr,      num_histoList, regions)
    rhDict_num_withCR1SF = GetRootHistos(withCR1SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR1 are only applied in the Numerator on Fake TT
    rhDict_num_withCR2SF = GetRootHistos(withCR2SF_datasetsMgr, num_histoList, regions) # Scale Factors from CR2 are only applied in the Numerator on EWK+QCD+ST
    
    #==========================================================================================
    # Normalization Factors (see: getNormalization.py)
    #==========================================================================================
    f1 = 0.602756; f2=0.902921;

    # =========================================================================================
    # (A) Apply Normalization Factors (see: getNormalizations.py)
    # =========================================================================================
    
    # Normalize all histograms (QCD and TT) to normalization factors
    for re in regions:
        
        rhDict_den_noSF["NormQCD-"+re+"-Inclusive"] = rhDict_den_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1)

        rhDict_num_noSF["NormQCD-"+re+"-Inclusive"] =rhDict_num_noSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Scale(f1)

        rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"] = rhDict_num_withCR2SF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Scale(f1)
        
        for la in labels:
            
            rhDict_den_noSF["NormTT-"+re+"-"+la] = rhDict_den_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_den_noSF["NormTT-"+re+"-"+la].Scale(f2)
            
            rhDict_num_noSF["NormTT-"+re+"-"+la] = rhDict_num_noSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_num_noSF["NormTT-"+re+"-"+la].Scale(f2)
            
            rhDict_num_withCR1SF["NormTT-"+re+"-"+la] = rhDict_num_withCR1SF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_num_withCR1SF["NormTT-"+re+"-"+la].Scale(f2)
            
    # ==========================================================================================
    # (B) Make control plots with & without any SF applied in all regions
    # ==========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = True
    _kwargs["createLegend"]      = {"x1": 0.70, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    
    # (B1) Denominator
    for re in regions:

        hName = "Denominator_"+re+"_StackedMC"

        h0_Data      = rhDict_den_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h0_QCD       = rhDict_den_noSF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h0_GenuineTT = rhDict_den_noSF["NormTT-"+re+"-Genuine"].Clone("genuine t#bar{t}")
        h0_FakeTT    = rhDict_den_noSF["NormTT-"+re+"-Fake"].Clone("fake t#bar{t}")
        h0_EWK       = rhDict_den_noSF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h0_ST        = rhDict_den_noSF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        
        #print "------------------------------------------------"
        #print "             Region =  ", re
        #print "------------------------------------------------"
        #print "Data         = ", h0_Data.Integral()
        #print "Inclusive TT = ", rhDict_den_noSF["NormTT-"+re+"-Inclusive"].Integral()
        #print "Genuine TT   = ", h0_GenuineTT.Integral()
        #print "Fake TT      = ", h0_FakeTT.Integral()
        #print "ST           = ", h0_ST.Integral()
        #print "QCD          = ", h0_QCD.Integral()
        #print "EWK          = ", h0_EWK.Integral()
        
        styles.getFakeBStyle().apply(h0_FakeTT)
        styles.FakeBStyle6.apply(h0_GenuineTT)
        styles.ewkStyle.apply(h0_EWK)
        styles.genuineBAltStyle.apply(h0_ST)
        
        h0 = histograms.Histo(h0_Data, "Data", "Data")
        h1 = histograms.Histo(h0_GenuineTT, "t#bar{t} (genuine)", "TT")
        h2 = histograms.Histo(h0_FakeTT, "t#bar{t} (fake)", "TT")
        h3 = histograms.Histo(h0_EWK, "EWK", "EWK")
        h4 = histograms.Histo(h0_QCD, "QCD", "QCD")
        h5 = histograms.Histo(h0_ST, "ST", "ST")
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h2.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)
        
        myStackList = []
        myStackList.insert(0, h0)
        myStackList.append(h4)
        myStackList.append(h2)
        myStackList.append(h1)
        myStackList.append(h5)
        myStackList.append(h3)

        pDen = plots.DataMCPlot2(myStackList, saveFormats=[])
        pDen.setLuminosity(opts.intLumi)
        pDen.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(pDen, hName, **_kwargs)
        SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])


    # (B2) Numerator
    for re in regions:
        
        hName = "Numerator_"+re+"_StackedMC_noSF"
        
        h1_Data      = rhDict_num_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h1_QCD       = rhDict_num_noSF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h1_GenuineTT = rhDict_num_noSF["NormTT-"+re+"-Genuine"].Clone("genuine t#bar{t}")
        h1_FakeTT    = rhDict_num_noSF["NormTT-"+re+"-Fake"].Clone("fake t#bar{t}")
        h1_EWK       = rhDict_num_noSF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h1_ST        = rhDict_num_noSF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        
        styles.getFakeBStyle().apply(h1_FakeTT)
        styles.FakeBStyle6.apply(h1_GenuineTT)
        styles.ewkStyle.apply(h1_EWK)
        styles.genuineBAltStyle.apply(h1_ST)
        
        h0 = histograms.Histo(h1_Data, "Data", "Data")
        h1 = histograms.Histo(h1_GenuineTT, "t#bar{t} (genuine)", "TT")
        h2 = histograms.Histo(h1_FakeTT, "t#bar{t} (fake)", "TT")
        h3 = histograms.Histo(h1_EWK, "EWK", "EWK")
        h4 = histograms.Histo(h1_QCD, "QCD", "QCD")
        h5 = histograms.Histo(h1_ST, "ST", "ST")
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h2.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)

        myStackList = []
        myStackList.insert(0, h0)
        myStackList.append(h4)
        myStackList.append(h2)
        myStackList.append(h1)
        myStackList.append(h5)
        myStackList.append(h3)

        pNum = plots.DataMCPlot2(myStackList, saveFormats=[])
        pNum.setLuminosity(opts.intLumi)
        pNum.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(pNum, hName, **_kwargs)
        SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])


    #print " "
    #print "Numerator:"
    
    # (C3) Numerator with SF
    for re in regions:
        
        hName = "Numerator_"+re+"_StackedMC_withSF"
        
        h2_Data      = rhDict_num_noSF["Data-"+re+"-Inclusive"].Clone("Data")
        h2_QCD       = rhDict_num_withCR2SF["NormQCD-"+re+"-Inclusive"].Clone("QCD")
        h2_GenuineTT = rhDict_num_withCR1SF["NormTT-"+re+"-Genuine"].Clone("genuine t#bar{t}")
        h2_FakeTT    = rhDict_num_withCR1SF["NormTT-"+re+"-Fake"].Clone("fake t#bar{t}")
        h2_EWK       = rhDict_num_withCR2SF["EWK-"+re+"-Inclusive"].Clone("EWK")
        h2_ST        = rhDict_num_withCR2SF["SingleTop-"+re+"-Inclusive"].Clone("ST")
        
        #print "------------------------------------------------"
        #print "             Region =  ", re
        #print "------------------------------------------------"
        #print "Data         = ", h2_Data.Integral()
        #print "Inclusive TT = ", rhDict_num_withCR1SF["NormTT-"+re+"-Inclusive"].Integral()
        #print "Genuine TT   = ", h2_GenuineTT.Integral()
        #print "Fake TT      = ", h2_FakeTT.Integral()
        #print "ST           = ", h2_ST.Integral()
        #print "QCD          = ", h2_QCD.Integral()
        #print "EWK          = ", h2_EWK.Integral()

        styles.getFakeBStyle().apply(h2_FakeTT)
        styles.FakeBStyle6.apply(h2_GenuineTT)
        styles.ewkStyle.apply(h2_EWK)
        styles.genuineBAltStyle.apply(h2_ST)
        
        h0 = histograms.Histo(h2_Data,      "Data"               , "Data")
        h1 = histograms.Histo(h2_GenuineTT, "t#bar{t} (genuine)" , "TT"  )
        h2 = histograms.Histo(h2_FakeTT,    "t#bar{t} (fake)"    , "TT"  )
        h3 = histograms.Histo(h2_EWK,       "EWK"                , "EWK" )
        h4 = histograms.Histo(h2_QCD,       "QCD"                , "QCD" )
        h5 = histograms.Histo(h2_ST,        "ST"                 , "ST"  )
        
        h0.setIsDataMC(isData=True,  isMC=False)
        h1.setIsDataMC(isData=False, isMC=True)
        h2.setIsDataMC(isData=False, isMC=True)
        h3.setIsDataMC(isData=False, isMC=True)
        h4.setIsDataMC(isData=False, isMC=True)
        h5.setIsDataMC(isData=False, isMC=True)

        myStackList = []
        myStackList.insert(0, h0)
        myStackList.append(h4)
        myStackList.append(h2)
        myStackList.append(h1)
        myStackList.append(h5)
        myStackList.append(h3)
        
        p1 = plots.DataMCPlot2(myStackList, saveFormats=[])
        p1.setLuminosity(opts.intLumi)
        p1.setDefaultStyles()
        ROOT.gStyle.SetNdivisions(8, "X")
        plots.drawPlot(p1, hName, **_kwargs)
        SavePlot(p1, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])

    
    return