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", "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:
        #manager.CalculateTransferFactor(binLabels[0], rhDict["CRone-FakeB"], rhDict["CRtwo-FakeB"])
        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)
        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 = []
        
        # 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 #"test"
    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"% ( getModuleInfoString(opts) ) )
    manager.writeTransferFactorsToFile(fileName, opts)
    return
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
Beispiel #3
0
def PlotHistograms(datasetsMgr_Mcrab644_TopPtRew,
                   datasetsMgr_Mcrab644_noTopPtRew,
                   datasetsMgr_Mcrab905_TopPtRew,
                   datasetsMgr_Mcrab905_noTopPtRew):

    # Definitions
    kwargs = {}
    histos = []

    # For-loop: All histos in list
    dName = "TT"

    # Multicrab *644, top pt reweighting:
    p0 = plots.MCPlot(datasetsMgr_Mcrab644_TopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab644_TopPtRew = p0.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab644-ptRew")
    histos.append(h_Mcrab644_TopPtRew)

    # Multicrab *644, no top pt reweighting:
    p1 = plots.MCPlot(datasetsMgr_Mcrab644_noTopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab644_noTopPtRew = p1.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab644-noptRew")
    histos.append(h_Mcrab644_noTopPtRew)

    # Multicrab *905, top pt reweighting:
    p2 = plots.MCPlot(datasetsMgr_Mcrab905_TopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab905_TopPtRew = p2.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab905-ptRew")
    histos.append(h_Mcrab905_TopPtRew)

    # Multicrab *905, no top pt reweighting:
    p3 = plots.MCPlot(datasetsMgr_Mcrab905_noTopPtRew,
                      "Analysis_/TopQuarkPt",
                      normalizeToLumi=opts.intLumi,
                      saveFormats=[],
                      **kwargs)
    h_Mcrab905_noTopPtRew = p3.histoMgr.getHisto(dName).getRootHisto().Clone(
        "Mcrab905-noptRew")
    histos.append(h_Mcrab905_noTopPtRew)

    # Normalise histos
    for h in histos:
        if opts.normaliseToOne:
            h = h.Scale(1 / h.Integral())

    # Make comparison plot
    if opts.eight:
        # p = plots.ComparisonManyPlot(h_Mcrab905_TopPtRew, [ h_Mcrab905_noTopPtRew], saveFormats=[])
        p = plots.ComparisonManyPlot(h_Mcrab905_noTopPtRew,
                                     [h_Mcrab905_TopPtRew],
                                     saveFormats=[])
    else:
        # p = plots.ComparisonManyPlot(h_Mcrab644_TopPtRew, [h_Mcrab644_noTopPtRew], saveFormats=[])
        # p = plots.ComparisonManyPlot(h_Mcrab644_noTopPtRew, [h_Mcrab644_TopPtRew], saveFormats=[])
        p = plots.ComparisonManyPlot(
            h_Mcrab644_noTopPtRew, [h_Mcrab644_TopPtRew, h_Mcrab905_TopPtRew],
            saveFormats=[])
    p.setLuminosity(opts.intLumi)

    # Overwite signal style?
    if opts.eight:
        p.histoMgr.forHisto("Mcrab905-ptRew", styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Mcrab905-noptRew", styles.getFakeBLineStyle())
    else:
        p.histoMgr.forHisto("Mcrab644-ptRew", styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Mcrab644-noptRew", styles.getFakeBLineStyle())

    # Set draw style
    if opts.eight:
        p.histoMgr.setHistoDrawStyle("Mcrab905-noptRew", "HIST")
        p.histoMgr.setHistoDrawStyle("Mcrab905-ptRew", "AP")
    else:
        p.histoMgr.setHistoDrawStyle("Mcrab644-noptRew", "HIST")
        p.histoMgr.setHistoDrawStyle("Mcrab644-ptRew", "AP")

    # Set legend style
    if opts.eight:
        p.histoMgr.setHistoLegendStyle("Mcrab905-noptRew", "L")  #"F"
        p.histoMgr.setHistoLegendStyle("Mcrab905-ptRew", "LP")
    else:
        p.histoMgr.setHistoLegendStyle("Mcrab644-noptRew", "L")  #"F"
        p.histoMgr.setHistoLegendStyle("Mcrab644-ptRew", "LP")

    if opts.eight:
        p.histoMgr.setHistoLegendLabelMany({
            "Mcrab905-ptRew": "p_{T} reweight (8 TeV)",
            "Mcrab905-noptRew": "Default",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            "Mcrab644-ptRew": "p_{T} reweight (13 TeV)",
            "Mcrab644-noptRew": "Default",
        })

    # Draw customised plot
    if opts.eight:
        saveName = "TopQuarkPt_PtReweight_8TeV"
    else:
        saveName = "TopQuarkPt_PtReweight_13TeV"
    _units = "GeV/c"
    _leg = {"x1": 0.55, "y1": 0.75, "x2": 0.85, "y2": 0.87}

    if opts.normaliseToOne:
        yLabel = "Arbitrary Units / %0.0f " + _units
    else:
        yLabel = "Events / %0.0f " + _units

    plots.drawPlot(
        p,
        saveName,
        xlabel="generated top p_{T} (%s)" % (_units),
        ylabel=yLabel,
        log=False,
        rebinX=2,
        cmsExtraText="Simulation",  #"Preliminary",
        ratio=True,
        ratioType="errorPropagation",  #"errorScale", "binomial"
        divideByBinWidth=False,
        ratioErrorOptions={
            "numeratorStatSyst": False,
            "denominatorStatSyst": True
        },
        ratioMoveLegend={
            "dx": +0.21,
            "dy": 0.03,
            "dh": -0.08
        },
        ratioYlabel="Ratio ",
        createLegend=_leg,
        opts={
            "xmin": 0.0,
            "xmax": 800.0,
            "ymin": 0.0,
            "ymaxfactor": 1.2
        },
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        cutBox={
            "cutValue": 0.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        })

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath)
    return
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 are only applied in the Numerator
    
    # =================================================
    # Normalization Factors (see: getNormalization.py)
    # =================================================
    # Marina
    f1=0.619886; f2=0.904877;
    
    # Marina
    jsonName = "Efficiency_SystBDT_CR1_MET50_MuIso0p1_InvMET20_InvMuIso0p1_massCut300_LeadingJet.json"
    # =========================================================================================
    # (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) Estimate Fake TT in CR1 
    # ========================================================================================
    
    # (B1) Fake TT in Data - Denominator:  Data - EWK - ST - F1*QCD - F2*GenuineTT   
    rhDict_den_noSF["TTinData-CR1-Fake"] = rhDict_den_noSF["Data-CR1-Inclusive"].Clone("TTinData-CR1-Fake")
    rhDict_den_noSF["TTinData-CR1-Fake"].Add(rhDict_den_noSF["EWK-CR1-Inclusive"],       -1)
    rhDict_den_noSF["TTinData-CR1-Fake"].Add(rhDict_den_noSF["SingleTop-CR1-Inclusive"], -1)
    rhDict_den_noSF["TTinData-CR1-Fake"].Add(rhDict_den_noSF["NormQCD-CR1-Inclusive"],   -1)
    rhDict_den_noSF["TTinData-CR1-Fake"].Add(rhDict_den_noSF["NormTT-CR1-Genuine"],      -1)
    
    
    # (B2) Fake TT in Data - Numerator: Data - EWK*SF_{CR2} - ST_{CR2} - F1*QCD*SF_{CR2} - F2*GenuineTT
    rhDict_num_noSF["TTinData-CR1-Fake"] = rhDict_num_noSF["Data-CR1-Inclusive"].Clone("TTinData-CR1-Fake")
    rhDict_num_noSF["TTinData-CR1-Fake"].Add(rhDict_num_withCR2SF["EWK-CR1-Inclusive"],       -1)
    rhDict_num_noSF["TTinData-CR1-Fake"].Add(rhDict_num_withCR2SF["SingleTop-CR1-Inclusive"], -1)
    rhDict_num_noSF["TTinData-CR1-Fake"].Add(rhDict_num_withCR2SF["NormQCD-CR1-Inclusive"],   -1)
    rhDict_num_noSF["TTinData-CR1-Fake"].Add(rhDict_num_noSF["NormTT-CR1-Genuine"],           -1)
    
    # (B3) Fake TT in MC - Denominator: rhDict_den_noSF["TT-CR1-Fake"]
    # (B4) Fake TT in MC - Numerator:   rhDict_num_noSF["TT-CR1-Fake"]
    
    # ========================================================================================
    # (C) Plot Numerator and Denominator (Data Vs MC)
    # ========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"]      = {"x1": 0.60, "y1": 0.70, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"]  = True
    
    num_data = rhDict_num_noSF["TTinData-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (Data)")
    den_data = rhDict_den_noSF["TTinData-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (Data)")
    
    num_mc   = rhDict_num_noSF["TT-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (MC)")
    den_mc   = rhDict_den_noSF["TT-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (MC)")
    
    styles.getABCDStyle("SR").apply(num_data)
    styles.getABCDStyle("SR").apply(den_data)
    
    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)
    
    # Denominator
    hName = "FakeTT_CR1_Denominator_LeadingJet"
    hData_Den = histograms.Histo( den_data, "fake t#bar{t}_{CR1} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den   = histograms.Histo( den_mc,   "fake t#bar{t}_{CR1} (MC)", "MC", drawStyle="HIST");   hMC_Den.setIsDataMC(isData=False, isMC=True)
    
    pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDen.setLuminosity(opts.intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    
    # Numerator
    hName = "FakeTT_CR1_Numerator_LeadingJet"
    hData_Num = histograms.Histo( num_data, "fake t#bar{t}_{CR1} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num   = histograms.Histo( num_mc,   "fake t#bar{t}_{CR1} (MC)", "MC", drawStyle="HIST");   hMC_Num.setIsDataMC(isData=False, isMC=True)
    
    pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNum.setLuminosity(opts.intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    
    # =======================================================================================
    # (D) Plot Misidentification Rate (Data Vs MC)
    # =======================================================================================
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Misidentification rate",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : "errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 1.0, "xmax" : 600},
        "opts2"            : {"ymin": 0.6, "ymax": 1.5},
        "log"              : False,
        "createLegend"     : {"x1": 0.64, "y1": 0.72, "x2": 0.95, "y2": 0.92},
        }

    # Definitions
    bins = [0, 100, 200, 300, 400, 500, 600, 700]
    #bins = [0, 50, 100, 135, 185, 240, 275, 350, 450, 600]
    #bins = [0, 60, 100, 145, 210, 250,  350, 450, 600]
    #bins  = [0, 100, 175, 250, 325, 450, 600]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1
    
    # Data 
    h0_data_den = rhDict_den_noSF["TTinData-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (Data)")
    h0_data_num = rhDict_num_noSF["TTinData-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (Data)")
    
    # MC
    h0_mc_den   = rhDict_den_noSF["TT-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (MC)")
    h0_mc_num   = rhDict_num_noSF["TT-CR1-Fake"].Clone("fake t#bar{t}_{CR1} (MC)")
    
    h0_data_den = h0_data_den.Rebin(nx, "", xBins)
    h0_data_num = h0_data_num.Rebin(nx, "", xBins)
    
    h0_mc_den = h0_mc_den.Rebin(nx, "", xBins)
    h0_mc_num = h0_mc_num.Rebin(nx, "", xBins)
    
    hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den)
    hNumerator_MC,   hDenominator_MC   = GetHistosForEfficiency(h0_mc_num, h0_mc_den)
    
    eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data)
    eff_mc   = ROOT.TEfficiency(hNumerator_MC,   hDenominator_MC)
    
    eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)
    
    geff_data = convert2TGraph(eff_data)
    geff_mc   = convert2TGraph(eff_mc)
    
    styles.dataStyle.apply(geff_data)
    styles.ttStyle.apply(geff_mc)
    
    Graph_Data = histograms.HistoGraph(geff_data, "fake t#bar{t} (Data) ", "p", "P")
    Graph_MC   = histograms.HistoGraph(geff_mc, "fake t#bar{t} (MC)", "p", "P")
    
    # Create plot
    p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "MisID_CR1_LeadingJet"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    

    
    # Save results in JSON
    runRange = "273150-284044"
    analysis = opts.analysisName
    label = "2016"
    plotDir =  os.path.join(opts.folder, jsonName)
    pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geff_data)
    pythonWriter.addMCParameters(label, geff_mc)
    fileName_json = jsonName
    pythonWriter.writeJSON(fileName_json)
    

    return
Beispiel #5
0
def GetScaleFactors(datasetsMgr, num_pathList, den_pathList, intLumi):  

    # Get kwargs
    _kwargs = GetHistoKwargs(num_pathList[0], opts)        
    _kwargs["stackMCHistograms"] = False
    _kwargs["opts2"]     = {"ymin": 0.50, "ymax": 1.50}
    _kwargs["ratioType"] = "errorScale"
    
    # Get the root histos for all datasets and Control Regions (CRs)
    regions = ["SR", "VR", "CR1", "CR2"]
    labels  = ["Genuine", "Fake", "Inclusive"]
    
    # Get Dictionaries 
    rhDict_num = GetRootHistos(datasetsMgr, num_pathList, regions)
    rhDict_den = GetRootHistos(datasetsMgr, den_pathList, regions)
    
    # Marina
    # Normalization Factors (see: getNormalization.py)
    f1=0.619886; f2=0.904877;

    # Marina
    jsonName = "Efficiency_SystBDT_CR2_MET50_MuIso0p1_InvMET20_InvMuIso0p1_massCut300.json"


    # ------------------------------------------------------------------------------
    # (A) Normalize QCD and TT (MC) in all regions
    # -------------------------------------------------------------------------------
    
    for re in regions:
        rhDict_den["NormQCD-"+re+"-Inclusive"] = rhDict_den["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_den["NormQCD-"+re+"-Inclusive"].Scale(f1)
        
        rhDict_num["NormQCD-"+re+"-Inclusive"] = rhDict_num["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num["NormQCD-"+re+"-Inclusive"].Scale(f1)

        for la in labels:
            rhDict_den["NormTT-"+re+"-"+la] = rhDict_den["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_den["NormTT-"+re+"-"+la].Scale(f2)
            
            rhDict_num["NormTT-"+re+"-"+la] = rhDict_num["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_num["NormTT-"+re+"-"+la].Scale(f2)

    # -----------------------------------------------------------------------------
    # (B) Calculate BKG=QCD+EWK+ST in Data (CR2)
    # -----------------------------------------------------------------------------
    # (B1) Denominator
    rhDict_den["BKG_Data-CR2-Inclusive"] = rhDict_den["Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)")
    rhDict_den["BKG_Data-CR2-Inclusive"].Add( rhDict_den["NormTT-CR2-Inclusive"], -1)
    
    # (B2) Numerator
    rhDict_num["BKG_Data-CR2-Inclusive"] = rhDict_num["Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)")
    rhDict_num["BKG_Data-CR2-Inclusive"].Add( rhDict_num["NormTT-CR2-Inclusive"], -1)
    
    # -----------------------------------------------------------------------------
    # (C) Calculate BKG=QCD+EWK+ST in MC (CR2)
    # -----------------------------------------------------------------------------
    # (C1) Denominator
    rhDict_den["BKG_MC-CR2-Inclusive"] = rhDict_den["NormQCD-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2}  (MC)")
    rhDict_den["BKG_MC-CR2-Inclusive"].Add( rhDict_den["EWK-CR2-Inclusive"], +1)
    rhDict_den["BKG_MC-CR2-Inclusive"].Add( rhDict_den["SingleTop-CR2-Inclusive"], +1)
    
    # (C2) Numerator
    rhDict_num["BKG_MC-CR2-Inclusive"] = rhDict_num["NormQCD-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2}  (MC)")
    rhDict_num["BKG_MC-CR2-Inclusive"].Add( rhDict_num["EWK-CR2-Inclusive"], +1)
    rhDict_num["BKG_MC-CR2-Inclusive"].Add( rhDict_num["SingleTop-CR2-Inclusive"], +1)
    
        
    # Rebinning
    bins  = [0, 100, 200, 300, 400, 500, 600, 800]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1
    
    Den_QCD = rhDict_den["NormQCD-CR2-Inclusive"].Clone("QCD")
    Den_EWK = rhDict_den["EWK-CR2-Inclusive"].Clone("EWK")
    Den_ST  = rhDict_den["SingleTop-CR2-Inclusive"].Clone("ST")
    
    Num_QCD = rhDict_num["NormQCD-CR2-Inclusive"].Clone("QCD")
    Num_EWK = rhDict_num["EWK-CR2-Inclusive"].Clone("EWK")
    Num_ST = rhDict_num["SingleTop-CR2-Inclusive"].Clone("ST")
    
    Num_QCD = Num_QCD.Rebin(nx, "", xBins)
    Num_EWK = Num_EWK.Rebin(nx, "", xBins)
    Num_ST  = Num_ST.Rebin(nx, "", xBins)
    
    Den_QCD = Den_QCD.Rebin(nx, "", xBins)
    Den_EWK = Den_EWK.Rebin(nx, "", xBins)
    Den_ST  = Den_ST.Rebin(nx, "", xBins)
    
    # ------------------------------------------------------------------------------
    # (D) Plot denominator & numerator (Data Vs MC)
    # ------------------------------------------------------------------------------
    # (D1) Denominator
    hName = "QCD_EWK_ST_Denominator_CR2"
    
    h0 = rhDict_den["BKG_Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)")
    h1 = rhDict_den["BKG_MC-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2}  (MC)")

    hData = histograms.Histo( h0, "QCD+EWK (Data)", "Data", drawStyle="AP");    hData.setIsDataMC(isData=True, isMC=False)
    hMC   = histograms.Histo( h1, "QCD+EWK (MC)", "MC", drawStyle="HIST");     hMC.setIsDataMC(isData=False, isMC=True)
    
    _kwargs["createLegend"] = {"x1": 0.70, "y1": 0.60, "x2": 0.95, "y2": 0.92}
    
    pDen = plots.ComparisonManyPlot(hMC, [hData], saveFormats=[])
    pDen.setLuminosity(intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])

    # (D2) Numerator
    hName = "QCD_EWK_ST_Numerator_CR2"
    
    h2 = rhDict_num["BKG_Data-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (Data)")
    h3 = rhDict_num["BKG_MC-CR2-Inclusive"].Clone("QCD+EWK+ST_{CR2} (MC)")
    
    hDataNum = histograms.Histo( h2, "QCD+EWK (Data)", "Data", drawStyle="AP");    hDataNum.setIsDataMC(isData=True, isMC=False)
    hMCNum   = histograms.Histo( h3, "QCD+EWK (MC)", "MC", drawStyle="HIST");     hMCNum.setIsDataMC(isData=False, isMC=True)
    
    pNum = plots.ComparisonManyPlot(hMCNum, [hDataNum], saveFormats=[])
    pNum.setLuminosity(intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])
    
    # -----------------------------------------------------------------------------------------------------
    # (E) Plot Mis-Identification rate in CR2
    # -----------------------------------------------------------------------------------------------------
    hName = "MisID_CR2"
    
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Misidentification rate",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : "errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 2.0, "xmax" : 600},
        "opts2"            : {"ymin": 0.30, "ymax": 1.70},
        "log"              : False,
        "createLegend"     : {"x1": 0.55, "y1": 0.70, "x2": 0.95, "y2": 0.92},
        }

    hNum_Data = rhDict_num["BKG_Data-CR2-Inclusive"].Clone("Numerator (Data)")
    hDen_Data = rhDict_den["BKG_Data-CR2-Inclusive"].Clone("Denominator (Data)")
    hNum_MC   = rhDict_num["BKG_MC-CR2-Inclusive"].Clone("Numerator (MC)")
    hDen_MC   = rhDict_den["BKG_MC-CR2-Inclusive"].Clone("Denominator (MC)")

    # Rebinning
    bins  = [0, 100, 200, 300, 400, 500, 600, 800]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1
    
    hNum_Data = hNum_Data.Rebin(nx, "", xBins)
    hDen_Data = hDen_Data.Rebin(nx, "", xBins)
    hNum_MC   = hNum_MC.Rebin(nx, "", xBins)
    hDen_MC   = hDen_MC.Rebin(nx, "", xBins)
    
    num_data, den_data = GetHistosForEfficiency(hNum_Data, hDen_Data)
    num_mc, den_mc     = GetHistosForEfficiency(hNum_MC, hDen_MC)
    
    eff_Data = ROOT.TEfficiency(num_data, den_data)
    eff_Data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    geff_Data = convert2TGraph(eff_Data)
    Graph_Data = histograms.HistoGraph(geff_Data, "QCD+EWK (Data)", "p", "P")
    
    eff_MC = ROOT.TEfficiency(num_mc, den_mc)
    eff_MC.SetStatisticOption(ROOT.TEfficiency.kFCP)
    geff_MC = convert2TGraph(eff_MC)
    styles.getABCDStyle("CR1").apply(geff_MC)
    Graph_MC = histograms.HistoGraph(geff_MC, "QCD+EWK (MC)", "p", "P")

    # Create efficiency plots
    p2 = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    plots.drawPlot(p2, hName, **_kwargs)
    SavePlot(p2, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])
    

    # Dump results in a JSON File
    runRange = "273150-284044"
    analysis = opts.analysisName
    label = "2016"
    plotDir =  os.path.join(opts.folder, jsonName)
    pythonWriter.addParameters(plotDir, label, runRange, intLumi, geff_Data)
    pythonWriter.addMCParameters(label, geff_MC)
    fileName_json = jsonName
    pythonWriter.writeJSON(fileName_json)
        
    return
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.619886; f2=0.904877;

    # =========================================================================================
    # (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) Estimate Inclusive TT in SR
    # ==========================================================================================
            
    # (B1) Inclusive TT in Data - Denominator = Data - F1*QCD - - EWK - ST
    rhDict_den_noSF["TTinData-SR-Inclusive"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("t#bar{t} (Data)") 
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["EWK-SR-Inclusive"],       -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)

    # (B2) Inclusive TT in Data - Numerator = Data - F1*QCD*SF_{CR2} - ST*SF_{CR2} - EWK*SF_{CR2}
    rhDict_num_noSF["TTinData-SR-Inclusive"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["NormQCD-SR-Inclusive"],   -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["SingleTop-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withCR2SF["EWK-SR-Inclusive"],       -1)
    
    # (B3) Inclusive TT in MC - Denominator:  rhDict_den_noSF["TT-SR-Inclusive"]
    # (B4) Inclusive TT in MC - Numerator:    rhDict_num_noSF["TT-SR-Inclusive"]
    
    
    # ========================================================================================
    # (C) Plot Numerator and Denominator (Data Vs MC)
    # ========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"]      = {"x1": 0.68, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"]  = True

    num_data = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)")
    
    num_mc = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)")
    
    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)               

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)
    
    # Denominator
    hName = "InclusiveTT_SR_Denominator_LeadingJet"
    hData_Den = histograms.Histo( den_data, "t#bar{t} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den   = histograms.Histo( den_mc,   "t#bar{t} (MC)", "MC", drawStyle="HIST");   hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDen.setLuminosity(opts.intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])
    
    # Numerator
    hName = "InclusiveTT_SR_Numerator_LeadingJet"
    hData_Num = histograms.Histo( num_data, "t#bar{t} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num   = histograms.Histo( num_mc,   "t#bar{t} (MC)", "MC", drawStyle="HIST");   hMC_Num.setIsDataMC(isData=False, isMC=True)

    pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNum.setLuminosity(opts.intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".C", ".pdf"])
    
    # ========================================================================================
    # (D) Plot Genuine TT Efficiency
    # ========================================================================================
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Efficiency",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : "errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 1.28, "xmax" : 600},
        "opts2"            : {"ymin": 0.72, "ymax": 1.28},
        "log"              : False,
        "createLegend"     : {"x1": 0.68, "y1": 0.80, "x2": 0.95, "y2": 0.92},
        }

    bins = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1

    # Data 
    h0_data_den = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)")
    h0_data_num = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t} (Data)")
    
    # MC
    h0_mc_den = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)")
    h0_mc_num = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t} (MC)")
    
    h0_data_den = h0_data_den.Rebin(nx, "", xBins)
    h0_data_num = h0_data_num.Rebin(nx, "", xBins)
    
    h0_mc_den = h0_mc_den.Rebin(nx, "", xBins)
    h0_mc_num = h0_mc_num.Rebin(nx, "", xBins)
    
    hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den)
    hNumerator_MC,   hDenominator_MC   = GetHistosForEfficiency(h0_mc_num, h0_mc_den)
    
    eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data)
    eff_mc   = ROOT.TEfficiency(hNumerator_MC,   hDenominator_MC)

    eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geff_data = convert2TGraph(eff_data)
    geff_mc   = convert2TGraph(eff_mc)

    styles.dataStyle.apply(geff_data)
    styles.ttStyle.apply(geff_mc)

    Graph_Data = histograms.HistoGraph(geff_data, "t#bar{t} (Data) ", "p", "P")
    Graph_MC   = histograms.HistoGraph(geff_mc, "t#bar{t} (MC)", "p", "P")
    
    p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_InclusiveTT_SR_LeadingJet"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])

    # =============================
    #    Export JSON file
    # =============================
    #jsonName = "Efficiency_InclusiveTT_SR_MET50_MuIso0p1_InvMET20_InvMuIso0p1.json"
    #runRange = "273150-284044"
    #analysis = opts.analysisName
    #label = "2016"
    #plotDir =  os.path.join(opts.folder, jsonName)
    #pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geff_data)
    #pythonWriter.addMCParameters(label, geff_mc)
    #pythonWriter.writeJSON(jsonName)
    
    
    return
