def draw_nse_mean(self): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_mean = TGraphErrors() gr_width = TGraphErrors() gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): f_gaus = self.draw_nse(cent_bin1[1], cent_bin2[1], p_bin1[i], p_bin2[i], -1, 2) mean = f_gaus.GetParameter(1) mean_err = f_gaus.GetParError(1) width = f_gaus.GetParameter(2) width_err = f_gaus.GetParError(2) gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean) gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err) gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width) gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err) p = 0.5 * (p_bin1[i] + p_bin2[i]) if p < 1: nse_low = 0.5 * p - 1.5 else: nse_low = -1 m = f_gaus.Integral(nse_low, 2.0) N = f_gaus.Integral(-10.0, 10.0) gr_eff.SetPoint(i, p, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_mean.SetMarkerStyle(20) gr_mean.SetMarkerSize(1.5) gr_mean.SetMarkerColor(632) gr_width.SetMarkerStyle(20) gr_width.SetMarkerSize(1.5) gr_width.SetMarkerColor(600) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width") canvas_file = self.__canvas__ canvas_file.cd() c1 = TCanvas("c1", "c1", 1000, 800) hx.Draw() gr_width.Draw("psame") gr_mean.Draw("psame") c1.Write("nse") c1.SaveAs("nse.png") c2 = TCanvas("c2", "c2", 1000, 800) hx.GetYaxis().SetTitle("n#sigma_{e} cut efficiency") hx.Draw() gr_eff.Draw("psame") c2.Write("nse_eff") c2.SaveAs("nse_eff.png")
def testIthr(): lines = get_lines('DAC_scan_ithr_0x40to0xf0.dat') gr1 = TGraphErrors() gr2 = TGraphErrors() fUnit = 1000. / 0.7 yUnit = 'e^{-}' for line in lines: if len(line) == 0: continue if line[0] in ['#', '\n']: continue fs = line.rstrip().split() ix = int(fs[0]) gr1.SetPoint(ix, float(fs[1]), float(fs[2]) * fUnit) gr1.SetPointError(ix, 0, float(fs[3]) * fUnit) gr2.SetPoint(ix, float(fs[1]), float(fs[4]) * fUnit) gr2.SetPointError(ix, 0, float(fs[5]) * fUnit) useAtlasStyle() gStyle.SetMarkerStyle(20) gr1.SetMarkerStyle(20) gr1.Draw('AP') h1 = gr1.GetHistogram() h1.GetYaxis().SetTitle("Threshold [" + yUnit + "]") h1.GetXaxis().SetTitle("I_{Thre} code") # h1.GetYaxis().SetRangeUser(0,0.2) gPad.SetTicks(1, 0) gPad.SetRightMargin(0.16) y1b = 0 y2b = 15 x1 = h1.GetXaxis().GetXmax() y1 = h1.GetYaxis().GetXmin() y2 = h1.GetYaxis().GetXmax() raxis = TGaxis(x1, y1, x1, y2, y1b, y2b, 506, "+L") raxis.SetLineColor(2) raxis.SetLabelColor(2) raxis.SetTitleColor(2) raxis.SetTitle("ENC [" + yUnit + "]") raxis.Draw() nP = gr2.GetN() Ys = gr2.GetY() EYs = gr2.GetEY() Y = array( 'd', [y1 + (y2 - y1) / (y2b - y1b) * (Ys[i] - y1b) for i in range(nP)]) EY = array('d', [(y2 - y1) / (y2b - y1b) * EYs[i] for i in range(nP)]) gr2x = TGraphErrors(nP, gr2.GetX(), Y, gr2.GetEX(), EY) gr2x.SetMarkerStyle(24) gr2x.SetLineColor(2) gr2x.SetMarkerColor(2) gr2x.Draw('Psame') waitRootCmdX()
def draw_tof_cut_eff(self, cent_low, cent_high): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_mean = TGraphErrors() gr_width = TGraphErrors() gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): f_gaus = self.draw_tof_cut(cent_bin1[1], cent_bin2[1], p_bin1[i], p_bin2[i]) mean = f_gaus.GetParameter(1) mean_err = f_gaus.GetParError(1) width = f_gaus.GetParameter(2) width_err = f_gaus.GetParError(2) gr_mean.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, mean) gr_mean.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, mean_err) gr_width.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, width) gr_width.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, width_err) m = f_gaus.Integral(0.97, 1.03) N = f_gaus.GetParameter(0) * math.sqrt( 2 * math.pi) * f_gaus.GetParameter(2) print m, N gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_mean.SetMarkerStyle(20) gr_mean.SetMarkerSize(1.5) gr_mean.SetMarkerColor(632) gr_width.SetMarkerStyle(20) gr_width.SetMarkerSize(1.5) gr_width.SetMarkerColor(600) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 10, -0.2, 1.2, "p_{T}(GeV/c)", "Mean/Width") canvas_file = self.__canvas__ canvas_file.cd() c1 = TCanvas("c1", "c1", 1000, 800) hx.GetYaxis().SetTitle("1/#beta cut efficency") hx.Draw() gr_width.Draw("psame") gr_mean.Draw("psame") c1.Write("tof") c1.SaveAs("tof.png") c2 = TCanvas("c2", "c2", 1000, 800) hx.Draw() gr_eff.Draw("psame") c2.Write("tof_cut_eff") c2.SaveAs("tof_cut.png")
def rescaleJetPlot(plot): #loop on all data points nPoints = plot.GetN() # print "old:",plot.GetName(), nPoints #create another TGraph newPlot = TGraphErrors() for i in xrange(0, nPoints): dataPointX = Double(0) dataPointY = Double(0) error = Double(0) plot.GetPoint(i, dataPointX, dataPointY) #if numpy.isnan(dataPointY) : dataPointY = 0.000001 if dataPointY < 0.000001: dataPointY = 0.000001 errorX = plot.GetErrorX(i) errorY = plot.GetErrorY(i) newPlot.SetPoint(i, dataPointX / 1000., dataPointY) newPlot.SetPointError(i, errorX / 1000., errorY) # print "new:", newPlot.GetName(), newPlot.GetN() return newPlot
def test1a(fname='data/fpgaLin/dp02a_Mar04C1a_data_0.root'): add_fit_menu() t1 = TChain('reco') t1.Add(fname) t1.Show(0) V = 200 gr1 = TGraphErrors() for i in range(19): c1.cd(i+1) lt.DrawLatexNDC(0.2,0.4,'Ch={0:d}'.format(i)) t1.Draw('Q[{0:d}]>>hx{0:d}'.format(i),'tID!=7') hx = gPad.GetPrimitive('hx{0:d}'.format(i)) hx.Fit('gaus') fun1 = hx.GetFunction('gaus') encN = 7.40*V*fun1.GetParameter(2)/fun1.GetParameter(1) encE = 7.40*V*fun1.GetParError(2)/fun1.GetParameter(1) gr1.SetPoint(i,i,encN) gr1.SetPointError(i,0,encE) c1.cd(20) gr1.Draw('AP') c1.cd() waitRootCmdX()
def write(self, setup): #Rescaling to efficiency normalisation = 1/self.histogram.GetBinContent(1) #Rescaling everything to have rates self.histogram.Scale(normalisation) efficiencyPlot = TGraphErrors(self.histogram) efficiencyPlot.SetName(self.cfg_ana.plot_name+"_errors") efficiencyPlot.SetTitle(self.cfg_ana.plot_title) for index in xrange(0, len(efficiencyPlot.GetX())): efficiencyPlot.SetPointError(index, efficiencyPlot.GetEX()[index], sqrt(efficiencyPlot.GetY()[index] * normalisation) ) c1 = TCanvas ("canvas_" + self.cfg_ana.plot_name, self.cfg_ana.plot_title, 600, 600) c1.SetGridx() c1.SetGridy() efficiencyPlot.Draw("AP") c1.Update() c1.Write() c1.Print(self.cfg_ana.plot_name + ".svg", "svg") efficiencyPlot.Write()
def DivideTGraphErrors(num, denom, name): nPoints = num.GetN() nSkipPoints = 0 # count of when we can't divide newTGraph = TGraphErrors(nPoints) newTGraph.SetName(name) for i in range(nPoints): x = num.GetX()[i] x_err = num.GetEX()[i] y1 = num.GetY()[i] y2 = denom.GetY()[i] y = 0.0 y_err = 0.0 if ((y1 != 0) and (y2 != 0)): # technically could make this work for y1 = 0 y = y1 / y2 y1_err = num.GetEY()[i] y2_err = denom.GetEY()[i] y_err = y * math.sqrt( math.pow(y1_err / y1, 2) + math.pow(y2_err / y2, 2)) newTGraph.SetPoint(i - nSkipPoints, x, y) newTGraph.SetPointError(i - nSkipPoints, x_err, y_err) else: newTGraph.RemovePoint(i - nSkipPoints) nSkipPoints += 1 newTGraph.SetLineColor(num.GetLineColor()) newTGraph.SetMarkerColor(num.GetMarkerColor()) newTGraph.SetMarkerStyle(num.GetMarkerStyle()) return newTGraph
def sub2pull(dataHist, pdfwErrs): from ROOT import TGraphErrors from math import sqrt ThePull = TGraphErrors(dataHist.GetN()) pdfi = 0 for i in range(0, ThePull.GetN()): while (dataHist.GetX()[i] > pdfwErrs.GetX()[pdfi]): pdfi += 1 #print 'pull point:',i,'pdfi:',pdfi diff = dataHist.GetY()[i] - pdfwErrs.GetY()[pdfi] if (diff < 0): err2 = pdfwErrs.GetErrorY(pdfi)**2 + dataHist.GetErrorYhigh(i)**2 else: err2 = pdfwErrs.GetErrorY(pdfi)**2 + dataHist.GetErrorYlow(i)**2 if (err2>0): pull = diff/(sqrt(err2)*1.2) else: pull = 0 ThePull.SetPoint(i, dataHist.GetX()[i], pull) ThePull.SetPointError(i, 0., 1.) ThePull.SetName(dataHist.GetName() + "_pull") ThePull.SetTitle("data") return ThePull
def draw_neta_cut_eff(self, cent_low, cent_high): cent_bin1 = [0, 4, 7] cent_bin2 = [3, 6, 8] p_bin1 = [ 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5 ] p_bin2 = [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 ] gr_eff = TGraphErrors() for i in range(0, len(p_bin1)): mn = self.draw_neta_cut(cent_low, cent_high, p_bin1[i], p_bin2[i]) m = mn[0] N = mn[1] gr_eff.SetPoint(i, (p_bin1[i] + p_bin2[i]) * 0.5, m / N) gr_eff.SetPointError(i, (p_bin2[i] - p_bin1[i]) * 0.5, eff_err(m, N)) gr_eff.SetMarkerStyle(20) gr_eff.SetMarkerSize(1.5) gr_eff.SetMarkerColor(600) hx = histo(0, 8, -0.2, 1.2, "p_{T}(GeV/c)", "n#eta cut efficiency") canvas_file = self.__canvas__ canvas_file.cd() c2 = TCanvas("c2", "c2", 1000, 800) hx.Draw() gr_eff.Draw("psame") c2.Write("neta_cut_eff") c2.SaveAs("neta_cut.png")
def plotGainSummary(self, strDetName): #Create the Plot - Average gDet_AvgEffGain = TGraphErrors(len(self.GAIN_AVG_POINTS)) gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxEffGain = TGraphErrors(len(self.GAIN_MAX_POINTS)) gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinEffGain = TGraphErrors(len(self.GAIN_MIN_POINTS)) gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName)) #Set and print the points #print "===============Printing Gain Data===============" #print "[BEGIN_DATA]" #print "\tVAR_INDEP,VAR_DEP,VAR_DEP_ERR" for i in range(0, len(self.GAIN_AVG_POINTS)): #Average gDet_AvgEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_AVG_POINTS[i]) gDet_AvgEffGain.SetPointError(i, 0, self.GAIN_STDDEV_POINTS[i]) #print "\t%f,%f,%f"%(self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i],self.GAIN_STDDEV_POINTS[i]) #Max gDet_MaxEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_MAX_POINTS[i]) #Min gDet_MinEffGain.SetPoint(i, self.DET_IMON_POINTS[i], self.GAIN_MIN_POINTS[i]) pass #print "[END_DATA]" #print "" #Draw canv_AvgEffGain = TCanvas( "canv_{0}_EffGainAvg".format(strDetName), "{0} Average Effective Gain".format(strDetName), 600, 600) canv_AvgEffGain.cd() canv_AvgEffGain.cd().SetLogy() gDet_AvgEffGain.GetXaxis().SetTitle("HV") gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2, 1e6) gDet_AvgEffGain.SetMarkerStyle(21) gDet_AvgEffGain.Draw("AP") gDet_MaxEffGain.Draw("sameL") gDet_MinEffGain.Draw("sameL") #Write dir_Summary = self.FILE_OUT.mkdir("Summary") dir_Summary.cd() canv_AvgEffGain.Write() gDet_AvgEffGain.Write() gDet_MaxEffGain.Write() gDet_MinEffGain.Write() return
class GraphicsObject: def __init__(self, data, name): self._data = data self._graphics = None self._style = Style(kBlack, 20) self._plotrange = {"Min": None, "Max": None} self._name = name def SetPlotRange(self, min, max): self._plotrange[min] = min self._plotrange[max] = max def SetStyle(self, style): self._style = style def SetName(self, name): self._name = name def GetData(self): return self._data def GetGraphics(self): return self._graphics def GetStyle(self): return self._style def Draw(self): if not self._graphics: self._graphics = TGraphErrors() np = 0 for bin in range(1, self._data.GetXaxis().GetNbins() + 1): if self._plotrange["Min"] and self._data.GetXaxis( ).GetBinLowEdge(bin) < self._plotrange["Min"]: continue if self._plotrange["Max"] and self._data.GetXaxis( ).GetBinUpEdge(bin) > self._plotrange["Max"]: break self._graphics.SetPoint( np, self._data.GetXaxis().GetBinCenter(bin), self._data.GetBinContent(bin)) self._graphics.SetPointError( np, self._data.GetXaxis().GetBinWidth(bin) / 2., self._data.GetBinError(bin)) np = np + 1 self._graphics.SetMarkerColor(self._style.GetColor()) self._graphics.SetLineColor(self._style.GetColor()) self._graphics.SetMarkerStyle(self._style.GetMarker()) self._graphics.Draw("epsame") def AddToLegend(self, legend, title=None): if self._graphics: tit = self._name if title: tit = title legend.AddEntry(self._graphics, tit, "lep")
def get_data_graph(hx, centers): #make graph erros from input distribution and bin centers gr = TGraphErrors(hx.GetNbinsX()) for i in xrange(hx.GetNbinsX()): gr.SetPoint(i, centers[i]["val"], hx.GetBinContent(i + 1)) gr.SetPointError(i, centers[i]["err"], hx.GetBinError(i + 1)) return gr
def getGraph(data, name='graph', offset=0): from ROOT import TGraphErrors g = TGraphErrors(len(data)) for n, (_, throughput, throughputE) in enumerate(data): g.SetPoint(n, offset + n, throughput) g.SetPointError(n, 0., throughputE) g.SetName(name) g.SetLineWidth(2) g.SetMarkerSize(1.7) return g
def plotPDSummary(self, strDetName): #Create the Plot - Average gDet_AvgPD = TGraphErrors(len(self.PD_AVG_POINTS)) gDet_AvgPD.SetName("g_{0}_PDAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxPD = TGraphErrors(len(self.PD_MAX_POINTS)) gDet_MaxPD.SetName("g_{0}_PDMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinPD = TGraphErrors(len(self.PD_MIN_POINTS)) gDet_MinPD.SetName("g_" + strDetName + "_PDMin") gDet_MinPD.SetName("g_{0}_PDMin".format(strDetName)) #Set the points for i in range(0, len(self.PD_AVG_POINTS)): #Average gDet_AvgPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_AVG_POINTS[i]) gDet_AvgPD.SetPointError(i, self.GAIN_STDDEV_POINTS[i], self.PD_STDDEV_POINTS[i]) #Max gDet_MaxPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_MAX_POINTS[i]) #Min gDet_MinPD.SetPoint(i, self.GAIN_AVG_POINTS[i], self.PD_MIN_POINTS[i]) #Draw canv_AvgPD = TCanvas("canv_{0}_PDAvg".format(strDetName), "{0} Discharge Probability".format(strDetName), 600, 600) canv_AvgPD.cd() canv_AvgPD.cd().SetLogx() canv_AvgPD.cd().SetLogy() gDet_AvgPD.GetXaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgPD.GetYaxis().SetTitle("Discharge Probability P_{D}") gDet_AvgPD.GetYaxis().SetRangeUser(1e-11, 1e-6) gDet_AvgPD.SetMarkerStyle(21) gDet_AvgPD.Draw("AP") gDet_MaxPD.Draw("sameL") gDet_MinPD.Draw("sameL") #Write dir_Summary = self.FILE_OUT.GetDirectory("Summary") dir_Summary.cd() canv_AvgPD.Write() gDet_AvgPD.Write() gDet_MaxPD.Write() gDet_MinPD.Write() return
def plotGraph(self, x='vv', y='acc'): ''' Plot a graph with specified quantities on x and y axes , and saves the graph ''' if (x not in self.quantities.keys()) or (y not in self.quantities.keys()): raise RuntimeError('selected quantities not available, available quantities are: \n{}'.format(self.quantities.keys())) xq = self.quantities[x] yq = self.quantities[y] #graph = TGraphAsymmErrors() #graph = TGraph() graph = TGraphErrors() for i,s in enumerate(self.samples): graph.SetPoint(i,getattr(s, xq.name), getattr(s, yq.name) ) #if xq.err: # graph.SetPointEXhigh(i, getattr(s, xq.name+'_errup')) # errup errdn # graph.SetPointEXlow (i, getattr(s, xq.name+'_errdn')) if yq.err: graph.SetPointError(i, 0, getattr(s, yq.name+'_errup')) # graph.SetPointEYhigh(i, getattr(s, yq.name+'_errup')) # graph.SetPointEYlow (i, getattr(s, yq.name+'_errdn')) c = TCanvas() graph.SetLineWidth(2) graph.SetMarkerStyle(22) graph.SetTitle(';{x};{y}'.format(y=yq.title,x=xq.title)) graph.Draw('APLE') if yq.forceRange: graph.SetMinimum(yq.Range[0]) graph.SetMaximum(yq.Range[1]) gPad.Modified() gPad.Update() if yq.name=='expNevts': line = TLine(gPad.GetUxmin(),3,gPad.GetUxmax(),3) line.SetLineColor(ROOT.kBlue) line.Draw('same') #graph.SetMinimum(0.01) #graph.SetMaximum(1E06) if xq.log: c.SetLogx() if yq.log: c.SetLogy() c.SetGridx() c.SetGridy() c.SaveAs('./plots/{}{}/{}_{}VS{}.pdf'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.C'.format(self.label,suffix,self.name,yq.name,xq.name)) c.SaveAs('./plots/{}{}/{}_{}VS{}.png'.format(self.label,suffix,self.name,yq.name,xq.name)) self.graphs['{}VS{}'.format(yq.name,xq.name)] = graph # add the graph container for memory? graph_saver.append(graph)
def addErrors(err1, err2): from ROOT import TGraphErrors from math import sqrt newErrs = TGraphErrors(err1) for i in range(0, newErrs.GetN()): newErrs.SetPoint(i, newErrs.GetX()[i], err1.GetY()[i] + err2.GetY()[i]) newErrs.SetPointError(i, err1.GetErrorX(i), sqrt(err1.GetErrorY(i)**2 + \ err2.GetErrorY(i)**2) ) return newErrs
def plotGainSummary(self, strDetName): #Create the Plot - Average gDet_AvgEffGain = TGraphErrors( len(self.GAIN_AVG_POINTS) ) #gDet_AvgEffGain.SetName("g_" + strDetName + "_EffGainAvg") gDet_AvgEffGain.SetName("g_{0}_EffGainAvg".format(strDetName)) #Create the Plot - Max Gain gDet_MaxEffGain = TGraphErrors( len(self.GAIN_MAX_POINTS) ) #gDet_MaxEffGain.SetName("g_" + strDetName + "_EffGainMax") gDet_MaxEffGain.SetName("g_{0}_EffGainMax".format(strDetName)) #Create the Plot - Min Gain gDet_MinEffGain = TGraphErrors( len(self.GAIN_MIN_POINTS) ) #gDet_MinEffGain.SetName("g_" + strDetName + "_EffGainMin") gDet_MinEffGain.SetName("g_{0}_EffGainMin".format(strDetName)) #Set the points for i in range(0, len(self.GAIN_AVG_POINTS) ): #Average gDet_AvgEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_AVG_POINTS[i]) gDet_AvgEffGain.SetPointError(i,0,self.GAIN_STDDEV_POINTS[i]) #Max gDet_MaxEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MAX_POINTS[i]) #Min gDet_MinEffGain.SetPoint(i,self.DET_IMON_POINTS[i],self.GAIN_MIN_POINTS[i]) #Draw #canv_AvgEffGain = TCanvas("canv_" + strDetName + "_EffGainAvg",strDetName + " Average Effective Gain",600,600) canv_AvgEffGain = TCanvas("canv_{0}_EffGainAvg".format(strDetName),"{0} Average Effective Gain".format(strDetName),600,600) canv_AvgEffGain.cd() canv_AvgEffGain.cd().SetLogy() gDet_AvgEffGain.GetXaxis().SetTitle("HV") gDet_AvgEffGain.GetYaxis().SetTitle("#LT Effective Gain #GT") gDet_AvgEffGain.GetYaxis().SetRangeUser(1e2,1e6) gDet_AvgEffGain.SetMarkerStyle(21) gDet_AvgEffGain.Draw("AP") gDet_MaxEffGain.Draw("sameL") gDet_MinEffGain.Draw("sameL") #Write dir_Summary = self.FILE_OUT.mkdir("Summary") dir_Summary.cd() canv_AvgEffGain.Write() gDet_AvgEffGain.Write() gDet_MaxEffGain.Write() gDet_MinEffGain.Write() return
def Read1DGraphErrors(self, iline): """ Read 1D graph section """ ngraphs = self.GetNhist( self.lines[iline]) # graph and hist format is the same xarray = [] data = {} errors = {} for igraph in range(ngraphs): data[igraph] = [] errors[igraph] = [] for line in self.lines[iline + 1:]: line = line.strip() if line == '': break elif re.search("^#", line): continue words = line.split() xarray.append(float(words[0])) for igraph in range(ngraphs): data[igraph].append(float(words[(igraph + 1) * 2 - 1])) errors[igraph].append(float(words[(igraph + 1) * 2])) npoints = len(xarray) for igraph in range(ngraphs): if self.subtitles[igraph]: subtitle = ' - ' + self.subtitles[igraph] else: subtitle = '' self.FixTitles() g = TGraphErrors(npoints) # self.ihist+1 - start from ONE as in Angel - easy to compare g.SetNameTitle( "g%d" % (self.ihist + 1), "%s%s;%s;%s" % (self.title, subtitle, self.xtitle, self.ytitle)) self.ihist += 1 for i in range(npoints): x = xarray[i] y = data[igraph][i] ey = errors[igraph][i] g.SetPoint(i, x, y) g.SetPointError(i, 0, ey * y) self.histos.Add(g) del self.subtitles[:]
def getGraph(Ts, filename): lines = None with open(filename) as f1: lines = f1.readlines() Tx = None for line in lines: ### find the associated tamperature line = line.rstrip() if len(line) == 0: Tx = None continue if line[0] == '#': fs = line.split() data = fs[1] + ' ' + fs[2] b = parse(data) if b is None: continue for x in Ts: for y in x.Times: if b > y[0] and b < y[1]: Tx = x print b, Tx.T break if Tx is not None: break continue if Tx is None: continue ### Add the samples to it fs = line.split(',') if len(fs) < 3: continue Tx.data.append(float(fs[2])) gr1 = TGraphErrors() for t in Ts: if len(t.data) == 0: continue ### calculate the mean and err ### Fill in the tgraph print t.T, len(t.data), nm.mean(t.data), nm.std(t.data) i = gr1.GetN() gr1.SetPoint(i, t.T, nm.mean(t.data)) gr1.SetPointError(i, 0, nm.std(t.data)) return gr1
def tgraphNormError(self): """ returns a TGraphErrors object normalized to value=1.0 at the first data point""" if (len(self._data) == 0): print "***** Dataset.tgraphNormError(): ERROR: no data available for", self._algo + '_' + self._impl return TGraphErrors() result = TGraphErrors(len(self._data)) normFactor = 1. / self._data[0]._y i = 0 for k in self._data: normValue = k._y * normFactor if normValue < self._minvalue: self._minvalue = normValue if normValue > self._maxvalue: self._maxvalue = normValue #print "Normalizing %s: i=%d days=%d val=%f normFactor=%f stored=%f minVal=%f maxVal=%f" % (self._name, i, k, self.serie[k], normFactor, normValue, self._minvalue, self._maxvalue) result.SetPoint(i, k._x, normValue) result.SetPointError(i, 0, k._dy * normFactor) i = i + 1 return result
def createPull(theData, curve, curveUp=None, curveDown=None): from ROOT import TGraphErrors, TMath pullGraph = TGraphErrors(theData.GetN()) for datapt in range(0, theData.GetN()): binmin = theData.GetX()[datapt] - theData.GetEXlow()[datapt] binmax = theData.GetX()[datapt] + theData.GetEXhigh()[datapt] binN = theData.GetY()[datapt] * (binmax - binmin) curveN = curve.average(binmin, binmax) * (binmax - binmin) diffUp = 0. diffDown = 0. if curveUp and curveDown: diffUp = curveUp.average(binmin, binmax) * (binmax - binmin) - curveN diffDown = curveN - curveDown.average(binmin, binmax) * (binmax - binmin) if diffUp < 0: #print diffUp hold = diffDown diffDown = -1. * diffUp diffUp = -1. * diffDown if (binN > curveN): errN = TMath.Sqrt((theData.GetEYlow()[datapt]*(binmax-binmin))**2 \ + diffUp**2) else: errN = TMath.Sqrt((theData.GetEYhigh()[datapt]*(binmax-binmin))**2 \ + diffDown**2) pull = 0. if errN > 0: pull = (binN - curveN) / errN # print 'bin: (', binmin, ',', binmax, ') N:', binN, '+/-', errN, # print 'curve N:', curveN pullGraph.SetPoint(datapt, theData.GetX()[datapt], pull) pullGraph.SetPointError(datapt, 0., 1.) return pullGraph
def getGraph(self, filename): data = self.getData(filename) from ROOT import TFile, TTree, gDirectory, TGraphErrors, TCanvas from array import array nsteps = len(data) g = TGraphErrors(nsteps) ## Loop on the data for n,(fragsize,tp,tpE) in enumerate(data): g.SetPoint( n, fragsize, tp) g.SetPointError( n, 0., tpE) g.SetLineWidth(2) g.SetMarkerSize(1.7) return g
def tgraph(self): """ returns data points in a TGraphErrors object.""" if (len(self._data) == 0): print "***** Dataset.tgraph(): ERROR: no data available for", self._algo + '_' + self._impl return TGraphErrors() result = TGraphErrors(len(self._data)) i = 0 #for k in sorted(self._data.iterkeys()): for k in self._data: x = k._x y = k._y #if y < self._minvalue : self._minvalue = y #if y > self._maxvalue : self._maxvalue = y #print "raw %s %s %s: i=%d value=%f minVal=%f maxVal=%f" % (self._shape, self._algo, self._impl, i, k, self._minvalue, self._maxvalue) result.SetPoint(i, x, y) result.SetPointError(i, 0, k._dy) i = i + 1 return result
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("", "--spline3", action="store_true", dest="spline3", default=False) (options, args) = parser.parse_args() from ROOT import TFile, TGraph, TGraphErrors, NULL import csv with open(options.inputfile) as f: reader = csv.reader(f, delimiter=" ", skipinitialspace=True) rows = list(reader) outfile = TFile("%s.root" % options.inputfile, "RECREATE") g = TGraphErrors(len(rows)) for i, row in enumerate(rows): g.SetPoint(i, float(row[1]) / 1000., float(row[2])) g.SetPointError(i, 0.0, float(row[3])) if options.spline3: g_spline3 = TGraph(10 * (g.GetN() - 1)) x = g.GetX() y = g.GetY() for i in range(g.GetN() - 1): step = (x[i + 1] - x[i]) / 10 for j in range(10): index = 10 * i + j x_ = x[i] + j * step y_ = g.Eval(x_, NULL, "S") g_spline3.SetPoint(index, x_, y_) g_spline3.SetName(options.inputfile) g_spline3.Write() else: g.SetName(options.inputfile) g.Write() outfile.Close()
def getRatio(result, result2, label): masses = result["mass"] massErr = result["massErr"] sigma = result["sigma"] sigmaErr = result["sigmaErr"] masses2 = result2["mass"] massErr2 = result2["massErr"] sigma2 = result2["sigma"] sigmaErr2 = result2["sigmaErr"] ratio = TGraphErrors(len(masses)) ratio.SetName(label) for i, mass in enumerate(masses): ratio.SetPoint(i, mass, sigma[i] / sigma2[i]) ratio.SetPointError(i, massErr[i], (sigma[i] / sigma2[i]) * math.sqrt((sigmaErr[i] / sigma[i])**2 + (sigmaErr2[i] / sigma2[i])**2)) return ratio
def getResponseGraph(file): print "Read=", file i = 0 g1 = TGraphErrors() for line in open(file, "r"): columns = line.split(',') pt = float(columns[0]) pt_err = float(columns[1]) sigma = float(columns[2]) err = float(columns[3]) g1.SetPoint(i, pt, sigma) ex = pt_err ey = err g1.SetPointError(i, ex, ey) i = i + 1 g1.SetMarkerColor(1) g1.SetMarkerStyle(20) g1.SetMarkerSize(0.5) # g1->Print(); return g1
def getDeltaVarGraph(graph): #get number of points for the graph nPoints = graph.GetN() #prepare the final graph deltaVarGraph = TGraphErrors() deltaVarGraph.SetName(graph.GetName()) #loop on points of the graphs for iPoint in xrange(0, nPoints): #retrieve the point dataPointX = Double(0) dataPointY = Double(0) errorX = graph.GetErrorX(iPoint) errorY = graph.GetErrorY(iPoint) graph.GetPoint(iPoint, dataPointX, dataPointY) #subtract unity and do the absolute value dataPointXDeltaVar = dataPointX dataPointYDeltaVar = abs(1 - dataPointY) errorXDeltaVar = errorX deltaVarGraph.SetPoint(iPoint, dataPointXDeltaVar, dataPointYDeltaVar) #being lazy (we will truncate the error if it goes below zero anyways) errorYDeltaVar = errorY #to calculate the error correctly #if dataPointY != 0 and (dataPointY-1) > 0 : #errorYDeltaVar = sqrt((dataPointY-1)/abs(dataPointY-1) * errorY) #this guarantees one does not go negative spitting an exception #else #one here would need to do a TGraphAsymmErrors with only the positive error in full deltaVarGraph.SetPointError(iPoint, errorXDeltaVar, errorYDeltaVar) return deltaVarGraph
def HistToGraph(hist, xmin=None, xmax=None): """ Build a graph from a histogram. Optionally one can set the bin ranges @param hist: Histogram to build the graph from @param xmin: Minimum x for the x-range of the points @param xmax: Maximum x for the x-range of the points @return: A TGraphErrors created from the histogram """ output = TGraphErrors() npoints = 0 for mybin in range(1, hist.GetXaxis().GetNbins() + 1): if xmin and hist.GetXaxis().GetBinLowEdge(mybin) < xmin: continue if xmax and hist.GetXaxis().GetBinLowEdge(mybin) > xmax: break output.SetPoint(npoints, hist.GetXaxis().GetBinCenter(mybin), hist.GetBinContent(mybin)) output.SetPointError(npoints, hist.GetXaxis().GetBinWidth(mybin) / 2., hist.GetBinError(mybin)) npoints = npoints + 1 return output
def GetData(file, scale=1., sed=True, title='SED', barUL=True): GetData.Ng += 1 g = TGraphErrors(file) gUL = TGraphErrors() if sed: for i in range(g.GetN()): g.GetY()[i] = pow(g.GetX()[i], 2) * g.GetY()[i] * 1e-6 / scale g.GetEY()[i] = pow(g.GetX()[i], 2) * g.GetEY()[i] * 1e-6 / scale g.GetX()[i] *= 1e-3 idel = 0 nUL = 0 while idel < g.GetN(): if g.GetEY()[idel] < 0: gUL.SetPoint(nUL, g.GetX()[idel], g.GetY()[idel]) if barUL: gUL.SetPointError(nUL, 0, g.GetY()[idel] * 1e-5) nUL += 1 g.RemovePoint(idel) else: idel += 1 if sed: g.SetTitle(title + ";Energy [GeV];E^{2}dN/dE [TeV cm^{-2} s^{-1}]") else: g.SetTitle(title + ";Energy [MeV];dN/dE [cm^{-2} s^{-1} MeV^{-1}]") g.SetLineColor(kRed) g.SetMarkerColor(kRed) g.SetMarkerStyle(20) g.SetName("g%d" % GetData.Ng) gUL.SetLineColor(g.GetLineColor()) gUL.SetName("gUL%d" % GetData.Ng) return g, gUL
def _FitKuriePlot(self, centralList, kurieList, errorList): logger.debug("Fitter private method") kurieGraph = TGraphErrors() for i, KE in enumerate(centralList): kurieGraph.SetPoint(i, KE, kurieList[i]) kurieGraph.SetPointError(i, 0, errorList[i]) self.fitFunction = TF1("kurieFit", "[0]*([1]-x)*(x<[1]) + [2]", centralList[0], centralList[-1], 3) self.fitFunction.SetParameters(kurieList[0] / (18600 - centralList[0]), 18600, kurieList[-1]) rootResults = kurieGraph.Fit(self.fitFunction, 'MERS') resultsDict = { "amplitude": rootResults.Parameter(0), "err_amplitude": rootResults.ParError(0), "endpoint": rootResults.Parameter(1), "err_endpoint": rootResults.ParError(1), "background": rootResults.Parameter(2), "err_background": rootResults.ParError(2), "chi2": rootResults.Chi2(), "ndf": rootResults.Ndf(), "p-value": rootResults.Prob() } logger.debug("Fit done") return resultsDict