Exemple #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 doPlotMu(name, graphs, styleList, limits, xlabel):
    objs = []
    ll = {}
    for gr, mu in graphs:
        objs.append(histograms.HistoGraph(gr, "Obs%d"%mu, drawStyle="LP", legendStyle="lp"))
        ll["Obs%d"%mu] = "Observed, #mu=%d %s" % (mu, limit.massUnit())

    plot = plots.PlotBase(objs)
    plot.histoMgr.forEachHisto(styles.Generator(styleList))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355), dx=-0.1))

    plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax})
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.9, limit.process, size=size)
    histograms.addText(x, 0.863, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size)
    histograms.addText(x, 0.775, limit.BRassumption, size=size)

    plot.save()
def rtauGen(h, name, rebin=2, ratio=False, defaultStyles=True):
    if defaultStyles:
        h.setDefaultStyles()
        h.histoMgr.forEachHisto(styles.generator())

    h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))


    xlabel = "PF E_{T}^{miss} (GeV)"
    ylabel = "Events / %.2f" % h.binWidth()
    if "LeptonsInMt" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "NoLeptonsRealTau" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()
    if "Mass" in name:
        xlabel = "m_{T}(#tau jet, E_{T}^{miss}) (GeV/c^{2})"
        ylabel = "Events / %.0f GeV/c^{2}" % h.binWidth()

        
    kwargs = {"ymin": 0.1, "ymax": 1000}
    if "LeptonsInMt" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "NoLeptonsRealTau" in name: 
        kwargs = {"ymin": 0., "xmax": 300}
    if "Rtau" in name:
        kwargs = {"ymin": 0.0001, "xmax": 1.1}   
        kwargs = {"ymin": 0.1, "xmax": 1.1}     
        h.getPad().SetLogy(True)

#    kwargs["opts"] = {"ymin": 0, "xmax": 14, "ymaxfactor": 1.1}}
    if ratio:
        kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
        kwargs["createRatio"] = True
#    name = name+"_log"

    h.createFrame(name, **kwargs)

#    histograms.addText(0.65, 0.7, "BR(t #rightarrow bH^{#pm})=0.05", 20)
    h.getPad().SetLogy(True)
    
    leg = histograms.createLegend(0.6, 0.75, 0.8, 0.9)
 
    if "LeptonsInMt" in name:
        h.getPad().SetLogy(False)
        leg = histograms.moveLegend(leg, dx=-0.18)
        histograms.addText(0.5, 0.65, "TailKiller cut: Tight", 20)
  
    h.setLegend(leg)
    plots._legendLabels["MetNoJetInHole"] = "Jets outside dead cells"
    plots._legendLabels["MetJetInHole"] = "Jets within dead cells"
    histograms.addText(300, 300, "p_{T}^{jet} > 50 GeV/c", 20)
    kwargs["opts2"] = {"ymin": 0.5, "ymax": 1.5}
    kwargs["createRatio"] = True
#    if ratio:
#        h.createFrameFraction(name, opts=opts, opts2=opts2)
#    h.setLegend(leg)

    common(h, xlabel, ylabel)
def doPlot2(limits, legendLabels, name):
    graphs = [
        histograms.HistoGraph(limits[0].expectedGraph(), "Expected", drawStyle="L"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1), "Expected1", drawStyle="F", legendStyle="fl"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2), "Expected2", drawStyle="F", legendStyle="fl"),
        ]
    graphs[0].getRootHisto().SetLineStyle(1)
    plot = plots.PlotBase(graphs)
    ll = {
        "Expected": None,
        "Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0],
        "Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0],
        }

    stGen = styles.generator()
    for i in xrange(1, len(limits)):
        gr = histograms.HistoGraph(limits[i].expectedGraph(), "Exp%d"%i, drawStyle="L")
        stGen(gr)
        gr.getRootHisto().SetLineWidth(3)
        gr.getRootHisto().SetLineStyle(1)
        plot.histoMgr.insertHisto(len(plot.histoMgr)-2, gr, legendIndex=len(plot.histoMgr))
        ll["Exp%d"%i] = "%s exp. median" % legendLabels[i]

    plot.histoMgr.setHistoLegendLabelMany(ll)

    legend = histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=-0.02)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    plot.setLegend(legend)

    plot.createFrame(name+"_limits", opts={"ymin": 0, "ymax": limits[0].getFinalstateYmaxBR()})
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(limit.BRlimit)

    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    plot.save()
def doPlot(limits, legendLabels, graphs, name, ylabel, opts={}, plotLabel=None, moveLegend={}, log=False):
    hg = []
    ll = {}
    for i in xrange(len(graphs)):
        hg.append(histograms.HistoGraph(graphs[i], "Graph%d"%i, drawStyle="PL", legendStyle="lp"))
        ll["Graph%d"%i] = legendLabels[i]

    plot = plots.PlotBase(hg)
    plot.histoMgr.forEachHisto(styles.Generator(styleList[0:len(limits)]))
    def sty(h):
        r = h.getRootHisto()
        r.SetLineWidth(3)
        r.SetLineStyle(1)
    plot.histoMgr.forEachHisto(sty)
    plot.histoMgr.setHistoLegendLabelMany(ll)
    legend = histograms.createLegend(0.48, 0.65, 0.85, 0.92)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    if plotLabel:
        legend = histograms.moveLegend(legend, dy=-0.04)
    legend = histograms.moveLegend(legend, **moveLegend)
    plot.setLegend(legend)
    opts_ = {"ymin": 0}
    opts_.update(opts)
    plot.createFrame(name, opts=opts_)

    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(ylabel)

    ROOT.gPad.SetLogy(log)
    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.18
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)
    if plotLabel:
        histograms.addText(legend.GetX1()+0.01, legend.GetY2(), plotLabel, size=size)

    plot.save()
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, addMCUncertainty=True, ratio=False, opts={}, opts2={}, moveLegend={}, textFunction=None, cutLine=None, cutBox=None):
    if cutLine != None and cutBox != None:
        raise Exception("Both cutLine and cutBox were given, only either one can exist")

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()


#    scaleMCfromWmunu(h)     
#    h.stackMCSignalHistograms()

    h.stackMCHistograms(stackSignal=True)#stackSignal=True)    
#    h.stackMCHistograms()
    
    if addMCUncertainty:
        h.addMCUncertainty()
        
    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
##    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts2 = {"ymin": 0.0, "ymax": 2.0}
    _opts.update(opts)
    _opts2.update(opts2)

    #if log:
    #    name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    if log:
        h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    common(h, xlabel, ylab, textFunction=textFunction)
def drawPlot(h, name, xlabel, ylabel="Events / %.0f GeV/c", rebin=1, log=True, addMCUncertainty=True, ratio=False, opts={}, opts2={}, moveLegend={}, textFunction=None, cutLine=None, cutBox=None):
    if cutLine != None and cutBox != None:
        raise Exception("Both cutLine and cutBox were given, only either one can exist")

    if rebin > 1:
        h.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(rebin))
    ylab = ylabel
    if "%" in ylabel:
        ylab = ylabel % h.binWidth()


    scaleMCfromWmunu(h)     
#    h.stackMCSignalHistograms()

    h.stackMCHistograms(stackSignal=True)#stackSignal=True)    
#    h.stackMCHistograms()
    
    if addMCUncertainty:
        h.addMCUncertainty()
        
    _opts = {"ymin": 0.01, "ymaxfactor": 2}
    if not log:
        _opts["ymin"] = 0
        _opts["ymaxfactor"] = 1.1
##    _opts2 = {"ymin": 0.5, "ymax": 1.5}
    _opts2 = {"ymin": 0.0, "ymax": 2.0}
    _opts.update(opts)
    _opts2.update(opts2)

    #if log:
    #    name = name + "_log"
    h.createFrame(name, createRatio=ratio, opts=_opts, opts2=_opts2)
    if log:
        h.getPad().SetLogy(log)
    h.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

    # Add cut line and/or box
    if cutLine != None:
        lst = cutLine
        if not isinstance(lst, list):
            lst = [lst]

        for line in lst:
            h.addCutBoxAndLine(line, box=False, line=True)
    if cutBox != None:
        lst = cutBox
        if not isinstance(lst, list):
            lst = [lst]

        for box in lst:
            h.addCutBoxAndLine(**box)

    common(h, xlabel, ylab, textFunction=textFunction)
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 plotClosure(mt_nom, mts_var, name, optMode):
    #for mt_var in mts_var:
    #    printSummedDifference(mt_nom, mt_var)

    style = tdrstyle.TDRStyle()
    plot = plots.ComparisonManyPlot(mt_nom, mts_var)
    plot.createFrame(optMode.replace("Opt","mT_Closure_"+ name +"_"), createRatio=True)
        
    moveLegend={"dx": -0.325,"dy": 0.02,"dw":-0.14,"dh":-0.12}
        
    plot.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    histograms.addText(0.65, 0.3, optMode.replace("OptQCDTailKiller","R_{BB} ").replace("Plus",""), 25)
        
    histograms.addStandardTexts()
    
    plot.draw()
    plot.save()
def plotClosure(mt_nom, mts_var, name, optMode):
    #for mt_var in mts_var:
    #    printSummedDifference(mt_nom, mt_var)

    style = tdrstyle.TDRStyle()
    plot = plots.ComparisonManyPlot(mt_nom, mts_var)
    plot.createFrame(optMode.replace("Opt", "mT_Closure_" + name + "_"),
                     createRatio=True)

    moveLegend = {"dx": -0.325, "dy": 0.02, "dw": -0.14, "dh": -0.12}

    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(), **moveLegend))
    histograms.addText(
        0.65, 0.3,
        optMode.replace("OptQCDTailKiller", "R_{BB} ").replace("Plus", ""), 25)

    histograms.addStandardTexts()

    plot.draw()
    plot.save()
Exemple #11
0
def doPlotMu(name, graphs, styleList, limits, xlabel):
    objs = []
    ll = {}
    for gr, mu in graphs:
        objs.append(
            histograms.HistoGraph(gr,
                                  "Obs%d" % mu,
                                  drawStyle="LP",
                                  legendStyle="lp"))
        ll["Obs%d" % mu] = "Observed, #mu=%d %s" % (mu, limit.massUnit())

    plot = plots.PlotBase(objs)
    plot.histoMgr.forEachHisto(styles.Generator(styleList))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87,
                                                      0.355),
                              dx=-0.1))

    plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax})
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.9, limit.process, size=size)
    histograms.addText(x, 0.863, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size)
    histograms.addText(x, 0.775, limit.BRassumption, size=size)

    plot.save()
Exemple #12
0
def doLimitError(limits, unblindedStatus):
    expRelErrors = []
    expLabels = {}
    obsRelErrors = []
    obsLabels = {}

    order = [0, 1, -1, 2, -2]
    expErrors = [limits.expectedErrorGraph(sigma=s) for s in order]
    if expErrors[0] != None:
        exps = [limits.expectedGraph(sigma=s) for s in order]
        expRelErrors = [(limit.divideGraph(expErrors[i],
                                           exps[i]), "ExpRelErr%d" % i)
                        for i in xrange(len(exps))]
        expLabels = {
            "ExpRelErr0": "Expected median",
            "ExpRelErr1": "Expected +1#sigma",
            "ExpRelErr2": "Expected -1#sigma",
            "ExpRelErr3": "Expected +2#sigma",
            "ExpRelErr4": "Expected -2#sigma",
        }

    if unblindedStatus:
        obsErr = limits.observedErrorGraph()
        if obsErr != None:
            obs = limits.observedGraph()
            if obs != None:
                obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")]
                obsLabels = {"ObsRelErr": "Observed"}

    if len(expRelErrors) == 0 and len(obsRelErrors) == 0:
        return

    # Create the plot
    plot = plots.PlotBase()
    if len(expRelErrors) > 0:
        plot.histoMgr.extendHistos([
            histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp")
            for x in expRelErrors
        ])
        plot.histoMgr.forEachHisto(styles.generator())

        def sty(h):
            r = h.getRootHisto()
            r.SetLineStyle(1)
            r.SetLineWidth(3)
            r.SetMarkerSize(1.4)

        plot.histoMgr.forEachHisto(sty)
        plot.histoMgr.setHistoLegendLabelMany(expLabels)
    if unblindedStatus:
        if len(obsRelErrors) > 0:
            obsRelErrors[0][0].SetMarkerSize(1.4)
            obsRelErrors[0][0].SetMarkerStyle(25)
            plot.histoMgr.insertHisto(
                0,
                histograms.HistoGraph(obsRelErrors[0][0],
                                      obsRelErrors[0][1],
                                      drawStyle="PL",
                                      legendStyle="lp"))
            plot.histoMgr.setHistoLegendLabelMany(obsLabels)

    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92),
                              dx=0.1,
                              dy=-0.1))

    if len(limits.mass) == 1:
        plot.createFrame("limitsBrRelativeUncertainty",
                         opts={
                             "xmin": limits.mass[0] - 5.0,
                             "xmax": limits.mass[0] + 5.0,
                             "ymin": 0,
                             "ymaxfactor": 1.5
                         })
    else:
        plot.createFrame("limitsBrRelativeUncertainty",
                         opts={
                             "ymin": 0,
                             "ymaxfactor": 1.5
                         })
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle("Uncertainty/limit")

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    size = 22
    x = 0.55
    histograms.addText(x, 0.88, "Toy MC relative", size=size)
    histograms.addText(x, 0.84, "statistical uncertainty", size=size)

    plot.save()
Exemple #13
0
def main(opts):

    # Setup the style
    style = tdrstyle.TDRStyle()

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

    # ========================================
    # Datasets
    # ========================================
    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)
    intLumi = GetLumi(datasetsMgr)
    datasetsMgr.updateNAllEventsToPUWeighted()
    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)

    # Merge datasets:All JetHT to "Data", QCD_Pt to "QCD",
    # QCD_bEnriched to "QCD_b",  single-top to "SingleTop", WW, WZ, ZZ to "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets
    if 0:
        datasetsMgr.remove("TTJets")
        datasetsMgr.remove(
            filter(lambda name: not "QCD" in name,
                   datasetsMgr.getAllDatasetNames()))

    # Print dataset information
    datasetsMgr.PrintInfo()

    # ========================================
    # Histograms
    # ========================================
    for counter, hName in enumerate(hNames):

        # Get the save path and name, Get Histos for Plotter
        savePath, saveName = GetSavePathAndName(hName, **kwargs)
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName,
                                                    **kwargs)

        # Create a comparison plot
        #p = plots.ComparisonManyPlot(refHisto, otherHistos)
        p = plots.DataMCPlot(datasetsMgr, hName)

        # Remove negative contributions
        if 0:
            RemoveNegativeBins(datasetsMgr, hName, p)

        # Y-axis
        ratioOpts = {"ymin": 0.0, "ymax": 2.0}
        if kwargs.get("logY") == True:
            opts = {"ymin": 1e-2, "ymaxfactor": 100}
        else:
            opts = {"ymin": 0.0, "ymaxfactor": 1.2}

        # ========================================
        # Frame
        # ========================================
        p.createFrame(saveName,
                      createRatio=kwargs.get("createRatio"),
                      opts=opts,
                      opts2=ratioOpts)

        # Legend
        moveLegend = {"dx": -0.11, "dy": +0.0, "dh": +0.2}
        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(
            filter(
                lambda n: plots._legendLabels[kwargs.get("refDataset")] not in
                n, histoNames))
        if 0:
            p.removeLegend()

        # Axes
        #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
        #p.getFrame().GetYaxis().SetTitle( getTitleY(p.histoMgr.getHistos()[0], **kwargs) )
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

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

        # Cut line / Cut box
        _kwargs = {"lessThan": kwargs.get("cutLessthan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                           fillColor=kwargs.get("cutFillColour"),
                           box=kwargs.get("cutBox"),
                           line=kwargs.get("cutLine"),
                           **_kwargs)

        # Draw the final plot
        p.draw()

        # ========================================
        # Add Text
        # ========================================
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

        # Save the canvas to a file
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter == 0)

    return