Beispiel #7
0
def PlotHistos(d_noSF, d_withSF, 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(d_noSF, den_histoList, regions)
    rhDict_num_noSF = GetRootHistos(d_noSF, num_histoList, regions)
    rhDict_num_withSF = GetRootHistos(d_withSF, num_histoList, regions)

    # =========================================================================================
    # Normalization Factors (see: getNormalization.py)
    # =========================================================================================
    #f1=0.626877; f2=0.880767;
    f1 = 0.625454
    f2 = 0.836566
    #noTopPtRew
    #f1 = 0.626893; f2 = 0.880846; #noDeltaRqq
    #f1 = 0.625454; f2 = 0.836566; #noDeltaRqq, noTopPtRew

    # =========================================================================================
    # (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_withSF["NormQCD-" + re + "-Inclusive"] = rhDict_num_withSF[
            "QCD-" + re + "-Inclusive"].Clone("NormQCD-" + re + "-Inclusive")
        rhDict_num_withSF["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_withSF["NormTT-" + re + "-" +
                              la] = rhDict_num_withSF["TT-" + re + "-" +
                                                      la].Clone("NormTT-" +
                                                                re + "-" + la)
            rhDict_num_withSF["NormTT-" + re + "-" + la].Scale(f2)

    # =========================================================================================
    # (B) Estimate Inclusive TT in SR
    # =========================================================================================

    # (B1) Inclusive TT in Data (Denominator)  =  Data - F1*QCD - EWK - ST
    rhDict_den_noSF["TTinData-SR-Inclusive"] = rhDict_den_noSF[
        "Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)")
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_den_noSF["NormQCD-SR-Inclusive"], -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_den_noSF["EWK-SR-Inclusive"], -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)

    # (B2) Inclusive TT in Data (Numerator)    =  Data - (F1*QCD -EWK - ST)*SF
    rhDict_num_noSF["TTinData-SR-Inclusive"] = rhDict_num_noSF[
        "Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_num_withSF["NormQCD-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_num_withSF["EWK-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(
        rhDict_num_withSF["SingleTop-SR-Inclusive"], -1)

    # ==========================================================================================
    # (C) Plot Inclusive Efficiency (Data Vs MC)
    # ==========================================================================================
    _kwargs["opts"] = {"xmax": 800, "ymaxfactor": 2.0}
    _kwargs["ratioYlabel"] = "Data/MC"
    _kwargs["ratio"] = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"] = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"] = True

    num_data = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone(
        "t#bar{t}_{SR} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone(
        "t#bar{t}_{SR} (Data)")

    num_mc = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")

    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)

    # Denominator
    hName = "InclusiveTT_SR_Denominator"
    hData_Den = histograms.Histo(den_data,
                                 "t#bar{t}_{SR} (Data)",
                                 "Data",
                                 drawStyle="AP")
    hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den = histograms.Histo(den_mc,
                               "t#bar{t}_{SR} (MC)",
                               "MC",
                               drawStyle="HIST")
    hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDen.setLuminosity(opts.intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png"])

    # Numerator
    hName = "InclusiveTT_SR_Numerator"
    hData_Num = histograms.Histo(num_data,
                                 "t#bar{t}_{SR} (Data)",
                                 "Data",
                                 drawStyle="AP")
    hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num = histograms.Histo(num_mc,
                               "t#bar{t}_{SR} (MC)",
                               "MC",
                               drawStyle="HIST")
    hMC_Num.setIsDataMC(isData=False, isMC=True)

    pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNum.setLuminosity(opts.intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png"])

    # =========================
    # Inclusive Efficiency
    # =========================
    _kwargs = {
        "xlabel": "p_{T} (GeV/c)",
        "ylabel": "Efficiency",
        "ratioYlabel": "Data/MC",
        "ratio": True,
        "ratioInvert": False,
        "ratioType": None,
        "ratioCreateLegend": True,
        "ratioMoveLegend": {
            "dx": -0.51,
            "dy": 0.03,
            "dh": -0.08
        },
        "ratioErrorOptions": {
            "numeratorStatSyst": False,
            "denominatorStatSyst": False
        },
        "errorBarsX": True,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 0.0,
            "ymaxfactor": 1.5,
            "xmax": 600
        },
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": False,
        "createLegend": {
            "x1": 0.64,
            "y1": 0.80,
            "x2": 0.95,
            "y2": 0.92
        },
    }
    _kwargs["cutBoxY"] = {
        "cutValue": 1.10,
        "fillColor": ROOT.kGray + 1,
        "fillStyle": 3001,
        "box": False,
        "line": True,
        "greaterThan": True,
        "mainCanvas": False,
        "ratioCanvas": True,
        "mirror": True
    }

    bins = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx = len(xBins) - 1

    # Data
    h0_data_den = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone(
        "t#bar{t}_{SR} (Data)")
    h0_data_num = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone(
        "t#bar{t}_{SR} (Data)")

    # MC
    h0_mc_den = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    h0_mc_num = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")

    h0_data_den = h0_data_den.Rebin(nx, "", xBins)
    h0_data_num = h0_data_num.Rebin(nx, "", xBins)

    h0_mc_den = h0_mc_den.Rebin(nx, "", xBins)
    h0_mc_num = h0_mc_num.Rebin(nx, "", xBins)

    hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(
        h0_data_num, h0_data_den)
    hNumerator_MC, hDenominator_MC = GetHistosForEfficiency(
        h0_mc_num, h0_mc_den)

    eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data)
    eff_mc = ROOT.TEfficiency(hNumerator_MC, hDenominator_MC)

    eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geff_data = convert2TGraph(eff_data)
    geff_mc = convert2TGraph(eff_mc)

    styles.dataStyle.apply(geff_data)
    styles.ttStyle.apply(geff_mc)

    Graph_Data = histograms.HistoGraph(geff_data, "t#bar{t}_{SR} (Data) ", "p",
                                       "P")
    Graph_MC = histograms.HistoGraph(geff_mc, "t#bar{t}_{SR} (MC)", "p", "P")

    p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_InclusiveTT_SR"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p,
             saveName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf", ".C"])

    # Save results in JSON
    if (opts.inclusiveEff):
        name = opts.noSFcrab.split("_")[-4]
        name = name.replace(opts.analysisName, "")
        print "name = ", name
        jsonName = "toptagEff_BDT" + name + "_InclusiveTT_TopMassCut400.json"
        runRange = "273150-284044"
        analysis = opts.analysisName
        label = "2016"
        plotDir = os.path.join(opts.folder, jsonName)
        pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi,
                                   geff_data)
        pythonWriter.addMCParameters(label, geff_mc)
        fileName_json = jsonName
        pythonWriter.writeJSON(fileName_json)

    # ==========================================================================================
    # (D) Estimate Genuine TT in SR
    # ==========================================================================================

    # (D1) Genuine TT in Data - Denominator = Data - F1*QCD - F2*FakeTT - EWK - ST
    rhDict_den_noSF["TTinData-SR-Genuine"] = rhDict_den_noSF[
        "Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)")
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(
        rhDict_den_noSF["NormQCD-SR-Inclusive"], -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(
        rhDict_den_noSF["NormTT-SR-Fake"], -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(
        rhDict_den_noSF["EWK-SR-Inclusive"], -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(
        rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)

    # (D2) Genuine TT in Data - Numerator = Data - [F1*QCD - F2*FakeTT - ST - EWK] * SF
    rhDict_num_noSF["TTinData-SR-Genuine"] = rhDict_num_noSF[
        "Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(
        rhDict_num_withSF["NormQCD-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(
        rhDict_num_withSF["NormTT-SR-Fake"], -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(
        rhDict_num_withSF["SingleTop-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(
        rhDict_num_withSF["EWK-SR-Inclusive"], -1)

    # ========================================================================================
    # (E) Plot Numerator and Denominator (Data Vs MC)
    # ========================================================================================
    _kwargs = GetHistoKwargs(num_histoList[0])
    _kwargs["opts"] = {"xmax": 800, "ymaxfactor": 2.0}
    _kwargs["ratioYlabel"] = "Data/MC"
    _kwargs["ratio"] = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"] = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"] = True

    num_data.Reset()
    den_data.Reset()
    num_mc.Reset()
    den_mc.Reset()

    num_data = rhDict_num_noSF["TTinData-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (Data)")

    num_mc = rhDict_num_noSF["TT-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (MC)")

    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)

    # Denominator
    hName = "GenuineTT_SR_Denominator"
    hData_Den = histograms.Histo(den_data,
                                 "genuine t#bar{t}_{SR} (Data)",
                                 "Data",
                                 drawStyle="AP")
    hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den = histograms.Histo(den_mc,
                               "genuine t#bar{t}_{SR} (MC)",
                               "MC",
                               drawStyle="HIST")
    hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDenumerator = plots.ComparisonManyPlot(hData_Den, [hMC_Den],
                                            saveFormats=[])
    pDenumerator.setLuminosity(opts.intLumi)
    pDenumerator.setDefaultStyles()
    plots.drawPlot(pDenumerator, hName, **_kwargs)
    SavePlot(pDenumerator,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png"])

    # Numerator
    hName = "GenuineTT_SR_Numerator"
    hData_Num = histograms.Histo(num_data,
                                 "genuine t#bar{t}_{SR} (Data)",
                                 "Data",
                                 drawStyle="AP")
    hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num = histograms.Histo(num_mc,
                               "genuine t#bar{t}_{SR} (MC)",
                               "MC",
                               drawStyle="HIST")
    hMC_Num.setIsDataMC(isData=False, isMC=True)

    pNumerator = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNumerator.setLuminosity(opts.intLumi)
    pNumerator.setDefaultStyles()
    plots.drawPlot(pNumerator, hName, **_kwargs)
    SavePlot(pNumerator,
             hName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png"])

    # ========================================================================================
    # (F) Plot Genuine TT Efficiency
    # ========================================================================================
    _kwargs = {
        "xlabel": "p_{T} (GeV/c)",
        "ylabel": "Efficiency",
        "ratioYlabel": "Data/MC",
        "ratio": True,
        "ratioInvert": False,
        "ratioType": None,  #"errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend": {
            "dx": -0.51,
            "dy": 0.03,
            "dh": -0.08
        },
        "ratioErrorOptions": {
            "numeratorStatSyst": False,
            "denominatorStatSyst": False
        },
        "errorBarsX": True,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 0.0,
            "ymaxfactor": 1.25,
            "xmax": 600
        },
        "opts2": {
            "ymin": 0.55,
            "ymax": 1.55
        },
        "log": False,
        "createLegend": {
            "x1": 0.54,
            "y1": 0.80,
            "x2": 0.95,
            "y2": 0.92
        },
    }
    _kwargs["cutBoxY"] = {
        "cutValue": 1.10,
        "fillColor": ROOT.kGray + 1,
        "fillStyle": 3001,
        "box": False,
        "line": True,
        "greaterThan": True,
        "mainCanvas": False,
        "ratioCanvas": True,
        "mirror": True
    }

    bins = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx = len(xBins) - 1

    # Data
    h1_data_den = rhDict_den_noSF["TTinData-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (Data)")
    h1_data_num = rhDict_num_noSF["TTinData-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (Data)")

    # MC
    h1_mc_den = rhDict_den_noSF["TT-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (MC)")
    h1_mc_num = rhDict_num_noSF["TT-SR-Genuine"].Clone(
        "genuine t#bar{t}_{SR} (MC)")

    h1_data_den = h1_data_den.Rebin(nx, "", xBins)
    h1_data_num = h1_data_num.Rebin(nx, "", xBins)

    h1_mc_den = h1_mc_den.Rebin(nx, "", xBins)
    h1_mc_num = h1_mc_num.Rebin(nx, "", xBins)

    h_Numerator_Data, h_Denominator_Data = GetHistosForEfficiency(
        h1_data_num, h1_data_den)
    h_Numerator_MC, h_Denominator_MC = GetHistosForEfficiency(
        h1_mc_num, h1_mc_den)

    effi_data = ROOT.TEfficiency(h_Numerator_Data, h_Denominator_Data)
    effi_mc = ROOT.TEfficiency(h_Numerator_MC, h_Denominator_MC)

    effi_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    effi_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geffi_data = convert2TGraph(effi_data)
    geffi_mc = convert2TGraph(effi_mc)

    styles.dataStyle.apply(geffi_data)
    styles.ttStyle.apply(geffi_mc)

    Graph_Data = histograms.HistoGraph(geffi_data,
                                       "genuine t#bar{t}_{SR} (Data) ", "p",
                                       "P")
    Graph_MC = histograms.HistoGraph(geffi_mc, "genuine t#bar{t}_{SR} (MC)",
                                     "p", "P")

    pp = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_GenuineTT_SR"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(pp, savePath, **_kwargs)
    SavePlot(pp,
             saveName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf", ".C"])

    # Save results in JSON
    if (not opts.inclusiveEff):
        name = opts.noSFcrab.split("_")[-4]
        name = name.replace(opts.analysisName, "")
        jsonName = "toptagEff_BDT" + name + "_GenuineTT_TopMassCut400.json"
        runRange = "273150-284044"
        analysis = opts.analysisName
        label = "2016"
        plotDir = os.path.join(opts.folder, jsonName)
        pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi,
                                   geffi_data)
        pythonWriter.addMCParameters(label, geffi_mc)
        fileName_json = jsonName
        pythonWriter.writeJSON(fileName_json)

    return
Beispiel #8
0
def GetPurityHistoGraph(datasetsMgr, folder, hName):

    # Which folder to use
    genuineBFolder = folder + "EWKGenuineB"
    fakeBFolder = folder + "EWKFakeB"
    histoName = os.path.join(folder, hName)
    hNameGenuineB = os.path.join(genuineBFolder, hName)
    Verbose("Creating purity plot for %s" % (histoName), True)

    # Get histogram customisations
    _kwargs = GetHistoKwargs(histoName, opts)

    # Get histos (Data, EWK) for Inclusive
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName))
    if opts.doQCD:
        p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName))
    else:
        p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, hNameGenuineB))

    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Clone histograms
    Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    EWK = p2.histoMgr.getHisto("EWK").getRootHisto().Clone(
        "EWK")  # EWKGenuineB
    QCD = p1.histoMgr.getHisto("Data").getRootHisto().Clone("QCD")

    # Rebin histograms (Before calculating Purity)
    if "binList" in _kwargs:
        xBins = _kwargs["binList"]
        nx = len(xBins) - 1
        newName = ""
        Verbose("Setting customly-selected bins %s" % (xBins), True)

        Data = Data.Rebin(nx, "", xBins)
        EWK = EWK.Rebin(nx, "", xBins)
        QCD = QCD.Rebin(nx, "", xBins)

    # Get QCD = Data-EWK
    QCD.Add(EWK, -1)

    # Create the Purity histos
    hPurity = GetPurityHisto(Data,
                             EWK,
                             _kwargs,
                             printValues=False,
                             hideZeros=True)
    if opts.doEWK:
        hPurity = GetPurityHisto(Data,
                                 QCD,
                                 _kwargs,
                                 printValues=False,
                                 hideZeros=True)

    # Convert histos to TGraph
    gPurity = convertHisto2TGraph(hPurity, printValues=False)

    # Set legend labels
    if opts.doQCD:
        qcdLabel = "QCD (%s)" % GetControlRegionLabel(histoName)
        ewkLabel = "EWK (%s)" % GetControlRegionLabel(histoName)
    else:
        qcdLabel = "Fake-b (%s)" % GetControlRegionLabel(histoName)
        ewkLabel = "Genuine-b (%s)" % GetControlRegionLabel(histoName)

    # Apply random histo styles
    s = styles.getABCDStyle(GetControlRegionLabel(histoName))
    s.apply(gPurity)

    # Create histoGraph object
    if opts.doEWK:
        hgPurity = histograms.HistoGraph(gPurity, ewkLabel, "p", "P")
    else:
        hgPurity = histograms.HistoGraph(gPurity, qcdLabel, "p", "P")

    # Save for future use
    _kwargs["histoName"] = histoName
    return hgPurity, _kwargs
