def fitAngularDistribution(h, store=True): """ Fit the angular distribution function to the histogram. If store is set to True, the fitresult pointer is stored in the current TFile. """ from ROOT import TF2, TFitResult W = TF2( "Wcosthphi", "[0] * (" "1.0 + [1]*x[0]*x[0] + [2]*(1.0-x[0]*x[0])*cos(2*x[1]*0.0174532925)" "+ [3]*2*x[0]*sqrt(1-x[0]*x[0])*cos(x[1]*0.0174532925)" ")", -1.0, 1.0, -180.0, 180.0) W.SetParameters(1.0, 0.0, 0.0, 0.0) fitRlt = h.Fit(W, "S") if int(fitRlt) == 0: # 0 indicates succesful fit fitRlt.SetName("_".join([h.GetName(), "Wcosthphi_rlt"])) if store: fitRlt.Write() return { "lth": [fitRlt.Parameter(1), fitRlt.Error(1)], "lph": [fitRlt.Parameter(2), fitRlt.Error(2)], "ltp": [fitRlt.Parameter(3), fitRlt.Error(3)] } else: print("Fit returned status {} for histogram {}".format( int(fitRlt), h.GetName())) return {"lth": [-999, 999], "lph": [-999, 999], "ltp": [-999, 999]}
def TF2_Fit_NKG(h2,N0,r0,s0,x0,y0,x_min,x_max,y_min,y_max): fitf2= TF2('fitf2',func_nkg_show,x_min,x_max,y_min,y_max,5) fitf2.SetParameter(0,N0) # Setting starting values (Ne) fitf2.SetParameter(1,r0) # ,, ,, (r_M) fitf2.SetParameter(2,s0) # ,, ,, (s) fitf2.SetParameter(3,x0) # ,, ,, (x_core) fitf2.SetParameter(4,y0) # ,, ,, (y_core) #//fitf2->SetParLimits(1,10,300) ; //Setting r_M limits fitf2.SetParLimits(1,r0,r0)# //Setting r_M limits #//fitf2->SetParLimits(2,1,2.5) ; //Setting Age limits (keeping fixed) fitf2.SetParLimits(2,s0,s0)# //Setting Age limits (Keeping fixed) h2.Fit(fitf2,"Q0") #h2SetXTitle("X (m)") ; #h2->GetXaxis()->CenterTitle() ; #h2->SetYTitle("Y (m)") ; #h2->GetYaxis()->CenterTitle() ; #//h2->Draw("HIST") ; #//fitf2->DrawCopy("surf1 same"); #gStyle->SetOptFit(1111) ; Ne_fit=fitf2.GetParameter(0) rM_fit=fitf2.GetParameter(1) s_fit=fitf2.GetParameter(2) x_core_fit=fitf2.GetParameter(3) y_core_fit=fitf2.GetParameter(4) x_core_fit_err=fitf2.GetParError(3) y_core_fit_err=fitf2.GetParError(4) fitter=TVirtualFitter.GetFitter() corMatrix=np.zeros([5,5]) sig_i=0 sig_j=0 cov_ij=0 for i in np.arange(4): sig_i=np.sqrt(fitter.GetCovarianceMatrixElement(i,i)) for j in np.arange(4): sig_j=np.sqrt(fitter.GetCovarianceMatrixElement(j,j)) cov_ij=fitter.GetCovarianceMatrixElement(i,j) corMatrix[i][j]=cov_ij/(sig_i*sig_j) if(sig_i==0 or sig_j==0): corMatrix[i][j]=0 corCoef_xy=corMatrix[1][2] #Correlation coeff. between the x & y core position return Ne_fit,rM_fit,s_fit,x_core_fit,y_core_fit,x_core_fit_err,y_core_fit_err, corCoef_xy
def normalize(self): # Normalize the efficiency funtion try: self.norm = 1.0 / self.TF1.GetMaximum(0.0, 0.0) except ZeroDivisionError: self.norm = 1.0 self.TF1.SetParameter(0, self.norm) normfunc = TF2("norm_" + hex(id(self)), "[0]*y") normfunc.SetParameter(0, self.norm) self.TGraph.Apply(normfunc)
def fit_arrival_direction(detectors,event): #print 'fit arrival direction' plane=TH2F("Shower plane","",1000,-500,500,1000,-500,500) for i in np.arange(LORA.nDetA): if detectors[i].cdt>=0: plane.SetBinContent(plane.GetXaxis().FindBin(detectors[i].x_cord),plane.GetYaxis().FindBin(detectors[i].y_cord),detectors[i].cdt) fit_plane= TF2("fit_plane",func_plane,-500,500,-500,500,3) fit_plane.SetParameter(0,100) ; fit_plane.SetParameter(1,0.2) ; fit_plane.SetParameter(2,0.2) ; fit_plane.SetParLimits(1,-1,1) ; fit_plane.SetParLimits(2,-1,1) ; plane.Fit(fit_plane,"Q0") ; t0=fit_plane.GetParameter(0) l=fit_plane.GetParameter(1) m=fit_plane.GetParameter(2) n=np.sqrt(1.0-(l*l+m*m)) err_l=fit_plane.GetParError(1) err_m=fit_plane.GetParError(2) theta=(np.arcsin(np.sqrt(l*l+m*m)))*(180.0/np.pi)#//Zenith in degrees (from vertical direction +Z) phi=(np.arccos(m/np.sqrt(l*l+m*m)))*(180.0/np.pi)# ; //in degrees (Eastward from North) if(l<0): phi=360.0-phi err_theta=np.sqrt(np.power(l*err_l/(n*n),2)+np.power(m*err_m/(n*n),2))/np.tan(theta*np.pi/180.0) err_theta=err_theta*(180.0/np.pi) df_f2=np.power((l*l)/(m*(l*l+m*m)),2)*np.power(err_m,2)+np.power(l/(l*l+m*m),2)*np.power(err_l,2) err_phi=np.sqrt(df_f2/np.power(np.tan(phi*np.pi/180.0),2)) err_phi=err_phi*(180.0/np.pi) if phi>360.0: phi=phi=360 if math.isnan(theta)==True or math.isnan(phi)==True: event.fit_theta=event.theta event.fit_phi=event.phi event.fit_elevation=90.0-theta event.fit_theta_err=err_theta event.fit_elevation_err=err_theta event.fit_phi_err=err_phi print('fitting doesn\'t work') else: event.fit_theta=theta event.fit_phi=phi event.fit_elevation=90.0-theta event.fit_theta_err=err_theta event.fit_elevation_err=err_theta event.fit_phi_err=err_phi print('fit theta: {0:.2f} phi: {1:.2f} '.format(theta,phi,err_theta,err_phi))
def total_fit(N1, N2, N3, N4): # fit_func = "[12]*[0]*exp((-(x-[1])**2)/(2*[2]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[13]*[0]*exp((-(x-[1])**2)/(2*[2]))*([9]+[10]*y+[11]*y**2)+[14]*([3]+[4]*x+[5]*x**2)*[6]*exp((-(y-[7])**2)/(2*[8]))+[15]*([3]+[4]*x+[5]*x**2)*([9]+[10]*y+[11]*y**2)" # fit_func = "[12]*[0]*exp((-(x-[1])**2)/(2*[2]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[13]*[0]*exp((-(x-[1])**2)/(2*[2]))*[9]*exp((-(y-[10])**2)/(2*[11]))+[14]*[3]*exp((-(x-[4])**2)/(2*[5]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[15]*[3]*exp((-(x-[4])**2)/(2*[5]))*[9]*exp((-(y-[10])**2)/(2*[11]))" gauss = "(%f*exp(-0.5*((x - [0])/[1])**2))" % N1 pol = "(%f + [2] * x + [3] * x**2)" % N3 gauss_not = "(%f*exp(-0.5*((y - [4])/[5])**2))" % N2 pol_not = "(%f + [6] * y + [7] * y**2)" % N4 fit_func = ( "+[8] *" + gauss + "*" + gauss_not + "+[9] *" + gauss + "*" + pol_not + "+[10]*" + pol + "*" + gauss_not + "+[11]*" + pol + "*" + pol_not) total_fit = TF2("total_fit", fit_func, 1.8, 1.92, 1.8, 1.92) return total_fit
def __init__(self, model, adc_east, adc_west): self.model = model self.adc_east = adc_east self.adc_west = adc_west self.adc_min = 10 self.adc_max = 400 #2D pdf self.pdf = TF2("pdf", self.pdf_eval2D, self.adc_min, self.adc_max, self.adc_min, self.adc_max) self.pdf.SetNpx(100) self.pdf.SetNpy(100) #pdf.GetXaxis().SetTitle("x") #1D pdf east self.pdf_east = TF1("pdf_east", self.pdf_eval_east, self.adc_min, self.adc_max) self.pdf_east.SetNpx(1000)
def normalize(self): # Normalize the efficiency function try: self.norm = 1.0 / exp( self.TF1.GetMaximum(min([p[0] for p in self._fitInput]), max([p[0] for p in self._fitInput]))) except ZeroDivisionError: self.norm = 1.0 self.TF1.SetParameter(0, self.norm) normfunc = TF2("norm_" + hex(id(self)), "[0]*y") normfunc.SetParameter(0, self.norm) self.TGraph.Apply(normfunc)
def min_par_fit(p1_0, p1_1, p1_2, p2_0, p2_1, p2_2, p3_0, p3_1, p3_2, p4_0, p4_1, p4_2): # fit_func = "[12]*[0]*exp((-(x-[1])**2)/(2*[2]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[13]*[0]*exp((-(x-[1])**2)/(2*[2]))*([9]+[10]*y+[11]*y**2)+[14]*([3]+[4]*x+[5]*x**2)*[6]*exp((-(y-[7])**2)/(2*[8]))+[15]*([3]+[4]*x+[5]*x**2)*([9]+[10]*y+[11]*y**2)" # fit_func = "[12]*[0]*exp((-(x-[1])**2)/(2*[2]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[13]*[0]*exp((-(x-[1])**2)/(2*[2]))*[9]*exp((-(y-[10])**2)/(2*[11]))+[14]*[3]*exp((-(x-[4])**2)/(2*[5]))*[6]*exp((-(y-[7])**2)/(2*[8]))+[15]*[3]*exp((-(x-[4])**2)/(2*[5]))*[9]*exp((-(y-[10])**2)/(2*[11]))" gauss = "(%f*exp(-0.5*((x - %f)/%f)**2))" % (p1_0, p1_1, p1_2) pol = "(%f + %f * x + %f * x**2)" % (p2_0, p2_1, p2_2) gauss_not = "(%f*exp(-0.5*((y - %f)/%f)**2))" % (p3_0, p3_1, p3_2) pol_not = "(%f + %f * y + %f * y**2)" % (p4_0, p4_1, p4_2) fit_func = ( "+[0] *" + gauss + "*" + gauss_not + "+[1] *" + gauss + "*" + pol_not + "+[2]*" + pol + "*" + gauss_not + "+[3]*" + pol + "*" + pol_not) total_fit = TF2("total_fit", fit_func, 1.64, 2.1, 1.64, 2.1) return total_fit
def test_random_sample(): funcs = [ TF1("f1", "TMath::DiLog(x)"), TF2("f2", "sin(x)*sin(y)/(x*y)"), TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)"), ] hists = [ TH1D("h1", "h1", 10, -3, 3), TH2D("h2", "h2", 10, -3, 3, 10, -3, 3), TH3D("h3", "h3", 10, -3, 3, 10, -3, 3, 10, -3, 3), ] for i, hist in enumerate(hists): hist.FillRandom(funcs[i].GetName()) for obj in funcs + hists: yield check_random_sample, obj
def get_fit_fcn_1d(histo): fit_fcn = TF2( "expo1", "[0]*exp(-[1] - [2]*x + 0*y)", histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax(), histo.GetYaxis().GetXmin(), histo.GetYaxis().GetXmax(), ) fit_fcn.SetNpx(histo.GetNbinsX()) fit_fcn.SetNpy(histo.GetNbinsY()) fit_fcn.SetParameter(0, 1000) fit_fcn.SetParameter(1, 1) fit_fcn.SetParameter(2, 0.2) return fit_fcn
def get_fit_fcn_1(): fit_fcn = TF2( "mjj_avg_fcn", "[0]*(1-x/13000)^[1]*(x/13000)^([2] + [3]*log(x/13000))*" + "(1-y/13000)^[4]*(y/13000)^([5] + [6]*log(y/13000))", *(mj_fit_range + mjj_fit_range)) fit_fcn.SetParameter(0, 5000) fit_fcn.SetParameter(1, 15) fit_fcn.SetParameter(2, -4) fit_fcn.SetParameter(3, -1) fit_fcn.SetParameter(4, 15) fit_fcn.SetParameter(5, -4) fit_fcn.SetParameter(6, -1) return fit_fcn
def get_fit_fcn(histo, args): fit_fcn = TF2( "expo2", args.formula, histo.GetXaxis().GetXmin(), histo.GetXaxis().GetXmax(), histo.GetYaxis().GetXmin(), histo.GetYaxis().GetXmax(), ) fit_fcn.SetNpx(histo.GetNbinsX()) fit_fcn.SetNpy(histo.GetNbinsY()) fit_fcn.SetParameter(0, 1000) fit_fcn.SetParameter(1, 1) fit_fcn.SetParameter(2, 0.2) fit_fcn.SetParameter(3, 0.2) return fit_fcn
def fitReferenceMap(rapBin, ptBin, histfile): """ Fit the reference map of the rapidity and pt bin and return the fit result """ f = TF2( "fcosthphi", "[0]*(1.+[1]*x[0]*x[0]+[2]*(1.-x[0]*x[0])*cos(2.*x[1]*0.0174532925)+[3]*2.*x[0]*sqrt(1.-x[0]*x[0])*cos(x[1]*0.0174532925))", -1.0, 1.0, -180.0, 180.0) f.SetParameters(1.0, 0.0, 0.0, 0.0) histname = "".join(["cosThPhi_refMap_rap", str(rapBin), "_pt", str(ptBin)]) h = histfile.Get(histname) h.Fit(f) return { "lth": [f.GetParameter(1), f.GetParError(1)], "lph": [f.GetParameter(2), f.GetParError(2)], "ltp": [f.GetParameter(3), f.GetParError(3)] }
def get_fit_fcn_2(): fit_fcn = TF2( "mjj_avg_fcn", "[0]*(1-y/13000)^([1]*(x/13000) + [2])*(y/13000)^([3]*(x/13000) + [4] + ([5]*(x/13000) + [6])*log(y/13000))", *(mj_fit_range + mjj_fit_range)) fit_fcn.SetParameter(0, 5000) # This was param [1] fit_fcn.SetParameter(1, 3000) fit_fcn.SetParameter(2, 6) # This was param [2] fit_fcn.SetParameter(3, -350) fit_fcn.SetParameter(4, -2.5) # This was param [3] fit_fcn.SetParameter(5, -250) fit_fcn.SetParameter(6, 1) return fit_fcn
def get_fit_fcn_1b(): fit_fcn = TF2( "mjj_avg_fcn", "[0]*(1-x/200)^([1] + [2]*log(1-x/200))*(x/200)^([3] + [4]*log(x/200))*" + "(1-y/4000)^([5] + [6]*log(1-y/4000))*(y/4000)^([7] + [8]*log(y/4000))", *(mj_fit_range + mjj_fit_range)) fit_fcn.SetParameter(0, 10000) fit_fcn.SetParameter(1, 19) fit_fcn.SetParameter(2, .1) fit_fcn.SetParameter(3, -4) fit_fcn.SetParameter(4, -1) fit_fcn.SetParameter(5, 20) fit_fcn.SetParameter(6, .1) fit_fcn.SetParameter(7, -2.5) fit_fcn.SetParameter(8, -1) return fit_fcn
def get_flux_ratio(self, dim, show=False, redo=False): # dim -> [x1, x2, y1, y2] in mm tel = [ c - s / 2 for c in self.Ana.find_center() for s in mean(self.Run.get_mask_dims(mm=True), axis=0) * [1, -1] ] h = self.Ana.draw_hitmap(.7, show=show, prnt=False, redo=redo) f = TF2('ff', 'xygaus') fx, fy = self.Ana.Tracks.fit_beam_profile( h.ProjectionX()), self.Ana.Tracks.fit_beam_profile(h.ProjectionY()) f.SetParameters(1, *[i.n for i in fx], *[i.n for i in fy]) int_dim, int_tel = f.Integral(*[d.n for d in dim]), f.Integral(*tel) f.SetParameters(1, *[i.n + i.s for i in fx], *[i.n + i.s for i in fy]) int_dim, int_tel = ufloat( int_dim, abs(int_dim - f.Integral(*[d.n for d in dim]))), ufloat( int_tel, abs(int_tel - f.Integral(*tel))) ratio = (int_dim / prod(diff(dim)[[0, 2]])) / (int_tel / prod(diff(tel)[[0, 2]])) return ufloat(ratio.n, ratio.s + .05 * ratio.n) # add 5% systematic uncertainty
def invert_col(pad, fgcol=rt.kOrange - 3, bgcol=rt.kBlack): #set foreground and background color #fgcol = rt.kAzure #fgcol = rt.kGreen #fgcol = rt.kOrange-3 pad.SetFillColor(bgcol) pad.SetFrameLineColor(fgcol) next = TIter(pad.GetListOfPrimitives()) obj = next() while obj != None: #H1 if obj.InheritsFrom(TH1.Class()) == True: if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetFillColor(bgcol) if obj.GetMarkerColor() == rt.kBlack: obj.SetMarkerColor(fgcol) obj.SetAxisColor(fgcol, "X") obj.SetAxisColor(fgcol, "Y") obj.SetLabelColor(fgcol, "X") obj.SetLabelColor(fgcol, "Y") obj.GetXaxis().SetTitleColor(fgcol) obj.GetYaxis().SetTitleColor(fgcol) #Legend if obj.InheritsFrom(TLegend.Class()) == True: obj.SetTextColor(fgcol) #obj.SetFillStyle(1000) #obj.SetFillColor(fgcol) #obj.SetTextColor(bgcol) #ln = TIter(obj.GetListOfPrimitives()) #lo = ln.Next() #while lo != None: #if lo.GetObject() == None: #lo = ln.Next() #continue #if lo.GetObject().InheritsFrom(TH1.Class()) == True: #hx = lo.GetObject() #hx.SetFillColor(bgcol) #if hx.GetMarkerColor() == rt.kBlack: #hx.SetMarkerColor(fgcol) #hx.SetLineColor(fgcol) #pass #lo = ln.Next() #RooHist if obj.InheritsFrom(RooHist.Class()) == True: if obj.GetMarkerColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetMarkerColor(fgcol) #H2 if obj.InheritsFrom(TH2.Class()) == True: obj.SetAxisColor(fgcol, "Z") obj.SetLabelColor(fgcol, "Z") obj.GetZaxis().SetTitleColor(fgcol) #obj.SetLineColor(fgcol) #obj.SetMarkerColor(fgcol) #TLatex if obj.InheritsFrom(TLatex.Class()) == True: if obj.GetTextColor() == rt.kBlack: obj.SetTextColor(fgcol) #F2 if obj.InheritsFrom(TF2.Class()) == True: axes = [obj.GetXaxis(), obj.GetYaxis(), obj.GetZaxis()] for i in range(len(axes)): axes[i].SetAxisColor(fgcol) axes[i].SetLabelColor(fgcol) axes[i].SetTitleColor(fgcol) #F1 if obj.InheritsFrom(TF1.Class()) == True: axes = [obj.GetXaxis(), obj.GetYaxis()] for i in range(len(axes)): axes[i].SetAxisColor(fgcol) axes[i].SetLabelColor(fgcol) axes[i].SetTitleColor(fgcol) #TGraph if obj.InheritsFrom(TGraph.Class()) == True: obj.SetFillColor(bgcol) ax = obj.GetXaxis() ay = obj.GetYaxis() ax.SetAxisColor(fgcol) ay.SetAxisColor(fgcol) ax.SetLabelColor(fgcol) ay.SetLabelColor(fgcol) ax.SetTitleColor(fgcol) ay.SetTitleColor(fgcol) if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetMarkerColor(fgcol) #TGaxis if obj.InheritsFrom(TGaxis.Class()) == True: obj.SetLineColor(fgcol) obj.SetLabelColor(fgcol) obj.SetTitleColor(fgcol) #TFrame if obj.InheritsFrom(TFrame.Class()) == True: if obj.GetLineColor() == rt.kBlack: obj.SetLineColor(fgcol) obj.SetFillColor(bgcol) #move to next item obj = next()
#Detector area calculation radius = [ 1920, 1920 + 26.9, 1920 + 26.9 + 120.9, 1920 + 26.9 + 120.9 * 2, 1920 + 26.9 + 120.9 * 3, 1920 + 26.9 + 120.9 * 4, 1920 + 26.9 + 120.9 * 5, 1920 + 26.9 + 120.9 * 6, 1920 + 26.9 + 120.9 * 7 ] epsilonRLAr = 1.5 # LAr at 88 K epsilon0 = 8.854 / 1000. #pF/mm gStyle.SetOptStat(0) cImpedance = TCanvas("cImpedance", "", 600, 800) cImpedance.Divide(1, 2) cImpedance.cd(1) fImpedance = TF2("fImpedance", "60/sqrt([0])*log(1.9*(2*x+[1])/(0.8*y+[1]))", 0.04, 0.2, 0.04, 0.2) fImpedance.SetTitle("Impedance vs trace width and distance to ground") fImpedance.SetParameters(epsilonR, t) fImpedance.Draw("colz") fImpedance.GetXaxis().SetTitle("Distance to ground [mm]") fImpedance.GetYaxis().SetTitle("Trace width [mm]") cImpedance.cd(2) fImpedance1D = TF1("fImpedance1D", "60/sqrt([0])*log(1.9*(2*x+[1])/(0.8*[2]+[1]))", 0.04, 0.2) fImpedance1D.SetTitle("Impedance vs distance to ground") fImpedance1D.SetParameters(epsilonR, t, w) fImpedance1D.Draw() fImpedance1D.GetXaxis().SetTitle("Distance to ground [mm]") fImpedance1D.GetYaxis().SetTitle("Impedance [#Omega]") hCapTrace = []
from ROOT import TF2, TCanvas, kBlue, kRed #To run this macro just run on the terminal #python2 twodfunction.py c = TCanvas("c", "Function", 700, 700) c.Divide(2, 1) c.cd(1) f1 = TF2("f2", "sin(x)*sin(y)/(x*y)", 0, 5, 0, 5) f1.SetLineColor(kRed) f1.SetLineStyle(8) f1.Draw() c.cd(2) f2 = TF2("f2", "cos(x)*sin(x*y)", 0., 5., 0., 5.) f2.SetLineColor(kBlue) f2.SetLineStyle(9) f2.Draw() c.Draw() c.SaveAs("twodfunctionpy.png")
x = array.array('d', [+zActiveDipoleLengh / 2, +zActiveDipoleLengh / 2]) y = array.array('d', [0, strength]) n = len(x) Lz = TPolyLine(n, x, y) Lz.SetLineColor(ROOT.kBlack) s3func = '[0] * ((2-ROOT::Math::erfc(([1]/2+x)/[2]))/2)*((2-ROOT::Math::erfc(([1]/2-x)/[2]))/2)\ * ((2-ROOT::Math::erfc(([3]/2+y)/[4]))/2)*((2-ROOT::Math::erfc(([3]/2-y)/[4]))/2)\ * ((2-ROOT::Math::erfc(([5]/2+z)/[6]))/2)*((2-ROOT::Math::erfc(([5]/2-z)/[6]))/2)' fieldxyz = TF3("fieldxyz", s3func, -25, +25, -10, +10, -80, +80) s2func = '[0] * ((2-ROOT::Math::erfc(([1]/2+x)/[2]))/2) * ((2-ROOT::Math::erfc(([1]/2-x)/[2]))/2)\ * ((2-ROOT::Math::erfc(([3]/2+y)/[4]))/2) * ((2-ROOT::Math::erfc(([3]/2-y)/[4]))/2)' fieldxy = TF2("fieldxy", s2func, -25, +25, -10, +10) fieldxz = TF2("fieldxz", s2func, -25, +25, -80, +80) fieldyz = TF2("fieldyz", s2func, -10, +10, -80, +80) s1func = '[0] * ((2-ROOT::Math::erfc(([1]/2+x)/[2]))/2) * ((2-ROOT::Math::erfc(([1]/2-x)/[2]))/2)' fieldx = TF1("fieldx", s1func, -25, +25) fieldy = TF1("fieldy", s1func, -10, +10) fieldz = TF1("fieldz", s1func, -80, +80) fieldxy.SetTitle("B-field x:y") fieldxz.SetTitle("B-field x:z") fieldyz.SetTitle("B-field y:z") fieldx.SetTitle("B-field x") fieldy.SetTitle("B-field y") fieldz.SetTitle("B-field z")
weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # ' > ' + str(bins[len(bins) - 2]) + ')', 'goff') elif (model == "par1par2par3_TH3" or model == "par1par2par3_TF3"): sigObj.Draw( par3Name + ':' + par2Name + ':' + par1Name + ' >> theBaseData_' + section + '_' + str(i), weight.GetName() + '*(' + cfg.get(section, 'obsVar') + # ' > ' + str(bins[len(bins) - 2]) + ')', 'goff') if (model == "par1_TH1" or model == "par1_TF1"): func = TF1('bin_content_par1_' + str(i), func_string, 2 * par1GridMin, 2 * par1GridMax) elif (model == "par1par2_TH2" or model == "par1par2_TF2"): func = TF2('bin_content_par1_par2_' + str(i), func_string, par1GridMin, par1GridMax, par2GridMin, par2GridMax) elif (model == "par1par2par3_TH3" or model == "par1par2par3_TF3"): func = TF3('bin_content_par1_par2_par3_' + str(i), func_string, par1GridMin, par1GridMax, par2GridMin, par2GridMax, par3GridMin, par3GridMax) print range(nGridPar1Bins) for k in range(nGridPar1Bins + 1): # theBaseData.SetBinError(k,0.0000021); print "bin" + str(k) + ": ", theBaseData.GetBinContent( k), " +- ", theBaseData.GetBinError(k) func.SetLineColor(2) r = theBaseData.Fit(func, 'R0S', '') print "chi2: ", r.Chi2()
def __init__(self, parse, tree, hepmc_attrib): print("Quasi-real configuration:") #electron and proton beam energy, GeV self.Ee = parse.getfloat("main", "Ee") self.Ep = parse.getfloat("main", "Ep") print("Ee =", self.Ee, "GeV") print("Ep =", self.Ep, "GeV") #electron and proton mass self.me = TDatabasePDG.Instance().GetParticle(11).Mass() mp = TDatabasePDG.Instance().GetParticle(2212).Mass() #boost vector pbvec of proton beam pbeam = TLorentzVector() pbeam.SetPxPyPzE(0, 0, TMath.Sqrt(self.Ep**2-mp**2), self.Ep) self.pbvec = pbeam.BoostVector() #electron beam energy Ee_p in proton beam rest frame ebeam = TLorentzVector() ebeam.SetPxPyPzE(0, 0, -TMath.Sqrt(self.Ee**2-self.me**2), self.Ee) ebeam.Boost(-self.pbvec.x(), -self.pbvec.y(), -self.pbvec.z()) # transform to proton beam frame self.Ee_p = ebeam.E() #center-of-mass squared s, GeV^2 self.s = self.get_s(self.Ee, self.Ep) print("s =", self.s, "GeV^2") print("sqrt(s) =", TMath.Sqrt(self.s), "GeV") #range in x xmin = parse.getfloat("main", "xmin") xmax = parse.getfloat("main", "xmax") print("xmin =", xmin) print("xmax =", xmax) #range in u = log_10(x) umin = TMath.Log10(xmin) umax = TMath.Log10(xmax) print("umin =", umin) print("umax =", umax) #range in y ymin = parse.getfloat("main", "ymin") ymax = parse.getfloat("main", "ymax") #range in W wmin = -1. wmax = -1. if parse.has_option("main", "Wmin"): wmin = parse.getfloat("main", "Wmin") print("Wmin =", wmin) if parse.has_option("main", "Wmax"): wmax = parse.getfloat("main", "Wmax") print("Wmax =", wmax) #adjust range in y according to W if wmin > 0 and ymin < wmin**2/self.s: ymin = wmin**2/self.s if wmax > 0 and ymax > wmax**2/self.s: ymax = wmax**2/self.s print("ymin =", ymin) print("ymax =", ymax) #range in v = log_10(y) vmin = TMath.Log10(ymin) vmax = TMath.Log10(ymax) print("vmin =", vmin) print("vmax =", vmax) #range in Q2 self.Q2min = parse.getfloat("main", "Q2min") self.Q2max = parse.getfloat("main", "Q2max") print("Q2min =", self.Q2min) print("Q2max =", self.Q2max) #constant term in the cross section self.const = TMath.Log(10)*TMath.Log(10)*(1./137)/(2.*math.pi) #cross section formula for d^2 sigma / dxdy, Eq. II.6 #transformed as x -> u = log_10(x) and y -> v = log_10(y) self.eq_II6_uv_par = self.eq_II6_uv(self) self.eq = TF2("d2SigDuDvII6", self.eq_II6_uv_par, umin, umax, vmin, vmax) self.eq.SetNpx(1000) self.eq.SetNpy(1000) #uniform generator for azimuthal angles self.rand = TRandom3() self.rand.SetSeed(5572323) #generator event variables in output tree tnam = ["gen_u", "gen_v", "true_x", "true_y", "true_Q2", "true_W2"] tnam += ["true_el_Q2"] tnam += ["true_el_pT", "true_el_theta", "true_el_phi", "true_el_E"] #create the tree variables tcmd = "struct gen_out { Double_t " for i in tnam: tcmd += i + ", " tcmd = tcmd[:-2] + ";};" gROOT.ProcessLine( tcmd ) self.out = rt.gen_out() #put zero to all variables for i in tnam: exec("self.out."+i+"=0") #set the variables in the tree if tree is not None: for i in tnam: tree.Branch(i, addressof(self.out, i), i+"/D") #event attributes for hepmc self.hepmc_attrib = hepmc_attrib #counters for all generated and selected events self.nall = 0 self.nsel = 0 #print generator statistics at the end atexit.register(self.show_stat) #total integrated cross section self.sigma_tot = self.eq.Integral(umin, umax, vmin, vmax) print("Total integrated cross section for a given x and y range:", self.sigma_tot, "mb") print("Quasi-real photoproduction initialized")
def __init__(self, parse, tree): #electron and proton energy, GeV self.Ee = parse.getfloat("main", "Ee") self.Ep = parse.getfloat("main", "Ep") print("Ee, GeV =", self.Ee) print("Ep, GeV =", self.Ep) #A and Z of the nucleus self.A = 1 self.Z = 1 if parse.has_option("main", "A"): self.A = parse.getint("main", "A") if parse.has_option("main", "Z"): self.Z = parse.getint("main", "Z") print("A:", self.A) print("Z:", self.Z) #minimal photon energy, GeV self.emin = parse.getfloat("main", "emin") print("emin, GeV =", self.emin) #alpha r_e^2 self.ar2 = 7.297 * 2.818 * 2.818 * 1e-2 # m barn #electron and nucleus mass self.me = TDatabasePDG.Instance().GetParticle(11).Mass() self.mp = TDatabasePDG.Instance().GetParticle(2212).Mass() self.mn = self.A * self.mp #nucleus beam vector nvec = TLorentzVector() pz_a = TMath.Sqrt(self.Ep**2 - self.mp**2) * self.Z en_a = TMath.Sqrt(pz_a**2 + self.mn**2) nvec.SetPxPyPzE(0, 0, pz_a, en_a) print("Nucleus beam gamma:", nvec.Gamma()) #boost vector of nucleus beam self.nbvec = nvec.BoostVector() #electron beam vector evec = TLorentzVector() evec.SetPxPyPzE(0, 0, -TMath.Sqrt(self.Ee**2 - self.me**2), self.Ee) print("Electron beam gamma:", evec.Gamma()) #electron beam energy in nucleus beam rest frame evec.Boost(-self.nbvec.x(), -self.nbvec.y(), -self.nbvec.z()) self.Ee_n = evec.E() print("Ee_n, GeV:", self.Ee_n) #minimal photon energy in nucleus rest frame eminv = TLorentzVector() eminv.SetPxPyPzE(0, 0, -self.emin, self.emin) eminv.Boost(-self.nbvec.x(), -self.nbvec.y(), -self.nbvec.z()) emin_n = eminv.E() print("emin_n, GeV:", emin_n) #maximal delta in nucleus frame dmax_n = 100. if parse.has_option("main", "dmax_n"): dmax_n = parse.getfloat("main", "dmax_n") print("dmax_n:", dmax_n) #cross section formula self.eqpar = self.eq(self) self.dSigDwDt = TF2("dSigDwDt", self.eqpar, emin_n, self.Ee_n, 0, dmax_n) self.dSigDwDt.SetNpx(2000) self.dSigDwDt.SetNpy(2000) gRandom.SetSeed(5572323) #total integrated cross section over all delta (to 1e5) dSigInt = TF2("dSigInt", self.eqpar, emin_n, self.Ee_n, 0, 1e5) sigma_tot = dSigInt.Integral(emin_n, self.Ee_n, 0, 1e5) print("Total cross section, mb:", sigma_tot) #uniform generator for azimuthal angles self.rand = TRandom3() self.rand.SetSeed(5572323) #tree output from the generator tlist = ["true_phot_w", "true_phot_delta", "true_phot_theta_n"] tlist += ["true_phot_theta", "true_phot_phi", "true_phot_E"] tlist += ["true_el_theta", "true_el_phi", "true_el_E"] self.tree_out = self.set_tree(tree, tlist) print("Lifshitz_93p16 parametrization initialized")
def funcOverlap(self): multBeam = TF2('multBeam', self.calcOverlap, -30.0, 30.0, -30.0, 30.0, 10) multBeam = self.assignToOverlap(multBeam) return multBeam
def test_random_sample_f2(): func = TF2("f2", "sin(x)*sin(y)/(x*y)") sample = rnp.random_sample(func, 100) assert_equal(sample.shape, (100, 2))
from ROOT import gROOT, TCanvas, TF2 gROOT.Reset() c1 = TCanvas( 'c1', 'Sin(x) * Cos(y)', 200, 10, 700, 500 ) # # Create a one dimensional function and draw it # f1 = TF2("f1", "sin(x) * cos (y)", 0, 10, 0 , 10) c1.SetGridx() c1.SetGridy() f1.Draw() c1.Update()
def test_evaluate(): # create functions and histograms f1 = TF1("f1", "x") f2 = TF2("f2", "x*y") f3 = TF3("f3", "x*y*z") h1 = TH1D("h1", "", 10, 0, 1) h1.FillRandom("f1") h2 = TH2D("h2", "", 10, 0, 1, 10, 0, 1) h2.FillRandom("f2") h3 = TH3D("h3", "", 10, 0, 1, 10, 0, 1, 10, 0, 1) h3.FillRandom("f3") # generate random arrays arr_1d = np.random.rand(5) arr_2d = np.random.rand(5, 2) arr_3d = np.random.rand(5, 3) arr_4d = np.random.rand(5, 4) # evaluate the functions assert_array_equal(rnp.evaluate(f1, arr_1d), map(f1.Eval, arr_1d)) assert_array_equal(rnp.evaluate(f1.GetTitle(), arr_1d), map(f1.Eval, arr_1d)) assert_array_equal(rnp.evaluate(f2, arr_2d), [f2.Eval(*x) for x in arr_2d]) assert_array_equal(rnp.evaluate(f2.GetTitle(), arr_2d), [f2.Eval(*x) for x in arr_2d]) assert_array_equal(rnp.evaluate(f3, arr_3d), [f3.Eval(*x) for x in arr_3d]) assert_array_equal(rnp.evaluate(f3.GetTitle(), arr_3d), [f3.Eval(*x) for x in arr_3d]) # 4d formula f4 = TFormula('test', 'x*y+z*t') assert_array_equal(rnp.evaluate(f4, arr_4d), [f4.Eval(*x) for x in arr_4d]) # evaluate the histograms assert_array_equal(rnp.evaluate(h1, arr_1d), [h1.GetBinContent(h1.FindBin(x)) for x in arr_1d]) assert_array_equal(rnp.evaluate(h2, arr_2d), [h2.GetBinContent(h2.FindBin(*x)) for x in arr_2d]) assert_array_equal(rnp.evaluate(h3, arr_3d), [h3.GetBinContent(h3.FindBin(*x)) for x in arr_3d]) # create a graph g = TGraph(2) g.SetPoint(0, 0, 1) g.SetPoint(1, 1, 2) assert_array_equal(rnp.evaluate(g, [0, .5, 1]), [1, 1.5, 2]) from ROOT import TSpline3 s = TSpline3("spline", g) assert_array_equal(rnp.evaluate(s, [0, .5, 1]), map(s.Eval, [0, .5, 1])) # test exceptions assert_raises(TypeError, rnp.evaluate, object(), [1, 2, 3]) assert_raises(ValueError, rnp.evaluate, h1, arr_2d) assert_raises(ValueError, rnp.evaluate, h2, arr_3d) assert_raises(ValueError, rnp.evaluate, h2, arr_1d) assert_raises(ValueError, rnp.evaluate, h3, arr_1d) assert_raises(ValueError, rnp.evaluate, h3, arr_2d) assert_raises(ValueError, rnp.evaluate, f1, arr_2d) assert_raises(ValueError, rnp.evaluate, f2, arr_3d) assert_raises(ValueError, rnp.evaluate, f2, arr_1d) assert_raises(ValueError, rnp.evaluate, f3, arr_1d) assert_raises(ValueError, rnp.evaluate, f3, arr_2d) assert_raises(ValueError, rnp.evaluate, g, arr_2d) assert_raises(ValueError, rnp.evaluate, s, arr_2d) assert_raises(ValueError, rnp.evaluate, "f", arr_1d) assert_raises(ValueError, rnp.evaluate, "x*y", arr_1d) assert_raises(ValueError, rnp.evaluate, "x", arr_2d) assert_raises(ValueError, rnp.evaluate, "x*y", arr_3d)
c1 = TCanvas('c1', 'Surfaces Drawing Options', 200, 10, 700, 900) c1.SetFillColor(42) gStyle.SetFrameFillColor(42) title = TPaveText(.2, 0.96, .8, .995) title.SetFillColor(33) title.AddText('Examples of Surface options') title.Draw() pad1 = TPad('pad1', 'Gouraud shading', 0.03, 0.50, 0.98, 0.95, 21) pad2 = TPad('pad2', 'Color mesh', 0.03, 0.02, 0.98, 0.48, 21) pad1.Draw() pad2.Draw() # We generate a 2-D function f2 = TF2('f2', 'x**2 + y**2 - x**3 -8*x*y**4', -1, 1.2, -1.5, 1.5) f2.SetContour(48) f2.SetFillColor(45) # Draw this function in pad1 with Gouraud shading option pad1.cd() pad1.SetPhi(-80) pad1.SetLogz() f2.Draw('surf4') # Draw this function in pad2 with color mesh option pad2.cd() pad2.SetTheta(25) pad2.SetPhi(-110) pad2.SetLogz() f2.Draw('surf1')
def TrackToFile_ROOT(data, save_path, log_z=False, plot_opt='', force_aspect=True, legend_text='', fitline=None): from ROOT import TH2F, TCanvas if plot_opt == '': plot_opt = 'lego2 0' if plot_opt != 'lego' and plot_opt != 'box' and plot_opt != 'colz' and plot_opt != 'lego2' and plot_opt != 'lego2 0': plot_opt = 'lego2 0' if force_aspect: nbinsx = xmax = max(data.shape[0], data.shape[1]) nbinsy = ymax = max(data.shape[0], data.shape[1]) else: nbinsx = xmax = data.shape[0] nbinsy = ymax = data.shape[1] xlow = 0 ylow = 0 image_hist = TH2F('', '', nbinsx, xlow, xmax, nbinsy, ylow, ymax) for x in range(data.shape[0]): for y in range(data.shape[1]): value = data[x, y] if value != 0: image_hist.Fill(float(x), float(y), float(value)) c4 = TCanvas('canvas', 'canvas', 0, 0, 1000, 1000) #create canvas image_hist.Draw(plot_opt) if legend_text != '': from ROOT import TPaveText textbox = TPaveText(0.80, 0.90, 1.0, 1.0, "NDC") for line in legend_text: textbox.AddText(line) textbox.Draw("same") if fitline != None: from ROOT import TF2 a = fitline.a b = fitline.b # formula = "y - (" + str(a) + "*x) - "+ str(b) + " - 5" formula = "(" + str(a) + "*x) - " + str(b) print formula # formula = "sin(x)*sin(y)/(x*y)" plane = TF2("f2", formula, 0, 20, 0, 20) plane.SetContour(100) plane.Draw("same") # from root_functions import Browse # image_hist.SetDrawOption(plot_opt) # Browse(image_hist) if log_z: c4.SetLogz() image_hist.SetStats(False) c4.SaveAs(save_path)
1), f_pol2.GetParameter(2), f_pol2.GetParameter(3), f_pol2.GetParameter(4) y_value = str(f_y.GetExpFormula()).replace( "x", "(116.5/([0]+[1]*x+[2]*x**2+[3]*x**3+[4]*x**4)*y)") y_value_neg = str(f_y.GetExpFormula()).replace( "x", "-116.5/([0]+[1]*x+[2]*x**2+[3]*x**3+[4]*x**4)*y") y_max = str(f_y.GetExpFormula()).replace("x", "116.5") y_max_neg = str(f_y.GetExpFormula()).replace("x", "-116.5") #y_value = "1" #y_max = "1" #y_value_neg = "1" #y_max_neg = "1" print(y_value, y_max) f3 = TF2( "f_corr_pos", "y+(116.5-([0]+[1]*x+[2]*x**2+[3]*x**3+[4]*x**4))*" + "(" + y_value + ")/(" + y_max + ")", 0, x_end, y_start + 10, y_end - 10) f3.SetParameter(0, a) f3.SetParameter(1, b) f3.SetParameter(2, c) f3.SetParameter(3, d) f3.SetParameter(4, e) f4 = TF2( "f_corr_neg", "y-(([0]+[1]*x+[2]*x**2+[3]*x**3+[4]*x**4)+116.5)*" + "(" + y_value_neg + ")/(" + y_max_neg + ")", 0, x_end, y_start + 10, -1) f4.SetParameter(0, a2) f4.SetParameter(1, b2) f4.SetParameter(2, c2) f4.SetParameter(3, d2) f4.SetParameter(4, e2)