def PlotProb(datasets, numPath, denPath):

    EfficiencyList = []
    index = 0
    for dataset in datasets:

        datasetName = dataset.getName()
        print "Dataset = ", datasetName

        statOption = ROOT.TEfficiency.kFNormal
        ##        n = dataset.getDatasetRootHisto(numPath).getHistogram()
        #        n.normalizeToOne()
        ##        d = dataset.getDatasetRootHisto(denPath).getHistogram()
        nn = dataset.getDatasetRootHisto(numPath)
        nn.normalizeToLuminosity(35.8 * (10**3))
        n = nn.getHistogram()
        dd = dataset.getDatasetRootHisto(denPath)
        #        dd.normalizeToOne()
        #        dd.normalizeToLuminosity(36.3*(10**3))
        dd.normalizeToLuminosity(35.8 * (10**3))
        #        dd.normalizeByCrossSection()
        d = dd.getHistogram()

        #        if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
        #            continue
        #        elif "M_"  in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
        #            continue

        if "Event" in numPath:
            n.Rebin(10)
            d.Rebin(10)
        else:
            n.Rebin(5)
            d.Rebin(5)

        if d.GetEntries() == 0 or n.GetEntries() == 0:
            continue

        if n.GetEntries() > d.GetEntries():
            continue
        # Check Negatives
        CheckNegatives(n, d, True)

        # Remove Negatives
        RemoveNegatives(n)

        nBins = d.GetNbinsX()
        xMin = d.GetXaxis().GetXmin()
        xMax = d.GetXaxis().GetXmax()

        binwidth = int(n.GetBinWidth(0))

        # ----------------------------------------------------------------------------------------- #
        #      Ugly hack to ignore EMPTY (in the wanted range) histograms with overflows/underflows
        # ----------------------------------------------------------------------------------------- #
        if (0):
            print "\n"
            print "=========== getEfficiency:"
            print "Dataset             = ", dataset.getName()
            print "Numerator:   entries=", n.GetEntries(
            ), " Bins=", n.GetNbinsX(), " Low edge=", n.GetBinLowEdge(1)
            print "Denominator: entries=", d.GetEntries(
            ), " Bins=", d.GetNbinsX(), " Low edge=", d.GetBinLowEdge(1)
            print "\n"

            print ">>>>>>  Sanity Check:  <<<<<<"
            print "Numerator Mean       = ", n.GetMean()
            print "Numerator RMS        = ", n.GetRMS()
            print "Numerator Integral   = ", n.Integral(1, nBins)
            print "Denominator Mean     = ", d.GetMean()
            print "Denominator RMS      = ", d.GetRMS()
            print "Denominator Integral = ", d.Integral(1, nBins)

        if (n.GetMean() == 0 or d.GetMean() == 0): continue
        if (n.GetRMS() == 0 or d.GetRMS() == 0): continue
        if (n.Integral(1, nBins) == 0 or d.Integral(1, nBins) == 0): continue

        #        if not (ROOT.TEfficiency.CheckConsistency(n,d)): continue;
        effic = ROOT.TEfficiency(n, d)
        effic.SetStatisticOption(statOption)

        weight = 1
        if dataset.isMC():
            weight = dataset.getCrossSection()
            effic.SetWeight(weight)

        eff = convert2TGraph(effic)

        # Apply Styles
        if "TT" in datasetName:
            if index == 0:
                styles.signalStyleHToTB500.apply(eff)
                #            styles.ttStyle.apply(eff)
                eff.SetLineStyle(1)
                eff.SetLineWidth(3)
                eff.SetLineColor(619)
                legend = "Default: t#bar{t}"
                index = 1
            else:
                styles.signalStyleHToTB500.apply(eff)
                #            styles.ttStyle.apply(eff)
                eff.SetLineStyle(1)
                eff.SetLineWidth(3)
                eff.SetLineColor(417)
                legend = "#Delta R(q,q')>0.8: t#bar{t}"

        elif "M_500" in datasetName:
            styles.signalStyleHToTB500.apply(eff)
            legend = "H^{+} m_{H^{+}} = 500 GeV"
        elif "M_300" in datasetName:
            styles.signalStyleHToTB300.apply(eff)
            legend = "H^{+} m_{H^{+}} = 300 GeV"
        elif "M_1000" in datasetName:
            styles.signalStyleHToTB1000.apply(eff)
            legend = "H^{+} m_{H^{+}} = 1000 GeV"
        elif "M_800" in datasetName:
            styles.signalStyleHToTB800.apply(eff)
            legend = "H^{+} m_{H^{+}} = 800 GeV"
        elif "M_200" in datasetName:
            styles.signalStyleHToTB200.apply(eff)
            legend = "H^{+} m_{H^{+}} = 200 GeV"
        else:
            styles.ttStyle.apply(eff)
            legend = "other"

        EfficiencyList.append(histograms.HistoGraph(eff, legend, "lp", "P"))

    saveName = "Eff_" + numPath.split("/")[-1] + "Over" + denPath.split(
        "/")[-1]
    if "Pt" in numPath:
        xMin = 0.0
        #        rebinX = 2
        xMax = 805.0
        #        xMax = 555.0 # For topPt < 500GeV
        xTitle = "p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Efficiency / " + str(binwidth) + " " + units
        yMin = 0.0
        yMax = 1.1

    elif "_Eta" in numPath:
        xMin = -3.0
        xMax = +3.0
        xTitle = "#eta"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    elif "_Mass" in numPath:
        xMin = 50.0
        xMax = 300
        xTitle = "M (GeV/c^{2})"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    elif "_Phi" in numPath:
        xMin = -3
        xMax = +3
        xTitle = "#phi"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    else:
        xMin = 0.0
        xMax = 250.0
        xTitle = "xTitle"
        yTitle = "yTitle"
        yMin = 0.0
        yMax = 1.1

    if "Fake" in numPath:
        #        xMin = 95.0
        #        rebinX = 4
        xMax = 805.0
        xTitle = "candidate p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Misid rate / " + str(binwidth) + " " + units
        yMin = 0.0
        yMax = 0.11

    if "Event" in numPath:
        rebinX = 2
        #        xMin = 95.0
        xMax = 805.0
        xTitle = "candidate p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Efficiency  / " + str(binwidth) + " " + units
        yMin = 0.0
        yMax = 1.1

    if "NonMatched" in numPath:
        xMin = 90.0
        rebinX = 4
        xMax = 700.0
        xMax = 555.0  # For topPt < 500GeV
        xTitle = "p_{T} (GeV)"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 0.15

    if "AllTopQuarkPt_MatchedBDT" in numPath and "TopQuarkPt" in denPath:
        xMin = 0.0
        #        rebinX = 4
        xMax = 805.0  #705
        units = "GeV/c"
        xTitle = "generated top p_{T} (GeV/c)"
        yTitle = "Efficiency / " + str(binwidth) + " " + units
        yMin = 0.0
        yMax = 1.1

    if "SameFake" in numPath:
        xMin = 95.0
        rebinX = 4
        xMax = 705.0
        xMax = 555.0  # For topPt < 500GeV
        xTitle = "p_{T} [GeV]"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    options = {"ymin": yMin, "ymax": yMax, "xmin": xMin, "xMax": xMax}

    #    if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
    #        return
    #    if "M_"  in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
    #        return

    p = plots.PlotBase(datasetRootHistos=EfficiencyList,
                       saveFormats=kwargs.get("saveFormats"))

    #p = plots.ComparisonManyPlot(refEff, EfficiencyList, saveFormats=[])

    p.createFrame(saveName, opts=options)

    #    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))

    # Set Titles
    #    p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel"))  #"ylabel"
    p.getFrame().GetXaxis().SetTitle(xTitle)
    p.getFrame().GetYaxis().SetTitle(yTitle)

    # Set range
    p.getFrame().GetXaxis().SetRangeUser(xMin, xMax)

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

    # Add Standard Texts to plot
    histograms.addStandardTexts()

    p.draw()

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, "HplusMasses",
                            numPath.split("/")[0], opts.optMode)
    save_path = savePath + opts.MVAcut

    #    SavePlot(p, saveName, savePath)
    SavePlot(p, saveName, save_path)
    return
Exemple #15
0
def analyze(analysis=None):

    paths = [sys.argv[1]]

    datasets = dataset.getDatasetsFromMulticrabDirs(paths)
    #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="SingleNeutrino")
    #    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="QCD")

    #    analysis = datasets.getAllDatasets()[0].getAnalysisName()

    #datasetsMC = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="ZeroBias")

    createRatio = False

    #    for d in datasets.getAllDatasets():
    #        print d.getName()

    style = tdrstyle.TDRStyle()

    dataset1 = datasets.getDataDatasets()
    ####    dataset1 = datasets.getMCDatasets()
    rateETM120 = 5521.35  # Hz
    #effETM120 = 0.000611208781402 #8.75017364672e-05
    #effETM120 = 0.000619219298648
    effETM120 = 0.000203698623826
    ####    effETM120 = 0.186701136914 # QCD
    scale = rateETM120 / effETM120 * 0.001  #(Hz->kHz)
    #    for d in dataset1:
    #        d.scale(scale)
    dataset2 = dataset1
    createRatio = False

    #if isinstance(datasetsMC,dataset.DatasetManager):
    #    dataset2 = datasetsMC.getMCDatasets()
    #    createRatio = True

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

    scaleGraph(eff1PU, scale)

    namePU = "TauMET_" + analysis + "_nVtx"
    legend1 = "Data"
    legend2 = "Simulation"

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

    pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")])
    pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1})

    # Fit
    #    yval = fit("Data",pPU,eff1PU,30,59)
    yval = fit("Data", pPU, eff1PU, 5, 59)

    ####    opts = {"ymin": 0, "ymax": 6, "xmax": 60}
    opts = {"ymin": 0, "ymax": 20, "xmax": 60}
    ####    opts = {"ymin": 0, "ymax": 300, "xmax": 60}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    moveLegend = {"dx": -0.5, "dy": -0.1, "dh": -0.1}

    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))

    pPU.getFrame().GetYaxis().SetTitle("L1 rate (kHz)")
    pPU.getFrame().GetXaxis().SetTitle("n vertices")
    if createRatio:
        pPU.getFrame2().GetYaxis().SetTitle("Ratio")
        pPU.getFrame2().GetYaxis().SetTitleOffset(1.6)

    pPU.draw()

    print "check frame min,max", pPU.getFrame().GetYaxis().GetXmin(
    ), pPU.getFrame().GetYaxis().GetXmax()
    x = array.array('d', [55, 55, 0])
    y = array.array('d', [0, yval, yval])
    n = 3
    vert = ROOT.TGraph(n, x, y)
    vert.SetLineStyle(2)
    vert.SetLineColor(2)
    vert.SetLineWidth(2)
    vert.Draw("L")

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

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

    print "Output written in", plotDir
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
Exemple #17
0
def main():

    style = tdrstyle.TDRStyle()

    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(parseOpts.batchMode)
    ROOT.gErrorIgnoreLevel = 3000

    # Get all datasets from the mcrab dir
    datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))
    # datasetsMgr  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_200")
    # datasetsMgr  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), excludeTasks="M_200")

    # Determine Integrated Luminosity
    intLumi = GetLumi(datasetsMgr)

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))

    # Set custom XSections
    # datasetsMgr.getDataset("TT_ext3").setCrossSection(831.76)

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

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))

    # For-loop: All Histogram names
    for hName in hNames:

        savePath, saveName = GetSavePathAndName(hName, **kwargs)

        # Get efficiency histos
        refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFCP",
                                                   **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFFC", **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kBJeffrey", **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFNormal", **kwargs)

        # Plot the efficiencies
        p = plots.ComparisonManyPlot(refEff, otherEff)

        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.2}  #"ymax": 5e-1}
        ratioOpts = {"ymin": 0.0, "ymaxfactor": 1.2}
        p.createFrame(saveName,
                      createRatio=kwargs.get("createRatio"),
                      opts=opts,
                      opts2=ratioOpts)

        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))
        #p.removeLegend()

        # Customise frame
        # p.setEnergy("13")
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = {"lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                           fillColor=kwargs.get("cutFillColour"),
                           box=kwargs.get("cutBox"),
                           line=kwargs.get("cutLine"),
                           **_kwargs)

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(
            filter(
                lambda n: plots._legendLabels[kwargs.get("refDataset")] not in
                n, histoNames))

        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
Exemple #18
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
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
def doPlot2(limits, legendLabels, name):
    graphs = [
        histograms.HistoGraph(limits[0].expectedGraph(),
                              "Expected",
                              drawStyle="L"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=1),
                              "Expected1",
                              drawStyle="F",
                              legendStyle="fl"),
        histograms.HistoGraph(limits[0].expectedBandGraph(sigma=2),
                              "Expected2",
                              drawStyle="F",
                              legendStyle="fl"),
    ]
    graphs[0].getRootHisto().SetLineStyle(1)
    plot = plots.PlotBase(graphs)
    ll = {
        "Expected": None,
        "Expected1": "%s exp. median #pm 1#sigma" % legendLabels[0],
        "Expected2": "%s exp. median #pm 2#sigma" % legendLabels[0],
    }

    stGen = styles.generator()
    for i in xrange(1, len(limits)):
        gr = histograms.HistoGraph(limits[i].expectedGraph(),
                                   "Exp%d" % i,
                                   drawStyle="L")
        stGen(gr)
        gr.getRootHisto().SetLineWidth(3)
        gr.getRootHisto().SetLineStyle(1)
        plot.histoMgr.insertHisto(len(plot.histoMgr) - 2,
                                  gr,
                                  legendIndex=len(plot.histoMgr))
        ll["Exp%d" % i] = "%s exp. median" % legendLabels[i]

    plot.histoMgr.setHistoLegendLabelMany(ll)

    legend = histograms.moveLegend(histograms.createLegend(
        0.48, 0.75, 0.85, 0.92),
                                   dx=-0.02)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    plot.setLegend(legend)

    plot.createFrame(name + "_limits",
                     opts={
                         "ymin": 0,
                         "ymax": limits[0].getFinalstateYmaxBR()
                     })
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(limit.BRlimit)

    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    plot.save()
Exemple #21
0
def main():

    style = tdrstyle.TDRStyle()

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

    # Get all datasets from the mcrab dir
    datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))

    # Set custom XSections
    # d.getDataset("TT_ext3").setCrossSection(831.76)

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

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))

    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):

        # Get the save path and name
        savePath, saveName = GetSavePathAndName(hName, **kwargs)

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName,
                                                    **kwargs)

        # Create a comparison plot
        p = plots.ComparisonManyPlot(refHisto, otherHistos)

        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.2}
        ratioOpts = {"ymin": 0.0, "ymax": 2.0}
        p.createFrame(saveName,
                      createRatio=kwargs.get("createRatio"),
                      opts=opts,
                      opts2=ratioOpts)

        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))
        #p.removeLegend()

        # Customise frame
        p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs))
        #p.setEnergy("13")
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = {"lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                           fillColor=kwargs.get("cutFillColour"),
                           box=kwargs.get("cutBox"),
                           line=kwargs.get("cutLine"),
                           **_kwargs)

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(
            filter(
                lambda n: plots._legendLabels[kwargs.get("refDataset")] not in
                n, histoNames))

        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
def doPlot(limits,
           legendLabels,
           graphs,
           name,
           ylabel,
           opts={},
           plotLabel=None,
           moveLegend={},
           log=False):
    hg = []
    ll = {}
    for i in xrange(len(graphs)):
        hg.append(
            histograms.HistoGraph(graphs[i],
                                  "Graph%d" % i,
                                  drawStyle="PL",
                                  legendStyle="lp"))
        ll["Graph%d" % i] = legendLabels[i]

    plot = plots.PlotBase(hg)
    plot.histoMgr.forEachHisto(styles.Generator(styleList[0:len(limits)]))

    def sty(h):
        r = h.getRootHisto()
        r.SetLineWidth(3)
        r.SetLineStyle(1)

    plot.histoMgr.forEachHisto(sty)
    plot.histoMgr.setHistoLegendLabelMany(ll)
    legend = histograms.createLegend(0.48, 0.65, 0.85, 0.92)
    if len(limits[0].getFinalstates()) > 1:
        legend = histograms.moveLegend(legend, dy=-0.1)
    if plotLabel:
        legend = histograms.moveLegend(legend, dy=-0.04)
    legend = histograms.moveLegend(legend, **moveLegend)
    plot.setLegend(legend)
    opts_ = {"ymin": 0}
    opts_.update(opts)
    plot.createFrame(name, opts=opts_)

    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle(ylabel)

    ROOT.gPad.SetLogy(log)
    plot.draw()

    plot.setLuminosity(limits[0].getLuminosity())
    plot.addStandardTexts(cmsTextPosition="outframe")

    size = 20
    x = 0.18
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits[0].getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)
    if plotLabel:
        histograms.addText(legend.GetX1() + 0.01,
                           legend.GetY2(),
                           plotLabel,
                           size=size)

    plot.save()