def GetPurityHistoGraph(datasetsMgr, folder, hName):

    # Which folder to use (Inclusive or GenuineB?)
    genuineBFolder = folder + "EWKGenuineB"
    fakeBFolder    = folder + "EWKFakeB"    
    histoName_Incl = os.path.join(folder, hName)
    histoName_Gen  = os.path.join(genuineBFolder, hName)
    
    # Get histogram customisations
    _kwargs  = GetHistoKwargs(histoName_Incl, opts)

    # Get histos (Data, EWK) for Inclusive
    pIncl = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName_Incl) )
    pGen  = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName_Gen) )

    # Save name for future use
    _kwargs["histoName"] = histoName_Incl

    # Normalise to luminosity
    pIncl.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())
    pGen.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Clone histograms 
    Data  = pIncl.histoMgr.getHisto("Data").getRootHisto().Clone("Data")
    FakeB = pIncl.histoMgr.getHisto("Data").getRootHisto().Clone("FakeB")
    QCD   = pIncl.histoMgr.getHisto("Data").getRootHisto().Clone("QCD")
    EWK   = pIncl.histoMgr.getHisto("EWK").getRootHisto().Clone("EWK")
    GenB  = pGen.histoMgr.getHisto("EWK").getRootHisto().Clone("GenuineB")

    # Rebin histograms (Before calculating Purity)
    if "binList" in _kwargs:
        xBins = _kwargs["binList"]
        nx    = len(xBins)-1
        Data  = Data.Rebin(nx , "", xBins)
        FakeB = FakeB.Rebin(nx, "", xBins)
        QCD   = QCD.Rebin(nx  , "", xBins)
        EWK   = EWK.Rebin(nx  , "", xBins)
        GenB  = GenB.Rebin(nx , "", xBins)

    # FakeB = Data - EWK_GenuineB ; QCD = Data-EWK
    FakeB.Add(GenB, -1)
    QCD.Add(EWK, -1)


    # Create the Purity histos
    if opts.type == "FakeB":
        if 1:
            hPurity = GetPurityHisto(Data, GenB, _kwargs, subtractFromOne=True, printValues=False, hideZeros=False) 
        else: #equivalent
            hPurity = GetPurityHisto(Data, FakeB, _kwargs, subtractFromOne=False, printValues=False, hideZeros=False) 
    elif opts.type == "GenuineB":
        if 1:
            hPurity = GetPurityHisto(Data, GenB, _kwargs, subtractFromOne=False, printValues=False, hideZeros=False)
        else:#equivalent
            hPurity = GetPurityHisto(Data, FakeB, _kwargs, subtractFromOne=True, printValues=False, hideZeros=False) 
    elif opts.type == "QCD":
        hPurity = GetPurityHisto(Data, EWK, _kwargs, subtractFromOne=True, printValues=False, hideZeros=False)
    elif opts.type == "EWK":
        hPurity = GetPurityHisto(Data, EWK, _kwargs, subtractFromOne=False, printValues=False, hideZeros=False)
    else:
        raise Exception("This should never be reached")
            
    # Convert histos to TGraph
    gPurity = convertHisto2TGraph(hPurity, _kwargs, printValues=False)

    # Set legend label    
    label = "%s (%s)" % (opts.type, GetControlRegionLabel(histoName_Incl))
    label = label.replace("FakeB", "Fake-b").replace("GenuineB", "Genuine-b")

    # Apply random histo styles
    s = styles.getABCDStyle( GetControlRegionLabel(histoName_Incl) )
    s.apply(gPurity)        

    # Create histoGraph object
    hgPurity = histograms.HistoGraph( gPurity, label, "p", "P")

    return hgPurity, _kwargs
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
def PlotComparison(datasetsMgr, hBaseline, hInverted, ext):

    # Create corresponding paths for GenuineB and FakeB histograms (not only Inclusive) 
    hBaseline_Inclusive = hBaseline #no extra string 
    hInverted_Inclusive = hInverted #no extra string 
    hBaseline_GenuineB  = hBaseline_Inclusive.replace(opts.folder, opts.folder + "EWKGenuineB")
    hInverted_GenuineB  = hInverted_Inclusive.replace(opts.folder, opts.folder + "EWKGenuineB")
    hBaseline_FakeB     = hBaseline_Inclusive.replace(opts.folder, opts.folder + "EWKFakeB")
    hInverted_FakeB     = hInverted_Inclusive.replace(opts.folder, opts.folder + "EWKFakeB")

    # Create the histograms in the Baseline (SR) and Inverted (CR) regions
    pBaseline_Inclusive = plots.DataMCPlot(datasetsMgr, hBaseline_Inclusive)
    pBaseline_GenuineB  = plots.DataMCPlot(datasetsMgr, hBaseline_GenuineB )
    pBaseline_FakeB     = plots.DataMCPlot(datasetsMgr, hBaseline_FakeB    )
    pInverted_Inclusive = plots.DataMCPlot(datasetsMgr, hInverted_Inclusive)
    pInverted_GenuineB  = plots.DataMCPlot(datasetsMgr, hInverted_GenuineB )
    pInverted_FakeB     = plots.DataMCPlot(datasetsMgr, hInverted_FakeB )

    # Extract the correct SR and CR histograms
    baseline_Data        = pBaseline_Inclusive.histoMgr.getHisto("Data").getRootHisto().Clone("Baseline-Data")
    if opts.useMC: 
        baseline_QCD     = pBaseline_Inclusive.histoMgr.getHisto("QCD").getRootHisto().Clone("Baseline-QCD")
    baseline_EWKGenuineB = pBaseline_GenuineB.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKGenuineB")
    baseline_EWKFakeB    = pBaseline_FakeB.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKFakeB")
    inverted_Data        = pInverted_Inclusive.histoMgr.getHisto("Data").getRootHisto().Clone("Inverted-Data")
    if opts.useMC:    
        inverted_QCD     = pInverted_Inclusive.histoMgr.getHisto("QCD").getRootHisto().Clone("Inverted-QCD")
    inverted_EWKGenuineB = pInverted_GenuineB.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKGenuineB") 
    inverted_EWKFakeB    = pInverted_FakeB.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKFakeB")

    # Subtract EWKGenuineB from Data to get FakeB (= QCD_inclusive + EWK_genuineB)
    if opts.useMC: 
        # FakeB = QCD + EWKFakeB
        baseline_FakeB = baseline_QCD.Clone("Baseline-FakeB")
        inverted_FakeB = inverted_QCD.Clone("Inverted-FakeB")

        # Add the EWKFakeB
        baseline_FakeB.Add(baseline_EWKFakeB, +1)
        inverted_FakeB.Add(inverted_EWKFakeB, +1)
    else:
        # FakeB = Data -EWKGenuineB
        baseline_FakeB = baseline_Data.Clone("Baseline-FakeB")
        inverted_FakeB = inverted_Data.Clone("Inverted-FakeB")

        # Subtract the EWK GenuineB
        baseline_FakeB.Add(baseline_EWKGenuineB, -1)
        inverted_FakeB.Add(inverted_EWKGenuineB, -1)

    # Normalize histograms to unit area
    if opts.normaliseToOne:
        baseline_FakeB.Scale(1.0/baseline_FakeB.Integral())
        inverted_FakeB.Scale(1.0/inverted_FakeB.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(baseline_FakeB, [inverted_FakeB], saveFormats=[])
    #p = plots.ComparisonPlot(baseline_FakeB, inverted_FakeB, saveFormats=[]) #also works!
    p.setLuminosity(opts.intLumi)

    # Apply histogram styles
    p.histoMgr.forHisto("Baseline-FakeB" , styles.getABCDStyle(ext.split("v")[0]))
    p.histoMgr.forHisto("Inverted-FakeB" , styles.getABCDStyle(ext.split("v")[1]))
        
    # Set draw/legend style
    p.histoMgr.setHistoDrawStyle("Baseline-FakeB", "AP")
    p.histoMgr.setHistoDrawStyle("Inverted-FakeB", "HIST")
    p.histoMgr.setHistoLegendStyle("Baseline-FakeB", "LP")
    p.histoMgr.setHistoLegendStyle("Inverted-FakeB", "F")
        
    # Set legend labels
    if opts.useMC:
        p.histoMgr.setHistoLegendLabelMany({
                #"Baseline-FakeB" : "Fake-B (Baseline)",
                #"Inverted-FakeB" : "Fake-B (Inverted)",
                "Baseline-FakeB" : "Baseline (MC)",
                "Inverted-FakeB" : "Inverted (MC)",
         
       })
    else:
        p.histoMgr.setHistoLegendLabelMany({
                #"Baseline-FakeB" : "Baseline",
                #"Inverted-FakeB" : "Inverted",
                "Baseline-FakeB" : ext.split("v")[0],
                "Inverted-FakeB" : ext.split("v")[1],
                })

    # Get histogram keyword arguments
    kwargs_ = GetHistoKwargs(hBaseline_Inclusive, ext, opts)

    # Draw the histograms
    plots.drawPlot(p, hBaseline_Inclusive, **kwargs_)

    # Save plot in all formats    
    saveName = hBaseline_Inclusive.split("/")[-1]
    saveName = saveName.replace("Baseline_", "")
    saveName = saveName.replace("Inverted_", "")
    saveName = saveName.replace("_AfterAllSelections", "_" + ext)
    saveName = saveName.replace("_AfterCRSelections", "_" + ext)

    if opts.useMC:
        savePath = os.path.join(opts.saveDir, "MC", opts.optMode)
    else:
        savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath, saveFormats = [".png", ".pdf"])
    return
