Example #1
0
def Plot2dHistograms(datasetsMgr, dsetName, histoName, index):

    msg = "%s%s (%s)%s" % (ShellStyles.SuccessStyle(), histoName, dsetName,
                           ShellStyles.NormalStyle())
    aux.PrintFlushed(msg, index == 1)

    # Custom Filtering of datasets
    dsetsMgr = datasetsMgr.deepCopy()
    if opts.verbose:
        dsetsMgr.PrintInfo()

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1] + "_" + dsetName.split(
        "_")[0] + dsetName.split("_")[-1]
    kwargs_ = GetHistoKwargs(saveName, opts)

    for i, d in enumerate(dsetsMgr.getAllDatasetNames(), 0):
        if d == dsetName:
            continue
        else:
            # Remove dataset from manager but do NOT close the file!
            dsetsMgr.remove(d, close=False)

    # Sanity check
    nDatasets = len(dsetsMgr.getAllDatasets())
    if nDatasets > 1:
        raise Exception(
            "More than 1 datasets detected in the dataset manager! Can only support 1 dataset. Please use the -i option to choose exactly 1 dataset'"
        )

    # Get the reference histo and the list of histos to compare
    datasets0 = dsetsMgr.getAllDatasets()[0].getName()
    histoList = [getHisto(dsetsMgr, datasets0, histoName)]

    # Create the 2d plot
    Verbose("Creating the 2d plot", True)
    if opts.normalizeToLumi:
        p = plots.MCPlot(dsetsMgr,
                         histoName,
                         normalizeToLumi=opts.intLumi,
                         saveFormats=[])
    elif opts.normalizeByCrossSection:
        p = plots.MCPlot(dsetsMgr,
                         histoName,
                         normalizeByCrossSection=True,
                         saveFormats=[],
                         **{})
    elif opts.normalizeToOne:
        p = plots.MCPlot(dsetsMgr,
                         histoName,
                         normalizeToOne=True,
                         saveFormats=[],
                         **{})
    else:
        raise Exception(
            "One of the options --normalizeToOne, --normalizeByCrossSection, --normalizeToLumi must be enabled (set to \"True\")."
        )

    Verbose("Setting universal histo styles", True)
    p.histoMgr.setHistoDrawStyleAll("COLZ")
    #p.histoMgr.setHistoLegendStyleAll("L")

    Verbose("Customising histograms", True)
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3))  #fixme

    Verbose("Setting plot styles to histograms", True)
    for index, h in enumerate(p.histoMgr.getHistos()):
        plots._plotStyles[p.histoMgr.getHistos()
                          [index].getDataset().getName()].apply(
                              p.histoMgr.getHistos()[index].getRootHisto())

    Verbose("Drawing the plot", True)
    plots.drawPlot(p, saveName,
                   **kwargs_)  #the "**" unpacks the kwargs_ dictionary

    # Add fit line for shrinking cone?
    const = 0.0
    coeff = 0.0
    step = 1
    xmin = 0
    xmax = 0
    if "GenP_VisEt_Vs" in histoName:
        const = 5.0  #3.5
        coeff = 1.0
        step = 100
        xmin = 0
        xmax = 30
    if "GenP_PtLdg_Vs" in histoName:
        const = 2.5  #2.0
        coeff = 1.0
        step = 100
        xmin = 0
        xmax = 30
    if "VtxIso_Vs_RelIso" in histoName:
        const = -0.5
        coeff = 0.3  #0.4
        step = 100
        xmin = 0
        xmax = 0  #3

    if "GenP_VisEt_Vs" in histoName or "GenP_PtLdg_Vs" in histoName:
        gr = getCustomTGraph(histoName, const, coeff, xmin, xmax, step)
        gr.SetLineWidth(3)
        gr.Draw("L same")

    Verbose("Removing the legend", True)
    p.removeLegend()

    Verbose("Adding text on canvas", True)
    histograms.addText(0.22, 0.89, plots._legendLabels[datasets0], 18)
    #histograms.addText(0.5, 0.89, plots._legendLabels[datasets0], 18)

    Verbose("Saving the canvas", True)
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, opts.url)

    return
