def draw_geff(t, title, h_bins, to_draw, den_cut, extra_num_cut, opt = "", color = kBlue, marker_st = 1, marker_sz = 1.): """Make an efficiency plot""" ## total numerator selection cut num_cut = AND(den_cut,extra_num_cut) ## PyROOT works a little different than ROOT when you are plotting ## histograms directly from tree. Hence, this work-around nBins = int(h_bins[1:-1].split(',')[0]) minBin = float(h_bins[1:-1].split(',')[1]) maxBin = float(h_bins[1:-1].split(',')[2]) num = TH1F("num", "", nBins, minBin, maxBin) den = TH1F("den", "", nBins, minBin, maxBin) t.Draw(to_draw + ">>num", num_cut, "goff") t.Draw(to_draw + ">>den", den_cut, "goff") debug = False if debug: print("Denominator cut", den_cut, den.GetEntries()) print("Numerator cut", num_cut, num.GetEntries()) ## check if the number of passed entries larger than total entries doConsistencyCheck = False if doConsistencyCheck: for i in range(0,nBins): print(i, num.GetBinContent(i), den.GetBinContent(i)) if num.GetBinContent(i) > den.GetBinContent(i): print(">>>Error: passed entries > total entries") eff = TEfficiency(num, den) ## plotting options if not "same" in opt: num.Reset() num.GetYaxis().SetRangeUser(0.0,1.1) num.SetStats(0) num.SetTitle(title) num.Draw() eff.SetLineWidth(2) eff.SetLineColor(color) eff.SetMarkerStyle(marker_st) eff.SetMarkerColor(color) eff.SetMarkerSize(marker_sz) eff.Draw(opt + " same") SetOwnership(eff, False) return eff
def MakeOneHist(dirName, histogramName): HeaderLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetTextFont(42) HeaderLabel.SetTextSize(0.697674) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) CMSLabel = TPaveLabel(header_x_left,header_y_bottom,header_x_right,header_y_top,HeaderText,"NDC") CMSLabel.SetTextAlign(32) CMSLabel.SetTextFont(42) CMSLabel.SetTextSize(0.697674) CMSLabel.SetBorderSize(0) CMSLabel.SetFillColor(0) CMSLabel.SetFillStyle(0) if makeFancy: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,"CMS Preliminary","NDC") LumiLabel.SetTextFont(62) LumiLabel.SetTextSize(0.7) LumiLabel.SetTextAlign(12) else: LumiLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,LumiText,"NDC") LumiLabel.SetTextAlign(32) LumiLabel.SetTextFont(42) LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) #legend coordinates, empirically determined :-) x_left = 0.4 x_right = 0.7 y_min = 0.15 y_max = 0.3 Legend = TLegend(x_left,y_min,x_right,y_max) Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) Canvas = TCanvas(histogramName) Histograms = [] HistogramClones = [] NBins = [] MaxXValues = [] MinXValues = [] LegendEntries = [] colorIndex = 0 for source in input_sources: # loop over different input sources in config file dataset_file = "condor/%s/%s.root" % (source['condor_dir'],source['dataset']) inputFile = TFile(dataset_file) NumHistogramObj = inputFile.Get(source['num_channel'] + "Plotter/" + dirName + "/" + histogramName) if 'condor_dir_den' in source: # If specified, take the denominator histogram from a different condor directory. dataset_fileDen = "condor/%s/%s.root" % (source['condor_dir_den'],source['dataset']) inputFileDen = TFile(dataset_fileDen) DenHistogramObj = inputFileDen.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName) else: # Default is to use the same condor directory DenHistogramObj = inputFile.Get(source['den_channel'] + "Plotter/" + dirName + "/" + histogramName) if not NumHistogramObj: print "WARNING: Could not find histogram " + source['num_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return if not DenHistogramObj: print "WARNING: Could not find histogram " + source['den_channel'] + "Plotter/" + dirName + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return Histogram = NumHistogramObj.Clone() if Histogram.Class().InheritsFrom("TH2"): Histogram.SetName(Histogram.GetName() + "__" + source['dataset']) Histogram.SetDirectory(0) DenHistogram = DenHistogramObj.Clone() DenHistogram.SetDirectory(0) inputFile.Close() nbinsN = Histogram.GetNbinsX() nbinsD = DenHistogram.GetNbinsX() if not noOverFlow: # Add overflow Histogram.SetBinContent( nbinsN, Histogram.GetBinContent(nbinsN) + Histogram.GetBinContent(nbinsN+1)) DenHistogram.SetBinContent(nbinsD, DenHistogram.GetBinContent(nbinsD) + DenHistogram.GetBinContent(nbinsD+1)) # Set the errors to be the sum in quadrature Histogram.SetBinError( nbinsN, math.sqrt(math.pow(Histogram.GetBinError(nbinsN),2) + math.pow(Histogram.GetBinError(nbinsN+1),2))) DenHistogram.SetBinError(nbinsD, math.sqrt(math.pow(DenHistogram.GetBinError(nbinsD),2) + math.pow(DenHistogram.GetBinError(nbinsD+1),2))) if not noUnderFlow: # Add underflow Histogram.SetBinContent( 1, Histogram.GetBinContent(1) + Histogram.GetBinContent(0)) DenHistogram.SetBinContent(1, DenHistogram.GetBinContent(1) + DenHistogram.GetBinContent(0)) # Set the errors to be the sum in quadrature Histogram.SetBinError( 1, math.sqrt(math.pow(Histogram.GetBinError(1), 2) + math.pow(Histogram.GetBinError(0), 2))) DenHistogram.SetBinError(1, math.sqrt(math.pow(DenHistogram.GetBinError(1), 2) + math.pow(DenHistogram.GetBinError(0), 2))) if arguments.rebinFactor: RebinFactor = int(arguments.rebinFactor) #don't rebin histograms which will have less than 5 bins or any gen-matching histograms if Histogram.GetNbinsX() >= RebinFactor*5 and Histogram.GetTitle().find("GenMatch") is -1 and not Histogram.Class().InheritsFrom("TH2"): Histogram.Rebin(RebinFactor) DenHistogram.Rebin(RebinFactor) xAxisLabel = Histogram.GetXaxis().GetTitle() unitBeginIndex = xAxisLabel.find("[") unitEndIndex = xAxisLabel.find("]") if unitBeginIndex is not -1 and unitEndIndex is not -1: #x axis has a unit yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " " + xAxisLabel[unitBeginIndex+1:unitEndIndex] + " width)" else: yAxisLabel = "#epsilon_{ " + cutName + "} (" + str(Histogram.GetXaxis().GetBinWidth(1)) + " width)" if arguments.normalizeToUnitArea: yAxisLabel = yAxisLabel + " (Unit Area Norm.)" #check if bin content is consistent TEfficiency.CheckConsistency(Histogram,DenHistogram) for i in range(1,Histogram.GetNbinsX()+1): if Histogram.GetBinContent(i) > DenHistogram.GetBinContent(i): DenHistogram.SetBinContent(i,Histogram.GetBinContent(i)) #HistogramClone and HistogramClones only used for ratio plot HistogramClone = Histogram.Clone() HistogramClone.SetDirectory(0) HistogramClone.Divide(DenHistogram) Nbins = HistogramClone.GetNbinsX() MaxXValue = HistogramClone.GetXaxis().GetBinLowEdge(Nbins+1) MinXValue = HistogramClone.GetXaxis().GetBinLowEdge(1) #this Histogram becomes the main TEfficiency if Histogram.Class().InheritsFrom("TH2"): Histogram.Divide(DenHistogram) else: #using default methods (which give correct uncertainties) #see https://root.cern.ch/doc/master/classTEfficiency.html (c.f. section IV) Histogram = TEfficiency(Histogram,DenHistogram) if not arguments.makeFancy: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") # print splitTitle if len(splitTitle) > 1: histoTitle = splitTitle[1].lstrip(" ") else: histoTitle = splitTitle[0] else: histoTitle = "" if 'color' in source: Histogram.SetMarkerColor(colors[source['color']]) Histogram.SetLineColor(colors[source['color']]) else: Histogram.SetMarkerColor(colors[colorList[colorIndex]]) Histogram.SetLineColor(colors[colorList[colorIndex]]) colorIndex = colorIndex + 1 if colorIndex is len(colorList): colorIndex = 0 markerStyle = 20 if 'marker' in source: markerStyle = markers[source['marker']] if 'fill' in source: markerStyle = markerStyle + fills[source['fill']] Histogram.SetMarkerStyle(markerStyle) Histogram.SetLineWidth(line_width) Histogram.SetFillStyle(0) LegendEntries.append(source['legend_entry']) Histograms.append(Histogram) HistogramClones.append(HistogramClone) NBins.append(Nbins) MaxXValues.append(MaxXValue) MinXValues.append(MinXValue) ### scaling histograms as per user's specifications for histogram in Histograms: if arguments.normalizeToUnitArea and histogram.Integral() > 0: histogram.Scale(1./histogram.Integral()) ### formatting histograms and adding to legend legendIndex = 0 for histogram in Histograms: Legend.AddEntry(histogram,LegendEntries[legendIndex],"LEP") legendIndex = legendIndex+1 ### finding the maximum value of anything going on the canvas, so we know how to set the y-axis finalMax = 1.1 if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots addOneToRatio = -1 if arguments.addOneToRatio: addOneToRatio = arguments.addOneToRatio dontRebinRatio = -1 if arguments.dontRebinRatio: dontRebinRatio = arguments.dontRebinRatio ratioRelErrMax = -1 if arguments.ratioRelErrMax: ratioRelErrMax = arguments.ratioRelErrMax yAxisMin = 0.0001 if arguments.setYMin: yAxisMin = float(arguments.setYMin) if makeRatioPlots or makeDiffPlots: Canvas.SetFillStyle(0) Canvas.Divide(1,2) Canvas.cd(1) gPad.SetPad(0,0.25,1,1) gPad.SetMargin(0.15,0.05,0.01,0.07) gPad.SetFillStyle(0) gPad.Update() gPad.Draw() if arguments.setLogY: gPad.SetLogy() Canvas.cd(2) gPad.SetPad(0,0,1,0.25) #format: gPad.SetMargin(l,r,b,t) gPad.SetMargin(0.15,0.05,0.4,0.01) gPad.SetFillStyle(0) gPad.SetGridy(1) gPad.Update() gPad.Draw() Canvas.cd(1) histCounter = 0 plotting_options = "" if arguments.plot_hist: plotting_options = "HIST" h = TH2F("h1","",NBins[0],MinXValues[0],MaxXValues[0],110,0.,finalMax) h.SetTitle(";"+xAxisLabel+";"+yAxisLabel) h.Draw() for histogram in Histograms: if histogram.Class().InheritsFrom("TH2"): histogram.SetTitle(histoTitle) histogram.Draw("colz") DatasetName = histogram.GetName() DatasetName = DatasetName[DatasetName.rfind('__')+2:] # substring starting with the last underscore DatasetLabel = TPaveLabel(topLeft_x_left,topLeft_y_bottom,topLeft_x_right,topLeft_y_top,DatasetName,"NDC") DatasetLabel.SetBorderSize(0) DatasetLabel.SetFillColor(0) DatasetLabel.SetFillStyle(0) DatasetLabel.Draw() outputFile.cd() Canvas.SetName(histogram.GetName()) Canvas.Write() else: if histogram.InheritsFrom("TEfficiency") and histCounter==0: plotting_options = "P SAME" histogram.SetTitle(histoTitle) histogram.Draw(plotting_options) if histogram.InheritsFrom("TH1"): histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if histCounter is 0: if histogram.InheritsFrom("TH1"): plotting_options = plotting_options + " SAME" elif histogram.InheritsFrom("TEfficiency"): plotting_options = "P" + " SAME" histCounter = histCounter + 1 if histogram.Class().InheritsFrom("TH2"): return Legend.Draw() if arguments.makeFancy: HeaderLabel.Draw() LumiLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: makeRatio = functools.partial (ratioHistogram,HistogramClones[0],HistogramClones[1]) if addOneToRatio != -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, addOne = bool (addOneToRatio)) if ratioRelErrMax is not -1: # it gets initialized to this dummy value of -1 makeRatio = functools.partial (makeRatio, relErrMax = float (ratioRelErrMax)) if dontRebinRatio is True: makeRatio = functools.partial (makeRatio, dontRebinRatio) Comparison = makeRatio () elif makeDiffPlots: Comparison = Histograms[0].Clone("diff") Comparison.Add(Histograms[1],-1) Comparison.SetTitle("") Comparison.GetYaxis().SetTitle("hist1-hist2") Comparison.GetXaxis().SetTitle(xAxisLabel) Comparison.GetYaxis().CenterTitle() Comparison.GetYaxis().SetTitleSize(0.1) Comparison.GetYaxis().SetTitleOffset(0.5) Comparison.GetXaxis().SetTitleSize(0.15) Comparison.GetYaxis().SetLabelSize(0.1) Comparison.GetXaxis().SetLabelSize(0.15) if makeRatioPlots: RatioYRange = 1.15 if arguments.ratioYRange: RatioYRange = float(arguments.ratioYRange) if addOneToRatio == -1: # it gets initialized to this dummy value of -1 Comparison.GetYaxis().SetRangeUser(-1*RatioYRange, RatioYRange) else: Comparison.GetYaxis().SetRangeUser(-1*RatioYRange + 1.0, RatioYRange + 1.0) elif makeDiffPlots: YMax = Comparison.GetMaximum() YMin = Comparison.GetMinimum() if YMax <= 0 and YMin <= 0: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,0) elif YMax >= 0 and YMin >= 0: Comparison.GetYaxis().SetRangeUser(0,1.2*YMax) else: #axis crosses y=0 if abs(YMax) > abs(YMin): Comparison.GetYaxis().SetRangeUser(-1.2*YMax,1.2*YMax) else: Comparison.GetYaxis().SetRangeUser(-1.2*YMin,1.2*YMin) Comparison.GetYaxis().SetNdivisions(205) Comparison.Draw("E0") outputFile.cd(dirName) Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("efficiency_histograms_pdfs/"+histogramName+".pdf")
hPass.Sumw2() tree.Draw(var + '>>hAll', 'ht>450 && nBJets>1 && triggerBit[7]') tree.Draw( var + '>>hPass', 'ht>450 && nBJets>1 && triggerBit[7] && (triggerBit[0] || triggerBit[2])') print hAll.Integral() print hPass.Integral() eff = TEfficiency('Efficiency', 'Efficiency', bins, xmin, xmax) eff.SetPassedHistogram(hPass, "f") eff.SetTotalHistogram(hAll, "f") eff.SetMarkerColor(ROOT.kBlack) eff.SetLineColor(ROOT.kBlack) eff.SetMarkerStyle(20) x = [] y = [] exl = [] exh = [] eyl = [] eyh = [] for i in xrange(hAll.GetNbinsX()): x.append(hAll.GetBinCenter(i + 1)) exl.append(0) exh.append(0) y.append(eff.GetEfficiency(i + 1)) eyl.append(eff.GetEfficiencyErrorLow(i + 1)) eyh.append(eff.GetEfficiencyErrorUp(i + 1))
def makeCombinedEtaPlot(self, tight=False): hist = self.makeL1TimeVsEtaPlot(('tight_' if tight else '') + 'dtOnly_bxidVsEta')[2] countsInL1 = [] for x in np.arange(-.95, 1.05, 0.1): totalCounter = 0 zeroCount = 0 for y in range(-2, 3): totalCounter += hist.GetBinContent(hist.FindBin(x, y)) if y == 0: zeroCount = hist.GetBinContent(hist.FindBin(x, y)) countsInL1.append({ 'total': totalCounter, 'zero': zeroCount, 'eta': x }) #Graph for results graph1 = TEfficiency(hist.GetName(), "", 8, -9.195, -.5) graph2 = TEfficiency(hist.GetName(), "", 8, .5, 9.195) for item in countsInL1: if item['total'] == 0: continue print item['total'], item['zero'], item['eta'] if item['eta'] < 0: graph1.SetTotalEvents( graph1.FindFixBin(-0.5 + item['eta'] / 0.087), int(item['total'])) graph1.SetPassedEvents( graph1.FindFixBin(-0.5 + item['eta'] / 0.087), int(item['zero'])) else: graph2.SetTotalEvents( graph2.FindFixBin(0.5 + item['eta'] / 0.087), int(item['total'])) graph2.SetPassedEvents( graph2.FindFixBin(0.5 + item['eta'] / 0.087), int(item['zero'])) histHo = None if tight: histHo = self.plotTightHoTimeVsEta()[3][1] else: histHo = self.plotHoTimeVsEta()[3][1] histHo.SetTitle(('Tight ' if tight else '') + 'Unmatched DT + HO') canvas = TCanvas( 'combinedPlot' + ('Tight ' if tight else '') + hist.GetName(), 'combinedPlot') canvas.cd().SetTopMargin(.15) histHo.Draw('ap') canvas.Update() canvas.cd().SetTicks(0, 0) histHo.SetMarkerStyle(2) histHo.SetLineColor(colorRwthDarkBlue) histHo.SetMarkerColor(colorRwthDarkBlue) histHo.GetPaintedGraph().GetXaxis().SetRangeUser(-12, 12) histHo.GetPaintedGraph().GetXaxis().SetLabelColor(colorRwthDarkBlue) histHo.GetPaintedGraph().GetXaxis().SetTitleColor(colorRwthDarkBlue) histHo.GetPaintedGraph().GetXaxis().SetAxisColor(colorRwthDarkBlue) yMax = gPad.GetFrame().GetY2() yMin = gPad.GetFrame().GetY1() #Print average Fraction excluding iEta +/-2 x = Double(0) y = Double(0) mean = 0 var = 0 for i in range(0, histHo.GetPaintedGraph().GetN()): histHo.GetPaintedGraph().GetPoint(i, x, y) if abs(x) == 2: continue mean += y var += histHo.GetPaintedGraph().GetErrorY( i) * histHo.GetPaintedGraph().GetErrorY(i) mean /= histHo.GetPaintedGraph().GetN() - 2 sigma = sqrt(var / (histHo.GetPaintedGraph().GetN() - 2)) self.debug( "Average fraction excluding iEta +/- 2 %s: %5.2f%% +/- %5.2f%%" % ('[Tight]' if tight else '', mean * 100, sigma * 100)) nTotal = 0 nPassed = 0 for item in countsInL1: if fabs(item['eta']) == 2 or fabs(item['eta'] == 0): continue nTotal += item['total'] nPassed += item['zero'] #Print again with ClopperPearson uncertainty, the counts are for L1!!! mean = nPassed / nTotal * 100 sigmaPlus = TEfficiency.ClopperPearson(int(nTotal), int(nPassed), .68, 1) * 100 - mean sigmaMinus = mean - TEfficiency.ClopperPearson( int(nTotal), int(nPassed), .68, 0) * 100 #self.debug("Average fraction excluding iEta +/- 2 %s with Clop.Pear.: %5.2f%% +%5.2f%% -%5.2f%%" # % ('[Tight]' if tight else '',mean,sigmaPlus,sigmaMinus)) #Left axis part f1 = TF1("f1", "x", -0.87, 0) A1 = TGaxis(-10, yMax, -0.5, yMax, "f1", 010, "-") A1.SetLineColor(colorRwthRot) A1.SetLabelColor(colorRwthRot) A1.Draw() #Right axis part f2 = TF1("f2", "x", 0, 0.87) A2 = TGaxis(0.5, yMax, 10, yMax, "f2", 010, "-") A2.SetLineColor(colorRwthRot) A2.SetLabelColor(colorRwthRot) A2.Draw() #Box for shading out 0 box = TBox(-.5, yMin, 0.5, yMax) box.SetLineColor(colorRwthDarkGray) box.SetFillColor(colorRwthDarkGray) box.SetFillStyle(3013) box.Draw('same') #Left L1 eta graph1.SetMarkerColor(colorRwthRot) graph1.SetLineColor(colorRwthRot) graph1.SetMarkerStyle(20) graph1.Draw('same,p') #Right L1Eta graph2.SetMarkerColor(colorRwthRot) graph2.SetLineColor(colorRwthRot) graph2.SetMarkerStyle(20) graph2.Draw('same,p') #Label for extra axis axisLabel = TPaveText(0.83, 0.85, 0.89, 0.9, "NDC") axisLabel.AddText('#eta_{L1}') axisLabel.SetBorderSize(0) axisLabel.SetFillStyle(0) axisLabel.SetTextColor(colorRwthRot) axisLabel.SetTextSize(0.05) axisLabel.Draw() #Legend legend = getLegend(x1=0.1, y1=0.1, x2=0.4, y2=.35) legend.AddEntry(histHo, 'HO #in #pm12.5 ns', 'pe') legend.AddEntry(graph1, ('Tight ' if tight else '') + 'L1 BXID = 0', 'pe') legend.Draw() canvas.Update() self.storeCanvas(canvas, "combinedFractionL1AndHo" + ('Tight' if tight else ''), drawMark=False) return histHo, graph1, canvas, A1, f1, A2, f2, box, graph2, axisLabel, legend
eff_e_shower_only = TEfficiency(h_correct_shower_only, h_total) print "1 shower", h_correct_shower_only.Integral() / h_total.Integral() eff_e_more_showers_only = TEfficiency(h_correct_more_showers_only, h_total) print "1+ showers", h_correct_more_showers_only.Integral() / h_total.Integral() eff_e.Draw("apl") eff_e_more.Draw("pl same") eff_e_shower_only.Draw("pl same") eff_e_more_showers_only.Draw("pl same") gPad.Update() eff_e.GetPaintedGraph().SetMinimum(0.001) eff_e.GetPaintedGraph().SetMaximum(1.3) eff_e.GetPaintedGraph().GetXaxis().SetRangeUser(0, 3) eff_e.SetLineColor(kBlue + 1) eff_e.SetMarkerStyle(20) eff_e_more.SetLineColor(kRed + 1) eff_e_more.SetMarkerStyle(21) eff_e_shower_only.SetLineColor(kBlue + 1) eff_e_shower_only.SetLineStyle(2) eff_e_shower_only.SetMarkerStyle(24) eff_e_more_showers_only.SetLineColor(kRed + 1) eff_e_more_showers_only.SetLineStyle(2) eff_e_more_showers_only.SetMarkerStyle(25) eff_e.SaveAs("plots/pandoraNu_eff.root") eff_e_more.SaveAs("plots/pandoraNu_more_eff.root") eff_e_shower_only.SaveAs("plots/pandoraNu_s_eff.root") eff_e_more_showers_only.SaveAs("plots/pandoraNu_s_more_eff.root") leg_e = TLegend(0.16, 0.76, 0.84, 0.84) leg_e.SetNColumns(2)