def PlotHistograms(datasetsMgr, histoName):

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

    # For-loop: All histograms in all regions
    for region in regionsList:
        hName = histoName.replace(hRegion, region)
        p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])

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

    # For-loop: All histograms in all regions
    for region in regionsList:
        hName = histoName.replace(hRegion, region).replace("Medium_", "Loose_")
        p = plots.DataMCPlot(datasetsMgr, hName, saveFormats=[])

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

    p = plots.ComparisonManyPlot(rootHistos[0], rootHistos[1:], saveFormats=[])
    p.setLuminosity(opts.intLumi)

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

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

    # Apply styles
    dumbie  = ["SR", "VR", "CRone", "CRtwo"]
    for i, h in enumerate(rootHistos, 0):
        region = h.GetName()
        if region == "SR":
            styles.fakeBLineStyle1.apply(p.histoMgr.getHisto(region).getRootHisto())
            p.histoMgr.setHistoDrawStyle(region, "HIST")
            p.histoMgr.setHistoLegendStyle(region, "L")
        else:
            #styles.getABCDStyle(region.split("_")[0]).apply(p.histoMgr.getHisto(region).getRootHisto())
            styles.getABCDStyle(dumbie[i]).apply(p.histoMgr.getHisto(region).getRootHisto())

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

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

    p.histoMgr.setHistoLegendLabelMany({
            "SR_CSVv2-M" : "SR (CSVv2-M)",
            "VR_CSVv2-M" : "VR (CSVv2-M)",
            "VR_CSVv2-L" : "VR (CSVv2-L)",
                })

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

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"] )
    return
