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
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 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 makeGraph(self, name='', xtitle='', ytitle=''): """This function returns an instance of ROOTs TGraphErrors, made with the points in from this class. Some of the graph's default settings are changed: - black points - every point has the symbol of 'x' - x- and y-axis are centered Arguments: name -- ROOT internal name of graph (default = '') xtitle -- title of x-axis (default = '') ytitle -- title of y-axis (default = '') """ if self.points: x = self.getX() y = self.getY() ex = self.getEX() ey = self.getEY() graph = TGraphErrors(self.getLength(), array.array('f', x), array.array('f', y), array.array('f', ex), array.array('f', ey)) graph.SetName(name) graph.SetMarkerColor(1) graph.SetMarkerStyle(5) graph.SetTitle("") graph.GetXaxis().SetTitle(xtitle) graph.GetXaxis().CenterTitle() graph.GetYaxis().SetTitle(ytitle) graph.GetYaxis().CenterTitle() return graph else: return None
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 evaluateResolutionVariation(model, bcid, prefix, suffix, vtxres, scaling, \ legend=False): from array import array from ROOT import TFile, TMultiGraph, TGraphErrors, gStyle, TCanvas, \ TLegend, TLatex names = [pre+'_'+model+'_'+bcid+'_'+suf for (pre, suf) in zip(prefix, \ suffix)] xVal = {name: array('d', [0.0]*len(vtxres)) for name in names} xErr = {name: array('d', [0.0]*len(vtxres)) for name in names} yVal = {name: array('d', [0.0]*len(vtxres)) for name in names} yErr = {name: array('d', [0.0]*len(vtxres)) for name in names} for name, scale in zip(names, scaling): for i, vr in enumerate(vtxres): f = TFile('results/'+name+'_'+vr+'.root') yVal[name][i] = f.Get('h_overlapInt').GetMean() * 100.0 yErr[name][i] = f.Get('h_integ').GetMeanError() * 100.0 xVal[name][i] = f.Get('h_vtxRes').GetMean() * scale * 1.0e4 multi = TMultiGraph('overlapIntegralBcid'+bcid, '') graphs = [] for i, name in enumerate(names): graph = TGraphErrors(len(vtxres), xVal[name], yVal[name], xErr[name], \ yErr[name]) graph.SetName(name) graph.SetMarkerStyle(20) graph.SetMarkerColor(1+i) multi.Add(graph) graphs.append(graph) gStyle.SetOptStat(0) canvas = TCanvas(model+'_'+bcid, '', 600, 600) multi.Draw('AP') canvas.Update() multi.GetXaxis().SetTitle('vertex resolution [#mum]') multi.GetXaxis().SetLabelSize(0.025) multi.GetXaxis().SetRangeUser(11, 69) multi.GetYaxis().SetTitle('overlap integral [a.u.]') multi.GetYaxis().SetLabelSize(0.025) multi.GetYaxis().SetRangeUser(0.77, 1.43) if legend: leg = TLegend(0.55, 0.15, 0.88, 0.3) leg.SetBorderSize(0) for i, name in enumerate(names): entry = leg.AddEntry(name, legend[i], 'P') entry.SetMarkerStyle(20) entry.SetMarkerColor(1+i) leg.Draw() drawCMS(wip=True) text = TLatex() text.SetNDC() text.SetTextFont(62) text.SetTextSize(0.04) text.SetTextAlign(21) text.DrawLatex(0.5, 0.92, 'Vertex Resolution Study: '+model+', BCID '+bcid) canvas.Modified() canvas.Update() canvas.SaveAs('plots/'+canvas.GetName()+'.pdf') canvas.SaveAs('plots/'+canvas.GetName()+'.C')
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 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 __init__(self, models, bcids, values, fill=4954, workinprogress=False): """Initialize a summary plot of values per model and bcid.""" nbcid, nmodels = len(bcids), len(models) order = sorted(range(nbcid), key=lambda i: bcids[i]) mini, maxi = 1.0e99, -1.0e99 multi = TMultiGraph('summary', '') for i, mod in enumerate(models): xval = array( 'd', [c + 0.09 * (i - 0.5 * nmodels) for c in range(nbcid)]) xerr = array('d', [0.0] * nbcid) yval = array('d', [values[i][j][0] for j in order]) yerr = array('d', [values[i][j][1] for j in order]) #[0.0]*nbcid) mini = min(mini, min([v - e for v, e in zip(yval, yerr)])) maxi = max(maxi, max([v + e for v, e in zip(yval, yerr)])) graph = TGraphErrors(nbcid, xval, yval, xerr, yerr) graph.SetName('summary_{0}'.format(mod)) multi.Add(graph) self._multi = multi mini, maxi = mini - 0.08 * (maxi - mini), maxi + 0.25 * (maxi - mini) hist = TH2F('axishist', '', nbcid, -0.5, nbcid - 0.5, 100, mini, maxi) for i, j in enumerate(order): hist.GetXaxis().SetBinLabel(i + 1, str(bcids[j])) SingleGraphBase.__init__(self, hist, 'summary', fill, workinprogress) for gr in multi.GetListOfGraphs(): self.add(gr, draw=False) self._xtitle = 'bcid' self._drawoption = 'AXIS' self.markers = [markers(i) for i in range(nmodels)] self.colors = [colors(i) for i in range(nmodels)] self.xrange(-0.5, nbcid - 0.5) self.yrange(mini, maxi)
def compareEEC( filename="sjm91_all.root", datafilename="../EECMC/share/OPAL/data.dat" ): f= TFile( filename ) ao= createAnalysisObservable( f, "EEC" ) tokens= datafilename.split( "/" ) exp= tokens[3] plotoptions= { "xmin": 0.0, "xmax": 3.14159, "ymin": 0.05, "ymax": 5.0, "markerStyle": 20, "markerSize": 0.5, "drawas": "3", "fillcolor": 6, "title": "EEC "+exp, "xlabel": "\chi\ [rad.]", "ylabel": "1/\sigma d\Sigma/d\chi", "logy": 1 } tgest, tgesy= ao.plot( plotoptions ) lines= [ line.rstrip( '\n' ) for line in open( datafilename ) ] n= len( lines ) points= TVectorD( n ) values= TVectorD( n ) errors= TVectorD( n ) perrs= TVectorD(n) grad2rad= 3.14159/180.0 for i in range( n ): line= (lines[i]).split() points[i]= float(line[0])*grad2rad values[i]= float(line[3]) errors[i]= float(line[4]) perrs[i]= 0.0 datatge= TGraphErrors( points, values, perrs, errors ) datatge.SetMarkerStyle( 20 ) datatge.SetMarkerSize( 0.5 ) datatge.Draw( "psame" ) legend= TLegend( 0.2, 0.7, 0.5, 0.85 ) datatge.SetName( "datatge" ); tgesy.SetName( "tgesy" ) legend.AddEntry( "datatge", exp+" data", "pe" ) legend.AddEntry( "tgesy", "OPAL "+filename, "f" ) legend.Draw() return
def Scale(graph, scale): if not graph: return ArrX = array('d') ArrY = array('d') ArrXErr = array('d') ArrYErr = array('d') for i in range(graph.GetN()): x = ROOT.Double(0) y = ROOT.Double(0) graph.GetPoint(i, x, y) ex = graph.GetErrorX(i) ey = graph.GetErrorY(i) ArrX.append(x) ArrY.append(y * scale) ArrXErr.append(ex) ArrYErr.append(ey * scale) retTG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr) retTG.SetName(graph.GetName()) retTG.SetTitle(graph.GetTitle()) return retTG
def make_tgrapherrors(name, title, color=1, marker=20, marker_size=1, width=1, asym_err=False, style=1, x=None, y=None): if (x and y) is None: gr = TGraphErrors() if not asym_err else TGraphAsymmErrors() else: gr = TGraphErrors(len(x), array(x, 'd'), array( y, 'd')) if not asym_err else TGraphAsymmErrors( len(x), array(x, 'd'), array(y), 'd') gr.SetTitle(title) gr.SetName(name) gr.SetMarkerStyle(marker) gr.SetMarkerColor(color) gr.SetLineColor(color) gr.SetMarkerSize(marker_size) gr.SetLineWidth(width) gr.SetLineStyle(style) 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 correctedCrossSectionsPlot(crossings, shapes, overDiff): uncorrected = {41: (3.2575816286, 0.00514858611944), \ 281: (3.26316215713, 0.00468789412223), \ 872: (3.27340775031, 0.00484925398906), \ 1783: (3.24986926821, 0.00460908436455), \ 2063: (3.26363843728, 0.0044071069983)} multi = TMultiGraph('sigmavis', '') graphs = [] n = len(shapes) + 1 for i, shape in enumerate([''] + list(shapes)): xval = array('d', [a + 0.08 * (i - 0.5 * n) for a in range(len(crossings))]) xerr = array('d', len(crossings) * [0]) yval = array('d', [uncorrected[int(bx)][0] for bx in crossings]) yerr = array('d', [uncorrected[int(bx)][1] for bx in crossings]) if shape: for j, bx in enumerate(crossings): yval[j] *= 1 + overDiff[shape][bx] yerr[j] *= 1 + overDiff[shape][bx] graph = TGraphErrors(len(crossings), xval, yval, xerr, yerr) graph.SetName('ge' + shape) graph.SetMarkerStyle(20) graph.SetMarkerColor(1 + i) multi.Add(graph) graphs.append(graph) gStyle.SetOptStat(0) hist = TH2F('hist', '', len(crossings), -0.5, len(crossings) - 0.5, 100, 3.23, 3.33) for i, bx in enumerate(crossings): hist.GetXaxis().SetBinLabel(i + 1, bx) canvas = TCanvas('c_' + multi.GetName(), '', 600, 600) hist.Draw('AXIS') multi.Draw('P') canvas.Update() hist.GetXaxis().SetLabelSize(0.035) hist.GetXaxis().SetNdivisions(len(crossings), False) hist.GetYaxis().SetTitle('#sigma_{vis} [b]') hist.GetYaxis().SetLabelSize(0.025) hist.GetYaxis().SetTitleOffset(1.3) leg = TLegend(0.15, 0.82, 0.85, 0.85) leg.SetNColumns(len(shapes) + 1) leg.SetBorderSize(0) for i, shape in enumerate([''] + list(shapes)): entry = leg.AddEntry('ge' + shape, shapeNames[shape], 'P') entry.SetMarkerStyle(20) entry.SetMarkerColor(1 + i) leg.Draw() drawCMS() canvas.Modified() canvas.Update() canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.pdf') canvas.SaveAs('summaryPlots/' + canvas.GetName() + '.C')
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 fit_slices(histo, x_range, x_bin_step, y_fit_range): x_start = histo.GetXaxis().FindBin(x_range[0]) x_stop = histo.GetXaxis().FindBin(x_range[1]) x_values = array('d') slices = [] fits = [] for i, x_bin in enumerate(range(x_start, x_stop + 1, x_bin_step)): projec = histo.ProjectionY(histo.GetTitle() + '_proj{}'.format(i), x_bin, x_bin + x_bin_step) fit = TF1(histo.GetTitle() + '_fit{}'.format(i), 'gaus') fit.SetTitle(histo.GetTitle() + '_fit{}'.format(i)) fit.SetName(histo.GetTitle() + '_fit{}'.format(i)) if y_fit_range: fit.SetParameter(1, 0.5 * (y_fit_range[0] + y_fit_range[1])) projec.Fit(fit, 'R', '', y_fit_range[0], y_fit_range[1]) slices.append(projec) fits.append(fit) x_low = histo.GetXaxis().GetBinCenter(x_bin) x_high = histo.GetXaxis().GetBinCenter(x_bin + x_bin_step) x_values.append(0.5 * (x_high + x_low)) means = array('d') means_err = array('d') stds = array('d') stds_err = array('d') zeros = array('d') for f in fits: means.append(f.GetParameter(1)) means_err.append(f.GetParError(1)) stds.append(f.GetParameter(2)) stds_err.append( f.GetParError(1)) ### change if want the sigma of dist. zeros.append(0.0) graph = TGraphErrors(len(x_values), x_values, means, zeros, stds_err) graph.SetName('g_' + histo.GetName()) graph.SetMarkerStyle(21) graph.SetMarkerColor(kRed) return graph, slices, fits
def plot( self, plotoptions, opt="?" ): vx= array( "d", self.aostand.getPointsCenter() ) values= self.values sterrs= self.sterrs if "m" in opt: print "AnalysisObservable::plot: use errors from error matrix" sterrs= array( "d", self.aostand.getErrors( "m" ) ) syerrs= self.syerrs npoints= len(vx) if "xshift" in plotoptions: for i in range(npoints): vx[i]+= plotoptions["xshift"] vex= array( "d", npoints*[0.0] ) tgest= TGraphErrors( npoints, vx, values, vex, sterrs ) toterrs= np.sqrt( np.add( np.square( sterrs ), np.square( syerrs ) ) ) tgesy= TGraphErrors( npoints, vx, values, vex, toterrs ) tgesy.SetMarkerStyle( plotoptions["markerStyle"] ) tgesy.SetMarkerSize( plotoptions["markerSize"] ) drawas= plotoptions["drawas"] if "drawas" in plotoptions else "p" tgesy.SetName( self.obs ) if "fillcolor" in plotoptions: tgesy.SetFillColor(plotoptions["fillcolor"]) tgest.SetFillColor(plotoptions["fillcolor"]) if "s" in opt: tgesy.Draw( "psame" ) else: if "title" in plotoptions: tgesy.SetTitle( plotoptions["title"] ) else: tgesy.SetTitle( self.obs ) tgesy.SetMinimum( plotoptions["ymin"] ) tgesy.SetMaximum( plotoptions["ymax"] ) xaxis= tgesy.GetXaxis() xaxis.SetLimits( plotoptions["xmin"], plotoptions["xmax"] ) if "xlabel" in plotoptions: xaxis.SetTitle( plotoptions["xlabel"] ) if "ylabel" in plotoptions: tgesy.GetYaxis().SetTitle( plotoptions["ylabel"] ) tgesy.Draw( "a"+drawas ) optlogx= plotoptions["logx"] if "logx" in plotoptions else 0 gPad.SetLogx( optlogx ) optlogy= plotoptions["logy"] if "logy" in plotoptions else 0 gPad.SetLogy( optlogy ) tgest.Draw( "same"+drawas ) return tgest, tgesy
def fit_slices(histo, x_range, x_bin_step): x_start = histo.GetXaxis().FindBin(x_range[0]) x_stop = histo.GetXaxis().FindBin(x_range[1]) x_values = array('d') slices = [] fits = [] for i, x_bin in enumerate(range(x_start, x_stop + 1, x_bin_step)): projec = histo.ProjectionY(histo.GetTitle() + '_proj{}'.format(i), x_bin, x_bin + x_bin_step) fmin = projec.GetMean() - 3 * projec.GetStdDev() fmax = projec.GetMean() + 3 * projec.GetStdDev() fit = TF1(histo.GetTitle() + '_fit{}'.format(i), 'gaus', fmin, fmax) fit.SetTitle(histo.GetTitle() + '_fit{}'.format(i)) fit.SetName(histo.GetTitle() + '_fit{}'.format(i)) projec.Fit(fit, 'R', '', fmin, fmax) print('Fitting in {},{}'.format(fmin, fmax)) slices.append(projec) fits.append(fit) x_low = histo.GetXaxis().GetBinCenter(x_bin) x_high = histo.GetXaxis().GetBinCenter(x_bin + x_bin_step) x_values.append(0.5 * (x_high + x_low)) means = array('d') means_err = array('d') stds = array('d') stds_err = array('d') zeros = array('d') for f in fits: means.append(f.GetParameter(1)) means_err.append(f.GetParError(1)) stds.append(f.GetParameter(2)) stds_err.append(f.GetParError(2)) zeros.append(0.0) graph = TGraphErrors(len(x_values), x_values, means, zeros, stds) graph.SetName('g_' + histo.GetName()) # return graph return np.array(x_values), np.array(means), np.array(stds), slices, fits
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 compareY23d( filename="sjm91_all.root", mtffilename=None, opt="m" ): if mtffilename == None: ecm= ecmFromFilename( filename ) mtffilename= "mtford-y23d"+ecm+".txt" arrays= ascii2arrays( mtffilename ) mtfordpointsl= arrays[0] mtfordpointsr= arrays[1] mtfordpoints= np.divide( np.add( arrays[0], arrays[1] ), 2.0 ) mtfordvalues= arrays[2] mtfordsterrs= arrays[3] mtfordsyerrs= arrays[4] mtforderrs= np.sqrt( np.add( np.square( mtfordsterrs ), np.square( mtfordsyerrs ) ) ) if filename=="sjm133.root": f1= TFile( "sjm130.root" ) ao1= createAnalysisObservable( f1, "durhamymerge23" ) f2= TFile( "sjm136.root" ) ao2= createAnalysisObservable( f2, "durhamymerge23" ) ao= combineAnalysisObservables( [ ao1, ao2 ] ) else: f= TFile( filename ) ao= createAnalysisObservable( f, "durhamymerge23" ) npoints= len( mtfordpoints ) vex= array( "d", npoints*[0.0] ) tgest= TGraphErrors( npoints, mtfordpoints, mtfordvalues, vex, mtfordsterrs ) tgetot= TGraphErrors( npoints, mtfordpoints, mtfordvalues, vex, mtforderrs ) plotoptions= { "xmin": 0.0003, "xmax": 0.5, "ymin": 0.5, "ymax": 500.0, "markerStyle": 20, "markerSize": 0.75, "title": "Durham y23 "+filename, "xlabel": "y_{23}", "ylabel": "1/\sigma d\sigma/dy_{23}", "logx":1, "logy":1 } ao.plot( plotoptions, opt ) tgetot.SetMarkerStyle( 24 ) tgetot.SetMarkerSize( 1.25 ) tgetot.SetName( "mtford" ) tgetot.Draw( "psame" ) tgest.Draw( "psame" ) tl= TLegend( 0.7, 0.9, 0.7, 0.9 ) tl.AddEntry( "mtford", "M.T. Ford thesis", "ep" ) tl.AddEntry( "durhamymerge23", "sjmanalysis", "ep" ) tl.Draw() return
def killXErr(graph): if not graph: return ArrX = array('d') ArrY = array('d') ArrXErr = array('d') ArrYErr = array('d') for point in range(graph.GetN()): ArrX.append(graph.GetX()[point]) ArrY.append(graph.GetY()[point]) ArrXErr.append(0) ArrYErr.append(graph.GetEY()[point]) tmpG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr) tmpG.SetName(graph.GetName() + "_noErr") tmpG.SetTitle(graph.GetTitle()) tmpG.GetXaxis().SetTitle(graph.GetXaxis().GetTitle()) tmpG.GetYaxis().SetTitle(graph.GetYaxis().GetTitle()) #tmpG.Write() return tmpG
def compareThrust( filename="sjm91_all.root", mtffilename=None ): if mtffilename == None: ecm= ecmFromFilename( filename ) mtffilename= "mtford-thrust"+ecm+".txt" arrays= ascii2arrays( mtffilename ) mtfordvalues= arrays[2] mtfordsterrs= arrays[3] mtfordsyerrs= arrays[4] mtforderrs= np.sqrt( np.add( np.square( mtfordsterrs ), np.square( mtfordsyerrs ) ) ) if filename=="sjm133.root": # f1= TFile( "sjm130.root" ) # aothrust1= createAnalysisObservable( f1, "thrust" ) # f2= TFile( "sjm136.root" ) # aothrust2= createAnalysisObservable( f2, "thrust" ) # aothrust= combineAnalysisObservables( [ aothrust1, aothrust2 ] ) aothrust= createCombineAnalysisObservables( ( "sjm130.root", "sjm136.root" ), "lepthrust" ) else: f= TFile( filename ) aothrust= createAnalysisObservable( f, "lepthrust" ) vx= array( "d", aothrust.aostand.getPointsCenter() ) npoints= len(vx)-1 vex= array( "d", npoints*[0.0] ) tgethrustst= TGraphErrors( npoints, vx, mtfordvalues, vex, mtfordsterrs ) tgethrusttot= TGraphErrors( npoints, vx, mtfordvalues, vex, mtforderrs ) plotoptions= { "xmin": 0.0, "xmax": 0.5, "ymin": 0.2, "ymax": 30, "markerStyle": 20, "markerSize": 0.8, "title": "Thrust "+filename, "logy": 1, "xlabel": "1-T", "ylabel": "1/\sigma d\sigma/d(1-T)" } aothrust.plot( plotoptions ) tgethrusttot.SetMarkerStyle( 24 ) tgethrusttot.SetMarkerSize( 1.25 ) tgethrusttot.SetName( "mtford" ) tgethrusttot.Draw( "psame" ) tgethrustst.Draw( "psame" ) tl= TLegend( 0.6, 0.75, 0.85, 0.9 ) tl.AddEntry( "mtford", "M.T. Ford thesis", "ep" ) tl.AddEntry( "thrust", "sjmanalysis", "ep" ) tl.Draw() return
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 SumGraphs(g1, g2, name, title): nPoints = g1.GetN() if g1.GetN() != g2.GetN(): print "Mismatch in SumGraphs Points!" if g2.GetN() > nPoints: nPoints = g2.GetN() ArrX = array('d') ArrY = array('d') ArrXErr = array('d') ArrYErr = array('d') for gPoint in range(nPoints): if int(g1.GetX()[gPoint] * 1000) != int(g2.GetX()[gPoint] * 1000): print "Mismatch in X Values!" continue else: ArrX.append(g1.GetX()[gPoint]) if int(g1.GetEX()[gPoint] * 1000) != int(g2.GetEX()[gPoint] * 1000): print "Mismatch in X Error Values!" continue else: ArrXErr.append(g1.GetEX()[gPoint]) g1Y = ufloat(g1.GetY()[gPoint], g1.GetEY()[gPoint]) g2Y = ufloat(g2.GetY()[gPoint], g2.GetEY()[gPoint]) prod = g1Y * g2Y ArrY.append(prod.n) ArrYErr.append(prod.s) SumG = TGraphErrors(len(ArrX), ArrX, ArrY, ArrXErr, ArrYErr) SumG.SetName(name) SumG.SetTitle(title) return SumG
relEnergyErrorErrorVec.append( reso[3]/reso[0] ) small=1.e-5 c1.Divide(1,2,small,small) c1.cd(1) gPad.SetPad(small, 0.3, 1.-small, 1.-small) gPad.SetBottomMargin(small) labelSize=10 makerSize = 0.3 gStyle.SetEndErrorSize(0) gr = TGraphErrors( n, energyVec, recoEnergyVec, energyErrorVec, recoEnergyErrorVec ) gr.SetName('gr') gr.SetLineColor( 1 ) gr.SetLineWidth( 1 ) gr.SetLineStyle( 2 ) gr.SetMarkerColor( 2 ) gr.SetMarkerStyle( 20 ) gr.SetMarkerSize( makerSize ) textsize = labelSize/(gPad.GetWh()*gPad.GetAbsHNDC()) gr.SetTitle( '' ) gr.GetXaxis().SetTitle( 'E_{particle} (GeV)' ) gr.GetYaxis().SetTitle( 'E_{reco} (GeV)' ) gr.GetYaxis().SetTitleSize(textsize) gr.GetYaxis().SetLabelSize(textsize) gr.GetYaxis().SetTitleOffset(1.4) gr.GetYaxis().SetRangeUser(2, 100) gPad.SetLeftMargin(0.15)
store = HistoStore() models = [] with open("xsec_tmp2.txt", "rb") as f: reader = csv.reader(f, delimiter=" ", skipinitialspace=True) for row in reader: model = XsecParser(row) models.append(model) group = ModelGroup(models) for generator, group_generator in group.items(): for n, group_n in group_generator.items(): for icolor, (MD, models) in enumerate(group_n.items()): vsize = len(models) vx = TVectorD(vsize) vxsec = TVectorD(vsize) vex = TVectorD(vsize) vey = TVectorD(vsize) for i, m in enumerate(models): vx[i] = m.M vex[i] = 0.0 vxsec[i] = m.xsec vey[i] = m.xsecErr g = TGraphErrors(vx, vxsec, vex, vey) g.SetName("%s-MD%.1f_n%d-xsec" % (generator, MD, n)) store.book(g) store.saveAs("xsec_tmp2.root")
def getPlotRatio(plotNum, plotDen, doAverage): DataPointsForAverage = [] ErrorsForAverage = [] averageDelta = 0 maxDelta = 0 nPointsNum = plotNum.GetN() nPointsDen = plotDen.GetN() if nPointsNum != nPointsDen: print "Plots don't have the same number of points!" return (0, 0, 0) plotRatio = TGraphErrors() plotRatio.SetName(plotNum.GetName()) x1 = Double(0) y1 = Double(0) x2 = Double(0) y2 = Double(0) dx1 = Double(0) dx2 = Double(0) dy1 = Double(0) dy2 = Double(0) iv = int(0) dx = Double(0) for pointNum in xrange(0, nPointsNum): pointNum = int(pointNum) matchcount = 0 for pointDen in xrange(0, nPointsDen): pointDen = int(pointDen) plotNum.GetPoint(pointNum, x1, y1) plotDen.GetPoint(pointDen, x2, y2) dx1 = plotNum.GetErrorX(pointNum) dx2 = plotNum.GetErrorX(pointDen) emean = (dx1 + dx2) / 2. if fabs(x1 - x2) >= emean and fabs(x1 - x2) > dx: pass #print "no idea what's going on here" else: matchcount = matchcount + 1 dx1 = plotNum.GetErrorX(pointNum) if y1 != 0: dy1 = plotNum.GetErrorY(pointNum) / y1 if y2 != 0: dy2 = plotNum.GetErrorY(pointDen) / y2 if y2 != 0: plotRatio.SetPoint(iv, x1, y1 / y2) if doAverage: DataPointsForAverage.append(y1 / y2) else: plotRatio.SetPoint(iv, x1, y2) if doAverage: DataPointsForAverage.append(y2) e = Double(0) if y1 != 0 and y2 != 0: e = sqrt(dy1 * dy1 + dy2 * dy2) * (y1 / y2) plotRatio.SetPointError(iv, dx1, e) if doAverage: ErrorsForAverage.append(e) iv = iv + 1 if (matchcount > 1): print "too many x points matched!" return (0) if doAverage: averageDelta = getAverageDelta(DataPointsForAverage, ErrorsForAverage) maxDelta = getMaxDelta(DataPointsForAverage, ErrorsForAverage) return plotRatio, averageDelta - 1, maxDelta
efffunc.FixParameter(0, 1.0) s = sliceeff.Fit(efffunc, "S") sliceeff.Draw("AP") #c.Print(outfilename+".pdf"); if s.Get() and s.Get().IsValid() and s.Get().CovMatrixStatus() == 3: massArr.append(cleanhist.GetYaxis().GetBinCenter(iy)) zeroArr.append(0) xintArr.append(s.Parameter(1)) yintArr.append(s.Parameter(0)) xintErrArr.append(s.ParError(1)) yintErrArr.append(s.ParError(0)) xintgraph = TGraphErrors(len(massArr), massArr, xintArr, zeroArr, xintErrArr) xintgraph.SetTitle("X-intercept;mass [GeV];D1") xintgraph.SetName("xintgraph") xintgraph.Write() xintgraph.Draw("A*") xintgraph.GetYaxis().SetRangeUser(0, 1000) xintgraph.Fit("pol3") c.Print(outfilename + ".pdf") yintgraph = TGraphErrors(len(massArr), massArr, yintArr, zeroArr, yintErrArr) yintgraph.Draw("A*") yintgraph.GetYaxis().SetRangeUser(0.5, 1.5) c.Print(outfilename + ".pdf") #clean.Draw("D1>>cleanslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2)) #cleanslice = gDirectory.Get("cleanslice") #messyclean.Draw("D1>>messyslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2)) #messyslice = gDirectory.Get("messyslice")
class GlobBeamSpotRunPlots: def __init__(self,run): self.run = run self.hFitWidth = TH1I("run_"+ str(self.run)+"_hFitWidth","Run:" + str(self.run) + " Is Fitted Width", 10,0,10) self.hOnline = TH1I("run_"+ str(self.run)+"_hOnline" ,"Run:" + str(self.run) + " Is Online", 10,0,10) self.hStatus = TH1I("run_"+ str(self.run)+"_hStatus" ,"Run:" + str(self.run) + " Status", 10,0,10) self.AlgType = TH1I("run_"+ str(self.run)+"_hAlgType" ,"Run:" + str(self.run) + " Alg Type", 10,0,10) self.hPosX = TH1D("run_"+ str(self.run)+"_hPosX" ,"Run:" + str(self.run)+ "Beamspot x-positon; x [mm]; events ", 100,-5,5) self.hPosY = TH1D("run_"+ str(self.run)+"_hPosY" ,"Run:" + str(self.run)+ "Beamspot y-positon; y [mm]; events ", 100,-5,5) self.hPosZ = TH1D("run_"+ str(self.run)+"_hPosZ" ,"Run:" + str(self.run)+ "Beamspot z-positon; z [mm]; events ", 100,-50,50) self.hSigmaX = TH1D("run_"+ str(self.run)+"_hSigmaX" ,"Run:" + str(self.run)+ "Beamspot #sigma_x; #sigma_x [mm]; events ", 100,0,1) self.hSigmaY = TH1D("run_"+ str(self.run)+"_hSigmaY" ,"Run:" + str(self.run)+ "Beamspot #sigma_y; #sigma_y [mm]; events ", 100,0,1) self.hSigmaZ = TH1D("run_"+ str(self.run)+"_hSigmaZ" ,"Run:" + str(self.run)+ "Beamspot #sigma_z; #sigma_z [mm]; events ", 100,0,50) self.hTiltX = TH1D("run_"+ str(self.run)+"_hTilitX" ,"Run:" + str(self.run)+ "Beamspot tilt_x; tilt_x [rad]; events ", 100,-0.01,0.01) self.hTiltY = TH1D("run_"+ str(self.run)+"_hTilitY" ,"Run:" + str(self.run)+ "Beamspot tilt_y; tilt_y [rad]; events ", 100,-0.01,0.01) self.lbMid = [] self.lbEr = [] self.lbX = [] self.lbSX = [] self.lbY = [] self.lbSY = [] self.lbZ = [] self.lbSZ = [] def fill(self, beamspot): (status, online, fitWidth, alg) = getStatus(beamspot.status) self.hFitWidth.Fill(fitWidth,1) self.hOnline.Fill(online,1) self.AlgType.Fill(alg,1) self.hStatus.Fill(status,1) self.hPosX.Fill(beamspot.posX) self.hPosY.Fill(beamspot.posY) self.hPosZ.Fill(beamspot.posZ) self.hSigmaX.Fill(beamspot.sigmaX) self.hSigmaY.Fill(beamspot.sigmaY) self.hSigmaZ.Fill(beamspot.sigmaZ) self.hTiltX.Fill(beamspot.tiltX) self.hTiltY.Fill(beamspot.tiltY) (run,lb) = getRunLumi(beamspot.begin) (runE,lbE) = getRunLumi(beamspot.end) self.lbMid.append(0.5*( lb + lbE )) self.lbEr.append( 0.5*(lb - lbE)) self.lbX.append( beamspot.posX ) self.lbSX.append( beamspot.sigmaX) self.lbY.append( beamspot.posY ) self.lbSY.append( beamspot.sigmaY) self.lbZ.append( beamspot.posZ) self.lbSZ.append( beamspot.sigmaZ) def display(self): self.c = TCanvas("run_"+ str(self.run)) self.c.Divide(4,4) self.c.cd(1) self.hStatus.Draw() self.c.cd(2) self.hOnline.Draw() self.c.cd(3) self.hFitWidth.Draw() self.c.cd(4) self.AlgType.Draw() self.c.cd(5) self.hPosX.Draw() self.c.cd(9) self.hPosY.Draw() self.c.cd(13) self.hPosZ.Draw() self.c.cd(6) self.hSigmaX.Draw() self.c.cd(10) self.hSigmaY.Draw() self.c.cd(14) self.hSigmaZ.Draw() self.c.cd(7) self.hTiltX.Draw() self.c.cd(11) self.hTiltY.Draw() self.c.cd(8) self.gx.Draw("ap") self.c.cd(12) self.gy.Draw("ap") self.c.cd(16) self.gz.Draw("ap") def makeGraphs(self): nPoints = len(self.lbMid) print "N points", nPoints from ROOT import TGraphErrors self.gx = TGraphErrors(nPoints) self.gx.SetTitle("x-position and width; lb; x [mm]") self.gx.SetName("gr_run_"+str(self.run)+"_x") self.gy = TGraphErrors(nPoints) self.gy.SetTitle("y-position and width; lb; y [mm]") self.gy.SetName("gr_run_"+str(self.run)+"_y") self.gz = TGraphErrors(nPoints) self.gz.SetTitle("z-position and width; lb; z [mm]") self.gz.SetName("gr_run_"+str(self.run)+"_z") for i,lb in enumerate(self.lbMid): self.gx.SetPoint(i,lb, self.lbX[i]) self.gx.SetPointError(i,self.lbEr[i], self.lbSX[i]) self.gy.SetPoint(i,lb, self.lbY[i]) self.gy.SetPointError(i,self.lbEr[i], self.lbSY[i]) self.gz.SetPoint(i,lb, self.lbZ[i]) self.gz.SetPointError(i,self.lbEr[i], self.lbSZ[i])