def PlotHistograms(datasetsMgr, histoName, histos, **kwargs_):
    Verbose("Plotting Histograms")

    # Set the saveName
    saveName = histoName + "_Cumulative"
    legendDict = {}

    # Create & draw the plot
    p = plots.ComparisonManyPlot(histos[0], histos[1:], saveFormats=[])

    # Set individual styles
    for index, h in enumerate(p.histoMgr.getHistos()):
        p.histoMgr.setHistoDrawStyle(h.getName(), "AP")
        p.histoMgr.setHistoLegendStyle(h.getName(), "LP")
        legendDict[h.getName()] = plots._legendLabels[h.getName()]
        plots._plotStyles[h.getName()].apply(
            p.histoMgr.getHistos()[index].getRootHisto())

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

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

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode,
                                       opts.folder), [".pdf", ".png"])

    return
Example #2
0
def PlotRate(datasetsMgr, histoList, bkg, PU):

    # Get Histogram name and its kwargs
    taus = "SingleTau"
    saveName = "Rate_%s_PU%s" % (taus, PU)
    kwargs = GetHistoKwargs(saveName, opts)
    hList = []
    legDict = {}
    algos = getAlgos()

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

        #if algo == "DiTau":
        #    taus = "DiTau"
        #    algo = hName.split("_")[-1]
        if "ditau" in hName.lower():
            return
        #algo = hName.split("_")[-1]
        #tau  = hName.split("_")[1]
        #if  tau == "DiTau":
        #    taus = "DiTau"
        #    algo = hName.split("_")[-1]

        aux.PrintFlushed("Plotting rate (%s-%s)" % (algo, taus), False)
        h = datasetsMgr.getDataset(bkg).getDatasetRootHisto(
            hName).getHistogram()
        h.SetName(hName)
        legDict[hName] = algos[i]  #algo
        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]
        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 = "Rate_%s_PU%s" % (taus, PU)
    plots.drawPlot(p, saveName, **kwargs)

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    histograms.addText(0.70, 0.88, taus, 17)
    #histograms.addText(0.75, 0.88, taus, 17)
    #histograms.addText(0.60, 0.78, plots._legendLabels[bkg], 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    #print
    return
Example #3
0
def PlotHistograms(datasetsMgr, histoName):
    Verbose("Plotting Data-MC Histograms")

    # Get Histogram name and its kwargs
    saveName = histoName.rsplit("/")[-1]
    kwargs_  = GetHistoKwargs(saveName, opts)
    kwargs ={}

    ROOT.gStyle.SetNdivisions(8, "Z")
    ROOT.gStyle.SetNdivisions(8, "Y")

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

    if opts.normToOne:
        for h in histoList:
            h.normalizeToOne()
            
    p = plots.PlotBase(histoList, saveFormats=[])


    # Set universal histo styles
    p.histoMgr.setHistoDrawStyleAll("COLZ")
    p.histoMgr.setHistoLegendStyleAll("L")

    # Customize histo
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitle(kwargs_["zlabel"]))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.5))

    # Get the x and y axis title
    binWidthX = p.histoMgr.getHistos()[0].getRootHisto().GetXaxis().GetBinWidth(0)
    binWidthY = p.histoMgr.getHistos()[0].getRootHisto().GetYaxis().GetBinWidth(0)
    xlabel = p.histoMgr.getHistos()[0].getRootHisto().GetXaxis().GetTitle() + " / %s" % (GetBinwidthDecimals(binWidthX) % (binWidthX))
    kwargs_["xlabel"] = xlabel
    ylabel = p.histoMgr.getHistos()[0].getRootHisto().GetYaxis().GetTitle() + " / %s" % (GetBinwidthDecimals(binWidthY) % (binWidthY))
    kwargs_["ylabel"] = ylabel

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

    # Set default dataset style to all histos
    for index, h in enumerate(p.histoMgr.getHistos()):
        plots._plotStyles[p.histoMgr.getHistos()[index].getDataset().getName()].apply(p.histoMgr.getHistos()[index].getRootHisto())

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

    # Remove legend
    p.removeLegend()

    # Set log-z?                                                                                                                                               
    p.getPad().SetLogz(True)

     # Additional text                                                                                                                                          
    histograms.addText(0.18, 0.89, plots._legendLabels[datasets0], 17)

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode, opts.folder), [".pdf"])#, ".png"] )
    return
