def getGraph(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)) result = TMultiGraph() legendPosition = [ float(i) for i in self.__getStyleOption("legendPosition").split() ] legend = TLegend(*legendPosition) legend.SetFillColor(0) result.SetTitle("%s;%s;%s" % (self.__title, self.__xTitle, self.__yTitle)) #(refArrays, refLabel) = self.__getRefernceGraphArrays() #refGraph = TGraphAsymmErrors(*refArrays) #refGraph.SetLineWidth(2) #refGraph.SetLineColor(int(self.__config.get("reference","lineColor"))) #refGraph.SetFillColor(int(self.__config.get("reference","fillColor"))) #result.Add(refGraph,"L3") #legend.AddEntry(refGraph,self.__config.get("reference","name")) 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.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"))) sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow, self.__ySysErrHigh) sysGraph.SetLineWidth(1) sysGraph.SetFillColor(0) sysGraph.SetLineColor(int(self.__getStyleOption("lineColor"))) sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor"))) sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle"))) sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize"))) result.Add(sysGraph, "[]") result.Add(graph, "P") # result.SetName("MultiPlots") # result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle)) result.SetName("MG_%s" % (self.__title)) legend.AddEntry(graph, self.__getStyleOption("name")) #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)): # self.__addAnnotaion("hallo",x,y,yErr) return (result, legend)
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [3. * nchannels - 1.5 - 3. * i for i in range(0, nchannels)]) ey = np.array([0.8 for i in range(0, nchannels)]) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend x1 = gStyle.GetPadLeftMargin() + 0.01 y2 = 1 - gStyle.GetPadTopMargin() - 0.01 leg = TLegend(x1, y2 - 0.17, x1 + 0.25, y2) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") leg.AddEntry(gobs, "Observed", "pl") leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def draw_limits_per_category(nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig): channel = np.array( [nchannels - 1.5 - float(i) for i in range(0, nchannels)]) ey = np.full(nchannels, 0.494) zero = np.zeros(nchannels) gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig, upper1sig, ey, ey) gexpect1sig.SetFillColor(kGreen) gexpect1sig.SetLineWidth(2) gexpect1sig.SetLineStyle(2) gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig, upper2sig, ey, ey) gexpect2sig.SetFillColor(kYellow) gexpect2sig.SetLineWidth(2) gexpect2sig.SetLineStyle(2) gexpect2sig.Draw("2") gexpect1sig.Draw("2") gobs = TGraphErrors(nchannels, obs, channel, zero, ey) gobs.SetMarkerStyle(21) gobs.SetMarkerSize(1.5) gobs.SetLineWidth(2) #gobs.Draw("pz") # dashed line at median expected limits l = TLine() l.SetLineStyle(2) l.SetLineWidth(2) for bin in range(nchannels): l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin], channel[bin] + ey[bin]) # line to separate individual and combined limits l.SetLineStyle(1) l.SetLineWidth(1) l.DrawLine(xmin, 0, xmax, 0) # legend leg = TLegend(0.75, 0.75, 0.95, 0.9) leg.SetFillColor(4000) leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL") leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL") #leg.AddEntry( gobs, "Observed", "pl" ) leg.Draw() return gobs, gexpect1sig, gexpect2sig, leg
def makeResidHist(data, bkg): pulls = TGraphAsymmErrors(data.GetN()) pulls.SetName("Pulls") pulls.SetLineWidth(data.GetLineWidth()) pulls.SetLineStyle(data.GetLineStyle()) pulls.SetLineColor(data.GetLineColor()) pulls.SetMarkerSize(data.GetMarkerSize()) pulls.SetMarkerStyle(data.GetMarkerStyle()) pulls.SetMarkerColor(data.GetMarkerColor()) pulls.SetFillStyle(data.GetFillStyle()) pulls.SetFillColor(data.GetFillColor()) # Add histograms, calculate Poisson confidence interval on sum value for i in range(data.GetN()): x = data.GetX()[i] dyl = data.GetErrorYlow(i) dyh = data.GetErrorYhigh(i) yy = data.GetY()[i] - bkg.Interpolate(x) #bkg.GetBinContent(i+1) norm = dyl if yy > 0. else dyh if norm == 0.: yy, dyh, dyl = 0., 0., 0. else: yy /= norm dyh /= norm dyl /= norm pulls.SetPoint(i, x, yy) pulls.SetPointEYhigh(i, dyh) pulls.SetPointEYlow(i, dyl) return pulls
def convertHistToGraph(hist, useGarwood=False): alpha = 1 - 0.6827 graph = TGraphAsymmErrors(hist.GetNbinsX()) if useGarwood: lastEvent = False for i in reversed(range(hist.GetNbinsX())): N = hist.GetBinContent(i + 1) if not lastEvent and N > 0: lastEvent = True if lastEvent and N <= 0.: N = 1.e-6 L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) graph.SetPoint(i, hist.GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) graph.SetPointError(i, 0., 0., N - L, U - N) else: for i in range(hist.GetNbinsX()): graph.SetPoint(i, hist.GetXaxis().GetBinCenter(i + 1), hist.GetBinContent(i + 1)) graph.SetPointError(i, hist.GetXaxis().GetBinWidth(i + 1) / 2., hist.GetXaxis().GetBinWidth(i + 1) / 2., hist.GetBinError(i + 1), hist.GetBinError(i + 1)) graph.SetLineWidth(hist.GetLineWidth()) graph.SetLineStyle(hist.GetLineStyle()) graph.SetLineColor(hist.GetLineColor()) graph.SetMarkerSize(hist.GetMarkerSize()) graph.SetMarkerStyle(hist.GetMarkerStyle()) graph.SetMarkerColor(hist.GetMarkerColor()) graph.SetFillStyle(hist.GetFillStyle()) graph.SetFillColor(hist.GetFillColor()) return graph
def bestfit(): xmin = -10 xmax = 6 c, h = draw_canvas_histo( xmin, xmax, "Best fit #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV") # line at SM expectation of mu = 1 l = TLine() l.SetLineStyle(2) l.DrawLine(1.0, -1.0, 1.0, -1.0 + nchannels) mu = np.array([-0.4, -4.734, -2.014]) upper = np.array([2.12, 3.688, 1.80]) lower = np.array([2.08, 3.754, 1.8224]) channel = np.array([1.5, 0.5, -0.5]) zero = np.zeros(nchannels) gmu = TGraphAsymmErrors(nchannels, mu, channel, lower, upper, zero, zero) gmu.SetMarkerStyle(21) gmu.SetMarkerSize(1.5) gmu.SetLineColor(2) gmu.SetLineWidth(2) gmu.Draw("pz") #draw_disclaimer() c.RedrawAxis() c.Modified() c.Update() c.SaveAs("bestfit.pdf")
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 convertToPoisson(h): graph = TGraphAsymmErrors() q = (1-0.6827)/2. for i in range(1,h.GetNbinsX()+1): x=h.GetXaxis().GetBinCenter(i) xLow =h.GetXaxis().GetBinLowEdge(i) xHigh =h.GetXaxis().GetBinUpEdge(i) y=h.GetBinContent(i) yLow=0 yHigh=0 if y !=0.0: yLow = y-Math.chisquared_quantile_c(1-q,2*y)/2. yHigh = Math.chisquared_quantile_c(q,2*(y+1))/2.-y graph.SetPoint(i-1,x,y) graph.SetPointEYlow(i-1,yLow) graph.SetPointEYhigh(i-1,yHigh) graph.SetPointEXlow(i-1,0.0) graph.SetPointEXhigh(i-1,0.0) graph.SetMarkerStyle(20) graph.SetLineWidth(2) graph.SetMarkerSize(1.) graph.SetMarkerColor(kBlack) return graph
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 HistToAsymmErrs(name,hist) : X = [] EXlow = [] EXhigh = [] Y = [] EYlow = [] EYhigh = [] for i in range(hist.GetNbinsX()) : X .append(hist.GetBinCenter (i+1)) EXlow .append(hist.GetBinWidth (i+1)/2.) EXhigh.append(hist.GetBinWidth (i+1)/2.) Y .append(hist.GetBinContent(i+1)) EYlow .append(hist.GetBinError (i+1)) EYhigh.append(hist.GetBinError (i+1)) a_X = array('d',X ) a_EXlow = array('d',EXlow ) a_EXhigh = array('d',EXhigh ) a_Y = array('d',Y ) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) asymm = TGraphAsymmErrors(len(a_X),a_X,a_Y,a_EXlow,a_EXhigh,a_EYlow,a_EYhigh) asymm.GetXaxis().SetTitle(hist.GetXaxis().GetTitle()) asymm.GetYaxis().SetTitle(hist.GetYaxis().GetTitle()) asymm.SetLineWidth(2) asymm.SetName(name) return asymm
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 QuadratureUpDown(asymlist, hists=[], doFlatUnc=False, FlatUp=0.0, FlatDown=0.0): # These are TGraphAsymmErrors total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(asymlist[0].GetN()): total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(asymlist[0].GetN()): for j in range(len(asymlist)): E_up = asymlist[j].GetEYhigh()[i] E_dn = asymlist[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # hists # for i in range(len(total_unc_up_sq)): for j in range(len(hists)): E_up = hists[j].GetBinError(i + 1) E_dn = hists[j].GetBinError(i + 1) total_unc_up_sq[i] += math.pow(E_up, 2) total_unc_dn_sq[i] += math.pow(E_dn, 2) # # flat uncertainty # if doFlatUnc: for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] += math.pow(FlatUp * asymlist[0].GetY()[i], 2) total_unc_dn_sq[i] += math.pow(FlatDown * asymlist[0].GetY()[i], 2) # # sqrt # for i in range(len(total_unc_up_sq)): total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) #print 'Setting up unc to ',total_unc_up_sq[i] #print 'Setting dn unc to ',total_unc_dn_sq[i] #print total_unc_up_sq #print total_unc_dn_sq yup = array('d', total_unc_up_sq) ydn = array('d', total_unc_dn_sq) #print yup #print ydn result = TGraphAsymmErrors(asymlist[0].GetN(), asymlist[0].GetX(), asymlist[0].GetY(), asymlist[0].GetEXlow(), asymlist[0].GetEXhigh(), ydn, yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(asymlist[0].GetName() + ' Total Error') return result
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 envelope(thedict, thelist, nominal): # # Takes the nominal and makes an envelope around it # diff_up = nominal.Clone() key = 'diff_up' diff_up.SetNameTitle(key, key) diff_dn = nominal.Clone() key = 'diff_dn' diff_dn.SetNameTitle(key, key) for i in range(diff_up.GetNbinsX()): diff_up.SetBinContent(i + 1, 0) diff_dn.SetBinContent(i + 1, 0) # for var in thelist: if var == 'dummy': continue for i in range(nominal.GetNbinsX()): curr_diff_up = diff_up.GetBinContent(i + 1) curr_diff_dn = diff_dn.GetBinContent(i + 1) nominal_bc = nominal.GetBinContent(i + 1) thisvar_bc = thedict[var].GetBinContent(i + 1) diff_up.SetBinContent(i + 1, max(curr_diff_up, thisvar_bc - nominal_bc)) diff_dn.SetBinContent(i + 1, min(curr_diff_dn, thisvar_bc - nominal_bc)) nbins = nominal.GetNbinsX() x = array( 'd', list(nominal.GetBinCenter(a + 1) for a in range(nominal.GetNbinsX()))) xup = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) xdn = array( 'd', list( nominal.GetBinWidth(a + 1) / 2. for a in range(nominal.GetNbinsX()))) y = array( 'd', list(nominal.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) yup = array( 'd', list(diff_up.GetBinContent(a + 1) for a in range(nominal.GetNbinsX()))) ydn = array( 'd', list( diff_dn.GetBinContent(a + 1) * -1. for a in range(nominal.GetNbinsX()))) result = TGraphAsymmErrors(nbins, x, y, xdn, xup, ydn, yup) result.GetXaxis().SetTitle(nominal.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nominal.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(nominal.GetName() + ' Envelope') return result
def makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20): binning = [20, 30, 40, 50, 60, 70, 80, 100, 150, 200] c = TCanvas() if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) elif option == 'nvtx': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(vbinning) - 1, array('d', vbinning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(vbinning) - 1, array('d', vbinning)) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.BayesDivide(_ahist_, _hist_) g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return copy.deepcopy(g_efficiency)
def QuadratureUpDown(name,asymlist=[],hists=[],AddHists=False) : # These are TGraphAsymmErrors asymlist1 = [] for i in asymlist : asymlist1.append(i) for i in range(len(hists)) : asymlist1.append(HistToAsymmErrs(hists[i].GetName()+' QuadratureUpDown Asymm',hists[i])) nbins = asymlist1[0].GetN() total_unc_up_sq = [] total_unc_dn_sq = [] for i in range(nbins) : total_unc_up_sq.append(0) total_unc_dn_sq.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist1)) : E_up = asymlist1[j].GetEYhigh()[i] E_dn = asymlist1[j].GetEYlow()[i] total_unc_up_sq[i] += math.pow(E_up,2) total_unc_dn_sq[i] += math.pow(E_dn,2) # # # # hists # # # for i in range(nbins) : # for j in range(len(hists)) : # E_up = hists[j].GetBinError(i+1) # E_dn = hists[j].GetBinError(i+1) # total_unc_up_sq[i] += math.pow(E_up,2) # total_unc_dn_sq[i] += math.pow(E_dn,2) # # sqrt # for i in range(nbins) : total_unc_up_sq[i] = math.sqrt(total_unc_up_sq[i]) total_unc_dn_sq[i] = math.sqrt(total_unc_dn_sq[i]) y = [] for i in range(nbins) : y.append(asymlist1[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist1)) : y[-1] += asymlist1[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up_sq) ydn = array('d',total_unc_dn_sq) result = TGraphAsymmErrors(asymlist1[0].GetN(),asymlist1[0].GetX(),ybincontent ,asymlist1[0].GetEXlow(),asymlist1[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist1[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist1[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
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 makeEffPlotsVars(tree, varx, vary, sel, nbinx, xmin, xmax, nbiny, ymin, ymax, xtitle, ytitle, leglabel=None, header='', addon='', option='pt', marker=20, col=1): binning = [20, 200] if args.onebin else [ 20, 30, 40, 50, 60, 70, 80, 100, 150, 200 ] if option == 'pt': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, array('d', binning)) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, array('d', binning)) elif option == 'eta': _hist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, nbinx, xmin, xmax) _ahist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, nbinx, xmin, xmax) tree.Draw(varx + ' >> ' + _hist_.GetName(), sel) tree.Draw(varx + ' >> ' + _ahist_.GetName(), sel + ' && ' + vary) g_efficiency = TGraphAsymmErrors() g_efficiency.Divide(_ahist_, _hist_, "cl=0.683 b(1,1) mode") g_efficiency.GetXaxis().SetTitle(xtitle) g_efficiency.GetYaxis().SetTitle('efficiency') g_efficiency.GetYaxis().SetNdivisions(507) g_efficiency.SetLineWidth(3) g_efficiency.SetName(header) g_efficiency.SetMinimum(0.) g_efficiency.GetYaxis().SetTitleOffset(1.3) g_efficiency.SetMarkerStyle(marker) g_efficiency.SetMarkerSize(1) g_efficiency.SetMarkerColor(col) g_efficiency.SetLineColor(col) g_efficiency.Draw('ap') # save(c, 'plots/' + addon) return g_efficiency
def FlatErrorToAsymmErrs(name,nomhist,up_frac=0.,dn_frac=0.) : nom_2_asymm = HistToAsymmErrs(nomhist.GetName()+' FlatErrorToAsymmErrs Asymm',nomhist) EYlow = [] EYhigh = [] for i in range(nom_2_asymm.GetN()) : EYlow.append(nom_2_asymm.GetY()[i]*dn_frac) EYhigh.append(nom_2_asymm.GetY()[i]*up_frac) a_EYlow = array('d',EYlow ) a_EYhigh = array('d',EYhigh ) result = TGraphAsymmErrors(nom_2_asymm.GetN(),nom_2_asymm.GetX(),nom_2_asymm.GetY() ,nom_2_asymm.GetEXlow(),nom_2_asymm.GetEXhigh() ,a_EYlow,a_EYhigh) result.GetXaxis().SetTitle(nom_2_asymm.GetXaxis().GetTitle()) result.GetYaxis().SetTitle(nom_2_asymm.GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result
def convertHistToGraph(hist): graph = TGraphAsymmErrors(hist.GetNbinsX()) for i in range(hist.GetNbinsX()): graph.SetPoint(i, hist.GetXaxis().GetBinCenter(i), hist.GetBinContent(i)) graph.SetPointError(i, hist.GetXaxis().GetBinWidth(i) / 2., hist.GetXaxis().GetBinWidth(i) / 2., hist.GetBinError(i), hist.GetBinError(i)) graph.SetLineWidth(hist.GetLineWidth()) graph.SetLineStyle(hist.GetLineStyle()) graph.SetLineColor(hist.GetLineColor()) graph.SetMarkerSize(hist.GetMarkerSize()) graph.SetMarkerStyle(hist.GetMarkerStyle()) graph.SetMarkerColor(hist.GetMarkerColor()) graph.SetFillStyle(hist.GetFillStyle()) graph.SetFillColor(hist.GetFillColor()) return graph
def LinearUpDown(name,asymlist=[],hists=[],AddHists=False) : for i in range(len(hists)) : asymlist.append(HistToAsymmErrs(hists[i].GetName()+' LinearUpDown Asymm',hists[i])) nbins = asymlist[0].GetN() total_unc_up = [] total_unc_dn = [] for i in range(nbins) : total_unc_up.append(0) total_unc_dn.append(0) # # asym err hists # for i in range(nbins) : for j in range(len(asymlist)) : total_unc_up[i] += asymlist[j].GetEYhigh()[i] total_unc_dn[i] += asymlist[j].GetEYlow()[i] y = [] for i in range(nbins) : y.append(asymlist[0].GetY()[i]) if AddHists : for j in range(1,len(asymlist)) : y[-1] += asymlist[j].GetY()[i] ybincontent = array('d',y) yup = array('d',total_unc_up) ydn = array('d',total_unc_dn) result = TGraphAsymmErrors(asymlist[0].GetN(),asymlist[0].GetX(),ybincontent ,asymlist[0].GetEXlow(),asymlist[0].GetEXhigh() ,ydn,yup) result.GetXaxis().SetTitle(asymlist[0].GetXaxis().GetTitle()) result.GetYaxis().SetTitle(asymlist[0].GetYaxis().GetTitle()) result.SetLineWidth(2) result.SetName(name) return result return
def histToGraph(hist, name='', keepErrors=True, poissonErrors=True): ## Helper method to convert a histogram to a corresponding graph # @hist TH1 object # @name name of the graph (default is name of histogram) # @keepErrors decide if the y-errors should be propagated to the graph # @poissonErrors decide if the y-errors should be calculated as Poisson errors # @return graph if not name: name = 'g%s' % (hist.GetName()) from ROOT import TGraphAsymmErrors nBins = hist.GetNbinsX() graph = TGraphAsymmErrors(nBins) graph.SetNameTitle(name, hist.GetTitle()) xAxis = hist.GetXaxis() for i in xrange(nBins): xVal = xAxis.GetBinCenter(i + 1) yVal = hist.GetBinContent(i + 1) graph.SetPoint(i, xVal, yVal) graph.SetPointEXlow(i, abs(xVal - xAxis.GetBinLowEdge(i + 1))) graph.SetPointEXhigh(i, abs(xVal - xAxis.GetBinUpEdge(i + 1))) if keepErrors: if poissonErrors: lo, hi = calculatePoissonErrors(yVal) graph.SetPointEYlow(i, lo) graph.SetPointEYhigh(i, hi) else: graph.SetPointEYlow(i, hist.GetBinErrorLow(i + 1)) graph.SetPointEYhigh(i, hist.GetBinErrorUp(i + 1)) # copy the style graph.SetMarkerStyle(hist.GetMarkerStyle()) graph.SetMarkerColor(hist.GetMarkerColor()) graph.SetMarkerSize(hist.GetMarkerSize()) graph.SetLineStyle(hist.GetLineStyle()) graph.SetLineColor(hist.GetLineColor()) graph.SetLineWidth(hist.GetLineWidth()) graph.SetFillColor(hist.GetFillColor()) graph.SetFillStyle(hist.GetFillStyle()) return graph
def makeEffPlotsVars(tree, varx, numeratorAddSelection, baseSelection, binning, xtitle='', header='', addon='', marker=20, col=1): _denomHist_ = TH1F('h_effp_' + addon, 'h_effp' + addon, len(binning) - 1, binning) _nominatorHist_ = TH1F('ah_effp_' + addon, 'ah_effp' + addon, len(binning) - 1, binning) tree.Draw(varx + ' >> ' + _denomHist_.GetName(), baseSelection) tree.Draw(varx + ' >> ' + _nominatorHist_.GetName(), baseSelection + ' && ' + numeratorAddSelection) g_eff = TGraphAsymmErrors() g_eff.Divide(_nominatorHist_, _denomHist_, "cl=0.683 b(1,1) mode") g_eff.GetXaxis().SetTitle(xtitle) g_eff.GetYaxis().SetTitle('efficiency') g_eff.GetYaxis().SetNdivisions(507) g_eff.SetLineWidth(3) g_eff.SetName(header) g_eff.SetMinimum(0.) g_eff.GetYaxis().SetTitleOffset(1.3) g_eff.SetMarkerStyle(marker) g_eff.SetMarkerSize(1) g_eff.SetMarkerColor(col) g_eff.SetLineColor(col) g_eff.Draw('ap') return g_eff
def pullsVertical(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off) s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off) # for i, s in enumerate(content): l = s.split() b_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) s_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) b_pulls.SetBinContent(i + 1, float(l[1])) b_pulls.SetBinError(i + 1, float(l[2])) s_pulls.SetBinContent(i + 1, float(l[3])) s_pulls.SetBinError(i + 1, float(l[4])) b_pulls.SetFillStyle(3005) b_pulls.SetFillColor(923) b_pulls.SetLineColor(923) b_pulls.SetLineWidth(1) b_pulls.SetMarkerStyle(20) b_pulls.SetMarkerSize(1.25) s_pulls.SetLineColor(602) s_pulls.SetMarkerColor(602) s_pulls.SetMarkerStyle(24) #24 s_pulls.SetLineWidth(1) b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5) # Graphs h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins) B_pulls = TGraphAsymmErrors(nbins) S_pulls = TGraphAsymmErrors(nbins) boxes = [] canvas = TCanvas("canvas", "Pulls", 600, 150 + nbins * 10) #nbins*20) canvas.cd() canvas.SetGrid(0, 1) canvas.GetPad(0).SetTopMargin(0.01) canvas.GetPad(0).SetRightMargin(0.01) canvas.GetPad(0).SetBottomMargin(0.05) canvas.GetPad(0).SetLeftMargin(0.25) #(0.25)#(0.065) canvas.GetPad(0).SetTicks(1, 1) for i, s in enumerate(content): l = s.split() if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV" h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', '')) #C #y1 = gStyle.GetPadBottomMargin() #y2 = 1. - gStyle.GetPadTopMargin() #h = (y2 - y1) / float(nbins) #y1 = y1 + float(i) * h #y2 = y1 + h #box = TPaveText(0, y1, 1, y2, 'NDC') #box.SetFillColor(0) #box.SetTextSize(0.02) #box.SetBorderSize(0) #box.SetTextAlign(12) #box.SetMargin(0.005) #if i % 2 == 0: # box.SetFillColor(18) #box.Draw() #boxes.append(box) B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3) #C B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.) #C for i, s in enumerate(content): l = s.split() S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7) #C S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.) #C h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta") h_pulls.GetXaxis().SetLabelOffset(-0.01) h_pulls.GetXaxis().SetTitleOffset(.6) h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0) B_pulls.SetFillColor(1) B_pulls.SetLineColor(1) B_pulls.SetLineStyle(1) B_pulls.SetLineWidth(2) B_pulls.SetMarkerColor(1) B_pulls.SetMarkerStyle(20) B_pulls.SetMarkerSize(1) #(0.75) S_pulls.SetFillColor(629) S_pulls.SetLineColor(629) S_pulls.SetMarkerColor(629) S_pulls.SetLineWidth(2) S_pulls.SetMarkerStyle(20) S_pulls.SetMarkerSize(1) box1 = TBox(-1., 0., 1., nbins) box1.SetFillStyle(3001) #box1.SetFillStyle(0) box1.SetFillColor(417) box1.SetLineWidth(2) box1.SetLineStyle(2) box1.SetLineColor(417) box2 = TBox(-2., 0., 2., nbins) box2.SetFillStyle(3001) #box2.SetFillStyle(0) box2.SetFillColor(800) box2.SetLineWidth(2) box2.SetLineStyle(2) box2.SetLineColor(800) leg = TLegend(0.1, -0.05, 0.7, 0.08) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(B_pulls, "B-only fit", "lp") leg.AddEntry(S_pulls, "S+B fit", "lp") if text: leg.AddEntry(0, text, "") h_pulls.Draw("") box2.Draw() box1.Draw() B_pulls.Draw("P6SAME") S_pulls.Draw("P6SAME") leg.Draw() # drawCMS(35867, "Preliminary") # drawAnalysis("VH") # drawRegion(outName) canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def pullsVertical_noBonly(fileName): content = filterPullFile(fileName) nbins, off = len(content), 0.10 # Graphs h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins) S_pulls = TGraphAsymmErrors(nbins) boxes = [] canvas = TCanvas("canvas", "Pulls", 720, 300 + nbins * 18) #nbins*20) canvas.cd() canvas.SetGrid(0, 1) canvas.SetTopMargin(0.01) canvas.SetRightMargin(0.01) canvas.SetBottomMargin(0.10) canvas.SetLeftMargin(0.40) canvas.SetTicks(1, 1) for i, s in enumerate(content): l = s.split() h_pulls.GetYaxis().SetBinLabel(i + 1, l[0]) S_pulls.SetPoint(i, float(l[3]), float(i + 1) - 0.5) S_pulls.SetPointError(i, float(l[4]), float(l[4]), 0., 0.) h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta") h_pulls.GetXaxis().SetLabelOffset(0.0) h_pulls.GetXaxis().SetTitleOffset(0.8) h_pulls.GetXaxis().SetLabelSize(0.045) h_pulls.GetXaxis().SetTitleSize(0.050) h_pulls.GetYaxis().SetLabelSize(0.046) h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0) S_pulls.SetFillColor(kBlack) S_pulls.SetLineColor(kBlack) S_pulls.SetMarkerColor(kBlack) S_pulls.SetLineWidth(2) S_pulls.SetMarkerStyle(20) S_pulls.SetMarkerSize(1) box1 = TBox(-1., 0., 1., nbins) #box1.SetFillStyle(3001) # 3001 checkered #box1.SetFillStyle(0) box1.SetFillColor(kGreen + 1) # 417 box1.SetLineWidth(2) box1.SetLineStyle(2) box1.SetLineColor(kGreen + 1) # 417 box2 = TBox(-2., 0., 2., nbins) #box2.SetFillStyle(3001) # 3001 checkered #box2.SetFillStyle(0) box2.SetFillColor(kOrange) # 800 box2.SetLineWidth(2) box2.SetLineStyle(2) box2.SetLineColor(kOrange) # 800 leg = TLegend(0.01, 0.01, 0.3, 0.15) leg.SetTextSize(0.05) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) #leg.SetNColumns(2) leg.AddEntry(S_pulls, "S+B fit", "lp") if text: leg.AddEntry(0, text, "") h_pulls.Draw("") box2.Draw() box1.Draw() S_pulls.Draw("P6SAME") leg.Draw() canvas.RedrawAxis() canvas.Print(outName + ".png") canvas.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def getGraph(self,dset): 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)) result = TMultiGraph() legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()] legend = TLegend(*legendPosition) legend.SetFillColor(0) result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle)) #(refArrays, refLabel) = self.__getRefernceGraphArrays() #refGraph = TGraphAsymmErrors(*refArrays) #refGraph.SetLineWidth(2) #refGraph.SetLineColor(int(self.__config.get("reference","lineColor"))) #refGraph.SetFillColor(int(self.__config.get("reference","fillColor"))) #result.Add(refGraph,"L3") #legend.AddEntry(refGraph,self.__config.get("reference","name")) xErr = array("d",[0 for i in range(n)]) print "__x = ", self.__x print "__y = ", self.__y lst = [] for inc in range (0,n): d={} d['run']=self.__runs[inc] d['x']=self.__x[inc] d['y']=self.__y[inc] d['yErr']=self.__yErrLow[inc] d['yTitle']=self.__yTitle if self.__config.has_option(self.__section,"yMin") and self.__config.has_option(self.__section,"yMax") : d['ymin']=float(self.__config.get(self.__section,"yMin")) d['ymax']=float(self.__config.get(self.__section,"yMax")) else: d['ymin']=0 d['ymax']=0 lst.append(d) obj ={} obj[self.__title]=lst #finalObj[self.__title]=lst #finalList.append(finalObj) # save_path = './JSON_A/' #completeName = os.path.join(save_path, self.__title+".json") if not os.path.exists("JSON_RECO"): os.makedirs("JSON_RECO") if not os.path.exists("JSON_RECO/"+dset): os.makedirs("JSON_RECO/"+dset) with open("./JSON_RECO/"+dset+"/"+self.__title+".json", 'w') as outfile: json.dump(obj, outfile,indent=4) print json.dumps(obj,indent=2) graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh) 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"))) sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow,self.__ySysErrHigh) sysGraph.SetLineWidth(1) sysGraph.SetFillColor(0) sysGraph.SetLineColor(int(self.__getStyleOption("lineColor"))) sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor"))) sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle"))) sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize"))) #TOMAS removed sys error from the plot #result.Add(sysGraph,"[]") result.Add(graph,"P") # result.SetName("MultiPlots") # result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle)) result.SetName("MG_%s"%(self.__title)) legend.AddEntry(graph, self.__getStyleOption("name")) #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)): # self.__addAnnotaion("hallo",x,y,yErr) return (result, legend)
def significanceSB(cutlist, labellist): basecut = labellist[0] dim = len(cutlist) significance = [0] * (dim + 1) file = {} tree = {} effs = {} hist = {} GrAsym = {} yErrorUp = {} yErrorDown = {} totEve = 0 GrAsym = TGraphAsymmErrors() cuts = "" for j, c in enumerate(cutlist): s = 0. b = 0. cuts += cutlist[0] if j == 0 else " && " + cutlist[j] print "cuts = ", cuts for num1, v in enumerate(signals): #print "Signal = ", v for num2, filename in enumerate(samples[v]['files']): #print "Signal rootfile read = ", filename file[filename] = TFile(NTUPLESIG + filename + ".root", "READ") # Read TFile tree[filename] = file[filename].Get("Events") # Read TTree nevents = float(sample[filename]['nevents']) xs = float(sample[filename]['xsec']) * float( sample[filename]['kfactor']) LumiMC = nevents / xs Weight = float(LUMI) / float(LumiMC) sig_entries = tree[filename].GetEntries(cuts) #print "s = ", float(sig_entries) * float(Weight) s += float(sig_entries) * float(Weight) print "TOT SIG = ", s for num1, k in enumerate(back): #print "backgrounds = ", k for num2, filename in enumerate(samples[k]['files']): #print "backgrounds rootfile read = ", filename file[filename] = TFile(NTUPLEDIR + filename + ".root", "READ") # Read TFile tree[filename] = file[filename].Get("Events") # Read TTree nevents = float(sample[filename]['nevents']) xs = float(sample[filename]['xsec']) * float( sample[filename]['kfactor']) LumiMC = nevents / xs Weight = float(LUMI) / float(LumiMC) bkg_entries = tree[filename].GetEntries(cuts) #print "b = ", float(bkg_entries) * float(Weight) b += float(bkg_entries) * float(Weight) print "TOT BKG = ", b ##End of cutlist #COMPUTE #print "s = ", s #print "b = ", b #print "sqrt(b) = ", math.sqrt(b) #print "significance = ", float(s/math.sqrt(b)) significance[j] = float(s / math.sqrt(b)) yErrorUp[j] = float( TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, True) - significance[j]) yErrorDown[j] = float( significance[j] - TEfficiency.ClopperPearson(math.sqrt(b), s, 0.68, False)) GrAsym.SetPoint(j, j + 0.5, significance[j]) GrAsym.SetPointError(j, 0, 0, yErrorUp[j], yErrorDown[j]) for k, cs in enumerate(labellist): GrAsym.GetHistogram().GetXaxis().Set(dim, 0, dim) GrAsym.GetHistogram().GetXaxis().SetBinLabel(k + 1, "%s" % labellist[k]) GrAsym.SetLineColor(2) GrAsym.SetLineWidth(3) GrAsym.SetMarkerStyle(8) GrAsym.SetMarkerColor(2) c1 = TCanvas("c1", "Signals Acceptance", 800, 600) c1.cd() c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetTicks(1, 1) gStyle.SetOptStat(0) #GrAsym.SetMaximum(1.3) #GrAsym.SetMinimum(0.) GrAsym.GetHistogram().GetXaxis().SetTitle("") GrAsym.GetHistogram().GetYaxis().SetTitle("Significance (S/#sqrt{B})") GrAsym.Draw("pa") drawCMS(LUMI, "Work In Progress") drawRegion(basecut) if not os.path.exists('plots/Signal/Significance/'): os.system('mkdir -p plots/Signal/Significance/') c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".png") c1.Print("plots/Signal/Significance/Sigf_SB_" + basecut + ".pdf") #if not options.runBash: raw_input("Press Enter to continue...") pass
def limit(): method = '' channel = "bb" particleP = "Z'" particle = channel multF = ZPTOBB THEORY = ['A1', 'B3'] suffix = "_" + BTAGGING if ISMC: suffix += "_MC" if SY: suffix += "_comb" #if method=="cls": suffix="_CLs" if SY: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt" else: filename = "./combine/limits/MANtag_study/" + BTAGGING + "/" + YEAR + "_M%d.txt" if CATEGORY != "": filename = filename.replace( BTAGGING + "/", BTAGGING + "/single_category/" + CATEGORY + "_") suffix += "_" + CATEGORY if ISMC: filename = filename.replace(".txt", "_MC.txt") mass, val = fillValues(filename) #print "mass =",mass #print "val =", val Obs0s = TGraph() Exp0s = TGraph() Exp1s = TGraphAsymmErrors() Exp2s = TGraphAsymmErrors() Sign = TGraph() pVal = TGraph() Best = TGraphAsymmErrors() Theory = {} for i, m in enumerate(mass): if not m in val: print "Key Error:", m, "not in value map" continue n = Exp0s.GetN() Obs0s.SetPoint(n, m, val[m][0] * multF) Exp0s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPoint(n, m, val[m][3] * multF) Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF, val[m][4] * multF - val[m][3] * multF) Exp2s.SetPoint(n, m, val[m][3] * multF) Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF, val[m][5] * multF - val[m][3] * multF) if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6]) if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7]) if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8]) if len(val[m]) > 10: Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10]) for t in THEORY: Theory[t] = TGraphAsymmErrors() addXZH = True for m in sorted(HVT[t]['W']['XS'].keys()): if m < mass[0] or m > mass[-1]: continue if m > 4500: continue ## for now because I don't have the higher mass xs FIXME XsZ, XsZ_Up, XsZ_Down = 0., 0., 0. if addXZH: XsZ = 1000. * HVT[t]['Z']['XS'][ m] * 0.12 #temporary BR value set to 0.12 FIXME XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1., HVT[t]['Z']['PDF'][m][0] - 1.)) XsZ_Down = XsZ * (1. - math.hypot(1. - HVT[t]['Z']['QCD'][m][0], 1. - HVT[t]['Z']['PDF'][m][0])) n = Theory[t].GetN() Theory[t].SetPoint(n, m, XsZ) Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down), (XsZ_Up - XsZ)) Theory[t].SetLineColor(theoryLineColor[t]) Theory[t].SetFillColor(theoryFillColor[t]) Theory[t].SetFillStyle(theoryFillStyle[t]) Theory[t].SetLineWidth(2) #Theory[t].SetLineStyle(7) Exp2s.SetLineWidth(2) Exp2s.SetLineStyle(1) Obs0s.SetLineWidth(3) Obs0s.SetMarkerStyle(0) Obs0s.SetLineColor(1) Exp0s.SetLineStyle(2) Exp0s.SetLineWidth(3) Exp1s.SetFillColor(417) #kGreen+1 Exp1s.SetLineColor(417) #kGreen+1 Exp2s.SetFillColor(800) #kOrange Exp2s.SetLineColor(800) #kOrange Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25) Exp2s.GetXaxis().SetNoExponent(True) Exp2s.GetXaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetTitle("#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP + " #rightarrow " + particle + ") (fb)") Exp2s.GetYaxis().SetTitleOffset(1.5) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetMoreLogLabels() Sign.SetLineWidth(2) Sign.SetLineColor(629) Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1) Sign.GetYaxis().SetTitle("Significance") pVal.SetLineWidth(2) pVal.SetLineColor(629) pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1) pVal.GetYaxis().SetTitle("local p-Value") Best.SetLineWidth(2) Best.SetLineColor(629) Best.SetFillColor(629) Best.SetFillStyle(3003) Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)") Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1) Best.GetYaxis().SetTitle("Best Fit (pb)") c1 = TCanvas("c1", "Exclusion Limits", 800, 600) c1.cd() #SetPad(c1.GetPad(0)) c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetLeftMargin(0.12) c1.GetPad(0).SetTicks(1, 1) #c1.GetPad(0).SetGridx() #c1.GetPad(0).SetGridy() c1.GetPad(0).SetLogy() Exp2s.Draw("A3") Exp1s.Draw("SAME, 3") for t in THEORY: Theory[t].Draw("SAME, L3") Theory[t].Draw("SAME, L3X0Y0") Exp0s.Draw("SAME, L") if not options.blind: Obs0s.Draw("SAME, L") #setHistStyle(Exp2s) Exp2s.GetXaxis().SetTitleSize(0.050) Exp2s.GetYaxis().SetTitleSize(0.050) Exp2s.GetXaxis().SetLabelSize(0.045) Exp2s.GetYaxis().SetLabelSize(0.045) Exp2s.GetXaxis().SetTitleOffset(0.90) Exp2s.GetYaxis().SetTitleOffset(1.25) Exp2s.GetYaxis().SetMoreLogLabels(True) Exp2s.GetYaxis().SetNoExponent(True) Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3) #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2) #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6)) Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1]) #drawAnalysis(channel) drawAnalysis("") #drawRegion(channel, True) drawRegion("", True) #drawCMS(LUMI, "Simulation Preliminary") #Preliminary drawCMS(LUMI, "Work in Progress", suppressCMS=True) # legend top = 0.9 nitems = 4 + len(THEORY) leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top) #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("95% CL upper limits") leg.AddEntry(Obs0s, "Observed", "l") leg.AddEntry(Exp0s, "Expected", "l") leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f") leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f") for t in THEORY: leg.AddEntry(Theory[t], theoryLabel[t], "fl") leg.Draw() latex = TLatex() latex.SetNDC() latex.SetTextSize(0.045) latex.SetTextFont(42) #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h") leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225) leg2.SetBorderSize(0) leg2.SetFillStyle(0) #1001 leg2.SetFillColor(0) c1.GetPad(0).RedrawAxis() leg2.Draw() if not options.blind: Obs0s.Draw("SAME, L") c1.GetPad(0).Update() if not gROOT.IsBatch(): raw_input("Press Enter to continue...") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".png") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".pdf") if 'ah' in channel or 'sl' in channel: c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".C") c1.Print("combine/plotsLimit/ExclusionLimits/MANtag_study/" + YEAR + suffix + ".root") for t in THEORY: print "Model", t, ":", for m in range(mass[0], mass[-1], 1): if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == ( Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)): print m, print "" return
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')
mass_a = array("d", [1500, 1750, 2000, 2250, 2500, 3000, 3250, 3500]) mass_v = TVectorD(7, mass_a) err_a = array("d", [0, 0, 0, 0, 0, 0, 0, 0]) err_v = TVectorD(7, err_a) ## theory_a = array("d",[0.0006434760289,0.0005751010031,0.0005231099785,0.0005344069796,0.0005340549978]) ## theory_v = TVectorD(5,theory_a) ## mass_a = array("d",[1750,2000,2500,2750,3000]) ## mass_v = TVectorD(5,mass_a) ## err_a = array("d",[0,0,0,0,0,0]) ## err_v = TVectorD(5,err_a) theory = TGraphAsymmErrors(mass_v, theory_v, err_v, err_v, err_v, err_v) theory.SetLineColor(4) theory.SetLineStyle(9) theory.SetLineWidth(3) observed_p = TGraphAsymmErrors(massv, obsv, masserrv, masserrv, obserrv, obserrv) observed_p.SetLineColor(ROOT.kBlack) observed_p.SetLineWidth(2) observed_p.SetMarkerStyle(20) expected_p = TGraphAsymmErrors(massv, expv, masserrv, masserrv, experrv, experrv) expected_p.SetLineColor(ROOT.kBlack) expected_p.SetLineWidth(2) expected_p.SetLineStyle(2) expected68 = TGraphAsymmErrors(massv, expv, masserrv, masserrv, exp68Lv, exp68Hv) expected68.SetFillColor(ROOT.kGreen)