Example #2
0
def PlotHisto(datasetsMgr, h):
    Verbose("Plotting histogram %s" % (h), True)

    dsetsMgr = datasetsMgr.deepCopy()

    # Create the plot with selected normalization
    kwargs = {}
    hList = getHistoList(dsetsMgr, h)

    if opts.normalizeToOne:
        p = plots.ComparisonManyPlot(hList[0],
                                     hList[1:],
                                     saveFormats=[],
                                     **kwargs)

        # For-loop: All histograms in manager
        normValue = 1.0
        for hist in p.histoMgr.getHistos():
            # print "hist.getRootHisto().GetName() = ", hist.getRootHisto().GetName()
            # print "histo.getRootHistos().GetBinContent(1) = ", hist.getRootHisto().GetBinContent(1)
            normValue = hist.getRootHisto().GetBinContent(1)
            hist.getRootHisto().Scale(1.0 / normValue)

        # Normalise wrt bin #1
        #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(1.0/normValue) )
    else:
        p = plots.ComparisonManyPlot(hList[0],
                                     hList[1:],
                                     saveFormats=[],
                                     **kwargs)
        #p = plots.PlotSameBase(dsetsMgr, h, saveFormats=[], **kwargs)

    # Set default styles (Called by default in MCPlot)
    p._setLegendStyles()
    p._setLegendLabels()
    p._setPlotStyles()

    # Customise legend
    for d in dsetsMgr.getAllDatasetNames():
        if "SingleNeutrino" in d:
            p.histoMgr.setHistoLegendStyle(d, "F")
        else:
            p.histoMgr.setHistoLegendStyle(d, "L")
            p.histoMgr.setHistoDrawStyle(d, "HIST9")

    # Create legend
    if 0:
        p.setLegend(
            histograms.createLegend(
                0.18, 0.86 - 0.04 * len(dsetsMgr.getAllDatasetNames()), 0.42,
                0.92))
    else:
        p.setLegend(
            histograms.createLegend(
                0.58, 0.86 - 0.04 * len(dsetsMgr.getAllDatasetNames()), 0.92,
                0.92))

    # Draw a customised plot
    kwargs = GetHistoKwargs(h, opts)
    plots.drawPlot(p, h, **kwargs)

    # Remove legend?
    if kwargs["removeLegend"]:
        p.removeLegend()

    # Save in all formats chosen by user
    aux.SavePlot(p, opts.saveDir, h, opts.saveFormats, opts.url)
    return
Example #3
0
def PlotRateVsEff(datasetsMgr, effHistoList, rateHistoList, signal, bkg, sPU,
                  bPU):

    # Definitions
    tgraphs = []
    legDict = {}
    aux.PrintFlushed("Plotting ROC (%s-%s)" % (bkg, signal), False)  #count==0)

    # Get Histogram name and its kwargs
    if "ditau" in effHistoList[0].lower():
        if "TT_" in signal or "GluGlu" in signal:
            pass
        else:
            return
        saveName = "RateVsEff_DiTau_%s_PU%s_MBPU%s" % (signal.split("_")[0],
                                                       sPU, bPU)
    else:
        saveName = "RateVsEff_SingleTau_%s_PU%s_MBPU%s" % (
            signal.split("_")[0], sPU, bPU)
    kwargs_ = GetHistoKwargs(saveName, opts)

    for i in range(0, len(effHistoList)):
        if (i == 0):
            g1 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g1.SetName("Calo")
        elif (i == 1):
            g2 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g2.SetName("CaloIso")

    # Create the Rate Vs Efficiency TGraphs
    p = plots.ComparisonManyPlot(g1, [g2], saveFormats=[])
    algos = getAlgos()

    # Set individual styles
    for index, h in enumerate(p.histoMgr.getHistos()):
        hName = h.getName()
        legDict[hName] = algos[index]  #styles.getCaloLegend(index)
        p.histoMgr.forHisto(hName, styles.getTauAlgoStyle(
            h.getName()))  #styles.getCaloStyle(index))
        p.histoMgr.setHistoDrawStyle(h.getName(),
                                     "LX")  # "X" = Do not draw error bars
        p.histoMgr.setHistoLegendStyle(h.getName(), "L")  #LP

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany(legDict)

    # Draw and save the plot
    saveName = saveName.replace("RateVsEff_", "")
    plots.drawPlot(p, saveName,
                   **kwargs_)  #the "**" unpacks the kwargs_ dictionary

    # Draw Error bands
    if opts.errorBands:
        #for i, g in enumerate([g0, g1, g2, g3, g4]):
        for i, g in enumerate([g1, g2, g3]):
            shapes, min, max = DrawErrorBand(g)
            for shape in shapes:
                shape.SetFillColor(
                    p.histoMgr.getHistos()[i].getRootHisto().GetFillColor())
                shape.SetFillStyle(3002)
                shape.Draw("f same")
            ROOT.gPad.RedrawAxis()

    histograms.addPileupText("PU=%s" % (bPU))
    histograms.addText(0.55, 0.48, plots._legendLabels[signal], 18)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    return
