Esempio n. 1
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
Esempio n. 2
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
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
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
def main(opts):

    # Set the ROOTeError verbosity
    ROOT.gErrorIgnoreLevel = 3000  # kUnset=-1, kPrint=0, kInfo=1000, kWarning=2000, kError=3000, kBreak=4000

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    style.setGridX(opts.gridX)
    style.setGridY(opts.gridY)
    style.setOptStat(False)

    # Obtain dsetMgrCreator and register it to module selector
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=opts.mcrab)

    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts)
    datasetsMgr.updateNAllEventsToPUWeighted()

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

    # Setup & configure the dataset manager (no collision data => not needed)
    if 0:
        datasetsMgr.loadLuminosities()
        datasetsMgr.updateNAllEventsToPUWeighted()

    # Print information
    if opts.verbose:
        datasetsMgr.PrintCrossSections()
        # datasetsMgr.PrintLuminosities()

    # Print dataset information (before merge)
    datasetsMgr.PrintInfo()

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

    # Get Luminosity
    if 0:
        intLumi = datasetsMgr.getDataset("Data").getLuminosity()

    # Apply new dataset order?
    newOrder = ReorderDatasets(datasetsMgr.getAllDatasetNames(),
                               bReverse=False)
    datasetsMgr.selectAndReorder(newOrder)

    # Print dataset information (after merge)
    if 0:
        datasetsMgr.PrintInfo()  #Requires python 2.7.6 or 2.6.6

    # Plot Histograms
    histoList = datasetsMgr.getDataset(
        datasetsMgr.getAllDatasetNames()[0]).getDirectoryContent(opts.folder)
    histoPaths = [os.path.join(opts.folder, h) for h in histoList]
    histoType = type(
        datasetsMgr.getDataset(datasetsMgr.getAllDatasetNames()
                               [0]).getDatasetRootHisto(h).getHistogram())
    plotCount = 0
    inList = ["ETResolution"]

    # For-loop: All# histos in opts.folder
    for i, h in enumerate(histoPaths, 1):

        # Only do Et (don't expect dependence on PU for eta, phi
        if "etresolution" not in h.lower():
            continue

        # Forwards region not yet available for Calos
        if "_F" in h:
            continue

        bSkip = True
        for s in inList:
            bSkip = False
        if bSkip:
            continue

        histoType = str(
            type(
                datasetsMgr.getDataset(
                    datasetsMgr.getAllDatasetNames()[0]).getDatasetRootHisto(
                        h).getHistogram()))
        if "TH1" not in histoType:
            continue

        aux.PrintFlushed(h, plotCount == 0)
        plotCount += 1

        PlotHisto(datasetsMgr, h)

    print
    Print(
        "All plots saved under directory %s" %
        (ShellStyles.NoteStyle() + aux.convertToURL(opts.saveDir, opts.url) +
         ShellStyles.NormalStyle()), True)
    return
Esempio n. 8
0
def main(opts):

    # Set the ROOTeError verbosity
    ROOT.gErrorIgnoreLevel = 3000  # kUnset=-1, kPrint=0, kInfo=1000, kWarning=2000, kError=3000, kBreak=4000

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    style.setGridX(opts.gridX)
    style.setGridY(opts.gridY)
    style.setOptStat(False)

    # Obtain dsetMgrCreator and register it to module selector
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=opts.mcrab)

    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts)
    datasetsMgr.updateNAllEventsToPUWeighted()

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

    # Setup & configure the dataset manager (no collision data => not needed)
    if 0:
        datasetsMgr.loadLuminosities()
        datasetsMgr.updateNAllEventsToPUWeighted()

    # Print information
    if opts.verbose:
        datasetsMgr.PrintCrossSections()
        # datasetsMgr.PrintLuminosities()

    # Print dataset information (before merge)
    datasetsMgr.PrintInfo()

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

    # Get Luminosity
    if 0:
        intLumi = datasetsMgr.getDataset("Data").getLuminosity()

    # Apply new dataset order?
    newOrder = ReorderDatasets(datasetsMgr.getAllDatasetNames())
    datasetsMgr.selectAndReorder(newOrder)

    # Print dataset information (after merge)
    if 0:
        datasetsMgr.PrintInfo()  #Requires python 2.7.6 or 2.6.6

    # Plot Histograms
    histoList = datasetsMgr.getDataset(
        datasetsMgr.getAllDatasetNames()[0]).getDirectoryContent(opts.folder)
    histoPaths = [os.path.join(opts.folder, h) for h in histoList]
    histoType = type(
        datasetsMgr.getDataset(datasetsMgr.getAllDatasetNames()
                               [0]).getDatasetRootHisto(h).getHistogram())
    plotCount = 0
    skipList = [
        "L1TkTau_MatchTk_d0", "L1TkTau_MatchTk_d0Abs", "L1TkTau_SigTks_d0",
        "L1TkTau_SigTks_d0Abs", "L1TkTau_SigTks_d0Sig",
        "L1TkTau_SigTks_d0SigAbs", "L1TkTau_IsoTks_d0", "L1TkTau_IsoTks_d0Abs",
        "L1TkTau_IsoTks_d0Sig", "L1TkTau_IsoTks_d0SigAbs",
        "L1TkTau_ResolutionCaloEt_F", "L1TkTau_ResolutionCaloEta_F",
        "L1TkTau_ResolutionCaloPhi_F", "L1TkIsoTau_ResolutionCaloEt_F",
        "L1TkIsoTau_ResolutionCaloEta_F", "L1TkIsoTau_ResolutionCaloPhi_F",
        "DiTau_Rate_Calo_F", "DiTau_Rate_Tk_F", "DiTau_Rate_VtxIso_F",
        "DiTau_Rate_RelIso_F", "Calo_Rate_F", "Tk_Rate_F", "VtxIso_Rate_F",
        "RelIso_Rate_F"
    ]

    # For-loop: All histos in opts.folder
    for i, h in enumerate(histoPaths, 1):

        # Obsolete quantity
        if h in skipList:
            continue

        histoType = str(
            type(
                datasetsMgr.getDataset(
                    datasetsMgr.getAllDatasetNames()[0]).getDatasetRootHisto(
                        h).getHistogram()))
        if "TH1" not in histoType:
            continue

        aux.PrintFlushed(h, plotCount == 0)
        plotCount += 1
        PlotHisto(datasetsMgr, h)

    print
    Print(
        "All plots saved under directory %s" %
        (ShellStyles.NoteStyle() + aux.convertToURL(opts.saveDir, opts.url) +
         ShellStyles.NormalStyle()), True)
    return
        # Check & assign ROOT file 
        CheckRootFile(opts.rootFile)
        # opts.rootFile = f
        
        # Create directory and subdirectories
        CreatePseudoDir(opts, args)
        aux.Print("%sFile %d/%d: %s%s" % (hs, i, nFiles, f, ns), i==1)
        
        Print("Created pseudo-multicrab directory %s!" % (ss + opts.dirName + ns), True)        
        sys.exit()
    elif nFiles > 0: 
        Verbose("Multiple ROOT files mode", True)

        # For-loop: All ROOT files
        for i, f in enumerate(opts.rootFiles, 1):
            
            # Check & assign ROOT file 
            CheckRootFile(f)
            opts.rootFile = f
            
            # Create directory and subdirectories
            CreatePseudoDir(opts, args)
            aux.PrintFlushed("%sFile %d/%d: %s%s" % (hs, i, nFiles, f, ns), i==1)
        print

        Print("Created pseudo-multicrab %s" % (ss + opts.taskDirName + ns), True)
        sys.exit()
    else:
        sys.exit()
