Example #1
0
def main():

    if len(sys.argv) < 2:
        usage()

    paths = [sys.argv[1]]
    analysis = "Hplus2tbAnalysis"
    hName = "associatedTPt"
    plotname = analysis + "_" + hName

    datasetsHiggs = dataset.getDatasetsFromMulticrabDirs(
        paths,
        analysisName=analysis,
        includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTauB_M_")
    datasetsTT = dataset.getDatasetsFromMulticrabDirs(paths,
                                                      analysisName=analysis,
                                                      includeOnlyTasks="TT")
    datasetsTT.merge("MC", ["TT", "TT_ext"], keepSources=True)

    style = tdrstyle.TDRStyle()

    dataset1 = datasetsHiggs.getDataset(
        "ChargedHiggs_HplusTB_HplusToTauB_M_200").getDatasetRootHisto(hName)
    dataset2 = datasetsTT.getDataset("MC").getDatasetRootHisto(hName)
    #    dataset1.normalizeToOne()
    dataset2.normalizeToOne()

    histo1 = dataset1.getHistogram()
    histo1.SetMarkerColor(2)
    histo1.SetMarkerStyle(20)
    removeNegatives(histo1)
    histo1.Scale(1. / histo1.Integral())

    histo2 = dataset2.getHistogram()
    histo2.SetMarkerColor(4)
    histo2.SetMarkerStyle(21)

    p = plots.ComparisonPlot(
        histograms.Histo(histo1, "m_{H^{#pm}} = 200 GeV/c^{2}", "p", "P"),
        histograms.Histo(histo2, "t#bar{t}", "p", "P"))

    opts = {"ymin": 0, "ymax": 0.2}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    p.createFrame(os.path.join(plotDir, plotname),
                  createRatio=True,
                  opts=opts,
                  opts2=opts2)

    moveLegend = {"dx": -0.2, "dy": -0.1, "dh": -0.1}
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("Arbitrary units")
    p.getFrame().GetXaxis().SetTitle("Top p_{T} (GeV/c)")
    p.getFrame2().GetYaxis().SetTitle("Ratio")
    p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    p.draw()
    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    def doSystematicsPlots(self):
        if self._mySystObject == None:
            return
        # Make sure results have been obtained
        if self._hSystematicsUp == None:
            self.doSystematicsForMetShapeDifference()
        # Create output directory
        if os.path.exists("%s/Systematics_%s"%(self._myDir, self._systName)):
            shutils.rmtree("%s/Systematics_%s"%(self._myDir, self._systName))
        os.mkdir("%s/Systematics_%s"%(self._myDir, self._systName))
        # Make plot for systematics (phase-space bins integrated)
        if self._hFinalShape != None:
            self._hFinalShape.SetLineColor(ROOT.kBlack)
            self._hSystematicsUp.SetLineColor(ROOT.kBlue)
            self._hSystematicsDown.SetLineColor(ROOT.kRed)
            myYmax = 15
            if "2012" in self._moduleInfoString:
                myYmax = 30
            plot = plots.ComparisonManyPlot(histograms.Histo(self._hFinalShape, "Nominal", drawStyle="E"),
                [histograms.Histo(self._hSystematicsUp, "Up", drawStyle="E"), histograms.Histo(self._hSystematicsDown, "Down", drawStyle="E")])
            plot.createFrame("%s/Systematics_%s/QCDInvertedShapeWithMetSyst_final_%s"%(self._myDir, self._systName, self._moduleInfoString), createRatio=True, opts2={"ymin": 0, "ymax": 2}, opts={"addMCUncertainty": True, "ymin": -5, "ymax": myYmax})
            plot.frame.GetXaxis().SetTitle(self._histoSpecs["xtitle"])
            plot.frame.GetYaxis().SetTitle(self._histoSpecs["ytitle"])
            plot.setLegend(histograms.createLegend(0.59, 0.70, 0.87, 0.90))
            plot.legend.SetFillColor(0)
            plot.legend.SetFillStyle(1001)
            styles.mcStyle(plot.histoMgr.getHisto("Up"))
            #plot.histoMgr.getHisto("Up").getRootHisto().SetMarkerSize(0)
            styles.mcStyle2(plot.histoMgr.getHisto("Down"))
            styles.dataStyle(plot.histoMgr.getHisto("Nominal"))
            self._drawPlot(plot)

        # Make plots for systematics (for each phase-space bin separately)
        nSplitBins = self._myCtrlRegion.getNumberOfPhaseSpaceSplitBins()
        myCtrlHistograms = self._mySystObject.getHistogramsForCtrlRegion()
        mySignalHistograms = self._mySystObject.getHistogramsForSignalRegion()
        myMinIndex = 0
        if myCtrlHistograms[0] == None:
            myMinIndex = 1 # Skip empty first bin
        for i in range(myMinIndex, nSplitBins):
            plot = plots.ComparisonPlot(histograms.Histo(mySignalHistograms[i].Clone(), "Signal region", drawStyle="E"),
                                        histograms.Histo(myCtrlHistograms[i].Clone(), "Ctrl. region", drawStyle="E"))
            plot.createFrame("%s/Systematics_%s/QCDInvertedShapeWithMetSyst_%s_%s"%(self._myDir, self._systName, self._myCtrlRegion.getPhaseSpaceBinFileFriendlyTitle(i), self._moduleInfoString), createRatio=True, opts2={"ymin": 0, "ymax": 2}, opts={"addMCUncertainty": True, "ymin": -0.05, "ymax": 0.3})
            plot.frame.GetXaxis().SetTitle(self._histoSpecs["xtitle"])
            plot.frame.GetYaxis().SetTitle("Arb. units. (Normalised to 1)")
            styles.mcStyle(plot.histoMgr.getHisto("Ctrl. region"))
            styles.dataStyle(plot.histoMgr.getHisto("Signal region"))
            plot.setLegend(histograms.createLegend(0.59, 0.77, 0.87, 0.90))
            plot.legend.SetFillColor(0)
            plot.legend.SetFillStyle(1001)
            #plot.histoMgr.getHisto("Up").getRootHisto().SetMarkerSize(0)
            self._drawPlot(plot)
            print "Saved MET shape systematics plot for bin %s"%self._myCtrlRegion.getPhaseSpaceBinFileFriendlyTitle(i)
Example #3
0
def TauPtComparison(datasets):
    mt = plots.ComparisonPlot(*getHistos3(datasets, "tauPt", "tauPt"))

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

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


    mt.appendPlotObject(histograms.PlotText(100, 0.01, "tt events", size=20))
    xlabel = "PF E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f"
    plots.drawPlot(mt, "MetComparison", xlabel=xlabel, ylabel=ylabel, rebinX=2, log=True,
                   createLegend={"x1": 0.6, "y1": 0.75, "x2": 0.8, "y2": 0.9},
                   ratio=False, opts2={"ymin": 0.5, "ymax": 50}, opts={"xmax": 500})
def PurityPlots(datasetsMgr, histoName, analysisType="Inverted"):
    '''
    Create plots with "FakeB=Data-EWKGenuineB"
    '''
    Verbose("Plotting histogram %s for Data, EWK, QCD for %s" % (histoName, analysisType), True)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    # Which folder to use (redundant)
    defaultFolder  = "FakeBPurity" 
    genuineBFolder = defaultFolder + "EWKGenuineB"
    fakeBFolder    = defaultFolder + "EWKFakeB"

    # Get histos (Data, EWK) for Inclusive
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, analysisType) )
    p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Clone histograms 
    Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone(analysisType + "-Data")
    EWK  = p1.histoMgr.getHisto("EWK").getRootHisto().Clone(analysisType  + "-EWK")
    QCD= p1.histoMgr.getHisto("Data").getRootHisto().Clone(analysisType + "-QCD")

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

    # Comparison plot. The first argument is the reference histo. All other histograms are compared with respect to that. 
    QCD_Purity, xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto(QCD, Data, inclusiveBins=False, printValues=False)
    EWK_Purity  , xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto(EWK  , Data, inclusiveBins=False, printValues=False)

    # Create TGraphs
    if 0:
        gQCD_Purity = MakeGraph(ROOT.kFullTriangleUp, ROOT.kOrange, binList, valueDict, upDict, downDict)
        gEWK_Purity = MakeGraph(ROOT.kFullTriangleDown, ROOT.kPurple, binList, valueDict, upDict, downDict)
        
    # Make the plots
    p = plots.ComparisonManyPlot(QCD_Purity, [EWK_Purity], saveFormats=[])
    if 0:
        p = plots.PlotBase([gQCD_Purity, gEWK_Purity], saveFormats=[]) #legend/styles all wrog

    # Apply histo styles
    p.histoMgr.forHisto(analysisType + "-QCD", styles.getQCDLineStyle() )
    p.histoMgr.forHisto(analysisType + "-EWK"  , styles.getAltEWKLineStyle() )

    # Set draw style
    p.histoMgr.setHistoDrawStyle(analysisType + "-QCD", "P")
    p.histoMgr.setHistoDrawStyle(analysisType + "-EWK", "P")

    # Set legend style
    p.histoMgr.setHistoLegendStyle(analysisType + "-QCD", "P")
    p.histoMgr.setHistoLegendStyle(analysisType + "-EWK", "P")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            analysisType + "-QCD" : "QCD",
            analysisType + "-EWK" : "EWK",
            })
    
    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _opts   = {"ymin": 1e-3, "ymax": 1.0} #"ymaxfactor": 1.2}
    _format = "%0.0f"
    _opts["xmax"] = xMax
    _xlabel = None

    if "dijetm" in histoName.lower():
        _units  = "GeV/c^{2}" 
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {"cutValue": 80.399, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
    if "trijetm" in histoName.lower():
        _units  = "GeV/c^{2}" 
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 1000.0
    if "pt" in histoName.lower():
        _format = "%0.0f GeV/c" 
    if "eta" in histoName.lower():
        _format = "%0.2f" 
        _cutBox = {"cutValue": 0., "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in histoName.lower():
        _format = "%0.2f" 
        _opts["xmin"] =  0.0
        _opts["xmax"] = 6.0
    if "bdisc" in histoName.lower():
        _format = "%0.2f" 
    if "tetrajetm" in histoName.lower():
        _units  = "GeV/c^{2}" 
        _format = "%0.0f " + _units
        _xlabel = "m_{jjjb} (%s)" % (_units)
        _opts["xmax"] = 2500.0

    # Do the plot
    plots.drawPlot(p, 
                   histoName,  
                   xlabel        = _xlabel,
                   ylabel        = "Purity",
                   log           = False, 
                   cmsExtraText  = "Preliminary", 
                   createLegend  = {"x1": 0.80, "y1": 0.80, "x2": 0.92, "y2": 0.92},
                   opts          = _opts,
                   opts2         = {"ymin": 1e-5, "ymax": 1e0},
                   ratio         = False,
                   ratioInvert   = False, 
                   ratioYlabel   = "Ratio",
                   cutBox        = _cutBox,
                   )
    
    # Save plot in all formats
    SavePlot(p, histoName, os.path.join(opts.saveDir, "Purity", opts.optMode))#, saveFormats = [".png"] )
    return
Example #6
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
Example #7
0
def BaselineVsInvertedPlots(datasetsMgr, histoName):

    # Get the Inclusive (Data, EWK)
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, "Baseline"))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, "Inverted"))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get Baseline histos
    baseline_Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Baseline-Data")
    baseline_QCD = p1.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Baseline-QCD")
    baseline_EWK = p1.histoMgr.getHisto("EWK").getRootHisto().Clone(
        "Baseline-EWK")

    # Get Inverted histos
    inverted_Data = p2.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Inverted-Data")
    inverted_QCD = p2.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Inverted-QCD")
    inverted_EWK = p2.histoMgr.getHisto("EWK").getRootHisto().Clone(
        "Inverted-EWK")

    # Subtract EWK from Data to get QCD
    baseline_QCD.Add(baseline_EWK, -1)
    inverted_QCD.Add(inverted_EWK, -1)

    # Normalize histograms to unit area
    baseline_Data.Scale(1.0 / baseline_Data.Integral())
    baseline_QCD.Scale(1.0 / baseline_QCD.Integral())
    baseline_EWK.Scale(1.0 / baseline_EWK.Integral())
    inverted_Data.Scale(1.0 / inverted_Data.Integral())
    inverted_QCD.Scale(1.0 / inverted_QCD.Integral())
    inverted_EWK.Scale(1.0 / inverted_EWK.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(baseline_QCD, [inverted_QCD], saveFormats=[])
    #p.setLuminosity(GetLumi(datasetsMgr))

    # Apply styles
    p.histoMgr.forHisto("Baseline-QCD", styles.getBaselineStyle())
    p.histoMgr.forHisto("Inverted-QCD", styles.getInvertedStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Baseline-QCD", "AP")
    p.histoMgr.setHistoDrawStyle("Inverted-QCD", "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("Baseline-QCD", "LP")
    p.histoMgr.setHistoLegendStyle("Inverted-QCD", "F")
    # p.histoMgr.setHistoLegendStyleAll("LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        "Baseline-QCD": "QCD (Baseline)",
        "Inverted-QCD": "QCD (Inverted)",
    })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _opts = {"ymin": 1e-4, "ymaxfactor": 2.0}
    _format = "%0.0f"
    _xlabel = None

    if "dijetm" in histoName.lower():
        _rebinX = 2
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {
            "cutValue": 80.399,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 400.0
    if "trijetm" in histoName.lower():
        _rebinX = 5
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 1500.0
    if "pt" in histoName.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c"
    if "eta" in histoName.lower():
        _format = "%0.2f"
        _cutBox = {
            "cutValue": 0.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in histoName.lower():
        _format = "%0.2f"
        _opts["xmin"] = 0.0
        _opts["xmax"] = 6.0
    if "bdisc" in histoName.lower():
        _format = "%0.2f"
    if "tetrajetm" in histoName.lower():
        _rebinX = 10
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjjb} (%s)" % (_units)
        _opts["xmax"] = 3500.0

    plots.drawPlot(
        p,
        histoName,
        xlabel=_xlabel,
        ylabel="Arbitrary Units / %s" % (_format),
        log=True,
        rebinX=_rebinX,
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.62,
            "y1": 0.78,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        ratio=True,
        ratioInvert=False,
        ratioYlabel="Ratio",
        cutBox=_cutBox,
    )

    # Save plot in all formats
    SavePlot(p, histoName.replace("<Analysis>_", ""),
             os.path.join(opts.saveDir, "BaselineVsInverted", opts.optMode))
    return
Example #8
0
def Plot_Comparisons(datasetsMgr, datasetsMgrRef, hT, hR, intLumi):
    #kwargs = {}
    _kwargs = {}
    #kwargs = GetHistoKwargs(hG, opts)

    print
    if opts.normaliseToOne:
        pT = plots.MCPlot(datasetsMgr,
                          hT,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pR = plots.MCPlot(datasetsMgrRef,
                          hR,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pT = plots.MCPlot(datasetsMgr,
                          hT,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pR = plots.MCPlot(datasetsMgrRef,
                          hR,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    print "HT", hT

    xMax = 200
    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Events / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        #"opts"             : {"ymin": 0.1, "ymaxfactor": 1.2},
        "opts": {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": xMax
        },
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": True,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
        "rebinX": 1,
    }

    if "counters" in hT.lower():
        print "HERE"
        ROOT.gStyle.SetLabelSize(16.0, "X")
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 6
        }
        _kwargs["createLegend"] = {
            "x1": 0.65,
            "y1": 0.6,
            "x2": 0.90,
            "y2": 0.77
        },

    if "pt" in hT.lower():
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T} (%s)" % _units
        _kwargs["xmax"] = 800
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 800
        }

    if "mass" in hT.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units
        _kwargs["xmax"] = 800
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 800
        }
        if "tetrajet" in hT.lower():
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 2000
            }
            _kwargs["rebinX"] = 8
    if "trijetmass" in hT.lower():
        print "mass"
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _kwargs["xmax"] = 400  #1005
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 400
        }

    if "eta" in hT.lower():
        _units = ""
        _format = "%0.1f " + _units
        _xlabel = "#eta (%s)" % _units
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": -5.0,
            "xmax": +5.0
        }

    if "mult" in hT.lower():
        _format = "%0.0f"
        if "cleaned" in hT.lower():
            _kwargs["xmax"] = 10
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 10
            }
        else:
            _kwargs["xmax"] = 60
            _kwargs["opts"] = {
                "ymin": 0.1,
                "ymaxfactor": 1.2,
                "xmin": 0,
                "xmax": 60
            }

    if "bdisc" in hT.lower():
        _format = "%0.2f"
        _kwargs["xmax"] = 1
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 1
        }

    if "topbdt" in hT.lower():
        _format = "%0.2f"
        _kwargs["xmax"] = 1
        _kwargs["xmin"] = 0.3
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0.3,
            "xmax": 1.0
        }

    if "dijetmass" in hT.lower():
        print "dijet-mass"
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600
        _kwargs["opts"] = {
            "ymin": 0.1,
            "ymaxfactor": 1.2,
            "xmin": 0,
            "xmax": 300
        }

    else:
        pass

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.5

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    myList = []
    # Customise styling
    pT.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pR.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    datasetTarg = datasetsMgr.getDataset(
        "QCD")  #ChargedHiggs_HplusTB_HplusToTB_M_500
    datasetRef = datasetsMgrRef.getDataset(
        "QCD")  #ChargedHiggs_HplusTB_HplusToTB_M_500

    h = datasetTarg.getDatasetRootHisto(hT)
    #h.normalizeToOne()
    h.normalizeToLuminosity(intLumi)
    HT = h.getHistogram()

    h = datasetRef.getDatasetRootHisto(hR)
    #h.normalizeToOne()
    h.normalizeToLuminosity(intLumi)
    HR = h.getHistogram()

    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9, fillStyle=3001)
    ])

    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        #styles.StyleFill(fillColor=ROOT.kRed-4)
    ])

    signalStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kTeal + 2,
                           markerSizes=None,
                           markerStyle=ROOT.kFullTriangleUp),
        styles.StyleLine(lineColor=ROOT.kTeal + 2,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kTeal + 2, fillStyle=3001)
    ])

    p = plots.ComparisonPlot(
        histograms.Histo(HT, "Target", "pl", "PL"),
        histograms.Histo(HR, "Reference", "pl", "PL"),
    )
    p.histoMgr.setHistoLegendLabelMany({
        "Target": "bug fixed",
        "Reference": "bug"
    })

    if ("TT" in datasetTarg.getName()):
        p.histoMgr.forHisto("Target", altBackgroundBDTGStyle)
        p.histoMgr.forHisto("Reference", altSignalBDTGStyle)
    elif ("QCD" in datasetTarg.getName()):
        p.histoMgr.forHisto(
            "Target", altBackgroundBDTGStyle)  #styles.getABCDStyle("VR"))
        p.histoMgr.forHisto("Reference", styles.qcdFillStyle)
    elif ("Charged" in datasetTarg.getName()):
        p.histoMgr.forHisto("Target", altBackgroundBDTGStyle)
        p.histoMgr.forHisto("Reference", signalStyle)

    p.histoMgr.setHistoDrawStyle("Target", "HIST")
    p.histoMgr.setHistoLegendStyle("Target", "LP")  #F

    p.histoMgr.setHistoDrawStyle("Reference", "HIST")
    p.histoMgr.setHistoLegendStyle("Reference", "F")  #LP
    '''
    histoG = histograms.Histo(HT, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)
    
    histoF = histograms.Histo(HR, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)
    '''
    #styleT = styles.ttStyle
    #styleR = styles.signalStyleHToTB1000

    #styleT.apply(HT)
    #styleR.apply(HR)
    '''
    myList.append(histoT)
    myList.append(histoR)
    '''

    # Save plot in all formats
    #saveName = hT.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    #savePath = os.path.join(opts.saveDir, "HplusMasses", hT.split("/")[0], opts.optMode)
    #plots.drawPlot(p, savePath, **_kwargs)
    #SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    dName = datasetTarg.getName()
    dName = dName.replace("ChargedHiggs_HplusTB_HplusToTB_", "")

    saveName = hT.split("/")[-1] + "_" + dName
    #print saveName, hT, opts.saveDir
    savePath = os.path.join(opts.saveDir, hT.split("/")[0], opts.optMode)
    print "TYPE", type(hT), type(savePath), type(p)
    plots.drawPlot(p, savePath, **_kwargs)

    #leg = ROOT.TLegend(0.2, 0.8, 0.81, 0.87)
    leg = ROOT.TLegend(0.2, 0.8, 0.51, 0.87)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    #{"dx": -0.55, "dy": -0.55, "dh": -0.08}
    datasetName = datasetTarg.getName()
    datasetName = datasetName.replace("TT", "t#bar{t}")
    if "ChargedHiggs" in datasetName:
        datasetName = datasetName.replace("ChargedHiggs_HplusTB_HplusToTB_M_",
                                          "m_{H+} = ")
        datasetName = datasetName + "GeV"
    #leg.SetHeader("t#bar{t}")

    leg.SetHeader(datasetName)
    leg.Draw()

    #print savePath
    #savePath = os.path.join(opts.saveDir,  opts.optMode)

    SavePlot(p, saveName, savePath)

    return
