def MakeOneHist(histogramName): HeaderLabel = TPaveLabel(header_x_left, header_y_bottom, header_x_right, header_y_top, HeaderText, "NDC") HeaderLabel.SetTextAlign(32) HeaderLabel.SetBorderSize(0) HeaderLabel.SetFillColor(0) HeaderLabel.SetFillStyle(0) LumiLabel = TPaveLabel(topLeft_x_left, topLeft_y_bottom, topLeft_x_right, topLeft_y_top, LumiText, "NDC") LumiLabel.SetBorderSize(0) LumiLabel.SetFillColor(0) LumiLabel.SetFillStyle(0) NormLabel = TPaveLabel() NormLabel.SetDrawOption("NDC") NormLabel.SetX1NDC(topLeft_x_left) NormLabel.SetX2NDC(topLeft_x_right) NormLabel.SetBorderSize(0) NormLabel.SetFillColor(0) NormLabel.SetFillStyle(0) NormText = "" if arguments.normalizeToUnitArea: NormText = "Scaled to unit area" Legend = TLegend() Legend.SetBorderSize(0) Legend.SetFillColor(0) Legend.SetFillStyle(0) Canvas = TCanvas(histogramName) Histograms = [] 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("OSUAnalysis/" + source['num_channel'] + "/" + 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("OSUAnalysis/" + source['den_channel'] + "/" + histogramName) else: # Default is to use the same condor directory DenHistogramObj = inputFile.Get("OSUAnalysis/" + source['den_channel'] + "/" + histogramName) if not NumHistogramObj: print "WARNING: Could not find histogram " + source[ 'num_channel'] + "/" + histogramName + " in file " + dataset_file + ". Will skip it and continue." return if not DenHistogramObj: print "WARNING: Could not find histogram " + source[ 'den_channel'] + "/" + 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() 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.)" #Histogram = ROOT.TGraphAsymmErrors(NumHistogramObj,DenHistogramObj) if arguments.noTGraph or Histogram.Class().InheritsFrom("TH2"): Histogram.Divide(DenHistogram) else: Histogram = TGraphAsymmErrors(Histogram, DenHistogram) if not arguments.makeFancy: fullTitle = Histogram.GetTitle() splitTitle = fullTitle.split(":") # print splitTitle histoTitle = splitTitle[1].lstrip(" ") 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) ### 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 = 0 if arguments.noTGraph: for histogram in Histograms: currentMax = histogram.GetMaximum() + histogram.GetBinError( histogram.GetMaximumBin()) if (currentMax > finalMax): finalMax = currentMax finalMax = 1.5 * finalMax if finalMax is 0: finalMax = 1 if arguments.setYMax: finalMax = float(arguments.setYMax) ### Drawing histograms to canvas makeRatioPlots = arguments.makeRatioPlots makeDiffPlots = arguments.makeDiffPlots 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" 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() if arguments.makeFancy: HeaderLabel.Draw() else: if histogram.InheritsFrom("TGraph") and histCounter == 0: plotting_options = "AP" histogram.SetTitle(histoTitle) histogram.Draw(plotting_options) histogram.GetXaxis().SetTitle(xAxisLabel) histogram.GetYaxis().SetTitle(yAxisLabel) if histogram.InheritsFrom("TH1"): histogram.SetMaximum(finalMax) histogram.SetMinimum(yAxisMin) if makeRatioPlots or makeDiffPlots: histogram.GetXaxis().SetLabelSize(0) if histCounter is 0: if histogram.InheritsFrom("TH1"): plotting_options = plotting_options + " SAME" elif histogram.InheritsFrom("TGraph"): plotting_options = "P" histCounter = histCounter + 1 if histogram.Class().InheritsFrom("TH2"): return #legend coordinates, empirically determined :-) x_left = 0.1677852 x_right = 0.9647651 y_min = 0.6765734 y_max = 0.9 Legend.SetX1NDC(x_left) Legend.SetY1NDC(y_min) Legend.SetX2NDC(x_right) Legend.SetY2NDC(y_max) Legend.Draw() if arguments.makeFancy: HeaderLabel.Draw() #drawing the ratio or difference plot if requested if makeRatioPlots or makeDiffPlots: Canvas.cd(2) if makeRatioPlots: Comparison = ratioHistogram(Histograms[0], Histograms[1]) 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) Comparison.GetYaxis().SetRangeUser(-1 * RatioYRange, RatioYRange) 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() Canvas.Write() if arguments.savePDFs: Canvas.SaveAs("efficiency_histograms_pdfs/" + histogramName + ".pdf")
def makeplot_single( h1_sig=None, h1_bkg=None, h1_data=None, sig_legends_=None, bkg_legends_=None, sig_colors_=None, bkg_colors_=None, hist_name_=None, sig_scale_=1.0, dir_name_="plots", output_name_=None, extraoptions=None ): if h1_sig == None or h1_bkg == None: print("nothing to plot...") return os.system("mkdir -p "+dir_name_) os.system("cp index.php "+dir_name_) s_color = [632, 617, 839, 800, 1] b_color = [920, 2007, 2005, 2003, 2001, 2011] if sig_colors_: s_color = sig_colors_ if bkg_colors_: b_color = bkg_colors_ for idx in range(len(h1_sig)): h1_sig[idx].SetLineWidth(3) h1_sig[idx].SetLineColor(s_color[idx]) for idx in range(len(h1_bkg)): h1_bkg[idx].SetLineWidth(2) h1_bkg[idx].SetLineColor(b_color[idx]) h1_bkg[idx].SetFillColorAlpha(b_color[idx], 1) if h1_data: h1_data.SetBinErrorOption(1) h1_data.SetLineColor(1) h1_data.SetLineWidth(2) h1_data.SetMarkerColor(1) h1_data.SetMarkerStyle(20) myC = r.TCanvas("myC","myC", 600, 600) myC.SetTicky(1) pad1 = r.TPad("pad1","pad1", 0.05, 0.33,0.95, 0.97) pad1.SetBottomMargin(0.027) pad1.SetRightMargin( rightMargin ) pad1.SetLeftMargin( leftMargin ) pad2 = r.TPad("pad2","pad2", 0.05, 0.04, 0.95, 0.31) pad2.SetBottomMargin(0.4) pad2.SetTopMargin(0.05) pad2.SetRightMargin( rightMargin ) pad2.SetLeftMargin( leftMargin ) pad2.Draw() pad1.Draw() pad1.cd() for idx in range(len(h1_sig)): print("before signal scaling",h1_sig[idx].Integral()) h1_sig[idx].Scale(sig_scale_) print("after signal scaling",h1_sig[idx].Integral()) stack = r.THStack("stack", "stack") nS = np.zeros(h1_bkg[0].GetNbinsX()) eS = np.zeros(h1_bkg[0].GetNbinsX()) #hist_all is used to make the data/mc ratio. remove signal for the moment due to signal is scaled right now hist_all = h1_sig[0].Clone("hist_all") hist_all.Scale(0.0) hist_s = h1_sig[0].Clone("hist_s") hist_b = h1_bkg[0].Clone("hist_b") for idx in range(len(h1_bkg)): stack.Add(h1_bkg[idx]) for ib in range(h1_bkg[0].GetNbinsX()): nS[ib] += h1_bkg[idx].GetBinContent(ib+1) eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_bkg[idx].GetBinError(ib+1)*h1_bkg[idx].GetBinError(ib+1)) hist_all.Add(h1_bkg[idx]) if idx > 0: hist_b.Add(h1_bkg[idx]) for idx in range(len(h1_sig)): print("ggH signal yield: ", hist_s.Integral()) if idx > 0: hist_temp = h1_sig[idx].Clone(h1_sig[idx].GetName()+"_temp") #hist_all.Add(hist_temp) hist_s.Add(h1_sig[idx]) print("all signal yield: ", hist_s.Integral()) stack.SetTitle("") maxY = 0.0 if "stack_signal" in extraoptions and extraoptions["stack_signal"]: for idx in range(len(h1_sig)): h1_sig[idx].SetFillColorAlpha(s_color[idx], 1) stack.Add(h1_sig[idx]) for ib in range(h1_bkg[0].GetNbinsX()): nS[ib] += h1_sig[idx].GetBinContent(ib+1) eS[ib] = math.sqrt(eS[ib]*eS[ib] + h1_sig[idx].GetBinError(ib+1)*h1_sig[idx].GetBinError(ib+1)) if stack.GetMaximum() > maxY: maxY = stack.GetMaximum() #if "SR" in h.GetTitle(): stack.Draw("hist") else: stack.Draw("hist") if stack.GetMaximum() > maxY: maxY = stack.GetMaximum() for idx in range(len(h1_sig)): if h1_sig[idx].GetMaximum() > maxY: maxY = h1_sig[idx].GetMaximum() if "SR" in h1_bkg[0].GetTitle(): #h1_sig[idx].Draw("samehist") hist_s.Draw("samehist") ##draw stack total unc on top of total histogram box = r.TBox(0,0,1,1,) box.SetFillStyle(3002) box.SetLineWidth(0) box.SetFillColor(r.kBlack) for idx in range(h1_bkg[0].GetNbinsX()): box.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]-eS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), nS[idx]+eS[idx]) if h1_data: if h1_data.GetMaximum() > maxY: maxY = h1_data.GetMaximum()+np.sqrt(h1_data.GetMaximum()) #if not "SR" in h1_data.GetTitle() or "fail" in h1_data.GetTitle(): if True: #print("debug h1_data.GetName()",h1_data.GetName(), h1_data.GetTitle()) TGraph_data = TGraphAsymmErrors(h1_data) for i in range(TGraph_data.GetN()): #data point var_x, var_y = Double(0.), Double(0.) TGraph_data.GetPoint(i,var_x,var_y) if np.fabs(var_y) < 1e-5: TGraph_data.SetPoint(i,var_x,-1.0) TGraph_data.SetPointEYlow(i,-1) TGraph_data.SetPointEYhigh(i,-1) #print("zero bins in the data TGraph: bin",i+1) else: TGraph_data.SetPoint(i,var_x,var_y) err_low = var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)) TGraph_data.SetPointEYlow(i, var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y))) TGraph_data.SetPointEYhigh(i, (0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y) TGraph_data.SetMarkerColor(1) TGraph_data.SetMarkerSize(1) TGraph_data.SetMarkerStyle(20) TGraph_data.Draw("same P") stack.GetYaxis().SetTitle("Events") stack.GetYaxis().SetTitleOffset(1.05) stack.GetYaxis().SetTitleSize(0.08) stack.GetYaxis().SetLabelSize(0.06) #stack.GetYaxis().CenterTitle() stack.GetXaxis().SetLabelSize(0.) #stack.GetXaxis().SetLabelOffset(0.013) #if "xaxis_range" in extraoptions: # stack.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1])) leg = r.TLegend(0.2, 0.60, 0.9, 0.88) leg.SetNColumns(3) leg.SetFillStyle(0) leg.SetBorderSize(0) leg.SetTextFont(42) leg.SetTextSize(0.05) for idx in range(len(h1_bkg)): leg.AddEntry(h1_bkg[idx], bkg_legends_[idx], "F") if "SR" in hist_s.GetTitle(): leg.AddEntry(hist_s, 'HH #times {:1.2}'.format(sig_scale_), "L") leg.AddEntry(box, "Total unc", "F") if h1_data: leg.AddEntry(h1_data, "Data", "ep") leg.Draw() pad2.cd() pad2.SetGridy(1) ratio = None ratio_Low = 0.0 ratio_High = 4 if h1_data: ratio = TGraphAsymmErrors(h1_data) for i in range(ratio.GetN()): #bkg prediction imc = Double(hist_all.GetBinContent(i+1)) #data point var_x, var_y = Double(0.), Double(0.) if not ("SR" in h1_data.GetTitle() and (i>5 and i<9)): ratio.GetPoint(i,var_x,var_y) if var_y == 0.: ratio.SetPoint(i,var_x,-1.0) ratio.SetPointEYlow(i,-1) ratio.SetPointEYhigh(i,-1) continue ratio.SetPoint(i,var_x,var_y/imc) err_low = (var_y - (0.5*TMath.ChisquareQuantile(0.1586555,2.*var_y)))/imc err_high = ((0.5*TMath.ChisquareQuantile(1.-0.1586555,2.*(var_y+1))) - var_y)/imc ratio.SetPointEYlow(i, err_low) ratio.SetPointEYhigh(i, err_high) ratio.SetMarkerColor(1) ratio.SetMarkerSize(1) ratio.SetMarkerStyle(20) ratio.GetXaxis().SetTitle("j_{2} regressed mass [GeV]") #myC.Update() if "ratio_range" in extraoptions: ratio_Low = extraoptions["ratio_range"][0] ratio_High = extraoptions["ratio_range"][1] ratio.GetYaxis().SetTitle("data/mc") ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High) ratio.GetXaxis().SetRangeUser(50, 220) ratio.SetTitle("") ratio.Draw("same AP") pad2.Update() print(ratio.GetTitle(),ratio.GetName(),"debug") else: ratio = h1_sig[0].Clone("ratio") ratio_High = 0.0 for ibin in range(1,ratio.GetNbinsX()+1): s = hist_s.GetBinContent(ibin) b = hist_b.GetBinContent(ibin) L = 0.0 if b > 0.0: L = s/math.sqrt(b) if L > ratio_High: ratio_High = L ratio.SetBinContent(ibin, L) if ratio_High > 1.0: ratio_High = 1.0 ratio.GetYaxis().SetRangeUser(ratio_Low, ratio_High*1.2) ratio.GetYaxis().SetTitle("S/#sqrt{B}") ratio.Draw("samehist") ratio.SetLineColor(1) ratio.SetLineWidth(2) ratio.SetMarkerStyle(20) ratio.SetMarkerColor(1) ratio.SetFillColorAlpha(1, 0) ratio.GetXaxis().SetTitleOffset(0.94) ratio.GetXaxis().SetTitleSize(0.18) ratio.GetXaxis().SetLabelSize(0.12) ratio.GetXaxis().SetLabelOffset(0.013) ratio.GetYaxis().SetTitleOffset(0.40) ratio.GetYaxis().SetTitleSize(0.17) ratio.GetYaxis().SetLabelSize(0.13) ratio.GetYaxis().SetTickLength(0.01) ratio.GetYaxis().SetNdivisions(505) #if "xaxis_range" in extraoptions: # ratio.GetXaxis().SetRangeUser(float(extraoptions["xaxis_range"][0]),float(extraoptions["xaxis_range"][1])) #draw stack total unc on the ratio plot to present the background uncertainty box_ratio = r.TBox(0,0,1,1,) box_ratio.SetFillStyle(3002) box_ratio.SetLineWidth(0) box_ratio.SetFillColor(r.kBlack) for idx in range(h1_bkg[0].GetNbinsX()): if np.fabs(nS[idx])> 1e-06: box_ratio.DrawBox(h1_bkg[0].GetBinCenter(idx+1)-0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]-eS[idx])/nS[idx], h1_bkg[0].GetBinCenter(idx+1)+0.5*h1_bkg[0].GetBinWidth(idx+1), (nS[idx]+eS[idx])/nS[idx]) else: print("blinded Higgs peak region") if "xaxis_label" in extraoptions and extraoptions["xaxis_label"] != None: x_title = extraoptions["xaxis_label"] ratio.GetXaxis().SetTitle(x_title) ratio.GetYaxis().CenterTitle() ##########draw CMS preliminary pad1.cd() tex1 = r.TLatex(leftMargin, 0.91, "CMS") tex1.SetNDC() tex1.SetTextFont(61) tex1.SetTextSize(0.070) tex1.SetLineWidth(2) tex1.Draw() tex2 = r.TLatex(leftMargin+0.12,0.912,"Internal") tex2.SetNDC() tex2.SetTextFont(52) tex2.SetTextSize(0.055) tex2.SetLineWidth(2) tex2.Draw() lumi_value = 137 if "lumi_value" in extraoptions: lumi_value = extraoptions["lumi_value"] tex3 = r.TLatex(0.72,0.912,"%d"%lumi_value+" fb^{-1} (13 TeV)") tex3.SetNDC() tex3.SetTextFont(42) tex3.SetTextSize(0.055) tex3.SetLineWidth(2) tex3.Draw() outFile = dir_name_ if output_name_: outFile = outFile + "/" +output_name_ else: outFile = outFile + "/" + hist_name_ #print("maxY = "+str(maxY)) stack.SetMaximum(maxY*1.7) #print everything into txt file text_file = open(outFile+"_linY.txt", "w") text_file.write("bin | x ") for idx in range(len(h1_bkg)): text_file.write(" | %21s"%bkg_legends_[idx]) text_file.write(" | %21s"%("total B")) for idx in range(len(sig_legends_)): text_file.write(" | %25s"%sig_legends_[idx]) if h1_data: text_file.write(" | data | data/mc") text_file.write("\n-------------") for idx in range(24*(len(h1_bkg) + 1)+ 29*len(sig_legends_)): text_file.write("-") if h1_data: text_file.write("-------") text_file.write("\n") for ibin in range(0,h1_sig[0].GetNbinsX()+1): text_file.write("%3d"%ibin+" ") text_file.write(" | %6.3f"%h1_data.GetBinCenter(ibin)+" ") for idx in range(len(h1_bkg)): text_file.write(" | %7.3f "%h1_bkg[idx].GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%h1_bkg[idx].GetBinError(ibin)) text_file.write(" | %7.3f "%hist_b.GetBinContent(ibin)+"$\\pm$"+ " %7.3f"%hist_b.GetBinError(ibin)) for idx in range(len(sig_legends_)): text_file.write(" | %9.3f "%h1_sig[idx].GetBinContent(ibin)+"$\\pm$"+ " %9.3f"%h1_sig[idx].GetBinError(ibin)) if h1_data: text_file.write(" | %d"%h1_data.GetBinContent(ibin) + " | %7.3f "%h1_data.GetBinContent(ibin) +"$\\pm$"+ " %7.3f"%h1_data.GetBinError(ibin)) text_file.write("\n\n") #print yield table for AN text_file.write("print yield table for AN\n") bkg_all = 0 bkg_all_errsq = 0 for idx in range(len(h1_bkg)): bkg_tmp = h1_bkg[idx].GetBinContent(7)+h1_bkg[idx].GetBinContent(8)+h1_bkg[idx].GetBinContent(9) bkg_errsq_tmp = h1_bkg[idx].GetBinError(7)*h1_bkg[idx].GetBinError(7)+h1_bkg[idx].GetBinError(8)*h1_bkg[idx].GetBinError(8)+h1_bkg[idx].GetBinError(9)*h1_bkg[idx].GetBinError(9) bkg_all += bkg_tmp bkg_all_errsq += bkg_errsq_tmp text_file.write("%s"%(bkg_legends_[idx])+"& %7.2f"%(bkg_tmp)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_errsq_tmp)+"\n") text_file.write("total background & %7.2f"%(bkg_all)+"$\\pm$"+ "%7.2f"%np.sqrt(bkg_all_errsq)+"\n") text_file.write("\ggHH SM ($\kapl=1$) & %7.2f"%((h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9)))+"\n") text_file.write("\VBFHH SM ($\kapl=1$) & %7.2f"%((h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.1f"%(sig_scale_*np.sqrt(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9)))+"\n") text_file.write("HH bin 8 value %s"%h1_sig[0].GetBinContent(8)+"\n") text_file.write("HH bin 9 value %s"%h1_sig[0].GetBinContent(9)+"\n") text_file.write("HH bin 7 value %s"%h1_sig[0].GetBinContent(7)+"\n") text_file.write("HH bin 8 error %s"%h1_sig[0].GetBinError(8)+"\n") text_file.write("HH bin 9 error %s"%h1_sig[0].GetBinError(9)+"\n") text_file.write("HH bin 7 error %s"%h1_sig[0].GetBinError(7)+"\n") text_file.write("total & %7.2f"%(bkg_all+(h1_sig[0].GetBinContent(7)+h1_sig[0].GetBinContent(8)+h1_sig[0].GetBinContent(9)+h1_sig[1].GetBinContent(7)+h1_sig[1].GetBinContent(8)+h1_sig[1].GetBinContent(9))/sig_scale_)+"$\\pm$"+ "%7.2f"%(np.sqrt((h1_sig[0].GetBinError(7)*h1_sig[0].GetBinError(7)+h1_sig[0].GetBinError(8)*h1_sig[0].GetBinError(8)+h1_sig[0].GetBinError(9)*h1_sig[0].GetBinError(9))/(sig_scale_*sig_scale_)+(h1_sig[1].GetBinError(7)*h1_sig[1].GetBinError(7)+h1_sig[1].GetBinError(8)*h1_sig[1].GetBinError(8)+h1_sig[1].GetBinError(9)*h1_sig[1].GetBinError(9))/(sig_scale_*sig_scale_)+bkg_all_errsq))+"\n") text_file.close() os.system("cp "+outFile+"_linY.txt "+outFile+"_logY.txt") pad1.RedrawAxis() myC.SaveAs(outFile+"_linY.png") myC.SaveAs(outFile+"_linY.pdf") myC.SaveAs(outFile+"_linY.C") pad1.cd() stack.SetMaximum(maxY*100.0) stack.SetMinimum(0.5) pad1.SetLogy() pad1.RedrawAxis() myC.SaveAs(outFile+"_logY.png") myC.SaveAs(outFile+"_logY.pdf") myC.SaveAs(outFile+"_logY.C") #save histogram and ratio to root file outFile_root = r.TFile(outFile+".root", "recreate") outFile_root.cd() for idx in range(len(h1_bkg)): h1_bkg[idx].Write() for idx in range(len(sig_legends_)): h1_sig[idx].Write() if h1_data: h1_data.Write() ratio.Write() #outFile_root.Write() outFile_root.Close()
def draw_geff(target_dir, c_title, ext, t, title, h_name, h_bins, to_draw, denom_cut, extra_num_cut, opt, color, marker_st=1, marker_sz=1): c = TCanvas("c", "c", 600, 600) c.Clear() gPad.SetGrid(1) gStyle.SetStatStyle(0) gStyle.SetOptStat(0) gStyle.SetOptFit(0) t.Draw(to_draw + ">>num_" + h_name + h_bins, extra_num_cut + denom_cut, "goff") num = TH1F(gDirectory.Get("num_" + h_name)) if not num: sys.exit('num does not exist') num = TH1F(num.Clone("eff_" + h_name)) t.Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff") den = TH1F(gDirectory.Get("denom_" + h_name).Clone("denom_" + h_name)) eff = TGraphAsymmErrors(num, den) if not "same" in opt: num.Reset() num.GetYaxis().SetRangeUser(0., 1.05) 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") ## Do fit in the flat region if "eta" in c_title: xmin = eta_min xmax = eta_max else: xmin = -999. xmax = 999. f1 = TF1("fit1", "pol0", xmin, xmax) r = eff.Fit("fit1", "RQS") ptstats = TPaveStats(0.25, 0.35, 0.75, 0.55, "brNDC") ptstats.SetName("stats") ptstats.SetBorderSize(0) ptstats.SetLineWidth(0) ptstats.SetFillColor(0) ptstats.SetTextAlign(11) ptstats.SetTextFont(42) ptstats.SetTextSize(.05) ptstats.SetTextColor(kRed) ptstats.SetOptStat(0) ptstats.SetOptFit(1111) chi2 = int(r.Chi2()) ndf = int(r.Ndf()) ## prob = r.Prob() round(2.675, 2) p0 = f1.GetParameter(0) p0e = f1.GetParError(0) ptstats.AddText("#chi^{2} / ndf: %d/%d" % (chi2, ndf)) ## ptstats.AddText("Fit probability: %f %" %(prob)) ptstats.AddText("Efficiency: %f #pm %f %%" % (p0, p0e)) ptstats.Draw("same") pt = TPaveText(0.09899329, 0.9178322, 0.8993289, 0.9737762, "blNDC") pt.SetName("title") pt.SetBorderSize(1) pt.SetFillColor(0) pt.SetFillStyle(0) pt.SetTextFont(42) pt.AddText(eff.GetTitle()) pt.Draw("same") c.Modified() c.SaveAs(target_dir + c_title + ext)