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