def getGraphSimple(self): from array import array from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors n = len(self.__x) if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh): raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh)) legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()] legend = TLegend(*legendPosition) legend.SetFillColor(0) xErr = array("d",[0 for i in range(n)]) print "__x = ", self.__x print "__y = ", self.__y graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh) graph.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle)) graph.SetLineWidth(2) graph.SetFillColor(0) graph.SetLineColor(int(self.__getStyleOption("lineColor"))) graph.SetMarkerColor(int(self.__getStyleOption("markerColor"))) graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle"))) graph.SetMarkerSize(float(self.__getStyleOption("markerSize"))) graph.SetDrawOption("AP") return (graph, legend)
def getEff(name, den_input, num_input, rebin=0, xtitle='', ytitle=''): c = TCanvas(name + '_Canvas') legend = TLegend(0.8, 0.1, 0.999, 0.6) legend.SetFillColor(kWhite) den = den_input.Clone() num = num_input.Clone() if rebin != 0: den.Rebin(rebin) num.Rebin(rebin) error_bars = TGraphAsymmErrors() error_bars.Divide(num, den, "cl=0.683 b(1,1) mode") error_bars.SetLineWidth(3) if xtitle == '': error_bars.GetXaxis().SetTitle(num.GetXaxis().GetTitle()) else: error_bars.GetXaxis().SetTitle(xtitle) if ytitle == '': error_bars.GetYaxis().SetTitle(num.GetYaxis().GetTitle()) else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.GetXaxis().SetRangeUser(400, 2000) error_bars.SetLineColor(kBlack) error_bars.SetMaximum(1.01) error_bars.SetMinimum(0.) if ytitle == '': error_bars.GetYaxis().SetTitle("Trigger rate") else: error_bars.GetYaxis().SetTitle(ytitle) error_bars.SetTitle('') error_bars.Draw('AP') c.SaveAs('pdf/' + name + '.pdf') c.Write(name + '_Canvas') error_bars.Write(name)
def readDataIntoGraph(): f = open('HESSj1745_290.dat', "r") lines = f.readlines() x, y, yHigh, yLow = array('d'), array('d'), array('d'), array('d') # yScale = 10e12 yScale = 1 xScale = 1000 for iLine in lines: if iLine.isspace() == True or iLine[0] == '#': continue tmpList = iLine.split() tmpX = xScale * float(tmpList[0]) * float(tmpList[0]) x.append(xScale * float(tmpList[0])) y.append(yScale * float(tmpList[1]) * tmpX) yLow.append(yScale * (float(tmpList[1]) - float(tmpList[2])) * tmpX) yHigh.append(yScale * (float(tmpList[3]) - float(tmpList[1])) * tmpX) f.close() listOfZeros = array("d", [0] * len(x)) gr = TGraphAsymmErrors(len(x), x, y, listOfZeros, listOfZeros, yLow, yHigh) # gr.SetLineColor( color ) gr.SetLineWidth(2) # gr.SetMarkerColor( color ) gr.SetMarkerStyle(21) gr.GetXaxis().SetTitle('Energy [GeV]') gr.GetYaxis().SetTitle('E^{2} x Flux [GeV cm^{-2}s^{-1}]') gr.SetTitle('') return gr
def geterrorband(*hists, **kwargs): """Make an error band histogram for a list of histograms, or stack. Returns an TGraphAsymmErrors object.""" verbosity = LOG.getverbosity(kwargs) hists = unwraplistargs(hists) hists = [ h.GetStack().Last() if isinstance(h, THStack) else h for h in hists ] sysvars = kwargs.get( 'sysvars', []) # list of tuples with up/cent/down variation histograms name = kwargs.get('name', None) or "error_" + hists[0].GetName() title = kwargs.get( 'title', None) or ("Sys. + stat. unc." if sysvars else "Stat. unc.") color = kwargs.get('color', kBlack) hist0 = hists[0] nbins = hist0.GetNbinsX() if sysvars and isinstance(sysvars, dict): sysvars = [v for k, v in sysvars.iteritems()] error = TGraphAsymmErrors() error.SetName(name) error.SetTitle(title) LOG.verb("geterrorband: Making error band for %s" % (hists), verbosity, 2) TAB = LOG.table( "%5s %7s %6s %10s %11s %-20s %-20s %-20s", "%5d %7.6g %6.6g %10.2f %11.2f +%8.2f -%8.2f +%8.2f -%8.2f +%8.2f -%8.2f", verb=verbosity, level=3) TAB.printheader("ibin", "xval", "xerr", "nevts", "sqrt(nevts)", "statistical unc.", "systematical unc.", "total unc.") ip = 0 for ibin in range(1, nbins + 1): xval = hist0.GetXaxis().GetBinCenter(ibin) xerr = 0 if ibin in [0, nbins + 1] else hist0.GetXaxis().GetBinWidth(ibin) / 2 yval = 0 statlow2, statupp2 = 0, 0 syslow2, sysupp2 = 0, 0 for hist in hists: # STATISTICS yval += hist.GetBinContent(ibin) statlow2 += hist.GetBinErrorLow(ibin)**2 statupp2 += hist.GetBinErrorUp(ibin)**2 for histup, hist, histdown in sysvars: # SYSTEMATIC VARIATIONS syslow2 += (hist.GetBinContent(ibin) - histdown.GetBinContent(ibin))**2 sysupp2 += (hist.GetBinContent(ibin) - histup.GetBinContent(ibin))**2 ylow2, yupp2 = statlow2 + syslow2, statupp2 + sysupp2, error.SetPoint(ip, xval, yval) error.SetPointError(ip, xerr, xerr, sqrt(ylow2), sqrt(yupp2)) TAB.printrow(ibin, xval, xerr, yval, sqrt(abs(yval)), sqrt(statupp2), sqrt(statlow2), sqrt(sysupp2), sqrt(syslow2), sqrt(yupp2), sqrt(ylow2)) ip += 1 seterrorbandstyle(error, color=color) #error.SetLineColor(hist0.GetLineColor()) error.SetLineWidth(hist0.GetLineWidth()) # use draw option 'E2 SAME' return error
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = TCanvas() c.SetLogy() #Draw input histograms hists = ['h_frac_recoil_', 'h_full_recoil_'] label = ['recoil with MET triggers', 'recoil without MET triggers'] combineHist(hists, label, leg) #leg.Draw() #c.SaveAs("Combinehists_D.pdf") ratio = [] h1 = f.Get('h_frac_recoil_') #h1=setHistStyle(h1,bins) h2 = f.Get('h_full_recoil_') #h2=setHistStyle(h2,bins) h3 = createRatio(h1, h2) gr = TGraphAsymmErrors(h1, h2) gr.GetXaxis().SetRangeUser(0, 1500) gr.GetYaxis().SetRangeUser(0, 1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(0.5) gr.SetLineColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("Recoil [GeV]") gr.SetTitle("") # print ("ratio",ratio ) # c, pad1, pad2 = createCanvasPads() # # # draw everything # pad1.cd() # h1.Draw() # h2.Draw("same") # to avoid clipping the bottom zero, redraw a small axis # h1.GetYaxis().SetLabelSize(0.0) # axis = TGaxis(-5, 20, -5, 220, 20, 220, 510, "") # axis.SetLabelFont(43) # axis.SetLabelSize(15) # axis.Draw() # pad2.cd() gr.Draw() latex.DrawLatex(0.41, 0.93, "Trigger Efficincy in MET Run2017E") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1500, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() #h3.Draw('pl') c.SaveAs("test.pdf")
def dividebybinsize(hist, **kwargs): """Divide each bin by its bin width. If a histogram has assymmetric errors (e.g. data with Poisson), return a TGraphAsymmErrors instead.""" verbosity = LOG.getverbosity(kwargs) LOG.verbose('dividebybinsize: "%s"' % (hist.GetName()), verbosity, 2) zero = kwargs.get('zero', True) # include bins that are zero in TGraph zeroerrs = kwargs.get('zeroerrs', True) # include errors for zero bins errorX = kwargs.get('errorX', gStyle.GetErrorX()) # horizontal error bars nbins = hist.GetXaxis().GetNbins() TAB = LOG.table("%5s %8.6g %8.6g %10.3f %9.4f %8.4f %8.4f %10.4f", verb=verbosity, level=3) TAB.printheader("ibin", "xval", "width", "yval", "yerr", "yupp", "ylow", "yerr/width") if hist.GetBinErrorOption( ) == TH1.kPoisson: # make asymmetric Poisson errors (like for data) graph = TGraphAsymmErrors() graph.SetName(hist.GetName() + "_graph") graph.SetTitle(hist.GetTitle()) copystyle(graph, hist) ip = 0 # skip zero bins if not zero for ibin in xrange(1, nbins + 1): xval = hist.GetXaxis().GetBinCenter(ibin) width = hist.GetXaxis().GetBinWidth(ibin) xerr = width / 2 if errorX else 0 yval = hist.GetBinContent(ibin) yerr = hist.GetBinError(ibin) yupp = hist.GetBinErrorUp(ibin) ylow = hist.GetBinErrorLow(ibin) TAB.printrow(ibin, xval, width, yval, yerr, yupp, ylow, yval / width) hist.SetBinContent(ibin, yval / width) hist.SetBinError(ibin, yerr / width) if yval != 0 or zero: graph.SetPoint(ip, xval, yval / width) if yval != 0 or zeroerrs: graph.SetPointError(ip, xerr, xerr, ylow / width, yupp / width) else: graph.SetPointError(ip, xerr, xerr, 0, 0) ip += 1 return graph else: for ibin in xrange(0, nbins + 2): xval = hist.GetXaxis().GetBinCenter(ibin) width = hist.GetXaxis().GetBinWidth(ibin) yval = hist.GetBinContent(ibin) yerr = hist.GetBinError(ibin) hist.SetBinContent(ibin, yval / width) hist.SetBinError(ibin, yerr / width) TAB.printrow(ibin, xval, width, yval, yerr, hist.GetBinErrorUp(ibin), hist.GetBinErrorLow(ibin), yval / width) return hist
def getDataPoissonErrors(hist, kPoisson=False, drawZeroBins=False, drawXbars=False, centerBin=True): '''Make data poisson errors for a histogram with two different methods: - TH1.kPoisson - chi-squared quantile ''' # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/mcPlots.py#L70-L102 # https://github.com/DESY-CMS-SUS/cmgtools-lite/blob/8_0_25/TTHAnalysis/python/plotter/susy-1lep/RcsDevel/plotDataPredictWithSyst.py#L12-L21 if kPoisson: hist.SetBinErrorOption(TH1D.kPoisson) Nbins = hist.GetNbinsX() xaxis = hist.GetXaxis() alpha = (1 - 0.6827) / 2. graph = TGraphAsymmErrors(Nbins) graph.SetName(hist.GetName() + "_graph") graph.SetTitle(hist.GetTitle()) for i in xrange(1, Nbins + 1): N = hist.GetBinContent(i) if N <= 0 and not drawZeroBins: continue dN = hist.GetBinError(i) yscale = 1 if centerBin: x = xaxis.GetBinCenter(i) else: x = xaxis.GetBinLowEdge(i) if N > 0 and dN > 0 and abs(dN**2 / N - 1) > 1e-4: # check is error is Poisson yscale = (dN**2 / N) N = (N / dN)**2 if kPoisson: EYlow = hist.GetBinErrorLow(i) EYup = hist.GetBinErrorUp(i) else: EYlow = (N - Math.chisquared_quantile_c(1 - alpha, 2 * N) / 2.) if N > 0 else 0 EYup = Math.chisquared_quantile_c(alpha, 2 * (N + 1)) / 2. - N y = yscale * N EXup = xaxis.GetBinUpEdge(i) - x if drawXbars else 0 EXlow = x - xaxis.GetBinLowEdge(i) if drawXbars else 0 graph.SetPoint(i - 1, x, y) graph.SetPointError(i - 1, EXlow, EXup, EYlow, EYup) #print ">>> getDataPoissonErrors - bin %2d: (x,y) = ( %3.1f - %4.2f + %4.2f, %4.2f - %4.2f + %4.2f )"%(i,x,EXlow,EXup,y,EYlow,EYup) graph.SetLineWidth(hist.GetLineWidth()) graph.SetLineColor(hist.GetLineColor()) graph.SetLineStyle(hist.GetLineStyle()) graph.SetMarkerSize(hist.GetMarkerSize()) graph.SetMarkerColor(hist.GetMarkerColor()) graph.SetMarkerStyle(hist.GetMarkerStyle()) return graph
def trigger_efficiency(year, separate=False): from root_numpy import root2array, fill_hist from aliases import triggers, triggers_PFHT, triggers_Jet, triggers_BTag import numpy as np #spec_triggers = {"PFHT": triggers_PFHT, "Jet": triggers_Jet, "BTag": triggers_BTag} spec_triggers = { "HT/Jet": "(" + triggers_PFHT + " || " + triggers_Jet + ")", "BTag": triggers_BTag } spec_triggers_colors = { "PFHT": 418, "Jet": 4, "BTag": 6, "HT/Jet": 4, "total": 2 } hist_pass = TH1F("pass", "pass", 100, 0., 10000.) if separate: hist_pass_spec = {} for trig in spec_triggers.keys(): hist_pass_spec[trig] = TH1F("pass_" + trig, "pass_" + trig, 100, 0., 10000.) hist_all = TH1F("all", "all", 100, 0., 10000.) file_list = [] data_2016_letters = ["B", "C", "D", "E", "F", "G", "H"] data_2017_letters = ["B", "C", "D", "E", "F"] data_2018_letters = ["A", "B", "C", "D"] sample_names = [] if year == '2016': letters = data_2016_letters elif year == '2017': letters = data_2017_letters elif year == '2018': letters = data_2018_letters else: print "unknown year" sys.exit() for letter in letters: #dir_content = os.listdir(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)) ## intended to run directly on ntuples #for entry in dir_content: # if "_flatTuple" in entry: file_list.append(TRIGGERDIR+"/SingleMuon_{}_{}/".format(year, letter)+entry) file_list.append(TRIGGERDIR + "/SingleMuon_{}_{}.root".format(year, letter)) print "appending:", TRIGGERDIR + "/SingleMuon_{}_{}.root".format( year, letter) for file_name in file_list: temp_array = root2array(file_name, treename='tree', branches='jj_mass_widejet', selection="jj_deltaEta_widejet<1.1") fill_hist(hist_all, temp_array) temp_array = root2array(file_name, treename='tree', branches='jj_mass_widejet', selection="jj_deltaEta_widejet<1.1 && " + triggers) fill_hist(hist_pass, temp_array) if separate: for trig in spec_triggers.keys(): temp_array = root2array( file_name, treename='tree', branches='jj_mass_widejet', selection="jj_deltaEta_widejet<1.1 && " + spec_triggers[trig]) fill_hist(hist_pass_spec[trig], temp_array) temp_array = None import array from aliases import dijet_bins binning = [] for num in dijet_bins: if num <= 10000: binning.append(num) #binning = range(0,1500,100)+range(1500,2000,100)+range(2000,3100,150)+range(3100,10000,300) binning_ = array.array('d', binning) hist_pass2 = hist_pass.Rebin( len(binning_) - 1, "hist_pass_rebinned", binning_) hist_all2 = hist_all.Rebin( len(binning_) - 1, "hist_all_rebinned", binning_) if separate: hist_pass_spec2 = {} for trig in spec_triggers.keys(): hist_pass_spec2[trig] = hist_pass_spec[trig].Rebin( len(binning_) - 1, "hist_pass_" + trig + "_rebinned", binning_) hist_pass2.Sumw2() hist_all2.Sumw2() eff = TGraphAsymmErrors() eff.Divide(hist_pass2, hist_all2) eff.SetMarkerColor(spec_triggers_colors["total"]) if separate: eff.SetMarkerStyle(5) else: eff.SetMarkerStyle(1) eff.SetLineColor(spec_triggers_colors["total"]) eff.SetLineWidth(2) if separate: eff_spec = {} for trig in spec_triggers.keys(): hist_pass_spec2[trig].Sumw2() eff_spec[trig] = TGraphAsymmErrors() eff_spec[trig].Divide(hist_pass_spec2[trig], hist_all2) eff_spec[trig].SetMarkerColor(spec_triggers_colors[trig]) eff_spec[trig].SetMarkerStyle(1) eff_spec[trig].SetLineColor(spec_triggers_colors[trig]) eff_spec[trig].SetLineWidth(2) one_line = TGraph() one_line.SetPoint(0, 0., 1.) one_line.SetPoint(1, 10000., 1.) one_line.SetLineStyle(2) c1 = TCanvas("c1", "Trigger Efficiency", 800, 800) c1.cd(1) eff.Draw("AP") one_line.Draw("L") eff.SetTitle(";m_{jj} (GeV);trigger efficiency") eff.SetMinimum(0.) eff.SetMaximum(1.4) #0.65 ## new dijet_bin_centers = [] for b, lthr in enumerate(dijet_bins[:-1]): if lthr < 1200 or lthr > 2500: continue dijet_bin_centers.append(0.5 * (dijet_bins[b] + dijet_bins[b + 1])) print "total trigger efficiency:" for cval in dijet_bin_centers: print cval, ":", eff.Eval(cval) ## end new if separate: leg = TLegend(0.65, 0.75, 0.9, 0.95) leg.AddEntry(eff, "total") for trig in spec_triggers.keys(): leg.AddEntry(eff_spec[trig], trig + "-based") eff_spec[trig].Draw("P SAME") ## new print trig, "trigger efficiency" for cval in dijet_bin_centers: print cval, ":", eff_spec[trig].Eval(cval) ## end new leg.Draw() eff.GetXaxis().SetTitleSize(0.045) eff.GetYaxis().SetTitleSize(0.045) eff.GetYaxis().SetTitleOffset(1.1) eff.GetXaxis().SetTitleOffset(1.05) eff.GetXaxis().SetLimits(700., 5000.) c1.SetTopMargin(0.05) #drawCMS(-1, "Preliminary", year=year) #Preliminary #drawCMS(-1, "Work in Progress", year=year, suppressCMS=True) drawCMS(-1, "", year=year, suppressCMS=True) drawAnalysis("") suffix = "" if separate: suffix = "_sep" c1.Print("plots/Efficiency/trigger_" + year + suffix + ".pdf") c1.Print("plots/Efficiency/trigger_" + year + suffix + ".png")
y1 = np.array(mediantmva) y1ues = np.array(tmvaERRORUP) y1des = np.array(tmvaERRORDOWN) y2 = np.array(mediantmvaLL) y2ues = np.array(tmvaLLERRORUP) y2des = np.array(tmvaLLERRORDOWN) numbins = 4 canvas = Canvas() graph = Graph(numbins,x,y,xes,xes,ydes,yues) #CALLING AN OBJECT OF TYPE TGraphAsymmErrors #graph = Graph(numbins,np.array(masses200),np.array(mediantmva),np.array(zeros),np.array(zeros),np.array(cutexl2),np.array(cutexh2)) graph.SetTitle("") graph.GetXaxis().SetTitle("m_{llbb} GeV") graph.GetYaxis().SetTitle("Limits") graph.SetLineColor(R.kBlack) gStyle.SetEndErrorSize(10) graph.Draw("ALP*1") legend = Legend(0.7, 0.7, 0.9, 0.9) legend.AddEntry(graph,"Cut Based Limits","l") legend.Draw("same") canvas.Print(extension+'Tgraphlimits.png') canvas = Canvas() graph = Graph(numbins,x,y,xes,xes,ydes,yues) graph1 = Graph(numbins,x,y1,xes,xes,y1des,y1ues) #graph = Graph(numbins,np.array(masses200),np.array(mediantmva),np.array(zeros),np.array(zeros),np.array(cutexl2),np.array(cutexh2))
C = TCanvas() C.Print("PUWeights.pdf[") # Loop over json content # for name, path in dict_files.items(): print("Looking at %s" % name) # Load json content # with open(path, "r") as handle: data = json.load(handle) # Get binning content # bins = data['data'] # List of dict (1 dict per bin) g = TGraphAsymmErrors(len(bins)) # Loop over bins # for i, b in enumerate(bins): val = b['value'] up = b['error_high'] down = b['error_low'] bincenter = (b['bin'][0] + b['bin'][1]) / 2 g.SetPoint(i, bincenter, val) g.SetPointError(i, 0, 0, up, down) g.GetHistogram().SetMinimum(0.) g.GetHistogram().SetMaximum(2.) g.SetTitle("Sample : %s" % name) g.GetXaxis().SetTitle("nTrueInt") g.GetYaxis().SetTitle("PU weight") C.Clear() g.Draw() C.Print("PUWeights.pdf", "Title:%s" % name) C.Print("PUWeights.pdf]")
import math from ROOT import TFile, TCanvas, TGraph, TGraphAsymmErrors import array Binning_PT = array.array("d", [0, 30, 35, 40, 50, 60, 75, 95, 120, 150, 200]) OutFile = TFile("OutPutFR.root") HistoNum = OutFile.Get("histoLooseNumerator") HistoNum = HistoNum.Rebin(len(Binning_PT) - 1, "", Binning_PT) HistoDeNum = OutFile.Get("histoDenominator") HistoDeNum = HistoDeNum.Rebin(len(Binning_PT) - 1, "", Binning_PT) fakeRate = TGraphAsymmErrors(HistoNum, HistoDeNum, "") canv = TCanvas("canv", "histograms", 0, 0, 600, 600) canv.SetLogy() fakeRate.GetXaxis().SetRangeUser(0, 200) fakeRate.GetXaxis().SetTitle("#tau p_{T} [GeV]") fakeRate.GetYaxis().SetRangeUser(0.01, 0.5) fakeRate.SetTitle('Jet to Tau Fake Rate') fakeRate.SetMarkerStyle(20) fakeRate.Draw() canv.SaveAs("jetToTauFR.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 Plot1DEfficiency(num, den, plotname, topTitle, xAxisTitle, xAxisRangeLow, xAxisRangeHigh): nbins = num.GetXaxis().GetNbins() x = list() y = list() xErrLow = list() xErrHigh = list() yErrLow = list() yErrHigh = list() for b in range(1, nbins): xtemp = num.GetXaxis().GetBinCenter(b + 1) xerrlow = num.GetXaxis().GetBinCenter( b + 1) - num.GetXaxis().GetBinLowEdge(b + 1) xerrhigh = num.GetXaxis().GetBinUpEdge( b + 1) - num.GetXaxis().GetBinCenter(b + 1) ratio = 0 errLow = 0 errHigh = 0 n1 = int(num.GetBinContent(b + 1)) n2 = int(den.GetBinContent(b + 1)) print "numerator: " + str(n1) + " and denominator: " + str(n2) if (n1 > n2): n1 = n2 if (n2 > 0): ratio = float(n1) / float(n2) if (ratio > 1): ratio = 1 errLow = ratio - TEfficiency.ClopperPearson( n2, n1, 0.68269, False) errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio print " done bin " + str( b) + " " + str(xtemp) + " : " + str(n1) + "(" + str( num.GetBinContent(b + 1)) + ")" + " / " + str(n2) + "(" + str( den.GetBinContent(b + 1)) + ")" + " = " + str( ratio) + " " + str(errLow) + " " + str(errHigh) ytemp = ratio yerrlowtemp = errLow yerrhightemp = errHigh print "x: " + str(xtemp) + " and y: " + str(ytemp) x.append(xtemp) y.append(ytemp) xErrLow.append(xerrlow) xErrHigh.append(xerrhigh) yErrLow.append(yerrlowtemp) yErrHigh.append(yerrhightemp) c = TCanvas("cv", "cv", 800, 800) c.SetLeftMargin(0.12) #must convert list into array for TGraphAsymmErrors to work xArr = array.array('f', x) yArr = array.array('f', y) xErrLowArr = array.array('f', xErrLow) xErrHighArr = array.array('f', xErrHigh) yErrLowArr = array.array('f', yErrLow) yErrHighArr = array.array('f', yErrHigh) effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr, yErrLowArr, yErrHighArr) effGraph.Draw("APE") effGraph.SetTitle("") effGraph.GetXaxis().SetTitle(xAxisTitle) effGraph.GetXaxis().SetTitleSize(0.05) effGraph.GetXaxis().SetTitleOffset(0.90) effGraph.GetXaxis().SetLabelSize(0.03) effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh) effGraph.GetYaxis().SetTitle("Efficiency") effGraph.GetYaxis().SetTitleSize(0.05) effGraph.GetYaxis().SetTitleOffset(1.05) effGraph.GetYaxis().SetLabelSize(0.03) title = TLatex() title.SetTextSize(0.05) title.DrawLatexNDC(.2, .93, topTitle) c.Update() c.SaveAs(plotname + ".gif")
import math from ROOT import TFile, TCanvas, TGraph, TGraphAsymmErrors import array Binning_PT = array.array('d', [0, 20, 25, 30, 40, 55, 75, 95, 120, 150, 200, 300]) OutFile = TFile('outputEfficiency.root') HistoNum = OutFile.Get('histoLooseNumerator') HistoNum = HistoNum.Rebin(len(Binning_PT) - 1, '', Binning_PT) HistoDeNum = OutFile.Get('histoDenominator') HistoDeNum = HistoDeNum.Rebin(len(Binning_PT) - 1, '', Binning_PT) tauEffi = TGraphAsymmErrors(HistoNum, HistoDeNum, '') canv = TCanvas('canv', 'histograms', 0, 0, 600, 600) tauEffi.SetMinimum(0.5) tauEffi.GetXaxis().SetRangeUser(0, 300) tauEffi.GetXaxis().SetTitle('Reconstructed #tau p_{T} [GeV]') tauEffi.GetYaxis().SetRangeUser(0, 1) tauEffi.SetTitle('Tau Efficiency') tauEffi.SetMarkerStyle(20) tauEffi.Draw() canv.SaveAs('tauEfficiency.pdf')
name = ["300", "400", "600", "1000", "1200", "1400", "1600"] err_sigeff_M1 = [] xM1 = ROOT.Double(0) yM1 = ROOT.Double(0) for i in range(nfile): preselect = file.Get("h_preselect_"+str(i)) med1 = file.Get("h_med1_"+str(i)) effM1 = TGraphAsymmErrors(med1,preselect,"cl=0.683 b(1,1) mode") effM1.SetTitle("Medium 1") binM1 = effM1.GetN() for j in range(binM1): effM1.GetPoint(j, xM1, yM1) if (yM1 == 0): continue else: errM1 = effM1.GetErrorY(j) err_sigeff_M1.append(errM1) #print "errM1_"+str(name[i]), errM1 ''' print "####################################" print "err_sigeff_M1", err_sigeff_M1 print "####################################" '''
def drawMassRes(data, mc, output, rapidity, ptda, ptmc, trackType, funct, mcIsData, dataIsMC): style = setTDRStyle() pt_e = [0 for x in range(len(data))] pt_x = [0 for x in range(len(data))] for i, pt in enumerate(pt_x): pt_x[i] = ptbins[i] + (ptbins[i + 1] - ptbins[i]) / 2. pt_e[i] = (ptbins[i + 1] - ptbins[i]) / 2. if dataIsMC: (da_mean, da_meane, da_sig, da_sige, da_nChi2) = doFit(data, output, rapidity, "MC2", trackType, funct) else: (da_mean, da_meane, da_sig, da_sige, da_nChi2) = doFit(data, output, rapidity, "DATA", trackType, funct) if mcIsData: (mc_mean, mc_meane, mc_sig, mc_sige, mc_nChi2) = doFit(mc, output, rapidity, "DATA2", trackType, funct) else: (mc_mean, mc_meane, mc_sig, mc_sige, mc_nChi2) = doFit(mc, output, rapidity, "MC", trackType, funct) result = {} result["data_mean"] = da_mean result["data_meane"] = da_meane result["data_sig"] = da_sig result["data_sige"] = da_sige result["mc_mean"] = mc_mean result["mc_meane"] = mc_meane result["mc_sig"] = mc_sig result["mc_sige"] = mc_sige result["ptda"] = ptda result["ptmc"] = ptmc result["da_nChi2"] = da_nChi2 result["mc_nChi2"] = mc_nChi2 pklFile = open( output + "/MassResolutionVsPt_%s_%s.pkl" % (trackType, rapidity), "wb") pickle.dump(result, pklFile) pklFile.close() c2 = TCanvas("c2", "c2", 700, 700) c2.cd() # Upper plot will be in pad1 pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.SetGrid() # Vertical grid pad1.SetBottomMargin(0.1) pad1.Draw() # Draw the upper pad: pad1 pad1.cd() # pad1 becomes the current pad pad1.SetTicks() res_data = TGraphAsymmErrors() res_data.SetName("res_data") res_mc = TGraphAsymmErrors() res_mc.SetName("res_mc") ratio = TGraphErrors() ratio.SetName("ratio") #~ print len(pt_x) for i, pt in enumerate(pt_x): res_data.SetPoint(i, ptda[i], da_sig[i]) res_data.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i], da_sige[i], da_sige[i]) res_mc.SetPoint(i, ptmc[i], mc_sig[i]) res_mc.SetPointError(i, ptmc[i] - ptbins[i], ptbins[i + 1] - ptmc[i], mc_sige[i], mc_sige[i]) if mc_sig[i] > 0: ratio.SetPoint(i, pt, da_sig[i] / mc_sig[i]) ratio.SetPointError(i, pt_e[i], (da_sig[i] / mc_sig[i]) * math.sqrt((da_sige[i] / da_sig[i])**2 + (mc_sige[i] / mc_sig[i])**2)) res_data.SetMarkerStyle(22) res_data.SetMarkerColor(kBlack) res_data.SetLineColor(kBlack) res_data.SetFillColor(0) res_data.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType) res_data.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]") res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") res_data.GetYaxis().SetTitleOffset(1.2) res_data.GetYaxis().SetRangeUser(0., 6.) if trackType == "Outer": res_data.GetYaxis().SetRangeUser(1., 20.) res_data.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)]) res_data.Draw("AP E0") res_mc.SetMarkerStyle(22) res_mc.SetMarkerColor(kRed) res_mc.SetLineColor(kRed) res_mc.SetFillColor(0) res_mc.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType) res_mc.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]") res_mc.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") res_mc.GetYaxis().SetTitleOffset(1.5) res_mc.Draw("P E0 SAME") if rapidity == "BB": leg = TLegend(0.25, 0.6, 0.50, 0.80, "both muons |#eta| < 1.2", "brNDC") else: leg = TLegend(0.25, 0.6, 0.5, 0.8, "at least one muon |#eta| > 1.2", "brNDC") if mcIsData: leg.AddEntry(res_data, "DATA 2017") leg.AddEntry(res_mc, "DATA 2016") elif dataIsMC: leg.AddEntry(res_data, "MC 2017") leg.AddEntry(res_mc, "MC 2016") else: leg.AddEntry(res_data, "DATA", "p") leg.AddEntry(res_mc, "Simulation") leg.SetTextFont(42) leg.SetBorderSize(0) leg.SetTextSize(.04) leg.Draw("SAME") latex = TLatex() latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(0.04) latex.SetNDC(True) latexCMS = TLatex() latexCMS.SetTextFont(61) latexCMS.SetTextSize(0.055 / 0.7) latexCMS.SetNDC(True) latexCMSExtra = TLatex() latexCMSExtra.SetTextFont(52) latexCMSExtra.SetTextSize(0.03 / 0.7) latexCMSExtra.SetNDC(True) latex.DrawLatex(0.95, 0.96, "(13 TeV)") cmsExtra = "Preliminary" latexCMS.DrawLatex(0.78, 0.88, "CMS") yLabelPos = 0.84 latexCMSExtra.DrawLatex(0.78, yLabelPos, "%s" % (cmsExtra)) c2.cd() # Go back to the main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0, 0.1, 1, 0.30) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.3) pad2.SetGrid() pad2.Draw() pad2.cd() pad2.SetTicks() ratio.SetMarkerColor(kBlue - 4) ratio.SetFillColor(kBlue - 4) ratio.SetTitle("") ratio.GetYaxis().SetTitle("Data/MC") if mcIsData: ratio.GetYaxis().SetTitle("Data 2017 / Data 2016") elif dataIsMC: ratio.GetYaxis().SetTitle("MC 2017 / MC 2016") ratio.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]") ratio.GetYaxis().SetRangeUser(0.5, 1.5) ratio.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)]) ratio.GetYaxis().SetTitleOffset(0.50) ratio.GetYaxis().SetTitleSize(0.14) ratio.GetYaxis().SetLabelSize(0.14) ratio.GetYaxis().SetNdivisions(506) ratio.GetXaxis().SetTitleSize(0.12) ratio.GetXaxis().SetTitleOffset(1.2) ratio.GetXaxis().SetLabelSize(0.20) ratio.Draw("A P E2") pad2.Update() line = TLine(ptbins[0], 1, ptbins[len(ptda)], 1) line.SetLineColor(kBlue + 1) line.SetLineWidth(2) line.Draw() saveas = "/MassResolutionVsPt_%s_%s" % (trackType, rapidity) c2.SaveAs(output + saveas + ".png") c2.SaveAs(output + saveas + ".pdf") c2.SaveAs(output + saveas + ".root") c2.SaveAs(output + saveas + ".C")
def RootifyCrossBR(self): for processname in self.processnames: outfilename_cross = self.crosssecfolder+'/Crosssections_%s%s.root' % (processname, self.tag) cross_module = importlib.import_module('crosssections.ChiPsi.Crosssections_%s' % (processname)) crosssections = cross_module.crosssection if self.submit: outfile = TFile(outfilename_cross, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_cross)) print green('--> Now at sample %s' % (processname)) for lamb in self.lambdas: if not lamb in crosssections: continue print green(' --> Now at lambda: %s' % (get_lambdastring(lamb))) xsecs_per_mref = crosssections[lamb] graph2d = TGraph2D() npoints2d=0 set_points ={} all_combinations = get_all_combinations(preferred_configurations=preferred_configurations) for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = False for mref in xsecs_per_mref: xsecs = xsecs_per_mref[mref] final_xsecs = [] mdeps = array('d') sigmas = array('d') tot_los = array('d') tot_his = array('d') mdeps_lo = array('d') mdeps_hi = array('d') for tuple in xsecs: mdep, sigma, q_lo, q_hi, pdf = tuple tot_lo = XsecTotErr(sigma, q_lo, pdf) tot_hi = XsecTotErr(sigma, q_hi, pdf) final_xsecs.append((mdep, sigma, tot_lo, tot_hi)) mdeps.append(mdep) sigmas.append(sigma) tot_los.append(tot_lo) tot_his.append(tot_hi) mdeps_lo.append(0.) mdeps_hi.append(0.) if 'LQLQ' in processname or 'LQTChannel' in processname: graph2d.SetPoint(npoints2d, mdep, mref, sigma) set_points[mdep][mref] = True elif 'PsiPsi' in processname: graph2d.SetPoint(npoints2d, mref, mdep, sigma) set_points[mref][mdep] = True else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') npoints2d += 1 # make TGraph out of it graph = TGraphAsymmErrors(len(mdeps), mdeps, sigmas, mdeps_lo, mdeps_hi, tot_los, tot_his) xaxistitle = 'M_{LQ} [GeV]' if ('LQLQ' in processname or 'LQTChannel' in processname) else 'M_{#chi_{1}} [GeV]' graph.GetXaxis().SetTitle('M_{LQ} [GeV]') graph.GetYaxis().SetTitle('#sigma [pb]') graphname = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphname += '_MC1%i' % (mref) elif 'PsiPsi' in processname: graphname += '_MLQ%i' % (mref) else: raise ValueError('processname does not contain \'LQLQ\' or \'PsiPsi\', what kind of process are we looking at here?') graphname += '_L%s' % (get_lambdastring(lamb)) graph.SetName(graphname) # print 'graphname: %s' % (graphname) graphtitle = processname if 'LQLQ' in processname or 'LQTChannel' in processname: graphtitle += ', M_{#chi_{1}} = %i GeV' % (mref) elif 'PsiPsi' in processname: graphtitle += ', M_{LQ} = %i GeV' % (mref) graphtitle += ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.')) # print 'graphtitle: %s' % (graphtitle) graph.SetTitle(graphtitle) if self.submit: outfile.cd() graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: if not set_points[mlq][mch]: graph2d.SetPoint(npoints2d, mlq, mch, 0.) npoints2d += 1 graph2d.SetName(processname + '_L%s' % (get_lambdastring(lamb))) graph2d.GetXaxis().SetTitle('M_{LQ} [GeV]') graph2d.GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') graph2d.GetZaxis().SetTitle('#sigma [pb]') graph2d.SetTitle(processname + ', #lambda = %s' % (get_lambdastring(lamb).replace('p', '.'))) if self.submit: graph2d.Write() else: print yellow(' --> Would have written 2d-graph to outfile') if self.submit: outfile.Close() # also rootify BRs if we are looking at the LQLQ process without decays (just for fun, could also be any other LQLQ process) if processname == 'LQLQ': outfilename_br = self.crosssecfolder+'/Branchingratios_%s%s.root' % (processname, self.tag) if self.submit: outfile = TFile(outfilename_br, 'RECREATE') else: print yellow('--> Would have created outfile %s' % (outfilename_br)) br_module = importlib.import_module('crosssections.ChiPsi.Branchingratios_%s' % (processname)) allbrs = br_module.branchingratio for lamb in allbrs.keys(): brs = allbrs[lamb] brs2d = {} npoints2d = {} set_points ={} for mlq in all_combinations: set_points[mlq] = {} for mch in all_combinations[mlq]: set_points[mlq][mch] = {} for decaymode in decaymode_dict.keys(): set_points[mlq][mch][decaymode] = False decaymodes_present = [] for mlq in sorted(brs): mchs_per_decaymode = {} brs_per_decaymode = {} for mch in sorted(brs[mlq]): for decaymode in brs[mlq][mch]: if not decaymode in decaymodes_present: decaymodes_present.append(decaymode) if not decaymode in mchs_per_decaymode.keys(): mchs_per_decaymode[decaymode] = array('d') if not decaymode in brs_per_decaymode.keys(): brs_per_decaymode[decaymode] = array('d') # if not decaymode in set_points[mlq][mch].keys(): # # print mlq, mch, decaymode # set_points[mlq][mch][decaymode] = False if not decaymode in brs2d.keys(): graphname2d = processname + ('_L%s_%i_%i' % (get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) # print graphname2d npoints2d[decaymode] = 0 brs2d[decaymode] = TGraph2D() brs2d[decaymode].SetName(graphname2d) brs2d[decaymode].GetXaxis().SetTitle('M_{LQ} [GeV]') brs2d[decaymode].GetYaxis().SetTitle('M_{#chi_{1}} = %i [GeV]') brs2d[decaymode].GetZaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) brs2d[decaymode].SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) mchs_per_decaymode[decaymode].append(mch) brs_per_decaymode[decaymode].append(brs[mlq][mch][decaymode][0]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, brs[mlq][mch][decaymode][0]) set_points[mlq][mch][decaymode] = True npoints2d[decaymode] += 1 for decaymode in mchs_per_decaymode.keys(): graph = TGraph(len(mchs_per_decaymode[decaymode]), mchs_per_decaymode[decaymode], brs_per_decaymode[decaymode]) graphname = processname + ('_MLQ%i_L%s_%i_%i' % (mlq, get_lambdastring(lamb), abs(decaymode[0]), abs(decaymode[1]))) graph.SetName(graphname) graph.GetXaxis().SetTitle('M_{#chi_{1}} [GeV]') graph.GetYaxis().SetTitle('BR (LQLQ#rightarrow%s)' % (decaymode_dict[decaymode])) graph.SetTitle(processname + ', %s' % (decaymode_dict[decaymode])) if self.submit: graph.Write() else: print yellow(' --> Would have written graph %s to outfile' % (graphname)) # fill remaining points in 2d graph with zeros for mlq in set_points: for mch in set_points[mlq]: for decaymode in set_points[mlq][mch]: if not set_points[mlq][mch][decaymode] and decaymode in decaymodes_present: # print decaymode # print brs2d.keys() # print npoints2d.keys() # print 'Setting BR for MLQ=%i, MCH=%i, decay=(%i, %i) to 0' % (mlq, mch, decaymode[0], decaymode[1]) brs2d[decaymode].SetPoint(npoints2d[decaymode], mlq, mch, 0) npoints2d[decaymode] += 1 if self.submit: for decaymode in brs2d: brs2d[decaymode].Write() else: print yellow(' --> Would have written 2d-graphs to outfile') outfile.Close()
xM1 = ROOT.Double(0) yM1 = ROOT.Double(0) xM2 = ROOT.Double(0) yM2 = ROOT.Double(0) for i in range(nfile): preselect = file.Get("h_preselect_"+str(i)) loo = file.Get("h_loo_"+str(i)) med1 = file.Get("h_med1_"+str(i)) med2 = file.Get("h_med2_"+str(i)) #gPad.Modified() effL = TGraphAsymmErrors(loo,preselect,"cl=0.683 b(1,1) mode") effL.SetTitle("Loose") binL = effL.GetN() for j in range(binL): effL.GetPoint(j, xL, yL) if (yL == 0): continue else: errL = effL.GetErrorY(j) err_sigeff_L.append(errL) #print "errL_"+str(name[i]), errL effM1 = TGraphAsymmErrors(med1,preselect,"cl=0.683 b(1,1) mode") effM1.SetTitle("Medium 1") binM1 = effM1.GetN() for j in range(binM1): effM1.GetPoint(j, xM1, yM1)
graph.SetMarkerStyle(8) c = ROOT.TCanvas("c","c",700,600) c.SetLeftMargin(0.17) c.Draw() graph.GetYaxis().SetTitle("#sigma(#Delta t) [ns]") graph.GetXaxis().SetTitle("A_{eff}") graph.Draw("ap") if args.logx: c.SetLogx(1) graph.GetXaxis().SetLimits(x[0]-2*x_low[0], x[-1]+2*x_low[-1]) if args.logy: c.SetLogy(1) graph.GetHistogram().SetMinimum(y.min()/2) graph.GetHistogram().SetMaximum(y.max()*3) graph.SetTitle("") Frame(gPad) yrlabel = TextAuto(gPad, args.year, align = 31) last = histo.GetNbinsX() - 1 func = TF1("func","sqrt(([0]/(x))^2 + 2*([1]^2))", x[0]-x_low[0], x[last]+x_high[last]) func.SetParameter(0, N) func.SetParameter(1, C) graph.Fit("func","R") Nlabel = Text(gPad, 0.6, 0.7, "N = {:.3f} #pm {:.3f} ns".format(func.GetParameter(0), func.GetParError(0))) Clabel = Text(gPad, 0.6, 0.65,"C = {:.3f} #pm {:.3f} ns".format(func.GetParameter(1), func.GetParError(1))) c.Update() c.Modified() if args.show: input()
def plotQIcalibration(results, outDir = "results", currentMode = ""): gROOT.SetBatch(True) calibGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) #for ch in xrange(1, len(results)+1): # Number of channels for ch in sorted(results.keys()): gr = TGraphAsymmErrors() gr.SetMarkerStyle(22) gr.SetMarkerSize(1.2) gr.SetName("Channel_%d_Charge_vs_DAC" % ch) gr.SetTitle("Channel %d Charge vs DAC value%s" % (ch, " %s current mode" % currentMode if currentMode in ["low", "high"] else "")) res = results[ch] for i, dacVal in enumerate(sorted(res.keys())): mean = res[dacVal]["mean"] * 25.e6 # Convert to fC err = res[dacVal]["std"] * 25.e6 # Index of new point np = gr.GetN() # Set value and error gr.SetPoint(np, dacVal, mean) gr.SetPointError(np, 0., 0., err, err) calibGraphs.append((gr,ch)) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/calibGraphs" % outDir ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/calibration.root", "RECREATE") fitParams = {} # Converted to charge by * 25ns for i,(gr,ch) in enumerate(calibGraphs): gr.Fit('pol1', "Q") # Q: Quiet mode f = gr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %g #pm %g slope %g #pm %g" % (p0, p0_err, p1, p1_err) # Convert to fC fitParams[ch] = {"slope":(p1), "offset":(p0)} #fitParams[(i+1)] = {"slope":(p1), "offset":(p0)} gr.GetXaxis().SetTitle("DAC value") gr.GetYaxis().SetTitle("Charge [fC]") if currentMode == "low": gr.GetYaxis().SetTitleOffset(1.37) pad1.cd() gr.Draw("AP") gr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.40,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/calibGraphs/channel_%d.png" % (i+1)) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close() return fitParams
def plotHistos(dac, histVals, qiCalib = None, outDir = "results", currentMode = ""): adcGraphs = [] chargeGraphs = [] gStyle.SetMarkerColor(kBlue) gStyle.SetLineColor(kBlack) convFactor = 1. if qiCalib is None: # Use nominal qiCalib print "Using nominal QI calibrations" if currentMode == "low": convFactor = 1.375 elif currentMode == "high": convFactor = 7.7 offset = 0. else: print "Using custom QI calibrations" #for i in range(len(histVals[dac[0]])): for i in range(12): adcGr = TGraphAsymmErrors() adcGr.SetMarkerStyle(22) #adcGr.SetMarkerSize(1.0) adcGr.SetName("h%d_ADC" % i) adcGr.SetTitle("h%d ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) chGr = TGraphAsymmErrors() chGr.SetMarkerStyle(22) #chGr.SetMarkerSize(1.3) chGr.SetName("h%d_LinADC" % i) chGr.SetTitle("h%d Lin ADC vs %s" % (i, "Charge %s current mode" % currentMode if currentMode in ["low", "high"] else "DAC value")) adcGraphs.append(adcGr) chargeGraphs.append(chGr) for i, dv in enumerate(dac): for n in range(len(adcGraphs)): mean = histVals[dv][n]["mean"] err = histVals[dv][n]["rms"] if qiCalib is not None: QIchan = int(n/6)*8 + n%6 + 1 convFactor = qiCalib[QIchan]["slope"] offset = qiCalib[QIchan]["offset"] # Index of new point np = adcGraphs[n].GetN() # Set value and error adcGraphs[n].SetPoint(np, dv*convFactor + offset, mean) adcGraphs[n].SetPointError(np, 0., 0., err, err) chMean, chErr = linADC(mean, err) chargeGraphs[n].SetPoint(np, dv*convFactor + offset, chMean) chargeGraphs[n].SetPointError(np, 0., 0., chErr, chErr) if outDir[-1] == "/": outDir = outDir[:-1] os.system("mkdir -p %s/adcH; mkdir -p %s/chargeH" % (outDir, outDir) ) c1 = TCanvas('c1','c1', 1200, 800) c1.SetLeftMargin(0.15); c1.SetRightMargin(0.25) c1.SetBottomMargin(0.25); pad1=TPad('p1','p1',0.,0.,1.0,1.0) pad1.Draw() outF = TFile.Open(outDir + "/histos.root", "RECREATE") xAxisTitle = "Charge [fC]" if currentMode in ["low", "high"] else "DAC value" for i,adcGr in enumerate(adcGraphs): """ adcGr.Fit('pol1', "Q") # Q: Quiet mode f = adcGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) """ adcGr.GetXaxis().SetTitle(xAxisTitle) adcGr.GetYaxis().SetTitle("ADC") adcGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) adcGr.Draw("AP") adcGr.Write() Quiet(c1.SaveAs)(outDir + "/adcH/adc_hist_%d.png" % i) c1.SetLogy(True) for i,chGr in enumerate(chargeGraphs): chGr.Fit('pol1', "Q") # Q: Quiet mode f = chGr.GetFunction("pol1") p0 = f.GetParameter(0) p0_err = f.GetParError(0) p1 = f.GetParameter(1) p1_err = f.GetParError(1) fitline = "offset %.3f #pm %.2f slope %.3f #pm %.6f" % (p0, p0_err, p1, p1_err) chGr.GetXaxis().SetTitle(xAxisTitle) chGr.GetYaxis().SetTitle("Linearized ADC") chGr.GetYaxis().SetTitleOffset(1.2) pad1.cd() pad1.SetLogx(True) pad1.SetLogy(True) chGr.Draw("AP") chGr.Write() txt=TLatex() txt.SetNDC(True) txt.SetTextFont(43) txt.SetTextSize(20) txt.SetTextAlign(12) txt.DrawLatex(0.45,0.87, fitline) Quiet(c1.SaveAs)(outDir + "/chargeH/charge_hist_%d.png" % i) # for g in adcGraphs: # # g.Write() # for g in chargeGraphs: # g.Write() #outF.Write() outF.Close()
vbfxsec = vbf[imass[0]] vbfGr.SetPoint(ipt, imass[0], vbfxsec[0]) vbfGr.SetPointError(ipt, 0, 0, vbfxsec[1], vbfxsec[2]) total = ggxsec[0] + vbfxsec[0] errUp = math.sqrt(pow(ggxsec[1], 2) + pow(vbfxsec[1], 2)) errDown = math.sqrt(pow(ggxsec[2], 2) + pow(vbfxsec[2], 2)) totalGr.SetPoint(ipt, imass[0], total) totalGr.SetPointError(ipt, 0, 0, errUp, errDown) ipt = ipt + 1 c = ROOT.TCanvas("c", "c", 600, 600) totalGr.SetName("total") totalGr.SetTitle("gg+VBF") totalGr.SetMarkerStyle(20) totalGr.SetMarkerColor(1) totalGr.SetFillColor(0) totalGr.SetFillStyle(0) totalGr.Draw("ae1p") totalGr.GetXaxis().SetTitle("Higgs mass [GeV/c^{2}]") totalGr.GetYaxis().SetTitle("Cross section [pb]") glugluGr.SetName("gg") glugluGr.SetTitle("gg") glugluGr.SetMarkerStyle(21) glugluGr.SetMarkerColor(2) glugluGr.SetFillColor(0) glugluGr.SetFillStyle(0) glugluGr.Draw("e1p")
float(lines_exp[1][3]) - float(lines_exp[1][1]), float(lines_exp[2][3]) - float(lines_exp[2][1]) ]) zeros = array('d', [0, 0, 0]) exp1sigma = TGraphAsymmErrors(3, x, y_exp, zeros, zeros, y_err1down, y_err1up) exp2sigma = TGraphAsymmErrors(3, x, y_exp, zeros, zeros, y_err2down, y_err2up) explim = TGraph(3, x, y_exp) obslim = TGraph(3, x, y_obs) obslim.SetLineWidth(3) explim.SetLineWidth(3) explim.SetLineStyle(2) explim.SetTitle('') obslim.SetTitle('') exp2sigma.SetTitle('') exp1sigma.SetTitle('') #obslim.SetMinimum(0.001); #duesigma=TGraphAsymmErrors(3,) exp1sigma.SetFillColor(kGreen + 1) exp2sigma.SetFillColor(kOrange) exp2sigma.SetMaximum(150) exp2sigma.SetMinimum(0.07) exp2sigma.Draw('a3lp') exp2sigma.GetXaxis().SetTitle("Z' mass [TeV]") exp2sigma.GetXaxis().SetRangeUser(1.4, 2.6) exp2sigma.GetYaxis().SetTitle("Upper cross section limit [pb]") sizefactor = 1.6 exp2sigma.GetXaxis().SetTitleSize( sizefactor * exp2sigma.GetXaxis().GetTitleSize())
def plot(inputfilename=None, histofilename="EfficiencyHistos.root", basecut="nTelTracks == 1", matchcut="hasHit == 0", ucells=0, vcells=0): ubins = ucells vbins = vcells total_cut = TCut(basecut) pass_cut = TCut(basecut) + TCut(matchcut) if inputfilename == None: return None rawfile = gROOT.FindObject(inputfilename) if rawfile: rawfile.Close() rawfile = TFile(inputfilename, 'READ') histofile = gROOT.FindObject(histofilename) if histofile: histofile.Close() histofile = TFile( histofilename, 'RECREATE', 'Efficiency histos created from input file ' + inputfilename) # Get access to tracks tree = rawfile.Get("Track") # Compute efficiency for v cells h_track_v_total = TH1F("h_track_v_total", "", vbins, 0, vcells) tree.Draw("cellV_fit >> +h_track_v_total", total_cut, "goff") h_track_v_total.GetXaxis().SetTitle("cellV_fit [cellID]") h_track_v_total.GetYaxis().SetTitle("tracks") h_track_v_pass = TH1F("h_track_v_pass", "", vbins, 0, vcells) tree.Draw("cellV_fit >> +h_track_v_pass", pass_cut, "goff") h_track_v_pass.GetXaxis().SetTitle("cellV_fit [cellID]") h_track_v_pass.GetYaxis().SetTitle("tracks") g_efficiency_v = TGraphAsymmErrors() g_efficiency_v.SetName("g_efficiency_v") g_efficiency_v.Divide(h_track_v_pass, h_track_v_total) g_efficiency_v.SetTitle("") g_efficiency_v.GetXaxis().SetTitle("cellV_fit [cellID]") g_efficiency_v.GetYaxis().SetTitle("efficiency") g_efficiency_v.Write() # Compute efficiency for u cells h_track_u_total = TH1F("h_track_u_total", "", ubins, 0, ucells) tree.Draw("cellU_fit >> +h_track_u_total", total_cut, "goff") h_track_u_total.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_u_total.GetYaxis().SetTitle("tracks") h_track_u_pass = TH1F("h_track_u_pass", "", ubins, 0, ucells) tree.Draw("cellU_fit >> +h_track_u_pass", pass_cut, "goff") h_track_u_pass.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_u_pass.GetYaxis().SetTitle("tracks") g_efficiency_u = TGraphAsymmErrors() g_efficiency_u.SetName("g_efficiency_u") g_efficiency_u.Divide(h_track_u_pass, h_track_u_total) g_efficiency_u.SetTitle("") g_efficiency_u.GetXaxis().SetTitle("cellU_fit [cellID]") g_efficiency_u.GetYaxis().SetTitle("efficiency") g_efficiency_u.Write() # Compute efficiency for u:v h_track_total = TH2F("h_track_total", "", ubins, 0, ucells, vbins, 0, vcells) tree.Draw("cellV_fit:cellU_fit >> +h_track_total", total_cut, "goff") h_track_total.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_total.GetYaxis().SetTitle("cellV_fit [cellID]") h_track_total.GetZaxis().SetTitle("tracks") h_track_pass = TH2F("h_track_pass", "", ubins, 0, ucells, vbins, 0, vcells) tree.Draw("cellV_fit:cellU_fit >> +h_track_pass", pass_cut, "goff") h_track_pass.GetXaxis().SetTitle("cellU_fit [cellID]") h_track_pass.GetYaxis().SetTitle("cellV_fit [cellID]") h_track_pass.GetZaxis().SetTitle("tracks") g_efficiency = h_track_pass g_efficiency.SetName("g_efficiency") g_efficiency.Divide(h_track_pass, h_track_total) g_efficiency.SetTitle("") g_efficiency.GetXaxis().SetTitle("cellU_fit [cellID]") g_efficiency.GetYaxis().SetTitle("cellV_fit [cellID]") g_efficiency.GetZaxis().SetTitle("efficiency") g_efficiency.SetStats(0) g_efficiency.Write() # write the tree into the output file and close the file histofile.Write() histofile.Close() rawfile.Close()
buffer_h_s = g_tpr.GetEYhigh() buffer_h_s.SetSize(g_size) arr_h_s = np.array(buffer_h_s, copy=True) print arr_h_s print arr_l_s exit() g_fpr = GAE() g_tpr = GAE() g_fpr.Divide(h_c_b, h_before_selection, "cl=0.683 b(1,1) mode") g_tpr.Divide(h_c_s, h_true, "cl=0.683 b(1,1) mode") # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> for debugging: ''' g_fpr.SetTitle('efficiency(fpr)') g_fpr.SetFillColor(5) g_fpr.SetMarkerStyle(21) g_fpr.SetMarkerColor(4) #g_fpr.Draw('ALP') #g_fpr.Draw('ALPE1') #g_fpr.Draw('3A')a #slp(33) g_tpr.SetTitle('True Positive Rate') g_tpr.SetFillColor(5) g_tpr.SetMarkerStyle(21) g_tpr.SetMarkerColor(4) #g_tpr.Draw('ALP') #g_tpr.Draw('3A')a #slp(33)
def Plot1DEfficiencyWithFit(tree, plotname, topTitle, xAxisTitle, xAxisRangeLow, xAxisRangeHigh): #make amp histogram c = TCanvas("c", "c", 800, 800) ampHist = TH1F("ampHist", ";Amplitude [mV]; Number of Events", 25, 0, 50) tree.Draw( "amp[3]>>ampHist", " x_dut[2] > 19.6 && x_dut[2] < 19.7 && y_dut[2] > 23.5 && y_dut[2] < 24.0 && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16)" ) # create function for fitting fitFunction = TF1("NoisePlusLandauGaus", NoisePlusLandauGaus, 0, 50, 5) fitFunction.SetParameters(10, 0.95, 20.0, 2.5, 3.0) fitFunction.SetParNames("a", "f", "mpv", "sigmaLandau", "sigmaGaus") #fitFunction.SetParLimits(0, -1, -4) #fitFunction.SetParLimits(1, 0.01, 0.2) #fitFunction.SetParLimits(2, 0, 2) #fitFunction.SetParLimits(3, 0, 1000) ampHist.Fit("NoisePlusLandauGaus") c.SaveAs("fit.gif") return nbins = num.GetXaxis().GetNbins() x = list() y = list() xErrLow = list() xErrHigh = list() yErrLow = list() yErrHigh = list() for b in range(1, nbins): xtemp = num.GetXaxis().GetBinCenter(b + 1) xerrlow = num.GetXaxis().GetBinCenter( b + 1) - num.GetXaxis().GetBinLowEdge(b + 1) xerrhigh = num.GetXaxis().GetBinUpEdge( b + 1) - num.GetXaxis().GetBinCenter(b + 1) ratio = 0 errLow = 0 errHigh = 0 n1 = int(num.GetBinContent(b + 1)) n2 = int(den.GetBinContent(b + 1)) print "numerator: " + str(n1) + " and denominator: " + str(n2) if (n1 > n2): n1 = n2 if (n2 > 0): ratio = float(n1) / float(n2) if (ratio > 1): ratio = 1 errLow = ratio - TEfficiency.ClopperPearson( n2, n1, 0.68269, False) errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio print " done bin " + str( b) + " " + str(xtemp) + " : " + str(n1) + "(" + str( num.GetBinContent(b + 1)) + ")" + " / " + str(n2) + "(" + str( den.GetBinContent(b + 1)) + ")" + " = " + str( ratio) + " " + str(errLow) + " " + str(errHigh) ytemp = ratio yerrlowtemp = errLow yerrhightemp = errHigh print "x: " + str(xtemp) + " and y: " + str(ytemp) x.append(xtemp) y.append(ytemp) xErrLow.append(xerrlow) xErrHigh.append(xerrhigh) yErrLow.append(yerrlowtemp) yErrHigh.append(yerrhightemp) c = TCanvas("cv", "cv", 800, 800) c.SetLeftMargin(0.12) #must convert list into array for TGraphAsymmErrors to work xArr = array.array('f', x) yArr = array.array('f', y) xErrLowArr = array.array('f', xErrLow) xErrHighArr = array.array('f', xErrHigh) yErrLowArr = array.array('f', yErrLow) yErrHighArr = array.array('f', yErrHigh) effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr, yErrLowArr, yErrHighArr) effGraph.Draw("APE") effGraph.SetTitle("") effGraph.GetXaxis().SetTitle(xAxisTitle) effGraph.GetXaxis().SetTitleSize(0.05) effGraph.GetXaxis().SetTitleOffset(0.90) effGraph.GetXaxis().SetLabelSize(0.03) effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh) effGraph.GetYaxis().SetTitle("Efficiency") effGraph.GetYaxis().SetTitleSize(0.05) effGraph.GetYaxis().SetTitleOffset(1.05) effGraph.GetYaxis().SetLabelSize(0.03) title = TLatex() title.SetTextSize(0.05) title.DrawLatexNDC(.2, .93, topTitle) c.Update() c.SaveAs(plotname + ".gif")
gCorrYieldPHSD.SetTitle(';#it{p}_{T} (GeV/#it{c}); d#it{N}/d#it{p}_{T}') gCorrYieldGossiaux.SetTitle(';#it{p}_{T} (GeV/#it{c}); d#it{N}/d#it{p}_{T}') gCorrYieldCatania.SetTitle(';#it{p}_{T} (GeV/#it{c}); d#it{N}/d#it{p}_{T}') gRawYieldTAMU.SetTitle(';#it{p}_{T} (GeV/#it{c}); raw yield') gRawYieldPHSD.SetTitle(';#it{p}_{T} (GeV/#it{c}); raw yield') gRawYieldGossiaux.SetTitle(';#it{p}_{T} (GeV/#it{c}); raw yield') gRawYieldCatania.SetTitle(';#it{p}_{T} (GeV/#it{c}); raw yield') hBackground = TH1F('hBackground', ';#it{p}_{T} (GeV/#it{c});B(3#sigma)', len(cutVars['Pt']['limits']) - 1, array.array('f', cutVars['Pt']['limits'])) SetGraphStyle(hBackground, kBlack, kWhite, kFullSquare) gFprompt = TGraphAsymmErrors(0) gFprompt.SetTitle(';#it{p}_{T} (GeV/#it{c});#it{f}_{prompt} (#it{f}_{c})') SetGraphStyle(gFprompt, kBlack, kWhite, kFullSquare) hAccEffPrompt = TH1F( 'hAccEffPrompt', ';#it{p}_{T} (GeV/#it{c});(Acc #times #epsilon) #times 2#it{y}_{fid}', len(cutVars['Pt']['limits']) - 1, array.array('f', cutVars['Pt']['limits'])) hAccEffFD = TH1F( 'hAccEffFD', ';#it{p}_{T} (GeV/#it{c});(Acc #times #epsilon) #times 2#it{y}_{fid}', len(cutVars['Pt']['limits']) - 1, array.array('f', cutVars['Pt']['limits'])) SetGraphStyle(hAccEffPrompt, kRed + 1, kWhite, kFullSquare) SetGraphStyle(hAccEffFD, kBlue + 1, kWhite, kFullCircle)
def Plot1DEfficiencyWithBkgSubtraction(tree, num, den, axis, pixel, plotname, topTitle, xAxisTitle, xAxisRangeLow, xAxisRangeHigh): #make amp histogram c = TCanvas("c", "c", 800, 800) #Each pixel has slightly different time distribution and efficiency of time window cut differs a bit #We derive corresponding efficiency corrections for each pixel timeWindowCutEfficiency = 1.0 if (pixel == "5_3"): timeWindowCutEfficiency = 0.989 if (pixel == "5_4"): timeWindowCutEfficiency = 0.9478 if (pixel == "5_10"): timeWindowCutEfficiency = 0.9643 #ampHist = TH1F("ampHist",";Amplitude [mV]; Number of Events", 25,0,50) #tree.Draw("amp[3]>>ampHist"," x_dut[2] > 19.6 && x_dut[2] < 19.7 && y_dut[2] > 23.5 && y_dut[2] < 24.0 && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16)") nbins = num.GetXaxis().GetNbins() x = list() y = list() xErrLow = list() xErrHigh = list() yErrLow = list() yErrHigh = list() for b in range(1, nbins): xtemp = num.GetXaxis().GetBinCenter(b + 1) xerrlow = num.GetXaxis().GetBinCenter( b + 1) - num.GetXaxis().GetBinLowEdge(b + 1) xerrhigh = num.GetXaxis().GetBinUpEdge( b + 1) - num.GetXaxis().GetBinCenter(b + 1) #Noise templates: #Pixel 5,3 : amp <= 6mV gives 0.4417 of the total and has 0 signal contamination #Pixel 5,4 : amp <= 10mV gives 0.0404 of the total and has 0 signal contamination #Pixel 5,10 : amp < gives 0. of the total and has 0 signal contamination #We will assume that bins 0+1+2 (0-6mV) do not contain ANY signal. #We count the number of events in those bins and divide by 0.4417 to get #the total number of noise events. We subtract those from the numerator. #Noise template is made from this data (outside of sensor region AND outside of time window): #/eos/uscms/store/user/cmstestbeam/2019_04_April_CMSTiming/KeySightScope/RecoData/TimingDAQRECO/RecoWithTracks/v6_CACTUSSkim/Completed/Data_CACTUSAnalog_Pixel5_3_16216-16263.root #pulse->Draw("amp[3]>>ampHist(25,0,50)","!(x_dut[2] > 19.4 && x_dut[2] < 20.6 && y_dut[2] > 23.4 && y_dut[2] < 24.1) && !((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16)") noiseSelection = "" noiseSelectionCRFraction = 1 xPositionSelection = "" yPositionSelection = "" if (pixel == "5_3"): noiseSelection = " && amp[3] <= 6" noiseSelectionCRFraction = 0.4417 xPositionSelection = " && x_dut[2] > 19.5 && x_dut[2] < 20.5 " yPositionSelection = " && y_dut[2] > 23.5 && y_dut[2] < 24.0 " if (pixel == "5_4"): noiseSelection = " && amp[3] <= 14" noiseSelectionCRFraction = 0.4053 xPositionSelection = " && x_dut[2] > 18.5 && x_dut[2] < 19.5 " yPositionSelection = " && y_dut[2] > 23.5 && y_dut[2] < 24.0 " if (pixel == "5_10"): noiseSelection = " && amp[3] <= 13" noiseSelectionCRFraction = 0.3802 xPositionSelection = " && x_dut[2] > 19.5 && x_dut[2] < 20.5 " yPositionSelection = " && y_dut[2] > 23.0 && y_dut[2] < 23.5 " print "noise selection = " + noiseSelection + " " + str( noiseSelectionCRFraction) positionSelectionString = "" if (axis == "x"): positionSelectionString = " && x_dut[2] > " + str( num.GetXaxis().GetBinLowEdge(b + 1)) + " && x_dut[2] < " + str( num.GetXaxis().GetBinUpEdge(b + 1)) + yPositionSelection if (axis == "y"): positionSelectionString = xPositionSelection + " && y_dut[2] > " + str( num.GetXaxis().GetBinLowEdge(b + 1)) + " && y_dut[2] < " + str( num.GetXaxis().GetBinUpEdge(b + 1)) + " " print "numerator: " + "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16)" ampHist = TH1F("ampHist" + "_" + str(b), ";Amplitude [mV]; Number of Events", 25, 0, 50) denominatorCount = tree.GetEntries( "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " ") tmpNumeratorTotalCount = tree.GetEntries( "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16)" ) tmpNumeratorNoiseControlRegionCount = tree.GetEntries( "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16) " + noiseSelection) tmpNumeratorSignalCount = tmpNumeratorTotalCount - tmpNumeratorNoiseControlRegionCount / noiseSelectionCRFraction print "ntracks==1 && y_dut[0] > 0 && npix>0 && nback>0 " + positionSelectionString + " && ((t_peak[3] - t_peak[0])*1e9 > 6 && (t_peak[3] - t_peak[0])*1e9 < 16) " + noiseSelection ratio = 0 errLow = 0 errHigh = 0 n1 = int(tmpNumeratorSignalCount) n2 = int(denominatorCount) print "numerator: " + str(n1) + " and denominator: " + str(n2) if (n1 > n2): n1 = n2 if (n2 > 0): ratio = float(n1) / float(n2) if (ratio > 1): ratio = 1 errLow = ratio - TEfficiency.ClopperPearson( n2, n1, 0.68269, False) errHigh = TEfficiency.ClopperPearson(n2, n1, 0.68269, True) - ratio print " done bin " + str(b) + " : " + str( num.GetXaxis().GetBinLowEdge(b + 1)) + " - " + str( num.GetXaxis().GetBinUpEdge(b + 1)) print " num = " + str(n1) + " = " + str( tmpNumeratorTotalCount) + " - " + str( tmpNumeratorNoiseControlRegionCount) + " / " + str( noiseSelectionCRFraction) + " | den = " + str(n2) print "ratio = " + str(ratio) + " " + str(errLow) + " " + str(errHigh) ytemp = ratio / timeWindowCutEfficiency #here we correct for the time window cut inefficiency yerrlowtemp = errLow yerrhightemp = errHigh print "x: " + str(xtemp) + " and y: " + str(ytemp) x.append(xtemp) y.append(ytemp) xErrLow.append(xerrlow) xErrHigh.append(xerrhigh) yErrLow.append(yerrlowtemp) yErrHigh.append(yerrhightemp) c = TCanvas("cv", "cv", 800, 800) c.SetLeftMargin(0.12) #must convert list into array for TGraphAsymmErrors to work xArr = array.array('f', x) yArr = array.array('f', y) xErrLowArr = array.array('f', xErrLow) xErrHighArr = array.array('f', xErrHigh) yErrLowArr = array.array('f', yErrLow) yErrHighArr = array.array('f', yErrHigh) effGraph = TGraphAsymmErrors(nbins, xArr, yArr, xErrLowArr, xErrHighArr, yErrLowArr, yErrHighArr) effGraph.Draw("APE") effGraph.SetTitle("") effGraph.GetXaxis().SetTitle(xAxisTitle) effGraph.GetXaxis().SetTitleSize(0.05) effGraph.GetXaxis().SetTitleOffset(0.90) effGraph.GetXaxis().SetLabelSize(0.03) effGraph.GetXaxis().SetRangeUser(xAxisRangeLow, xAxisRangeHigh) effGraph.GetYaxis().SetTitle("Efficiency") effGraph.GetYaxis().SetTitleSize(0.05) effGraph.GetYaxis().SetTitleOffset(1.05) effGraph.GetYaxis().SetLabelSize(0.03) title = TLatex() title.SetTextSize(0.05) title.DrawLatexNDC(.2, .93, topTitle) c.Update() c.SaveAs(plotname + ".gif")
def ratioplot(): # create required parts leg = getLegend() latex = getLatex() c = SetCanvas() #c.SetLogy() #c = TCanvas() #c.SetLogy() h1 = f.Get('h_num_calo_') #'calo',pf h1 = setHistStyle(h1, bins) h2 = f.Get('h_den_calo_') h2 = setHistStyle(h2, bins) h11 = f2.Get('h_num_calo_') h11 = setHistStyle(h11, bins) h21 = f2.Get('h_den_calo_') h21 = setHistStyle(h21, bins) gr = TGraphAsymmErrors(30) #gr.Divide(h1,h2) gr = TGraphAsymmErrors(h1, h2) gr2 = TGraphAsymmErrors(h11, h21) gr2.SetMarkerStyle(20) gr2.GetXaxis().SetRangeUser(0, 1000) gr2.SetMarkerSize(1.5) gr2.SetLineColor(2) gr2.SetLineWidth(1) gr2.SetMarkerColor(2) gr.GetXaxis().SetRangeUser(0, 1000) # gr.GetYaxis().SetRangeUser(0.0001,1.2) gr.SetMarkerStyle(20) gr.SetMarkerSize(1.5) gr.SetLineColor(1) gr.SetLineWidth(1) gr.SetMarkerColor(1) gr.GetYaxis().SetTitle("Trigger Efficiency") gr.GetXaxis().SetTitle("MET [GeV]") gr.SetTitle("") #base histogram histogram_base = TH1F("histogram_base", "", 1000, 0, 1000.) histogram_base.SetTitle("") histogram_base.SetStats(0) histogram_base.SetMarkerSize(2) #histogram_base.SetMinimum(0.0) histogram_base.SetMaximum(1.2) histogram_base.GetXaxis().SetTitle("Online E_{T}^{miss} (GeV)") histogram_base.GetYaxis().SetTitle("Efficiency") histogram_base = setHistStyle(histogram_base, bins) histogram_base.Draw("HIST") # c.SaveAs() gr.Draw('P same') gr2.Draw('P same') latex.DrawLatex(0.49, 0.93, " EGamma Run2018C, 13 TeV") xmin = 0.0 line = TLine(max(xmin, gr.GetXaxis().GetXmin()), 1, 1000, 1) line.SetLineColor(1) line.SetLineWidth(1) line.SetLineStyle(7) line.Draw() leg.AddEntry(gr, 'With HBHENoise filter', 'P') leg.AddEntry(gr2, 'Without HBHENoise filter', 'P') leg.Draw() txt = 'Path: HLT_PFMETTypeOne200_HBHE_BeamHaloCleaned' texcms = AddText(txt) texcms.Draw("same") c.SaveAs('testTurnOn_EGamma.png')
#h_efficiency = h_before_selection #h_efficiency.Divide(h_before_selection,h_after_selection,1.0,1.0,"B") h_efficiency.Draw() time.sleep(11) """ g_efficiency = GAE() g_efficiency.Divide(h_after_selection_cum, h_before_selection, "cl=0.683 b(1,1) mode") #from tools import DrawErrorBand #DrawErrorBand(g_efficiency) #""" g_efficiency.SetTitle('efficiency') g_efficiency.SetFillColor(5) g_efficiency.SetMarkerStyle(21) g_efficiency.SetMarkerColor(4) #g_efficiency.Draw('ALP') #g_efficiency.Draw('3A') #""" time.sleep(111)