def PlotSignalBackground(datasetsMgr, hG, hF, intLumi):
    kwargs = {}
    _kwargs = {}

    if opts.normaliseToOne:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 0, "ymaxfactor": 1.1}

    if "mass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units

    if "trijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 805  #1005
        _opts = {"xmin": 0.0, "xmax": 805}
    if "bjetmass" in hG.lower():
        _xlabel = "m_{b-tagged jet} (%s)" % _units
        _opts["xmax"] = 50
    if "bjetldgjet_mass" in hG.lower():
        _xlabel = "m_{b, ldg jet} (%s)" % _units
        _opts["xmax"] = 705
    if "bjetsubldgjet_mass" in hG.lower():
        _xlabel = "m_{b-tagged, subldg jet} (%s)" % _units
        _opts["xmax"] = 705
    if "jet_mass" in hG.lower():
        _opts["xmax"] = 750

    if "mult" in hG.lower():
        _format = "%0.0f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet mult"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet mult"
        if "avg" in hG.lower():
            _xlabel = "avg CvsL"

    if "cvsl" in hG.lower():
        _format = "%0.2f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet CvsL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CvsL"
        if "avg" in hG.lower():
            _xlabel = "avg CvsL"
    if "axis2" in hG.lower():
        _format = "%0.3f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet axis2"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet axis2"
        if "avg" in hG.lower():
            _xlabel = "avg axis2"

    if "dijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600
        _opts = {"xmin": 0.0, "xmax": 605, "ymin": 1e-3, "ymaxfactor": 1.0}

    if "trijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{t}"

    if "dijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{W}"

    if "dgjetptd" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet p_{T}D"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet p_{T}D"

    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        else:
            _xlabel = "b-tagged jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.35}

    if "over" in hG.lower():
        _format = "%0.2f "
        _xlabel = "m_{W}/m_{t}"
        _opts["xmax"] = 1
        _opts["xmin"] = 0
    if "likelihood" in hG.lower():
        _format = "%0.2f"
        if "ldg" in hG.lower():
            _xlabel = "Leading jet QGL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet QGL"
        if "avg" in hG.lower():
            _xlabel = "avg QGL"

    else:
        pass
    '''
    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
        else:
            _xlabel = "b-tagged jet CSV"
    '''

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    myList = []
    # Customise styling
    pG.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pF.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))

    #Dataset: ttbar
    dataset = datasetsMgr.getDataset(opts.dataset)  #soti
    #dataset = datasetsMgr.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_1000")

    #Get Genuine-top histogram
    h = dataset.getDatasetRootHisto(hG)
    h.normalizeToOne()
    HG = h.getHistogram()

    #Get Fake-top histogram
    h = dataset.getDatasetRootHisto(hF)
    h.normalizeToOne()
    HF = h.getHistogram()

    #Define Signal style
    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9)
    ])
    #Define Background style
    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kRed - 4, fillStyle=3001)
    ])

    signalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kTeal + 2,
                           markerSizes=None,
                           markerStyle=ROOT.kFullTriangleUp),
        styles.StyleLine(lineColor=ROOT.kTeal + 2,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kTeal + 2)
    ])  #, fillStyle=3001)])

    signalGrayStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kGray + 1,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kGray + 1,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kGray + 1)
    ])
    backgroundGrayStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kGray + 3,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kGray + 3,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kGray + 3, fillStyle=3001)
    ])

    #Comparison Plot
    p = plots.ComparisonPlot(
        histograms.Histo(HF, "Fake", "p", "P"),
        histograms.Histo(HG, "Genuine", "pl", "PL"),
    )

    #Set labels
    p.histoMgr.setHistoLegendLabelMany({
        "Fake": "Unmatched",
        "Genuine": "Truth-matched"
    })

    #Set Draw style
    p.histoMgr.forHisto("Fake", altBackgroundBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Fake", "LP")
    p.histoMgr.setHistoLegendStyle("Fake", "LP")  #F

    p.histoMgr.forHisto("Genuine", altSignalBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
    p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    if "avg" in hG.lower() or "likelihood" in hG.lower() or "over" in hG.lower(
    ):
        p.histoMgr.forHisto("Genuine", signalBDTGStyle)
        p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
        p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    if "Gray" in opts.mcrab:
        p.histoMgr.forHisto("Fake", backgroundGrayStyle)
        p.histoMgr.forHisto("Genuine", signalGrayStyle)
    histoG = histograms.Histo(HG, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)

    histoF = histograms.Histo(HF, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)

    styleG = styles.ttStyle
    styleF = styles.signalStyleHToTB1000

    styleG.apply(HG)
    styleF.apply(HF)

    myList.append(histoG)
    myList.append(histoF)

    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Arbitrary Units / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        #"opts"             : {"ymin": 0.0, "ymaxfactor": 1.1},
        "opts": _opts,
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": False,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
    }

    # Save plot in all formats
    saveName = hG.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    savePath = os.path.join(opts.saveDir + ANALYSISNAME, "HplusMasses",
                            hG.split("/")[0], opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p,
             saveName,
             os.path.join(opts.saveDir + opts.mcrab, opts.optMode),
             saveFormats=[".png"])

    return
def PlotPurity(datasetsMgr, histoName):
    '''
    Create plots with "FakeB=Data-EWKGenuineB"
    '''
    Verbose("Plotting histogram %s for Data, EWK, QCD " % (histoName), True)

    # Which folder to use (redundant)
    defaultFolder = "FakeBPurity"
    genuineBFolder = defaultFolder + "EWKGenuineB"
    fakeBFolder = defaultFolder + "EWKFakeB"

    # Customize the histograms (BEFORE calculating purity obviously otherwise numbers are nonsense)
    _cutBox = None
    _rebinX = 1
    _opts = {"ymin": 1e-3, "ymax": 1.0}  #"ymaxfactor": 1.2}
    _format = "%0.0f"
    #_opts["xmax"] = xMax
    _xlabel = None
    _ylabel = "Purity / "
    _format = "/ %.0f "

    h = histoName.split("/")[-1]
    if "dijetm" in h.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {
            "cutValue": 80.399,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
    if "trijetm" in h.lower():
        _rebinX = 2
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 1000.0
    if "pt" in h.lower():
        _format = "%0.0f GeV/c"
    if "chisqr" in h.lower():
        _opts["xmax"] = 100.0
        if "allselections" in h.lower():
            _opts["xmax"] = 10.0
    #if histo.lower().endswith("met_et"):
    if h.lower().startswith("ht_"):
        _rebinX = 5
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "H_{T} (%s)" % _units
        _cutBox = {
            "cutValue": 500.0,
            "fillColor": 16,
            "box": False,
            "line": False,
            "greaterThan": True
        }
        _opts["xmin"] = 500.0
        _opts["xmax"] = 3500.0
    if "eta" in h.lower():
        _rebinX = 1
        _format = "%0.2f"
        _cutBox = {
            "cutValue": 0.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in h.lower():
        _format = "%0.2f"
        _opts["xmin"] = 0.0
        _opts["xmax"] = 6.0
    if "bdisc" in h.lower():
        _format = "%0.2f"
    if "tetrajetm" in h.lower():
        _rebinX = 4
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _opts["xmax"] = 2500.0
    if "pt_" in h.lower():
        _rebinX = 2

    _ylabel += _format

    # Get histos (Data, EWK) for Inclusive
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

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

    # Rebin histograms (Before calculating Purity)
    Data.Rebin(_rebinX)
    EWK.Rebin(_rebinX)
    QCD.Rebin(_rebinX)

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

    # Comparison plot. The first argument is the reference histo. All other histograms are compared with respect to that.
    QCD_Purity, xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto(
        QCD, Data, inclusiveBins=False, printValues=False)
    EWK_Purity, xMin, xMax, binList, valueDict, upDict, downDict = getPurityHisto(
        EWK, Data, inclusiveBins=False, printValues=False)

    # Create TGraphs
    if 0:
        gQCD_Purity = MakeGraph(ROOT.kFullTriangleUp, ROOT.kOrange, binList,
                                valueDict, upDict, downDict)
        gEWK_Purity = MakeGraph(ROOT.kFullTriangleDown, ROOT.kPurple, binList,
                                valueDict, upDict, downDict)

    # Make the plots
    if opts.plotEWK:
        p = plots.ComparisonManyPlot(QCD_Purity, [EWK_Purity], saveFormats=[])
    else:
        p = plots.PlotBase([QCD_Purity], saveFormats=[])

    # Apply histo styles
    p.histoMgr.forHisto("QCD", styles.getQCDLineStyle())
    if opts.plotEWK:
        p.histoMgr.forHisto("EWK", styles.getAltEWKLineStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle("QCD", "P")
    if opts.plotEWK:
        p.histoMgr.setHistoDrawStyle("EWK", "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("QCD", "P")
    if opts.plotEWK:
        p.histoMgr.setHistoLegendStyle("EWK", "F")

    # Set legend labels
    if opts.plotEWK:
        p.histoMgr.setHistoLegendLabelMany({
            "QCD": "QCD",
            "EWK": "EWK",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            "QCD": "QCD",
        })

    # Do the plot
    plots.drawPlot(
        p,
        histoName,
        xlabel=_xlabel,
        ylabel=_ylabel,
        log=False,
        rebinX=1,  # must be done BEFORE calculating purity
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.76,
            "y1": 0.80,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 1e-5,
            "ymax": 1e0
        },
        ratio=False,
        ratioInvert=False,
        ratioYlabel="Ratio",
        cutBox=_cutBox,
    )

    # Save plot in all formats
    SavePlot(p, histoName,
             os.path.join(opts.saveDir, "Purity",
                          opts.optMode))  #, saveFormats = [".png"] )
    return
Example #11
0
def PurityPlots(datasetsMgr, histoName, analysisType="Inverted"):
    '''
    Create plots with "FakeB=Data-EWKGenuineB"
    '''
    Verbose(
        "Plotting histogram %s for Data, EWK, QCD for %s" %
        (histoName, analysisType), True)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    defaultFolder = "FakeBPurity"
    genuineBFolder = defaultFolder + "EWKGenuineB"
    fakeBFolder = defaultFolder + "EWKFakeB"

    # Get histos (Data, EWK) for Inclusive
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, analysisType))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get histos (Data, EWK) for GenuineB
    p2 = plots.ComparisonPlot(
        *getHistos(datasetsMgr, histoName.replace(
            defaultFolder, genuineBFolder), analysisType))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Clone histograms
    Data = p1.histoMgr.getHisto(analysisType +
                                "-Data").getRootHisto().Clone(analysisType +
                                                              "-Data")
    EWK = p1.histoMgr.getHisto(analysisType +
                               "-EWK").getRootHisto().Clone(analysisType +
                                                            "-EWK")
    EWKGenuineB = p2.histoMgr.getHisto(
        analysisType + "-EWK").getRootHisto().Clone(analysisType + "-EWK")
    FakeB = p1.histoMgr.getHisto(analysisType +
                                 "-Data").getRootHisto().Clone(analysisType +
                                                               "-FakeB")

    # Subtract EWKGEnuineB from Data to get FakeB
    FakeB.Add(EWKGenuineB, -1)
    #FakeB.Add(EWK, -1)

    # Dos not work
    # p1.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2))
    # p2.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2))

    # Comparison plot. The first argument is the reference histo. All other histograms are compared with respect to that.
    FakeB_Purity, xMin, xMax = getPurityHisto(FakeB,
                                              Data,
                                              inclusiveBins=False,
                                              printValues=False)
    EWKGenuineB_Purity, xMin, xMax = getPurityHisto(EWKGenuineB,
                                                    Data,
                                                    inclusiveBins=False,
                                                    printValues=False)
    p = plots.ComparisonManyPlot(FakeB_Purity, [EWKGenuineB_Purity],
                                 saveFormats=[])

    # Apply histo styles
    p.histoMgr.forHisto(
        analysisType + "-FakeB",
        styles.getInvertedLineStyle())  #styles.getFakeBLineStyle() )
    p.histoMgr.forHisto(
        analysisType + "-EWK",
        styles.getAltEWKLineStyle())  #styles.getAltEWKStyle() )

    # Set draw style
    p.histoMgr.setHistoDrawStyle(analysisType + "-FakeB", "HIST")
    p.histoMgr.setHistoDrawStyle(analysisType + "-EWK", "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle(analysisType + "-FakeB", "L")
    p.histoMgr.setHistoLegendStyle(analysisType + "-EWK", "L")

    # p.histoMgr.setHistoLegendStyleAll("LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        analysisType + "-FakeB": "FakeB",
        analysisType + "-EWK": "GenuineB (EWK)",
    })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.2}
    _format = "%0.0f"
    _opts["xmax"] = xMax
    _xlabel = None

    if "dijetm" in histoName.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {
            "cutValue": 80.399,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
    if "trijetm" in histoName.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 1500.0
    if "pt" in histoName.lower():
        _format = "%0.0f GeV/c"
    if "eta" in histoName.lower():
        _format = "%0.2f"
        _cutBox = {
            "cutValue": 0.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in histoName.lower():
        _format = "%0.2f"
        _opts["xmin"] = 0.0
        _opts["xmax"] = 6.0
    if "bdisc" in histoName.lower():
        _format = "%0.2f"
    if "tetrajetm" in histoName.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjjb} (%s)" % (_units)
        _opts["xmax"] = 3500.0

    # Do the plot
    plots.drawPlot(
        p,
        histoName,
        xlabel=_xlabel,
        ylabel="Purity / {0}".format(_format),
        log=False,
        rebinX=_rebinX,  # Can only Rebin BEFORE calculating purity
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.60,
            "y1": 0.80,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 1e-5,
            "ymax": 1e0
        },
        ratio=False,
        ratioInvert=False,
        ratioYlabel="Ratio",
        cutBox=_cutBox,
    )

    # Save plot in all formats
    SavePlot(p, histoName,
             os.path.join(opts.saveDir, "Purity",
                          opts.optMode))  #, saveFormats = [".png"] )
    return
Example #12
0
def main(opts):

    global RunEra
    mcrabName = opts.mcrab
    print("mcrabNAME ISSSSSS     ", mcrabName)
    RunEra = mcrabName.split("_")[1]

    print "    Run Era is: ", RunEra
    print "    Plotting efficiency for trigger:", kwargs.get("trigger")

    # Setup the style
    style = tdrstyle.TDRStyle()

    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(opts.batchMode)

    # Setup & configure the dataset manager
    #datasetsMgr   = GetSpecificDatasetsFromDir(opts.mcrab, opts, RunEra, reHLT_samples, **kwargs)
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)

    minRunRange = None
    maxRunRange = None

    Counter = 0
    nDataDatasets = len(datasetsMgr.getDataDatasets())

    for d in datasetsMgr.getDataDatasets():
        Counter = Counter + 1
        if Counter == 1:
            minRunRange = d.getName().split("_")[-2]
        if Counter == nDataDatasets:
            maxRunRange = d.getName().split("_")[-1]
        print "Data Name==> ", d.getName()
        print "RunRange ==> ", d.getName().split(
            "_")[-2], " - ", d.getName().split("_")[-1]

    print "Run Range = ", minRunRange, "     -      ", maxRunRange

    runRange = minRunRange + " - " + maxRunRange
    intLumi = GetLumi(datasetsMgr)
    print "intLumi=", intLumi

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Load Luminosities
    datasetsMgr.loadLuminosities()

    datasetsMgr.PrintLuminosities()

    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    #plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something!

    #dataset_MC.normalizeMCByLuminosity()

    datasetsMgr.PrintCrossSections()
    datasetsMgr.PrintLuminosities()

    plots.mergeRenameReorderForDataMC(datasetsMgr)

    datasetsMgr.PrintCrossSections()
    datasetsMgr.PrintLuminosities()

    dataset_Data = datasetsMgr.getDataDatasets()

    datasetsMgr.mergeMC()  #ATHER

    dataset_MC = None
    dataset_MC = datasetsMgr.getMCDatasets()

    #datasetsMgr.normalizeMCByLuminosity()
    #datasetsMgr.mergeMC()

    datasetsMgr.PrintCrossSections()
    datasetsMgr.PrintLuminosities()

    lumi = 0.0
    for d in datasetsMgr.getDataDatasets():
        lumi += d.getLuminosity()

    SigSel = ["1BTag", "2BTag", "OR", "OR_PFJet450"]
    for s in SigSel:
        for xVar in xVariables:
            print s, xVar

            #if xVar == "pt6thJet":
            #    cutValue = 40
            #    cutLine = True

            #for den,num
            num_name = "hNum_" + xVar + "_RefTrg_OfflineSel_Signal" + s
            den_name = "hDen_" + xVar + "_RefTrg_OfflineSel"
            # Get the save path and name
            plotName = "Eff" + "_" + xVar + "_" + s
            savePath, saveName = GetSavePathAndName(plotName, **kwargs)

            # Get Efficiency Plots
            eff_Data = getEfficiency(datasetsMgr, dataset_Data, num_name,
                                     den_name, **kwargs)
            eff_MC = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name,
                                   **kwargs)

            if xVar == "pt6thJet":
                xMin = 29.0
                xMax = 125.0
            elif xVar == "eta6thJet":
                xMin = -2.5
                xMax = 2.5
            elif xVar == "phi6thJet":
                xMin = -3.2
                xMax = 3.2
            elif xVar == "Ht":
                xMin = 350
                xMax = 2000
            elif xVar == "nBTagJets":
                xMin = 0
                xMax = 10
            elif xVar == "pu":
                xMin = 0
                xMax = 50
            elif xVar == "CSV":
                xMin = 0
                xMax = 1
            elif xVar == "JetMulti":
                xMin = 4
                xMax = 15
            elif xVar == "BJetMulti":
                xMin = 0
                xMax = 8

        # Apply Styles
            styles.dataStyle.apply(eff_Data)
            styles.mcStyle.apply(eff_MC)

            # Marker Style
            eff_Data.SetMarkerSize(1)

            # Create Comparison Plot
            p = plots.ComparisonPlot(
                histograms.HistoGraph(eff_Data, "eff_Data", "p", "P"),
                histograms.HistoGraph(eff_MC, "eff_MC", "p", "P"))

            opts = {"ymin": 0, "ymax": 1.1, "xmin": xMin, "xmax": xMax}
            opts2 = {"ymin": 0.8, "ymax": 1.05}
            if xVar == "pu":
                moveLegend = {"dx": -0.44, "dy": -0.62, "dh": -0.2}
            else:
                moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2}

            p.histoMgr.setHistoLegendLabelMany({
                "eff_Data": "Data",
                "eff_MC": "Simulation"
            })
            createRatio = True  #kwargs.get("ratio")
            p.createFrame(saveName,
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)

            # Set Legend
            p.setLegend(
                histograms.moveLegend(histograms.createLegend(), **moveLegend))

            # Set Log & Grid
            SetLogAndGrid(p, **kwargs)

            # Set Titles
            p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel"))
            if xVar == "pt6thJet":
                p.getFrame().GetXaxis().SetTitle("p_{T,6thJet} (Gev/c)")
            elif xVar == "eta6thJet":
                p.getFrame().GetXaxis().SetTitle("#eta_{6thJet}")
            elif xVar == "phi6thJet":
                p.getFrame().GetXaxis().SetTitle("#phi_{6thJet}")
            elif xVar == "Ht":
                p.getFrame().GetXaxis().SetTitle("H_{T} (Gev/c)")
            elif xVar == "nBTagJets":
                p.getFrame().GetXaxis().SetTitle("nB-Jet")
            elif xVar == "pu":
                p.getFrame().GetXaxis().SetTitle("nPU")
            elif xVar == "CSV":
                p.getFrame().GetXaxis().SetTitle("CSV")
            elif xVar == "JetMulti":
                p.getFrame().GetXaxis().SetTitle("Jet Multiplicity")
            elif xVar == "BJetMulti":
                p.getFrame().GetXaxis().SetTitle("B-Jet Multiplicity")

            if createRatio:
                p.getFrame2().GetYaxis().SetTitle("Ratio")
                p.getFrame2().GetYaxis().SetTitleOffset(1.6)

            #if xVar == "pt6thJet" and s == "OR":
            #    plist = [0.7, 0.99, 1000, 0.16, 28.0]
            #    Fit_Richards(30.0, 120.0, p, eff_Data, plist)
            #    plist = [0.72, 0.91, 0.212, 0.15, 50.0]
            #    Fit_Richards(30.0, 120.0, p, eff_MC, plist)
            #elif xVar == "Ht" and s == "OR":
            #    plist = [0.00005, 0.988, 0.000000109, 0.15, 29.0]
            #    Fit_Richards(350.0, 2000.0, p, eff_Data, plist)
            #plist = [0.0003, 0.97, 0.45, 0.24, 43.0]
            #Fit_Richards(500.0, 2000.0, p, eff_MC, plist)
            #elif xVar == "nBTagJets":
            #plist = [0.07, 0.984, 0.45, 0.24, 43.0]
            #Fit_Richards(30.0, 120.0, p, eff_Data, plist)
            #elif xVar == "pu":
            #plist = [0.07, 0.984, 0.45, 0.24, 43.0]
            #Fit_Richards(30.0, 120.0, p, eff_Data, plist)

            # Draw
            histograms.addText(0.30, 0.10, "Runs " + runRange, 17)
            histograms.addText(0.30, 0.15, "2016", 17)
            histograms.addStandardTexts(lumi=lumi)
            p.draw()

            # Save the canvas to a file
            SaveAs(p, kwargs.get("savePath"), saveName,
                   kwargs.get("saveFormats"), True)
            '''
            # IN SLICES OF HT
    HTSlices = ["450ht600","600ht800","800ht1000", "1000ht1250", "1250ht1500", "1500ht2000"]
    for s in SigSel:
        for hsl in HTSlices:
            num_name = "Num_pt6thJet_Vs_"+hsl+"_RefTrg_OfflineSel_"+s
            den_name = "Den_pt6thJet_Vs_"+hsl+"_RefTrg_OfflineSel"
            # Get the save path and name        
            plotName = "Eff_pt6thJet_Vs_"+hsl+"_"+s
            savePath, saveName = GetSavePathAndName(plotName, **kwargs)
        
            # Get Efficiency Plots
            eff_Data     = getEfficiency(datasetsMgr, dataset_Data, num_name, den_name , **kwargs)
            eff_MC       = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name, **kwargs) 
            
            xMin = 29.0
            xMax = 125.0
                
            # Apply Styles
            styles.dataStyle.apply(eff_Data)
            styles.mcStyle.apply(eff_MC)
        
            # Marker Style
            eff_Data.SetMarkerSize(1)
                
            # Create Comparison Plot
            p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data","p","P"),
                                     histograms.HistoGraph(eff_MC,   "eff_MC", "p", "P"))
                
            opts       = {"ymin": 0  , "ymax": 1.1, "xmin":xMin, "xMax":xMax}
            opts2      = {"ymin": 0.7, "ymax": 1.3}
            moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2 }
            
            p.histoMgr.setHistoLegendLabelMany({"eff_Data": "Data", "eff_MC": "Simulation"})
            createRatio = True #kwargs.get("ratio")
            p.createFrame(saveName, createRatio=createRatio, opts=opts, opts2=opts2)
                    
            # Set Legend
            p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        
            # Set Log & Grid
            SetLogAndGrid(p, **kwargs)
    
            # Set Titles
            p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel"))
            p.getFrame().GetXaxis().SetTitle("p_{T} (Gev/c)")
                    
            if createRatio:
                p.getFrame2().GetYaxis().SetTitle("Ratio")
                p.getFrame2().GetYaxis().SetTitleOffset(1.6)
                            
            # Draw
            histograms.addText(0.30, 0.10, "Runs "+runRange, 17)
            histograms.addText(0.30, 0.15, "2016", 17)
            histograms.addStandardTexts(lumi=lumi)
            p.draw()
        
            # Save the canvas to a file
            SaveAs(p, kwargs.get("savePath"), saveName, kwargs.get("saveFormats"), True)

    
    PTSlices = ["40pt50","50pt60", "60pt70", "70pt90", "90pt120"]
    for s in SigSel:
        for psl in PTSlices:
            num_name = "Num_ht_Vs_"+psl+"_HLT_PFHT350_"+s
            den_name = "Den_ht_Vs_"+psl+"_HLT_PFHT350"
            # Get the save path and name        
            plotName = "Eff_ht_Vs_"+psl+"_"+s
            savePath, saveName = GetSavePathAndName(plotName, **kwargs)
        
            # Get Efficiency Plots
            eff_Data     = getEfficiency(datasetsMgr, dataset_Data, num_name, den_name , **kwargs)
            eff_MC       = getEfficiency(datasetsMgr, dataset_MC, num_name, den_name, **kwargs) 

            xMin = 450
            xMax = 2000
                
            # Apply Styles
            styles.dataStyle.apply(eff_Data)
            styles.mcStyle.apply(eff_MC)
        
            # Marker Style
            eff_Data.SetMarkerSize(1)
                
            # Create Comparison Plot
            p = plots.ComparisonPlot(histograms.HistoGraph(eff_Data, "eff_Data","p","P"),
                                     histograms.HistoGraph(eff_MC,   "eff_MC", "p", "P"))
                
            opts       = {"ymin": 0  , "ymax": 1.1, "xmin":xMin, "xMax":xMax}
            opts2      = {"ymin": 0.7, "ymax": 1.3}
            moveLegend = {"dx": -0.44, "dy": -0.57, "dh": -0.2 }
                
            p.histoMgr.setHistoLegendLabelMany({"eff_Data": "Data", "eff_MC": "Simulation"})
            createRatio = True #kwargs.get("ratio")
            #if eff_Data != None and eff_MC != None:
            p.createFrame(saveName, createRatio=createRatio, opts=opts, opts2=opts2)
                    
            # Set Legend
            p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        
            # Set Log & Grid
            SetLogAndGrid(p, **kwargs)
    
            # Set Titles
            p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel"))
            p.getFrame().GetXaxis().SetTitle("H_{T} (Gev/c)")
                    
            if createRatio:
                p.getFrame2().GetYaxis().SetTitle("Ratio")
                p.getFrame2().GetYaxis().SetTitleOffset(1.6)
                            
            # Draw
            histograms.addText(0.30, 0.10, "Runs "+runRange, 17)
            histograms.addText(0.30, 0.15, "2016", 17)
            histograms.addStandardTexts(lumi=lumi)
            p.draw()
        
            # Save the canvas to a file
            SaveAs(p, kwargs.get("savePath"), saveName, kwargs.get("saveFormats"), True)
            '''
    return