Exemple #23
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")

    for optMode in optModes:
        plot = plots.PlotBase()
        color = 1

        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")

        for HISTONAME in histoNameList:
            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)

            invjet_name = "MTInvertedTauIdAfterAllSelectionsPlusJetFakeTau"
            basejet_name = "MTBaselineTauIdAfterAllSelectionsPlusJetFakeTau"

            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)

                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        legendName = "Data-driven Fake Taus"
                    else:
                        legendName = "Simulated Fake Taus"
                    legendName = legendName.replace("Plus", "")
                    mt.SetName(legendName)
                    mt.SetLineColor(color)
                    mt.Add(mt_ewk, -1)

                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        mt.Scale(QCDInvertedNormalizationFilteredEWKFakeTaus[
                            str(i)])
                    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)
                    h.Add(mt_ewk, -1)
                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        h.Scale(QCDInvertedNormalizationFilteredEWKFakeTaus[
                            str(i)])
                    else:
                        h.Scale(QCDInvertedNormalization[str(i)])
                    mt.Add(h)
            if HISTONAME == "shapeTransverseMass":
                mt.Add(mt_signalfaketaus)

            plot.histoMgr.appendHisto(histograms.Histo(mt, mt.GetName()))

            style = tdrstyle.TDRStyle()

        #plot.createFrame("mt")
        #plot.createFrame(HISTONAME.replace("shape","final"))
        plot.createFrame(optMode.replace("Opt", "Mt_DataDrivenVsMC_"))
        moveLegend = {"dx": -0.3, "dy": 0.}
        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()
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts):

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

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

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

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

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

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

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

    # Normalise the VR histogram with the Transfer Factor ( BkgSum = VR * (CR1/CR2) )
    #VRtoSR_TF = manager.GetTransferFactor("Inclusive")
    #Print("Applying TF = %s%0.6f%s to VR shape" % (ShellStyles.NoteStyle(), VRtoSR_TF, ShellStyles.NormalStyle()), True)
    #rBkgSum_SR.Scale(VRtoSR_TF) 
    
    # Plot histograms    
    if opts.altPlot:
        # Add the SR EWK Genuine-b to the SR FakeB ( BkgSum = [FakeB] + [GenuineB-MC] = [VR * (CR1/CR2)] + [GenuineB-MC] )
        rBkgSum_SR.Add(rEWKGenuineB_SR, +1) 

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

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

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

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

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({
                "Data-SR"       : "Data",
                "BkgSum-SR"     : "Fake-b + Gen-b",
                })
    else:
        # Create empty histogram stack list
        myStackList = []
        
        # Signal
        p2 = plots.DataMCPlot(datasetsMgr, "ForTestQGLR/QGLR_SR/QGLR_SRInclusive", saveFormats=[])
        
        hSignal_800 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_800').getRootHisto()
        hhSignal_800= histograms.Histo(hSignal_800, 'ChargedHiggs_HplusTB_HplusToTB_M_800', "H^{+} m_{H^+}=800 GeV")
        hhSignal_800.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hhSignal_800)
        
        hSignal_250 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_250').getRootHisto()
        hhSignal_250= histograms.Histo(hSignal_250, 'ChargedHiggs_HplusTB_HplusToTB_M_250', "H^{+} m_{H^+}=250 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_250'])
        hhSignal_250.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_250)
                
        hSignal_500 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_500').getRootHisto()
        hhSignal_500= histograms.Histo(hSignal_500, 'ChargedHiggs_HplusTB_HplusToTB_M_500', "H^{+} m_{H^+}=500 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500'])
        hhSignal_500.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_500)

        hSignal_1000 = p2.histoMgr.getHisto('ChargedHiggs_HplusTB_HplusToTB_M_1000').getRootHisto()
        hhSignal_1000= histograms.Histo(hSignal_1000, 'ChargedHiggs_HplusTB_HplusToTB_M_1000', "H^{+} m_{H^+}=1000 GeV")#plots._legendLabels['ChargedHiggs_HplusTB_HplusToTB_M_500'])
        hhSignal_1000.setIsDataMC(isData=False, isMC=True)
        #myStackList.append(hhSignal_1000)
        
        # Add the FakeB data-driven background to the histogram list    
        hFakeB = histograms.Histo(rBkgSum_SR, "FakeB", "Fake-b")
        hFakeB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hFakeB)
        
        # Add the EWKGenuineB MC background to the histogram list
        hGenuineB = histograms.Histo(rEWKGenuineB_SR, "GenuineB", "EWK Genuine-b")
        hGenuineB.setIsDataMC(isData=False, isMC=True)
        myStackList.append(hGenuineB)

        # Add the collision datato the histogram list        
        hData = histograms.Histo(rData_SR, "Data", "Data")
        hData.setIsDataMC(isData=True, isMC=False)
        myStackList.insert(0, hData)
        
        p = plots.DataMCPlot2( myStackList, saveFormats=[])
        p.setLuminosity(opts.intLumi)
        p.setDefaultStyles()

        
    # Draw the plot and save it
    hName = "test"
    plots.drawPlot(p, hName, **_kwargs)
    SavePlot(p, hName, os.path.join(opts.saveDir, opts.optMode), saveFormats = [".png", ".pdf"])
    
    #==========================================================================================
    # Calculate Cut-Flow Efficiency
    #==========================================================================================
    kwargs = {
        "rebinX" : 1,
        "xlabel" : "QGLR",
        "ylabel" : "Significance / %.02f ",
        "opts"   : {"ymin": 0.0, "ymaxfactor": 1.3},
        "createLegend": {"x1": 0.55, "y1": 0.70, "x2": 0.92, "y2": 0.92},
        #            "cutBox"           : {"cutValue": 0.0, "fillColor" : 16, "box": False, "line": False, "greaterThan": True},
        }
    
    
    efficiencyList = [] 
    xValues = []
    
    yValues_250 = []
    yValues_500 = []
    yValues_800 = []
    yValues_1000 = []
    yValues_Bkg = []


    nBins = hSignal_250.GetNbinsX()+1

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

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

    for i in range (0, nBins):
        
        # Cut value 
        cut = hSignal_250.GetBinCenter(i)
        
        passed_250  = hSignal_250.Integral(i, hSignal_250.GetXaxis().GetNbins())
        passed_500  = hSignal_500.Integral(i, hSignal_500.GetXaxis().GetNbins())
        passed_800  = hSignal_800.Integral(i, hSignal_800.GetXaxis().GetNbins())
        passed_1000 = hSignal_1000.Integral(i, hSignal_1000.GetXaxis().GetNbins())
        
        passed_Bkg  = hBkg.Integral(i, hBkg.GetXaxis().GetNbins())
        
        total_250   = hSignal_250.Integral()
        total_500   = hSignal_500.Integral()
        total_800   = hSignal_800.Integral()
        total_1000  = hSignal_1000.Integral()
        total_Bkg   = hBkg.Integral()
         
        eff_250  = float(passed_250)/total_250
        eff_500  = float(passed_500)/total_500
        eff_800  = float(passed_800)/total_800
        eff_1000 = float(passed_1000)/total_1000
        
        eff_Bkg = float(passed_Bkg)/total_Bkg
        
        xValues.append(cut)
        yValues_250.append(eff_250)
        yValues_500.append(eff_500)
        yValues_800.append(eff_800)
        yValues_1000.append(eff_1000)
        
        yValues_Bkg.append(eff_Bkg)
        
    # Create the Efficiency Plot
    tGraph_250 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_250))
    tGraph_500 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_500))
    tGraph_800 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_800))
    tGraph_1000 = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_1000))
    tGraph_Bkg  = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues_Bkg))

    styles.getSignalStyleHToTB_M("200").apply(tGraph_250)
    styles.getSignalStyleHToTB_M("500").apply(tGraph_500)
    styles.getSignalStyleHToTB_M("800").apply(tGraph_800)
    styles.getSignalStyleHToTB_M("1000").apply(tGraph_1000)
    styles.getQCDLineStyle().apply(tGraph_Bkg)
    
    drawStyle = "CPE"
    effGraph_250  = histograms.HistoGraph(tGraph_250, "H^{+} m_{H^{+}} = 250 GeV", "lp", drawStyle)
    effGraph_500  = histograms.HistoGraph(tGraph_500, "H^{+} m_{H^{+}} = 500 GeV", "lp", drawStyle)
    effGraph_800  = histograms.HistoGraph(tGraph_800, "H^{+} m_{H^{+}} = 800 GeV", "lp", drawStyle)
    effGraph_1000 = histograms.HistoGraph(tGraph_1000, "H^{+} m_{H^{+}} = 1000 GeV", "lp", drawStyle)
    effGraph_Bkg  = histograms.HistoGraph(tGraph_Bkg, "Bkg", "lp", drawStyle)
    
    efficiencyList.append(effGraph_250)
    efficiencyList.append(effGraph_500)
    efficiencyList.append(effGraph_800)
    efficiencyList.append(effGraph_1000)
    efficiencyList.append(effGraph_Bkg)
    
    # Efficiency plot
    pE = plots.PlotBase(efficiencyList, saveFormats=["pdf"])
    pE.createFrame("QGLR_Efficiency")
    pE.setEnergy("13")
    pE.getFrame().GetYaxis().SetLabelSize(18)
    pE.getFrame().GetXaxis().SetLabelSize(20)
    
    pE.getFrame().GetYaxis().SetTitle("Efficiency / 0.01")
    pE.getFrame().GetXaxis().SetTitle("QGLR Cut")
    
    # Add Standard Texts to plot
    histograms.addStandardTexts()
    
    # Customise Legend
    moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1}
    pE.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    
    pE.draw()
#    plots.drawPlot(pE, "QGLR_Efficiency", **kwargs)
    SavePlot(pE, "QGLR_Efficiency", os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] )
    


    #==========================================================================================
    # Calculate Significance
    #==========================================================================================
                
    SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800"
    
    hSignif_250  = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName)
    hSignif_500  = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName)
    hSignif_800  = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName)
    hSignif_1000 = p.histoMgr.getHisto(SignalName).getRootHisto().Clone(SignalName)
    
    hSignif_250.Reset()
    hSignif_500.Reset()
    hSignif_800.Reset()
    hSignif_1000.Reset()
    
    hBkg = p.histoMgr.getHisto(SignalName).getRootHisto().Clone("Bkg")
    hBkg.Reset()
    
    # Bkg: FakeB + Genuine B
    hBkg.Add(hFakeB.getRootHisto(), +1)
    hBkg.Add(hGenuineB.getRootHisto(), +1)
    
    nBins = hSignif_250.GetNbinsX()+1

    # For-loop: All histo bins
    for i in range (1, nBins+1):
    
        sigmaB = ROOT.Double(0)
        
        b = hBkg.IntegralAndError(i, nBins, sigmaB)
        
        s_250 = hSignal_250.Integral(i, nBins)
        s_500 = hSignal_500.Integral(i, nBins)
        s_800 = hSignal_800.Integral(i, nBins)
        s_1000 = hSignal_1000.Integral(i, nBins)
        
        # Calculate significance
        signif_250 = stat.significance(s_250, b, sigmaB, option="Simple")#Asimov")
        signif_500 = stat.significance(s_500, b, sigmaB, option="Simple")#Asimov")
        signif_800 = stat.significance(s_800, b, sigmaB, option="Simple")#Asimov")
        signif_1000 = stat.significance(s_1000, b, sigmaB, option="Simple")#"Asimov")

        # Set signif for this bin
        hSignif_250.SetBinContent(i, signif_250)
        hSignif_500.SetBinContent(i, signif_500)
        hSignif_800.SetBinContent(i, signif_800)
        hSignif_1000.SetBinContent(i, signif_1000)
        
        # Apply style
        s_250 = styles.getSignalStyleHToTB_M("200")
        s_250.apply(hSignif_250)
        
        s_500 = styles.getSignalStyleHToTB_M("500")
        s_500.apply(hSignif_500)
        
        s_800 = styles.getSignalStyleHToTB_M("800")
        s_800.apply(hSignif_800)

        s_1000 = styles.getSignalStyleHToTB_M("1000")
        s_1000.apply(hSignif_1000)
        
        hList = []
        hList.append(hSignif_250)
        hList.append(hSignif_500)
        hList.append(hSignif_800)
        hList.append(hSignif_1000)
        
        hSignif_250.SetName("H^{+} m_{H^{+}} = 250 GeV")
        hSignif_500.SetName("H^{+} m_{H^{+}} = 500 GeV")
        hSignif_800.SetName("H^{+} m_{H^{+}} = 800 GeV")
        hSignif_1000.SetName("H^{+} m_{H^{+}} = 1000 GeV")
        
    pS = plots.PlotBase(hList, saveFormats=["png", "pdf"])
    pS.setLuminosity(opts.intLumi)
        
    # Drawing style
    pS.histoMgr.setHistoDrawStyleAll("HIST")
    pS.histoMgr.setHistoLegendStyleAll("L")
    pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.0))
    pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineStyle(ROOT.kSolid))
    pS.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerStyle(ROOT.kFullCircle))
    
    # Draw the plot
    name = "QGLR_Signif" + "GE"
    
    plots.drawPlot(pS, name, **kwargs)
    SavePlot(pS, name, os.path.join(opts.saveDir, opts.optMode), saveFormats=[".png", ".pdf"] ) 
    

        


    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    Verbose("Write the normalisation factors to a python file", True)
    fileName = os.path.join(opts.mcrab, "FakeBTransferFactors%s.py"% ( getModuleInfoString(opts) ) )
    manager.writeNormFactorFile(fileName, opts)
    return
Exemple #25
0
def main(opts):

    style = tdrstyle.TDRStyle()

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

    # Get all datasets from the mcrab dir
    # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts,
                                     **kwargs)  #kwargs.get("analysis"))
    datasetsMgr_fixed = GetDatasetsFromDir(opts.mcrab, opts, **kwargs_fixed)

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    datasetsMgr_fixed.remove(kwargs_fixed.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))

    # Set custom XSections
    #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0)

    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr)
    plots.mergeRenameReorderForDataMC(datasetsMgr_fixed)

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))
    datasetsMgr_fixed.remove(kwargs_fixed.get("rmDataset"))

    # Print the cross
    datasetsMgr.PrintCrossSections()

    for h_prefix in ["reco", "gen"]:
        # Get ref histo (?) here and the fixed histos (TT, QCD, QCD-b
        inclusiveHisto, fixedHistos = GetHistosForPlotter(
            datasetsMgr_fixed, h_prefix + "MHT", **kwargs_fixed)
        inclusiveHisto.setName(inclusiveHisto.getName() + " (inclusive)")
        #for hi in fixedHistos:
        #    print(type(hi), hi.getName())
        #return
        # For-loop: All Histogram names
        for counter, hName in enumerate(hNames):

            # Get the save path and name
            savePath, saveName = GetSavePathAndName(h_prefix + hName, **kwargs)

            # Get Histos for Plotter
            refHisto_, otherHistos_ = GetHistosForPlotter(
                datasetsMgr, h_prefix + hName, **kwargs)
            refHisto = refHisto_
            otherHistos = otherHistos_ + fixedHistos
            #for hi in otherHistos:
            #     print hi.getName()
            #return

            # Create a comparison plot
            p = plots.ComparisonManyPlot(refHisto, otherHistos)

            # Remove negative contributions
            #RemoveNegativeBins(datasetsMgr, hName, p)

            # Create a frame
            if kwargs.get("logY") == True:
                opts = {"ymin": 8e-5, "ymax": 2}
                #opts = {"ymin": 1e-3, "ymax": 1}
            else:
                opts = {"ymin": 8.e-5, "ymax": 2}
            ratioOpts = {"ymin": 0.0, "ymax": 2.0}
            p.createFrame(saveName,
                          createRatio=kwargs.get("createRatio"),
                          opts=opts,
                          opts2=ratioOpts)

            # Customise Legend
            moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1}
            p.setLegend(
                histograms.moveLegend(histograms.createLegend(), **moveLegend))
            #p.removeLegend()

            # Customise frame
            p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs))
            #p.setEnergy("13")
            if kwargs.get("createRatio"):
                p.getFrame2().GetYaxis().SetTitle("Ratio")
                p.getFrame2().GetYaxis().SetTitleOffset(1.6)

            # SetLog
            SetLogAndGrid(p, **kwargs)

            # Add cut line/box
            _kwargs = {"lessThan": kwargs.get("cutLessThan")}
            p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                               fillColor=kwargs.get("cutFillColour"),
                               box=kwargs.get("cutBox"),
                               line=kwargs.get("cutLine"),
                               **_kwargs)

            # Move the refDataset to first in the draw order (back)
            histoNames = [h.getName() for h in p.histoMgr.getHistos()]
            p.histoMgr.reorder(
                filter(
                    lambda n: plots._legendLabels[kwargs.get("refDataset")]
                    not in n, histoNames))

            #  Draw plots
            p.draw()

            # Customise text
            histograms.addStandardTexts(lumi=intLumi)
            # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
            # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

            # Save canvas under custom dir
            if not os.path.exists(savePath):
                os.mkdir(savePath)
            SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
def doPlot(name, graphs, limits, xlabel, scenario, mass):

    higgs = "h"
    if "lowMH" in scenario:
	higgs = "H"
       
    excluded = graphs["muexcluded"]
    limit.setExcludedStyle(excluded)
    excluded.SetFillStyle(1001)
    excluded.SetLineWidth(0)
    excluded.SetLineStyle(0)
    excluded.SetLineColor(ROOT.kWhite)
    excludedCopy = excluded.Clone()
    if not mass in [90]:
        excludedCopy.SetFillColorAlpha(ROOT.kWhite, 0.0) # actual color doesn't matter, want fully transparent
    else:
        excluded.SetLineColor(ROOT.kBlack)


    # Uncomment when we have allowed
    for n in ["Allowed", "Allowed2"]:
        a = graphs[n]
        if a is None:
            continue
        a.SetFillStyle(3005)
        a.SetFillColor(ROOT.kRed)
        a.SetLineWidth(-302)
        a.SetLineColor(ROOT.kRed)
        a.SetLineStyle(1)

    legend_dh = 0
    grs = []
    if "observed" in graphs:
        grs.extend([
            histograms.HistoGraph(graphs["observed"], "Observed", drawStyle="L", legendStyle="l"),
            histograms.HistoGraph(graphs["obs_th_plus"], "ObservedPlus", drawStyle="L", legendStyle="l"),
            histograms.HistoGraph(graphs["obs_th_minus"], "ObservedMinus", drawStyle="L", legendStyle=None),
            ])
        legend_dh = 0.1
    grs.extend([
        histograms.HistoGraph(excluded, "Excluded", drawStyle="F"),
        histograms.HistoGraph(excludedCopy, "ExcludedCopy", drawStyle=None, legendStyle="f"),
        histograms.HistoGraph(graphs["Allowed"], "Allowed", drawStyle="L", legendStyle="lf"),
#        histograms.HistoGraph(graphs["IsoMass120"], "IsoMass120", drawStyle="L", legendStyle="lf"),
#        histograms.HistoGraph(graphs["IsoMass160"], "IsoMass160", drawStyle="L", legendStyle="lf"),
#        histograms.HistoGraph(graphs["IsoMass165"], "IsoMass165", drawStyle="L", legendStyle="lf"),
        histograms.HistoGraph(graphs["InAccessible"], "InAccessible", drawStyle="F", legendStyle="lf"),
    ])
    if graphs["Allowed2"] is not None:
        grs.append(histograms.HistoGraph(graphs["Allowed2"], "Allowed2", drawStyle="L", legendStyle=None))


    plot = plots.PlotBase(grs, saveFormats=[".png", ".pdf", ".C"])

    plot.histoMgr.setHistoLegendLabelMany({
   	"ExcludedCopy": "Excluded",
        "Allowed": "m_{"+higgs+"}^{MSSM} #neq 125#pm3 GeV",
        "Excluded": None,
#        "IsoMass120": None,
#        "IsoMass160": None,
#        "IsoMass165": None,
        "InAccessible": "Inaccessible",
        })
    if "observed" in graphs:
        plot.histoMgr.setHistoLegendLabelMany({
            "ObservedPlus": "Observed #pm1#sigma (th.)",
        })

    textPos = "left"
    dx = 0
    dy = -0.15
    if mass in [90, 150]:
        textPos = "right"
        dx = 0.35
    if mass in [155, 160]:
        textPos = "right"
        dy = -0.02

    plot.setLegend(histograms.createLegend(0.19+dx, 0.75+dy-legend_dh, 0.57+dx, 0.80+dy))
    histograms.moveLegend(plot.legend, dh=0.05, dy=-0.05)
    #plot.legend.SetFillColor(0)
    #plot.legend.SetFillStyle(1001)

    name = name.replace("-","_")
    plot.createFrame(name, opts={"ymin": 0.5, "ymax": tanbMax, "xmin": 200, "xmax": 3300})
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)
    ROOT.gPad.SetLogy(True)
    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts(cmsTextPosition=textPos)

    size = 20
    x = 0.2+dx
    histograms.addText(x, 0.9+dy, limit.process, size=size)
    histograms.addText(x, 0.863+dy, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.815+dy, limit.getTypesetScenarioName(scenario.replace("_mu", "")), size=size)
    histograms.addText(x, 0.767+dy, "m_{A}=%d GeV" % mass, size=size)