Esempio n. 10
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
Esempio n. 11
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
Esempio n. 12
0
def main(opts):

    # Set the ROOTeError verbosity
    ROOT.gErrorIgnoreLevel = 3000  # kUnset=-1, kPrint=0, kInfo=1000, kWarning=2000, kError=3000, kBreak=4000

    # Apply TDR style
    style = tdrstyle.TDRStyle()
    style.setGridX(opts.gridX)
    style.setGridY(opts.gridY)
    style.setOptStat(False)

    # Obtain dsetMgrCreator and register it to module selector
    dsetMgrCreator = dataset.readFromMulticrabCfg(directory=opts.mcrab)

    # Setup & configure the dataset manager
    datasetsMgr = GetDatasetsFromDir(opts)
    datasetsMgr.updateNAllEventsToPUWeighted()

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

    # Setup & configure the dataset manager (no collision data => not needed)
    if 0:
        datasetsMgr.loadLuminosities()
        datasetsMgr.updateNAllEventsToPUWeighted()

    # Print information
    if opts.verbose:
        datasetsMgr.PrintCrossSections()
        # datasetsMgr.PrintLuminosities()

    # Print dataset information (before merge)
    datasetsMgr.PrintInfo()

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

    # Get Luminosity
    if 0:
        intLumi = datasetsMgr.getDataset("Data").getLuminosity()

    # Print dataset information (after merge)
    if 0:
        datasetsMgr.PrintInfo()  #Requires python 2.7.6 or 2.6.6

    # Sanity check
    nDatasets = len(datasetsMgr.getAllDatasetNames())
    if (nDatasets) > 1:
        raise Exception(
            "More than 1 datasets found! Please choose only 1 dataset (-i \"regex\") and retry"
        )

    # Plot Histograms
    histoList = datasetsMgr.getDataset(
        datasetsMgr.getAllDatasetNames()[0]).getDirectoryContent(opts.folder)
    histoPaths = [os.path.join(opts.folder, h) for h in histoList]
    histoType = type(
        datasetsMgr.getDataset(datasetsMgr.getAllDatasetNames()
                               [0]).getDatasetRootHisto(h).getHistogram())
    plotCount = 0

    # For-loop: All# histos in opts.folder
    for i, h in enumerate(histoPaths, 1):

        histoType = str(
            type(
                datasetsMgr.getDataset(
                    datasetsMgr.getAllDatasetNames()[0]).getDatasetRootHisto(
                        h).getHistogram()))
        if "TH1" in histoType or "TDirectoryFile" in histoType:
            continue
        else:
            # print "histoType = ", histoType
            pass

        if "GenP" in h:
            continue

        aux.PrintFlushed(h, plotCount == 0)
        plotCount += 1

        PlotHisto(datasetsMgr, h, histoType)

    print
    Print(
        "All plots saved under directory %s" %
        (ShellStyles.NoteStyle() + aux.convertToURL(opts.saveDir, opts.url) +
         ShellStyles.NormalStyle()), True)
    return
Esempio n. 13
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