def PlotComparison(datasetsMgr1, datasetsMgr2, datasetsMgr3, hBaseline, hInverted, ext):

    # Create corresponding paths for GenuineB and FakeB histograms (not only Inclusive) 
    hBaseline_Inclusive = hBaseline #no extra string 
    hInverted_Inclusive = hInverted #no extra string 
    hBaseline_GenuineB  = hBaseline_Inclusive.replace(opts.folder, opts.folder + "EWKGenuineB")
    hInverted_GenuineB  = hInverted_Inclusive.replace(opts.folder, opts.folder + "EWKGenuineB")
    hBaseline_FakeB     = hBaseline_Inclusive.replace(opts.folder, opts.folder + "EWKFakeB")
    hInverted_FakeB     = hInverted_Inclusive.replace(opts.folder, opts.folder + "EWKFakeB")

    # Create the histograms in the Baseline (SR) and Inverted (CR) regions
    pBaseline_Inclusive1 = plots.DataMCPlot(datasetsMgr1, hBaseline_Inclusive)
    pBaseline_GenuineB1  = plots.DataMCPlot(datasetsMgr1, hBaseline_GenuineB )
    pBaseline_FakeB1     = plots.DataMCPlot(datasetsMgr1, hBaseline_FakeB    )
    pInverted_Inclusive1 = plots.DataMCPlot(datasetsMgr1, hInverted_Inclusive)
    pInverted_GenuineB1  = plots.DataMCPlot(datasetsMgr1, hInverted_GenuineB )
    pInverted_FakeB1     = plots.DataMCPlot(datasetsMgr1, hInverted_FakeB )

    pBaseline_Inclusive2 = plots.DataMCPlot(datasetsMgr2, hBaseline_Inclusive)
    pBaseline_GenuineB2  = plots.DataMCPlot(datasetsMgr2, hBaseline_GenuineB )
    pBaseline_FakeB2     = plots.DataMCPlot(datasetsMgr2, hBaseline_FakeB    )
    pInverted_Inclusive2 = plots.DataMCPlot(datasetsMgr2, hInverted_Inclusive)
    pInverted_GenuineB2  = plots.DataMCPlot(datasetsMgr2, hInverted_GenuineB )
    pInverted_FakeB2     = plots.DataMCPlot(datasetsMgr2, hInverted_FakeB )

    pBaseline_Inclusive3 = plots.DataMCPlot(datasetsMgr3, hBaseline_Inclusive)
    pBaseline_GenuineB3  = plots.DataMCPlot(datasetsMgr3, hBaseline_GenuineB )
    pBaseline_FakeB3     = plots.DataMCPlot(datasetsMgr3, hBaseline_FakeB    )
    pInverted_Inclusive3 = plots.DataMCPlot(datasetsMgr3, hInverted_Inclusive)
    pInverted_GenuineB3  = plots.DataMCPlot(datasetsMgr3, hInverted_GenuineB )
    pInverted_FakeB3     = plots.DataMCPlot(datasetsMgr3, hInverted_FakeB )

    # Extract the correct SR and CR histograms
    baseline_Data1        = pBaseline_Inclusive1.histoMgr.getHisto("Data").getRootHisto().Clone("Baseline-Data1")
    baseline_EWKGenuineB1 = pBaseline_GenuineB1.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKGenuineB1")
    baseline_EWKFakeB1    = pBaseline_FakeB1.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKFakeB1")
    inverted_Data1        = pInverted_Inclusive1.histoMgr.getHisto("Data").getRootHisto().Clone("Inverted-Data1")
    inverted_EWKGenuineB1 = pInverted_GenuineB1.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKGenuineB1") 
    inverted_EWKFakeB1    = pInverted_FakeB1.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKFakeB1")

    baseline_Data2        = pBaseline_Inclusive2.histoMgr.getHisto("Data").getRootHisto().Clone("Baseline-Data2")
    baseline_EWKGenuineB2 = pBaseline_GenuineB2.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKGenuineB2")
    baseline_EWKFakeB2    = pBaseline_FakeB2.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKFakeB2")
    inverted_Data2        = pInverted_Inclusive2.histoMgr.getHisto("Data").getRootHisto().Clone("Inverted-Data2")
    inverted_EWKGenuineB2 = pInverted_GenuineB2.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKGenuineB2") 
    inverted_EWKFakeB2    = pInverted_FakeB2.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKFakeB2")

    baseline_Data3        = pBaseline_Inclusive3.histoMgr.getHisto("Data").getRootHisto().Clone("Baseline-Data3")
    baseline_EWKGenuineB3 = pBaseline_GenuineB3.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKGenuineB3")
    baseline_EWKFakeB3    = pBaseline_FakeB3.histoMgr.getHisto("EWK").getRootHisto().Clone("Baseline-EWKFakeB3")
    inverted_Data3        = pInverted_Inclusive3.histoMgr.getHisto("Data").getRootHisto().Clone("Inverted-Data3")
    inverted_EWKGenuineB3 = pInverted_GenuineB3.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKGenuineB3") 
    inverted_EWKFakeB3    = pInverted_FakeB3.histoMgr.getHisto("EWK").getRootHisto().Clone("Inverted-EWKFakeB3")

    # FakeB = Data -EWKGenuineB
    baseline_FakeB1 = baseline_Data1.Clone("Baseline-FakeB1")
    inverted_FakeB1 = inverted_Data1.Clone("Inverted-FakeB1")

    baseline_FakeB2 = baseline_Data2.Clone("Baseline-FakeB2")
    inverted_FakeB2 = inverted_Data2.Clone("Inverted-FakeB2")

    baseline_FakeB3 = baseline_Data3.Clone("Baseline-FakeB3")
    inverted_FakeB3 = inverted_Data3.Clone("Inverted-FakeB3")


    # Subtract the EWK GenuineB
    baseline_FakeB1.Add(baseline_EWKGenuineB1, -1)
    inverted_FakeB1.Add(inverted_EWKGenuineB1, -1)

    baseline_FakeB2.Add(baseline_EWKGenuineB2, -1)
    inverted_FakeB2.Add(inverted_EWKGenuineB2, -1)

    baseline_FakeB3.Add(baseline_EWKGenuineB3, -1)
    inverted_FakeB3.Add(inverted_EWKGenuineB3, -1)

    # Normalize histograms to unit area
    if opts.normaliseToOne:
        baseline_FakeB1.Scale(1.0/baseline_FakeB1.Integral())
        inverted_FakeB1.Scale(1.0/inverted_FakeB1.Integral())

        baseline_FakeB2.Scale(1.0/baseline_FakeB2.Integral())
        inverted_FakeB2.Scale(1.0/inverted_FakeB2.Integral())

        baseline_FakeB3.Scale(1.0/baseline_FakeB3.Integral())
        inverted_FakeB3.Scale(1.0/inverted_FakeB3.Integral())

    # Create the final plot object
    if ext == "CR1" or ext == "SR":
        p = plots.ComparisonManyPlot(baseline_FakeB1, [baseline_FakeB2, baseline_FakeB3], saveFormats=[])
    elif ext == "CR2" or ext == "VR":
        p = plots.ComparisonManyPlot(inverted_FakeB1, [inverted_FakeB2, inverted_FakeB3], saveFormats=[])
    else:
        raise Exception("Unexpected extension %s" % (ext))
    p.setLuminosity(opts.intLumi)

    # Get the BDT cut values from the multicrab name
    BDT1 = find_between(opts.mcrab1, "MVAm1p00to", "_").replace("p", ".")
    BDT2 = find_between(opts.mcrab2, "MVAm1p00to", "_").replace("p", ".")
    BDT3 = find_between(opts.mcrab3, "MVAm1p00to", "_").replace("p", ".")

    # Apply histogram styles
    if ext == "CR1" or ext == "SR":
        p.histoMgr.forHisto("Baseline-FakeB1" , styles.getFakeBLineStyle()) # getABCDStyle("SR") , getABCDStyle("VR")
        p.histoMgr.forHisto("Baseline-FakeB2" , styles.genuineBAltStyle) 
        p.histoMgr.forHisto("Baseline-FakeB3" , styles.getABCDStyle("SR") )

        # Set drawing style
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB1"  , "HIST")
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB2"  , "AP")
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB3"  , "AP")

        # Set legend styles
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB1", "L")
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB2", "LP")
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB3", "LP")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
                "Baseline-FakeB1" : "%s (BDT < %s)" % (ext, BDT1),
                "Baseline-FakeB2" : "%s (BDT < %s)" % (ext, BDT2),
                "Baseline-FakeB3" : "%s (BDT < %s)" % (ext, BDT3),
                })        
    else:
        p.histoMgr.forHisto("Inverted-FakeB1" , styles.getFakeBLineStyle())
        p.histoMgr.forHisto("Inverted-FakeB2" , styles.genuineBAltStyle)
        p.histoMgr.forHisto("Inverted-FakeB3" , styles.getABCDStyle("SR") )
        # Set drawing styles
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB1"  , "HIST")
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB2"  , "AP")
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB3"  , "AP")
        
        # Set legend styles
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB1", "L")
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB2", "LP")
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB3", "LP")
        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
                "Inverted-FakeB1" : "%s (BDT < %s)" % (ext, BDT1),
                "Inverted-FakeB2" : "%s (BDT < %s)" % (ext, BDT2),
                "Inverted-FakeB3" : "%s (BDT < %s)" % (ext, BDT3),
            })


    # Get histogram keyword arguments
    kwargs_ = GetHistoKwargs(hBaseline_Inclusive, ext, opts)

    # Draw the histograms
    plots.drawPlot(p, hBaseline_Inclusive, **kwargs_) #iro
    
    # Save plot in all formats    
    saveName = hBaseline_Inclusive.split("/")[-1]
    saveName = saveName.replace("Baseline_", "")
    saveName = saveName.replace("Inverted_", "")
    saveName = saveName.replace("_AfterAllSelections", "_" + ext)
    saveName = saveName.replace("_AfterCRSelections", "_" + ext)
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath, saveFormats = [".png", ".pdf"])
    return