Example #4
0
def PlotEfficiency(datasetsMgr, histoList, signal, PU):

    # Get Histogram name and its kwargs
    taus = "SingleTau"
    saveName = "Efficiency_%s_%s" % (taus, signal)
    kwargs = GetHistoKwargs(saveName, opts)
    hList = []
    legDict = {}

    # 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

            taus = "DiTau"
            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] = algo
        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 = "Efficiency_%s_%s" % (taus, signal)
    plots.drawPlot(p, saveName, **kwargs)

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    # histograms.addText(0.75, 0.88, taus, 17)
    histograms.addText(0.60, 0.88, plots._legendLabels[signal], 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    #print
    return
Example #5
0
def MCPlot(datasetsMgr, json):
    Verbose("Creating MC plot")
        
    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    ylabel_ = json["ylabel"]
    if json["normalization"]=="normalizeToLumi":
        kwargs = {}
        p = plots.MCPlot(datasetsMgr, json["histogram"], normalizeToLumi=opts.intLumi, **kwargs)
    elif json["normalization"]=="normalizeToOne":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0], "Arbitrary Units")
        kwargs  = {json["normalization"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" % (json["normalization"]) )
    
    # Label size (optional. Commonly Used in counters)
    xlabelSize = None
    if "xlabelsize" in json:
        xlabelSize = json["xlabelsize"]
    ylabelSize = None
    if "ylabelsize" in json:
        ylabelSize = json["ylabelsize"]
    
    # Draw a customised plot
    saveName = os.path.join(json["saveDir"], json["title"])
    plots.drawPlot(p, 
                   saveName,                  
                   xlabel            = json["xlabel"], 
                   ylabel            = ylabel_,
                   rebinX            = json["rebinX"],
                   rebinY            = json["rebinY"], 
                   stackMCHistograms = json["stackMCHistograms"]=="True", 
                   addMCUncertainty  = json["addMCUncertainty"]=="True" and json["normalization"]!="normalizeToOne",
                   addLuminosityText = json["addLuminosityText"]=="True",
                   addCmsText        = json["addCmsText"]=="True",
                   cmsExtraText      = json["cmsExtraText"],
                   opts              = json["opts"],
                   log               = json["logY"]=="True", 
                   errorBarsX        = json["errorBarsX"]=="True", 
                   moveLegend        = json["moveLegend"],
                   # cutLine           = json["cutValue"], #cannot have this and "cutBox" defined
                   cutBox            = {"cutValue": json["cutValue"], "fillColor": json["cutFillColour"], "box": json["cutBox"]=="True", "line": json["cutLine"]=="True", "greaterThan": json["cutGreaterThan"]=="True"},
                   xlabelsize        = xlabelSize,
                   ylabelsize        = ylabelSize,
                   )
    
    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") )

    # Save in all formats chosen by user
    saveFormats = json["saveFormats"]
    for i, ext in enumerate(saveFormats):
        Print("%s" % saveName + ext, i==0)
    p.saveAs(saveName, formats=saveFormats)
    return
Example #6
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 #7
0
def PlotHisto(dsetsMgr, h, histoType):
    kwargs = {}
    hList = getHistoList(dsetsMgr, h)

    if 1:
        p = plots.PlotSameBase(dsetsMgr,
                               h,
                               normalizeToOne=False,
                               saveFormats=[],
                               **kwargs)
    else:
        p = plots.MCPlot(dsetsMgr,
                         h,
                         normalizeToLumi=opts.intLumi,
                         saveFormats=[],
                         **kwargs)
        p = plots.PlotSameBase(dsetsMgr, h, saveFormats=[], **kwargs)
        p = plots.MCPlot(dsetsMgr,
                         h,
                         normalizeToOne=True,
                         saveFormats=[],
                         **kwargs)

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

    # Customise legend
    for d in dsetsMgr.getAllDatasetNames():
        if "TH2" not in histoType:
            if "pCalo" in h:
                p.histoMgr.setHistoLegendStyle(d, "LP")
                p.histoMgr.setHistoDrawStyle(d, "AP")

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

    # Add text
    ptSlice = h.rsplit("_")[-1].replace("GE",
                                        "#geq ").replace("to", " to ").replace(
                                            "Pt", "p_{T} = ")
    ptSlice += " GeV"
    histograms.addText(0.20, 0.865, ptSlice, 18)

    # 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 #8
0
def PlotHisto(datasetsMgr, h):
    dsetsMgr = datasetsMgr.deepCopy()

    opts.normalizeToOne = False

    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    kwargs = {}
    if opts.normalizeToOne:
        #p = plots.MCPlot(dsetsMgr, h, normalizeToOne=True, saveFormats=[], **kwargs)
        p = plots.PlotSameBase(dsetsMgr,
                               h,
                               normalizeToOne=True,
                               saveFormats=[],
                               **kwargs)
    else:
        #p = plots.MCPlot(dsetsMgr, h, normalizeToLumi=opts.intLumi, saveFormats=[], **kwargs)
        p = plots.PlotSameBase(
            dsetsMgr, h, saveFormats=[], **kwargs
        )  #def __init__(self, datasetMgr, name, normalizeToOne=False, datasetRootHistoArgs={}, **kwargs):

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

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

    p.setLegend(
        histograms.createLegend(
            0.68, 0.85 - 0.05 * len(dsetsMgr.getAllDatasetNames()), 0.92,
            0.92))
    #p.histoMgr.setHistoLegendStyle("histo_" + dataset, "LP")
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(
        1 / h.getRootHisto().GetBinContent(1)))
    #
    # Draw a customised plot
    plots.drawPlot(p, h, **GetHistoKwargs(h, opts))
    p.getFrame().GetXaxis().SetLabelSize(15)
    p.getFrame().GetXaxis().LabelsOption("u")

    # Remove legend?
    if 0:
        p.removeLegend()

    # Save in all formats chosen by user
    aux.SavePlot(p, opts.saveDir, h, opts.saveFormats, opts.url)
    return
Example #9
0
def PlotTurnOns(datasetsMgr, histoList, signal, PU):

    # Get Histogram name and its kwargs
    myRegex = "(?:TurnOn)(.*)"
    m = re.search(myRegex, histoList[0])
    threshold = m.group(1)
    saveName = "TurnOns_%sGeV_%s" % (threshold, signal)
    kwargs = GetHistoKwargs(saveName, opts)
    hList = []
    legDict = {}

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

        algo = hName.split("_")[0]
        aux.PrintFlushed("Turn-on for \"%s\" algorithm (%s)" % (algo, signal),
                         False)  #l==0)
        h = datasetsMgr.getDataset(signal).getDatasetRootHisto(
            hName).getHistogram()
        h.SetName(hName)
        legDict[hName] = algo
        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, "AP")
        p.histoMgr.setHistoLegendStyle(hName, "LP")

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

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

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    # histograms.addText(0.75, 0.88, taus, 17)
    histograms.addText(0.60, 0.88 - 0.50, plots._legendLabels[signal], 17)

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

    # Get Histogram name and its kwargs
    saveName = "Rate_%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
    for i, hName in enumerate(histoList, 0):
        algo = hName.split("_")[0]
        aux.PrintFlushed("Plotting rate (%s-%s)" % (algo, taus), False)
        h = datasetsMgr.getDataset(bkg).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 i, h in enumerate(p.histoMgr.getHistos(), 0):
        hName = h.getName()
        algo = h.getName().split("_")[0]
        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("Rate_",
                                "")  #drop "Rate_" only AFTER getting kwargs
    plots.drawPlot(p, saveName, **kwargs)

    # Add additional canvas text
    histograms.addPileupText("PU=%s" % (PU))
    histograms.addText(0.66, 0.86, taus, 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    #print
    return
Example #11
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 "resolution" in h.lower(
    ) or "PoorNeuResol" in h or "match" 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 MC 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)
            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)
    
    '''
    if opts.normalizeToOne:
        #p = plots.MCPlot(dsetsMgr, h, normalizeToOne=True, saveFormats=[], **kwargs)
        p = plots.PlotSameBase(dsetsMgr,
                               h,
                               normalizeToOne=True,
                               saveFormats=[],
                               **kwargs)
    else:
        #p = plots.MCPlot(dsetsMgr, h, normalizeToLumi=opts.intLumi, saveFormats=[], **kwargs)
        p = plots.PlotSameBase(
            dsetsMgr, h, saveFormats=[], **kwargs
        )  #def __init__(self, datasetMgr, name, normalizeToOne=False, datasetRootHistoArgs={}, **kwargs):

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

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

    p.setLegend(
        histograms.createLegend(
            0.68, 0.85 - 0.05 * len(dsetsMgr.getAllDatasetNames()), 0.77,
            0.92))
    #p.histoMgr.setHistoLegendStyle("histo_" + dataset, "LP")

    # Draw a customised plot
    plots.drawPlot(p, h, **GetHistoKwargs(h, opts))
    if ("photons_egs_matching" in h.lower()):
        p.getFrame().GetXaxis().SetLabelSize(14)
        p.getFrame().GetXaxis().LabelsOption("u")

    # Remove legend?
    if 0:
        p.removeLegend()

    # Save in all formats chosen by user
    aux.SavePlot(p, opts.saveDir, h, opts.saveFormats, opts.url)
    return
Example #12
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
def PlotHisto(datasetsMgr, h):
    dsetsMgr = datasetsMgr.deepCopy()

    if "_resolution" in h.lower():
        dsetsMgr.remove("SingleNeutrino_L1TPU140", close=False)
        dsetsMgr.remove("SingleNeutrino_L1TPU200", close=False)

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

    # Overwrite default settings
    cNoPU = ROOT.kAzure
    cPU140 = ROOT.kRed
    cPU200 = ROOT.kOrange  #kYellow+2
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().SetFillColor(cNoPU) if "noPU" in h.getName(
        ) else h.getRootHisto().SetLineStyle(ROOT.kSolid))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetFillStyle(
        3002) if "noPU" in h.getName() else h.getRootHisto().SetFillStyle(0))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetLineColor(cPU140)
                            if "PU140" in h.getName() else (h.getRootHisto(
                            ).SetLineColor(cPU200) if "PU200" in h.getName(
                            ) else h.getRootHisto().SetLineColor(cNoPU)))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerColor(cPU140)
                            if "PU140" in h.getName() else (h.getRootHisto(
                            ).SetMarkerColor(cPU200) if "PU200" in h.getName(
                            ) else h.getRootHisto().SetMarkerColor(cNoPU)))

    # Customise legend
    dsetName0 = dsetsMgr.getAllDatasetNames()[0].rsplit("_L1T")[0]
    for d in dsetsMgr.getAllDatasetNames():
        # Sanity check
        dsetName = d.rsplit("_L1T")[0]
        if dsetName0 != dsetName:
            msg = "Different types of datasets detected (\"%s\" and \"%s\"). This script is designed for just one type of dataset for different PU" % (
                dsetName, dsetName0)
            raise Exception(es + msg + ns)
        else:
            # print "*"*100
            # print dsetName0
            # print dsetName
            # print "*"*100
            pass

        if "noPU" in d:
            p.histoMgr.setHistoLegendStyle(d, "L")
            p.histoMgr.setHistoDrawStyle(d, "HIST")
        else:
            p.histoMgr.setHistoLegendStyle(d, "AP")
            p.histoMgr.setHistoDrawStyle(d, "P")

    # 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.68, 0.86 - 0.04 * len(dsetsMgr.getAllDatasetNames()), 0.98,
                0.92))

    # Draw a customised plot
    kwargs = GetHistoKwargs(h, opts)
    saveName = h.replace("", "")
    #saveName += #iro
    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 #14
0
def PlotHistos(datasetsMgr, histoList, signal, PU, saveName=None):
    
    # Get Histogram name and its kwargs
    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"]
    if "_cif"  in saveName:
        #algos = ["Inclusive", "Central", "Intermediate", "Forward"]
        algos = ["Inclusive", "|#eta| < 0.8 (C)", "0.8 < |#eta| < 1.6 (I)", "|#eta| > 1.6 (F)"]

    # For-loop: All tau algorithms
    for l, hName in enumerate(histoList, 0):
        
        algo = hName.split("_")[0]
        msg  = "Resolution for \"%s\" algorithm (%s)" % (algo, signal)
        aux.PrintFlushed(msg, False)
        h = datasetsMgr.getDataset(signal).getDatasetRootHisto(hName).getHistogram()
        h.SetName(hName)
        legDict[hName] = algos[l]
        hList.append(h)

        # Create the rate histograms
        if opts.normalizeToOne:
            p = plots.ComparisonManyPlot(hList[0], hList[1:], saveFormats=[])
            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:
                aux.Print("Cannot normalise empty histo \"%s\" for dataset \"%s\"" % (hName, signal), True)
        else:
            p = plots.ComparisonManyPlot(hList[0], hList[1:], saveFormats=[])

    # Set legend labels
    for i, h in enumerate(p.histoMgr.getHistos(), 0):
        hName = h.getName()
        p.histoMgr.forHisto(hName, styles.getCaloStyle(i))
        #p.histoMgr.setHistoDrawStyle(hName, "HIST")
        #p.histoMgr.setHistoLegendStyle(hName, "L")
        p.histoMgr.setHistoDrawStyle(hName, "AP")
        p.histoMgr.setHistoLegendStyle(hName, "P")
    
    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany(legDict)

    # Draw and save the plot
    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 #15
0
def MCPlot(datasetsMgr, json):
    Verbose("Creating MC plot")

    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    ylabel_ = json["ylabel"]

    if json["normalization"] == "normalizeToLumi":
        kwargs = {}
        p = plots.MCPlot(datasetsMgr,
                         json["histogram"],
                         normalizeToLumi=opts.intLumi,
                         **kwargs)
    elif json["normalization"] == "normalizeToOne":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0],
                                  "Arbitrary Units")
        kwargs = {json["normalization"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" %
                        (json["normalization"]))
    '''

    if json["normalizationToOne"]=="True":
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0], "Arbitrary Units")
        kwargs  = {json["normalizationToOne"]: True}
        p = plots.MCPlot(datasetsMgr, json["histogram"], **kwargs)
    else:
        raise Exception("Invalid normalization \"%s\"" % (json["normalization"]) )
    '''
    # Label size (optional. Commonly Used in counters)
    xlabelSize = None
    if "xlabelsize" in json:
        xlabelSize = json["xlabelsize"]
    ylabelSize = None
    if "ylabelsize" in json:
        ylabelSize = json["ylabelsize"]

    # Set universal histo styles
    if ("drawStyle" in json):
        p.histoMgr.setHistoDrawStyleAll(json["drawStyle"])
    if ("legendStyle" in json):
        p.histoMgr.setHistoLegendStyleAll(json["legendStyle"])

    # For-loop: All histos
    for index, h in enumerate(p.histoMgr.getHistos()):
        if index == 0:
            continue
        else:
            p.histoMgr.setHistoDrawStyle(h.getName(), "AP")
            p.histoMgr.setHistoLegendStyle(h.getName(), "AP")

    # Set default dataset style to all histos
    for index, h in enumerate(p.histoMgr.getHistos()):
        plots._plotStyles[p.histoMgr.getHistos()
                          [index].getDataset().getName()].apply(
                              p.histoMgr.getHistos()[index].getRootHisto())

    # Draw a customised plot
    saveDir = "/afs/cern.ch/user/m/mtoumazo/public/html/hltaus/TkCalo/"
    saveName = os.path.join(saveDir, json["saveName"])
    plots.drawPlot(
        p,
        saveName,
        xlabel=json["xlabel"],
        ylabel=ylabel_,
        rebinX=json["rebinX"],
        rebinY=json["rebinY"],
        stackMCHistograms=json["stackMCHistograms"] == "True",
        addMCUncertainty=json["addMCUncertainty"] == "True"
        and json["normalization"] != "normalizeToOne",
        addLuminosityText=json["addLuminosityText"] == "True",
        addCmsText=json["addCmsText"] == "True",
        cmsExtraText=json["cmsExtraText"],
        opts=json["opts"],
        log=json["logY"] == "True",
        errorBarsX=json["errorBarsX"] == "True",
        moveLegend=json["moveLegend"],
        # cutLine           = json["cutValue"], #cannot have this and "cutBox" defined
        cutBox={
            "cutValue": json["cutValue"],
            "fillColor": json["cutFillColour"],
            "box": json["cutBox"] == "True",
            "line": json["cutLine"] == "True",
            "greaterThan": json["cutGreaterThan"] == "True"
        },
        xlabelsize=xlabelSize,
        ylabelsize=ylabelSize,
    )

    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"),
                       json["extraText"].get("text"),
                       json["extraText"].get("size"))

    # Save in all formats chosen by user
    saveFormats = [".pdf"]
    for i, ext in enumerate(saveFormats):
        saveNameURL = saveName + ext
        saveNameURL = saveNameURL.replace(
            "/afs/cern.ch/user/m/mtoumazo/public/html/hltaus/",
            "https://cmsdoc.cern.ch/~mtoumazo/hltaus/")
        if opts.url:
            Print(saveNameURL, 1)
        else:
            Print(saveName + ext, 1)
        p.saveAs(saveName, formats=saveFormats)

    return
Example #16
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 #17
0
def PlotHistograms(datasetsMgr, histoName):

    # Customise histo
    kwargs_ = GetHistoKwargs(histoName, opts)

    # Get dataset
    datasets0 = datasetsMgr.getAllDatasets()[0].getName()

    # Get histograms for the ComparisonPlot
    if "resVsEta" in histoName:
        myHistos = getResolutionHistos(datasetsMgr,
                                       datasets0,
                                       histoName,
                                       regions=["_L", "_M", "_H"])
    else:
        myHistos = getResolutionHistos(datasetsMgr,
                                       datasets0,
                                       histoName,
                                       regions=["_C", "_I", "_F"])

    # Get reference histo and list of comparison histos
    hReference = myHistos[0]
    hCompares = myHistos[1:]

    # Create the plotting object
    p = plots.ComparisonManyPlot(hReference, hCompares, saveFormats=[])

    # Get legend names
    legDict = GetLegendDictionary()
    legends = {}

    # For-loop: All histograms in manager
    for i, h in enumerate(p.histoMgr.getHistos(), 1):
        region = h.getName().split("_")[-1]

        if region not in legDict.keys():
            raise Exception(
                "Invalid region \"%s\". Cannot determine legend name for histogram \"%s\""
                % (region, h.getName()))
        legends[h.getName()] = legDict[region]
        p.histoMgr.forHisto(h.getName(), styles.getRegionStyle(region))
        p.histoMgr.setHistoDrawStyle(h.getName(), "LP")
        p.histoMgr.setHistoLegendStyle(h.getName(), "LP")

    # Normalise resolution plots
    if "res_" in histoName:
        if h.getRootHisto().Integral() > 0:
            aux.Verbose("Normalising \"%s\" to unit area" % (histoName), True)
            p.histoMgr.forEachHisto(lambda h: h.getRootHisto().Scale(
                1.0 / h.getRootHisto().Integral()))

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

    # Draw and save the plot
    plots.drawPlot(p, histoName,
                   **kwargs_)  #the "**" unpacks the kwargs_ dictionary

    # Additional text on canvas
    histograms.addText(
        0.65, 0.90, plots._legendLabels[datasetsMgr.getAllDatasetNames()[0]],
        17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, histoName, opts.saveFormats, opts.url)
    return
Example #18
0
def PlotHistos(datasetName, hPath, saveName):

    _kwargs = GetHistoKwargs(hPath, opts)
    datasetsMgr_list = []

    j = 0
    histoList = []
    legDict = {}

    # For-loop: All pseudo-multicrabs
    while j < len(opts.mcrabs):

        algo = opts.mcrabs[j].split("_")[1]
        dMgr = GetDatasetsFromDir(opts, j)
        dataset = dMgr.getDataset(datasetName)
        dMgr.updateNAllEventsToPUWeighted()

        # Get Histogram from dataset
        histo = dataset.getDatasetRootHisto(hPath).getHistogram()

        # Set style
        styles.styles[j].apply(histo)
        legDict[algo] = getAlgoLabel(algo)

        if (j == 0):
            if "turnon" in saveName.lower():
                refHisto = histograms.Histo(histo,
                                            algo,
                                            legendStyle="LP",
                                            drawStyle="AP")
            else:
                refHisto = histograms.Histo(histo,
                                            algo,
                                            legendStyle="L",
                                            drawStyle="HIST")
                refHisto.getRootHisto().SetLineStyle(ROOT.kSolid)
                refHisto.getRootHisto().SetLineWidth(4)
        else:
            if "turnon" in saveName.lower():
                histoList.append(
                    histograms.Histo(histo,
                                     algo,
                                     legendStyle="LP",
                                     drawStyle="AP"))
            else:
                histo.SetLineWidth(4)
                histoList.append(
                    histograms.Histo(histo,
                                     algo,
                                     legendStyle="L",
                                     drawStyle="HIST"))
        j = j + 1

    # Create the plotter object
    p = plots.ComparisonManyPlot(refHisto, histoList, saveFormats=[])
    p.setLegendHeader(plots._legendLabels[datasetName])

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

    # Draw the plots
    plots.drawPlot(p, opts.saveDir, **_kwargs)

    # Add text
    if 0:
        histograms.addText(0.65, 0.1, "#\pm %.1f %% band" % (opts.bandValue),
                           20)

    # Save plot in all formats
    saveName += datasetName
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    return
Example #19
0
def PlotRateVsEff(datasetsMgr, dataset, Type, PU):

    # Sanity checks
    if PU not in dataset.getName():
        return
    if "Neutrino" in dataset.getName():
        return

    # Definitions
    _kwargs = GetHistoKwargs("RateVsEff", opts)
    j = -1
    gList = []
    legDict = {}

    # For-loop: All pseudo-multicrabs
    while j < len(opts.mcrabs) - 1:
        j = j + 1

        dMgr = GetDatasetsFromDir(opts, j)
        dMgr.updateNAllEventsToPUWeighted()

        # Get dataset
        signal = dataset.getName()
        bkg = "SingleNeutrino_L1T%s" % (PU)

        # Get Histogram from dataset
        hEff = os.path.join(opts.folder, "L1Taus_%s_Eff" % (Type))
        hRate = os.path.join(opts.folder, "L1Taus_%s_Rate" % (Type))
        graph = convert2RateVsEffTGraph(dMgr, hEff, hRate, signal, bkg)
        algo = opts.mcrabs[j].split("_")[1]
        graph.SetName(algo)
        styles.styles[j].apply(graph)
        graph.SetLineWidth(4)
        gList.append(graph)
        legDict[algo] = getAlgoLabel(algo)

    # Create the plotter object
    p = plots.ComparisonManyPlot(gList[0], gList[1:], saveFormats=[])
    p.setLegendHeader(plots._legendLabels[signal])

    # Set individual styles
    for index, h in enumerate(p.histoMgr.getHistos(), 1):
        hName = h.getName()
        legDict[hName] = getAlgoLabel(hName)
        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 the plots
    plots.drawPlot(p, opts.saveDir, **_kwargs)

    # Add text
    if 0:
        histograms.addText(0.65, 0.1, "#\pm %.1f %% band" % (opts.bandValue),
                           20)

    # Save plot in all formats
    saveName = Type + "_" + dataset.getName()
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    return
Example #20
0
def main(opts):

    # Apply TDR style
    opts.style = tdrstyle.TDRStyle()
    opts.style.setGridX(opts.gridX)
    opts.style.setGridY(opts.gridY)
    # opts.style.setLogX(opts.logX)
    # opts.style.setLogY(opts.logY)
    opts.style.setOptStat(False)
    ROOT.gStyle.SetErrorX(
        0.5)  #required for x-axis error bars! (overwrites tdrstyle.TDRStyle())

    # Create  dictionary of algorithms (name -> object) for each dataset (?)
    algorithms = {}
    for algoName in opts.algos:
        algorithms[algoName] = Algorithm(algoName, opts)

    # Create dictionary mapping each dataset to the number of merged ROOT files
    opts.nFiles = {}

    # For-loop: All datasets
    for i, dset in enumerate(opts.dsetDict, 1):

        # Get the list with the ROOT files
        rootFiles = opts.dsetDict[dset]
        if opts.verbose:
            PrintRootFileNames(rootFiles)

        # Get the number of the merged ROOT files
        mergedRootFile = ROOT.TFile(rootFiles[0].GetName(), "OLD")
        if (mergedRootFile.GetListOfKeys().Contains("nFiles")):
            opts.nFiles[dset] = mergedRootFile.Get("nFiles").GetBinContent(1)
        else:
            msg = "Could not find the histogram with the number of the merged root files!"
            raise Exception(es + msg + ns)

        # Get all the histogram names
        hPathList = GetHistoPaths(rootFiles[0], opts.algos)

        # For-loop: All histograms inside the ROOT files
        for j, hPath in enumerate(hPathList, 1):

            aName = hPath.split("/")[0].replace("Rate", "").replace("Eff", "")
            algo = algorithms[aName]

            Verbose(
                "Fetching histograms for algorithm %s" %
                (hs + algo.getName() + ns), j == 1)
            algo.fetchHistogram(dset, hPath, rootFiles, opts)

            Verbose("Plotting histogram %s" % (hPath), True)
            style = algo.plot(dset, hPath)
            msg = "{:>10} {:>20} {:<30}".format("%s:" % (algo.getName()),
                                                "%s:" % dset, "%s" % (hPath))
            Print(style + msg + ns, j == 1)

        # Close all ROOT files for given dataset
        CloseRootFiles(rootFiles)

    # Declare list of histos to be drawn
    turnOns = []
    rates = []
    effVBF = []

    # For-loop: All final algorithm objects
    for i, algoName in enumerate(algorithms, 1):
        algo = algorithms[algoName]

        hDict = algo.getHistos()
        for j, hName in enumerate(hDict, 1):
            h = hDict[hName]
            if "GenEtTurnOn" in h.getRootHisto().GetName():
                turnOns.append(h)
            elif "EtThreshold" in h.getRootHisto().GetName():
                if "Neutrino" not in h.getRootHisto().GetName():
                    pass
                else:
                    rates.append(h)
            elif "EtEfficiency" in h.getRootHisto().GetName():
                if "HToTauTau" in h.getRootHisto().GetName():
                    effVBF.append(h)
            else:
                pass

    # Make the plot
    Verbose("Plotting turn-on histograms for comparison", True)
    p = plots.ComparisonManyPlot(turnOns[0], turnOns[1:], saveFormats=[])
    kwargs = GetHistoKwargs("GenEtTurnOn", "TEST-1")
    plots.drawPlot(p, "TurnOns", **kwargs)
    SavePlot(p,
             "TurnOns",
             os.path.join(opts.saveDir, "Algos"),
             saveFormats=opts.saveFormats)

    # Make the plot
    Verbose("Plotting rate histograms for comparison", True)
    p = plots.ComparisonManyPlot(rates[0], rates[1:], saveFormats=[])
    kwargs = GetHistoKwargs("EtThreshold", "TEST-2")
    plots.drawPlot(p, "Rates", **kwargs)
    SavePlot(p,
             "Rates",
             os.path.join(opts.saveDir, "Algos"),
             saveFormats=opts.saveFormats)

    # Make the plot
    Verbose("Plotting efficienciesiciency histograms for comparison", True)
    p = plots.ComparisonManyPlot(effVBF[0], effVBF[1:], saveFormats=[])
    kwargs = GetHistoKwargs("EtEfficiency", "TEST-3")
    plots.drawPlot(p, "Efficiency_VBF", **kwargs)
    SavePlot(p,
             "Efficiency_VBF",
             os.path.join(opts.saveDir, "Algos"),
             saveFormats=opts.saveFormats)

    # Inform user of location of files
    Print("%sPlots saved under director \"%s\"%s" % (hs, opts.saveDir, ns),
          True)

    return
Example #21
0
def ComparisonPlot(datasetsMgr, json):
    Verbose("Creating MC plot")

    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    kwargs = {}
    ylabel_ = json["ylabel"]
    normToOne_ = json["normalizationToOne"] == "True"
    if normToOne_:
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0],
                                  "Arbitrary Units")
    #p = plots.PlotSameBase(datasetsMgr, json["histogram"], normalizeToOne=normToOne_, **kwargs) #works
    #p = plots.ComparisonPlot(*getHistos(datasetsMgr, json['samples'][0], json['histogram'], json['histogram'])) #works
    p = plots.ComparisonPlot(*getHistos(datasetsMgr, json['samples'][0],
                                        json['histogram'], "Tk_Eff"))

    # Customise styling
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetFillStyle(0))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(1.2))
    p.histoMgr.setHistoDrawStyleAll(json["drawStyle"])
    p.histoMgr.setHistoLegendStyleAll(json["legendStyle"])

    # Apply styles
    ##########################################
    p.histoMgr.forHisto("h1-VBF_HToTauTau", styles.getBaselineStyle())
    p.histoMgr.forHisto("h2-VBF_HToTauTau", styles.getInvertedStyle())

    # Set draw style
    p.histoMgr.setHistoDrawStyle("h1-VBF_HToTauTau", "LP")
    p.histoMgr.setHistoLegendStyle("h2-VBF_HToTauTau", "LP")
    # p.histoMgr.setHistoLegendStyleAll("LP")

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany({
        "h1-VBF_HToTauTau": "h1",
        "h2-VBF_HToTauTau": "h2",
    })
    ##########################################

    # Label size (optional. Commonly Used in counters)
    xlabelSize = None
    if "xlabelsize" in json:
        xlabelSize = json["xlabelsize"]
    ylabelSize = None
    if "ylabelsize" in json:
        ylabelSize = json["ylabelsize"]
    # Draw a customised plot
    saveName = os.path.join(json["saveDir"], json["title"])

    plots.drawPlot(
        p,
        saveName,
        xlabel=json["xlabel"],
        ylabel=ylabel_,
        rebinX=json["rebinX"],
        stackMCHistograms=json["stackMCHistograms"] == "True",
        addCmsText=json["addCmsText"] == "True",
        cmsExtraText=json["cmsExtraText"],
        opts=json["opts"],
        log=json["logY"] == "True",
        moveLegend=json["moveLegend"],
        cutBox={
            "cutValue": json["cutValue"],
            "fillColor": json["cutFillColour"],
            "box": json["cutBox"] == "True",
            "line": json["cutLine"] == "True",
            "greaterThan": json["cutGreaterThan"] == "True"
        },
        xlabelsize=xlabelSize,
        ylabelsize=ylabelSize,
    )

    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"),
                       json["extraText"].get("text"),
                       json["extraText"].get("size"))

    # Save in all formats chosen by user
    saveFormats = json["saveFormats"]
    for i, ext in enumerate(saveFormats):
        Print("%s" % saveName + ext, i == 0)
    p.saveAs(saveName, formats=saveFormats)
    return
Example #22
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 #23
0
def ComparisonPlot(datasetsMgr, json):
    Verbose("Creating MC plot")

    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    legendDict = {}
    kwargs = {}
    ylabel_ = json["ylabel"]
    zlabel_ = json["zlabel"]
    cutBox_ = {
        "cutValue": json["cutValue"],
        "fillColor": json["cutFillColour"],
        "box": json["cutBox"] == "True",
        "line": json["cutLine"] == "True",
        "greaterThan": json["cutGreaterThan"] == "True"
    }
    normToOne_ = json["normalizationToOne"] == "True"
    if normToOne_:
        zlabel_ = ylabel_.replace(json["ylabel"].split(" /")[0],
                                  "Arbitrary Units")

    # Get the reference histo and the list of histos to compare
    histoList = [getHisto(datasetsMgr, json['sample'], json['histogram'])]
    p = plots.PlotBase(histoList, saveFormats=[])

    # Set universal histo styles
    p.histoMgr.setHistoDrawStyleAll(json["drawStyle"])
    p.histoMgr.setHistoLegendStyleAll(json["legendStyle"])
    print json['histogram']
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinX(json["rebinX"]))
    p.histoMgr.forEachHisto(lambda h: h.getRootHisto().RebinY(json["rebinY"]))
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().GetZaxis().SetTitle(zlabel_))
    p.histoMgr.forEachHisto(
        lambda h: h.getRootHisto().GetZaxis().SetTitleOffset(1.3))
    if json["zmin"] != 0 and json["zmax"] != 0:
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetMinimum(json["zmin"]))
        p.histoMgr.forEachHisto(
            lambda h: h.getRootHisto().SetMaximum(json["zmax"]))
    #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().GetZaxis().SetRangeUser(json["zmin"], json["zmax"]))

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

    # Draw a customised plot
    saveName = os.path.join(json["saveDir"], json["title"])

    # Create the customised plot
    plots.drawPlot(
        p,
        saveName,
        xlabel=json["xlabel"],
        ylabel=ylabel_,
        zLabel=zlabel_,
        stackMCHistograms=json["stackMCHistograms"] == "True",
        addCmsText=json["addCmsText"] == "True",
        cmsExtraText=json["cmsExtraText"],
        opts=json["opts"],
        opts2=json["opts2"],
        log=json["logY"] == "True",
        moveLegend=json["moveLegend"],
        #backgroundColor   = ROOT.kAzure,
        cutBox=cutBox_,
    )

    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Set log-z?
    if json["zlog"] == "True":
        p.getPad().SetLogz(True)

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"),
                       json["extraText"].get("text"),
                       json["extraText"].get("size"))

    # Save in all formats chosen by user
    saveFormats = json["saveFormats"]
    for i, ext in enumerate(saveFormats):
        Print("%s" % saveName + ext, i == 0)
    p.saveAs(saveName, formats=saveFormats)
    return
Example #24
0
def ComparisonPlot(datasetsMgr, json):
    Verbose("Creating MC plot")
        
    # Create the MC Plot with selected normalization ("normalizeToOne", "normalizeByCrossSection", "normalizeToLumi")
    legendDict = {}
    kwargs     = {}
    ylabel_    = json["ylabel"]
    cutBox_    = {"cutValue": json["cutValue"] , "fillColor": json["cutFillColour"],
                  "box": json["cutBox"]=="True", "line": json["cutLine"]=="True",
                  "greaterThan": json["cutGreaterThan"]=="True"}
    normToOne_ = json["normalizationToOne"]=="True"
    if normToOne_:
        ylabel_ = ylabel_.replace(json["ylabel"].split(" /")[0], "Arbitrary Units")

    # Get the reference histo and the list of histos to compare
    histoReference = getHisto(datasetsMgr, json['sample'], json['histograms'][0])
    histoCompares  = getHistos(datasetsMgr, json['sample'], json['histograms'])
    p = plots.ComparisonManyPlot(histoReference, histoCompares, saveFormats=[])
    
    # Set universal histo styles
    p.histoMgr.setHistoDrawStyleAll(json["drawStyle"])
    p.histoMgr.setHistoLegendStyleAll(json["legendStyle"])

    # Set individual styles
    for i in range(0, len(histoCompares)+1):
        hName = "h%s-%s" % (i, json["sample"])
        legendDict[hName] = styles.getCaloLegend(i)
        p.histoMgr.forHisto(hName, styles.getCaloStyle(i) )
        if 0:
            p.histoMgr.setHistoDrawStyle(hName, "L")
            p.histoMgr.setHistoLegendStyle(hName, "LP")
        if json["drawStyle"]=="HIST":
            p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetFillStyle(0))
            #p.histoMgr.forEachHisto(lambda h: h.getRootHisto().SetMarkerSize(0.0))

    # Set legend labels
    p.histoMgr.setHistoLegendLabelMany(legendDict)
    
    # Draw a customised plot
    saveName = os.path.join(json["saveDir"], json["title"])    

    # Create the customised plot
    plots.drawPlot(p, 
                   saveName,                  
                   xlabel            = json["xlabel"], 
                   ylabel            = ylabel_,
                   rebinX            = json["rebinX"],
                   stackMCHistograms = json["stackMCHistograms"]=="True", 
                   addCmsText        = json["addCmsText"]=="True",
                   cmsExtraText      = json["cmsExtraText"],
                   opts              = json["opts"],
                   opts2             = json["opts2"],
                   log               = json["logY"]=="True", 
                   moveLegend        = json["moveLegend"],
                   cutBox            = cutBox_,
                   ratio             = json["ratio"]=="True",
                   ratioInvert       = json["ratioInvert"]=="True",
                   ratioYlabel       = json["ratioYlabel"],
                   )
    
    # Remove legend?
    if json["removeLegend"] == "True":
        p.removeLegend()

    # Additional text
    histograms.addText(json["extraText"].get("x"), json["extraText"].get("y"), json["extraText"].get("text"), json["extraText"].get("size") )

    # Save in all formats chosen by user
    saveFormats = json["saveFormats"]
    for i, ext in enumerate(saveFormats):
        Print("%s" % saveName + ext, i==0)
    p.saveAs(saveName, formats=saveFormats)
    return
def PlotHistograms(datasetsMgr, histoNames):
    Verbose("Plotting Data-MC Histograms")

    ROOT.gStyle.SetNdivisions(8, "X")
    ROOT.gStyle.SetNdivisions(8, "Y")

    # Get Histogram saveNname and its kwargs
    saveName = histoNames[0].rsplit("/")[-1]
    if opts.etaReg:
        saveName = saveName.replace(saveName.split("_")[-1], "CIF")
    elif opts.ptReg:
        saveName = saveName.replace(saveName.split("_")[-1], "LMH")

    kwargs_ = GetHistoKwargs(saveName, opts)
    kwargs = {}

    # Get dataset
    datasets0 = datasetsMgr.getAllDatasets()[0].getName()

    # Get histograms for the ComparisonPlot
    histoReference = getHisto(datasetsMgr, datasets0, histoNames[0])
    histoCompares = getHistos(datasetsMgr, datasets0, histoNames)

    if ("res_" in histoNames[0]) or ("match_trk_"
                                     in histoNames[0]) or ("match_tp_"
                                                           in histoNames[0]):
        histoReference.normalizeToOne()
        for h in histoCompares:
            h.normalizeToOne()

    # Create the plotting object
    p = plots.ComparisonManyPlot(histoReference, histoCompares, saveFormats=[])

    # Get Legend Names depending on the regions & customize plot
    legendDict = {}
    for index, h in enumerate(p.histoMgr.getHistos()):
        hName = h.getName()
        if opts.etaReg:
            if "_C" in hName:
                legendDict[hName] = "|#eta| < 0.8"
            elif "_I" in hName:
                legendDict[hName] = "0.8 < |#eta| < 1.6"
            elif "_F" in hName:
                legendDict[hName] = "|#eta| > 1.6"
        elif opts.ptReg:
            if "_L" in hName:
                legendDict[hName] = "p_{T} < 5 GeV/c"
            elif "_M" in hName:
                legendDict[hName] = "5 < p_{T} < 15 GeV/c"
            elif "_H" in hName:
                legendDict[hName] = "p_{T} > 15 GeV/c"

        p.histoMgr.forHisto(hName, styles.getRegionStyle(index))
        p.histoMgr.setHistoDrawStyle(hName, "LP")
        p.histoMgr.setHistoLegendStyle(hName, "LP")

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

    # Get the y axis title
    binWidth = p.histoMgr.getHistos()[0].getRootHisto().GetXaxis().GetBinWidth(
        0)
    if ("res_" in histoNames[0]) or ("match_trk_"
                                     in histoNames[0]) or ("match_tp_"
                                                           in histoNames[0]):
        kwargs_["ylabel"] = "Arbitrary Units / %s" % (
            GetBinwidthDecimals(binWidth) % (binWidth))
    else:
        ylabel = p.histoMgr.getHistos()[0].getRootHisto().GetYaxis().GetTitle(
        ) + " / %s" % (GetBinwidthDecimals(binWidth) % (binWidth))
        kwargs_["ylabel"] = ylabel

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

    # Add extra text (dataset name)
    #histograms.addText(0.65, 0.88, plots._legendLabels[datasets0], 17)
    if ("match_trk_nstub_" in histoNames[0]) or ("match_trk_chi2_"
                                                 in histoNames[0]):
        histograms.addText(0.23, 0.38, plots._legendLabels[datasets0], 17)
    else:
        histograms.addText(0.23, 0.88, plots._legendLabels[datasets0], 17)

    # Save the plots in custom list of saveFormats
    SavePlot(p, saveName, os.path.join(opts.saveDir, opts.optMode,
                                       opts.folder), [".pdf", ".png"])
    return
Example #26
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=   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 #27
0
def PlotRateVsEff(datasetsMgr, effHistoList, rateHistoList, signal, bkg, PU):

    # Definitions
    tgraphs = []
    legendDict = {}
    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" % (signal.split("_")[0], PU)
    else:
        saveName = "RateVsEff_SingleTau_%s_PU%s" % (signal.split("_")[0], PU)
    kwargs_ = GetHistoKwargs(saveName, opts)

    for i in range(0, len(effHistoList)):
        if (i == 0):
            g0 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g0.SetName("Calo")
        elif (i == 1):
            g1 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g1.SetName("Tk")
        elif (i == 2):
            g2 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g2.SetName("VtxIso")
        elif (i == 3):
            g3 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g3.SetName("RelIso")
        elif (i == 4):
            g4 = convert2RateVsEffTGraph(datasetsMgr, effHistoList[i],
                                         rateHistoList[i], signal, bkg)
            g4.SetName("Iso")

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

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

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

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

    # Draw Error bands
    for i, g in enumerate([g0, g1, g2, g3, g4]):
        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" % (PU))
    histograms.addText(0.60, 0.38, plots._legendLabels[signal], 17)

    # Save the plots in custom list of saveFormats
    aux.SavePlot(p, opts.saveDir, saveName, opts.saveFormats, True)
    return
Example #28
0
    def plot(self, dset, hPath):

        # Sanity check
        if hPath not in self.histoPaths:
            msg = "Histogram %s was not stored for plotting. Skipping!" % (
                es + hPath + ns)
            Print(msg, False)
            return

        hList = []
        myLabel = os.path.basename(hPath)
        fullPath = os.path.join(dset, hPath)
        myHisto = self.histograms[fullPath]
        integral = myHisto.Integral()

        # Sanity check (Histogram is not empty)
        if integral == 0.0:
            msg = "Skipping histogram %s (Integral = %.1f)" % (ls + hPath + ns,
                                                               integral)
            Verbose(msg, False)
            self.histosSkipped.append(hPath)
            #return ls
            return es
        else:
            msg = "Creating histogram %s" % (hs + hPath + ns)
            Verbose(msg, False)

        # Create histogram histo
        if "Vs" in hPath:
            # opts.style.setWide(onoff=True, percIncrease=0.15)
            hh = histograms.Histo(myHisto,
                                  hPath,
                                  legendStyle="L",
                                  drawStyle="COLZ",
                                  legendLabel=myLabel)
        elif "genetturnon" in hPath.lower():
            hh = histograms.Histo(myHisto,
                                  hPath,
                                  legendStyle="LP",
                                  drawStyle="AP",
                                  legendLabel=myLabel)
        else:
            hh = histograms.Histo(myHisto,
                                  hPath,
                                  legendStyle="L",
                                  drawStyle="HIST",
                                  legendLabel=myLabel)

        # Convert to rate histogram (scale appropriately)
        ConvertToRateHisto(hh)

        # Convert to turn-on histogram (EtTurnOn/EtGen)
        ConvertToTurnOnHisto(hh, self)

        # Convert to efficiency histo (requires fix due to use of hadd)
        ConvertToEfficiencyHisto(hh, dset, self)

        # Skip meaningless histos
        if "EtThreshold" in hh.getName() and "neutrino" not in dset.lower():
            return es

        # Set histogram type (Data or MC)
        hh.setIsDataMC(isData=False, isMC=True)
        hList.append(hh)
        if 0:
            aux.PrintTH1Info(hh.getRootHisto())

        # Apply histogram style
        styles.styles[self.getIndex()].apply(hh.getRootHisto())
        self.histosCreated.append(hPath)

        # Replace original histo with final version of it
        self.histos[fullPath] = hh  #iro
        if "GenEtTurnOn" in hh.getName():
            pass
        # aux.PrintTH1Info(hh.getRootHisto())
        #sys.exit()

        # Sanity check
        if len(hList) < 1:
            return es

        # Get the keyword arguments for this specific histogram
        # saveName = hPath.replace("/", "_").replace(self.getName(), self.getName() + "_") #iro
        saveName = hPath.replace("/", "_")
        kwargs = GetHistoKwargs(saveName, self.getLabel())

        # Make the plot
        Verbose("Plotting all histograms for comparison", True)
        p = plots.ComparisonManyPlot(hList[0], hList[1:], saveFormats=[])

        # Apply Univeral style?
        if 0:
            p.histoMgr.setHistoDrawStyleAll("HIST")
            p.histoMgr.setHistoLegendStyleAll("FLP")

        # Set legend labels
        p.histoMgr.setHistoLegendLabelMany({hPath: kwargs["legend"]})

        # Set Legend header?
        p.setLegendHeader(
            GetDatasetLabel(dset))  # p.setLegendHeader(self.getLabel())

        # Add MC uncertainty (if not a TH2)
        if "Vs" in str(type(hList[0])):
            p.addMCUncertainty()  # appears to do nothing..

        # Draw the plot
        plots.drawPlot(p, dset + ":" + hPath, **kwargs)

        # Save the plot
        SavePlot(p,
                 saveName,
                 os.path.join(opts.saveDir, dset),
                 saveFormats=opts.saveFormats)
        return ss