#    histograms.addText(0.2, 0.231, "Min "+limit.BR+"(t#rightarrowH^{+}b)#times"+limit.BR+"(H^{+}#rightarrow#tau#nu)", size=0.5*size)


    #Adding a LHC label:
#    ROOT.LHCHIGGS_LABEL(0.97,0.72,1)
#    FH_version = db.getVersion("FeynHiggs")
#    histograms.addText(x, 0.55, FH_version)
#    HD_version = db.getVersion("HDECAY")
#    histograms.addText(x, 0.55, FH_version+" and "+HD_version, size=size)
#    histograms.addText(x, 0.48, "Derived from", size=size)
#    histograms.addText(x, 0.43, "CMS HIG-12-052", size=size)

    plot.save()

    print "Created",name
Exemple #27
0
def doPlotMu(name, graphs, styleList, limits, xlabel, xvarName,
             legendVariable):
    objs = []
    ll = {}
    cutValue = 100  # for cutting a slice +- cutValue around 0 from the (mu,tanb) plot
    for gr, mu in graphs:
        if xvarName == "mu":
            histo = histograms.HistoGraph(gr,
                                          "Obs%d" % mu,
                                          drawStyle="LP",
                                          legendStyle="lp")
            plus = gr.Clone()
            minus = gr.Clone()
            N = gr.GetN()
            for i in range(0, N):
                j = N - 1 - i
                x = gr.GetX()[j]
                if x > -cutValue:
                    minus.RemovePoint(j)
                if x < cutValue:
                    plus.RemovePoint(0)
            objs.append(
                histograms.HistoGraph(minus,
                                      "Obs%d" % mu,
                                      drawStyle="LP",
                                      legendStyle="lp"))
            objs.append(
                histograms.HistoGraph(plus,
                                      "ObsCopy%d" % mu,
                                      drawStyle="LP",
                                      legendStyle="lp"))
            ll["ObsCopy%d" % mu] = None

        else:
            objs.append(
                histograms.HistoGraph(gr,
                                      "Obs%d" % mu,
                                      drawStyle="LP",
                                      legendStyle="lp"))
        ll["Obs%d" %
           mu] = "Observed, " + legendVariable + "=%d %s" % (mu,
                                                             limit.massUnit())


#        N = gr.GetN()
#        for i in range(0,N):
#            j = N - 1 - i
#            if gr.GetY()[j] == 1:
#                gr.RemovePoint(j)

    plot = plots.PlotBase(objs)
    if xvarName == "mu":
        doubleStyleList = []
        for style in styleList:
            doubleStyleList.append(style)
            doubleStyleList.append(style)
        plot.histoMgr.forEachHisto(styles.Generator(doubleStyleList))
    else:
        plot.histoMgr.forEachHisto(styles.Generator(styleList))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(
        histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87,
                                                      0.355),
                              dx=-0.1))

    plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax})
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetXaxis().SetLabelSize(20)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.9, limit.process, size=size)
    histograms.addText(x, 0.863, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size)
    #    histograms.addText(x, 0.775, limit.BRassumption, size=size)

    histograms.addText(x, 0.72, "FeynHiggs 2.9.4", size=size)
    histograms.addText(x, 0.65, "Derived from", size=size)
    histograms.addText(x, 0.6, "CMS HIG-12-052", size=size)
    #    histograms.addText(x, 0.6, "CMS HIG-11-019", size=size)
    #    histograms.addText(x, 0.55, "JHEP07(2012)143", size=size)

    #Adding a LHC label:
    ROOT.LHCHIGGS_LABEL(0.97, 0.72, 1)

    plot.save()

    print
    print "Plotting", name
    print
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()
def main():

    style    = tdrstyle.TDRStyle()
    hNames   = getHistoNames(kinVar)
    # hName    = hNames[0]

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

    # Get all datasets from the mcrab dir
    datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis)
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_")
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_")
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$")

    
    # Inform user of datasets retrieved
    Print("Got following datasets from multicrab dir \"%s\"" % parseOpts.mcrab)
    for d in datasets.getAllDatasets():
        print "\t", d.getName()


    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = 0.0
    if len(datasets.getDataDatasets()) != 0:
        # Load Luminosity JSON file
        datasets.loadLuminosities(fname="lumi.json")

        # Load RUN range
        # runRange = datasets.loadRunRange(fname="runrange.json")

        # Calculate Integrated Luminosity
        intLumi = GetLumi(datasets)
    
    
    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):
        plotName = hName #analysis + "_" + hName
        saveName = os.path.join(savePath, plotName)
        
        # Get Data or MC datasets
        # dataDatasets = datasets.getDataDatasets()
        # mcDatasets   = datasets.getMCDatasets()

        # Build ROOT histos from individual datasets
        dataset1 = datasets.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_400").getDatasetRootHisto(hName)
        dataset2 = datasets.getDataset("ChargedHiggs_HplusTB_HplusToTB_M_300").getDatasetRootHisto(hName)
        # dataset2 = datasets.getDataset("TT_ext3").getDatasetRootHisto(hName)
        # datasets.getDataset("TT_ext3").setCrossSection(831.76)
        
        
        # Normalise datasets
        if normalizeTo == "One":
            dataset1.normalizeToOne()
            dataset2.normalizeToOne()
        elif normalizeTo == "XSection":
            dataset1.normalizeByCrossSection()
            dataset2.normalizeByCrossSection()
        elif normalizeTo == "Luminosity":
            dataset1.normalizeToLumi(intLumi)
            dataset2.normalizeToLumi(intLumi)
        else:
            isValidNorm(normalizeTo)
        
    
        # Customise histos
        histo1 = dataset1.getHistogram()
        styles.signal200Style.apply(histo1)
        # histo1.SetMarkerStyle(ROOT.kFullCircle)
        # histo1.SetFillStyle(3001)
        # histo1.SetFillColor(histo2.GetMarkerColor())
        # removeNegatives(histo1)
        # removeErrorBars(histo1)
        histo1.Rebin(rebinFactor)
        
        # Customise histos
        histo2 = dataset2.getHistogram()
        styles.ttStyle.apply(histo2)
        # histo2.SetMarkerStyle(ROOT.kFullCross)
        histo2.SetFillStyle(3001)
        histo2.SetFillColor(styles.ttStyle.color)
        # removeNegatives(histo2)
        # removeErrorBars(histo2)
        histo2.Rebin(rebinFactor)


        # Create a comparison plot
        p = plots.ComparisonPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 400 GeV/c^{2}", "p", "P"),
                                 histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST,E,9"))
#                                 histograms.Histo(histo2, "t#bar{t}", "F", "HIST,E,9"))
        
        # Create a comparison plot (One histogram is treated as a reference histogram, and all other histograms are compared with respect to that)
        # p = plots.ComparisonManyPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 200 GeV/c^{2}", "p", "P"),
        #                             [histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST9"),
        #                              histograms.Histo(histo3, "t#bar{t}", "F", "HIST9")])

    
        # Customise plots
        opts      = {"ymin": 0.0, "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar)}
        ratioOpts = {"ymin": 0.0, "ymax": 2.0 , "binWidthX": histo1.GetXaxis().GetBinWidth(0), "xUnits": getUnitsX(kinVar)}
        p.createFrame(os.path.join(savePath, plotName), createRatio=ratio, opts=opts, opts2=ratioOpts)
        

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


        # Customise text
        if intLumi > 0.0:
            histograms.addStandardTexts(lumi=intLumi)
        else:
            histograms.addStandardTexts()
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasets.loadRunRange(), 17)


        # Customise frame
        p.setEnergy("13")
        p.getFrame().GetYaxis().SetTitle( getTitleY(normalizeTo, kinVar, opts) )
        p.getFrame().GetXaxis().SetTitle( getTitleX(kinVar, opts) )
        if ratio:
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)


        #  Draw plots
        p.draw()

    
        # Save canvas under custom dir
        if counter == 0:
            Print("Saving plots in %s format(s)" % (len(saveFormats)) )
        SavePlotterCanvas(p, savePath, saveName, saveFormats)

    return
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
def Fit (datasets, histo, function):
    
    
    FitList = []
    for dataset in datasets:

        datasetName = dataset.getName()
        print "Dataset = ", datasetName
        hh = dataset.getDatasetRootHisto(histo)
 
        hh.normalizeToOne()
        h = hh.getHistogram()

        #h = dataset.getDatasetRootHisto(histo).getHistogram()
        xMin  = h.GetXaxis().GetXmin()
        xMax  = h.GetXaxis().GetXmax()
        yMin  = 0
        yMax  = 1.2
        #statOption = ROOT.TEfficiency.kFNormal
        if "TT" in datasetName:
            if function == "gaus":
                fitGauss = ROOT.TF1("fitGauss", "gaus", -2.5, 2.5)
#                TF1 *fitBoFreq = new TF1("fitBoFreq","[0]*x+[1]",0,20);
#                h.Fit("gaus")
                #fitTest = ROOT.TF1("fitTest", "0.01", -2.5, 2.5)
                
                h.Fit("fitGauss","SRBM")
                #h.GetListOfFunctions().Add(fitTest)
                legend = "TT"

        legend = "a legend"
        print "Legend", legend
        saveName = histo.split("/")[-1]+"_Fit"

        print saveName

        xTitle = "fixXTitle"
        yTitle = "fixYTitle"
    
        yMin = 0.
        yMax = 0.03
        xMin = -2.3
        xMax = 2.3
        kwargs = {}

        options = {"ymin": yMin  , "ymax": yMax, "xmin":xMin, "xMax":xMax}
        FitList.append(h)
        #p = plots.MCPlot(dataset, h, normalizeToLumi=0, saveFormats=[], **kwargs)

        p = plots.PlotBase(datasetRootHistos=FitList, saveFormats=kwargs.get("saveFormats"))
        p.createFrame(saveName, opts=options)
        
        p.getFrame().GetXaxis().SetTitle(xTitle)
        p.getFrame().GetYaxis().SetTitle(yTitle)
        #p.histoMgr.setHistoDrawStyle(datasetName, "AP")
        
# Set range                                                                                                                                                                          
        p.getFrame().GetXaxis().SetRangeUser(xMin, xMax)

        
        moveLegend = {"dx": -0.55, "dy": -0.01, "dh": -0.1}

        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        # Add Standard Texts to plot        
        histograms.addStandardTexts()
    
        p.draw()
    
    # Save plot in all formats                                                                                                                                                           
        savePath = os.path.join(opts.saveDir, "HplusMasses", histo.split("/")[0], opts.optMode)
        save_path = savePath 
        SavePlot(p, saveName, save_path)
    return
def main():

    style = tdrstyle.TDRStyle()
    hNames = getHistoNames(kinVar)
    # hName    = hNames[0]

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

    # Get all datasets from the mcrab dir
    datasets = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab],
                                                    analysisName=analysis)
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_")
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_")
    # datasets  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=analysis, excludeTasks="Tau_Run2015C|Tau\S+25ns_Silver$|DYJetsToLL|WJetsToLNu$")

    # Inform user of datasets retrieved
    Print("Got following datasets from multicrab dir \"%s\"" % parseOpts.mcrab)
    for d in datasets.getAllDatasets():
        print "\t", d.getName()

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = 0.0
    if len(datasets.getDataDatasets()) != 0:
        # Load Luminosity JSON file
        datasets.loadLuminosities(fname="lumi.json")

        # Load RUN range
        # runRange = datasets.loadRunRange(fname="runrange.json")

        # Calculate Integrated Luminosity
        intLumi = GetLumi(datasets)

    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):
        plotName = hName  #analysis + "_" + hName
        saveName = os.path.join(savePath, plotName)

        # Get Data or MC datasets
        # dataDatasets = datasets.getDataDatasets()
        # mcDatasets   = datasets.getMCDatasets()

        # Build ROOT histos from individual datasets
        dataset1 = datasets.getDataset(
            "ChargedHiggs_HplusTB_HplusToTB_M_400").getDatasetRootHisto(hName)
        dataset2 = datasets.getDataset(
            "ChargedHiggs_HplusTB_HplusToTB_M_300").getDatasetRootHisto(hName)
        # dataset2 = datasets.getDataset("TT_ext3").getDatasetRootHisto(hName)
        # datasets.getDataset("TT_ext3").setCrossSection(831.76)

        # Normalise datasets
        if normalizeTo == "One":
            dataset1.normalizeToOne()
            dataset2.normalizeToOne()
        elif normalizeTo == "XSection":
            dataset1.normalizeByCrossSection()
            dataset2.normalizeByCrossSection()
        elif normalizeTo == "Luminosity":
            dataset1.normalizeToLumi(intLumi)
            dataset2.normalizeToLumi(intLumi)
        else:
            isValidNorm(normalizeTo)

        # Customise histos
        histo1 = dataset1.getHistogram()
        styles.signal200Style.apply(histo1)
        # histo1.SetMarkerStyle(ROOT.kFullCircle)
        # histo1.SetFillStyle(3001)
        # histo1.SetFillColor(histo2.GetMarkerColor())
        # removeNegatives(histo1)
        # removeErrorBars(histo1)
        histo1.Rebin(rebinFactor)

        # Customise histos
        histo2 = dataset2.getHistogram()
        styles.ttStyle.apply(histo2)
        # histo2.SetMarkerStyle(ROOT.kFullCross)
        histo2.SetFillStyle(3001)
        histo2.SetFillColor(styles.ttStyle.color)
        # removeNegatives(histo2)
        # removeErrorBars(histo2)
        histo2.Rebin(rebinFactor)

        # Create a comparison plot
        p = plots.ComparisonPlot(
            histograms.Histo(histo1, "m_{H^{#pm}} = 400 GeV/c^{2}", "p", "P"),
            histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F",
                             "HIST,E,9"))
        #                                 histograms.Histo(histo2, "t#bar{t}", "F", "HIST,E,9"))

        # Create a comparison plot (One histogram is treated as a reference histogram, and all other histograms are compared with respect to that)
        # p = plots.ComparisonManyPlot(histograms.Histo(histo1, "m_{H^{#pm}} = 200 GeV/c^{2}", "p", "P"),
        #                             [histograms.Histo(histo2, "m_{H^{#pm}} = 300 GeV/c^{2}", "F", "HIST9"),
        #                              histograms.Histo(histo3, "t#bar{t}", "F", "HIST9")])

        # Customise plots
        opts = {
            "ymin": 0.0,
            "binWidthX": histo1.GetXaxis().GetBinWidth(0),
            "xUnits": getUnitsX(kinVar)
        }
        ratioOpts = {
            "ymin": 0.0,
            "ymax": 2.0,
            "binWidthX": histo1.GetXaxis().GetBinWidth(0),
            "xUnits": getUnitsX(kinVar)
        }
        p.createFrame(os.path.join(savePath, plotName),
                      createRatio=ratio,
                      opts=opts,
                      opts2=ratioOpts)

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

        # Customise text
        if intLumi > 0.0:
            histograms.addStandardTexts(lumi=intLumi)
        else:
            histograms.addStandardTexts()
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasets.loadRunRange(), 17)

        # Customise frame
        p.setEnergy("13")
        p.getFrame().GetYaxis().SetTitle(getTitleY(normalizeTo, kinVar, opts))
        p.getFrame().GetXaxis().SetTitle(getTitleX(kinVar, opts))
        if ratio:
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

        #  Draw plots
        p.draw()

        # Save canvas under custom dir
        if counter == 0:
            Print("Saving plots in %s format(s)" % (len(saveFormats)))
        SavePlotterCanvas(p, savePath, saveName, saveFormats)

    return
def Plot2d(datasetsMgr, dataset, histoName, kwargs, opts):
    '''
    '''
    # Definitions
    saveName = histoName.replace("/", "_")    
    
    # Get Histos for the plotter object
    refHisto = GetHisto(datasetsMgr, dataset, histoName)

    # Create the plotting object
    p = plots.PlotBase(datasetRootHistos=[refHisto], saveFormats=kwargs.get("saveFormats"))
    if 0:
        p.histoMgr.normalizeMCToLuminosity(opts.intLumi)

    # Customise axes (before drawing histo)    
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY")))
    if 0:
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle(kwargs.get("xlabel")))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetTitle(kwargs.get("ylabel")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetTitle( h.getRootHisto().GetXaxis().GetTitle() + "%0.1f" ))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(kwargs.get("xmin"), kwargs.get("xmax")))
    #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax")))

    #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(kwargs.get("ymin"), kwargs.get("ymax")))
    #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(kwargs.get("zmin"), kwargs.get("zmax")))

    # Create a frame                                                                                                                                                             
    fOpts = {"ymin": 0.0, "ymaxfactor": 1.0}
    p.createFrame(saveName, opts=fOpts)
        
    # SetLog
    SetLogAndGrid(p, **kwargs)

    # Add cut line/box
    if 1:
        _kwargs = { "lessThan": True}
        p.addCutBoxAndLine(cutValue=400.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs)
        p.addCutBoxAndLineY(cutValue=200.0, fillColor=ROOT.kGray, box=False, line=True, **_kwargs)

    # Customise Legend
    moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **kwargs.get("moveLegend")))
    p.removeLegend()

    # Customise histogram (after frame is created)
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle("Events"))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.4))
    #ROOT.gPad.RedrawAxis()

    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zmin")))    
    #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zmax")))

    # Drawing style    
    p.histoMgr.setHistoDrawStyle(dataset, "COLZ")
    p.histoMgr.setHistoDrawStyleAll("COLZ")

    # The lines below do nothing since the Legend is disabled
    if 0:
        p.histoMgr.setHistoLegendStyle(dataset, "F")
        if "FakeB" in dataset:
            p.histoMgr.setHistoLegendLabelMany({
                    dataset: "QCD (Data)",
                    })
        if dataset == "QCD":
            p.histoMgr.setHistoLegendLabelMany({
                    dataset: "QCD (MC)",
                    })
            
    # Draw the plot
    p.draw()

    # Add canvas text
    if kwargs.get("addLuminosityText"):
        histograms.addStandardTexts(lumi=opts.intLumi)
    else:
        histograms.addStandardTexts()

    # Add dataset name on the canvas
    if dataset == "QCD":
        histograms.addText(0.17, 0.88, "QCD (H_{T} binned)", 27)
    else:
        histograms.addText(0.17, 0.88, plots._legendLabels[dataset], 27)

    # Save the plots
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.analysisName, opts.folder, dataset, opts.optMode), [".png", ".pdf"] )
    return