Beispiel #14
0
def PlotHistograms(datasetsMgr, histoList, binLabels, opts):
    '''
    histoList contains all histograms for all bins for CR1 and CR2 
    
    '''
    # Get the root histos for all datasets and Control Regions (CRs)
    rhDict = GetRootHistos(datasetsMgr, histoList)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Get the histogram customisations (keyword arguments)
        p.appendPlotObject(
            histograms.PlotText(0.20,
                                0.88,
                                GetBinText(bin),
                                bold=True,
                                size=22))
        plots.drawPlot(p, saveName, **GetHistoKwargs(saveName))
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, opts.optMode),
                 saveFormats=[".png", ".pdf"])
    return
def PlotHistos(d_noSF, d_withSF, 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(d_noSF, den_histoList, regions)
    rhDict_num_noSF   = GetRootHistos(d_noSF, num_histoList, regions)
    rhDict_num_withSF = GetRootHistos(d_withSF, num_histoList, regions) 
        
    # =========================================================================================
    # Normalization Factors (see: getNormalization.py)
    # =========================================================================================
    #f1=0.626877; f2=0.880767;
    f1 = 0.625454; f2 = 0.836566; #noTopPtRew
    #f1 = 0.626893; f2 = 0.880846; #noDeltaRqq
    #f1 = 0.625454; f2 = 0.836566; #noDeltaRqq, noTopPtRew
    
    # =========================================================================================
    # (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_withSF["NormQCD-"+re+"-Inclusive"] = rhDict_num_withSF["QCD-"+re+"-Inclusive"].Clone("NormQCD-"+re+"-Inclusive")
        rhDict_num_withSF["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_withSF["NormTT-"+re+"-"+la] = rhDict_num_withSF["TT-"+re+"-"+la].Clone("NormTT-"+re+"-"+la)
            rhDict_num_withSF["NormTT-"+re+"-"+la].Scale(f2)
            

    # =========================================================================================
    # (B) Estimate Inclusive TT in SR
    # =========================================================================================
    
    # (B1) Inclusive TT in Data (Denominator)  =  Data - F1*QCD - EWK - ST
    rhDict_den_noSF["TTinData-SR-Inclusive"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)")
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["EWK-SR-Inclusive"],       -1)
    rhDict_den_noSF["TTinData-SR-Inclusive"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)
    
    # (B2) Inclusive TT in Data (Numerator)    =  Data - (F1*QCD -EWK - ST)*SF
    rhDict_num_noSF["TTinData-SR-Inclusive"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("Inclusive t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withSF["EWK-SR-Inclusive"],       -1)
    rhDict_num_noSF["TTinData-SR-Inclusive"].Add(rhDict_num_withSF["SingleTop-SR-Inclusive"], -1)
    
    # ==========================================================================================
    # (C) Plot Inclusive Efficiency (Data Vs MC)
    # ==========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"]      = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"]  = True
    
    num_data = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t}_{SR} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t}_{SR} (Data)")
    
    num_mc = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    
    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)
    
    # Denominator
    hName = "InclusiveTT_SR_Denominator"
    hData_Den = histograms.Histo( den_data, "t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den   = histograms.Histo( den_mc,   "t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDen.setLuminosity(opts.intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])

    # Numerator
    hName = "InclusiveTT_SR_Numerator"
    hData_Num = histograms.Histo( num_data, "t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num   = histograms.Histo( num_mc,   "t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Num.setIsDataMC(isData=False, isMC=True)
    
    pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNum.setLuminosity(opts.intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])
    

    # =========================
    # Inclusive Efficiency
    # =========================
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Efficiency",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : None,
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 1.5, "xmax" : 600},
        "opts2"            : {"ymin": 0.6, "ymax": 1.5},
        "log"              : False,
        "createLegend"     : {"x1": 0.64, "y1": 0.80, "x2": 0.95, "y2": 0.92},
        }
    _kwargs["cutBoxY"] = {"cutValue": 1.10, "fillColor": ROOT.kGray+1, "fillStyle": 3001, "box": False, "line": True, "greaterThan": True, "mainCanvas": False, "ratioCanvas": True, "mirror": True}

    bins  = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1

    # Data 
    h0_data_den = rhDict_den_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t}_{SR} (Data)")
    h0_data_num = rhDict_num_noSF["TTinData-SR-Inclusive"].Clone("t#bar{t}_{SR} (Data)")
    
    # MC
    h0_mc_den = rhDict_den_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    h0_mc_num = rhDict_num_noSF["TT-SR-Inclusive"].Clone("t#bar{t}_{SR} (MC)")
    
    h0_data_den = h0_data_den.Rebin(nx, "", xBins)
    h0_data_num = h0_data_num.Rebin(nx, "", xBins)
    
    h0_mc_den = h0_mc_den.Rebin(nx, "", xBins)
    h0_mc_num = h0_mc_num.Rebin(nx, "", xBins)
    
    hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den)
    hNumerator_MC,   hDenominator_MC   = GetHistosForEfficiency(h0_mc_num, h0_mc_den)
    
    eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data)
    eff_mc   = ROOT.TEfficiency(hNumerator_MC,   hDenominator_MC)

    eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geff_data = convert2TGraph(eff_data)
    geff_mc   = convert2TGraph(eff_mc)

    styles.dataStyle.apply(geff_data)
    styles.ttStyle.apply(geff_mc)

    Graph_Data = histograms.HistoGraph(geff_data, "t#bar{t}_{SR} (Data) ", "p", "P")
    Graph_MC   = histograms.HistoGraph(geff_mc, "t#bar{t}_{SR} (MC)", "p", "P")
    
    p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_InclusiveTT_SR"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    
    # Save results in JSON
    if (opts.inclusiveEff):
        name = opts.noSFcrab.split("_")[-4]
        name = name.replace(opts.analysisName, "")
        print "name = ", name
        jsonName = "toptagEff_BDT"+name+"_InclusiveTT_TopMassCut400.json"
        runRange = "273150-284044"
        analysis = opts.analysisName
        label = "2016"
        plotDir =  os.path.join(opts.folder, jsonName)
        pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geff_data)
        pythonWriter.addMCParameters(label, geff_mc)
        fileName_json = jsonName
        pythonWriter.writeJSON(fileName_json)
        
    
    
    # ==========================================================================================
    # (D) Estimate Genuine TT in SR
    # ==========================================================================================
    
    # (D1) Genuine TT in Data - Denominator = Data - F1*QCD - F2*FakeTT - EWK - ST
    rhDict_den_noSF["TTinData-SR-Genuine"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") 
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormTT-SR-Fake"],         -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["EWK-SR-Inclusive"],       -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)

    # (D2) Genuine TT in Data - Numerator = Data - [F1*QCD - F2*FakeTT - ST - EWK] * SF
    rhDict_num_noSF["TTinData-SR-Genuine"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withSF["NormTT-SR-Fake"],         -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withSF["SingleTop-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withSF["EWK-SR-Inclusive"],       -1)
    
    # ========================================================================================
    # (E) Plot Numerator and Denominator (Data Vs MC)
    # ========================================================================================
    _kwargs = GetHistoKwargs(num_histoList[0])
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"]      = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"]  = True
    
    num_data.Reset()
    den_data.Reset()
    num_mc.Reset()
    den_mc.Reset()
    
    num_data = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    
    num_mc = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    
    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)               

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)
    
    # Denominator
    hName = "GenuineTT_SR_Denominator"
    hData_Den = histograms.Histo( den_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den   = histograms.Histo( den_mc,   "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDenumerator = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDenumerator.setLuminosity(opts.intLumi)
    pDenumerator.setDefaultStyles()
    plots.drawPlot(pDenumerator, hName, **_kwargs)
    SavePlot(pDenumerator, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])
    
    # Numerator
    hName = "GenuineTT_SR_Numerator"
    hData_Num = histograms.Histo( num_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num   = histograms.Histo( num_mc,   "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Num.setIsDataMC(isData=False, isMC=True)

    pNumerator = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNumerator.setLuminosity(opts.intLumi)
    pNumerator.setDefaultStyles()
    plots.drawPlot(pNumerator, hName, **_kwargs)
    SavePlot(pNumerator, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])
    
    # ========================================================================================
    # (F) Plot Genuine TT Efficiency
    # ========================================================================================
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Efficiency",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : None, #"errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 1.25, "xmax" : 600},
        "opts2"            : {"ymin": 0.6, "ymax": 1.5},
        "log"              : False,
        "createLegend"     : {"x1": 0.54, "y1": 0.80, "x2": 0.95, "y2": 0.92},
        }
    _kwargs["cutBoxY"] = {"cutValue": 1.10, "fillColor": ROOT.kGray+1, "fillStyle": 3001, "box": False, "line": True, "greaterThan": True, "mainCanvas": False, "ratioCanvas": True, "mirror": True}
    
    bins  = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1
    
    # Data 
    h1_data_den = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    h1_data_num = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    
    # MC
    h1_mc_den = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    h1_mc_num = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    
    h1_data_den = h1_data_den.Rebin(nx, "", xBins)
    h1_data_num = h1_data_num.Rebin(nx, "", xBins)
    
    h1_mc_den = h1_mc_den.Rebin(nx, "", xBins)
    h1_mc_num = h1_mc_num.Rebin(nx, "", xBins)
    
    h_Numerator_Data, h_Denominator_Data = GetHistosForEfficiency(h1_data_num, h1_data_den)
    h_Numerator_MC,   h_Denominator_MC   = GetHistosForEfficiency(h1_mc_num, h1_mc_den)
    
    effi_data = ROOT.TEfficiency(h_Numerator_Data, h_Denominator_Data)
    effi_mc   = ROOT.TEfficiency(h_Numerator_MC,   h_Denominator_MC)

    effi_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    effi_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geffi_data = convert2TGraph(effi_data)
    geffi_mc   = convert2TGraph(effi_mc)

    styles.dataStyle.apply(geffi_data)
    styles.ttStyle.apply(geffi_mc)
    
    Graph_Data = histograms.HistoGraph(geffi_data, "genuine t#bar{t}_{SR} (Data) ", "p", "P")
    Graph_MC   = histograms.HistoGraph(geffi_mc, "genuine t#bar{t}_{SR} (MC)", "p", "P")
    
    pp = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_GenuineTT_SR"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(pp, savePath, **_kwargs)
    SavePlot(pp, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    
    # Save results in JSON
    if (not opts.inclusiveEff):
        name = opts.noSFcrab.split("_")[-4]
        name = name.replace(opts.analysisName, "")
        jsonName = "toptagEff_BDT"+name+"_GenuineTT_TopMassCut400.json"
        runRange = "273150-284044"
        analysis = opts.analysisName
        label = "2016"
        plotDir =  os.path.join(opts.folder, jsonName)
        pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi, geffi_data)
        pythonWriter.addMCParameters(label, geffi_mc)
        fileName_json = jsonName
        pythonWriter.writeJSON(fileName_json)


    return
def PlotHistograms(datasetsMgr, histoName):

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

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

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

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

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

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

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

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

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

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

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir), [".png", ".pdf"])
    return