Example #13
0
def BaselineVsInvertedComparison(datasetsMgr, histoName):
    
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, "Data", "topSelection_Baseline/%s" % histoName, "topSelection_Inverted/%s" % histoName))
    p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, "EWK", "topSelection_Baseline/%s" % histoName, "topSelection_Inverted/%s" % histoName) )
    p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Get Data histos    
    baseline_Data = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-Data")
    inverted_Data = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-Data")

    # Get EWK histos
    baseline_EWK = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline-EWK")
    inverted_EWK = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted-EWK")

    # Create QCD histos: QCD = Data-EWK
    baseline_QCD = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-QCD")
    baseline_QCD.Add(baseline_EWK, -1)
    inverted_QCD = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-QCD")
    inverted_QCD.Add(inverted_EWK, -1)

    # Normalize histograms to unit area
    baseline_QCD.Scale(1.0/baseline_QCD.Integral())
    inverted_QCD.Scale(1.0/inverted_QCD.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(baseline_QCD, [inverted_QCD], saveFormats=[]) #[".C", ".png", ".pdf"])
    p.setLuminosity(GetLumi(datasetsMgr))
        
    # Apply styles
    p.histoMgr.forHisto("Baseline-QCD" , styles.getBaselineStyle() )
    p.histoMgr.forHisto("Inverted-QCD" , styles.getInvertedStyle() )

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

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            "Baseline-QCD" : "Baseline (QCD)",
            "Inverted-QCD" : "Inverted (QCD)",
            })

    # Draw the histograms
    _rebinX = 1
    _cutBox = None
    _opts   = {"ymin": 8e-5, "ymaxfactor": 2.0}

    if "Pt_" in histoName:
        _format = "%0.f GeV/c"
        if "tetrajet" in histoName.lower():
            _rebinX = 2
            
    if "ChiSqr" in histoName:
        _format = "%0.1f"
        _rebinX = 10
        if "After" in histoName:
            _rebinX = 1
            _opts["xmax"] = 20.0
    if "Mass" in histoName:
        _format = "%0.0f GeV/c^{2}"
        _rebinX = 2
        if "tetrajet" in histoName.lower():
            _rebinX = 5
            _opts["xmax"] = 3000.0
    if "BDisc" in histoName:
        _format = "%0.2f"
        _rebinX = 2
        _opts["xmax"] = 1.01
    if "Eta" in histoName:
        _format = "%0.2f"
    if "trijet" in histoName.lower():
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
    if "dijet" in histoName.lower():
        _cutBox = {"cutValue": 80.399, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
    if "TetrajetMass" in histoName:
        _opts   = {"ymin": 8e-5, "ymaxfactor": 2.0, "xmax": 3000.0}
                
    plots.drawPlot(p, histoName,  
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = True, 
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.62, "y1": 0.78, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   ratio        = True,
                   ratioInvert  = False, 
                   ratioYlabel  = "Ratio",
                   cutBox       = _cutBox,
                   )
    # Save plot in all formats
    SavePlot(p, histoName, os.path.join(opts.saveDir, "BaselineVsInverted") ) 
    return
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
Example #15
0
def main(opts, signalMass):

        # Apply TDR style
    style = tdrstyle.TDRStyle()
    style.setGridX(False)
    style.setGridY(False)

    # Do the topSelection histos
    folder      = ""

    #=== Define styles: Fixme: Put in function

    #styles_S    = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=928, markerSizes=None, markerStyle=ROOT.kFullDiamond),
     #                                   styles.StyleLine(lineColor=928, lineStyle=ROOT.kSolid, lineWidth=3),
     #                                   styles.StyleFill(fillColor=38)])
    styles_S    = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=928, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                        styles.StyleLine(lineColor=928, lineStyle=ROOT.kSolid, lineWidth=3)])                                       


    styles_B    = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=2, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                        styles.StyleLine(lineColor=2, lineStyle=ROOT.kSolid, lineWidth=3),
                                        styles.StyleFill(fillColor=2, fillStyle=3005)])

    styles_SEff = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=ROOT.kBlue, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                        styles.StyleLine(lineColor=ROOT.kBlue, lineStyle=ROOT.kSolid, lineWidth=3),])

    styles_BEff = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=ROOT.kRed, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                        styles.StyleLine(lineColor=ROOT.kRed, lineStyle=ROOT.kSolid, lineWidth=3),])

    styles_Signif = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=ROOT.kGreen+2, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                          styles.StyleLine(lineColor=ROOT.kGreen+2, lineStyle=ROOT.kSolid, lineWidth=3),])

    styles_pur = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=ROOT.kOrange+7, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                       styles.StyleLine(lineColor=ROOT.kOrange+7, lineStyle=ROOT.kSolid, lineWidth=3),])

    styles_pureff = styles.StyleCompound([styles.StyleMarker(markerSize=0.4, markerColor=ROOT.kOrange, markerSizes=None, markerStyle=ROOT.kFullDiamond),
                                          styles.StyleLine(lineColor=ROOT.kOrange, lineStyle=ROOT.kSolid, lineWidth=3),])


    #=== Histo Names ============================================
    hN_SignalEff = "sigEffi"
    hN_BgdEff    = "bgdEffi"
    hN_signif    = "significance_BDTG"
    hN_purS      = "purS_BDTG"
    hN_effpurS   = "effpurS_BDTG"

    hN_BDTs      = "MVA_BDTG_S"
    hN_BDTb      = "MVA_BDTG_B"

    #=== Directories ============================================
    inpfile_eff = ROOT.TFile(opts.effFile, "R")
    inpfile     = ROOT.TFile(opts.rootfile, "R") #To be fixed!
    inpfile_dir = inpfile.Get("Method_BDT/BDTG")


    #=== Get histograms from directories=========================
    h_SignalEffi = inpfile_eff.Get(hN_SignalEff)
    h_BgdEffi    = inpfile_eff.Get(hN_BgdEff)
    h_signif     = inpfile_eff.Get(hN_signif)
    h_purS       = inpfile_eff.Get(hN_purS)
    h_effpurS    = inpfile_eff.Get(hN_effpurS)

    h_BDTs       = inpfile_dir.Get(hN_BDTs)
    h_BDTb       = inpfile_dir.Get(hN_BDTb)
    
    #=== Scale Significance
    h_signifScaled = h_signif.Clone("signif")
    maxSignif = h_signif.GetMaximum()
    h_signifScaled.Scale(1/maxSignif)

    histo_signalEff    = histograms.Histo(h_SignalEffi,   "sEff",     legendStyle = "LP", drawStyle="LP")
    histo_bgdEff       = histograms.Histo(h_BgdEffi,      "bEff",     legendStyle = "LP", drawStyle="LP")
    histo_signifScaled = histograms.Histo(h_signifScaled, "signif",   legendStyle = "LP", drawStyle="LP")
    histo_purS         = histograms.Histo(h_purS,         "purity",   legendStyle = "LP", drawStyle="LP")
    histo_effpurS      = histograms.Histo(h_effpurS,      "pureff",   legendStyle = "LP", drawStyle="LP")

    histo_BDTs         = histograms.Histo(h_BDTs,         "bdtS",     legendStyle = "LP", drawStyle="LP")
    histo_BDTb         = histograms.Histo(h_BDTb,         "bdtB",     legendStyle = "LP", drawStyle="LP")



    #=== Efficiency - Purity - Significance=================================
    histoList_Eff = [histo_bgdEff, histo_signifScaled, histo_purS, histo_effpurS]
    p_Eff = plots.ComparisonManyPlot(histo_signalEff, histoList_Eff,
                                     saveFormats=[])

    p_Eff.histoMgr.setHistoLegendLabelMany({"sEff": "Signal efficiency", 
                                        "bEff": "Bkg efficiency", 
                                        "signif": "S/#sqrt{S+B}", 
                                        #"signif": "#frac{S}{#sqrt{S+B}}", 
                                        "purity": "Signal purity", 
                                        "pureff": "Signal eff*purity",})



    # Define Right Axis (Significance)
    signifColor = ROOT.kGreen+2
    #rightAxis = ROOT.TGaxis(0.5, 0.17, 0.97, 0.34, 0, 1.1*maxSignif, 510, "+L")
    '''
    TGaxis::TGaxis(Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax,
                   Double_t wmin, Double_t wmax, Int_t ndiv, Option_t *chopt,
                   Double_t gridlength)
    '''
    rightAxis = ROOT.TGaxis(1, 0, 1, 1.1, 0, 1.1*maxSignif, 510, "+L")
    rightAxis.SetWmax(1.1*maxSignif)
    rightAxis.SetLineColor ( signifColor )
    rightAxis.SetLabelColor( signifColor )
    rightAxis.SetTitleColor( signifColor )

    # rightAxis.SetTitleSize( info->sSig->GetXaxis()->GetTitleSize() )
    # rightAxis.SetLabelOffset(0.9)
    # This will only be be visible if we use a wide canvas (but we don't want that)
    if 0:
        style.setWide(True, 0.15) #to make way for significane label
        rightAxis.SetTitle( "Significance" )
        # rightAxis.SetTitleOffset(1.1)

    #=== BDTG output ========================================================
    histo_BDTs         = histograms.Histo(h_BDTs,         "bdtS",     legendStyle = "LP", drawStyle="LP")
    histo_BDTb         = histograms.Histo(h_BDTb,         "bdtB",     legendStyle = "F", drawStyle="LP")

    #p_BDT = plots.ComparisonPlot(histo_BDTb, histo_BDTs, saveFormats=[])
    p_BDT = plots.ComparisonPlot(histo_BDTs, histo_BDTb, saveFormats=[])
    p_BDT.histoMgr.setHistoLegendLabelMany({"bdtS": "Signal", "bdtB": "Background"})
    
    p_Eff.histoMgr.forHisto("sEff", styles_SEff)
    p_Eff.histoMgr.setHistoDrawStyle("sEff", "L")
    p_Eff.histoMgr.setHistoLegendStyle("sEff", "L")

    p_Eff.histoMgr.forHisto("bEff", styles_BEff)
    p_Eff.histoMgr.setHistoDrawStyle("bEff", "L")
    p_Eff.histoMgr.setHistoLegendStyle("bEff", "L")

    p_Eff.histoMgr.forHisto("signif", styles_Signif)
    p_Eff.histoMgr.setHistoDrawStyle("signif", "L")
    p_Eff.histoMgr.setHistoLegendStyle("signif", "L")

    p_Eff.histoMgr.forHisto("purity", styles_pur)
    p_Eff.histoMgr.setHistoDrawStyle("purity", "L")
    p_Eff.histoMgr.setHistoLegendStyle("purity", "L")

    p_Eff.histoMgr.forHisto("pureff", styles_pureff)
    p_Eff.histoMgr.setHistoDrawStyle("pureff", "L")
    p_Eff.histoMgr.setHistoLegendStyle("pureff", "L")


    p_BDT.histoMgr.forHisto("bdtS", styles_S)
    p_BDT.histoMgr.setHistoDrawStyle("bdtS", "HIST")
    p_BDT.histoMgr.setHistoLegendStyle("bdtS", "L")

    p_BDT.histoMgr.forHisto("bdtB", styles_B)
    p_BDT.histoMgr.setHistoDrawStyle("bdtB", "HIST")
    p_BDT.histoMgr.setHistoLegendStyle("bdtB", "F")


    saveName_eff = "mvaeff"
    saveName     = "mva"
    savePath = os.path.join(opts.saveDir, opts.optMode)

    _kwargs = {
        "xlabel"           : "BDTG", #"Cut value applied on BDTG output",
        "ylabel"           : "Efficiency (Purity)",
        "ratioYlabel"      : "Ratio ",
        "ratio"            : False,
        "ratioInvert"      : False,
        "stackMCHistograms": False,
        "addMCUncertainty" : False,
        "addLuminosityText": False,
        "addCmsText"       : True,
        "cmsExtraText"     : "Preliminary",
        "opts"             : {"xmin": -1.0, "xmax": 1.01, "ymin": 0.0, "ymax": 1.1},
        "opts2"            : {"ymin": 0.6, "ymax": 1.5},
        "log"              : False,
        "createLegend"     : {"x1": 0.45, "y1": 0.45, "x2": 0.70, "y2": 0.70},
        }
    ROOT.gStyle.SetNdivisions(6 + 100*5 + 10000*2, "X") #ROOT.gStyle.SetNdivisions(8, "X")
    plots.drawPlot(p_Eff, savePath, **_kwargs)
    rightAxis.Draw()
    
    saveDir = opts.rootfile.split("/")[-1]
    saveDir = saveDir.replace(".root","")
    SavePlot(p_Eff, saveName_eff, os.path.join(opts.saveDir, saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])

    _kwargs["log"]  = True
    _kwargs["opts"]["ymin"] = 3e-2
    _kwargs["opts"]["ymax"] = 20
    _kwargs["xlabel"] = "BDTG"# response"
    _kwargs["ylabel"] = "(1/N) dN/dx"
    _kwargs["createLegend"] = {"x1": 0.25, "y1": 0.75, "x2": 0.50, "y2": 0.9}
    style.setWide(False, 0.15)
    ROOT.gStyle.SetNdivisions(6 + 100*5 + 10000*2, "X")
    plots.drawPlot(p_BDT, savePath, **_kwargs)
    SavePlot(p_BDT, saveName, os.path.join(opts.saveDir, saveDir, opts.optMode), saveFormats = [".png", ".pdf", ".C"])
    return