def PlotCutFlowEfficiency(h, datasetsMgr, intLumi):
    Verbose("Plotting Cut Flow Efficiency")
    
    efficiencyList = [] 
    
    signalMass.append("QCD")

    for mass in signalMass:
        
        xValues = []
        yValues = []
        
        hSignal = getHisto(datasetsMgr, h, mass, intLumi)
                
        for i in range (0, hSignal.GetXaxis().GetNbins()):
            
            # Cut value 
            cut = hSignal.GetBinCenter(i)
        
            passed = hSignal.Integral(i, hSignal.GetXaxis().GetNbins())
            total  = hSignal.Integral()
            
            eff = float(passed)/total
                            
            xValues.append(cut)
            yValues.append(eff)
        
        # Create the Significance Plot
        tGraph = ROOT.TGraph(len(xValues), array.array("d", xValues), array.array("d", yValues))
        if "M_" in mass:
            styles.getSignalStyleHToTB_M(mass.split("_")[-1]).apply(tGraph)
        else:
            styles.getQCDStyle().apply(tGraph)
      
        drawStyle = "CPE"
        legName   = plots._legendLabels[mass]
        effGraph = histograms.HistoGraph(tGraph, legName, "lp", drawStyle)
        efficiencyList.append(effGraph)
        
    saveName = "QGLREfficiency"
    
    # Create the plot with all the significance plots
    p = plots.PlotBase(efficiencyList, saveFormats=["pdf"])
    p.createFrame(saveName)
    
    # Customise frame
    p.setEnergy("13")
    p.getFrame().GetYaxis().SetLabelSize(18)
    p.getFrame().GetXaxis().SetLabelSize(20)
    
    p.getFrame().GetYaxis().SetTitle("Efficiency / 0.01")
    p.getFrame().GetXaxis().SetTitle("QGLR Cut")
    
    # Add Standard Texts to plot
    histograms.addStandardTexts()
    
    # Customise Legend
    moveLegend = {"dx": -0.50, "dy": -0.5, "dh": -0.1}
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    p.draw()
    
    savePath = opts.saveDir
    if opts.url:
        savePath = opts.saveDir.replace("/publicweb/m/mkolosov/", "http://home.fnal.gov/~mkolosov/")
        
    savePath = os.path.join(opts.saveDir, opts.folder, saveName, opts.optMode)
    SavePlot(p, saveName, savePath)
            
    return 
def PlotProb(datasets, numPath, denPath):


    EfficiencyList = []
    index = 0
    for dataset in datasets:
        
        datasetName = dataset.getName()
        print "Dataset = ", datasetName
        
        
        statOption = ROOT.TEfficiency.kFNormal        
##        n = dataset.getDatasetRootHisto(numPath).getHistogram()
#        n.normalizeToOne()
##        d = dataset.getDatasetRootHisto(denPath).getHistogram()
        nn = dataset.getDatasetRootHisto(numPath)
        nn.normalizeToLuminosity(35.8*(10**3))
        n = nn.getHistogram()
        dd = dataset.getDatasetRootHisto(denPath)
#        dd.normalizeToOne()                                                                                                                                            
#        dd.normalizeToLuminosity(36.3*(10**3))
        dd.normalizeToLuminosity(35.8*(10**3))                                                                                                                                   
#        dd.normalizeByCrossSection()
        d = dd.getHistogram()


#        if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
#            continue
#        elif "M_"  in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
#            continue
        
        if "Event" in numPath:
            n.Rebin(10)
            d.Rebin(10)
        else:
            n.Rebin(5)
            d.Rebin(5)
        
        if d.GetEntries() == 0 or n.GetEntries() == 0:
            continue

        if n.GetEntries() > d.GetEntries():
            continue
        # Check Negatives
        CheckNegatives(n, d, True)
        
        # Remove Negatives 
        RemoveNegatives(n)
                
        nBins = d.GetNbinsX()
        xMin  = d.GetXaxis().GetXmin()
        xMax  = d.GetXaxis().GetXmax()
        
        binwidth = int(n.GetBinWidth(0))
                
        # ----------------------------------------------------------------------------------------- #
        #      Ugly hack to ignore EMPTY (in the wanted range) histograms with overflows/underflows
        # ----------------------------------------------------------------------------------------- #
        if (0):
            print "\n"
            print "=========== getEfficiency:"
            print "Dataset             = ", dataset.getName()
            print "Numerator:   entries=", n.GetEntries(), " Bins=", n.GetNbinsX(), " Low edge=", n.GetBinLowEdge(1)
            print "Denominator: entries=", d.GetEntries(), " Bins=", d.GetNbinsX(), " Low edge=", d.GetBinLowEdge(1)
            print "\n"
            
            print ">>>>>>  Sanity Check:  <<<<<<"
            print "Numerator Mean       = ", n.GetMean()
            print "Numerator RMS        = ", n.GetRMS()                                                                                                                
            print "Numerator Integral   = ", n.Integral(1, nBins)
            print "Denominator Mean     = ", d.GetMean()
            print "Denominator RMS      = ", d.GetRMS()
            print "Denominator Integral = ", d.Integral(1, nBins)
            
        if (n.GetMean() == 0 or d.GetMean() == 0): continue
        if (n.GetRMS()  == 0 or d.GetRMS()  == 0): continue
        if (n.Integral(1,nBins) == 0 or d.Integral(1,nBins) == 0): continue
        
#        if not (ROOT.TEfficiency.CheckConsistency(n,d)): continue;
        effic = ROOT.TEfficiency(n,d)
        effic.SetStatisticOption(statOption)
        
        weight = 1
        if dataset.isMC():
            weight = dataset.getCrossSection()
            effic.SetWeight(weight)
            
        eff = convert2TGraph(effic)
    

        
        # Apply Styles
        if "TT" in datasetName:
            if index == 0:
                styles.signalStyleHToTB500.apply(eff)
#            styles.ttStyle.apply(eff)
                eff.SetLineStyle(1)
                eff.SetLineWidth(3)
                eff.SetLineColor(619)
                legend = "Default: t#bar{t}"
                index = 1
            else:
                styles.signalStyleHToTB500.apply(eff)
                #            styles.ttStyle.apply(eff)
                eff.SetLineStyle(1)
                eff.SetLineWidth(3)
                eff.SetLineColor(417)
                legend = "#Delta R(q,q')>0.8: t#bar{t}"

        elif "M_500" in datasetName:
            styles.signalStyleHToTB500.apply(eff)
            legend = "H^{+} m_{H^{+}} = 500 GeV"
        elif "M_300" in datasetName:
            styles.signalStyleHToTB300.apply(eff)
            legend = "H^{+} m_{H^{+}} = 300 GeV"
        elif "M_1000" in datasetName:
            styles.signalStyleHToTB1000.apply(eff)
            legend = "H^{+} m_{H^{+}} = 1000 GeV"
        elif "M_800" in datasetName:
            styles.signalStyleHToTB800.apply(eff)
            legend = "H^{+} m_{H^{+}} = 800 GeV"
        elif "M_200" in datasetName:
            styles.signalStyleHToTB200.apply(eff)
            legend = "H^{+} m_{H^{+}} = 200 GeV"
        else:
            styles.ttStyle.apply(eff)
            legend = "other"


        EfficiencyList.append(histograms.HistoGraph(eff, legend, "lp", "P"))
            
    saveName = "Eff_"+numPath.split("/")[-1]+"Over"+denPath.split("/")[-1]
    if "Pt" in numPath:
        xMin = 0.0
#        rebinX = 2
        xMax = 805.0
#        xMax = 555.0 # For topPt < 500GeV
        xTitle = "p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Efficiency / "   + str(binwidth) + " "+units
        yMin = 0.0
        yMax = 1.1

    elif "_Eta" in numPath:
        xMin = -3.0
        xMax = +3.0
        xTitle = "#eta"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    elif "_Mass" in numPath:
        xMin = 50.0
        xMax = 300
        xTitle = "M (GeV/c^{2})"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    elif "_Phi" in numPath:
        xMin = -3
        xMax = +3
        xTitle = "#phi"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1

    else:
        xMin = 0.0
        xMax = 250.0
        xTitle = "xTitle"
        yTitle = "yTitle"
        yMin = 0.0
        yMax = 1.1

    if "Fake" in numPath:
#        xMin = 95.0
#        rebinX = 4                                                                                                                                                  
        xMax = 805.0
        xTitle = "candidate p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Misid rate / "  + str(binwidth) + " " +units
        yMin = 0.0
        yMax = 0.11

    if "Event" in numPath:
        rebinX = 2
#        xMin = 95.0
        xMax = 805.0
        xTitle = "candidate p_{T} (GeV/c)"
        units = "GeV/c"
        _format = "%0.1f" + units
        yTitle = "Efficiency  / "  + str(binwidth) + " "+ units
        yMin = 0.0
        yMax = 1.1
        
    if "NonMatched" in numPath:
        xMin = 90.0
        rebinX = 4
        xMax = 700.0
        xMax = 555.0 # For topPt < 500GeV
        xTitle = "p_{T} (GeV)"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 0.15

    if "AllTopQuarkPt_MatchedBDT" in numPath and "TopQuarkPt" in denPath:
        xMin = 0.0
#        rebinX = 4
        xMax = 805.0 #705
        units = "GeV/c"
        xTitle = "generated top p_{T} (GeV/c)"
        yTitle = "Efficiency / "  + str(binwidth) + " " + units
        yMin = 0.0
        yMax = 1.1

    if "SameFake" in numPath:
        xMin = 95.0
        rebinX = 4
        xMax = 705.0
        xMax = 555.0 # For topPt < 500GeV
        xTitle = "p_{T} [GeV]"
        yTitle = "Efficiency"
        yMin = 0.0
        yMax = 1.1


    options = {"ymin": yMin  , "ymax": yMax, "xmin":xMin, "xMax":xMax}

#    if "TT" in datasetName and ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
#        return
#    if "M_"  in datasetName and not ("Higgs" in numPath or "LdgBjetPt_isLdgFreeBjet" in numPath):
#        return

    p = plots.PlotBase(datasetRootHistos=EfficiencyList, saveFormats=kwargs.get("saveFormats"))

    #p = plots.ComparisonManyPlot(refEff, EfficiencyList, saveFormats=[])
    
    p.createFrame(saveName, opts=options)

#    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))

     # Set Titles                                                                                                                                                                                                
#    p.getFrame().GetYaxis().SetTitle(kwargs.get("ylabel"))  #"ylabel"
    p.getFrame().GetXaxis().SetTitle(xTitle)
    p.getFrame().GetYaxis().SetTitle(yTitle)
    
    # Set range
    p.getFrame().GetXaxis().SetRangeUser(xMin, xMax)
    
    
    moveLegend = {"dx": -0.55, "dy": -0.02, "dh": -0.2}
#    moveLegend = {"dx": -0.55, "dy": -0.01, "dh": -0.1}
    p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    
    # Add Standard Texts to plot                                                                                                                                                                
    histograms.addStandardTexts()

    p.draw()

    # Save plot in all formats
    savePath = os.path.join(opts.saveDir, "HplusMasses", numPath.split("/")[0], opts.optMode)
    save_path = savePath + opts.MVAcut

#    SavePlot(p, saveName, savePath)
    SavePlot(p, saveName, save_path)
    return
Exemple #36
0
def main():

    style = tdrstyle.TDRStyle()
    #style.setWide(True)
    style.setPaletteMy()
    ROOT.gStyle.SetNumberContours(20)
    # tdrstyle.setDeepSeaPalette()
    # tdrstyle.setRainBowPalette()
    # tdrstyle.setDarkBodyRadiatorPalette()
    # tdrstyle.setGreyScalePalette()
    # tdrstyle.setTwoColorHuePalette()

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

    # Get all datasets from the mcrab dir
    #datasetsMgr  = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))
    datasetsMgr = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs)

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    #datasetsMgr.remove(kwargs.get("rmDataset"))
    datasetsMgr.remove(
        filter(lambda name: not kwargs.get("refDataset") in name,
               datasetsMgr.getAllDatasetNames()))

    # Set custom XSections
    # d.getDataset("TT_ext3").setCrossSection(831.76)

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

    # Remove datasets (for merged names)
    # datasetsMgr.remove(kwargs.get("rmDataset"))

    # For-loop: All Histogram names
    for hName in hNames:
        savePath, saveName = GetSavePathAndName(hName, **kwargs)

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName,
                                                    **kwargs)

        # Create a plot
        p = plots.PlotBase([refHisto], kwargs.get("saveFormats"))

        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Customize
        # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL"
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax")))

        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.0}
        p.createFrame(saveName, opts=opts)

        # Customise frame
        p.getFrame().GetXaxis().SetTitle(getTitleX(refHisto, **kwargs))
        p.getFrame().GetYaxis().SetTitle(getTitleY(refHisto, **kwargs))
        # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work

        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = {"lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                           fillColor=kwargs.get("cutFillColour"),
                           box=kwargs.get("cutBox"),
                           line=kwargs.get("cutLine"),
                           **_kwargs)

        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))
        p.removeLegend()

        # Add MC Uncertainty (Invalid method for a 2-d histogram)
        #p.addMCUncertainty()

        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22)
        histograms.addText(0.20, 0.88,
                           plots._legendLabels[kwargs.get("refDataset")], 17)

        # Save canvas under custom dir
        if not os.path.exists(savePath):
            os.mkdir(savePath)
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
def main(opts):

    # Setup the style
    style = tdrstyle.TDRStyle()
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(opts.batchMode)

    # ========================================
    # Datasets
    # ========================================
    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)
    intLumi     = GetLumi(datasetsMgr)
    datasetsMgr.updateNAllEventsToPUWeighted()
    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)
    
    # Merge datasets:All JetHT to "Data", QCD_Pt to "QCD", 
    # QCD_bEnriched to "QCD_b",  single-top to "SingleTop", WW, WZ, ZZ to "Diboson"           
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets
    if 0:
        datasetsMgr.remove("TTJets")
        datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    
    # Print dataset information
    datasetsMgr.PrintInfo()

    # ========================================
    # Histograms
    # ========================================
    for counter, hName in enumerate(hNames):
        
        # Get the save path and name, Get Histos for Plotter
        savePath, saveName    = GetSavePathAndName(hName, **kwargs)
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs)
        
        # Create a comparison plot
        #p = plots.ComparisonManyPlot(refHisto, otherHistos)
        p = plots.DataMCPlot(datasetsMgr, hName)

        # Remove negative contributions
        if 0:
            RemoveNegativeBins(datasetsMgr, hName, p)

        # Y-axis
        ratioOpts = {"ymin": 0.0, "ymax": 2.0}
        if kwargs.get("logY")==True:
            opts = {"ymin": 1e-2, "ymaxfactor": 100}
        else:
            opts = {"ymin": 0.0, "ymaxfactor": 1.2}

        # ========================================
        # Frame
        # ========================================
        p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts)

        # Legend
        moveLegend = {"dx": -0.11, "dy": +0.0, "dh": +0.2}
        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames))
        if 0:
            p.removeLegend()

        # Axes
        #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
        #p.getFrame().GetYaxis().SetTitle( getTitleY(p.histoMgr.getHistos()[0], **kwargs) )
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

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

        # Cut line / Cut box
        _kwargs = {"lessThan": kwargs.get("cutLessthan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)

        # Draw the final plot
        p.draw()


        # ========================================
        # Add Text
        # ========================================
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

        # Save the canvas to a file
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter==0)

    return
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
Exemple #39
0
def doPlot(name, graphs, limits, xlabel, scenario, mass):

    higgs = "h"
    if "lowMH" in scenario:
        higgs = "H"

    excluded = graphs["muexcluded"]
    limit.setExcludedStyle(excluded)
    excluded.SetFillStyle(1001)
    excluded.SetLineWidth(0)
    excluded.SetLineStyle(0)
    excluded.SetLineColor(ROOT.kWhite)
    excludedCopy = excluded.Clone()
    if not mass in [90]:
        excludedCopy.SetFillColorAlpha(
            ROOT.kWhite,
            0.0)  # actual color doesn't matter, want fully transparent


#    else:
#        excluded.SetLineColor(ROOT.kBlack)

# Uncomment when we have allowed
    for n in ["Allowed", "Allowed2"]:
        a = graphs[n]
        if a is None:
            continue
        a.SetFillStyle(3005)
        a.SetFillColor(ROOT.kRed)
        a.SetLineWidth(-302)
        a.SetLineColor(ROOT.kRed)
        a.SetLineStyle(1)

    legend_dh = 0
    grs = []
    if "observed" in graphs:
        grs.extend([
            histograms.HistoGraph(graphs["observed"],
                                  "Observed",
                                  drawStyle="L",
                                  legendStyle="l"),
            histograms.HistoGraph(graphs["obs_th_plus"],
                                  "ObservedPlus",
                                  drawStyle="L",
                                  legendStyle="l"),
            histograms.HistoGraph(graphs["obs_th_minus"],
                                  "ObservedMinus",
                                  drawStyle="L",
                                  legendStyle=None),
        ])
        legend_dh = 0.1
    grs.extend([
        histograms.HistoGraph(excluded, "Excluded", drawStyle="F"),
        histograms.HistoGraph(excludedCopy,
                              "ExcludedCopy",
                              drawStyle=None,
                              legendStyle="f"),
        histograms.HistoGraph(graphs["Allowed"],
                              "Allowed",
                              drawStyle="L",
                              legendStyle="lf"),
    ])
    if graphs["Allowed2"] is not None:
        grs.append(
            histograms.HistoGraph(graphs["Allowed2"],
                                  "Allowed2",
                                  drawStyle="L",
                                  legendStyle=None))

    plot = plots.PlotBase(grs, saveFormats=[".png", ".pdf", ".C"])

    plot.histoMgr.setHistoLegendLabelMany({
        "ExcludedCopy": "Excluded",
        "Allowed": "m_{" + higgs + "}^{MSSM} #neq 125#pm3 GeV",
        "Excluded": None,
    })
    if "observed" in graphs:
        plot.histoMgr.setHistoLegendLabelMany({
            "ObservedPlus":
            "Observed #pm1#sigma (th.)",
        })

    textPos = "left"
    dx = 0
    dy = -0.15
    if mass in [90, 150]:
        textPos = "right"
        dx = 0.35
    if mass in [155, 160]:
        textPos = "right"
        dy = -0.02

    plot.setLegend(
        histograms.createLegend(0.19 + dx, 0.75 + dy - legend_dh, 0.57 + dx,
                                0.80 + dy))
    histograms.moveLegend(plot.legend, dh=0.05, dy=-0.05)
    #plot.legend.SetFillColor(0)
    #plot.legend.SetFillStyle(1001)

    name = name.replace("-", "_")
    plot.createFrame(name,
                     opts={
                         "ymin": 0,
                         "ymax": tanbMax,
                         "xmin": 200,
                         "xmax": 3300
                     })
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts(cmsTextPosition=textPos)

    size = 20
    x = 0.2 + dx
    histograms.addText(x, 0.9 + dy, limit.process, size=size)
    histograms.addText(x, 0.863 + dy, limits.getFinalstateText(), size=size)
    histograms.addText(x,
                       0.815 + dy,
                       limit.getTypesetScenarioName(scenario.replace(
                           "_mu", "")),
                       size=size)
    histograms.addText(x, 0.767 + dy, "m_{H^{+}}=%d GeV" % mass, size=size)
    #    histograms.addText(0.2, 0.231, "Min "+limit.BR+"(t#rightarrowH^{+}b)#times"+limit.BR+"(H^{+}#rightarrow#tau#nu)", size=0.5*size)

    #Adding a LHC label:
    #    ROOT.LHCHIGGS_LABEL(0.97,0.72,1)
    #    FH_version = db.getVersion("FeynHiggs")
    #    histograms.addText(x, 0.55, FH_version)
    #    HD_version = db.getVersion("HDECAY")
    #    histograms.addText(x, 0.55, FH_version+" and "+HD_version, size=size)
    #    histograms.addText(x, 0.48, "Derived from", size=size)
    #    histograms.addText(x, 0.43, "CMS HIG-12-052", size=size)

    plot.save()

    print "Created", name
def analyze(analysis=None):

    paths = [sys.argv[1]]

    datasets = dataset.getDatasetsFromMulticrabDirs(paths)
#    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="SingleNeutrino")
#    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,includeOnlyTasks="QCD")

#    analysis = datasets.getAllDatasets()[0].getAnalysisName()

    #datasetsMC = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="ZeroBias")


    createRatio = False

#    for d in datasets.getAllDatasets():
#        print d.getName()

    style = tdrstyle.TDRStyle()

    dataset1 = datasets.getDataDatasets()
####    dataset1 = datasets.getMCDatasets()
    rateETM120 = 5521.35 # Hz
    #effETM120 = 0.000611208781402 #8.75017364672e-05
    #effETM120 = 0.000619219298648
    effETM120 = 0.000203698623826
####    effETM120 = 0.186701136914 # QCD
    scale = rateETM120/effETM120*0.001 #(Hz->kHz)
#    for d in dataset1:
#        d.scale(scale)
    dataset2 = dataset1
    createRatio = False

        #if isinstance(datasetsMC,dataset.DatasetManager):
        #    dataset2 = datasetsMC.getMCDatasets()
        #    createRatio = True

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

    scaleGraph(eff1PU,scale)


    namePU = "TauMET_"+analysis+"_nVtx"
    legend1 = "Data"
    legend2 = "Simulation"


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

    pPU = plots.PlotBase([histograms.HistoGraph(eff1PU, "eff1", "p", "P")])
    pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1})


    # Fit