def PlotComparison(datasetsMgr1, datasetsMgr2, datasetsMgr3, hBaseline,
                   hInverted, ext):

    # Create corresponding paths for GenuineB and FakeB histograms (not only Inclusive)
    hBaseline_Inclusive = hBaseline  #no extra string
    hInverted_Inclusive = hInverted  #no extra string
    hBaseline_GenuineB = hBaseline_Inclusive.replace(
        opts.folder, opts.folder + "EWKGenuineB")
    hInverted_GenuineB = hInverted_Inclusive.replace(
        opts.folder, opts.folder + "EWKGenuineB")
    hBaseline_FakeB = hBaseline_Inclusive.replace(opts.folder,
                                                  opts.folder + "EWKFakeB")
    hInverted_FakeB = hInverted_Inclusive.replace(opts.folder,
                                                  opts.folder + "EWKFakeB")

    # Create the histograms in the Baseline (SR) and Inverted (CR) regions
    pBaseline_Inclusive1 = plots.DataMCPlot(datasetsMgr1, hBaseline_Inclusive)
    pBaseline_GenuineB1 = plots.DataMCPlot(datasetsMgr1, hBaseline_GenuineB)
    pBaseline_FakeB1 = plots.DataMCPlot(datasetsMgr1, hBaseline_FakeB)
    pInverted_Inclusive1 = plots.DataMCPlot(datasetsMgr1, hInverted_Inclusive)
    pInverted_GenuineB1 = plots.DataMCPlot(datasetsMgr1, hInverted_GenuineB)
    pInverted_FakeB1 = plots.DataMCPlot(datasetsMgr1, hInverted_FakeB)

    pBaseline_Inclusive2 = plots.DataMCPlot(datasetsMgr2, hBaseline_Inclusive)
    pBaseline_GenuineB2 = plots.DataMCPlot(datasetsMgr2, hBaseline_GenuineB)
    pBaseline_FakeB2 = plots.DataMCPlot(datasetsMgr2, hBaseline_FakeB)
    pInverted_Inclusive2 = plots.DataMCPlot(datasetsMgr2, hInverted_Inclusive)
    pInverted_GenuineB2 = plots.DataMCPlot(datasetsMgr2, hInverted_GenuineB)
    pInverted_FakeB2 = plots.DataMCPlot(datasetsMgr2, hInverted_FakeB)

    pBaseline_Inclusive3 = plots.DataMCPlot(datasetsMgr3, hBaseline_Inclusive)
    pBaseline_GenuineB3 = plots.DataMCPlot(datasetsMgr3, hBaseline_GenuineB)
    pBaseline_FakeB3 = plots.DataMCPlot(datasetsMgr3, hBaseline_FakeB)
    pInverted_Inclusive3 = plots.DataMCPlot(datasetsMgr3, hInverted_Inclusive)
    pInverted_GenuineB3 = plots.DataMCPlot(datasetsMgr3, hInverted_GenuineB)
    pInverted_FakeB3 = plots.DataMCPlot(datasetsMgr3, hInverted_FakeB)

    # Extract the correct SR and CR histograms
    baseline_Data1 = pBaseline_Inclusive1.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Baseline-Data1")
    baseline_EWKGenuineB1 = pBaseline_GenuineB1.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKGenuineB1")
    baseline_EWKFakeB1 = pBaseline_FakeB1.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKFakeB1")
    inverted_Data1 = pInverted_Inclusive1.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Inverted-Data1")
    inverted_EWKGenuineB1 = pInverted_GenuineB1.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKGenuineB1")
    inverted_EWKFakeB1 = pInverted_FakeB1.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKFakeB1")

    baseline_Data2 = pBaseline_Inclusive2.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Baseline-Data2")
    baseline_EWKGenuineB2 = pBaseline_GenuineB2.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKGenuineB2")
    baseline_EWKFakeB2 = pBaseline_FakeB2.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKFakeB2")
    inverted_Data2 = pInverted_Inclusive2.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Inverted-Data2")
    inverted_EWKGenuineB2 = pInverted_GenuineB2.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKGenuineB2")
    inverted_EWKFakeB2 = pInverted_FakeB2.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKFakeB2")

    baseline_Data3 = pBaseline_Inclusive3.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Baseline-Data3")
    baseline_EWKGenuineB3 = pBaseline_GenuineB3.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKGenuineB3")
    baseline_EWKFakeB3 = pBaseline_FakeB3.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKFakeB3")
    inverted_Data3 = pInverted_Inclusive3.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Inverted-Data3")
    inverted_EWKGenuineB3 = pInverted_GenuineB3.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKGenuineB3")
    inverted_EWKFakeB3 = pInverted_FakeB3.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKFakeB3")

    # FakeB = Data -EWKGenuineB
    baseline_FakeB1 = baseline_Data1.Clone("Baseline-FakeB1")
    inverted_FakeB1 = inverted_Data1.Clone("Inverted-FakeB1")

    baseline_FakeB2 = baseline_Data2.Clone("Baseline-FakeB2")
    inverted_FakeB2 = inverted_Data2.Clone("Inverted-FakeB2")

    baseline_FakeB3 = baseline_Data3.Clone("Baseline-FakeB3")
    inverted_FakeB3 = inverted_Data3.Clone("Inverted-FakeB3")

    # Subtract the EWK GenuineB
    baseline_FakeB1.Add(baseline_EWKGenuineB1, -1)
    inverted_FakeB1.Add(inverted_EWKGenuineB1, -1)

    baseline_FakeB2.Add(baseline_EWKGenuineB2, -1)
    inverted_FakeB2.Add(inverted_EWKGenuineB2, -1)

    baseline_FakeB3.Add(baseline_EWKGenuineB3, -1)
    inverted_FakeB3.Add(inverted_EWKGenuineB3, -1)

    # Normalize histograms to unit area
    if opts.normaliseToOne:
        baseline_FakeB1.Scale(1.0 / baseline_FakeB1.Integral())
        inverted_FakeB1.Scale(1.0 / inverted_FakeB1.Integral())

        baseline_FakeB2.Scale(1.0 / baseline_FakeB2.Integral())
        inverted_FakeB2.Scale(1.0 / inverted_FakeB2.Integral())

        baseline_FakeB3.Scale(1.0 / baseline_FakeB3.Integral())
        inverted_FakeB3.Scale(1.0 / inverted_FakeB3.Integral())

    # Create the final plot object
    if ext == "CR1" or ext == "SR":
        p = plots.ComparisonManyPlot(baseline_FakeB1,
                                     [baseline_FakeB2, baseline_FakeB3],
                                     saveFormats=[])
    elif ext == "CR2" or ext == "VR":
        p = plots.ComparisonManyPlot(inverted_FakeB1,
                                     [inverted_FakeB2, inverted_FakeB3],
                                     saveFormats=[])
    else:
        raise Exception("Unexpected extension %s" % (ext))
    p.setLuminosity(opts.intLumi)

    # Get the BDT cut values from the multicrab name
    BDT1 = find_between(opts.mcrab1, "MVAm1p00to", "_").replace("p", ".")
    BDT2 = find_between(opts.mcrab2, "MVAm1p00to", "_").replace("p", ".")
    BDT3 = find_between(opts.mcrab3, "MVAm1p00to", "_").replace("p", ".")

    # Apply histogram styles
    if ext == "CR1" or ext == "SR":
        p.histoMgr.forHisto("Baseline-FakeB1", styles.getFakeBLineStyle()
                            )  # getABCDStyle("SR") , getABCDStyle("VR")
        p.histoMgr.forHisto("Baseline-FakeB2", styles.genuineBAltStyle)
        p.histoMgr.forHisto("Baseline-FakeB3", styles.getABCDStyle("SR"))

        # Set drawing style
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB1", "HIST")
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB2", "AP")
        p.histoMgr.setHistoDrawStyle("Baseline-FakeB3", "AP")

        # Set legend styles
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB1", "L")
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB2", "LP")
        p.histoMgr.setHistoLegendStyle("Baseline-FakeB3", "LP")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            "Baseline-FakeB1":
            "%s (BDT < %s)" % (ext, BDT1),
            "Baseline-FakeB2":
            "%s (BDT < %s)" % (ext, BDT2),
            "Baseline-FakeB3":
            "%s (BDT < %s)" % (ext, BDT3),
        })
    else:
        p.histoMgr.forHisto("Inverted-FakeB1", styles.getFakeBLineStyle())
        p.histoMgr.forHisto("Inverted-FakeB2", styles.genuineBAltStyle)
        p.histoMgr.forHisto("Inverted-FakeB3", styles.getABCDStyle("SR"))
        # Set drawing styles
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB1", "HIST")
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB2", "AP")
        p.histoMgr.setHistoDrawStyle("Inverted-FakeB3", "AP")

        # Set legend styles
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB1", "L")
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB2", "LP")
        p.histoMgr.setHistoLegendStyle("Inverted-FakeB3", "LP")
        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
            "Inverted-FakeB1":
            "%s (BDT < %s)" % (ext, BDT1),
            "Inverted-FakeB2":
            "%s (BDT < %s)" % (ext, BDT2),
            "Inverted-FakeB3":
            "%s (BDT < %s)" % (ext, BDT3),
        })

    # Get histogram keyword arguments
    kwargs_ = GetHistoKwargs(hBaseline_Inclusive, ext, opts)

    # Draw the histograms
    plots.drawPlot(p, hBaseline_Inclusive, **kwargs_)  #iro

    # Save plot in all formats
    saveName = hBaseline_Inclusive.split("/")[-1]
    saveName = saveName.replace("Baseline_", "")
    saveName = saveName.replace("Inverted_", "")
    saveName = saveName.replace("_AfterAllSelections", "_" + ext)
    saveName = saveName.replace("_AfterCRSelections", "_" + ext)
    savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath, saveFormats=[".png", ".pdf"])
    return
Beispiel #18
0
def PlotComparison(datasetsMgr, hBaseline, hInverted, ext):

    # Create corresponding paths for GenuineB and FakeB histograms (not only Inclusive)
    hBaseline_Inclusive = hBaseline  #no extra string
    hInverted_Inclusive = hInverted  #no extra string
    hBaseline_GenuineB = hBaseline_Inclusive.replace(
        opts.folder, opts.folder + "EWKGenuineB")
    hInverted_GenuineB = hInverted_Inclusive.replace(
        opts.folder, opts.folder + "EWKGenuineB")
    hBaseline_FakeB = hBaseline_Inclusive.replace(opts.folder,
                                                  opts.folder + "EWKFakeB")
    hInverted_FakeB = hInverted_Inclusive.replace(opts.folder,
                                                  opts.folder + "EWKFakeB")

    # Create the histograms in the Baseline (SR) and Inverted (CR) regions
    pBaseline_Inclusive = plots.DataMCPlot(datasetsMgr, hBaseline_Inclusive)
    pBaseline_GenuineB = plots.DataMCPlot(datasetsMgr, hBaseline_GenuineB)
    pBaseline_FakeB = plots.DataMCPlot(datasetsMgr, hBaseline_FakeB)
    pInverted_Inclusive = plots.DataMCPlot(datasetsMgr, hInverted_Inclusive)
    pInverted_GenuineB = plots.DataMCPlot(datasetsMgr, hInverted_GenuineB)
    pInverted_FakeB = plots.DataMCPlot(datasetsMgr, hInverted_FakeB)

    # Extract the correct SR and CR histograms
    baseline_Data = pBaseline_Inclusive.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Baseline-Data")
    if opts.useMC:
        baseline_QCD = pBaseline_Inclusive.histoMgr.getHisto(
            "QCD").getRootHisto().Clone("Baseline-QCD")
    baseline_EWKGenuineB = pBaseline_GenuineB.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKGenuineB")
    baseline_EWKFakeB = pBaseline_FakeB.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Baseline-EWKFakeB")
    inverted_Data = pInverted_Inclusive.histoMgr.getHisto(
        "Data").getRootHisto().Clone("Inverted-Data")
    if opts.useMC:
        inverted_QCD = pInverted_Inclusive.histoMgr.getHisto(
            "QCD").getRootHisto().Clone("Inverted-QCD")
    inverted_EWKGenuineB = pInverted_GenuineB.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKGenuineB")
    inverted_EWKFakeB = pInverted_FakeB.histoMgr.getHisto(
        "EWK").getRootHisto().Clone("Inverted-EWKFakeB")

    # Subtract EWKGenuineB from Data to get FakeB (= QCD_inclusive + EWK_genuineB)
    if opts.useMC:
        # FakeB = QCD + EWKFakeB
        baseline_FakeB = baseline_QCD.Clone("Baseline-FakeB")
        inverted_FakeB = inverted_QCD.Clone("Inverted-FakeB")

        # Add the EWKFakeB
        baseline_FakeB.Add(baseline_EWKFakeB, +1)
        inverted_FakeB.Add(inverted_EWKFakeB, +1)
    else:
        # FakeB = Data -EWKGenuineB
        baseline_FakeB = baseline_Data.Clone("Baseline-FakeB")
        inverted_FakeB = inverted_Data.Clone("Inverted-FakeB")

        # Subtract the EWK GenuineB
        baseline_FakeB.Add(baseline_EWKGenuineB, -1)
        inverted_FakeB.Add(inverted_EWKGenuineB, -1)

    # Normalize histograms to unit area
    if opts.normaliseToOne:
        baseline_FakeB.Scale(1.0 / baseline_FakeB.Integral())
        inverted_FakeB.Scale(1.0 / inverted_FakeB.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(baseline_FakeB, [inverted_FakeB],
                                 saveFormats=[])
    #p = plots.ComparisonPlot(baseline_FakeB, inverted_FakeB, saveFormats=[]) #also works!
    p.setLuminosity(opts.intLumi)

    # Apply histogram styles
    p.histoMgr.forHisto("Baseline-FakeB",
                        styles.getABCDStyle(ext.split("v")[0]))
    p.histoMgr.forHisto("Inverted-FakeB",
                        styles.getABCDStyle(ext.split("v")[1]))

    # Set draw/legend style
    p.histoMgr.setHistoDrawStyle("Baseline-FakeB", "AP")
    p.histoMgr.setHistoDrawStyle("Inverted-FakeB", "HIST")
    p.histoMgr.setHistoLegendStyle("Baseline-FakeB", "LP")
    p.histoMgr.setHistoLegendStyle("Inverted-FakeB", "F")

    # Set legend labels
    if opts.useMC:
        p.histoMgr.setHistoLegendLabelMany({
            #"Baseline-FakeB" : "Fake-B (Baseline)",
            #"Inverted-FakeB" : "Fake-B (Inverted)",
            "Baseline-FakeB": "Baseline (MC)",
            "Inverted-FakeB": "Inverted (MC)",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            #"Baseline-FakeB" : "Baseline",
            #"Inverted-FakeB" : "Inverted",
            "Baseline-FakeB": ext.split("v")[0],
            "Inverted-FakeB": ext.split("v")[1],
        })

    # Get histogram keyword arguments
    kwargs_ = GetHistoKwargs(hBaseline_Inclusive, ext, opts)

    # Draw the histograms
    plots.drawPlot(p, hBaseline_Inclusive, **kwargs_)

    # Save plot in all formats
    saveName = hBaseline_Inclusive.split("/")[-1]
    saveName = saveName.replace("Baseline_", "")
    saveName = saveName.replace("Inverted_", "")
    saveName = saveName.replace("_AfterAllSelections", "_" + ext)
    saveName = saveName.replace("_AfterCRSelections", "_" + ext)

    if opts.useMC:
        savePath = os.path.join(opts.saveDir, "MC", opts.optMode)
    else:
        savePath = os.path.join(opts.saveDir, opts.optMode)
    SavePlot(p, saveName, savePath, saveFormats=[".png", ".pdf"])
    return
Beispiel #19
0
def PlotHistograms(datasetsMgr, histoList, binLabels, opts):
    '''
    histoList contains all histograms for all bins for CR1 and CR2 
    
    '''
    # Get the root histos for all datasets and Control Regions (CRs)
    rhDict = GetRootHistos(datasetsMgr, histoList)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Get the histogram customisations (keyword arguments)
        p.appendPlotObject(
            histograms.PlotText(0.20,
                                0.88,
                                GetBinText(bin),
                                bold=True,
                                size=22))
        plots.drawPlot(p, saveName, **GetHistoKwargs(saveName))
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, opts.optMode),
                 saveFormats=[".png"])  #, ".pdf"])
    return