Example #16
0
def PlotBaselineVsInverted(datasetsMgr, hBaseline, hInverted):

    # Get the Inclusive (Data, EWK)
    p1 = plots.ComparisonPlot(
        *getHistos(datasetsMgr, "Data", hBaseline, hInverted))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(
        *getHistos(datasetsMgr, "EWK", hBaseline, hInverted))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    if opts.useMC:
        p3 = plots.ComparisonPlot(
            *getHistos(datasetsMgr, "QCD", hBaseline, hInverted))
        p3.histoMgr.normalizeMCToLuminosity(
            datasetsMgr.getDataset("Data").getLuminosity())

    # Get Baseline histos
    baseline_Data = p1.histoMgr.getHisto(
        "Baseline-Data").getRootHisto().Clone()
    baseline_QCD = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone(
        "Baseline-QCD")
    baseline_EWK = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone()
    if opts.useMC:
        baseline_QCDMC = p3.histoMgr.getHisto(
            "Baseline-QCD").getRootHisto().Clone("Baseline-QCDMC")

    # Get Inverted histos
    inverted_Data = p1.histoMgr.getHisto(
        "Inverted-Data").getRootHisto().Clone()
    inverted_QCD = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone(
        "Inverted-QCD")
    inverted_EWK = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone()
    if opts.useMC:
        inverted_QCDMC = p3.histoMgr.getHisto(
            "Inverted-QCD").getRootHisto().Clone("Inverted-QCDMC")

    # Subtract EWK from Data to get QCD
    baseline_QCD.Add(baseline_EWK, -1)
    inverted_QCD.Add(inverted_EWK, -1)

    # Option: Use QCD-MC instead of QCD=Data-EWK
    if opts.useMC:
        baseline_QCD = baseline_QCDMC
        inverted_QCD = inverted_QCDMC

    # Normalize histograms to unit area
    if opts.normaliseToOne:
        baseline_Data.Scale(1.0 / baseline_Data.Integral())
        baseline_QCD.Scale(1.0 / baseline_QCD.Integral())
        baseline_EWK.Scale(1.0 / baseline_EWK.Integral())
        inverted_Data.Scale(1.0 / inverted_Data.Integral())
        inverted_QCD.Scale(1.0 / inverted_QCD.Integral())
        inverted_EWK.Scale(1.0 / inverted_EWK.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(baseline_QCD, [inverted_QCD], saveFormats=[])

    # Apply styles
    if opts.useMC:
        p.histoMgr.forHisto("Baseline-QCDMC", styles.getBaselineStyle())
        p.histoMgr.forHisto("Inverted-QCDMC", styles.getInvertedStyle())
    else:
        p.histoMgr.forHisto("Baseline-QCD", styles.getBaselineStyle())
        p.histoMgr.forHisto("Inverted-QCD", styles.getInvertedStyle())

    # Set draw style
    if opts.useMC:
        p.histoMgr.setHistoDrawStyle("Baseline-QCDMC", "AP")
        p.histoMgr.setHistoDrawStyle("Inverted-QCDMC", "HIST")
    else:
        p.histoMgr.setHistoDrawStyle("Baseline-QCD", "AP")
        p.histoMgr.setHistoDrawStyle("Inverted-QCD", "HIST")

    # Set legend style
    if opts.useMC:
        p.histoMgr.setHistoLegendStyle("Baseline-QCDMC", "LP")
        p.histoMgr.setHistoLegendStyle("Inverted-QCDMC", "F")
    else:
        p.histoMgr.setHistoLegendStyle("Baseline-QCD", "LP")
        p.histoMgr.setHistoLegendStyle("Inverted-QCD", "F")

    # Set legend labels
    if opts.useMC:
        p.histoMgr.setHistoLegendLabelMany({
            "Baseline-QCDMC":
            "QCD-MC (Baseline)",
            "Inverted-QCDMC":
            "QCD-MC (Inverted)",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            "Baseline-QCD": "QCD (Baseline)",
            "Inverted-QCD": "QCD (Inverted)",
        })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    if opts.normaliseToOne:
        _opts = {"ymin": 3e-4, "ymaxfactor": 2.0}
    else:
        _opts = {"ymin": 1e0, "ymaxfactor": 2.0}
    _format = "%0.0f"
    _xlabel = None

    if "dijetm" in hBaseline.lower():
        _rebinX = 2
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {
            "cutValue": 80.399,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 400.0
    if "chisqr" in hBaseline.lower():
        _rebinX = 1
        _units = ""
        _format = "%0.1f " + _units
        _xlabel = "#chi^{2}"
        _cutBox = {
            "cutValue": 10.0,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 100.0
    if "ldgdijetpt" in hBaseline.lower():
        _rebinX = 1
        _units = "GeV/c"
        _format = "%0.0f " + _units
        _xlabel = "p_{T} (%s)" % _units
        _cutBox = {
            "cutValue": 40.0,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 800.0
    if "ldgdijetm" in hBaseline.lower():
        _rebinX = 1
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % _units
        _cutBox = {
            "cutValue": 80.385,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 300.0
    if "trijetm" in hBaseline.lower():
        _rebinX = 4  #5
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {
            "cutValue": 173.21,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmax"] = 1000.0
    if "pt" in hBaseline.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c"
        _cutBox = {
            "cutValue": 40.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        ROOT.gStyle.SetNdivisions(8, "X")
        _opts["xmax"] = 1000.0
    if "eta" in hBaseline.lower():
        _format = "%0.2f"
        _cutBox = {
            "cutValue": 0.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in hBaseline.lower():
        _format = "%0.2f"
        _opts["xmin"] = 0.0
        _opts["xmax"] = 6.0
    if "bdisc" in hBaseline.lower():
        _format = "%0.2f"
    if "tetrajetm" in hBaseline.lower():
        _rebinX = 10  #4
        if opts.useMC:
            _rebinX = 10
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjbb} (%s)" % (_units)
        _opts["xmax"] = 3000.0
        #_opts["xmax"] = 3500.0

    plots.drawPlot(
        p,
        hBaseline,
        xlabel=_xlabel,
        ylabel="Arbitrary Units / %s" % (_format),
        log=True,
        rebinX=_rebinX,
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.62,
            "y1": 0.78,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 0.6,
            "ymax": 1.4
        },
        ratio=True,
        ratioInvert=False,
        ratioYlabel="Ratio",
        cutBox=_cutBox,
    )

    # Save plot in all formats
    saveName = hBaseline.replace("/", "_")
    saveName = saveName.replace("_Baseline_", "_")
    savePath = os.path.join(opts.saveDir, "BaselineVsInverted", opts.optMode)
    if opts.useMC:
        savePath = os.path.join(opts.saveDir, "BaselineVsInverted", "MC",
                                opts.optMode)
    SavePlot(p, saveName, savePath)
    return
def PlotBaselineVsInvertedTemplates(datasetsMgr,
                                    histoName,
                                    addQcdBaseline=False):
    Verbose("Plotting EWK Vs QCD unity-normalised histograms")

    # Create comparison plot
    p1 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "Data", "topSelection_Baseline/%s" % histoName,
                 "Baseline"),
        getHisto(datasetsMgr, "EWK", "topSelection_Baseline/%s" % histoName,
                 "Baseline"))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "Data", "topSelection_Inverted/%s" % histoName,
                 "Inverted"),
        getHisto(datasetsMgr, "EWK", "topSelection_Inverted/%s" % histoName,
                 "Inverted"))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get EWK histos
    EWK_baseline = p1.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone(
        "Baseline-EWK")
    EWK_inverted = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone(
        "Inverted-EWK")
    # Get QCD histos
    QCD_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone(
        "Baseline-QCD")
    QCD_inverted = p2.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone(
        "Inverted-QCD")

    # Create QCD histos: QCD = Data-EWK
    QCD_baseline.Add(EWK_baseline, -1)
    QCD_inverted.Add(EWK_inverted, -1)

    # Normalize histograms to unit area
    EWK_baseline.Scale(1.0 / EWK_baseline.Integral())
    EWK_inverted.Scale(1.0 / EWK_inverted.Integral())
    QCD_baseline.Scale(1.0 / QCD_baseline.Integral())
    QCD_inverted.Scale(1.0 / QCD_inverted.Integral())

    # Create the final plot object
    if addQcdBaseline:
        compareHistos = [EWK_baseline, QCD_baseline]
    else:
        compareHistos = [EWK_baseline]
    p = plots.ComparisonManyPlot(QCD_inverted, compareHistos, saveFormats=[])
    p.setLuminosity(GetLumi(datasetsMgr))

    # Apply styles
    p.histoMgr.forHisto("Baseline-EWK", styles.getBaselineStyle())
    if addQcdBaseline:
        p.histoMgr.forHisto("Baseline-QCD", styles.getInvertedLineStyle())
    p.histoMgr.forHisto("Inverted-QCD", styles.getInvertedStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Baseline-EWK", "AP")
    p.histoMgr.setHistoLegendStyle("Baseline-EWK", "LP")
    if addQcdBaseline:
        p.histoMgr.setHistoDrawStyle("Baseline-QCD", "HIST")
        p.histoMgr.setHistoLegendStyle("Baseline-QCD", "FL")
    p.histoMgr.setHistoDrawStyle("Inverted-QCD", "AP")
    p.histoMgr.setHistoLegendStyle("Inverted-QCD", "LP")

    # Set legend labels
    if addQcdBaseline:
        p.histoMgr.setHistoLegendLabelMany({
            "Baseline-EWK": "EWK (Baseline)",
            "Baseline-QCD": "QCD (Baseline)",
            "Inverted-QCD": "QCD (Inverted)",
        })
    else:
        p.histoMgr.setHistoLegendLabelMany({
            "Baseline-EWK": "EWK (Baseline)",
            "Inverted-QCD": "QCD (Inverted)",
        })

    # Append analysisType to histogram name
    saveName = histoName

    # Draw the histograms #alex
    plots.drawPlot(p, saveName,
                   **GetHistoKwargs(histoName))  #the "**" unpacks the kwargs_

    # _kwargs = {"lessThan": True}
    # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs)

    # Add text
    text = opts.optMode.replace("OptChiSqrCutValue", "#chi^{2} #leq ")
    histograms.addText(0.21, 0.85, text)

    # Save plot in all formats
    saveDir = os.path.join(opts.saveDir, "Templates", opts.optMode)
    SavePlot(p, saveName, saveDir, saveFormats=[".C", ".png", ".pdf"])
    return
Example #18
0
def EWKvQCD(datasetsMgr, histoName, analysisType=""):
    Verbose("Plotting EWK Vs QCD unity-normalised histograms for %s" %
            analysisType)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    p1 = plots.ComparisonPlot(
        *getHistos(datasetsMgr, "Data", "topSelection_Baseline/%s" %
                   histoName, "topSelection_Inverted/%s" % histoName))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(
        *getHistos(datasetsMgr, "EWK", "topSelection_Baseline/%s" %
                   histoName, "topSelection_Inverted/%s" % histoName))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get histos
    data = p1.histoMgr.getHisto(analysisType +
                                "-Data").getRootHisto().Clone(analysisType +
                                                              " -Data")
    EWK = p2.histoMgr.getHisto(analysisType +
                               "-EWK").getRootHisto().Clone(analysisType +
                                                            "-EWK")
    # Create QCD histos: QCD = Data-EWK
    QCD = p1.histoMgr.getHisto(analysisType +
                               "-Data").getRootHisto().Clone(analysisType +
                                                             "-QCD")
    QCD.Add(EWK, -1)

    # Normalize histograms to unit area
    QCD.Scale(1.0 / QCD.Integral())
    EWK.Scale(1.0 / EWK.Integral())

    # Create the final plot object
    p = plots.ComparisonManyPlot(QCD, [EWK],
                                 saveFormats=[])  #[".C", ".png", ".pdf"])
    p.setLuminosity(GetLumi(datasetsMgr))

    # Apply styles
    p.histoMgr.forHisto(analysisType + "-QCD", styles.getQCDLineStyle())
    p.histoMgr.forHisto(analysisType + "-EWK", styles.getAltEWKStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle(analysisType + "-QCD", "LP")
    p.histoMgr.setHistoLegendStyle(analysisType + "-QCD", "LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        analysisType + "-QCD":
        analysisType + " (QCD)",
        analysisType + "-EWK":
        analysisType + " (EWK)",
    })

    # Append analysisType to histogram name
    saveName = histoName + "_" + analysisType

    # Draw the histograms #alex
    plots.drawPlot(p, saveName,
                   **GetHistoKwargs(histoName))  #the "**" unpacks the kwargs_

    # _kwargs = {"lessThan": True}
    # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs)

    # Save plot in all formats
    saveDir = os.path.join(opts.saveDir, "EWKvQCD", opts.optMode)
    SavePlot(p, saveName, saveDir)
    return
Example #19
0
def PlotAndFitTemplates(datasetsMgr, histoName, addQcdBaseline, opts):
    Verbose("PlotAndFitTemplates()")

    # Create comparison plot
    p1 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "Data", "topSelection_Baseline/%s" % histoName, "Baseline"),
        getHisto(datasetsMgr, "EWK" , "topSelection_Baseline/%s" % histoName, "Baseline")
        )
    p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    p2 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "Data", "topSelection_Inverted/%s" % histoName, "Inverted"),
        getHisto(datasetsMgr, "EWK" , "topSelection_Inverted/%s" % histoName, "Inverted")
        )
    p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())


    # Get Baseline histos
    Data_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline_Data")
    EWK_baseline  = p1.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline_EWK")
    QCD_baseline  = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline_QCD")

    # Get Inverted histos
    Data_inverted = p2.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted_Data")
    EWK_inverted  = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted_EWK")
    QCD_inverted  = p2.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted_QCD")

    # Create QCD histos: QCD = Data-EWK
    QCD_baseline.Add(EWK_baseline, -1)
    QCD_inverted.Add(EWK_inverted, -1)

    # Normalize histograms to unit area
    if 0:
        EWK_baseline.Scale(1.0/EWK_baseline.Integral())    
        EWK_inverted.Scale(1.0/EWK_inverted.Integral())
        QCD_baseline.Scale(1.0/QCD_baseline.Integral())
        QCD_inverted.Scale(1.0/QCD_inverted.Integral())
        
    # Create the final plot object
    if addQcdBaseline:
        compareHistos = [EWK_baseline, QCD_baseline]
    else:
        compareHistos = [EWK_baseline]
    p = plots.ComparisonManyPlot(QCD_inverted, compareHistos, saveFormats=[])
    p.setLuminosity(GetLumi(datasetsMgr))


    #=========================================================================================
    # Start Fit process
    #=========================================================================================
    binLabels = ["Inclusive"]
    moduleInfoString = opts.optMode
    FITMIN = 0
    FITMAX = 1500

    manager = QCDNormalization.QCDNormalizationManagerDefault(binLabels, opts.mcrab, moduleInfoString)

    #=========================================================================================
    # Create templates (EWK fakes, EWK genuine, QCD; data template is created by manager)
    #=========================================================================================
    template_EWKFakeB_Baseline     = manager.createTemplate("EWKFakeB_Baseline")
    template_EWKFakeB_Inverted     = manager.createTemplate("EWKFakeB_Inverted")
    template_EWKInclusive_Baseline = manager.createTemplate("EWKInclusive_Baseline")
    template_EWKInclusive_Inverted = manager.createTemplate("EWKInclusive_Inverted")
    template_QCD_Baseline          = manager.createTemplate("QCD_Baseline")
    template_QCD_Inverted          = manager.createTemplate("QCD_Inverted")
        
    #=========================================================================================
    # Inclusive EWK
    #=========================================================================================
    # par[0]*ROOT.Math.crystalball_function(x[0], par[1], par[2], par[3], par[4]) +
    # par[5]*ROOT.TMath.BreitWigner(x[0], par[6], par[7]) +
    # (1-par[0]-par[5])*ROOT.TMath.Landau(x[0], par[8], par[9])

    #template_EWKInclusive_Baseline.setFitter(QCDNormalization.FitFunction("EWKFunction", boundary=200, norm=1, rejectPoints=0), FITMIN, FITMAX)
    template_EWKInclusive_Baseline.setFitter(QCDNormalization.FitFunction("EWKFunction", boundary=200, norm=1, rejectPoints=0), FITMIN, 800)
    template_EWKInclusive_Baseline.setDefaultFitParam(defaultInitialValue=None,
                                                      #                   p0   p1     p2     p3     p4   p5    p6    p7      p8      p9
                                                      #defaultLowerLimit=[0.0, 150.0,  0.0, -5.0, 0.0, 0.0, 150.0,   0.0, 100.0,    0.0],
                                                      #defaultUpperLimit=[1.0, 300.0, 50.0,  0.0, 1.0, 1.0, 200.0, 100.0, 200.0,  100.0])
                                                      defaultLowerLimit=[0.0, 160.0,   0.0, -1.0, 0.0],
                                                      defaultUpperLimit=[1.0, 180.0,  60.0,  0.0, 1e6])

    #=========================================================================================
    # Note that the same function is used for QCD only and QCD+EWK fakes
    #=========================================================================================
    #par[0]*ROOT.Math.lognormal_pdf(x[0], par[1], par[2]) + par[3]*ROOT.TMath.Exp(-x[0]*par[4]) + (1-par[0]-par[3])*ROOT.TMath.Gaus(x[0], par[5], part[6])
    
    # 0 =   0.8489  for coeff of lognorm
    # 1 =   1.42978 for logshape
    # 2 = 238.546   for logmean
    #
    # 3 =   0.047   for coeff of exp
    # 4 =  -0.0048  for exp
    #
    # 5 =  45.486   for gaus sigma
    # 6 = 204.6     for gaus mean

    #my lognormal is of the form:
    #lognorm(x,m0,k) = exp{-[log(x/m0)]^2/[2*log(k)]^2}/sqrt[2pi*log(k)*x]
    #and differs than the Math::lognormal_pdf parametrization which takes as arguments lognormal(x,m,s,x0)
    #where m = log(m0) and s=log(k)
    #TMath::LogNormal  return Math::lognormal_pdf
    #my exponential is   exp(x*a)  so the sign comes from the fit
    #and my gaussian is exp[-0.5*mean*mean/(sigma*sigma)]

    # Double_t LogNormal(x, sigma, theta = 0, m = 1)

    #template_QCD_Inverted.setFitter(QCDNormalization.FitFunction("QCDFunction", boundary=350, norm=1), FITMIN, FITMAX)
    template_QCD_Inverted.setFitter(QCDNormalization.FitFunction("QCDFunction", boundary=350, norm=1), 100, 800)
    template_QCD_Inverted.setDefaultFitParam(defaultInitialValue=None,
                                             defaultLowerLimit=[0.0, 0.0, 200.0, 0.0, -0.1, 200.0,  0.0],
                                             defaultUpperLimit=[1.0, 2.0, 400.0, 0.1, +0.0, 300.0, 60.0])


    #=========================================================================================
    # Set histograms to the templates
    #=========================================================================================
    template_EWKFakeB_Baseline.setHistogram(EWK_baseline, "Inclusive")
    template_EWKFakeB_Inverted.setHistogram(EWK_inverted, "Inclusive")
    template_EWKInclusive_Baseline.setHistogram(EWK_baseline, "Inclusive")
    template_EWKInclusive_Inverted.setHistogram(EWK_inverted, "Inclusive")
    template_QCD_Baseline.setHistogram(QCD_baseline, "Inclusive")
    template_QCD_Inverted.setHistogram(QCD_inverted, "Inclusive")

    #=========================================================================================
    # Make plots of templates
    #=========================================================================================
    manager.plotTemplates()
    
    #=========================================================================================
    # Fit individual templates to histogram "data_baseline", with custom fit options
    #=========================================================================================
    fitOptions = "R B L W M Q"
    manager.calculateNormalizationCoefficients(Data_baseline, fitOptions, FITMIN, FITMAX)
            
    # Append analysisType to histogram name
    saveName = histoName

    # Draw the histograms #alex
    plots.drawPlot(p, saveName, **GetHistoKwargs(histoName) ) #the "**" unpacks the kwargs_ 

    _kwargs = {"lessThan": True}
    p.addCutBoxAndLine(cutValue=173.21, fillColor=ROOT.kRed, box=False, line=True, **_kwargs)

    # Save plot in all formats
    #SavePlot(p, saveName, os.path.join(opts.saveDir, "Templates") ) 
    return
Example #20
0
def main(opts):

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    style.setOptStat(True)
    style.setGridX(False)
    style.setGridY(False)

    # If user does not define optimisation mode do all of them
    if opts.optMode == None:
        if len(optList) < 1:
            optList.append("")
        else:
            pass
        optModes = optList
    else:
        optModes = [opts.optMode]

    # For-loop: All optimisation modes
    for opt in optModes:
        opts.optMode = opt

        # Setup & configure the dataset manager
        datasetsMgr = GetDatasetsFromDir(opts)
        datasetsMgr.updateNAllEventsToPUWeighted()
        datasetsMgr.loadLuminosities()  # from lumi.json

        if opts.verbose:
            datasetsMgr.PrintCrossSections()
            datasetsMgr.PrintLuminosities()

        # Set/Overwrite cross-sections
        for d in datasetsMgr.getAllDatasets():
            if "ChargedHiggs" in d.getName():
                datasetsMgr.getDataset(d.getName()).setCrossSection(1.0)

        # Print dataset information before removing anything?
        datasetsMgr.PrintInfo()

        # Determine integrated Lumi before removing data
        if "Data" in datasetsMgr.getAllDatasetNames():
            intLumi = datasetsMgr.getDataset("Data").getLuminosity()

        # Remove datasets
        filterKeys = ["TTW"]
        for key in filterKeys:
            datasetsMgr.remove(
                filter(lambda name: key in name,
                       datasetsMgr.getAllDatasetNames()))
        else:
            intLumi = 35920

        for key in filterKeys:
            datasetsMgr.remove(
                filter(lambda name: key in name,
                       datasetsMgr.getAllDatasetNames()))

        # Re-order datasets
        datasetOrder = []
        haveQCD = False
        for d in datasetsMgr.getAllDatasets():
            if "QCD" in d.getName():
                haveQCD = True
            datasetOrder.append(d.getName())
        datasetsMgr.selectAndReorder(datasetOrder)

        # Define the mapping histograms in numerator->denominator pairs
        VariableList = [
            "LdgTop_Pt",
        ]

        minRunRange, maxRunRange, runRange = GetRunRange(datasetsMgr)

        # Merge histograms (see NtupleAnalysis/python/tools/plots.py)
        plots.mergeRenameReorderForDataMC(datasetsMgr)

        datasets_ = datasetsMgr.getAllDatasets()
        dataset_Data = datasetsMgr.getDataDatasets()
        dataset_MC = datasetsMgr.getMCDatasets()

        # Print dataset information
        datasetsMgr.PrintInfo()

        # For-loop: All numerator-denominator pairs
        counter = 0
        nPlots = len(VariableList)

        for var in VariableList:
            histoN = "AfterAllSelections_" + var
            histoD = "AfterStandardSelections_" + var
            numerator = os.path.join(opts.folder, histoN)
            denominator = os.path.join(opts.folder, histoD)

            counter += 1
            msg = "{:<9} {:>3} {:<1} {:<3} {:<50}".format(
                "Histogram", "%i" % counter, "/", "%s:" % (nPlots),
                "%s" % (var))
            Print(ShellStyles.SuccessStyle() + msg + ShellStyles.NormalStyle(),
                  counter == 1)

            for dataset in datasets_:

                if dataset.isMC():
                    n = dataset.getDatasetRootHisto(numerator)
                    n.normalizeToLuminosity(intLumi)
                    num = n.getHistogram()
                    d = dataset.getDatasetRootHisto(denominator)
                    d.normalizeToLuminosity(intLumi)
                    den = d.getHistogram()

                else:
                    num = dataset.getDatasetRootHisto(numerator).getHistogram()
                    den = dataset.getDatasetRootHisto(
                        denominator).getHistogram()

                x_bins = num.GetXaxis().GetNbins()

                i = 1
                while i < x_bins:
                    xvalue = num.GetXaxis().GetBinLowEdge(
                        i) + 0.5 * num.GetXaxis().GetBinWidth(i)
                    if xvalue < 20:
                        my_bin = i
                    i += 1

                my_xvalue = num.GetXaxis().GetBinUpEdge(
                    my_bin) + 0.5 * num.GetXaxis().GetBinWidth(my_bin)
                total = den.Integral(0, x_bins)  #my_bin
                selected = num.Integral(0, x_bins)  #my_bin

            plotName = "Eff_%s" % (var)
            # Get Efficiency Plots
            _kwargs = GetHistoKwargs(var, opts)
            eff_Data = GetEfficiency(datasetsMgr, dataset_Data, numerator,
                                     denominator, intLumi)
            eff_MC = GetEfficiency(datasetsMgr, dataset_MC, numerator,
                                   denominator, intLumi)

            # Apply Styles
            styles.dataStyle.apply(eff_Data)
            styles.qcdStyle.apply(eff_MC)
            # Create the plot
            p = plots.ComparisonPlot(
                histograms.HistoGraph(eff_Data, "eff_Data", "p", "P"),
                histograms.HistoGraph(eff_MC, "eff_MC", "p", "P"),
                saveFormats=[])
            # Define the legend entries
            p.histoMgr.setHistoLegendLabelMany({
                "eff_Data": "Data",
                "eff_MC": "QCD"
            })

            # Append in list
            myList = []
            myList.append(
                histograms.HistoGraph(eff_Data, plots._legendLabels["Data"],
                                      "lp", "P"))

            p.setLuminosity(intLumi)
            _kwargs["ratio"] = True
            _kwargs["opts"] = {
                "xmin": 0.0,
                "xmax": 600.0,
                "ymin": 0.0,
                "ymax": 0.16,
                "ymaxfactor": 1.8
            }
            _kwargs["cutBoxY"] = {
                "cutValue": 1.10,
                "fillColor": ROOT.kGray + 1,
                "fillStyle": 3001,
                "box": False,
                "line": True,
                "greaterThan": True,
                "mainCanvas": False,
                "ratioCanvas": True,
                "mirror": True
            }
            plots.drawPlot(p, plotName, **_kwargs)

            # Draw
            savePath = os.path.join(opts.saveDir, opts.optMode)
            SavePlot(p, plotName, savePath, saveFormats=[".png", ".pdf", ".C"])

    # Save results in JSON
    name = opts.mcrab.split("_")[-3]
    name = name.replace(opts.analysisName, "")
    jsonName = "topMisID_" + name + "_TopMassCut400.json"
    analysis = opts.analysisName
    label = "2016"
    plotDir = os.path.join(opts.folder, jsonName)
    pythonWriter.addParameters(plotDir, label, runRange, opts.intLumi,
                               eff_Data)
    pythonWriter.addMCParameters(label, eff_MC)
    fileName_json = jsonName
    pythonWriter.writeJSON(fileName_json)

    return