#    yval = fit("Data",pPU,eff1PU,30,59)
    yval = fit("Data",pPU,eff1PU,5,59)

####    opts = {"ymin": 0, "ymax": 6, "xmax": 60}
    opts = {"ymin": 0, "ymax": 20, "xmax": 60}
####    opts = {"ymin": 0, "ymax": 300, "xmax": 60}
    opts2 = {"ymin": 0.5, "ymax": 1.5}
    moveLegend = {"dx": -0.5, "dy": -0.1, "dh": -0.1}

    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))

    pPU.getFrame().GetYaxis().SetTitle("L1 rate (kHz)")
    pPU.getFrame().GetXaxis().SetTitle("n vertices")
    if createRatio:
        pPU.getFrame2().GetYaxis().SetTitle("Ratio")
        pPU.getFrame2().GetYaxis().SetTitleOffset(1.6)

    pPU.draw()

    print "check frame min,max",pPU.getFrame().GetYaxis().GetXmin(),pPU.getFrame().GetYaxis().GetXmax()
    x = array.array('d',[55,55,0])
    y = array.array('d',[0,yval,yval])
    n = 3
    vert = ROOT.TGraph(n,x,y)
    vert.SetLineStyle(2)
    vert.SetLineColor(2)
    vert.SetLineWidth(2)
    vert.Draw("L")

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

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

    print "Output written in",plotDir
Exemple #41
0
def main():

    style    = tdrstyle.TDRStyle()

    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(parseOpts.batchMode)
    
    # Get all datasets from the mcrab dir
    datasetsMgr  = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)
    
    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))
    
    # Set custom XSections
    # d.getDataset("TT_ext3").setCrossSection(831.76)
    
    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something!

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))

    
    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):
        
        # Get the save path and name
        savePath, saveName = GetSavePathAndName(hName, **kwargs)

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs)
        
        # Create a comparison plot
        p = plots.ComparisonManyPlot(refHisto, otherHistos)


        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Create a frame
        if kwargs.get("logY"):
            opts = {"ymin": 1e-5, "ymaxfactor": 10}
        else:
            opts = {"ymin": 0.0, "ymaxfactor": 1.2}
        ratioOpts = {"ymin": 0.0, "ymax": 2.0}
        p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts)
        
        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        #p.removeLegend()

        # Customise frame
        p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
        #p.setEnergy("13")
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = { "lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames))
                
        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)
        
        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
Exemple #42
0
def main(opts):
    style = tdrstyle.TDRStyle()
    style.setOptStat(True)
    style.setWide(True, 0.15)

    ###    style = tdrstyle.TDRStyle()
    ###    #style.setWide(True)
    ###    style.setPaletteMy()
    ###    ROOT.gStyle.SetNumberContours(20)
    # tdrstyle.setDeepSeaPalette()
    # tdrstyle.setRainBowPalette()
    # tdrstyle.setDarkBodyRadiatorPalette()
    # tdrstyle.setGreyScalePalette()
    # tdrstyle.setTwoColorHuePalette()
    style.setWide(True, 0.15)

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

    # ========================================
    # Datasets
    # ========================================
    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)
    intLumi = GetLumi(datasetsMgr)
    datasetsMgr.updateNAllEventsToPUWeighted()
    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)

    # Merge datasts (Note: Merged MC histograms must be normalized to something)
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets
    if 0:
        datasetsMgr.remove("TTJets")
        datasetsMgr.remove(
            filter(lambda name: not "QCD" in name,
                   datasetsMgr.getAllDatasetNames()))

    # Print dataset information
    datasetsMgr.PrintInfo()

    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):
        savePath, saveName = GetSavePathAndName(hName, **kwargs)

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName,
                                                    **kwargs)

        # Create a plot
        p = plots.PlotBase([refHisto], kwargs.get("saveFormats"))

        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Customize
        # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL"
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015))
        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.00001))
        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.05))

        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(2))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(2))

        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0009))
        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0041))

        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0012))
        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.00435))

        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().GetZaxis().SetTitle("Arbitrary Units"))
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(2.))
        #ROOT.gPad.RedrawAxis()

        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin")))
        #        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax")))

        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.0}
        p.createFrame(saveName, opts=opts)

        # Customise frame
        p.getFrame().GetXaxis().SetTitle(getTitleX(refHisto, **kwargs))
        #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )

        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = {"lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"),
                           fillColor=kwargs.get("cutFillColour"),
                           box=kwargs.get("cutBox"),
                           line=kwargs.get("cutLine"),
                           **_kwargs)

        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))
        p.removeLegend()

        # Add MC Uncertainty (Invalid method for a 2-d histogram)
        #p.addMCUncertainty()
        # Customise histogram (after frame is created)
        #  Draw plots
        p.draw()

        # Customise text
        #Soti lumitext        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.17, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22)
        histograms.addText(0.17, 0.88,
                           plots._legendLabels[kwargs.get("refDataset")], 17)

        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter == 0)

    return