Beispiel #20
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
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.619886; f2=0.904877;
    
    # =========================================================================================
    # (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) Estimate Genuine TT in SR
    # ==========================================================================================
            
    # (B1) Genuine TT in Data - Denominator = Data - F1*QCD - F2*FakeTT - EWK - ST
    rhDict_den_noSF["TTinData-SR-Genuine"] = rhDict_den_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)") 
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormQCD-SR-Inclusive"],   -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["NormTT-SR-Fake"],         -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["EWK-SR-Inclusive"],       -1)
    rhDict_den_noSF["TTinData-SR-Genuine"].Add(rhDict_den_noSF["SingleTop-SR-Inclusive"], -1)

    # (B2) Genuine TT in Data - Numerator = Data - F1*QCD*SF_{CR2} - F2*FakeTT*SF_{CR1} - ST*SF_{CR2} - EWK*SF_{CR2}
    rhDict_num_noSF["TTinData-SR-Genuine"] = rhDict_num_noSF["Data-SR-Inclusive"].Clone("genuine t#bar{t} (Data)")
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["NormQCD-SR-Inclusive"],   -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR1SF["NormTT-SR-Fake"],         -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["SingleTop-SR-Inclusive"], -1)
    rhDict_num_noSF["TTinData-SR-Genuine"].Add(rhDict_num_withCR2SF["EWK-SR-Inclusive"],       -1)
    
    # (B3) Genuine TT in MC - Denominator:  rhDict_den_noSF["TT-SR-Genuine"]
    # (B4) Genuine TT in MC - Numerator:    rhDict_num_noSF["TT-SR-Genuine"]
    
    # ========================================================================================
    # (C) Plot Numerator and Denominator (Data Vs MC)
    # ========================================================================================
    _kwargs["opts"] = {"xmax" : 800, "ymaxfactor" : 2.0}
    _kwargs["ratioYlabel"]  = "Data/MC"
    _kwargs["ratio"]        = True
    _kwargs["stackMCHistograms"] = False
    _kwargs["createLegend"]      = {"x1": 0.60, "y1": 0.75, "x2": 0.95, "y2": 0.92}
    _kwargs["ratioInvert"]  = True

    num_data = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    den_data = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    
    num_mc = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    den_mc = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    
    num_data.Rebin(2)
    num_mc.Rebin(2)
    den_data.Rebin(2)
    den_mc.Rebin(2)               

    styles.getABCDStyle("CR4").apply(num_mc)
    styles.getABCDStyle("CR4").apply(den_mc)
    
    # Denominator
    hName = "GenuineTT_SR_Denominator_LeadingJet"
    hData_Den = histograms.Histo( den_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Den.setIsDataMC(isData=True, isMC=False)
    hMC_Den   = histograms.Histo( den_mc,   "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Den.setIsDataMC(isData=False, isMC=True)

    pDen = plots.ComparisonManyPlot(hData_Den, [hMC_Den], saveFormats=[])
    pDen.setLuminosity(opts.intLumi)
    pDen.setDefaultStyles()
    plots.drawPlot(pDen, hName, **_kwargs)
    SavePlot(pDen, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])
    
    # Numerator
    hName = "GenuineTT_SR_Numerator_LeadingJet"
    hData_Num = histograms.Histo( num_data, "genuine t#bar{t}_{SR} (Data)", "Data", drawStyle="AP"); hData_Num.setIsDataMC(isData=True, isMC=False)
    hMC_Num   = histograms.Histo( num_mc,   "genuine t#bar{t}_{SR} (MC)", "MC", drawStyle="HIST");   hMC_Num.setIsDataMC(isData=False, isMC=True)

    pNum = plots.ComparisonManyPlot(hData_Num, [hMC_Num], saveFormats=[])
    pNum.setLuminosity(opts.intLumi)
    pNum.setDefaultStyles()
    plots.drawPlot(pNum, hName, **_kwargs)
    SavePlot(pNum, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])
    
    # ========================================================================================
    # (D) Plot Genuine TT Efficiency
    # ========================================================================================
    _kwargs = {
        "xlabel"           : "p_{T} (GeV/c)",
        "ylabel"           : "Efficiency",
        "ratioYlabel"      : "Data/MC",
        "ratio"            : True,
        "ratioInvert"      : False,
        "ratioType"        : "errorScale",
        "ratioCreateLegend": True,
        "ratioMoveLegend"  : {"dx": -0.51, "dy": 0.03, "dh": -0.08},
        "ratioErrorOptions": {"numeratorStatSyst": False, "denominatorStatSyst": False},
        "errorBarsX"       : True,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"ymin": 0.0, "ymaxfactor": 1.2, "xmax" : 600},
        "opts2"            : {"ymin": 0.6, "ymax": 1.5},
        "log"              : False,
        "createLegend"     : {"x1": 0.54, "y1": 0.80, "x2": 0.95, "y2": 0.92},
        }

    bins  = [0, 100, 200, 300, 400, 500, 600]
    xBins = array.array('d', bins)
    nx    = len(xBins)-1

    # Data 
    h0_data_den = rhDict_den_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    h0_data_num = rhDict_num_noSF["TTinData-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (Data)")
    
    # MC
    h0_mc_den = rhDict_den_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    h0_mc_num = rhDict_num_noSF["TT-SR-Genuine"].Clone("genuine t#bar{t}_{SR} (MC)")
    
    h0_data_den = h0_data_den.Rebin(nx, "", xBins)
    h0_data_num = h0_data_num.Rebin(nx, "", xBins)
    
    h0_mc_den = h0_mc_den.Rebin(nx, "", xBins)
    h0_mc_num = h0_mc_num.Rebin(nx, "", xBins)
    
    hNumerator_Data, hDenominator_Data = GetHistosForEfficiency(h0_data_num, h0_data_den)
    hNumerator_MC,   hDenominator_MC   = GetHistosForEfficiency(h0_mc_num, h0_mc_den)
    
    eff_data = ROOT.TEfficiency(hNumerator_Data, hDenominator_Data)
    eff_mc   = ROOT.TEfficiency(hNumerator_MC,   hDenominator_MC)

    eff_data.SetStatisticOption(ROOT.TEfficiency.kFCP)
    eff_mc.SetStatisticOption(ROOT.TEfficiency.kFCP)

    geff_data = convert2TGraph(eff_data)
    geff_mc   = convert2TGraph(eff_mc)

    styles.dataStyle.apply(geff_data)
    styles.ttStyle.apply(geff_mc)

    Graph_Data = histograms.HistoGraph(geff_data, "genuine t#bar{t}_{SR} (Data) ", "p", "P")
    Graph_MC   = histograms.HistoGraph(geff_mc, "genuine t#bar{t}_{SR} (MC)", "p", "P")
    
    p = plots.ComparisonManyPlot(Graph_MC, [Graph_Data], saveFormats=[])
    saveName = "Efficiency_GenuineTT_SR_LeadingJet"
    savePath = os.path.join(opts.saveDir, opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"])


    return
def PlotHistograms(datasetsMgr, histoList, binLabels, opts):

    '''
    histoList contains all histograms for all bins for CR1 and CR2 
    
    '''
    # Get the root histos for all datasets and Control Regions (CRs)
    rhDict  = GetRootHistos(datasetsMgr, histoList)

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

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

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

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

            rFakeB_VR = rhDict[key3].Clone()
            rFakeB_VR.Reset("ICES")
            
            rFakeB_SR = rhDict[key4].Clone()
            rFakeB_SR.Reset("ICES")

            # For-loop: All fakeB bins (to add-up all binned histos)
            for i, b in enumerate(binLabels, 1):
                if "Inclusive" in b:
                    Verbose("Skipping bin-label %s" % (b), False)
                    continue
                else:
                    Verbose("Adding bin %s" % (b), False)
    
                # Determine keys
                k1 = key1.replace("Inclusive", b)
                k2 = key2.replace("Inclusive", b)
                k3 = key3.replace("Inclusive", b)
                k4 = key4.replace("Inclusive", b)

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

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

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

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

        # Apply histogram styles          
        doAllRegions = False #iro
        styles.getABCDStyle("CRone").apply(rFakeB_CRone)
        styles.getABCDStyle("CRtwo").apply(rFakeB_CRtwo)
        if doAllRegions:
            styles.getABCDStyle("VR").apply(rFakeB_VR)
            styles.getABCDStyle("SR").apply(rFakeB_SR)
        
        # Create the plot
        if doAllRegions:
            p = plots.ComparisonManyPlot(rFakeB_CRone, [rFakeB_VR, rFakeB_SR, rFakeB_CRtwo], saveFormats=[]) 
        else:
            p = plots.ComparisonManyPlot(rFakeB_CRone, [rFakeB_CRtwo], saveFormats=[])
        p.setLuminosity(opts.intLumi)
    
        # Set draw/legend style
        p.histoMgr.setHistoDrawStyle(hName1, "AP")
        p.histoMgr.setHistoLegendStyle(hName1, "LP")
        p.histoMgr.setHistoDrawStyle(hName2, "HIST")
        p.histoMgr.setHistoLegendStyle(hName2, "F")
        if doAllRegions:
            p.histoMgr.setHistoDrawStyle(hName3, "AP")
            p.histoMgr.setHistoLegendStyle(hName3, "LP")
            p.histoMgr.setHistoDrawStyle(hName4, "AP")
            p.histoMgr.setHistoLegendStyle(hName4, "LP")
        
        # Set legend labels
        if doAllRegions:
            p.histoMgr.setHistoLegendLabelMany({
                    hName1 : "CR1",
                    hName2 : "CR2",
                    hName3 : "VR",
                    hName4 : "SR",
                    })
        else:
            p.histoMgr.setHistoLegendLabelMany({
                    hName1 : "CR1",
                    hName2 : "CR2",
                    })

        # Draw the plot and save it
        if bin == "Inclusive":
            histoName = histoList[0] + "_CR1vCR2_combined"
        else:
            histoName = histoList[0] + "_CR1vCR2_bin%s" % (bin)
        saveName = histoName.split("/")[-1].replace("CRone0_", "").replace("CRtwo0_", "")
        
        # Get the histogram customisations (keyword arguments)
        p.appendPlotObject(histograms.PlotText(0.20, 0.88, GetBinText(bin), bold=True, size=22))
        plots.drawPlot(p, saveName, **GetHistoKwargs(saveName))
        SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png"])#, ".pdf"])
    return