def PlotSignalBackground(datasetsMgr, hG, hF, intLumi):
    kwargs = {}
    _kwargs = {}
    #kwargs = GetHistoKwargs(hG, opts)

    if opts.normaliseToOne:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToOne=True,
                          saveFormats=[],
                          **_kwargs)
    else:
        pG = plots.MCPlot(datasetsMgr,
                          hG,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)
        pF = plots.MCPlot(datasetsMgr,
                          hF,
                          normalizeToLumi=intLumi,
                          saveFormats=[],
                          **_kwargs)

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _format = "%0.2f"
    _xlabel = None
    logY = False
    _opts = {"ymin": 1e-3, "ymaxfactor": 1.0}

    if "mass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "M (%s)" % _units

    if "trijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{top} (%s)" % _units
        #_cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 805  #1005

    if "bjetmass" in hG.lower():
        _xlabel = "m_{b-tagged jet} (%s)" % _units
        _opts["xmax"] = 50
    if "bjetldgjet_mass" in hG.lower():
        _xlabel = "m_{b, ldg jet} (%s)" % _units
    if "bjetsubldgjet_mass" in hG.lower():
        _xlabel = "m_{b-tagged, subldg jet} (%s)" % _units

    if "jet_mass" in hG.lower():
        _opts["xmax"] = 750

    if "mult" in hG.lower():
        _format = "%0.0f"
        _xlabel = "Leading jet mult"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet mult"

    if "cvsl" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet CvsL"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CvsL"

    if "axis2" in hG.lower():
        _format = "%0.3f"
        _xlabel = "Leading jet axis2"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet axis2"

    if "dijetmass" in hG.lower():
        _units = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{W} (%s)" % _units
        _opts["xmax"] = 600

    if "trijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{t}"

    if "dijetptdr" in hG.lower():
        _opts["xmax"] = 800
        _format = "%0.0f"
        _xlabel = "p_{T}#Delta R_{W}"

    if "dgjetptd" in hG.lower():
        _format = "%0.2f"
        _xlabel = "Leading jet p_{T}D"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet p_{T}D"

    else:
        pass
    '''
    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
        else:
            _xlabel = "b-tagged jet CSV"
    '''

    if logY:
        yMaxFactor = 2.0
    else:
        yMaxFactor = 1.2

    _opts["ymaxfactor"] = yMaxFactor
    if opts.normaliseToOne:
        _opts["ymin"] = 1e-3
    else:
        _opts["ymin"] = 1e0

    if "bdisc" in hG.lower():
        _format = "%0.2f"
        if "subldg" in hG.lower():
            _xlabel = "Subleading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        elif "ldg" in hG.lower():
            _xlabel = "Leading jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.06}
        else:
            _xlabel = "b-tagged jet CSV"
            _opts = {"ymin": 1e-3, "ymax": 0.35}

    myList = []
    # Customise styling
    pG.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pF.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    '''
    plots.drawPlot(pG, 
                   hG,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    plots.drawPlot(pF, 
                   hF,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   cutBox       = _cutBox,
                   )

    '''

    dataset = datasetsMgr.getDataset("TT")

    h = dataset.getDatasetRootHisto(hG)
    h.normalizeToOne()
    HG = h.getHistogram()

    h = dataset.getDatasetRootHisto(hF)
    h.normalizeToOne()
    HF = h.getHistogram()

    altSignalBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kAzure + 9,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kAzure + 9,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kAzure + 9)
    ])
    altBackgroundBDTGStyle = styles.StyleCompound([
        styles.StyleMarker(markerSize=1.2,
                           markerColor=ROOT.kRed - 4,
                           markerSizes=None,
                           markerStyle=ROOT.kFullDiamond),
        styles.StyleLine(lineColor=ROOT.kRed - 4,
                         lineStyle=ROOT.kSolid,
                         lineWidth=3),
        styles.StyleFill(fillColor=ROOT.kRed - 4, fillStyle=3001)
    ])

    p = plots.ComparisonPlot(
        histograms.Histo(HF, "Fake", "p", "P"),
        histograms.Histo(HG, "Genuine", "pl", "PL"),
    )
    p.histoMgr.setHistoLegendLabelMany({
        "Fake": "Unmatched",
        "Genuine": "Truth-matched"
    })
    p.histoMgr.forHisto("Fake", altBackgroundBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Fake", "LP")
    p.histoMgr.setHistoLegendStyle("Fake", "LP")  #F

    p.histoMgr.forHisto("Genuine", altSignalBDTGStyle)
    p.histoMgr.setHistoDrawStyle("Genuine", "HIST")
    p.histoMgr.setHistoLegendStyle("Genuine", "LP")  #LP

    #HF = dataset.getDatasetRootHisto(hF).getHistogram()
    #HG = dataset.getDatasetRootHisto(hG).getHistogram()

    histoG = histograms.Histo(HG, "TT", "Signal")
    histoG.setIsDataMC(isData=False, isMC=True)

    histoF = histograms.Histo(HF, "QCD", "Signal")
    histoF.setIsDataMC(isData=False, isMC=True)

    styleG = styles.ttStyle
    styleF = styles.signalStyleHToTB1000

    #hG = histograms.Histo(histoBkg3, legNameBkg3, "F", "HIST9" )
    #background3_histo = histograms.Histo(histoBkg3, legNameBkg3, "F", "HIST9" )

    styleG.apply(HG)
    styleF.apply(HF)

    myList.append(histoG)
    myList.append(histoF)

    #myList.append(HF)
    #myList.append(HG)

    #    p = plots.PlotBase(datasetRootHistos=myList, saveFormats=[])

    _kwargs = {
        "xlabel": _xlabel,
        "ylabel": "Arbitrary Units / %s" % (_format),
        "ratioYlabel": "Ratio ",
        "ratio": False,
        "ratioInvert": False,
        "stackMCHistograms": False,
        "addMCUncertainty": False,
        "addLuminosityText": False,
        "addCmsText": True,
        "cmsExtraText": "Preliminary",
        "opts": {
            "ymin": 0.0,
            "ymaxfactor": 1.1
        },
        "opts2": {
            "ymin": 0.6,
            "ymax": 1.5
        },
        "log": False,
        #"createLegend"     : {"x1": 0.5, "y1": 0.75, "x2": 0.9, "y2": 0.9},
        "createLegend": {
            "x1": 0.58,
            "y1": 0.65,
            "x2": 0.92,
            "y2": 0.82
        },
    }
    '''
    plots.drawPlot(p, 
                   hG,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = logY,
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.58, "y1": 0.65, "x2": 0.92, "y2": 0.82},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymaxfactor": 1.1},
                   cutBox       = _cutBox,
                   )


    '''
    # Save plot in all formats
    saveName = hG.split("/")[-1]
    #plots.drawPlot(p, saveName, **_kwargs)
    savePath = os.path.join(opts.saveDir, "HplusMasses",
                            hG.split("/")[0], opts.optMode)
    plots.drawPlot(p, savePath, **_kwargs)
    SavePlot(p,
             saveName,
             os.path.join(opts.saveDir, opts.optMode),
             saveFormats=[".png", ".pdf", ".C"])

    #SavePlot(p, saveName, savePath)

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

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

    return
Example #22
0
def DataEwkQcd(datasetsMgr, histoName, analysisType):
    '''
    Create plots with "Data", "QCD=Data-EWK", and "EWK" on the same canvas
    Mostly for sanity checks and visualisation purposes
    '''
    Verbose(
        "Plotting histogram %s for Data, EWK, QCD for %s" %
        (histoName, analysisType), True)

    # Sanity check
    IsBaselineOrInverted(analysisType)

    # Define histogram names (full path)
    h1 = "topSelection_Baseline/%s" % (histoName)
    h2 = "topSelection_Inverted/%s" % (histoName)

    # Create plot object for Data
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, "Data", h1, h2))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())
    # Create plot object for EWK
    p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, "EWK", h1, h2))
    p2.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get Data and EWK histos
    Data = p1.histoMgr.getHisto(analysisType +
                                "-Data").getRootHisto().Clone(analysisType +
                                                              "-Data")
    EWK = p2.histoMgr.getHisto(analysisType +
                               "-EWK").getRootHisto().Clone(analysisType +
                                                            "-EWK")

    # Create QCD histo: QCD = Data-EWK
    QCD = p1.histoMgr.getHisto(analysisType +
                               "-Data").getRootHisto().Clone(analysisType +
                                                             "-QCD")
    QCD.Add(EWK, -1)

    # Create the final plot object. The Data is treated as the reference histo.
    # All other histograms are compared with respect to that.
    p = plots.ComparisonManyPlot(Data, [QCD, EWK], saveFormats=[])
    p.setLuminosity(GetLumi(datasetsMgr))

    # Apply histo styles
    p.histoMgr.forHisto(analysisType + "-Data", styles.getDataStyle())
    p.histoMgr.forHisto(analysisType + "-QCD", styles.getQCDLineStyle())
    p.histoMgr.forHisto(analysisType + "-EWK", styles.getAltEWKStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle(analysisType + "-Data", "P")
    p.histoMgr.setHistoLegendStyle(analysisType + "-Data", "P")
    p.histoMgr.setHistoDrawStyle(analysisType + "-QCD", "LP")
    p.histoMgr.setHistoLegendStyle(analysisType + "-QCD", "LP")
    p.histoMgr.setHistoDrawStyle(analysisType + "-EWK", "HIST")
    p.histoMgr.setHistoLegendStyle(analysisType + "-EWK", "LFP")
    # p.histoMgr.setHistoLegendStyleAll("LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        analysisType + "-Data": "Data",
        analysisType + "-QCD": "QCD",  #=Data-EWK",
        analysisType + "-EWK": "EWK",
        # analysisType + "-Data": "%s (Data)" % (analysisType),
        # analysisType + "-QCD" : "%s (QCD)"  % (analysisType),
        # analysisType + "-EWK" : "%s (EWK)"  % (analysisType),
    })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _opts = {"ymin": 1e0, "ymaxfactor": 10}
    _format = "%0.0f"

    if "mass" in histoName.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c^{2}"
        if "TrijetMass" in histoName:
            _cutBox = {
                "cutValue": 173.21,
                "fillColor": 16,
                "box": False,
                "line": True,
                "greaterThan": True
            }
        if "DijetMass" in histoName:
            _cutBox = {
                "cutValue": 80.399,
                "fillColor": 16,
                "box": False,
                "line": True,
                "greaterThan": True
            }
    if "pt" in histoName.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c"
    if "eta" in histoName.lower():
        _rebinX = 2
        _format = "%0.2f"
        _cutBox = {
            "cutValue": 0.,
            "fillColor": 16,
            "box": False,
            "line": True,
            "greaterThan": True
        }
    if "bdisc" in histoName.lower():
        _format = "%0.2f"
        _rebinX = 1
    if "chisqr" in histoName.lower():
        _format = "%0.0f"
        _rebinX = 10
        if "after" in histoName.lower():
            _rebinX = 1
            _opts["xmax"] = 20.0
    if "tetrajet" in histoName.lower():
        if "mass" in histoName.lower():
            _rebinX = 10
            _opts["xmax"] = 3500.0

    else:
        pass

    histoName += "_" + analysisType
    plots.drawPlot(
        p,
        histoName,
        ylabel="Events /  %s" % (_format),
        log=True,
        rebinX=_rebinX,
        cmsExtraText="Preliminary",
        createLegend={
            "x1": 0.75,
            "y1": 0.76,
            "x2": 0.92,
            "y2": 0.92
        },
        opts=_opts,
        opts2={
            "ymin": 1e-5,
            "ymax": 1e0
        },
        ratio=True,
        ratioInvert=False,
        ratioYlabel="Ratio",
        cutBox=_cutBox,
    )

    # Save plot in all formats
    SavePlot(p,
             histoName,
             os.path.join(opts.saveDir, "DataEwkQcd"),
             saveFormats=[".png"])
    return
def analyze(analysis=None):

    paths = [sys.argv[1]]

    if not analysis == None:
        datasets = dataset.getDatasetsFromMulticrabDirs(
            paths,
            analysisName=analysis,
            excludeTasks="Silver|GluGluHToTauTau_M125")
    else:
        datasets = dataset.getDatasetsFromMulticrabDirs(
            paths, excludeTasks="Silver|GluGluHToTauTau_M125")
        analysis = datasets.getAllDatasets()[0].getAnalysisName()

#    datasetsDY = None
    datasetsDY = dataset.getDatasetsFromMulticrabDirs(
        paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL")
    #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="GluGluHToTauTau_M125|TTJets")
    datasetsH125 = None
    #    datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125",emptyDatasetsAsNone=True)
    #    datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125")

    datasets.loadLuminosities()

    style = tdrstyle.TDRStyle()

    dataset1 = datasets.getDataDatasets()
    dataset2 = dataset1
    #    dataset2 = datasets.getMCDatasets()
    if not datasetsDY == None:
        dataset2 = datasetsDY.getMCDatasets()

    eff1 = getEfficiency(dataset1)
    eff2 = getEfficiency(dataset2)
    if isinstance(datasetsH125, dataset.DatasetManager):
        eff3 = getEfficiency(datasetsH125.getMCDatasets())

    styles.dataStyle.apply(eff1)
    styles.mcStyle.apply(eff2)
    eff1.SetMarkerSize(1)
    #    eff2.SetMarkerSize(1.5)
    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3)
        eff3.SetMarkerSize(1.5)
        eff3.SetMarkerColor(4)
        eff3.SetLineColor(4)