Exemple #43
0
def main():

    style = tdrstyle.TDRStyle()
    #style.setWide(True)
    style.setPaletteMy()
    ROOT.gStyle.SetNumberContours(20)
    # tdrstyle.setDeepSeaPalette()
    # tdrstyle.setRainBowPalette()
    # tdrstyle.setDarkBodyRadiatorPalette()
    # tdrstyle.setGreyScalePalette()
    # tdrstyle.setTwoColorHuePalette()
 
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(parseOpts.batchMode)
    
    # Get all datasets from the mcrab dir
    #datasetsMgr  = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))
    datasetsMgr  = GetDatasetsFromDir(parseOpts.mcrab, parseOpts, **kwargs)

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)
    
    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    #datasetsMgr.remove(kwargs.get("rmDataset"))
    datasetsMgr.remove(filter(lambda name: not kwargs.get("refDataset") in name, datasetsMgr.getAllDatasetNames()))

    # Set custom XSections
    # d.getDataset("TT_ext3").setCrossSection(831.76)
    
    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something!

    # Remove datasets (for merged names)
    # datasetsMgr.remove(kwargs.get("rmDataset"))
                  
    # For-loop: All Histogram names
    for hName in hNames:
        savePath, saveName = GetSavePathAndName(hName, **kwargs)                

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs)

        # Create a plot
        p = plots.PlotBase([refHisto], kwargs.get("saveFormats"))
        
        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Customize
        # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL"
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax")))
        
        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.0}
        p.createFrame(saveName, opts=opts)


        # Customise frame
        p.getFrame().GetXaxis().SetTitle( getTitleX(refHisto, **kwargs) )
        p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
        # p.getFrame().GetZaxis().SetTitle( getTitleZ(refHisto, **kwargs) ) #does not work
        
        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = { "lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)
        
        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        p.removeLegend()

        # Add MC Uncertainty (Invalid method for a 2-d histogram)
        #p.addMCUncertainty()
        
        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        #histograms.addText(0.16, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22)
        histograms.addText(0.20, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17)
        
        # Save canvas under custom dir
	if not os.path.exists(savePath):
		os.mkdir(savePath)
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
def main():

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

    paths = [sys.argv[1]]

    analysis = "METLeg_2015D_MET80"
#    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$")

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

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

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

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

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

    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"
    p.histoMgr.setHistoLegendLabelMany({"eff1_MET80": legend1, "eff2_MET80": 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)

    histograms.addText(0.2, 0.6, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17)
#    histograms.addText(0.2, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17)
    label = analysis.split("_")[1]
    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,"metLegTriggerEfficiency2015.json"))

    """
    #### 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_2015D_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)

    pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"),
                                   [histograms.HistoGraph(eff2PU, "eff2", "p", "P")])


    pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2})

    opts = {"ymin": 0.001, "ymax": 0.1}
    pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=opts, opts2=opts2)
    pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    pPU.getPad1().SetLogy(True)

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

    histograms.addText(0.4, 0.25, "LooseIsoPFTau50_Trk30_eta2p1_MET80", 17)
    histograms.addText(0.4, 0.18, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.4, 0.11, "Runs "+datasets.loadRunRange(), 17)

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

    pPU.save(formats)

    print "Output written in",plotDir
def doPlot(mass, mu, mul=None):
    f = openFile(mass)
    tree_obs = f.Get("TESTED_R%s"%mu)
    if not tree_obs:
        print "Did not find TESTED_R%s TTree in file %s" % (mu, f.GetName())
        listMu(mass, f)
        f.Close()
        return

    tree_sb = f.Get("SAMPLING_SB_TESTED_R%s" % mu)
    if not tree_sb:
        raise Exception("Did not find SAMPLING_SB_TESTED_R%s from file %s" % (mu, f.GetName()))
    tree_b = f.Get("SAMPLING_B_TESTED_R%s" % mu)
    if not tree_b:
        raise Exception("Did not find SAMPLING_B_TESTED_R%s from file %s" % (mu, f.GetName()))

    xmin = min(tree_sb.GetMinimum("brT"), tree_b.GetMinimum("brT"))
    xmax = max(tree_sb.GetMaximum("brT"), tree_b.GetMaximum("brT"))
    obsval = tree_obs.GetMinimum("brT")

    # Get the distributions
    tree_sb.Draw("brT >>hsb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_sb = tree_sb.GetHistogram()
    tree_b.Draw("brT >>hb(%d, %f, %f)" % (nbins, xmin, xmax), "", "goff")
    h_b = tree_b.GetHistogram()

    # Set obsval to bin boundary
    obsval_bin = obsval
    for bin in xrange(0, h_sb.GetNbinsX()+1):
        edge = h_sb.GetBinLowEdge(bin)
        if obsval > edge:
            obsval_bin = edge

    # Normalize the distributions to unit area
    dataset._normalizeToOne(h_sb)
    dataset._normalizeToOne(h_b)

    plot = plots.PlotBase([
            histograms.Histo(h_b, "B"),
            histograms.Histo(h_sb, "SB")
            ])
    mulegend = mul
    if mul == None:
        mulegend = mu
    plot.histoMgr.setHistoLegendLabelMany({
            "B":  "f(#tilde{q}_{#mu=%s} | #mu=0, #hat{#bf{#theta}}_{0}^{obs})" % mulegend,
            "SB": "f(#tilde{q}_{#mu=%s} | #mu=%s, #hat{#bf{#theta}}_{#mu=%s}^{obs})" % (mulegend, mulegend, mulegend),
            })
    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.6, 0.8, 0.9, 0.9), dy=0.02, dx=-0.05))
    plot.histoMgr.forEachHisto(styles.generator())

    fname = "teststat_m%s_mu%s" % (mass, mu)
    plot.createFrame(fname.replace(".", "_"), opts={"ymin": 1e-6, "ymaxfactor": 2})
    plot.frame.GetXaxis().SetTitle("Test statistic #tilde{q}_{#mu}")
    plot.frame.GetYaxis().SetTitle("Arbitrary units")
    plot.getPad().SetLogy(True)

    area_sb = h_sb.Clone("AreaSB")
    area_sb.SetFillColor(area_sb.GetLineColor())
    area_sb.SetFillStyle(3005)
    area_sb.SetLineWidth(0)

    area_b = h_b.Clone("AreaB")
    area_b.SetFillColor(area_b.GetLineColor())
    area_b.SetFillStyle(3004)
    area_b.SetLineWidth(0)
    for bin in xrange(0, area_sb.GetNbinsX()+1):
        if area_sb.GetBinLowEdge(bin) < obsval_bin:
            area_sb.SetBinContent(bin, 0)
        if area_b.GetBinLowEdge(bin) >= obsval_bin:
            area_b.SetBinContent(bin, 0)

    plot.appendPlotObject(area_b, "HIST ][")
    plot.appendPlotObject(area_sb, "HIST ][")

    plot.addCutBoxAndLine(box=False, cutValue=obsval_bin)


    plot.draw()

    size = 26
    histograms.addText(0.35, 0.4, "CL_{s+b}", size=size)
    histograms.addText(0.18, 0.4, "1-CL_{b}", size=size)

    size = 20
#    x = obsval_bin/(plot.frame.GetXaxis().GetXmax() - plot.frame.GetXaxis().GetXmin())+0.02
    x = (obsval_bin - plot.getPad().GetX1()) / (plot.getPad().GetX2() - plot.getPad().GetX1())
    x += 0.01
    histograms.addText(x, 0.88, "Observed", size=size)
    histograms.addText(x, 0.85, "value", size=size)

    histograms.addText(0.62, 0.78, "m_{H^{+}} = %s %s" % (mass, limit.massUnit()), size=size)

#    size = 20
#    x = 0.2
#    histograms.addText(x, 0.88, brlimit.process, size=size)
#    histograms.addText(x, 0.84, brlimit._finalstateLabels["taujets"], size=size)
#    histograms.addText(x, 0.79, brlimit.BRassumption, size=size)

    plot.save()

    f.Close()
def main(opts):

    style = tdrstyle.TDRStyle()
    #style.setWide(True)
    style.setPaletteMy()
    ROOT.gStyle.SetNumberContours(20)
    # tdrstyle.setDeepSeaPalette()
    # tdrstyle.setRainBowPalette()
    # tdrstyle.setDarkBodyRadiatorPalette()
    # tdrstyle.setGreyScalePalette()
    # tdrstyle.setTwoColorHuePalette()
 
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(opts.batchMode)
    
    # ========================================
    # Datasets
    # ========================================
    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts.mcrab, opts, **kwargs)
    intLumi     = GetLumi(datasetsMgr)
    datasetsMgr.updateNAllEventsToPUWeighted()
    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)
    
    # Merge datasts (Note: Merged MC histograms must be normalized to something)
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets
    if 0:
        datasetsMgr.remove("TTJets")
        datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    
    # Print dataset information
    datasetsMgr.PrintInfo()
                  
    # For-loop: All Histogram names
    for counter, hName in enumerate(hNames):
        savePath, saveName = GetSavePathAndName(hName, **kwargs)                

        # Get Histos for Plotter
        refHisto, otherHistos = GetHistosForPlotter(datasetsMgr, hName, **kwargs)

        # Create a plot
        p = plots.PlotBase([refHisto], kwargs.get("saveFormats"))
        
        # Remove negative contributions
        #RemoveNegativeBins(datasetsMgr, hName, p)

        # Customize
        # p.histoMgr.setHistoDrawStyleAll("COL") #"CONT4" "COLZ" "COL"
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(kwargs.get("rebinX")))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(kwargs.get("rebinY")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetXaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetYaxis().SetRangeUser(1.0, 5.0))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(0.0, 0.015))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(kwargs.get("zMin")))
        # p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(kwargs.get("zMax")))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(2))
        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(2))

#        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMinimum(0.0015))
#        p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMaximum(0.0045))



        
        # Create a frame
        opts = {"ymin": 0.0, "ymaxfactor": 1.0}
        p.createFrame(saveName, opts=opts)


        # Customise frame
        p.getFrame().GetXaxis().SetTitle( getTitleX(refHisto, **kwargs) )
        #p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
        
        # SetLog
        SetLogAndGrid(p, **kwargs)

        # Add cut line/box
        _kwargs = { "lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)
        
        # Customise Legend
        moveLegend = {"dx": -0.1, "dy": +0.0, "dh": -0.1}
        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        p.removeLegend()

        # Add MC Uncertainty (Invalid method for a 2-d histogram)
        #p.addMCUncertainty()
        
        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.17, 0.95, plots._legendLabels[kwargs.get("refDataset")], 22)
        histograms.addText(0.17, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17)
        
        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"), counter==0)

    return
Exemple #47
0
def main(argv):

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

    dirs.append(sys.argv[1])

    dirs_signal = ["../../SignalAnalysis_140605_143702/"]

    QCDInvertedNormalization = sort(
        QCDInvertedNormalizationFactors.QCDInvertedNormalization)
    labels, QCDInvertedNormalizationFilteredEWKFakeTaus = getSortedLabelsAndFactors(
        QCDInvertedNormalizationFactorsFilteredEWKFakeTaus.
        QCDInvertedNormalization)

    analysis_inverted = "signalAnalysisInvertedTau"
    analysis = "signalAnalysis"

    optModes = []
    #optModes.append("OptQCDTailKillerZeroPlus")
    optModes.append("OptQCDTailKillerLoosePlus")
    optModes.append("OptQCDTailKillerMediumPlus")
    optModes.append("OptQCDTailKillerTightPlus")

    varHistoName = "shapeEWKGenuineTausTransverseMass"
    nomHistoName = "shapeTransverseMass"
    signalHistoName = "shapeEWKFakeTausTransverseMass"

    #Optimal: 0.8, 0.82, 0.9

    ###w_list = [0.65, 0.7, 0.76] #old baseline ft
    w_list = [0.66, 0.67, 0.75]
    #w_list = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1]

    #defaultBinning = systematics.getBinningForPlot("shapeTransverseMass")
    defaultBinning = [0, 20, 40, 60, 80, 100, 120, 140, 160, 200, 400]
    defaultBinning_array = array.array("d", defaultBinning)

    diff_opt = []
    for optMode in optModes:
        diff_list = []
        for w in w_list:
            var_values = []
            nom_values = []

            # baseline fake taus
            mt_baseline_faketaus_data = getDataSets(dirs_signal, dataEra,
                                                    searchMode, analysis,
                                                    optMode)
            mtplot_signalfaketaus = plots.DataMCPlot(mt_baseline_faketaus_data,
                                                     signalHistoName)
            mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto(
                "EWK").getRootHisto().Clone(signalHistoName)

            # inverted fake taus
            mt_inverted_faketaus_data = getDataSets(dirs, dataEra, searchMode,
                                                    analysis_inverted, optMode)

            histonames_var = mt_inverted_faketaus_data.getDataset(
                "Data").getDirectoryContent(varHistoName)
            histonames_nom = mt_inverted_faketaus_data.getDataset(
                "Data").getDirectoryContent(nomHistoName)

            bins_var = getBins(histonames_var, varHistoName)
            bins_nom = getBins(histonames_nom, nomHistoName)

            normalization_var_qg = getNormalization(
                bins_var, w, QCDInvertedNormalizationFilteredEWKFakeTaus, True,
                True)
            normalization_var = getNormalization(
                bins_var, w, QCDInvertedNormalizationFilteredEWKFakeTaus, True,
                False)
            normalization_nom = getNormalization(bins_nom, w,
                                                 QCDInvertedNormalization,
                                                 False, False)

            mt_var_qg = getMt(mt_inverted_faketaus_data, bins_var,
                              varHistoName, normalization_var_qg)
            mt_var = getMt(mt_inverted_faketaus_data, bins_var, varHistoName,
                           normalization_var)
            mt_nom = getMt(mt_inverted_faketaus_data, bins_nom, nomHistoName,
                           normalization_nom)

            mt_nom.Add(mt_signalfaketaus)

            mt_var_qg.SetName(
                "QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau), q-g bal.")
            mt_var.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)")
            mt_nom.SetName("QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)")

            mt_var_qg.SetLineWidth(4)
            mt_var.SetLineColor(14)
            mt_nom.SetLineColor(2)

            mt_var_qg = mt_var_qg.Rebin(
                len(defaultBinning) - 1, "", defaultBinning_array)
            mt_var = mt_var.Rebin(
                len(defaultBinning) - 1, "", defaultBinning_array)
            mt_nom = mt_nom.Rebin(
                len(defaultBinning) - 1, "", defaultBinning_array)

            for i in range(0, mt_nom.GetSize()):
                var_values.append(mt_var_qg.GetBinContent(i))
                nom_values.append(mt_nom.GetBinContent(i))

            style = tdrstyle.TDRStyle()

            varPlots = [mt_var, mt_var_qg]
            plot = plots.ComparisonManyPlot(mt_nom, varPlots)
            plot.createFrame(optMode.replace(
                "Opt", "Mt_DataDrivenVsMC_" + "w=" + str(w) + "_"),
                             createRatio=True)

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

            plot.draw()
            plot.save()

            mt_var_qg.Delete()
            mt_var.Delete()
            mt_nom.Delete()

            #TFile.CurrentFile().Close("R")
            mt_baseline_faketaus_data.close()
            mt_inverted_faketaus_data.close()
            ROOT.gROOT.CloseFiles()
            ROOT.gROOT.GetListOfCanvases().Delete()
            ROOT.gDirectory.GetList().Delete()

            #print var_values
            #print nom_values

            # difference metrics
            num = 0
            denom = 0
            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)

    os.system("rm MtOptimal/*")
    os.system("mkdir -p MtOptimal")
    print "\nWeights:\t", w_list, '\n'
    optimalWeights = {}
    for i in range(0, len(diff_opt)):
        print optModes[i]
        print "Differences:\t", diff_opt[i], "- Optimal: w =", w_list[
            diff_opt[i].index(min(diff_opt[i]))]
        optimalWeights[optModes[i]] = w_list[diff_opt[i].index(min(
            diff_opt[i]))]
        command = "cp *" + str(w_list[diff_opt[i].index(min(
            diff_opt[i]))]) + "*" + optModes[i].replace("Opt",
                                                        "") + ".eps MtOptimal"
        os.system(command)
    print optimalWeights
    writeWeightsToFile("OptimalWeights.py", optimalWeights)
    writeNormalizationToFile("QCDPlusEWKFakeTauNormalizationFactors.py",
                             normalization_var_qg, labels)
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")

    for optMode in optModes:
        plot = plots.PlotBase()
        color = 1

        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")
        
        for HISTONAME in histoNameList:
            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)

            invjet_name = "MTInvertedTauIdAfterAllSelectionsPlusJetFakeTau"
            basejet_name = "MTBaselineTauIdAfterAllSelectionsPlusJetFakeTau"

            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)
                    
                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        legendName = "Data-driven Fake Taus"
                    else:
                        legendName = "Simulated Fake Taus"
                    legendName = legendName.replace("Plus","")
                    mt.SetName(legendName)
                    mt.SetLineColor(color)
                    mt.Add(mt_ewk,-1)
                    
                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        mt.Scale(QCDInvertedNormalizationFilteredEWKFakeTaus[str(i)])
                    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)
                    h.Add(mt_ewk,-1)
                    if HISTONAME == "shapeEWKGenuineTausTransverseMass":
                        h.Scale(QCDInvertedNormalizationFilteredEWKFakeTaus[str(i)])
                    else:
                        h.Scale(QCDInvertedNormalization[str(i)])
                    mt.Add(h)
            if HISTONAME == "shapeTransverseMass":
                mt.Add(mt_signalfaketaus)

            
            plot.histoMgr.appendHisto(histograms.Histo(mt,mt.GetName()))
            
            style = tdrstyle.TDRStyle()

        #plot.createFrame("mt")
        #plot.createFrame(HISTONAME.replace("shape","final"))
        plot.createFrame(optMode.replace("Opt","Mt_DataDrivenVsMC_"))
        moveLegend={"dx": -0.3,"dy": 0.}
        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()
Exemple #49
0
def main(opts):

    style    = tdrstyle.TDRStyle()
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(opts.batchMode)
    
    # Get all datasets from the mcrab dir
    # def GetDatasetsFromDir(mcrab, opts, **kwargs): #iro
    datasetsMgr       = GetDatasetsFromDir(opts.mcrab, opts, **kwargs) #kwargs.get("analysis"))

    # Determine Integrated Luminosity (If Data datasets present)
    intLumi = GetLumi(datasetsMgr)
    
    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()

    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))
    
    # Set custom XSections
    #datasetsMgr.getDataset("QCD_bEnriched_HT1000to1500").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT1500to2000").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT2000toInf").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT300to500").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT500to700").setCrossSection(1.0)
    #datasetsMgr.getDataset("QCD_bEnriched_HT700to1000").setCrossSection(1.0)
    
    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr)

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))
    
    # Print the cross
    datasetsMgr.PrintCrossSections()

    for h_prefix in ["reco"]:
        # Get ref histo here and the fixed histos (TT, QCD, QCD-b
        inclusiveHisto, fixedHistos = GetHistosForPlotter(datasetsMgr, h_prefix + "MET_Et", **kwargs)
        inclusiveHisto.setName("Inclusive")
        inclusiveHisto.setLegendLabel("Inclusive")
        #for hi in fixedHistos:
        #    print(type(hi), hi.getName())
        #return
        # For-loop: All Histogram names
        for counter, hName in enumerate(hNames):
            # Get the save path and name
            savePath, saveName = GetSavePathAndName(h_prefix + hName[0], **kwargs)
            saveName = savePath + h_prefix + hSaveNames[counter]

            # Get Histos for Plotter
            refHisto_, otherHistos_ = GetHistosForPlotter(datasetsMgr, h_prefix + hName[0], **kwargs)
            refHisto1, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[1], **kwargs)
            refHisto2, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[2], **kwargs)
            refHisto3, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[3], **kwargs)
            refHisto4, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[4], **kwargs)
            refHisto5, otherHistos2 = GetHistosForPlotter(datasetsMgr, h_prefix + hName[5], **kwargs)
            refHisto = inclusiveHisto

            # customize histos
            refHisto_.setName(hLegends[counter][0])
            refHisto_.setLegendLabel(hLegends[counter][0])
            refHisto_.setDrawStyle("P")
            refHisto_.setLegendStyle("P")
            styleDict[hStyles[0]].apply(refHisto_.getRootHisto())

            refHisto1.setName(hLegends[counter][1])
            refHisto1.setLegendLabel(hLegends[counter][1])
            refHisto1.setDrawStyle("P")
            refHisto1.setLegendStyle("P")
            styleDict[hStyles[1]].apply(refHisto1.getRootHisto())

            refHisto2.setName(hLegends[counter][2])
            refHisto2.setLegendLabel(hLegends[counter][2])
            refHisto2.setDrawStyle("P")
            refHisto2.setLegendStyle("P")
            styleDict[hStyles[2]].apply(refHisto2.getRootHisto())

            refHisto3.setName(hLegends[counter][3])
            refHisto3.setLegendLabel(hLegends[counter][3])
            refHisto3.setDrawStyle("P")
            refHisto3.setLegendStyle("P")
            styleDict[hStyles[3]].apply(refHisto3.getRootHisto())

            refHisto4.setName(hLegends[counter][4])
            refHisto4.setLegendLabel(hLegends[counter][4])
            refHisto4.setDrawStyle("P")
            refHisto4.setLegendStyle("P")
            styleDict[hStyles[4]].apply(refHisto4.getRootHisto())

            refHisto5.setName(hLegends[counter][5])
            refHisto5.setLegendLabel(hLegends[counter][5])
            refHisto5.setDrawStyle("P")
            refHisto5.setLegendStyle("P")
            styleDict[hStyles[5]].apply(refHisto5.getRootHisto())

            otherHistos = [refHisto_, refHisto1, refHisto2, refHisto3, refHisto4, refHisto5]
            #for hi in otherHistos:
            #     print hi.getName()
            #return

            # Create a comparison plot
            p = plots.ComparisonManyPlot(refHisto, otherHistos)

            # Remove negative contributions
            #RemoveNegativeBins(datasetsMgr, hName, p)

            # Create a frame
            if kwargs.get("logY")==True:
                opts = {"ymin": 8e-5, "ymax": 2}
                #opts = {"ymin": 1e-3, "ymax": 1}
            else:
                opts = {"ymin": 8.e-5, "ymax": 2}
            ratioOpts = {"ymin": 0.1, "ymax": 10.0}
            p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts)
            
            # Customise Legend
            moveLegend = {"dx": -0.2, "dy": +0.0, "dh": -0.1}
            p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
            #p.removeLegend()

            # Customise frame
            p.getFrame().GetYaxis().SetTitle( getTitleY(refHisto, **kwargs) )
            #p.setEnergy("13")
            if kwargs.get("createRatio"):
                p.getFrame2().GetYaxis().SetTitle("Ratio")
                p.getFrame2().GetYaxis().SetTitleOffset(1.7)

            # SetLog
            SetLogAndGrid(p, **kwargs)

            # Add cut line/box
            _kwargs = { "lessThan": kwargs.get("cutLessThan")}
            p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)
            
            # Move the refDataset to first in the draw order (back)
            histoNames = [h.getName() for h in p.histoMgr.getHistos()]
            p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames))
            p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Rebin(2))

            #  Draw plots
            p.draw()

            # Customise text
            histograms.addStandardTexts(lumi=intLumi)
            # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
            histograms.addText(0.2, 0.88, plots._legendLabels[kwargs.get("refDataset")], 17)

            # Save canvas under custom dir
            if not os.path.exists(savePath):
                    os.mkdir(savePath)
            SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
Exemple #50
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
def doPlotMu(name, graphs, styleList, limits, xlabel, xvarName, legendVariable):
    objs = []
    ll = {}
    cutValue = 100 # for cutting a slice +- cutValue around 0 from the (mu,tanb) plot
    for gr, mu in graphs:
        if xvarName == "mu":
            histo = histograms.HistoGraph(gr, "Obs%d"%mu, drawStyle="LP", legendStyle="lp")
            plus  = gr.Clone()
            minus = gr.Clone()
            N = gr.GetN()
            for i in range(0,N):
                j = N - 1 - i
                x = gr.GetX()[j]
                if x > -cutValue:
                    minus.RemovePoint(j)
                if x < cutValue:
                    plus.RemovePoint(0)
            objs.append(histograms.HistoGraph(minus, "Obs%d"%mu, drawStyle="LP", legendStyle="lp"))
            objs.append(histograms.HistoGraph(plus, "ObsCopy%d"%mu, drawStyle="LP", legendStyle="lp"))
            ll["ObsCopy%d"%mu] = None
                
        else:
            objs.append(histograms.HistoGraph(gr, "Obs%d"%mu, drawStyle="LP", legendStyle="lp"))
        ll["Obs%d"%mu] = "Observed, "+legendVariable+"=%d %s" % (mu, limit.massUnit())
#        N = gr.GetN()
#        for i in range(0,N):
#            j = N - 1 - i
#            if gr.GetY()[j] == 1:
#                gr.RemovePoint(j)

    plot = plots.PlotBase(objs)
    if xvarName == "mu":
        doubleStyleList = []
        for style in styleList:
            doubleStyleList.append(style)
            doubleStyleList.append(style)
        plot.histoMgr.forEachHisto(styles.Generator(doubleStyleList))
    else:
        plot.histoMgr.forEachHisto(styles.Generator(styleList))
    plot.histoMgr.setHistoLegendLabelMany(ll)
    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.57, 0.155, 0.87, 0.355), dx=-0.1))

    plot.createFrame(name, opts={"ymin": 0, "ymax": tanbMax})
    plot.frame.GetXaxis().SetTitle(xlabel)
    plot.frame.GetXaxis().SetLabelSize(20)
    plot.frame.GetYaxis().SetTitle(limit.tanblimit)

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.9, limit.process, size=size)
    histograms.addText(x, 0.863, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.815, "MSSM m_{h}^{max}", size=size)
#    histograms.addText(x, 0.775, limit.BRassumption, size=size)

    histograms.addText(x, 0.72, "FeynHiggs 2.9.4", size=size)
    histograms.addText(x, 0.65, "Derived from", size=size)
    histograms.addText(x, 0.6, "CMS HIG-12-052", size=size)
#    histograms.addText(x, 0.6, "CMS HIG-11-019", size=size)
#    histograms.addText(x, 0.55, "JHEP07(2012)143", size=size)
    
    #Adding a LHC label:
    ROOT.LHCHIGGS_LABEL(0.97,0.72,1)
                    
    plot.save()

    print
    print "Plotting",name
    print
def main(argv):

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

    dirs.append(sys.argv[1])

    dirs_signal = ["../../SignalAnalysis_140605_143702/"]

    QCDInvertedNormalization = sort(QCDInvertedNormalizationFactors.QCDInvertedNormalization)
    labels,QCDInvertedNormalizationFilteredEWKFakeTaus = getSortedLabelsAndFactors(QCDInvertedNormalizationFactorsFilteredEWKFakeTaus.QCDInvertedNormalization)

    analysis_inverted = "signalAnalysisInvertedTau"
    analysis = "signalAnalysis"

    optModes = []
    #optModes.append("OptQCDTailKillerZeroPlus")
    optModes.append("OptQCDTailKillerLoosePlus") 
    optModes.append("OptQCDTailKillerMediumPlus") 
    optModes.append("OptQCDTailKillerTightPlus") 

    varHistoName = "shapeEWKGenuineTausTransverseMass"
    nomHistoName = "shapeTransverseMass"
    signalHistoName = "shapeEWKFakeTausTransverseMass"

    #Optimal: 0.8, 0.82, 0.9

    ###w_list = [0.65, 0.7, 0.76] #old baseline ft
    w_list = [0.66, 0.67, 0.75]
    #w_list = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 1]
    
    #defaultBinning = systematics.getBinningForPlot("shapeTransverseMass")
    defaultBinning = [0,20,40,60,80,100,120,140,160,200,400]
    defaultBinning_array = array.array("d",defaultBinning)

    diff_opt = []
    for optMode in optModes:
        diff_list = []
        for w in w_list:
            var_values = []
            nom_values = []

            # baseline fake taus
            mt_baseline_faketaus_data = getDataSets(dirs_signal, dataEra, searchMode, analysis, optMode)
            mtplot_signalfaketaus = plots.DataMCPlot(mt_baseline_faketaus_data, signalHistoName)
            mt_signalfaketaus = mtplot_signalfaketaus.histoMgr.getHisto("EWK").getRootHisto().Clone(signalHistoName)

            # inverted fake taus
            mt_inverted_faketaus_data = getDataSets(dirs, dataEra, searchMode, analysis_inverted, optMode)

            histonames_var = mt_inverted_faketaus_data.getDataset("Data").getDirectoryContent(varHistoName)
            histonames_nom = mt_inverted_faketaus_data.getDataset("Data").getDirectoryContent(nomHistoName)


            bins_var = getBins(histonames_var, varHistoName)
            bins_nom = getBins(histonames_nom, nomHistoName)

            normalization_var_qg = getNormalization(bins_var,w,QCDInvertedNormalizationFilteredEWKFakeTaus,True,True)
            normalization_var = getNormalization(bins_var,w,QCDInvertedNormalizationFilteredEWKFakeTaus,True,False)
            normalization_nom = getNormalization(bins_nom,w,QCDInvertedNormalization,False,False)

            mt_var_qg = getMt(mt_inverted_faketaus_data,bins_var,varHistoName,normalization_var_qg)
            mt_var = getMt(mt_inverted_faketaus_data,bins_var,varHistoName,normalization_var)
            mt_nom = getMt(mt_inverted_faketaus_data,bins_nom,nomHistoName,normalization_nom)
                
            mt_nom.Add(mt_signalfaketaus)

            mt_var_qg.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau), q-g bal.")
            mt_var.SetName("QCD(Data)+EWK+t#bar{t}(Data, mis-ID. #tau)")
            mt_nom.SetName("QCD(Data)+EWK+t#bar{t}(MC, mis-ID. #tau)")

            mt_var_qg.SetLineWidth(4)
            mt_var.SetLineColor(14)
            mt_nom.SetLineColor(2)
            
            mt_var_qg = mt_var_qg.Rebin(len(defaultBinning)-1,"",defaultBinning_array)
            mt_var = mt_var.Rebin(len(defaultBinning)-1,"",defaultBinning_array)
            mt_nom = mt_nom.Rebin(len(defaultBinning)-1,"",defaultBinning_array)

            for i in range(0,mt_nom.GetSize()):
                var_values.append(mt_var_qg.GetBinContent(i))
                nom_values.append(mt_nom.GetBinContent(i))
                
            style = tdrstyle.TDRStyle()

            varPlots = [mt_var, mt_var_qg]
            plot = plots.ComparisonManyPlot(mt_nom,varPlots)
            plot.createFrame(optMode.replace("Opt","Mt_DataDrivenVsMC_"+"w="+str(w)+"_"), createRatio=True)

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

            plot.draw()
            plot.save()

            mt_var_qg.Delete()
            mt_var.Delete()
            mt_nom.Delete()

            #TFile.CurrentFile().Close("R")
            mt_baseline_faketaus_data.close()
            mt_inverted_faketaus_data.close()
            ROOT.gROOT.CloseFiles()
            ROOT.gROOT.GetListOfCanvases().Delete()
            ROOT.gDirectory.GetList().Delete()

            #print var_values
            #print nom_values
            
            # difference metrics
            num = 0
            denom = 0
            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)

    os.system("rm MtOptimal/*")
    os.system("mkdir -p MtOptimal")
    print "\nWeights:\t",w_list,'\n'
    optimalWeights = {}
    for i in range(0,len(diff_opt)):
        print optModes[i]
        print "Differences:\t",diff_opt[i],"- Optimal: w =",w_list[diff_opt[i].index(min(diff_opt[i]))]
        optimalWeights[optModes[i]] = w_list[diff_opt[i].index(min(diff_opt[i]))]
        command = "cp *" + str(w_list[diff_opt[i].index(min(diff_opt[i]))])+"*"+optModes[i].replace("Opt","") + ".eps MtOptimal"
        os.system(command)
    print optimalWeights
    writeWeightsToFile("OptimalWeights.py",optimalWeights)
    writeNormalizationToFile("QCDPlusEWKFakeTauNormalizationFactors.py",normalization_var_qg,labels)
def doLimitError(limits, unblindedStatus):
    expRelErrors = []
    expLabels    = {}
    obsRelErrors = []
    obsLabels    = {}

    order = [0, 1, -1, 2, -2]
    expErrors = [limits.expectedErrorGraph(sigma=s) for s in order]
    if expErrors[0] != None:
        exps = [limits.expectedGraph(sigma=s) for s in order]
        expRelErrors = [(limit.divideGraph(expErrors[i], exps[i]), "ExpRelErr%d"%i) for i in xrange(len(exps))]
        expLabels = {
            "ExpRelErr0": "Expected median",
            "ExpRelErr1": "Expected +1#sigma",
            "ExpRelErr2": "Expected -1#sigma",
            "ExpRelErr3": "Expected +2#sigma",
            "ExpRelErr4": "Expected -2#sigma",
            }

    if unblindedStatus:
        obsErr = limits.observedErrorGraph()
        if obsErr != None:
            obs = limits.observedGraph()
            if obs != None:
                obsRelErrors = [(limit.divideGraph(obsErr, obs), "ObsRelErr")]
                obsLabels = {"ObsRelErr": "Observed"}

    if len(expRelErrors) == 0 and len(obsRelErrors) == 0:
        return

    # Create the plot
    plot = plots.PlotBase()
    if len(expRelErrors) > 0:
        plot.histoMgr.extendHistos([histograms.HistoGraph(x[0], x[1], drawStyle="PL", legendStyle="lp") for x in expRelErrors])
        plot.histoMgr.forEachHisto(styles.generator())
        def sty(h):
            r = h.getRootHisto()
            r.SetLineStyle(1)
            r.SetLineWidth(3)
            r.SetMarkerSize(1.4)
        plot.histoMgr.forEachHisto(sty)
        plot.histoMgr.setHistoLegendLabelMany(expLabels)
    if unblindedStatus:
        if len(obsRelErrors) > 0:
            obsRelErrors[0][0].SetMarkerSize(1.4)
            obsRelErrors[0][0].SetMarkerStyle(25)
            plot.histoMgr.insertHisto(0, histograms.HistoGraph(obsRelErrors[0][0], obsRelErrors[0][1], drawStyle="PL", legendStyle="lp"))
            plot.histoMgr.setHistoLegendLabelMany(obsLabels)

    plot.setLegend(histograms.moveLegend(histograms.createLegend(0.48, 0.75, 0.85, 0.92), dx=0.1, dy=-0.1))
 
    if len(limits.mass) == 1:
        plot.createFrame("limitsBrRelativeUncertainty", opts={"xmin": limits.mass[0]-5.0, "xmax": limits.mass[0]+5.0,  "ymin": 0, "ymaxfactor": 1.5})
    else:
        plot.createFrame("limitsBrRelativeUncertainty", opts={"ymin": 0, "ymaxfactor": 1.5})
    plot.frame.GetXaxis().SetTitle(limit.mHplus())
    plot.frame.GetYaxis().SetTitle("Uncertainty/limit")

    plot.draw()

    plot.setLuminosity(limits.getLuminosity())
    plot.addStandardTexts()

    size = 20
    x = 0.2
    histograms.addText(x, 0.88, limit.process, size=size)
    histograms.addText(x, 0.84, limits.getFinalstateText(), size=size)
    histograms.addText(x, 0.79, limit.BRassumption, size=size)

    size = 22
    x = 0.55
    histograms.addText(x, 0.88, "Toy MC relative", size=size)
    histograms.addText(x, 0.84, "statistical uncertainty", size=size)

    plot.save()
def PlotHistosAndCalculateTF(datasetsMgr, histoList, binLabels, opts):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    efficiencyList = []
    xValues = []

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

    nBins = hSignal_250.GetNbinsX() + 1

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

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

    for i in range(0, nBins):

        # Cut value
        cut = hSignal_250.GetBinCenter(i)

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

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

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

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

        eff_Bkg = float(passed_Bkg) / total_Bkg

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

        yValues_Bkg.append(eff_Bkg)

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

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

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

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

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

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

    # Add Standard Texts to plot
    histograms.addStandardTexts()

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

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

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

    SignalName = "ChargedHiggs_HplusTB_HplusToTB_M_800"

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

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

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

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

    nBins = hSignif_250.GetNbinsX() + 1

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

        sigmaB = ROOT.Double(0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    #=========================================================================================
    # Calculate the Transfer Factor (TF) and save to file
    #=========================================================================================
    Verbose("Write the normalisation factors to a python file", True)
    fileName = os.path.join(
        opts.mcrab, "FakeBTransferFactors%s.py" % (getModuleInfoString(opts)))
    manager.writeNormFactorFile(fileName, opts)
    return
Exemple #55
0
def main():

    style = tdrstyle.TDRStyle()
    
    # Set ROOT batch mode boolean
    ROOT.gROOT.SetBatch(parseOpts.batchMode)
    ROOT.gErrorIgnoreLevel = 3000
    
    # Get all datasets from the mcrab dir
    datasetsMgr  = GetDatasetsFromDir(parseOpts.mcrab, kwargs.get("analysis"))
    # datasetsMgr  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), includeOnlyTasks="ChargedHiggs_HplusTB_HplusToTB_M_200")
    # datasetsMgr  = dataset.getDatasetsFromMulticrabDirs([parseOpts.mcrab], analysisName=kwargs.get("analysis"), excludeTasks="M_200")

    # Determine Integrated Luminosity
    intLumi = GetLumi(datasetsMgr)

    # Update to PU
    datasetsMgr.updateNAllEventsToPUWeighted()
    
    # Remove datasets
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))
    
    # Set custom XSections
    # datasetsMgr.getDataset("TT_ext3").setCrossSection(831.76)
    
    
    # Default merging & ordering: "Data", "QCD", "SingleTop", "Diboson"
    plots.mergeRenameReorderForDataMC(datasetsMgr) #WARNING: Merged MC histograms must be normalized to something!

    # Remove datasets (for merged names)
    datasetsMgr.remove(kwargs.get("rmDataset"))
    # datasetsMgr.remove(filter(lambda name: not "QCD" in name, datasetsMgr.getAllDatasetNames()))
    # datasetsMgr.remove(filter(lambda name: "QCD" in name in name, datasetsMgr.getAllDatasetNames()))

    
    # For-loop: All Histogram names
    for hName in hNames:
    
        savePath, saveName = GetSavePathAndName(hName, **kwargs)
    
        # Get efficiency histos
        refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFCP", **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFFC", **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kBJeffrey", **kwargs)
        # refEff, otherEff = GetCutEfficiencyTGraphs(datasetsMgr, hName, "kFNormal", **kwargs)

        # Plot the efficiencies
        p = plots.ComparisonManyPlot(refEff, otherEff)        
                
        # Create a frame
        opts      = {"ymin": 0.0, "ymaxfactor": 1.2} #"ymax": 5e-1}
        ratioOpts = {"ymin": 0.0, "ymaxfactor": 1.2}
        p.createFrame(saveName, createRatio=kwargs.get("createRatio"), opts=opts, opts2=ratioOpts)
        
        # Customise Legend
        moveLegend = {"dx": -0.1 , "dy": +0.0, "dh": -0.1}
        p.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
        #p.removeLegend()
        
        # Customise frame
        # p.setEnergy("13")
        if kwargs.get("createRatio"):
            p.getFrame2().GetYaxis().SetTitle("Ratio")
            p.getFrame2().GetYaxis().SetTitleOffset(1.6)

        # SetLog
        SetLogAndGrid(p, **kwargs)

        
        # Add cut line/box
        _kwargs = { "lessThan": kwargs.get("cutLessThan")}
        p.addCutBoxAndLine(cutValue=kwargs.get("cutValue"), fillColor=kwargs.get("cutFillColour"), box=kwargs.get("cutBox"), line=kwargs.get("cutLine"), **_kwargs)

        # Move the refDataset to first in the draw order (back)
        histoNames = [h.getName() for h in p.histoMgr.getHistos()]
        p.histoMgr.reorder(filter(lambda n: plots._legendLabels[kwargs.get("refDataset") ] not in n, histoNames))
        
        #  Draw plots
        p.draw()

        # Customise text
        histograms.addStandardTexts(lumi=intLumi)
        # histograms.addText(0.4, 0.9, "Alexandros Attikis", 17)
        # histograms.addText(0.4, 0.11, "Runs " + datasetsMgr.loadRunRange(), 17)

        
        # Save canvas under custom dir
        SaveAs(p, savePath, saveName, kwargs.get("saveFormats"))

    return
Exemple #56
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()
Exemple #57
0
def Fit(datasets, histo, function):

    FitList = []
    for dataset in datasets:

        datasetName = dataset.getName()
        print "Dataset = ", datasetName
        hh = dataset.getDatasetRootHisto(histo)

        hh.normalizeToOne()
        h = hh.getHistogram()

        #h = dataset.getDatasetRootHisto(histo).getHistogram()
        xMin = h.GetXaxis().GetXmin()
        xMax = h.GetXaxis().GetXmax()
        yMin = 0
        yMax = 1.2
        #statOption = ROOT.TEfficiency.kFNormal
        if "TT" in datasetName:
            if function == "gaus":
                fitGauss = ROOT.TF1("fitGauss", "gaus", -2.5, 2.5)
                #                TF1 *fitBoFreq = new TF1("fitBoFreq","[0]*x+[1]",0,20);
                #                h.Fit("gaus")
                #fitTest = ROOT.TF1("fitTest", "0.01", -2.5, 2.5)

                h.Fit("fitGauss", "SRBM")
                #h.GetListOfFunctions().Add(fitTest)
                legend = "TT"

        legend = "a legend"
        print "Legend", legend
        saveName = histo.split("/")[-1] + "_Fit"

        print saveName

        xTitle = "fixXTitle"
        yTitle = "fixYTitle"

        yMin = 0.
        yMax = 0.03
        xMin = -2.3
        xMax = 2.3
        kwargs = {}

        options = {"ymin": yMin, "ymax": yMax, "xmin": xMin, "xMax": xMax}
        FitList.append(h)
        #p = plots.MCPlot(dataset, h, normalizeToLumi=0, saveFormats=[], **kwargs)

        p = plots.PlotBase(datasetRootHistos=FitList,
                           saveFormats=kwargs.get("saveFormats"))
        p.createFrame(saveName, opts=options)

        p.getFrame().GetXaxis().SetTitle(xTitle)
        p.getFrame().GetYaxis().SetTitle(yTitle)
        #p.histoMgr.setHistoDrawStyle(datasetName, "AP")

        # Set range
        p.getFrame().GetXaxis().SetRangeUser(xMin, xMax)

        moveLegend = {"dx": -0.55, "dy": -0.01, "dh": -0.1}

        p.setLegend(
            histograms.moveLegend(histograms.createLegend(), **moveLegend))
        # Add Standard Texts to plot
        histograms.addStandardTexts()

        p.draw()

        # Save plot in all formats
        savePath = os.path.join(opts.saveDir, "HplusMasses",
                                histo.split("/")[0], opts.optMode)
        save_path = savePath
        SavePlot(p, saveName, save_path)
    return
def analyze(analysis):

    paths = [sys.argv[1]]

    datasets = dataset.getDatasetsFromMulticrabDirs(paths,analysisName=analysis,excludeTasks="Silver|GluGluHToTauTau_M125")
    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 = datasets.getMCDatasets()
    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")])
    else:
        p = plots.ComparisonPlot(histograms.HistoGraph(eff1, "eff1", "p", "P"),
                                 histograms.HistoGraph(eff2, "eff2", "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)"
    legend3 = "MC (H125)"
    p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2})
    if isinstance(datasetsH125,dataset.DatasetManager):
        p.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2, "eff3": legend3})

    p.createFrame(os.path.join(plotDir, name), createRatio=True, 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.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]
    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,"tauLegTriggerEfficiency2015.json"))

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

    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")])
    else:
        p_eta = plots.ComparisonPlot(histograms.HistoGraph(eff1eta, "eff1eta", "p", "P"),
                                     histograms.HistoGraph(eff2eta, "eff2eta", "p", "P"))

    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"
    p_eta.createFrame(os.path.join(plotDir, name), createRatio=True, 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")
    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, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.2, 0.31, "Runs "+datasets.loadRunRange(), 17)

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

    p_eta.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)

    pPU = plots.ComparisonManyPlot(histograms.HistoGraph(eff1PU, "eff1", "p", "P"),
                                   [histograms.HistoGraph(eff2PU, "eff2", "p", "P")])


    pPU.histoMgr.setHistoLegendLabelMany({"eff1": legend1, "eff2": legend2})

    optsPU = {"ymin": 0.001, "ymax": 0.1}
    pPU.createFrame(os.path.join(plotDir, namePU), createRatio=True, opts=optsPU, opts2=opts2)
    pPU.setLegend(histograms.moveLegend(histograms.createLegend(), **moveLegend))
    pPU.getPad1().SetLogy(True)

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

    histograms.addText(0.5, 0.6, "LooseIsoPFTau50_Trk30_eta2p1", 17)
    histograms.addText(0.5, 0.53, analysis.split("_")[len(analysis.split("_")) -1], 17)
    histograms.addText(0.5, 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", ["TTJets","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