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 numericalInvertPlot(graph): #pick up point by point pl #loop on all data points nPoints = graph.GetN() newGraph = TGraphAsymmErrors(nPoints) #x=array('f') #y=array('f') #ey=array('f') for iPoint in xrange(0, nPoints): #get info on data point dataPointX = Double(0) dataPointY = Double(0) graph.GetPoint(iPoint, dataPointX, dataPointY) dataErrorX = graph.GetErrorX(iPoint) dataErrorY = graph.GetErrorY(iPoint) #numerical-invert the X newDataPointX = dataPointX * dataPointY newErrorXLeft = fabs(newDataPointX - (dataPointX - dataErrorX)) newErrorXRight = fabs(newDataPointX - (dataPointX + dataErrorX)) #setting the new graph (with asymm errors this time) newGraph.SetPoint(iPoint, newDataPointX, dataPointY) newGraph.SetPointEXhigh(iPoint, newErrorXRight) newGraph.SetPointEXlow(iPoint, newErrorXLeft) newGraph.SetPointEYhigh(iPoint, dataErrorY) newGraph.SetPointEYlow(iPoint, dataErrorY) print dataPointY, newDataPointX #check that the numerical-inverted X is still in the previous bin - otherwise, ERROR! binRangeLow = dataPointX - dataErrorX binRangeHigh = dataPointX + dataErrorX if newDataPointX < binRangeLow or newDataPointX > binRangeHigh: print "Warning! Data point should not be here!" print "Old data point: ", dataPointX print "New NI data point:", newDataPointX print "XLow: ", binRangeLow print "XHigh: ", binRangeHigh newGraph.SetPoint(iPoint, dataPointX, 0.0000000000001) newGraph.SetPointEXhigh(iPoint, dataErrorX) newGraph.SetPointEXlow(iPoint, dataErrorX) newGraph.SetPointEYhigh(iPoint, dataErrorY) newGraph.SetPointEYlow(iPoint, dataErrorY) return newGraph
def apply_centers(hPt, hCen): #bin center points according to the data cen = get_centers_from_toyMC(hCen) gSig = TGraphAsymmErrors(hPt.GetNbinsX()) for i in xrange(hPt.GetNbinsX()): #center point #xcen = hPt.GetBinCenter(i+1) xcen = cen[i]["val"] #cross section value gSig.SetPoint(i, xcen, hPt.GetBinContent(i + 1)) #vertical error gSig.SetPointEYlow(i, hPt.GetBinErrorLow(i + 1)) gSig.SetPointEYhigh(i, hPt.GetBinErrorUp(i + 1)) #horizontal error gSig.SetPointEXlow(i, cen[i]["err"]) gSig.SetPointEXhigh(i, cen[i]["err"]) return gSig
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 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 resolutionGraph( tree, xVar, yVar, title, measure, cut='', weightExpression='' ): ## Create and fill a resolution graph for this dataset, i.e. resolution of y vs. x # @ param tree TTree object used to create the histogram # @ param xVar Variable object defining the xAxis and the draw command # @ param yVar Variable object defining the xAxis and the draw command # @ param title histogram title # @param measure Measure object to evaluate the resolution # @ param cut Cut object (optional) # @ param weightExpression weight expression (optional) # @ return the generated histogram bins = xVar.binning.bins title = '%s vs %s' % (yVar.title, xVar.title) if not title else title name = 'h%s_%s' % ( title.replace(' ', '_').replace('(', '').replace(')',''), uuid.uuid1() ) from ROOT import TGraphAsymmErrors graph = TGraphAsymmErrors( xVar.binning.nBins ) graph.SetNameTitle( name, '%s;%s;%s' % (title, xVar.axisLabel, measure.getDecoratedLabel( yVar ) ) ) # create a histogram of y for each bin in x and evaluate measure for iBin in xrange( xVar.binning.nBins ): low = bins[iBin] up = bins[iBin+1] xMean = low + 0.5 * (up - low) xErr = xMean - low myCut = (Cut( '%s >= %s && %s < %s' % (xVar.command, low, xVar.command, up) ) + cut) * weightExpression values, weights = getValuesFromTree( tree, yVar.command, myCut.cut ) yMean, yErrLow, yErrUp = measure.calculateFromValues( values, weights ) graph.SetPoint( iBin, xMean, yMean ) graph.SetPointError( iBin, xErr, xErr, yErrLow, yErrUp ) return graph
def ReadHepDataROOT(HepDataFileName, tablenum): infile = TFile(HepDataFileName) table = infile.Get('Table %d' % tablenum) Hist1D_y1 = table.Get('Hist1D_y1') Hist1D_y1_e1 = table.Get('Hist1D_y1_e1') Hist1D_y1_e2plus = table.Get('Hist1D_y1_e2plus') Hist1D_y1_e2minus = table.Get('Hist1D_y1_e2minus') Hist1D_y1_e3 = table.Get('Hist1D_y1_e3') Hist1D_y1.SetDirectory(0) Hist1D_y1_e1.SetDirectory(0) Hist1D_y1_e2plus.SetDirectory(0) Hist1D_y1_e2minus.SetDirectory(0) Hist1D_y1_e3.SetDirectory(0) infile.Close() graphSyst = TGraphAsymmErrors() histoStat = Hist1D_y1.Clone('histoStat') for iPt in range(Hist1D_y1.GetNbinsX()): histoStat.SetBinContent(iPt + 1, Hist1D_y1.GetBinContent(iPt + 1)) histoStat.SetBinError(iPt + 1, Hist1D_y1_e1.GetBinContent(iPt + 1)) systlow = math.sqrt( Hist1D_y1_e2minus.GetBinContent(iPt + 1)**2 + Hist1D_y1_e3.GetBinContent(iPt + 1)**2) systhigh = math.sqrt( Hist1D_y1_e2plus.GetBinContent(iPt + 1)**2 + Hist1D_y1_e3.GetBinContent(iPt + 1)**2) graphSyst.SetPoint(iPt, histoStat.GetBinCenter(iPt + 1), histoStat.GetBinContent(iPt + 1)) graphSyst.SetPointError(iPt, histoStat.GetBinWidth(iPt + 1) / 2, histoStat.GetBinWidth(iPt + 1) / 2, systlow, systhigh) return histoStat, graphSyst
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 MakeErrorGraphForSource(self, source): result = TGraphAsymmErrors() counter = 0 for point in sorted(self._pointlist): result.SetPoint(counter, point.GetX(), point.GetY()) result.SetPointError(counter, point.GetDX(), point.GetDX(), point.GetLowerErrorForSource(source), point.GetUpperErrorForSource(source)) counter += 1 return result
def fit(x, y): from ROOT import TF1, TGraphAsymmErrors g = TGraphAsymmErrors(len(x)) for i in xrange(len(x)): g.SetPoint(i, x[i], y[i].nominal_value) g.SetPointError(i, 0, 0, y[i].std_dev, y[i].std_dev) fit = TF1("fit", "-[1]*x*x+[0]", -40, 120) fit.SetParNames("z0", "a") g.Fit(fit) return fit
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 normalizeGraph(graph, binwidth): xsecSum = 0. for pt in range(1, graph.GetN()): xsecSum += graph.GetY()[pt] * binwidth[pt] normGraph = TGraphAsymmErrors(graph.GetN() - 1) for pt in range(0, normGraph.GetN()): normGraph.SetPoint(pt, graph.GetX()[pt + 1], graph.GetY()[pt + 1] / xsecSum) normGraph.SetPointEYhigh(pt, graph.GetErrorYhigh(pt + 1) / xsecSum) normGraph.SetPointEYlow(pt, graph.GetErrorYlow(pt + 1) / xsecSum) return normGraph
def getGraph(result, label): masses = result["mass"] massErr = result["massErr"] sigma = result["sigma"] sigmaErr = result["sigmaErr"] res = TGraphAsymmErrors(len(masses)) res.SetName(label) for i, mass in enumerate(masses): res.SetPoint(i, mass, sigma[i]) res.SetPointError(i, massErr[i], massErr[i], sigmaErr[i], sigmaErr[i]) return res
def createGraph(x, y, exh, exl, eyh, eyl): """ Create a TGraphAsymmErrors from the passed (lists) of values """ from ROOT import TGraphAsymmErrors nPoints = len(x) # simply assume that all lists have the same length graph = TGraphAsymmErrors(nPoints) for i in range(0, nPoints): # "blinding" of signal region # if x[i] > 5.2 and x[i] < 5.4: continue graph.SetPoint(i, x[i], y[i]) graph.SetPointError(i, exl[i], exh[i], eyl[i], eyh[i]) return graph
def getGraphFromHistos(histoCent, histoMin, histoMax): ''' Method that takes in input 3 histos and returns a graph ''' nPoints = histoCent.GetNbinsX() graph = TGraphAsymmErrors(nPoints) for iPt in range(nPoints): centC = histoCent.GetBinContent(iPt+1) minC = histoMin.GetBinContent(iPt+1) maxC = histoMax.GetBinContent(iPt+1) width = histoCent.GetBinWidth(iPt+1)/2 graph.SetPoint(iPt, histoCent.GetBinCenter(iPt+1), centC) graph.SetPointError(iPt, width, width, centC-minC, maxC-centC) return graph
def fixData(hist, useGarwood=True, cutGrass=False, maxPoisson=False): if hist == None: return varBins = False data = TGraphAsymmErrors() alpha = 1 - 0.6827 for i in list(reversed(range(0, hist.GetNbinsX()))): #print "bin", i, "x:", hist.GetX()[i], "y:", hist.GetY()[i] # X error bars to 0 - do not move this, otherwise the first bin will disappear, thanks Wouter and Rene! N = max(hist.GetBinContent(i + 1), 0.) # Avoid unphysical bins data.SetPoint(i, hist.GetXaxis().GetBinCenter(i + 1), N) if not varBins: data.SetPointEXlow(i, 0) data.SetPointEXhigh(i, 0) # Garwood confidence intervals if (useGarwood): L = ROOT.Math.gamma_quantile(alpha / 2, N, 1.) if N > 0 else 0. U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) # maximum between Poisson and Sumw2 error bars EL = N - L if not maxPoisson else max(N - L, hist.GetBinErrorLow(i)) EU = U - N if not maxPoisson else max(U - N, hist.GetBinErrorHigh(i)) data.SetPointEYlow(i, EL) data.SetPointEYhigh(i, EU) else: data.SetPointEYlow(i, math.sqrt(N)) data.SetPointEYhigh(i, math.sqrt(N)) # Cut grass if cutGrass and data.GetY()[i] > 0.: cutGrass = False # Treatment for 0 bins # if abs(hist.GetY()[i])<=1.e-6: # if cutGrass: hist.SetPointError(i, hist.GetErrorXlow(i), hist.GetErrorXhigh(i), 1.e-6, 1.e-6, ) # if (hist.GetX()[i]>65 and hist.GetX()[i]<135 and hist.GetY()[i]==0): hist.SetPointError(i, hist.GetErrorXlow(i), hist.GetErrorXhigh(i), 1.e-6, 1.e-6, ) # hist.SetPoint(i, hist.GetX()[i], -1.e-4) # X error bars #if hist.GetErrorXlow(i)<1.e-4: # binwidth = hist.GetX()[1]-hist.GetX()[0] # hist.SetPointEXlow(i, binwidth/2.) # hist.SetPointEXhigh(i, binwidth/2.) data.SetMarkerColor(hist.GetMarkerColor()) data.SetMarkerStyle(hist.GetMarkerStyle()) data.SetMarkerSize(hist.GetMarkerSize()) #data.SetLineSize(hist.GetLineSize()) return data
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 getGraph(result, label, Data=False): ptda = result["ptda"] if Data: sigma = result["da_nChi2"] else: sigma = result["mc_nChi2"] sigmaErr = 0 res = TGraphAsymmErrors(len(ptda)) res.SetName(label) for i, pt in enumerate(ptda): res.SetPoint(i, pt, sigma[i]) res.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i], 0, 0) return res
def diffGraph(self, g, h, opt): gdiff = TGraphAsymmErrors(g) gdiff.SetName(g.GetName() + h.GetName() + '_diff') for i in range(0, gdiff.GetN()): x = Double(0.) y = Double(0.) g.GetPoint(i, x, y) gdiff.SetPoint(i, x, y - h.GetBinContent(i + 1)) if opt == 1: # keep bin errors pass elif opt == 2: gdiff.SetPointEYhigh( i, math.sqrt(g.GetErrorYhigh(i)**2 + h.GetBinError(i + 1)**2)) return gdiff
def ComputeRatioGraph(gNum, gDen, useDenUnc=True): ''' Helper method to divide two TGraph (assuming same binning) Parameters ---------- - gNum: graph to divide (numerator) - gDen: graph to divide (denominator) Returns ---------- - gRatio: resulting graph ''' if gNum.GetN() != gDen.GetN(): print('ERROR: only graphs with same number of bins can be divided!') return None gRatio = TGraphAsymmErrors(1) for iPt in range(gNum.GetN()): x, num = ctypes.c_double(), ctypes.c_double() xd, den = ctypes.c_double(), ctypes.c_double() gNum.GetPoint(iPt, x, num) xUncLow = gNum.GetErrorXlow(iPt) xUncHigh = gNum.GetErrorXhigh(iPt) numUncLow = gNum.GetErrorYlow(iPt) numUncHigh = gNum.GetErrorYhigh(iPt) gDen.GetPoint(iPt, xd, den) denUncLow = gDen.GetErrorYlow(iPt) denUncHigh = gDen.GetErrorYhigh(iPt) ratio, ratioUncLow, ratioUncHigh = 0., 0., 0. if num.value != 0. and den.value != 0.: ratio = num.value/den.value if useDenUnc: ratioUncLow = np.sqrt((numUncLow/num.value)**2 + (denUncLow/den.value)**2) * ratio ratioUncHigh = np.sqrt((numUncHigh/num.value)**2 + (denUncHigh/den.value)**2) * ratio else: ratioUncLow = numUncLow / num.value * ratio ratioUncHigh = numUncHigh / num.value * ratio gRatio.SetPoint(iPt, x.value, ratio) gRatio.SetPointError(iPt, xUncLow, xUncHigh, ratioUncLow, ratioUncHigh) return gRatio
def fixed_centers(hPt): #fixed bin centers gSig = TGraphAsymmErrors(hPt.GetNbinsX()) for i in xrange(hPt.GetNbinsX()): #cross section value gSig.SetPoint(i, hPt.GetBinCenter(i + 1), hPt.GetBinContent(i + 1)) #vertical error gSig.SetPointEYlow(i, hPt.GetBinErrorLow(i + 1)) gSig.SetPointEYhigh(i, hPt.GetBinErrorUp(i + 1)) #horizontal error gSig.SetPointEXlow(i, hPt.GetBinWidth(i + 1) / 2.) gSig.SetPointEXhigh(i, hPt.GetBinWidth(i + 1) / 2.) return gSig
def getErrHist(plot,ofHist,rSFOFErr): hist = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) histUp = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) histDown = TH1F("errHist","errHist",plot.nBins,plot.firstBin,plot.lastBin) graph = TGraphAsymmErrors() for i in range(1,hist.GetNbinsX()+1): hist.SetBinContent(i,1) hist.SetBinError(i,ofHist.GetBinContent(i)*rSFOFErr) for i in range(0,hist.GetNbinsX()+1): graph.SetPoint(i,plot.firstBin - ((plot.lastBin-plot.firstBin)/plot.nBins)*0.5 +(i)*((plot.lastBin-plot.firstBin)/plot.nBins),ofHist.GetBinContent(i)) graph.SetPointError(i,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,((plot.firstBin-plot.lastBin)/plot.nBins)*0.5,(hist.GetBinError(i)**2 + ofHist.GetBinContent(i))**0.5,(hist.GetBinError(i)**2 + ofHist.GetBinContent(i))**0.5) for i in range(1,hist.GetNbinsX()+1): histUp.SetBinContent(i,ofHist.GetBinContent(i) + hist.GetBinError(i)) histDown.SetBinContent(i,ofHist.GetBinContent(i) - hist.GetBinError(i)) if ofHist.GetBinContent(i) > 0: hist.SetBinError(i,hist.GetBinError(i) / (ofHist.GetBinContent(i))) else: hist.SetBinError(i,0) return graph, histUp, histDown
def efficiencyRatioSF( eff1, eff2, ): newEff = TGraphAsymmErrors(eff1.GetN()) for i in range(0, eff1.GetN()): pointX1 = ROOT.Double(0.) pointX2 = ROOT.Double(0.) pointY1 = ROOT.Double(0.) pointY2 = ROOT.Double(0.) isSuccesful1 = eff1.GetPoint(i, pointX1, pointY1) isSuccesful2 = eff2.GetPoint(i, pointX2, pointY2) errY1Up = eff1.GetErrorYhigh(i) errY1Down = eff1.GetErrorYlow(i) errY2Up = eff2.GetErrorYhigh(i) errY2Down = eff2.GetErrorYlow(i) errX = eff1.GetErrorX(i) if pointY1 != 0 and pointY2 != 0: yValue = pointY1 / pointY2 xValue = pointX1 xError = errX yErrorUp = math.sqrt((1. / pointY2 * errY1Up)**2 + (pointY1 / pointY2**2 * errY2Down)**2) yErrorDown = math.sqrt((1. / pointY2 * errY1Down)**2 + (pointY1 / pointY2**2 * errY2Up)**2) else: yValue = 0 xValue = pointX1 xError = errX yErrorUp = 0 yErrorDown = 0 newEff.SetPoint(i, xValue, yValue) newEff.SetPointError(i, xError, xError, yErrorDown, yErrorUp) return newEff
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 efficiencyRatio(eff1, eff2): newEff = TGraphAsymmErrors(eff1.GetN()) for i in range(0, eff1.GetN()): pointX1 = Double(0.) pointX2 = Double(0.) pointY1 = Double(0.) pointY2 = Double(0.) isSuccesful1 = eff1.GetPoint(i, pointX1, pointY1) isSuccesful2 = eff2.GetPoint(i, pointX2, pointY2) errY1Up = eff1.GetErrorYhigh(i) errY1Low = eff1.GetErrorYlow(i) errY2Up = eff2.GetErrorYhigh(i) errY2Low = eff2.GetErrorYlow(i) errX = eff1.GetErrorX(i) if pointY2 != 0: yValue = pointY1 / pointY2 xValue = pointX1 xError = errX #~ yErrorUp = math.sqrt(((1/pointY2)*errY1Up)**2+((pointY1/pointY2**2)*errY2Up)**2) yErrorUp = math.sqrt(((1 / pointY2) * errY1Up)**2 + ((pointY1 / pointY2**2) * errY2Up)**2) yErrorDown = math.sqrt(((1 / pointY2) * errY1Low)**2 + ((pointY1 / pointY2**2) * errY2Low)**2) else: yValue = 0 xValue = pointX1 xError = errX yErrorUp = 0 yErrorDown = 0 #~ print i newEff.SetPoint(i, xValue, yValue) newEff.SetPointError(i, xError, xError, yErrorDown, yErrorUp) return newEff
def getRatio(result, result2, label, Data=False): ptda = result["ptda"] ptda2 = result2["ptda"] if Data: sigma = result["da_nChi2"] sigma2 = result2["da_nChi2"] else: sigma = result["mc_nChi2"] sigma2 = result2["mc_nChi2"] print(sigma) print(sigma2) ratio = TGraphAsymmErrors(len(ptda)) ratio.SetName(label) for i, pt in enumerate(ptda): ratio.SetPoint(i, pt, sigma[i] / sigma2[i]) ratio.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i], 0, 0) return ratio
def averageGraphs(graphs): """ Create a new TGraphAsymmErrors from the passed list of TGraphAsymmErrors where the central values are the average values of all graphs. The uncertainties are computed from adding in quadrature the average of the uncertainties and the std-deviation of the central values """ from ROOT import TGraphAsymmErrors from math import sqrt # simply assume that all graphs have the same number of points nPoints = graphs[0].GetN() graph = TGraphAsymmErrors(nPoints) for i in range(0, nPoints): [centralVal, cValSig] = getAvgVal(graphs, i) meanErr = getAvgErr(graphs, i) uncer = sqrt(cValSig**2 + meanErr**2) [x, exl, exh] = getXInfo(graphs[0], i) # simply assume it is the same for all graph.SetPoint(i, x, centralVal) graph.SetPointError(i, exl, exh, uncer, uncer) return graph
def DivideGraphByHisto(gNum, hDen, useHistoUnc=True): ''' Helper method to divide a TGraph by a TH1 (assuming same binning) Parameters ---------- - gNum: graph to divide (numerator) - hDen: histogram (denominator) Returns ---------- - gRatio: resulting graph ''' if gNum.GetN() != hDen.GetNbinsX(): print('ERROR: only graphs and histos with same number of bins can be divided!') return None gRatio = TGraphAsymmErrors(0) for iPt in range(gNum.GetN()): x, num = ctypes.c_double(), ctypes.c_double() gNum.GetPoint(iPt, x, num) xUncLow = gNum.GetErrorXlow(iPt) xUncHigh = gNum.GetErrorXhigh(iPt) numUncLow = gNum.GetErrorYlow(iPt) numUncHigh = gNum.GetErrorYhigh(iPt) ptBinHisto = hDen.GetXaxis().FindBin(x.value) den = hDen.GetBinContent(ptBinHisto) if useHistoUnc: ratioUncLow = np.sqrt((numUncLow/num.value)**2 + (hDen.GetBinError(ptBinHisto)/den)**2) * num.value/den ratioUncHigh = np.sqrt((numUncHigh/num.value)**2 + (hDen.GetBinError(ptBinHisto)/den)**2) * num.value/den else: ratioUncLow = numUncLow/num.value * num.value/den ratioUncHigh = numUncHigh/num.value * num.value/den gRatio.SetPoint(iPt, x.value, num.value/den) gRatio.SetPointError(iPt, xUncLow, xUncHigh, ratioUncLow, ratioUncHigh) return gRatio
def readFile(fname, maxenergy=4.8): infile = file(fname, 'r') inlines = infile.readlines() graph = TGraphAsymmErrors() for iline in range(0, len(inlines)): line = inlines[iline] if '*' in line: continue lineparts = ' '.join(line.split()).strip().split(' ') if not check_number(lineparts[0:5]): continue energy = float(lineparts[0]) R = float(lineparts[3]) if (energy > maxenergy): continue statupp = abs(float(lineparts[4])) statlow = abs(float(lineparts[5])) (systlow, systupp) = systematics(iline, inlines) ipoint = graph.GetN() graph.SetPoint(ipoint, energy, R) graph.SetPointError( ipoint, 0, 0, math.sqrt(statlow * statlow + 1e-4 * systlow * systlow * R * R), math.sqrt(statupp * statupp + 1e-4 * systupp * systupp * R * R)) return graph