#    p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"),
#                             histograms.HistoGraph(eff2, "eff2", "p", "P"))

    if isinstance(datasetsH125, dataset.DatasetManager):
        p = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1, "eff1", "p", "P"), [
                histograms.HistoGraph(eff2, "eff2", "p", "P"),
                histograms.HistoGraph(eff3, "eff3", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"),
                                 histograms.HistoGraph(eff2, "eff2", "p", "P"))
    else:
        p = plots.PlotBase([histograms.HistoGraph(eff1, "eff1", "p", "P")])

    fit("Data", p, eff1, 20, 200)
    fit("MC", p, eff2, 20, 200)
    if isinstance(datasetsH125, dataset.DatasetManager):
        fit("H125", p, eff3, 20, 200)

    opts = {"ymin": 0, "ymax": 1.1}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    #    moveLegend = {"dx": -0.55, "dy": -0.15, "dh": -0.1}
    moveLegend = {"dx": -0.2, "dy": -0.5, "dh": -0.1}
    name = "TauMET_" + analysis + "_DataVsMC_PFTauPt"

    legend1 = "Data"
    #    legend2 = "MC (DY)"
    legend2 = "Simulation"
    legend3 = "MC (H125)"
    createRatio = False
    p.histoMgr.setHistoLegendLabelMany({"eff1": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2})
        createRatio = True
    if isinstance(datasetsH125, dataset.DatasetManager):
        p.histoMgr.setHistoLegendLabelMany({
            "eff1": legend1,
            "eff2": legend2,
            "eff3": legend3
        })

    if createRatio:
        p.createFrame(os.path.join(plotDir, name),
                      createRatio=createRatio,
                      opts=opts,
                      opts2=opts2)
    else:
        p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    #    p.getFrame().GetXaxis().SetTitle("#tau-jet p_{T} (GeV/c)")
    p.getFrame().GetXaxis().SetTitle("#tau_{h} p_{T} (GeV/c)")
    if createRatio:
        p.getFrame2().GetYaxis().SetTitle("Ratio")
        p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    #    label = analysis.split("_")[len(analysis.split("_")) -1]
    label = "2016"

    histograms.addText(0.5, 0.53, label, 17)
    runRange = datasets.loadRunRange()
    histograms.addText(0.5, 0.46, "Runs " + runRange, 17)

    p.draw()
    lumi = 0.0
    for d in datasets.getDataDatasets():
        print "luminosity", d.getName(), d.getLuminosity()
        lumi += d.getLuminosity()
    print "luminosity, sum", lumi
    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)

    pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1)
    pythonWriter.addMCParameters(label, eff2)

    pythonWriter.writeJSON(
        os.path.join(plotDir, "tauLegTriggerEfficiency_" + label + ".json"))

    #    if not createRatio:
    #        sys.exit()

    #########################################################################

    eff1eta = getEfficiency(dataset1, "NumeratorEta", "DenominatorEta")
    eff2eta = getEfficiency(dataset2, "NumeratorEta", "DenominatorEta")
    if isinstance(datasetsH125, dataset.DatasetManager):
        eff3eta = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorEta",
                                "DenominatorEta")

    styles.dataStyle.apply(eff1eta)
    styles.mcStyle.apply(eff2eta)
    eff1eta.SetMarkerSize(1)

    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3eta)
        eff3eta.SetMarkerSize(1.5)
        eff3eta.SetMarkerColor(4)
        eff3eta.SetLineColor(4)

    if isinstance(datasetsH125, dataset.DatasetManager):
        p_eta = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), [
                histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"),
                histograms.HistoGraph(eff3eta, "eff3eta", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p_eta = plots.ComparisonPlot(
            histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"),
            histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"))
    else:
        p_eta = plots.PlotBase(
            [histograms.HistoGraph(eff1eta, "eff1eta", "p", "P")])

    p_eta.histoMgr.setHistoLegendLabelMany({"eff1eta": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p_eta.histoMgr.setHistoLegendLabelMany({
            "eff1eta": legend1,
            "eff2eta": legend2
        })
    if isinstance(datasetsH125, dataset.DatasetManager):
        p_eta.histoMgr.setHistoLegendLabelMany({
            "eff1eta": legend1,
            "eff2eta": legend2,
            "eff3eta": legend3
        })

    name = "TauMET_" + analysis + "_DataVsMC_PFTauEta"

    if createRatio:
        p_eta.createFrame(os.path.join(plotDir, name),
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)
    else:
        p_eta.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)

    moveLegendEta = {"dx": -0.5, "dy": -0.65, "dh": -0.1}
    p_eta.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegendEta))

    p_eta.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    p_eta.getFrame().GetXaxis().SetTitle("#tau-jet #eta")
    if createRatio:
        p_eta.getFrame2().GetYaxis().SetTitle("Ratio")
        p_eta.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.38, label, 17)
    histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17)

    p_eta.draw()
    histograms.addStandardTexts(lumi=lumi)

    p_eta.save(formats)

    #########################################################################

    eff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi")
    eff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi")
    if isinstance(datasetsH125, dataset.DatasetManager):
        eff3phi = getEfficiency(datasetsH125.getMCDatasets(), "NumeratorPhi",
                                "DenominatorPhi")

    styles.dataStyle.apply(eff1phi)
    styles.mcStyle.apply(eff2phi)
    eff1phi.SetMarkerSize(1)

    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3phi)
        eff3phi.SetMarkerSize(1.5)
        eff3phi.SetMarkerColor(4)
        eff3phi.SetLineColor(4)

    if isinstance(datasetsH125, dataset.DatasetManager):
        p_phi = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), [
                histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"),
                histograms.HistoGraph(eff3phi, "eff3phi", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p_phi = plots.ComparisonPlot(
            histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"),
            histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"))
    else:
        p_phi = plots.PlotBase(
            [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")])

    p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p_phi.histoMgr.setHistoLegendLabelMany({
            "eff1phi": legend1,
            "eff2phi": legend2
        })
    if isinstance(datasetsH125, dataset.DatasetManager):
        p_phi.histoMgr.setHistoLegendLabelMany({
            "eff1phi": legend1,
            "eff2phi": legend2,
            "eff3phi": legend3
        })

    name = "TauMET_" + analysis + "_DataVsMC_PFTauPhi"

    if createRatio:
        p_phi.createFrame(os.path.join(plotDir, name),
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)
    else:
        p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)

    moveLegendPhi = {"dx": -0.5, "dy": -0.65, "dh": -0.1}
    p_phi.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegendPhi))

    p_phi.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    p_phi.getFrame().GetXaxis().SetTitle("#tau-jet #phi")
    if createRatio:
        p_phi.getFrame2().GetYaxis().SetTitle("Ratio")
        p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.38, label, 17)
    histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17)

    p_phi.draw()
    histograms.addStandardTexts(lumi=lumi)

    p_phi.save(formats)

    #########################################################################

    namePU = "TauMET_" + analysis + "_DataVsMC_nVtx"

    eff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU")
    eff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU")

    styles.dataStyle.apply(eff1PU)
    styles.mcStyle.apply(eff2PU)
    eff1PU.SetMarkerSize(1)
    eff2PU.SetMarkerSize(1.5)

    if isinstance(datasetsDY, dataset.DatasetManager):
        pPU = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1PU, "eff1", "p", "P"),
            [histograms.HistoGraph(eff2PU, "eff2", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({
            "eff1": legend1,
            "eff2": legend2
        })
    else:
        pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1})

    optsPU = {"ymin": 0.01, "ymax": 1.0}
    createRatio = False
    if createRatio:
        pPU.createFrame(os.path.join(plotDir, namePU),
                        createRatio=True,
                        opts=optsPU,
                        opts2=opts2)
    else:
        pPU.createFrame(os.path.join(plotDir, namePU),
                        opts=optsPU,
                        opts2=opts2)

    moveLegend = {"dx": -0.5, "dy": -0.5, "dh": -0.1}
    pPU.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegend))
    #    if createRatio:
    #        pPU.getPad1().SetLogy(True)
    #    else:
    #        pPU.getPad().SetLogy(True)

    pPU.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices")
    if createRatio:
        pPU.getFrame2().GetYaxis().SetTitle("Ratio")
        pPU.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.53, label, 17)
    histograms.addText(0.2, 0.46, "Runs " + datasets.loadRunRange(), 17)

    pPU.draw()
    histograms.addStandardTexts(lumi=lumi)

    pPU.save(formats)

    #########################################################################
    """
    hName = "Pull"
#    hName = "Sub"
    namePull = "TauMET_"+analysis+"_DataVsMC_"+hName+"s"

    plots.mergeRenameReorderForDataMC(datasets)
    datasets.merge("MC", ["TT","WJets","DYJetsToLL","SingleTop","QCD"], keepSources=True)

    drh1 = datasets.getDataset("Data").getDatasetRootHisto(hName)
    drh2 = datasets.getDataset("MC").getDatasetRootHisto(hName)
    drh1.normalizeToOne()
    drh2.normalizeToOne()
    pull1 = drh1.getHistogram()
    pull2 = drh2.getHistogram()

    if isinstance(datasetsH125,dataset.DatasetManager):
        plots.mergeRenameReorderForDataMC(datasetsH125)
        drh3 = datasetsH125.getMCDatasets()[0].getDatasetRootHisto(hName)
        drh3.normalizeToOne()
        pull3 = drh3.getHistogram()

    styles.dataStyle.apply(pull1)
    styles.mcStyle.apply(pull2)
    pull1.SetMarkerSize(1)

    if isinstance(datasetsH125,dataset.DatasetManager):
        styles.mcStyle.apply(pull3)
        pull3.SetMarkerSize(1.5)
        pull3.SetMarkerColor(4)
        pull3.SetLineColor(4)

    if isinstance(datasetsH125,dataset.DatasetManager):
        p_pull = plots.ComparisonManyPlot(histograms.Histo(pull1, "pull1", "p", "P"),
                                         [histograms.Histo(pull2, "pull2", "p", "P"),
                                          histograms.Histo(pull3, "pull3", "p", "P")])
    else:
        p_pull = plots.ComparisonPlot(histograms.Histo(pull1, "pull1", "p", "P"),
                                      histograms.Histo(pull2, "pull2", "p", "P"))

    p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2})
    if isinstance(datasetsH125,dataset.DatasetManager):
        p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2, "pull3": legend3})

    p_pull.createFrame(os.path.join(plotDir, namePull), createRatio=True, opts=opts, opts2=opts2)
    moveLegendPull = {"dx": -0.5, "dy": -0.35, "dh": -0.1}
    p_pull.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPull))

    p_pull.getFrame().GetYaxis().SetTitle("Arbitrary units")
#    p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T} - #tau-jet p_{T} (GeV/c)")
    p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T}/ #tau-jet p_{T} - 1")                                                                                                                                     
    p_pull.getFrame2().GetYaxis().SetTitle("Ratio")
    p_pull.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.75, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.68, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.2, 0.61, "Runs "+runRange, 17)

    p_pull.draw()

    histograms.addStandardTexts(lumi=lumi)
    p_pull.save(formats)
    """
    #########################################################################
    print "Output written in", plotDir
Example #24
0
def analyze(analysis=None):

    paths = [sys.argv[1]]

    if (len(sys.argv) == 3):
        howAnalyse = sys.argv[2]
    else:
        howAnalyse = "--fit"
#        howAnalyse = "--bin"

    if not analysis == None:
        datasets = dataset.getDatasetsFromMulticrabDirs(
            paths,
            analysisName=analysis,
            excludeTasks="Silver|GluGluHToTauTau_M125")
    else:
        datasets = dataset.getDatasetsFromMulticrabDirs(
            paths, excludeTasks="Silver|GluGluHToTauTau_M125")
        analysis = datasets.getAllDatasets()[0].getAnalysisName()

#    datasetsDY = None
    datasetsDY = dataset.getDatasetsFromMulticrabDirs(
        paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL")
    datasetsDY = dataset.getDatasetsFromMulticrabDirs(
        paths, analysisName=analysis, includeOnlyTasks="DYJetsToLL|Zprime")
    #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="GluGluHToTauTau_M125|TTJets")
    datasetsH125 = None
    #    datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125",emptyDatasetsAsNone=True)
    #    datasetsH125 = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="GluGluHToTauTau_M125")

    datasets.loadLuminosities()

    style = tdrstyle.TDRStyle()

    dataset1 = datasets.getDataDatasets()
    dataset2 = dataset1
    #    dataset2 = datasets.getMCDatasets()
    if not datasetsDY == None:
        dataset2 = datasetsDY.getMCDatasets()

    histeff1 = getEfficiency(dataset1)
    histeff2 = getEfficiency(dataset2)

    eff1 = convert2TGraph(histeff1)
    eff2 = convert2TGraph(histeff2)

    if isinstance(datasetsH125, dataset.DatasetManager):
        histeff3 = getEfficiency(datasetsH125.getMCDatasets())
        eff3 = convert2TGraph(histeff3)

    styles.dataStyle.apply(eff1)
    styles.mcStyle.apply(eff2)
    eff1.SetMarkerSize(1)
    #    eff2.SetMarkerSize(1.5)
    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3)
        eff3.SetMarkerSize(1.5)
        eff3.SetMarkerColor(4)
        eff3.SetLineColor(4)

#    p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"),
#                             histograms.HistoGraph(eff2, "eff2", "p", "P"))

    if isinstance(datasetsH125, dataset.DatasetManager):
        p = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1, "eff1", "p", "P"), [
                histograms.HistoGraph(eff2, "eff2", "p", "P"),
                histograms.HistoGraph(eff3, "eff3", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"),
                                 histograms.HistoGraph(eff2, "eff2", "p", "P"))
    else:
        p = plots.PlotBase([histograms.HistoGraph(eff1, "eff1", "p", "P")])

## FIT FUNCTIONS: "Sigmoid", "Error", "Gompertz", "Richard","Crystal" ##
## FIT TYPES: binned max likelihood: "ML" , Chi2-fit: "Chi" ##

    if (howAnalyse == "--fit"):
        datafit = fitType("Data", p, histeff1, eff1, 20, 500, "Crystal", "ML")
        mcfit = fitType("MC", p, histeff2, eff2, 20, 500, "Crystal", "ML")

    if isinstance(datasetsH125, dataset.DatasetManager):
        fit("H125", p, eff3, 20, 200)

    opts = {"ymin": 0, "ymax": 1.1}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    #    moveLegend = {"dx": -0.55, "dy": -0.15, "dh": -0.1}
    moveLegend = {"dx": -0.2, "dy": -0.5, "dh": -0.1}
    name = "TauMET_" + analysis + "_DataVsMC_PFTauPt"

    legend1 = "Data"
    #    legend2 = "MC (DY)"
    legend2 = "Simulation"
    legend3 = "MC (H125)"
    createRatio = False
    p.histoMgr.setHistoLegendLabelMany({"eff1": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2})
        createRatio = True
    if isinstance(datasetsH125, dataset.DatasetManager):
        p.histoMgr.setHistoLegendLabelMany({
            "eff1": legend1,
            "eff2": legend2,
            "eff3": legend3
        })

    if createRatio:
        p.createFrame(os.path.join(plotDir, name),
                      createRatio=createRatio,
                      opts=opts,
                      opts2=opts2)
    else:
        p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    #    p.getFrame().GetXaxis().SetTitle("#tau-jet p_{T} (GeV/c)")
    p.getFrame().GetXaxis().SetTitle("#tau_{h} p_{T} (GeV/c)")
    if createRatio:
        p.getFrame2().GetYaxis().SetTitle("Ratio")
        p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    #    histograms.addText(0.5, 0.6, "VLooseIsoPFTau120_Trk50_eta2p1", 17)
    #    histograms.addText(0.5, 0.6, "VLooseIsoPFTau140_Trk50_eta2p1", 17)
    #    label = analysis.split("_")[len(analysis.split("_")) -1]
    label = "2016"

    histograms.addText(0.5, 0.53, label, 17)
    runRange = datasets.loadRunRange()
    histograms.addText(0.5, 0.46, "Runs " + runRange, 17)

    p.draw()

    ## does the ratio of the fits
    if (howAnalyse == "--fit"):
        funcRatio = ROOT.TH1F("", "", 480, 20, 500)
        for i in range(0, 480):
            ratio = datafit.Eval(i + 20 - 1) / mcfit.Eval(i + 20 - 1)
            funcRatio.SetBinContent(i, ratio)
        p.getPad().GetCanvas().cd(2)
        funcRatio.Draw("SAME")
        p.getPad().GetCanvas().cd(1)

##
    lumi = 0.0
    for d in datasets.getDataDatasets():
        if (d.getName() != "SingleMuon_Run2016F_03Feb2017_v1_277932_278800"
                and d.getName() !=
                "SingleMuon_Run2016C_03Feb2017_v1_275656_276283"):
            print "luminosity", d.getName(), d.getLuminosity()
            lumi += d.getLuminosity()
    print "luminosity, sum", lumi
    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)

    if (howAnalyse == "--fit"):
        pythonWriter.addParameters(plotDir, label, runRange, lumi, datafit)
        pythonWriter.addMCParameters(label, mcfit)
        pythonWriter.writeJSON(
            os.path.join(plotDir,
                         "tauLegTriggerEfficiency_" + label + "_fit.json"))
        pythonWriter.__init__()  #need to clear the Json arrays


#    if (howAnalyse == "--bin"):
    pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1)
    pythonWriter.addMCParameters(label, eff2)
    pythonWriter.writeJSON(
        os.path.join(plotDir,
                     "tauLegTriggerEfficiency_" + label + "_bin.json"))

    #    if not createRatio:
    #        sys.exit()

    #########################################################################

    histeff1eta = getEfficiency(dataset1, "NumeratorEta", "DenominatorEta")
    histeff2eta = getEfficiency(dataset2, "NumeratorEta", "DenominatorEta")

    eff1eta = convert2TGraph(histeff1eta)
    eff2eta = convert2TGraph(histeff2eta)

    if isinstance(datasetsH125, dataset.DatasetManager):
        histeff3eta = getEfficiency(datasetsH125.getMCDatasets(),
                                    "NumeratorEta", "DenominatorEta")
        eff3eta = convert2TGraph(histeff3eta)
    styles.dataStyle.apply(eff1eta)
    styles.mcStyle.apply(eff2eta)
    eff1eta.SetMarkerSize(1)

    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3eta)
        eff3eta.SetMarkerSize(1.5)
        eff3eta.SetMarkerColor(4)
        eff3eta.SetLineColor(4)

    if isinstance(datasetsH125, dataset.DatasetManager):
        p_eta = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"), [
                histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"),
                histograms.HistoGraph(eff3eta, "eff3eta", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p_eta = plots.ComparisonPlot(
            histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"),
            histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"))
    else:
        p_eta = plots.PlotBase(
            [histograms.HistoGraph(eff1eta, "eff1eta", "p", "P")])

    p_eta.histoMgr.setHistoLegendLabelMany({"eff1eta": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p_eta.histoMgr.setHistoLegendLabelMany({
            "eff1eta": legend1,
            "eff2eta": legend2
        })
    if isinstance(datasetsH125, dataset.DatasetManager):
        p_eta.histoMgr.setHistoLegendLabelMany({
            "eff1eta": legend1,
            "eff2eta": legend2,
            "eff3eta": legend3
        })

    name = "TauMET_" + analysis + "_DataVsMC_PFTauEta"

    if createRatio:
        p_eta.createFrame(os.path.join(plotDir, name),
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)
    else:
        p_eta.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)

    moveLegendEta = {"dx": -0.5, "dy": -0.65, "dh": -0.1}
    p_eta.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegendEta))

    p_eta.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    p_eta.getFrame().GetXaxis().SetTitle("#tau-jet #eta")
    if createRatio:
        p_eta.getFrame2().GetYaxis().SetTitle("Ratio")
        p_eta.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.38, label, 17)
    histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17)

    p_eta.draw()
    histograms.addStandardTexts(lumi=lumi)

    p_eta.save(formats)

    #########################################################################

    histeff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi")
    histeff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi")

    eff1phi = convert2TGraph(histeff1phi)
    eff2phi = convert2TGraph(histeff2phi)

    if isinstance(datasetsH125, dataset.DatasetManager):
        histeff3phi = getEfficiency(datasetsH125.getMCDatasets(),
                                    "NumeratorPhi", "DenominatorPhi")
        eff3phi = convert2TGraph(histeff3phi)

    styles.dataStyle.apply(eff1phi)
    styles.mcStyle.apply(eff2phi)
    eff1phi.SetMarkerSize(1)

    if isinstance(datasetsH125, dataset.DatasetManager):
        styles.mcStyle.apply(eff3phi)
        eff3phi.SetMarkerSize(1.5)
        eff3phi.SetMarkerColor(4)
        eff3phi.SetLineColor(4)

    if isinstance(datasetsH125, dataset.DatasetManager):
        p_phi = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"), [
                histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"),
                histograms.HistoGraph(eff3phi, "eff3phi", "p", "P")
            ])
    elif isinstance(datasetsDY, dataset.DatasetManager):
        p_phi = plots.ComparisonPlot(
            histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"),
            histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"))
    else:
        p_phi = plots.PlotBase(
            [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")])

    p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1})
    if isinstance(datasetsDY, dataset.DatasetManager):
        p_phi.histoMgr.setHistoLegendLabelMany({
            "eff1phi": legend1,
            "eff2phi": legend2
        })
    if isinstance(datasetsH125, dataset.DatasetManager):
        p_phi.histoMgr.setHistoLegendLabelMany({
            "eff1phi": legend1,
            "eff2phi": legend2,
            "eff3phi": legend3
        })

    name = "TauMET_" + analysis + "_DataVsMC_PFTauPhi"

    if createRatio:
        p_phi.createFrame(os.path.join(plotDir, name),
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)
    else:
        p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)

    moveLegendPhi = {"dx": -0.5, "dy": -0.65, "dh": -0.1}
    p_phi.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegendPhi))

    p_phi.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    p_phi.getFrame().GetXaxis().SetTitle("#tau-jet #phi")
    if createRatio:
        p_phi.getFrame2().GetYaxis().SetTitle("Ratio")
        p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.46, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.38, label, 17)
    histograms.addText(0.2, 0.31, "Runs " + datasets.loadRunRange(), 17)

    p_phi.draw()
    histograms.addStandardTexts(lumi=lumi)

    p_phi.save(formats)

    #########################################################################

    namePU = "TauMET_" + analysis + "_DataVsMC_nVtx"

    histeff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU")
    histeff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU")

    eff1PU = convert2TGraph(histeff1PU)
    eff2PU = convert2TGraph(histeff2PU)

    styles.dataStyle.apply(eff1PU)
    styles.mcStyle.apply(eff2PU)
    eff1PU.SetMarkerSize(1)
    eff2PU.SetMarkerSize(1.5)

    if isinstance(datasetsDY, dataset.DatasetManager):
        pPU = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1PU, "eff1", "p", "P"),
            [histograms.HistoGraph(eff2PU, "eff2", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({
            "eff1": legend1,
            "eff2": legend2
        })
    else:
        pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1})

    optsPU = {"ymin": 0.01, "ymax": 1.0}
    createRatio = False
    if createRatio:
        pPU.createFrame(os.path.join(plotDir, namePU),
                        createRatio=True,
                        opts=optsPU,
                        opts2=opts2)
    else:
        pPU.createFrame(os.path.join(plotDir, namePU),
                        opts=optsPU,
                        opts2=opts2)

    moveLegend = {"dx": -0.5, "dy": -0.5, "dh": -0.1}
    pPU.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegend))
    #    if createRatio:
    #        pPU.getPad1().SetLogy(True)
    #    else:
    #        pPU.getPad().SetLogy(True)

    pPU.getFrame().GetYaxis().SetTitle("HLT tau efficiency")
    pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices")
    if createRatio:
        pPU.getFrame2().GetYaxis().SetTitle("Ratio")
        pPU.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.53, label, 17)
    histograms.addText(0.2, 0.46, "Runs " + datasets.loadRunRange(), 17)

    pPU.draw()
    histograms.addStandardTexts(lumi=lumi)

    pPU.save(formats)

    #########################################################################
    """
    hName = "Pull"
#    hName = "Sub"
    namePull = "TauMET_"+analysis+"_DataVsMC_"+hName+"s"

    plots.mergeRenameReorderForDataMC(datasets)
    datasets.merge("MC", ["TT","WJets","DYJetsToLL","SingleTop","QCD"], keepSources=True)

    drh1 = datasets.getDataset("Data").getDatasetRootHisto(hName)
    drh2 = datasets.getDataset("MC").getDatasetRootHisto(hName)
    drh1.normalizeToOne()
    drh2.normalizeToOne()
    pull1 = drh1.getHistogram()
    pull2 = drh2.getHistogram()

    if isinstance(datasetsH125,dataset.DatasetManager):
        plots.mergeRenameReorderForDataMC(datasetsH125)
        drh3 = datasetsH125.getMCDatasets()[0].getDatasetRootHisto(hName)
        drh3.normalizeToOne()
        pull3 = drh3.getHistogram()

    styles.dataStyle.apply(pull1)
    styles.mcStyle.apply(pull2)
    pull1.SetMarkerSize(1)

    if isinstance(datasetsH125,dataset.DatasetManager):
        styles.mcStyle.apply(pull3)
        pull3.SetMarkerSize(1.5)
        pull3.SetMarkerColor(4)
        pull3.SetLineColor(4)

    if isinstance(datasetsH125,dataset.DatasetManager):
        p_pull = plots.ComparisonManyPlot(histograms.Histo(pull1, "pull1", "p", "P"),
                                         [histograms.Histo(pull2, "pull2", "p", "P"),
                                          histograms.Histo(pull3, "pull3", "p", "P")])
    else:
        p_pull = plots.ComparisonPlot(histograms.Histo(pull1, "pull1", "p", "P"),
                                      histograms.Histo(pull2, "pull2", "p", "P"))

    p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2})
    if isinstance(datasetsH125,dataset.DatasetManager):
        p_pull.histoMgr.setHistoLegendLabelMany({"pull1": legend1, "pull2": legend2, "pull3": legend3})

    p_pull.createFrame(os.path.join(plotDir, namePull), createRatio=True, opts=opts, opts2=opts2)
    moveLegendPull = {"dx": -0.5, "dy": -0.35, "dh": -0.1}
    p_pull.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegendPull))

    p_pull.getFrame().GetYaxis().SetTitle("Arbitrary units")
#    p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T} - #tau-jet p_{T} (GeV/c)")
    p_pull.getFrame().GetXaxis().SetTitle("HLT #tau p_{T}/ #tau-jet p_{T} - 1")                                                                                                                                     
    p_pull.getFrame2().GetYaxis().SetTitle("Ratio")
    p_pull.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.2, 0.75, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.2, 0.68, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.2, 0.61, "Runs "+runRange, 17)

    p_pull.draw()

    histograms.addStandardTexts(lumi=lumi)
    p_pull.save(formats)
    """
    #########################################################################
    print "Output written in", plotDir