Example #4
0
def PlotTurnOns(datasetsMgr, histoList, signal, PU, saveName=None):

    # Get Histogram name and its kwargs
    myRegex = "(?:TurnOn)(.*)"
    m = re.search(myRegex, histoList[0])
    threshold = m.group(1)
    if saveName == None:
        #saveName  = "TurnOns_%sGeV_%s" % (threshold, signal)
        saveName = "TurnOns_%s_%s" % (threshold, signal)
    kwargs = GetHistoKwargs(saveName, opts)
    hList = []
    legDict = {}
    algos = getAlgos()
    if "_all" in saveName:
        algos = [
            "Inclusive", "1-prong", "3-prong", "#geq 1 #pi^{0}'s",
            "0 #pi^{0}'s"
        ]

    # For-loop: All tau algorithms
    for l, hName in enumerate(histoList, 0):

        algo = hName.split("_")[0]
        msg = "Turn-on for \"%s\" algorithm (%s)" % (algo, signal)
        aux.PrintFlushed(msg, False)
        #aux.Print(msg, True)
        h = datasetsMgr.getDataset(signal).getDatasetRootHisto(
            hName).getHistogram()
        h.SetName(hName)
        legDict[hName] = algos[l]
        hList.append(h)

    # Create the rate histograms
    p = plots.ComparisonManyPlot(hList[0], hList[1:], saveFormats=[])

    # Set legend labels
    for i, h in enumerate(p.histoMgr.getHistos(), 0):
        hName = h.getName()
        algo = h.getName().split("_")[0]
        if algo == "DiTau":
            algo = hName.split("_")[-1]
        if "_all" in saveName:
            p.histoMgr.forHisto(hName, styles.getCaloStyle(i))
        else:
            p.histoMgr.forHisto(hName, styles.getTauAlgoStyle(algo))
        p.histoMgr.setHistoDrawStyle(hName, "AP")
        p.histoMgr.setHistoLegendStyle(hName, "P")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany(legDict)

    # Draw and save the plot
    saveName = saveName.replace("TurnOns_", "")
    plots.drawPlot(p, saveName, **kwargs)

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    histograms.addText(0.22, 0.86, plots._legendLabels[signal], 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    return
Example #5
0
def PlotEfficiency(datasetsMgr, histoList, signal, PU, taus):

    # Get Histogram name and its kwargs
    saveName = "Efficiency_%s_%s" % (taus, signal)
    #saveName = "Efficiency_%s_PU%s" % (taus, PU) # "Rate_" here incuded to apply customisations with kwargs. Drop later
    kwargs = GetHistoKwargs(saveName, opts)
    hList = []
    legDict = {}
    algos = getAlgos()

    # For-loop: All tau algorithms
    count = -1
    for i, hName in enumerate(histoList, 0):
        algo = hName.split("_")[0]
        if algo == "DiTau":

            if "TT_" in signal or "GluGlu" in signal:
                pass
            else:
                return

            algo = hName.split("_")[-1]
        count += 1
        aux.PrintFlushed("Plotting efficiency (%s-%s-%s)" %
                         (algo, taus, signal), False)  #count==0)
        h = datasetsMgr.getDataset(signal).getDatasetRootHisto(
            hName).getHistogram()
        h.SetName(hName)
        legDict[hName] = algos[i]
        hList.append(h)

    # Create the rate histograms
    p = plots.ComparisonManyPlot(hList[0], hList[1:], saveFormats=[])

    # Set legend labels
    for h in p.histoMgr.getHistos():
        hName = h.getName()
        algo = h.getName().split("_")[0]
        if algo == "DiTau":
            algo = hName.split("_")[-1]
        p.histoMgr.forHisto(hName, styles.getTauAlgoStyle(algo))
        p.histoMgr.setHistoDrawStyle(hName, "HIST")
        p.histoMgr.setHistoLegendStyle(hName, "L")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany(legDict)

    # Draw and save the plot
    saveName = saveName.replace(
        "Efficiency_",
        "")  # drop "Efficiency_" only AFTER getting histo kwargs
    #saveName = "%s_%s_%s" % (taus, algo, signal) # drop "Efficiency_" only AFTER getting histo kwargs
    plots.drawPlot(p, saveName, **kwargs)

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    histograms.addText(0.66, 0.86, plots._legendLabels[signal], 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    #print
    return
Example #6
0
def PlotHisto(datasetsMgr, h):
    dsetsMgr = datasetsMgr.deepCopy()

    if "_eff" in h.lower():
        dsetsMgr.remove("SingleNeutrino_L1TPU140", close=False)
        dsetsMgr.remove("SingleNeutrino_L1TPU200", close=False)
        opts.normalizeToOne = False
    elif "_deltargenp" in h.lower():
        dsetsMgr.remove("SingleNeutrino_L1TPU140", close=False)
        dsetsMgr.remove("SingleNeutrino_L1TPU200", close=False)
    elif "_resolution" in h.lower():
        dsetsMgr.remove("SingleNeutrino_L1TPU140", close=False)
        dsetsMgr.remove("SingleNeutrino_L1TPU200", close=False)
    elif "_rate" in h.lower():
        opts.normalizeToOne = False
        for d in dsetsMgr.getAllDatasetNames():
            if "SingleNeutrino" in d:
                continue
            else:
                dsetsMgr.remove(d, close=False)
    else:
        pass

    # Create the plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    kwargs = {}
    hList = getHistoList(dsetsMgr, h)

    if opts.normalizeToOne:
        if 1:
            p = plots.ComparisonManyPlot(hList[0],
                                         hList[1:],
                                         saveFormats=[],
                                         **kwargs)
            norm = True
            for hist in p.histoMgr.getHistos():
                if hist.getRootHisto().Integral() == 0:
                    norm = False
                    break
            if (norm):
                p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(
                    1.0 / h.getRootHisto().Integral()))
        else:
            # p = plots.MCPlot(dsetsMgr, h, normalizeToOne=True, saveFormats=[], **kwargs)
            p = plots.PlotSameBase(dsetsMgr,
                                   h,
                                   normalizeToOne=True,
                                   saveFormats=[],
                                   **kwargs)
    else:
        if 1:
            p = plots.ComparisonManyPlot(hList[0],
                                         hList[1:],
                                         saveFormats=[],
                                         **kwargs)  #FIXME
        else:
            # p = plots.MCPlot(dsetsMgr, h, normalizeToLumi=opts.intLumi, saveFormats=[], **kwargs)
            p = plots.PlotSameBase(dsetsMgr, h, saveFormats=[], **kwargs)

    # Set default styles (Called by default in MCPlot)
    p._setLegendStyles()
    p._setLegendLabels()
    p._setPlotStyles()

    # Customise legend
    for d in dsetsMgr.getAllDatasetNames():
        if "SingleNeutrino" in d:
            p.histoMgr.setHistoLegendStyle(d, "F")
        else:
            p.histoMgr.setHistoLegendStyle(d, "L")
            p.histoMgr.setHistoDrawStyle(d, "HIST9")

            #p.histoMgr.setHistoLegendStyle(d, "P") #"L"
            #p.histoMgr.setHistoDrawStyle(d, "AP")

    # Create legend
    if 0:
        p.setLegend(
            histograms.createLegend(
                0.18, 0.86 - 0.04 * len(dsetsMgr.getAllDatasetNames()), 0.42,
                0.92))
    else:
        p.setLegend(
            histograms.createLegend(
                0.58, 0.86 - 0.04 * len(dsetsMgr.getAllDatasetNames()), 0.92,
                0.92))

    # Draw a customised plot
    kwargs = GetHistoKwargs(h, opts)
    plots.drawPlot(p, h, **kwargs)

    # Remove legend?
    if kwargs["removeLegend"]:
        p.removeLegend()

    # Save in all formats chosen by user
    aux.SavePlot(p, opts.saveDir, h, opts.saveFormats, opts.url)
    return