Example #25
0
def DoPlots(datasetsMgr, histoName):
    analysisType = "Inverted"

    # Get the Inclusive (Data, EWK)
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, histoName, analysisType))
    p1.histoMgr.normalizeMCToLuminosity(
        datasetsMgr.getDataset("Data").getLuminosity())

    # Get histos
    inverted_Data = p1.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Inverted-Data")
    inverted_EWK = p1.histoMgr.getHisto("EWK").getRootHisto().Clone(
        "Inverted-EWK")
    inverted_QCD = p1.histoMgr.getHisto("Data").getRootHisto().Clone(
        "Inverted-QCD")

    # Normalize histograms to unit area
    inverted_Data.Scale(1.0 / inverted_QCD.Integral())
    inverted_QCD.Scale(1.0 / inverted_QCD.Integral())
    inverted_EWK.Scale(1.0 / inverted_EWK.Integral())

    # Create the final plot object (Cannot subtract EWK from Data since the trigger in the MC samples is NOT prescaled. In data it is)
    p = plots.ComparisonManyPlot(inverted_Data, [inverted_EWK], saveFormats=[])
    #p = plots.PlotBase([inverted_Data], saveFormats=[])

    # Apply styles
    p.histoMgr.forHisto("Inverted-Data", styles.getDataStyle())
    #p.histoMgr.forHisto("Inverted-QCD"  , styles.getInvertedLineStyle() )
    p.histoMgr.forHisto("Inverted-EWK", styles.getAltEWKStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Inverted-Data", "AP")
    #p.histoMgr.setHistoDrawStyle("Inverted-QCD" , "HIST")
    p.histoMgr.setHistoDrawStyle("Inverted-EWK", "AP")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("Inverted-Data", "P")
    #p.histoMgr.setHistoLegendStyle("Inverted-QCD" , "L")
    p.histoMgr.setHistoLegendStyle("Inverted-EWK", "P")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        "Inverted-Data": "Data",
        "Inverted-EWK": "EWK",
        #"Inverted-QCD" : "QCD=Data-EWK",
    })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    #_opts   = {"ymin": 1e-4, "ymaxfactor": 2.0}
    _opts = {"ymin": 1e-4, "ymax": 1e-1}
    _xlabel = None
    _units = "GeV/c^{2}"
    _xlabel = "m_{jjb} (%s)" % _units
    _ylabel = "Arbitrary Units / %0.0f %s " % (inverted_QCD.GetBinWidth(0),
                                               _units)
    _cutBox = {
        "cutValue": 173.21,
        "fillColor": 16,
        "box": False,
        "line": True,
        "greaterThan": True
    }
    _opts["xmax"] = 1500.0

    # Complains (SysError in <TFile::TFile>: file ...)
    if 0:
        plots.drawPlot(p,
                       histoName,
                       xlabel=_xlabel,
                       ylabel=_ylabel,
                       log=True,
                       rebinX=_rebinX,
                       cmsExtraText="Preliminary",
                       createLegend={
                           "x1": 0.62,
                           "y1": 0.78,
                           "x2": 0.92,
                           "y2": 0.92
                       },
                       opts=_opts)

    if 1:
        plots.drawPlot(
            p,
            histoName,
            xlabel=_xlabel,
            ylabel=_ylabel,
            log=True,
            rebinX=_rebinX,
            cmsExtraText="Preliminary",
            createLegend={
                "x1": 0.62,
                "y1": 0.78,
                "x2": 0.92,
                "y2": 0.92
            },
            opts=_opts,
            opts2={
                "ymin": 0.0,
                "ymax": 2.0
            },
            ratio=True,
            ratioInvert=False,
            ratioYlabel="Ratio",
            cutBox=_cutBox,
        )
    # Save to ROOT file
    inverted_QCD.SaveAs("Inverted_QCD.root")

    # Save plot in all formats
    SavePlot(p, histoName, os.path.join(opts.saveDir, "Test", opts.optMode))
    return
Example #26
0
def BaselineVsInvertedPlots(datasetsMgr, histoName, analysisType="Inverted"):
    
    # Sanity check
    IsBaselineOrInverted(analysisType)
    
    # Get the Data (Inclusive)
    p1 = plots.ComparisonPlot(*getHistos(datasetsMgr, "Data",  histoName, analysisType))
    p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Get the EWK (GenuineB)                              
    defaultFolder  = "ForFakeBMeasurement"
    genuineBFolder = defaultFolder + "EWKGenuineB"
    fakeBFolder    = defaultFolder + "EWKFakeB"
    histoNameNew   = histoName.replace( defaultFolder, genuineBFolder)
    p2 = plots.ComparisonPlot(*getHistos(datasetsMgr, "EWK", histoNameNew, analysisType) )
    p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Get Data histos    
    baseline_Data = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-Data")
    inverted_Data = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-Data")

    # Get EWK histos
    baseline_EWKGenuineB = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline-EWKGenuineB")
    inverted_EWKGenuineB = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted-EWKGenuineB")

    # Get FakeB (Baseline): FakeB = Data-EWKGenuineB
    baseline_FakeB = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-FakeB")
    baseline_FakeB.Add(baseline_EWKGenuineB, -1)

    # Get FakeB (Inverted): FakeB = Data-EWKGenuineB
    inverted_FakeB = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-FakeB")
    inverted_FakeB.Add(inverted_EWKGenuineB, -1)

    # Normalize histograms to unit area
    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=[]) #[".C", ".png", ".pdf"])
    p.setLuminosity(GetLumi(datasetsMgr))
        
    # Apply styles
    p.histoMgr.forHisto("Baseline-FakeB" , styles.getBaselineStyle() )
    p.histoMgr.forHisto("Inverted-FakeB" , styles.getInvertedStyle() )

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Baseline-FakeB", "AP")
    p.histoMgr.setHistoDrawStyle("Inverted-FakeB", "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("Baseline-FakeB", "LP")
    p.histoMgr.setHistoLegendStyle("Inverted-FakeB", "F")
    # p.histoMgr.setHistoLegendStyleAll("LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            "Baseline-FakeB" : "FakeB (Baseline)",
            "Inverted-FakeB" : "FakeB (Inverted)",
            })

    # Draw the histograms
    _cutBox = None
    _rebinX = 1
    _opts   = {"ymin": 1e-4, "ymaxfactor": 2.0}
    _format = "%0.0f"
    _xlabel = None

    if "dijetm" in histoName.lower():
        _rebinX = 2
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jj} (%s)" % (_units)
        _cutBox = {"cutValue": 80.399, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 400.0
    if "trijetm" in histoName.lower():
        _rebinX = 5
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjb} (%s)" % _units
        _cutBox = {"cutValue": 173.21, "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmax"] = 1500.0
    if "pt" in histoName.lower():
        _rebinX = 2
        _format = "%0.0f GeV/c"
    if "eta" in histoName.lower():
        _format = "%0.2f"
        _cutBox = {"cutValue": 0., "fillColor": 16, "box": False, "line": True, "greaterThan": True}
        _opts["xmin"] = -3.0
        _opts["xmax"] = +3.0
    if "deltaeta" in histoName.lower():
        _format = "%0.2f"
        _opts["xmin"] =  0.0
        _opts["xmax"] = 6.0
    if "bdisc" in histoName.lower():
        _format = "%0.2f"
    if "tetrajetm" in histoName.lower():
        _rebinX = 10
        _units  = "GeV/c^{2}"
        _format = "%0.0f " + _units
        _xlabel = "m_{jjjb} (%s)" % (_units)
        _opts["xmax"] = 3500.0

    plots.drawPlot(p, histoName,  
                   xlabel       = _xlabel,
                   ylabel       = "Arbitrary Units / %s" % (_format),
                   log          = True, 
                   rebinX       = _rebinX, cmsExtraText = "Preliminary", 
                   createLegend = {"x1": 0.62, "y1": 0.78, "x2": 0.92, "y2": 0.92},
                   opts         = _opts,
                   opts2        = {"ymin": 0.6, "ymax": 1.4},
                   ratio        = True,
                   ratioInvert  = False, 
                   ratioYlabel  = "Ratio",
                   cutBox       = _cutBox,
                   )
    # Save plot in all formats
    SavePlot(p, histoName, os.path.join(opts.saveDir, "BaselineVsInverted", opts.optMode) ) 
    return
Example #27
0
def PlotTemplates(datasetsMgr, histoName, analysisType="Inverted"):                  
    Verbose("Plotting EWK Vs QCD unity-normalised histograms")

    # Create comparison plot
    p1 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "Data", histoName, "Baseline"),
        getHisto(datasetsMgr, "Data", histoName, "Inverted")
        )
    p1.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())
    
    defaultFolder  = "ForFakeBMeasurement"
    genuineBFolder = defaultFolder + "EWKGenuineB"
    fakeBFolder    = defaultFolder + "EWKFakeB"
    histoNameNew   = histoName.replace( defaultFolder, genuineBFolder)
    p2 = plots.ComparisonPlot(
        getHisto(datasetsMgr, "EWK", histoNameNew, "Baseline"),
        getHisto(datasetsMgr, "EWK", histoNameNew, "Inverted")
        )
    p2.histoMgr.normalizeMCToLuminosity(datasetsMgr.getDataset("Data").getLuminosity())

    # Get EWKGenuineB histos
    EWKGenuineB_baseline = p2.histoMgr.getHisto("Baseline-EWK").getRootHisto().Clone("Baseline-EWKGenuineB")
    EWKGenuineB_inverted = p2.histoMgr.getHisto("Inverted-EWK").getRootHisto().Clone("Inverted-EWKGenuineB")

    # Get FakeB histos
    FakeB_baseline = p1.histoMgr.getHisto("Baseline-Data").getRootHisto().Clone("Baseline-FakeB")
    FakeB_baseline.Add(EWKGenuineB_baseline, -1)
    FakeB_inverted = p1.histoMgr.getHisto("Inverted-Data").getRootHisto().Clone("Inverted-FakeB")
    FakeB_inverted.Add(EWKGenuineB_inverted, -1)

    # Normalize histograms to unit area
    EWKGenuineB_baseline.Scale(1.0/EWKGenuineB_baseline.Integral())    
    EWKGenuineB_inverted.Scale(1.0/EWKGenuineB_inverted.Integral())
    FakeB_baseline.Scale(1.0/FakeB_baseline.Integral())
    FakeB_inverted.Scale(1.0/FakeB_inverted.Integral())
    
    # Create the final plot object
    comparisonList = [EWKGenuineB_baseline]
    p = plots.ComparisonManyPlot(FakeB_inverted, comparisonList, saveFormats=[])
    p.setLuminosity(GetLumi(datasetsMgr))
        
    # Apply styles
    p.histoMgr.forHisto("Baseline-EWKGenuineB", styles.getBaselineStyle() )
    p.histoMgr.forHisto("Inverted-FakeB"      , styles.getInvertedStyle() )

    # Set draw style
    p.histoMgr.setHistoDrawStyle("Baseline-EWKGenuineB", "AP")
    p.histoMgr.setHistoDrawStyle("Inverted-FakeB"      , "HIST")

    # Set legend style
    p.histoMgr.setHistoLegendStyle("Baseline-EWKGenuineB", "LP")
    p.histoMgr.setHistoLegendStyle("Inverted-FakeB"        , "LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
            "Baseline-EWKGenuineB": "GenuineB (EWK)", # (Baseline)
            "Inverted-FakeB"      : "FakeB", # (Inverted)
            })

    # Append analysisType to histogram name
    saveName = histoName

    # Draw the histograms #alex
    plots.drawPlot(p, saveName, **GetHistoKwargs(histoName) ) #the "**" unpacks the kwargs_ 

    # _kwargs = {"lessThan": True}
    # p.addCutBoxAndLine(cutValue=200, fillColor=ROOT.kRed, box=False, line=True, ***_kwargs)
    
    # Add text
    text = opts.optMode.replace("OptChiSqrCutValue", "#chi^{2} #leq ")
    histograms.addText(0.21, 0.85, text)

    # Save plot in all formats
    saveDir = os.path.join(opts.saveDir, "Templates", opts.optMode)
    SavePlot(p, saveName, saveDir, saveFormats = [".C", ".png", ".pdf"])
    return
Example #28
0
def main(argv):

    dirs = []
    if len(sys.argv) < 2:
        usage()

    dirs.append(sys.argv[1])

    QCDInvertedNormalization = QCDInvertedNormalizationFactors.QCDInvertedNormalization
    QCDInvertedNormalizationFilteredEWKFakeTaus = QCDInvertedNormalizationFactorsFilteredEWKFakeTaus.QCDInvertedNormalization
    analysis = "signalAnalysisInvertedTau"
    optModes = []
    #optModes.append("OptQCDTailKillerZeroPlus")
    optModes.append("OptQCDTailKillerLoosePlus")
    optModes.append("OptQCDTailKillerMediumPlus")
    optModes.append("OptQCDTailKillerTightPlus")
    #optModes.append("OptQCDTailKillerVeryTightPlus")
    #optModes.append("OnlyGenuineMCTausFalse")
    #optModes.append("OnlyGenuineMCTausTrue")

    #Optimal: 0.8, 0.82, 0.9
    #w1_list = [0.8, 0.82, 0.84, 0.87]
    #w1_list = [0.8, 0.82, 0.9, 1]
    w1_list = [0.9]

    defaultBinning = systematics.getBinningForPlot("shapeTransverseMass")

    diff_opt = []
    for optMode in optModes:
        diff_list = []
        for w1 in w1_list:
            var_values = []
            nom_values = []
            w2 = 1 - w1

            color = 1

            #signal

            dirs_signal = ["../../SignalAnalysis_140605_143702/"]
            datasets_signal = dataset.getDatasetsFromMulticrabDirs(
                dirs_signal,
                dataEra=dataEra,
                searchMode=searchMode,
                analysisName=analysis.replace("InvertedTau", ""),
                optimizationMode=optMode)

            datasets_signal.updateNAllEventsToPUWeighted()
            datasets_signal.loadLuminosities()

            datasets_signal.remove(
                filter(lambda name: "TTToHplus" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "HplusTB" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "Hplus_taunu_t-channel" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "Hplus_taunu_tW-channel" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "TTJets_SemiLept" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "TTJets_FullLept" in name,
                       datasets_signal.getAllDatasetNames()))
            datasets_signal.remove(
                filter(lambda name: "TTJets_Hadronic" in name,
                       datasets_signal.getAllDatasetNames()))

            plots.mergeRenameReorderForDataMC(datasets_signal)

            datasets_signal.merge(
                "EWK",
                ["TTJets", "WJets", "DYJetsToLL", "SingleTop", "Diboson"])

            mtplot_signalfaketaus = plots.DataMCPlot(
                datasets_signal, "shapeEWKFakeTausTransverseMass")
            mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto(
                "EWK").getRootHisto().Clone("shapeEWKFakeTausTransverseMass")
            mt_signalfaketaus.SetName("BaselineFakeTaus")

            myBinning = [0, 20, 40, 60, 80, 100, 120, 140, 160, 200, 400]
            myArray = array.array("d", myBinning)

            fitBinning = []
            for i in range(0, 45):
                fitBinning.append(i * 10)
            fitArray = array.array("d", fitBinning)

            mt_baseline = mt_signalfaketaus

            #rangeMin = mt_signalfaketaus.GetXaxis().GetXmin()
            #rangeMax = mt_signalfaketaus.GetXaxis().GetXmax()
            #theFit = TF1('theFit',FitFunction(),rangeMin,rangeMax,4)
            #theFit.SetParLimits(0,0.5,10000)
            #theFit.SetParLimits(1,90,10000)
            #theFit.SetParLimits(2,30,10000)
            #theFit.SetParLimits(3,0.001,10000)
            #mt_signalfaketaus.Fit(theFit,"R")
            #theFit.SetRange(mt_signalfaketaus.GetXaxis().GetXmin(),mt_signalfaketaus.GetXaxis().GetXmax())
            #theFit.SetLineStyle(2)
            #theFit.SetLineColor(4)
            #theFit.SetLineWidth(3)
            #theFit.Draw()
            #mt_corr = theFit.GetHistogram()
            #mt_corr = mt_corr.Rebin(len(fitBinning)-1,"",fitArray)
            #mt_corr.Scale(mt_baseline.GetMaximum()/mt_corr.GetMaximum())

            for HISTONAME in histoNameList:
                var = False
                if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                    var = True
                datasets = dataset.getDatasetsFromMulticrabDirs(
                    dirs,
                    dataEra=dataEra,
                    searchMode=searchMode,
                    analysisName=analysis,
                    optimizationMode=optMode)

                datasets.updateNAllEventsToPUWeighted()
                datasets.loadLuminosities()

                plots.mergeRenameReorderForDataMC(datasets)

                datasets.merge(
                    "EWK",
                    ["TTJets", "WJets", "DYJetsToLL", "SingleTop", "Diboson"])

                histonames = datasets.getDataset("Data").getDirectoryContent(
                    HISTONAME)

                bins = []
                for histoname in histonames:
                    binname = histoname.replace(HISTONAME, "")
                    if not binname == "Inclusive":
                        bins.append(binname)

                for i, bin in enumerate(bins):
                    mtplot = plots.DataMCPlot(
                        datasets, HISTONAME + "/" + HISTONAME + bin)

                    if i == 0:
                        mt = mtplot.histoMgr.getHisto(
                            "Data").getRootHisto().Clone(HISTONAME + "/" +
                                                         HISTONAME + bin)
                        mt_ewk = mtplot.histoMgr.getHisto(
                            "EWK").getRootHisto().Clone(HISTONAME + "/" +
                                                        HISTONAME + bin)
                        mtn = mtplot.histoMgr.getHisto(
                            "Data").getRootHisto().Clone(HISTONAME + "/" +
                                                         HISTONAME + bin)
                        mtn_ewk = mtplot.histoMgr.getHisto(
                            "EWK").getRootHisto().Clone(HISTONAME + "/" +
                                                        HISTONAME + bin)

                        if var:
                            legendName = "QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)"
                        else:
                            legendName = "QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)"
                        legendName = legendName.replace("Plus", "")
                        mt.SetName(legendName)
                        mt.SetLineColor(color)
                        mt.Add(mt_ewk, -1)
                        mtn.Add(mtn_ewk, -1)
                        mtn.Scale(QCDInvertedNormalization[str(i)])

                        if var:
                            scale = w1 * QCDInvertedNormalizationFilteredEWKFakeTaus[
                                str(
                                    i
                                )] + w2 * QCDInvertedNormalizationFilteredEWKFakeTaus[
                                    str(i) + "EWK_FakeTaus"]
                            mt.Scale(scale)
                        else:
                            mt.Scale(QCDInvertedNormalization[str(i)])
                        color += 1
                        if color == 5:
                            color += 1
                    else:
                        h = mtplot.histoMgr.getHisto(
                            "Data").getRootHisto().Clone(HISTONAME + "/" +
                                                         HISTONAME + bin)
                        mt_ewk = mtplot.histoMgr.getHisto(
                            "EWK").getRootHisto().Clone(HISTONAME + "/" +
                                                        HISTONAME + bin)
                        hn = mtplot.histoMgr.getHisto(
                            "Data").getRootHisto().Clone(HISTONAME + "/" +
                                                         HISTONAME + bin)
                        mtn_ewk = mtplot.histoMgr.getHisto(
                            "EWK").getRootHisto().Clone(HISTONAME + "/" +
                                                        HISTONAME + bin)

                        h.Add(mt_ewk, -1)
                        hn.Add(mtn_ewk, -1)
                        hn.Scale(QCDInvertedNormalization[str(i)])

                        if var:
                            scale = w1 * QCDInvertedNormalizationFilteredEWKFakeTaus[
                                str(
                                    i
                                )] + w2 * QCDInvertedNormalizationFilteredEWKFakeTaus[
                                    str(i) + "EWK_FakeTaus"]
                            h.Scale(scale)
                        else:
                            h.Scale(QCDInvertedNormalization[str(i)])
                        mt.Add(h)
                        mtn.Add(hn)

                #mt = mt.Rebin(len(myBinning)-1,"",myArray)
                #mt_corr = mt_corr.Rebin(len(myBinning)-1,"",myArray)

                if not var:
                    mt.Add(mt_baseline)
                    #mt.Add(mt_corr)

                #myBinning = []
                #for i in range(0,11):
                #    myBinning.append(20*i)
                #myBinning.append(400)

                #myArray = array.array("d",defaultBinning)
                mt = mt.Rebin(len(myBinning) - 1, "", myArray)

                for i in range(0, mt.GetSize()):
                    if var:
                        var_values.append(mt.GetBinContent(i))
                    else:
                        nom_values.append(mt.GetBinContent(i))

                if var:
                    #mt.SetLineStyle(2)
                    var_hist = mt
                else:
                    #mt.SetLineStyle(2)
                    nom_hist = mt

                style = tdrstyle.TDRStyle()

                #gStyle.SetOptStat(1101)
                #mt_data.SetStats(1)
                #gPad.Update()
                bins = [0, 390, 400]
                arr = array.array("d", bins)
                mtn = mtn.Rebin(len(bins) - 1, "", arr)
                plot_data = plots.PlotBase()
                plot_data.histoMgr.appendHisto(histograms.Histo(mtn, "Data"))
                plot_data.createFrame("Data_" + HISTONAME + "_" + optMode +
                                      "_" + str(w1))
                plot_data.draw()
                plot_data.save()

            plot = plots.ComparisonPlot(nom_hist, var_hist)
            plot.createFrame(optMode.replace(
                "Opt", "Mt_" + "w1=" + str(w1) + "_w2=" + str(w2) +
                "_DataDrivenVsMC_"),
                             createRatio=True)

            moveLegend = {"dx": -0.295, "dy": 0.05}
            plot.setLegend(
                histograms.moveLegend(histograms.createLegend(), **moveLegend))
            histograms.addText(
                0.65, 0.20,
                optMode.replace("OptQCDTailKiller",
                                "R_{BB} ").replace("Plus", ""), 25)
            histograms.addCmsPreliminaryText()
            histograms.addEnergyText()
            lumi = datasets.getDataset("Data").getLuminosity()
            histograms.addLuminosityText(x=None, y=None, lumi=lumi)

            plot.draw()
            plot.save()

            num = 0
            denom = 0
            #print var_values
            for i in range(0, len(nom_values)):
                num += var_values[i] * (var_values[i] - nom_values[i])**2
                denom += var_values[i]
            diff = num / denom
            diff_list.append(diff)
        diff_opt.append(diff_list)

    print w1_list, '\n'
    for i in range(0, len(diff_opt)):
        print diff_opt[i]
        print w1_list[diff_opt[i].index(min(diff_opt[i]))]

    mt_baseline = mt_baseline.Rebin(len(bins) - 1, "", arr)
    plot_bft = plots.PlotBase()
    plot_bft.histoMgr.appendHisto(histograms.Histo(mt_baseline, "baseline"))
    #mt_corr.Scale(2)
    #plot_bft.histoMgr.appendHisto(histograms.Histo(mt_corr,"test"))

    #rangeMin = mt_signalfaketaus.GetXaxis().GetXmin()
    #rangeMax = mt_signalfaketaus.GetXaxis().GetXmax()
    #theFit = TF1('theFit',FitFunction(),rangeMin,rangeMax,4)
    #theFit.SetParLimits(0,0.5,10000)
    #theFit.SetParLimits(1,90,10000)
    #theFit.SetParLimits(2,30,10000)
    #theFit.SetParLimits(3,0.001,10000)
    #mt_signalfaketaus.Fit(theFit,"R")
    #theFit.SetRange(mt_signalfaketaus.GetXaxis().GetXmin(),mt_signalfaketaus.GetXaxis().GetXmax())
    #theFit.SetLineStyle(2)
    #theFit.SetLineColor(4)
    #theFit.SetLineWidth(3)
    #theFit.Draw()

    #mt_corr = theFit.GetHistogram()
    #mt_corr = mt_corr.Rebin(len(fitBinning)-1,"",fitArray)
    #mt_corr.Scale(mt_baseline.GetMaximum()/mt_corr.GetMaximum())
    #plot_bft.histoMgr.appendHisto(histograms.Histo(mt_corr,"test"))
    #plot_bft.histoMgr.appendHisto(histograms.Histo(theFit,"theFit"))

    plot_bft.createFrame('BaselineFakeTaus')
    plot_bft.draw()
    plot_bft.save()
Example #29
0
def doSinglePlot(hbase, hinv, myDir, histoName, luminosity):
    def rebin(h, name):
        myBinning = []
        if name.startswith("MT"):
            myBinning = systematics.getBinningForPlot("shapeTransverseMass")
        elif name.startswith("INVMASS"):
            myBinning = systematics.getBinningForPlot("shapeInvariantMass")
        else:
            raise Exception("Unknown binning information")
        myArray = array.array("d", myBinning)
        # Rebin and move under/overflow bins to visible bins
        h = h.Rebin(len(myBinning) - 1, "", myArray)
        h.SetBinContent(1, h.GetBinContent(0) + h.GetBinContent(1))
        h.SetBinError(1,
                      math.sqrt(h.GetBinContent(0)**2 + h.GetBinContent(1)**2))
        h.SetBinContent(
            h.GetNbinsX() + 1,
            h.GetBinContent(h.GetNbinsX() + 1) +
            h.GetBinContent(h.GetNbinsX() + 2))
        h.SetBinError(
            h.GetNbinsX() + 1,
            math.sqrt(
                h.GetBinError(h.GetNbinsX() + 1)**2 +
                h.GetBinError(h.GetNbinsX() + 2)**2))
        h.SetBinContent(0, 0.0)
        h.SetBinError(0, 0.0)
        h.SetBinContent(h.GetNbinsX() + 2, 0.0)
        h.SetBinError(h.GetNbinsX() + 2, 0.0)
        return h

    hbase.SetLineColor(ROOT.kBlack)
    hinv.SetLineColor(ROOT.kRed)
    # Rebin
    hbase = rebin(hbase, histoName)
    hinv = rebin(hinv, histoName)
    # Normalize
    print "baseline: %.1f events, inverted %.1f events" % (hbase.Integral(),
                                                           hinv.Integral())
    #hbase.Scale(1.0 / hbase.Integral())
    #hinv.Scale(1.0 / hinv.Integral())
    # Plot
    baseHisto = histograms.Histo(hbase,
                                 "Isolated",
                                 drawStyle="HIST",
                                 legendStyle="l")
    invHisto = histograms.Histo(hinv,
                                "Anti-isolated",
                                drawStyle="HIST",
                                legendStyle="l")
    plot = plots.ComparisonPlot(baseHisto, invHisto)
    plot.setLuminosity(luminosity)
    plot.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineWidth(3))
    myPlotName = "%s/QCDInv_ClosureTest_%s" % (myDir, histoName)
    myParams = {}
    myParams["ylabel"] = "Events/#Deltam_{T}, normalized to 1"
    myParams["log"] = False
    myParams["opts2"] = {"ymin": 0.0, "ymax": 2.0}
    myParams["opts"] = {"ymin": 0.0}
    myParams["ratio"] = True
    myParams["ratioType"] = "errorScale"
    myParams["ratioYlabel"] = "Var./Nom."
    myParams["cmsText"] = myCMSText
    myParams["addLuminosityText"] = True
    myParams["divideByBinWidth"] = True
    plots.drawPlot(plot, myPlotName, **myParams)
Example #30
0
def analyze(analysis=None):

    paths = [sys.argv[1]]

    if not analysis == None:
        #        datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis, includeOnlyTasks="Tau|TT")
        datasets = dataset.getDatasetsFromMulticrabDirs(paths,
                                                        analysisName=analysis)
    else:
        datasets = dataset.getDatasetsFromMulticrabDirs(paths)
        analysis = datasets.getAllDatasets()[0].getAnalysisName()

    analysisList = []
    #    analysisList.append("METLeg_2016MET80_MET80")
    #    analysisList.append("METLeg_2016ICHEP_MET90")
    #    analysisList.append("METLeg_2016_MET90")

    met_re = re.compile("_(?P<met>MET\d+)$")
    if True:
        #for analysis in analysisList:

        met = "METX"
        met_match = met_re.search(analysis)
        if met_match:
            met = met_match.group("met")

        print "Analysis", analysis
        datasets = dataset.getDatasetsFromMulticrabDirs(paths,
                                                        analysisName=analysis)
        #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau\S+25ns$|TTJets$")
        #        datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$")
        #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="Tau_Run2015D_PromptReco_v4_246908_260426_25ns$|DYJetsToLL_M_50$")
        #    datasetsMC = None
        datasetsMC = dataset.getDatasetsFromMulticrabDirs(
            paths, analysisName=analysis, excludeTasks="Tau_")

        for d in datasets.getAllDatasets():
            print d.getName()
            style = tdrstyle.TDRStyle()

            dataset1 = datasets.getDataDatasets()
            dataset2 = dataset1
            createRatio = False
            if isinstance(datasetsMC, dataset.DatasetManager):
                dataset2 = datasetsMC.getMCDatasets()
                createRatio = True

        eff1_MET80 = getEfficiency(dataset1)
        eff2_MET80 = getEfficiency(dataset2)

        styles.dataStyle.apply(eff1_MET80)
        eff1_MET80.SetMarkerSize(1)
        if createRatio:
            styles.mcStyle.apply(eff2_MET80)
            eff2_MET80.SetMarkerSize(1.5)

        if createRatio:
            p = plots.ComparisonPlot(
                histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P"),
                histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"))
        else:
            p = plots.PlotBase(
                [histograms.HistoGraph(eff1_MET80, "eff1_MET80", "p", "P")])

        #from plotTauLegEfficiency import fit
        #fit("Data",p,eff1_MET80,20,300)
        #fit("MC",p,eff2_MET80,20,300)

        opts = {"ymin": 0, "ymax": 1.1}
        opts2 = {"ymin": 0.5, "ymax": 1.5}
        moveLegend = {"dx": -0.55, "dy": -0.15}

        name = "TauMET_" + analysis + "_DataVsMC_PFMET"

        legend1 = "Data"
        #    legend2 = "MC (TTJets)"
        #legend2 = "MC"
        legend2 = "Simulation"

        if createRatio:
            p.histoMgr.setHistoLegendLabelMany({
                "eff1_MET80": legend1,
                "eff2_MET80": legend2
            })
            p.createFrame(os.path.join(plotDir, name),
                          createRatio=True,
                          opts=opts,
                          opts2=opts2)
        else:
            p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1})
            p.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)

        p.setLegend(
            histograms.moveLegend(histograms.createLegend(y1=0.8),
                                  **moveLegend))

        p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
        p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)")
        if createRatio:
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

#        histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_"+met, 17)
        histograms.addText(0.4, 0.87, "LooseIsoPFTau50_Trk30_eta2p1_" + met,
                           17)
        #    histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17)
        #        label = analysis.split("_")[1]
        #        label = "2016"
        label = string.replace(analysis, "METLeg_", "")
        histograms.addText(0.2, 0.53, label, 17)
        runRange = datasets.loadRunRange()
        histograms.addText(0.2, 0.46, "Runs " + runRange, 17)

        p.draw()
        lumi = 0.0
        for d in datasets.getDataDatasets():
            print "luminosity", d.getName(), d.getLuminosity()
            lumi += d.getLuminosity()
        print "luminosity, sum", lumi
        histograms.addStandardTexts(lumi=lumi)

        if not os.path.exists(plotDir):
            os.mkdir(plotDir)
        p.save(formats)

        pythonWriter.addParameters(plotDir, label, runRange, lumi, eff1_MET80)
        pythonWriter.addMCParameters(label, eff2_MET80)

    pythonWriter.writeJSON(
        os.path.join(plotDir, "metLegTriggerEfficiency_" + label + ".json"))

    #########################################################################

    eff1phi = getEfficiency(dataset1, "NumeratorPhi", "DenominatorPhi")
    eff2phi = getEfficiency(dataset2, "NumeratorPhi", "DenominatorPhi")

    styles.dataStyle.apply(eff1phi)
    styles.mcStyle.apply(eff2phi)
    eff1phi.SetMarkerSize(1)

    if isinstance(datasetsMC, dataset.DatasetManager):
        p_phi = plots.ComparisonPlot(
            histograms.HistoGraph(eff1phi, "eff1phi", "p", "P"),
            histograms.HistoGraph(eff2phi, "eff2phi", "p", "P"))
    else:
        p_phi = plots.PlotBase(
            [histograms.HistoGraph(eff1phi, "eff1phi", "p", "P")])

    p_phi.histoMgr.setHistoLegendLabelMany({"eff1phi": legend1})
    if isinstance(datasetsMC, dataset.DatasetManager):
        p_phi.histoMgr.setHistoLegendLabelMany({
            "eff1phi": legend1,
            "eff2phi": legend2
        })

    opts = {"ymin": 0, "ymax": 0.3}
    name = "TauMET_" + analysis + "_DataVsMC_PFMETPhi"

    if createRatio:
        p_phi.createFrame(os.path.join(plotDir, name),
                          createRatio=createRatio,
                          opts=opts,
                          opts2=opts2)
    else:
        p_phi.createFrame(os.path.join(plotDir, name), opts=opts, opts2=opts2)


#    moveLegendPhi = {"dx": -0.5, "dy": -0.6, "dh": -0.1}
    moveLegendPhi = {"dx": -0.55, "dy": -0.15, "dh": -0.1}
    p_phi.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegendPhi))

    p_phi.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
    p_phi.getFrame().GetXaxis().SetTitle("MET Type 1 #phi")
    if createRatio:
        p_phi.getFrame2().GetYaxis().SetTitle("Ratio")
        p_phi.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.4, 0.86, "LooseIsoPFTau50_Trk30_eta2p1_" + met, 17)
    #   histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.4, 0.78, "2016", 17)
    histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17)

    p_phi.draw()
    histograms.addStandardTexts(lumi=lumi)

    p_phi.save(formats)

    #########################################################################
    """
    #### MET120

    analysis = "METLeg_2015CD_MET120"
    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis)
    for d in datasets.getAllDatasets():
        print d.getName()
    style = tdrstyle.TDRStyle()

    dataset1 = datasets.getDataDatasets()
    dataset2 = datasets.getMCDatasets()

    eff1_MET120 = getEfficiency(dataset1)
    eff2_MET120 = getEfficiency(dataset2)

    styles.dataStyle.apply(eff1_MET120)
    styles.mcStyle.apply(eff2_MET120)
    eff1_MET120.SetMarkerSize(1)
    eff2_MET120.SetMarkerSize(1.5)

    p = plots.ComparisonPlot(histograms.HistoGraph(eff1_MET120, "eff1_MET120", "p", "P"),
                             histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"))

    opts = {"ymin": 0, "ymax": 1.1}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    moveLegend = {"dx": -0.55, "dy": -0.15}

    name = "DataVsMC_L1HLTMET_PFMET_MET120"

    legend1 = "Data"
    legend2 = "MC"
    p.histoMgr.setHistoLegendLabelMany({"eff1_MET120": legend1, "eff2_MET120": legend2})

    p.createFrame(os.path.join(plotDir, name), createRatio=True, opts=opts, opts2=opts2)
    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
    p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)")
    p.getFrame2().GetYaxis().SetTitle("Ratio")
    p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    p.draw()
    lumi = 0.0
    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    """

    # CaloMET
    """
    #### MET80

    analysisc = "METLeg_2016B_CaloMET_MET80"

    datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc)
    datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,excludeTasks="Tau\S+25ns_Silver$")
#    datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc,includeOnlyTasks="Tau\S+25ns$|TTJets$")

    style = tdrstyle.TDRStyle()

    dataset1c = datasetsc.getDataDatasets()
    dataset2c = datasetsc.getMCDatasets()

#    eff1c_MET80 = getEfficiency(dataset1c)
    eff2c_MET80 = getEfficiency(dataset2c)

#    styles.dataStyle.apply(eff1c_MET80)
    styles.mcStyle.apply(eff2c_MET80)
#    eff1c_MET80.SetMarkerSize(1)
    eff2c_MET80.SetMarkerSize(1.5)
    eff2c_MET80.SetMarkerColor(4)

    p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET80, "eff2_MET80", "p", "P"),
                             histograms.HistoGraph(eff2c_MET80, "eff2c_MET80", "p", "P"))

    namec = "TauMET_"+analysis+"_MC_TrgBitVsCaloMET80_PFMET"

    legend1c = "MC, trigger bit"
    legend2c = "MC, CaloMET > 80"
    p.histoMgr.setHistoLegendLabelMany({"eff2_MET80": legend1c, "eff2c_MET80": legend2c})

    p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2)
    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
    p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)")
    p.getFrame2().GetYaxis().SetTitle("Ratio")
    p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    p.draw()
    lumi = 0.0
    for d in datasets.getDataDatasets():
        print "luminosity",d.getName(),d.getLuminosity()
        lumi += d.getLuminosity()
    print "luminosity, sum",lumi
    histograms.addStandardTexts(lumi=lumi)
    histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    """
    """
    #### MET120 

    analysisc = "METLeg_2015A_CaloMET_MET120"
    datasetsc = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysisc)

    style = tdrstyle.TDRStyle()

    dataset1c = datasetsc.getDataDatasets()
    dataset2c = datasetsc.getMCDatasets()

    eff1c_MET120 = getEfficiency(dataset1c)
    eff2c_MET120 = getEfficiency(dataset2c)

    styles.dataStyle.apply(eff1c_MET120)
    styles.mcStyle.apply(eff1c_MET120)
    eff1c_MET120.SetMarkerSize(1)
    eff2c_MET120.SetMarkerSize(1.5)

    p = plots.ComparisonPlot(histograms.HistoGraph(eff2_MET120, "eff2_MET120", "p", "P"),
                             histograms.HistoGraph(eff2c_MET120, "eff2c_MET120", "p", "P"))

    namec = "MC_TrgBitVsCaloMET120_L1HLTMET_PFMET"

    legend1c = "MC, trigger bit"
    legend2c = "MC, CaloMET > 120"
    p.histoMgr.setHistoLegendLabelMany({"eff2_MET120": legend1c, "eff2c_MET120": legend2c})

    p.createFrame(os.path.join(plotDir, namec), createRatio=True, opts=opts, opts2=opts2)
    p.setLegend(histograms.moveLegend(histograms.createLegend(y1=0.8), **moveLegend))

    p.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
    p.getFrame().GetXaxis().SetTitle("MET Type 1 (GeV)")
    p.getFrame2().GetYaxis().SetTitle("Ratio")
    p.getFrame2().GetYaxis().SetTitleOffset(1.6)

    p.draw()
    lumi = 0.0
    histograms.addStandardTexts(lumi=lumi)

    if not os.path.exists(plotDir):
        os.mkdir(plotDir)
    p.save(formats)
    """

    #########################################################################

    namePU = "TauMET_" + analysis + "_DataVsMC_nVtx"

    eff1PU = getEfficiency(dataset1, "NumeratorPU", "DenominatorPU")
    eff2PU = getEfficiency(dataset2, "NumeratorPU", "DenominatorPU")

    styles.dataStyle.apply(eff1PU)
    styles.mcStyle.apply(eff2PU)
    eff1PU.SetMarkerSize(1)
    eff2PU.SetMarkerSize(1.5)

    if isinstance(datasetsMC, dataset.DatasetManager):
        pPU = plots.ComparisonManyPlot(
            histograms.HistoGraph(eff1PU, "eff1", "p", "P"),
            [histograms.HistoGraph(eff2PU, "eff2", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({
            "eff1": legend1,
            "eff2": legend2
        })
    else:
        pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")])
        pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1})

    opts = {"ymin": 0.001, "ymax": 1.0}
    moveLegend = {"dx": -0.33, "dy": -0.25, "dh": -0.1}
    createRatio = False
    if createRatio:
        pPU.createFrame(os.path.join(plotDir, namePU),
                        createRatio=True,
                        opts=opts,
                        opts2=opts2)
    else:
        pPU.createFrame(os.path.join(plotDir, namePU), opts=opts, opts2=opts2)
    pPU.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegend))
    #    if createRatio:
    #        pPU.getPad1().SetLogy(True)
    #    else:
    #        pPU.getPad().SetLogy(True)

    pPU.getFrame().GetYaxis().SetTitle("L1+HLT MET efficiency")
    pPU.getFrame().GetXaxis().SetTitle("Number of reco vertices")
    if createRatio:
        pPU.getFrame2().GetYaxis().SetTitle("Ratio")
        pPU.getFrame2().GetYaxis().SetTitleOffset(1.6)

    histograms.addText(0.4, 0.85, "LooseIsoPFTau50_Trk30_eta2p1_MET90", 17)
    #    histograms.addText(0.4, 0.78, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.4, 0.78, "2016", 17)
    histograms.addText(0.4, 0.71, "Runs " + datasets.loadRunRange(), 17)

    pPU.draw()
    histograms.addStandardTexts(lumi=lumi)

    pPU.save(formats)

    print "Output written in", plotDir