def __init__(self, eamfile, rcut, rcutsm): # Read eam file (nvr,scr,npp,sce,pairs), (rs,Vs,er), (mele,rce0,rce1,dre,em) = readfiles.readeampot(eamfile) (self.nvr,self.scr,self.npp,self.sce,self.pairs), (self.rs,self.Vs,self.er), (self.mele,self.rce0,self.rce1,self.dre,self.em) = (nvr,scr,npp,sce,pairs), (rs,Vs,er), (mele,rce0,rce1,dre,em) self.cutoff = rcut # Setup splines self.V_spl = spline.spline(rs, Vs.T, rcut=rcut, rcutsm=rcutsm) self.rho_spl = spline.spline(rs, er.T, rcut=rcut, rcutsm=rcutsm) rce = np.array([[rce0+dre*i for i in range(nvr)] for (rce0,dre) in zip(self.rce0, self.dre)]) ems = np.array([e for e in em]) self.em_spl = spline.spline(rce.T, ems.T) # Setup type tables for fast access self.ntypes = len(self.mele) self.pair_table = np.zeros((self.ntypes, self.ntypes), dtype='int') mele = list(mele) self.mele = mele for pair, cnt in zip(self.pairs, range(self.npp)): i,j = pair i_idx = mele.index(i) j_idx = mele.index(j) self.pair_table[i_idx, j_idx] = cnt if i_idx != j_idx: self.pair_table[j_idx, i_idx] = cnt
def hermite_gauss_integral(m, n, x0, x1, stepsize=0.01): "compute integral(h[m](x}*h[n](x)*exp(-x^2),{x,x0,x1})" if m>n: m,n = n,m #always make m<=n xmax=max(abs(x0), abs(x1)) if not integral_cache.has_key((m,n)) or integral_cache[(m,n)][0] < xmax: #just use Simpson's rule for this #first, load up cache hermite_gauss(m,xmax) hermite_gauss(n,xmax) xm, xa1, ya1, y2a1 = hermite_cache[m] xm, xa2, ya2, y2a2 = hermite_cache[n] stepcount=int(2.0*xmax/stepsize) if stepcount%2==0: stepcount=stepcount+1 #always odd for Simpson stepsize=2*xmax/(stepcount-1) #exact step size xlist=Numeric.array(range(stepcount),Numeric.Float)*stepsize - xmax y=spline.splint(xa1, ya1, y2a1, xlist)*spline.splint(xa2, ya2, y2a2, xlist) hmn2=spline.spline(xlist, y) yint=Numeric.cumsum(y[0:-2:2]+y[2::2]+4.0*y[1::2])*(stepsize/3.0) yint=Numeric.concatenate( ( (0,), yint )) #first element of integral is 0 yi2=spline.spline(xlist[::2], yint) integral_cache[(m,n)]=(xmax, xlist[::2], yint, yi2, stepsize, xlist, y, hmn2) xmax, xa, ya, y2a, stepjunk, xjunk, yjunk, hmn2junk=integral_cache[(m,n)] iv1, iv2=spline.splint(xa, ya, y2a, (x0, x1) ) return iv2-iv1
def getPath(self, dp, z, splined=False, scaled=False): scale = 1 if scaled: scale = self.scale path = [(p.x * scale, p.y * scale) for p in dp] if splined: path = spline(path, 0, len(path) * 7) path_msg = Path() path_msg.header.frame_id = HEADER_FRAME for x, y in path: ps = PoseStamped() ps.header.frame_id = HEADER_FRAME ps.pose.position.x = x ps.pose.position.y = self.height - y ps.pose.position.z = z ps.pose.orientation.w = 0.0 ps.pose.orientation.x = 0.0 ps.pose.orientation.y = 0.0 ps.pose.orientation.z = 0.0 path_msg.poses.append(ps) return path_msg
def test_s_equals_sum_dN(self): ''' Test if S(u) = sum(d_i*N_i) Also plots the points and the spline ''' d = np.array([[0, 0], [0.5, -1], [1, 2], [2, -2], [2.5, 2], [3, -2], [3.5, 1], [4, 0], [5, 1], [6, -1], [7, 1], [8, -1], [9, 1], [10, -1], [11, 0]]) sp = spline(d, steps=100, p=3) u_knots = sp.get_knots( ) # returns the knots to Calculate the base functions at x = 0.0 y = 0.0 results = sp.get_spline_values() for u in np.linspace(u_knots[0], u_knots[-1], 200): for i in range(0, len(u_knots) - 2): N_i = sp.getN_i_k(u_knots, i) # gets the N_i function x += N_i(u) * d[i][0] y += N_i(u) * d[i][1] plt.plot(x, y, '*') self.assertEqual(round(sp.value(u)[0], 2), round(x, 2)) self.assertEqual(round(sp.value(u)[1], 2), round(y, 2)) x = 0 y = 0 plt.plot(d[:, 0], d[:, 1], '.', label="Control points") plt.plot(results[:, 0], results[:, 1], label="Spline") plt.legend(loc='best') plt.show() print("\nTEST: S(u)=Sum[d_i*N_i] OK\n")
def model_mXX(idacm,idacr,a,ac,mc,T,pw,mr,meq,mend,mpeak,mf,Rmc,slmc,filletstyle,N): [Rcap,Rcap_mXX]=spo2ida_get_Rcap_pXXmXXcXXtXX(a,ac,T,meq,mpeak,Rmc,pw) [b0,b1]=spo2ida_get_ab_pXXtXX(0,T,pw) #This b0 will be used if filletstyle = 3 for i in range(0,3): # the softening part starts at m=mc and ends at m==mr # compute the R-values. Note that "mc" is included though it # should not. #keyboard if filletstyle==0 or filletstyle==1 or filletstyle==2: # don't do any cute tricks. Just extend the pXX linearly # following the final slmc slope. RmXX=np.linspace(Rmc[i],Rcap[i],N+1) # try not to repeat the end of the last segment RmXX=RmXX[1:] newMu = mc+(RmXX-Rmc[i])*slmc[i] # this is something that I (Chiara) added, check with Dimitrios if it's ok if newMu[-1]>mf: f = np.nonzero(newMu<=mf) RmXX=RmXX[f] newMu = mc+(RmXX-Rmc[i])*slmc[i] idacr[i]=idacr[i] + RmXX.tolist() idacm[i]=idacm[i] + newMu.tolist() else: # # use a repeated midpoint insertion and a control polygon with spcrv to get the desired filleting. # # intersection of flatline and the tangent at end of pXX xi=(np.log(Rcap[i])-np.log(Rmc[i]))*slmc[i] + np.log(mc) # Controlling Polygon cp: cp_mu = [2*np.log(mc)-xi, xi, 2*np.log(mend)-xi] cp_R = [2*np.log(Rmc[i])-np.log(Rcap[i]), np.log(Rcap[i]), np.log(Rcap[i])] [newcx,newcy] = spline(cp_mu,cp_R) x_mc = np.nonzero(newcx>mc)[0] indy = [ele for ele in x_mc if newcx[ele]<=mr] # # add a "final point" right on mr. The filleting will never do that by default, so make sure it happens! # # this is especially critical if the real mr > mf, so we are supplied a mr==mf here. So capacity really depends on us # # providing this point. m_rXX = mr if len(indy) == 0: # # then probably mc slightly less than mr. Then just interpolate between the closest values # # surrounding "mc" (or "mr" they are actually the same values since mc,mr are so close). i1=np.max(np.nonzero(newcx<=mc)) i2=i1+1 else: if indy[-1]==len(newcx)-1: # # Linear extrapolation. Just so that you get a point right on the "mf" and capacity gets displayed correctly i1=indy[-2] i2=indy[-1] else: # # Interpolation between indy(end) and the indy(end)+1 point (if it has been calculated). i1=indy[-1] i2=indy[-1]+1 R_rXX = newcy[i2]+(newcy[i2]-newcy[i1])/(newcx[i2]-newcx[i1])*(mr-newcx[i2]) idacm[i]=idacm[i] + newcx[indy].tolist() + [m_rXX] idacr[i]=idacr[i] + newcy[indy].tolist() + [R_rXX] return [idacm,idacr]
def resample(self, xdivs, use_spline): self.top = [] self.bottom = [] n = len(self.parax) totaldist = self.parax[n - 1][0] # print "total surface dist = " + str(totaldist) # extract the top surface step = self.nosedist / xdivs parax_y2 = spline.derivative2(self.parax) paray_y2 = spline.derivative2(self.paray) for i in range(0, xdivs + 1): d = i * step if use_spline: index = spline.binsearch(self.parax, d) x = spline.spline(self.parax, parax_y2, index, d) y = spline.spline(self.paray, paray_y2, index, d) else: x = self.simple_interp(self.parax, d) y = self.simple_interp(self.paray, d) if x >= 0.0: #print str(x) + " " + str(y) self.top.append((x, y)) self.top.reverse() # extract the bottom surface step = (totaldist - self.nosedist) / xdivs for i in range(0, xdivs + 1): d = i * step + self.nosedist if use_spline: index = spline.binsearch(self.parax, d) x = spline.spline(self.parax, parax_y2, index, d) y = spline.spline(self.paray, paray_y2, index, d) else: x = self.simple_interp(self.parax, d) y = self.simple_interp(self.paray, d) if x < 0.0: x = 0.0 self.bottom.append((x, y))
def resample(self, xdivs, use_spline): self.top = [] self.bottom = [] n = len(self.parax) totaldist = self.parax[n-1][0] # print "total surface dist = " + str(totaldist) # extract the top surface step = self.nosedist / xdivs parax_y2 = spline.derivative2( self.parax ) paray_y2 = spline.derivative2( self.paray ) for i in range(0, xdivs+1): d = i * step if use_spline: index = spline.binsearch(self.parax, d) x = spline.spline(self.parax, parax_y2, index, d) y = spline.spline(self.paray, paray_y2, index, d) else: x = self.simple_interp(self.parax, d ) y = self.simple_interp(self.paray, d ) if x >= 0.0: #print str(x) + " " + str(y) self.top.append( (x, y) ) self.top.reverse() # extract the bottom surface step = (totaldist - self.nosedist) / xdivs for i in range(0, xdivs+1): d = i * step + self.nosedist if use_spline: index = spline.binsearch(self.parax, d) x = spline.spline(self.parax, parax_y2, index, d) y = spline.spline(self.paray, paray_y2, index, d) else: x = self.simple_interp(self.parax, d ) y = self.simple_interp(self.paray, d ) if x < 0.0: x = 0.0 self.bottom.append( (x, y) )
def test_interpolate(self): ''' Plots the interpolation of chosen points and the spline that interpolates ''' xi = np.linspace(0, 1., 8) xi = np.hstack([0, 0, xi, 1, 1]) points = np.array( [[0.0, 2.7, 3.37, 8.0, 10.0, 13.37, 15.0, 16.0, 18.2, 21.0], [-2.0, 3.0, 1.0, 4.0, -4.0, 0.0, 0.0, 3.0, 6.0, -2.0]]).T sp1 = spline(points, steps=100, xi=xi) sp1.interpolate() psp = ps.plot_splines() psp.add_spline(sp1) psp.plot_all(interpolation=True, de_boor=False, ctrl_pol=False)
def spline_determinant_test(): #*****************************************************************************80 # ## SPLINE_DETERMINANT_TEST tests SPLINE_DETERMINANT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 February 2015 # # Author: # # John Burkardt # from spline import spline from r8vec_uniform_ab import r8vec_uniform_ab from r8mat_print import r8mat_print print '' print 'SPLINE_DETERMINANT_TEST' print ' SPLINE_DETERMINANT computes the SPLINE determinant.' m = 5 n = m r8_lo = -5.0 r8_hi = +5.0 seed = 123456789 x, seed = r8vec_uniform_ab(n - 1, r8_lo, r8_hi, seed) a = spline(n, x) r8mat_print(m, n, a, ' SPLINE matrix:') value = spline_determinant(n, x) print '' print ' Value = %g' % (value) print '' print 'SPLINE_DETERMINANT_TEST' print ' Normal end of execution.' return
def spline_determinant_test ( ): #*****************************************************************************80 # ## SPLINE_DETERMINANT_TEST tests SPLINE_DETERMINANT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 February 2015 # # Author: # # John Burkardt # from spline import spline from r8vec_uniform_ab import r8vec_uniform_ab from r8mat_print import r8mat_print print '' print 'SPLINE_DETERMINANT_TEST' print ' SPLINE_DETERMINANT computes the SPLINE determinant.' m = 5 n = m r8_lo = -5.0 r8_hi = +5.0 seed = 123456789 x, seed = r8vec_uniform_ab ( n - 1, r8_lo, r8_hi, seed ) a = spline ( n, x ) r8mat_print ( m, n, a, ' SPLINE matrix:' ) value = spline_determinant ( n, x ) print '' print ' Value = %g' % ( value ) print '' print 'SPLINE_DETERMINANT_TEST' print ' Normal end of execution.' return
def main(): tab = [[i, i**2] for i in range(11)] x = 0.5 print('\n\nТаблица функции (y = x^2):') print("+{:11s}|{:11s}+".format('-', '-').replace(' ', '-')) print('| X | Y |') print("|{:11s}|{:11s}|".format('-', '-').replace(' ', '-')) for i in tab: print('|{:11d}|{:11d}|'.format(i[0], i[1])) print("|{:11s}|{:11s}|".format('-', '-').replace(' ', '-')) print('\nX =', x) print('Результат интерполяции кубическим сплайном: {:.6f}'.format(spline(tab, x))) print('Значение y(x): {:.3f}'.format(x ** 2)) print('Результат интерполяции полиномом Ньютона 3-ей степени: {:.6f}'.format(newton(tab, 3, x)))
def plot_N(self): ''' Plots the basefunctions N_i ''' d = np.array([[0, 0], [3, 1], [4, 1], [5, 0], [5, 2], [6, 3], [8, 3], [8, 4], [5, 8], [0, 10]]).astype(float) #Control pointss sp = spline(d, steps=100, p=3) s = np.linspace(0, 2, 300) # Resoluton of plot u_knots = sp.get_knots( ) # returns the knots to Calculate the base functions at for u in range(3, len(u_knots) - 5): #Starts at 3 since u0=u1=u2 N_i = sp.getN_i_k(u_knots, u) # gets the N_i function plotArray = [] for i in s: plotArray.append(N_i(i)) plt.plot(s, plotArray, label="N" + str(u - 2)) plt.plot(u_knots, np.zeros(len(u_knots)), '*') plt.legend(loc='best') plt.show()
def path_create(start, goal, obstacleList, randArea): import matplotlib.pyplot as plt rrt = RRT(start, goal, obstacleList, randArea) path = rrt.Planning(animation=False) # Draw final path #rrt.DrawGraph() #plt.plot([x for (x,y) in path], [y for (x,y) in path],'-r') #Path smoothing maxIter = 1000 smoothedPath = PathSmoothing(path, maxIter, obstacleList) x = map(lambda d: d[0], smoothedPath) y = map(lambda d: d[1], smoothedPath) line = spline(x, y) curvature = line[0] out = line[1] delta_l = line[2] return (curvature, out, smoothedPath, delta_l)
def test_sum_of_N(self): ''' Test if sum(N_i(u))=1 Also plots it ''' d = np.array([[0, 0], [3, 1], [4, 1], [5, 0], [5, 2], [6, 3], [8, 3], [8, 4], [5, 8], [0, 10]]).astype(float) #Control pointss sp = spline(d, steps=100, p=3) x = 0 u_knots = sp.get_knots( ) # returns the knots to Calculate the base functions at for u in np.linspace(u_knots[2], u_knots[len(u_knots) - 2], 200): for i in range(0, len(u_knots) - 2): N_i = sp.getN_i_k(u_knots, i) # gets the N_i function x += (N_i(u)) self.assertEqual(round(x, 10), 1.0) x = 0 print("TEST: Sum of N OK") plot = input("Show plots of N? y/n(y)") if (plot != "n"): self.plot_N()
def generate_table(order, final_x=None, npoints=None): "generate a spline table of H[n](x) exp(-x^2/2) ... a Hermite-Gauss basis function, using the Numerov method" if final_x is None: final_x=hermite_x_bound if npoints is None: npoints=hermite_n_points Y=Numeric.zeros(npoints+1, Numeric.Float) dx=float(final_x)/npoints dx2=dx*dx e2=2*order+1 x=-final_x+Numeric.array(range(npoints+1),Numeric.Float)*dx V=(x*x-e2) ypsifact=1.0/(1.0-(dx*dx/12.0)*V) coef=2.0+dx2*V*ypsifact Y[0]=1.0/ypsifact[0] Y[1]=math.exp(math.sqrt(V[0])*dx))/ypsifact[1] for i in range(1,npoints): yy=Y[i+1]=Y[i]*coef[i]-Y[i-1] if abs(yy) > 1e20: #don't let exponential blow up Y*=1e-20 psi = Y*ypsifact x=-final_x+Numeric.array(range(2*npoints+1),Numeric.Float)*dx if order%2 == 0: #even function y=Numeric.concatenate((psi, psi[::-1][1:])) else: psi[-1]=0 #enforce oddness exactly y=Numeric.concatenate((psi, -psi[::-1][1:])) y=y*math.sqrt(1.0/(Numeric.dot(y,y)*dx)) y2=spline.spline(x, y) return (final_x, x,y,y2)
def __init__(self, ppfile, rcut, rcutsm): # Read pp file (nvr,scr,npp,sce,pairs), (rs,Vs) = readfiles.readpairpot(ppfile) (self.nvr,self.scr,self.npp,self.sce,self.pairs), (self.rs,self.Vs) = (nvr,scr,npp,sce,pairs), (rs,Vs) self.cutoff = rcut # Setup splines self.V_spl = spline.spline(rs, Vs.T, rcut=rcut, rcutsm=rcutsm) self.mele = list(set(sorted(pairs.flatten()))) # Setup type tables for fast access self.ntypes = len(self.mele) self.pair_table = np.zeros((self.ntypes, self.ntypes), dtype='int') mele = list(self.mele) self.mele = mele for pair, cnt in zip(self.pairs, range(self.npp)): i,j = pair i_idx = mele.index(i) j_idx = mele.index(j) self.pair_table[i_idx, j_idx] = cnt if i_idx != j_idx: self.pair_table[j_idx, i_idx] = cnt
#!/usr/bin/env python try: import spline except ImportError: # if airfoil is not 'installed' append parent dir of __file__ to sys.path import sys, os sys.path.insert(0, os.path.abspath(os.path.split(os.path.abspath(__file__))[0]+'/../lib')) import spline points = ((0.0, 9.0), (5.0, 11.0), (10, 11.0), (30.0, 6.0)) y2 = spline.derivative2( points ) for x in range(0, 31, 1): index = spline.binsearch(points, x) y = spline.spline(points, y2, index, x) print str(x) + " " + str(y)
y_up = ymax if ymax > y_up else y_up # Sets axes to relate to the max and min control values and also sets a legend plt.axis([x_low-2, x_up+2, y_low-1, y_up+1]) plt.legend() plt.show() if __name__ == '__main__': """ d = np.array([[5,2], [14, 2.1], [26,2], [27,1.5], [27,1.5], [24,1.5], [24,1.5], [27,1.5], [27,1.5], [26,1], [9,1], [9,1], [10,1], [10,0], [5,0], [5,0.7], [5,0.7], [5,0], [0,0], [0,1], [1.5,1.8], [5,2]]).astype(float) """ d = np.array([[0, 0], [0.5, 0.5], [1, 1], [2, 2], [2.5, 2.5], [3, 3], [3.5, 3.5]]) d1 = np.array([[-2, -1], [0.5, -4], [1, 2], [2, -6], [2.5, 4], [3, -2], [5, 1]]) s = spl.spline(d, steps=100) s1 = spl.spline(d1, steps=100) s2 = s + s1 s3 = s1 + s p = plot_splines() p.add_spline(s) p.add_spline(s1) p.add_spline(s2) p.add_spline(s3) p.plot_all(de_boor=False, ctrl_pol=False)
dX, theta_degree, Zm, Wm, f_w, step, splineData = params # создание переменных из массива параметров f_w *= 1000000 # МГц в Гц theta = radians(theta_degree) # градусы в радианы Zm *= 1000 # километры в метры Wm *= 1000 # километры в метры splineData = [x * 1000000 for x in splineData] # МГц в Гц dataX = [step * i * 1000 for i,y in enumerate(splineData)] # километры в метры # вычисление высоты, от расстояния по дуге на плоскости земли def H(x): a = cos(theta) b = cos(theta + x / R0) return R0 * (a / b - 1) f = spline(dataX, splineData) # вычисление электронной концентрации, от расстояния по дуге на плоскости земли и высоты def N(x, h): a = f(x) ** 2 / 80.8 b = (h - Zm) / Wm c = -b ** 2 return a * exp(c) # вычисление длины траектории по прямой линии от приёмника до спутника в зависимости от x def Z(x): a = sin(x / R0) b = cos(theta + x / R0) return R0 * a / b def printData(TEC):
def model_rXX(idacm,idacr,a,ac,mc,mr,mf,r,req,T,pw,filletstyle,N): [b0,b1]=spo2ida_get_ab_mXXrXXtXX(ac,req,T,pw) for i in range(0,3): Rmr = idacr[i][-1] # if intersection of rXX "secant" with flatline is earlier # than mr, calculate only points beyond mr. This situation # should be extremely rare, unless r very close to 1. Also # notice that if mi > mf, then rXX is not present in THIS # fractile. This is a very usual situation for 84%-line. real_mi=max( np.exp(b0[i] + np.log(Rmr)*b1[i]), mr) # We will still use "real_mi" for our spline filleting, so # that the filleting will be independent of "mf". mi = min( mf, real_mi) if filletstyle == 0: # keyboard m_rXX = np.linspace(mi,mf,N+1); # the residual part starts at mr and ends at m==mf if mi<mf: # method 1: Don't do anything fancy, just extend the # "flatline" that almost got through at mr (this will be at # a height slightly less than the flatline that would have # appeared without the rXX) all the way to the intersection # with the "secant" of rXX. R_rXX = np.exp((np.log(m_rXX)-b0[i])/b1[i]) else: # mf has chopped us off before the secant can manifest itself R_rXX = np.repeat(Rmr,len(m_rXX)) idacr[i]=idacr[i]+R_rXX.tolist() idacm[i]=idacm[i]+m_rXX.tolist() else: # Use a spline curve to connect the different branches of the IDA curves if round(np.log(idacr[i][-1])-np.log(idacr[i][-2]),3)!= 0: # how much precision?? slope_mXXend = (np.log(idacm[i][-1])-np.log(idacm[i][-2]))/(np.log(idacr[i][-1])-np.log(idacr[i][-2])) if slope_mXXend == b1[i]: # if this causes the secant and the tangent to intercept lower than Rmr, the next "if" will fix it. # actually I don't expect this piece of code to ever need to run. It will be a wild case indeed! slope_mXXend = b1[i] + 0.05 int_mXXend = np.log(mr) - slope_mXXend * np.log(Rmr) lRmi = (int_mXXend-b0[i])/(b1[i]-slope_mXXend) else: # The end of the mXX is indeed flat! so the secant and the flat, intersect at the Rmr height! No need for fancy # interpolation or intersection searching! lRmi = np.log(Rmr) # Prevent pathologies of the fitting process that can cause the secant and the tangent to meet at Rmi < Rmr. There are # two such cases. Also, sometimes the tangent is parallel to the secant. Improbable but keep it in mind. if lRmi < np.log(Rmr): # This may happen for very large r-values. The two lines are intersecting lower that Rmr, or they are parallel if b1[i]>=slope_mXXend: # secant is softer and lower than the tangent."soften" the tangent to reach the secant. slope_mXXend = b1[i] + 0.05 else: # "secant" is harder and above the tangent. "Harden" the tangent to reach the secant. slope_mXXend = b1[i] - 0.05 int_mXXend = np.log(mr) - slope_mXXend * np.log(Rmr) lRmi = (int_mXXend-b0[i])/(b1[i]-slope_mXXend) new_Rmi = np.exp(lRmi) lmmi = b0[i]+b1[i]*lRmi new_mmi = np.exp(lmmi) # Control points for spline fitting cp_mu = [2*np.log(mr)-lmmi, lmmi, 3*lmmi] cp_R = [2*np.log(Rmr) - lRmi, lRmi, (3*lmmi-b0[i])/b1[i]] # the control polygon stops at 3*mi, so points will be produced up to 2*mi? At least that is where the filleting # spline should touch the secant (smoothly) [newcx,newcy] = spline(cp_mu,cp_R) # sometimes, when mf is very close to mc or mr, the spline fitting will not generate any points within the # interval (mc,mf) or (mr,mf). The trick is to get the closest point that spcrv generates plus the point # AT mc or mr and linearly interpolate (although adding the flatline there should be ok in most cases! x_mc = np.nonzero(newcx>mr)[0] indy = [ele for ele in x_mc if newcx[ele]<=mf] # add some more points along the "secant" if mf is larger than the filleting length. The filleting is supposed to # stop at the midpoint of the last segment, so about mu=2*mi. Actually, now with the new fitting it is # exp(3*lmmi-lmmi)=new_mmi^2 if mf > np.power(new_mmi,2): m_rXX = np.linspace(new_mmi^2,mf,N+1) m_rXX = m_rXX R_rXX = np.exp((np.log(m_rXX)-b0[i])/b1[i]) else: # add a "flatline point" right on mf. The filleting will never do that by default, so make sure it happens! m_rXX = mf if len(indy) == 0: # then probably mr slightly less than mf (could be just round-off error sometimes). Then just interpolate # between the closest values surrounding "mr" (or "mf" they are actually the same values since mr,mf are so close). i1 = np.max(np.nonzero(newcx<=mr)) i2 = i1+1 else: if indy[-1]==len(newcx)-1: # a linear extrapolation. Just so that you get a point right on the "mf" and capacity gets displayed # correctly i1=indy[-2] i2=indy[-1] else: # Better to interpolate between indy(end) and the indy(end)+1 point (if it has been calculated). i1=indy[-1] i2=indy[-1]+1 R_rXX = newcy[i2]+(newcy[i2]-newcy[i1])/(newcx[i2]-newcx[i1])*(mf-newcx[i2]) idacm[i]=idacm[i] + newcx[indy].tolist() + [m_rXX] idacr[i]=idacr[i] + newcy[indy].tolist() + [R_rXX] return [idacm,idacr]
def counts(s, niter, sDict={'':[-0.25, [[7.5, -0.75]]]}, smooth=True, spl=False, out=False, reco=True, zcorrect=False): r = np.log10(s['ML_energy']) rEbins = getEbins(reco=True) tEbins = getEbins(reco=reco) rEmids = getMids(rEbins) tEmids = getMids(tEbins) cutName = 'llh' cut = s['cuts'][cutName] eList = getComps(s) tList = getComps(s, reco=False) fig, ax = plt.subplots() ax.set_title('Energy Spectum using '+cutName+' cut') ax.set_xlabel('Log10(Energy/GeV)') ax.set_ylabel('Counts') # Load probability tables p = getProbs(s, cut, reco=reco, zcorrect=zcorrect) # Option for splining if spl: for key in p.keys(): p[key] = 10**(spline.spline(s, p[key], nk=2, npoly=3)) print sum(p['Rf|Tp']+p['Rp|Tp'], axis=0) print sum(p['Rf|Tf']+p['Rp|Tf'], axis=0) # Create our toy MC spectrum temp = {} for key in sDict.keys(): s0 = sDict[key][0] sTable = sDict[key][1] temp[key] = powerFit.powerFit(s0, sTable=sTable, reco=reco) specCut = fakeSpec(s, cut, temp, reco=reco) #specCut = np.array([True for i in range(len(specCut))]) # Create starting arrays N_passed = float(np.histogram(r[cut*specCut], bins=rEbins)[0].sum()) N = {} for e in eList: recocut = s['llh_comp'] == e N[e] = np.histogram(r[cut*recocut*specCut], bins=rEbins)[0] p['R'+e] = N[e] / N_passed p['T'+e] = powerFit.powerFit(-2.7, reco=reco) # Get relative errors due to unfolding #chi2, unrel = load('unfold_err.npy') # Due to efficiency #effarea, sigma, relerr = eff.getEff(s, cut, smooth=smooth) effarea, sigma, relerr = eff.getEff(s, cut, reco=reco) # Bayesian unfolding for i in range(niter): p = unfold(p, reco=reco) #All_unfold = (p['Tf']+p['Tp']) * N_passed #ax.errorbar(Emids, All_unfold, yerr=unrel[i]*All_unfold, label=str(i)) # Smooth prior before next iteration (except last time) if i < niter-1: for e in eList: p['T'+e] = smoother(p['T'+e]) # Find bin values Nun, Rel, Err = {},{},{} for e in eList: Nun[e] = p['T'+e] * N_passed Nun['All'] = np.sum([Nun[e] for e in eList], axis=0) # Calculate errors for e in eList + ['All']: ## NOTE: I don't think you can use the relative errors like this ## #Rel[e] = np.sqrt(1/Nun[e] + relerr**2 + unrel[niter-1]**2) Rel[e] = np.sqrt(1/Nun[e] + relerr**2) Err[e] = Nun[e] * Rel[e] # And plot pnt = getColor(e) + '.' ax.errorbar(tEmids, Nun[e], yerr=Err[e], fmt=pnt, label=e) # Attempt to fit with broken power law #p0 = [1, 10**(-4.5), 7.5, -0.5] #yfit = powerFit.pow_fit(10**Emids, Nun['f'], Err['f'], p0) #ax.plot(Emids, yfit, label='test') #err = {} #err[0] = 1/np.sqrt(All_Nunfold) #err[1] = relerr #err[2] = unrel[niter-1] # Plot error bars nicely #errCalc = lambda i: np.sqrt(np.sum([err[j]**2 for j in range(i+1)], axis=0)) #uperr, dnerr = {}, {} #for i in range(len(err)): # uperr[i] = All_Nunfold * (1 + errCalc(i)) # dnerr[i] = All_Nunfold * (1 - errCalc(i)) # for j in range(len(dnerr[i])): # if dnerr[i][j] < 0: # dnerr[i][j] = 10**(-3) #ax.errorbar(Emids, All_Nunfold, yerr=All_err, fmt='gx', label='Unfold') #ax.plot(Emids, All_Nunfold, 'b.', label='Unfold') #for i in range(len(err)): # ax.fill_between(Emids, dnerr[i], uperr[i], facecolor='blue', alpha=0.2) # Plot true spectrum MC = {} etrue = np.log10(s['MC_energy']) MC['All'] = np.histogram(etrue[cut*specCut], bins=tEbins)[0] for t in tList: truecut = s['comp'] == t MC[t] = np.histogram(etrue[cut*specCut*truecut], bins=tEbins)[0] for t in tList + ['All']: pnt = getColor(t) + 'x' ax.plot(tEmids, MC[t], pnt, label='MC_'+t) # plot original (not unfolded) spectrum O_N = (np.sum([N[e] for e in eList], axis=0)) # Just for now... temperr = relerr if reco else relerr[20:] O_relerr = np.sqrt(1/O_N + temperr**2) O_err = O_N * O_relerr ax.errorbar(rEmids, O_N, yerr=O_err, fmt='gx', label='Original') ax.set_yscale('log') #ax.legend(loc='lower left') #ax.set_ylim((10**(-1), 10**(4))) if out: plt.savefig('collab/pics/'+out+'.png') plt.show()
print '#######################################################' print '' print ' TIME-STEPPING PARTICLES ' print '' print '#######################################################' for it in range(nit): # particle time steps if t_interp == 'linear': fct = (time + 0.5 * dt - tim0) * delti u = (1 - fct) * u0 + fct * u1 v = (1 - fct) * v0 + fct * v1 else: ptime = (part_time[it] - tim0) / tim0 if tim_opt: start_time = clock.time() u = fspline.spline(u0, u1, du0, du1, ptime)[:, :, 0] v = fspline.spline(v0, v1, dv0, dv1, ptime)[:, :, 0] if tim_opt: print 'spline time: ' + str(clock.time() - start_time) ############################ #ADVANCE PARTICLES ############################ if it == 0: scheme_first = True else: scheme_first = False if tim_opt: start_time = clock.time() PN.advance2d(px_temp, py_temp, dpx,
def build(self): if len(self.stations) < 2: print "Must define at least 2 stations to build a wing" return sweep_y2 = spline.derivative2( self.sweep.top ) taper_y2 = spline.derivative2( self.taper.top ) # make the base ribs at each defined station for index, station in enumerate(self.stations): percent = station / self.span # generate airfoil if not self.tip: af = self.root else: af = airfoil.blend(self.root, self.tip, percent) # compute placement parameters lat_dist = station twist = self.twist * percent # compute chord if self.taper: sp_index = spline.binsearch(self.taper.top, lat_dist) chord = spline.spline(self.taper.top, taper_y2, sp_index, lat_dist) else: print "Cannot build a wing with no chord defined!" return print "building station @ " + str(lat_dist) \ + " chord = " + str(chord) # compute sweep offset pos if a sweep function provided if self.sweep: sw_index = spline.binsearch(self.sweep.top, lat_dist) sweep_dist = spline.spline(self.sweep.top, sweep_y2, sw_index, \ lat_dist) else: sweep_dist = 0.0 # make the rib (cutouts will be handled later) label = 'WR' + str(index+1) right_rib = self.make_raw_rib(af, chord, lat_dist, sweep_dist, \ twist, label) right_rib.side = "right" if percent < 0.001: right_rib.nudge = -right_rib.thickness * 0.5 elif percent > 0.999: right_rib.nudge = right_rib.thickness * 0.5 self.right_ribs.append(right_rib) label = 'WL' + str(index+1) left_rib = self.make_raw_rib(af, chord, -lat_dist, sweep_dist, \ twist, label) left_rib.side = "left" if percent < 0.001: left_rib.nudge = right_rib.thickness * 0.5 elif percent > 0.999: left_rib.nudge = -right_rib.thickness * 0.5 self.left_ribs.append(left_rib) # make the control surface ribs. Instead of dividing the # original base ribs into two parts, we make copies of the # base ribs and then trim off the parts we don't want. This # makes a bit of sense considering we need double ribs at the # cutout edges. We do this in one pass per side, stepping # through each rib and seeing if it matches a control surface # cutout and if it's an inner, outer, or mid rib. new_ribs = [] for rib in self.right_ribs: for flap in self.flaps: if self.match_station(flap.start_station, flap.start_station, rib.pos[0]): #print "start station = " + str(rib.pos[0]) newrib = copy.deepcopy(rib) rib.nudge = rib.thickness * 0.5 newrib.nudge = -rib.thickness * 1.0 flap.start_bot_str_pos = newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) elif self.match_station(flap.end_station, flap.end_station, rib.pos[0]): #print "end station = " + str(rib.pos[0]) newrib = copy.deepcopy(rib) rib.nudge = -rib.thickness * 0.5 newrib.nudge = rib.thickness * 1.0 flap.end_bot_str_pos = newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) elif self.match_station(flap.start_station, flap.end_station, rib.pos[0]): #print "match flap at mid station " + str(rib.pos[0]) newrib = copy.deepcopy(rib) newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) rib.trim_rear(flap.pos) rib.has_te = False for rib in new_ribs: self.right_ribs.append(rib) new_ribs = [] for rib in self.left_ribs: for flap in self.flaps: if self.match_station(flap.start_station, flap.start_station, rib.pos[0]): #print "start station = " + str(rib.pos[0]) newrib = copy.deepcopy(rib) rib.nudge = -rib.thickness * 0.5 newrib.nudge = rib.thickness * 1.0 flap.start_bot_str_pos = newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) elif self.match_station(flap.end_station, flap.end_station, rib.pos[0]): #print "end station = " + str(rib.pos[0]) newrib = copy.deepcopy(rib) rib.nudge = rib.thickness * 0.5 newrib.nudge = -rib.thickness * 1.0 flap.end_bot_str_pos = newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) elif self.match_station(flap.start_station, flap.end_station, rib.pos[0]): #print "left match flap at station " + str(rib.pos[0]) newrib = copy.deepcopy(rib) newrib.trim_front_wedge(flap.pos, flap.angle) newrib.part = "flap" newrib.has_le = False new_ribs.append(newrib) rib.trim_rear(flap.pos) rib.has_te = False #rib.contour.trim(surf="top", discard="rear", cutpos=flap.pos) #rib.contour.trim(surf="bottom", discard="rear", cutpos=flap.pos) for rib in new_ribs: self.left_ribs.append(rib) # now place the leading edge bottom stringer for each flap. # This is left until now because this can be very dynamic # depending on the wing layout and control surface blending. for flap in self.flaps: if flap.start_bot_str_pos != None and flap.end_bot_str_pos != None \ and flap.edge_stringer_size != None: xdist = flap.end_station - flap.start_station if math.fabs(xdist) > 0.0001: atstation = flap.start_station ydist = flap.end_bot_str_pos - flap.start_bot_str_pos slope = ydist / xdist half_offset = flap.edge_stringer_size[0] * 0.5 if flap.side == "left": atstation *= -1.0 slope *= -1.0 cutpos = contour.Cutpos(xpos=flap.start_bot_str_pos, \ atstation=atstation, \ slope=slope) cutpos.move(half_offset) cutout = contour.Cutout(surf="bottom", \ orientation="tangent", \ cutpos=cutpos, \ xsize=flap.edge_stringer_size[0], \ ysize=flap.edge_stringer_size[1] ) print "making bottom stringer: " + str(flap.start_station) + " - " + str(flap.end_station) stringer = Stringer( cutout, flap.start_station, flap.end_station, "flap" ) stringer.side = flap.side self.stringers.append( stringer ) else: print "skipped building a flap bottom stringer" print str(flap.start_bot_str_pos) print str(flap.end_bot_str_pos) print str(flap.edge_stringer_size) # do all the cutouts now at the end after we've made and # positioned all the ribs for the wing and the control # surfaces for rib in self.right_ribs: self.make_rib_cuts(rib) for rib in self.left_ribs: self.make_rib_cuts(rib) # a quick pass to update labels on "flap" parts after the # cutouts so there is half a chance the label ends up on the # part itself for rib in self.right_ribs: if rib.part == "flap": rib.relabel_flap() for rib in self.left_ribs: if rib.part == "flap": rib.relabel_flap()
def chartGen1(save, path=""): x1 = np.arange(-1.0,1.0,0.01) rows = len(funcList) colors = "bgrcmy" fig=plt.figure() base = rows * 100 + 21 for i in range(rows): plt.subplot(base + 2*i) plt.title("Equidistant Point Interpolation") approxList = [] plt.plot(x1, funcList[i](x1), "k") for n in nVals: approxList.append(polynomialInterpolate(funcList[i],makeEquiDistRange(n))) for j in range(len(approxList)): plt.plot(x1, approxList[j](x1), colors[j], label=str(nVals[j])) plt.subplot(base + 2*i + 1) plt.title("Error") for k in range(len(approxList)): plt.plot(x1, composedError(funcList[i],approxList[k])(x1), colors[k], label=str(nVals[k])) plt.subplots_adjust(wspace=1.,hspace=0.7) lines_labels = [fig.axes[0].get_legend_handles_labels()] lines, labels = [sum(lol,[]) for lol in zip(*lines_labels)] fig.legend(lines, labels, title="Intervals", loc="center") if save: plt.savefig(path + "-Equi.png") else: plt.show() fig=plt.figure() for i in range(rows): plt.subplot(base + 2*i) plt.title("Chebyshev Node Interpolation") approxList = [] plt.plot(x1, funcList[i](x1), "k") for n in nVals: approxList.append(polynomialInterpolate(funcList[i],makeCosRange(n))) for j in range(len(approxList)): plt.plot(x1, approxList[j](x1), colors[j], label=str(nVals[j])) plt.subplot(base + 2*i + 1) plt.title("Error") for k in range(len(approxList)): plt.plot(x1, composedError(funcList[i],approxList[k])(x1), colors[k], label=str(nVals[k])) plt.subplots_adjust(wspace=1.,hspace=0.7) lines_labels = [fig.axes[0].get_legend_handles_labels()] lines, labels = [sum(lol,[]) for lol in zip(*lines_labels)] fig.legend(lines, labels, title="Intervals", loc="center") if save: plt.savefig(path + "-Chebyshev.png") else: plt.show() fig = plt.figure() base = rows * 100 + 21 for i in range(rows): plt.subplot(base + 2*i) plt.title("Spline Interpolation") plt.plot(x1,funcList[i](x1),"k") spList = [spline(funcList[i], makeEquiDistRange(n)) for n in nVals] for j in range(len(spList)): plt.plot(x1, list(map(spList[j],(x1))), colors[j], label=str(nVals[j])) plt.subplot(base + 2*i + 1) plt.title("Error") for k in range(len(nVals)): iSpline = spline(funcList[i], makeEquiDistRange(nVals[k])) spError = composedError(funcList[i], iSpline) plt.plot(x1, list(map(spError,(x1))), colors[k], label=str(nVals[k])) plt.subplots_adjust(wspace=1.,hspace=0.7) lines_labels = [fig.axes[0].get_legend_handles_labels()] lines, labels = [sum(lol,[]) for lol in zip(*lines_labels)] fig.legend(lines, labels, title="Intervals", loc="center") if save: plt.savefig(path + "-Spline.png") else: plt.show()
def f2(x): return mt.sin(x) / x def f3(x): return mt.cos(2 * x) * x f = f3 a, b = -100, 100 xS = list(np.linspace(a, b, 10)) yS = list(map(f, xS)) s = spl.spline(xS, yS) xR = list(np.linspace(a, b, 100)) yR = list(map(s.interpolate, xR)) yE = list(map(f, xR)) plt.plot(xR, yE, 'r--', label='expected function') plt.plot(xR, yR, label='result spline') plt.plot(xS, yS, 'ro', markerfacecolor='black', markeredgecolor='black', markersize=4) plt.title('Cubic Spline') plt.legend()
from matplotlib import pyplot as plt from numpy import * from spline import spline from time import * n = 1000 h = 3 * pi / (2 * (n + 1)) T = arange(0, 3 * pi / 2, h) X = cos(T) Y = sin(T) fig = plt.figure() plt.plot(X, Y, '.r', markersize=10) t = linspace(0, 2 * pi, 1000) plt.plot(cos(t), sin(t), '--r') t = linspace(0, 3 * pi / 2, 1000) plt.plot(spline(t, h, X), spline(t, h, Y), '-b') plt.axis("equal") plt.axis("off") plt.show()
def appendPath(self, path): if path == []: return pos = [(p.x, p.y) for p in path] if pos[-1] == (-1, -1): pos.pop() self.finish = True #last 5 points, used for better splining l5 = [(p.x, p.y) for p in self.path[-5::]] #use linepoints for splining useLine = False if len(l5) <= 4: print "using linepoints for splining" (a, b) = self.line if a != None and b != None: l5 = [(b.x, b.y)] + l5 useLine = True else: if b == None and a != None: l5 = [(a.x, a.y)] + l5 useLine = True spl_pos = s.spline(l5 + pos) #remove first point so it's not duplicated if useLine: spl_pos = spl_pos[1::] #extend path so truck doesn't stop early due to lookahead if self.finish: print "finish appended" nl, last = spl_pos[-2:] d = getDirection(nl, last) la = getLookAheadPoint(last, d, GOAL_LOOKAHEAD) spl_pos.append(la) #remove points used for splining to make room for result self.path = self.path[:-5:] for (x, y) in spl_pos: self.path.append(Point(x, y)) #add points to line if empty l1, l2 = self.line pathLength = len(self.path) if l1 != None and l2 == None: if pathLength >= 1: self.line = (l1, self.path.pop(0)) elif self.line == (None, None): if pathLength == 1: self.line = (self.path.pop(0), l2) elif pathLength >= 2: self.line = (self.path.pop(0), self.path.pop(0))
for it in range(nit): # particle time steps if t_interp == 'linear': fct = (time + 0.5 * dt - tim0) * delti u = (1 - fct) * u0 + fct * u1 v = (1 - fct) * v0 + fct * v1 W = (1 - fct) * W0 + fct * W1 #################################### #SPLINE INTERPOLATION OF VELOCITIES # TO PARTICLE TIME-STEP ################################### if t_interp == 'spline': if tim_opt: start_time = clock.time() ptime = (part_time[it] - tim0) / (tim1 - tim0) u = fspline.spline(u0, u1, du0, du1, ptime) v = fspline.spline(v0, v1, dv0, dv1, ptime) W = fspline.spline(W0, W1, dW0, dW1, ptime) if tim_opt: print 'spline time: ' + str(clock.time() - start_time) ############################ #ADVANCE PARTICLES ############################ if it == 0: scheme_first = True else: scheme_first = False if tim_opt: start_time = clock.time() PN.advance3d(px_temp, py_temp,
def build(self): if len(self.stations) < 2: print "Must define at least 2 stations to build a wing" return sweep_y2 = spline.derivative2(self.sweep.top) taper_y2 = spline.derivative2(self.taper.top) # make the base ribs at each defined station for index, station in enumerate(self.stations): percent = station / self.span # generate airfoil if not self.tip: af = self.root else: af = airfoil.blend(self.root, self.tip, percent) # compute placement parameters lat_dist = station twist = self.twist * percent # compute chord if self.taper: sp_index = spline.binsearch(self.taper.top, lat_dist) chord = spline.spline(self.taper.top, taper_y2, sp_index, lat_dist) else: print "Cannot build a wing with no chord defined!" return print "building station @ " + str(lat_dist) \ + " chord = " + str(chord) # compute sweep offset pos if a sweep function provided if self.sweep: sw_index = spline.binsearch(self.sweep.top, lat_dist) sweep_dist = spline.spline(self.sweep.top, sweep_y2, sw_index, lat_dist) else: sweep_dist = 0.0 # make the rib (cutouts will be handled later) label = 'WR' + str(index + 1) right_rib = self.make_raw_rib(af, chord, lat_dist, sweep_dist, twist, label) right_rib.side = "right" if percent < 0.001: right_rib.nudge = -right_rib.thickness * 0.5 elif percent > 0.999: right_rib.nudge = right_rib.thickness * 0.5 self.right_ribs.append(right_rib) label = 'WL' + str(index + 1) left_rib = self.make_raw_rib(af, chord, -lat_dist, sweep_dist, twist, label) left_rib.side = "left" if percent < 0.001: left_rib.nudge = right_rib.thickness * 0.5 elif percent > 0.999: left_rib.nudge = -right_rib.thickness * 0.5 self.left_ribs.append(left_rib) # at the ends of each control surface we need a full length # rib to cap off the space, so we need to create copies of the # ribs at these points. self.right_ribs = self.make_new_ribs_for_flaps(self.right_ribs, 'right') self.left_ribs = self.make_new_ribs_for_flaps(self.left_ribs, 'left') for rib in self.right_ribs: rib_pos = rib.pos[0] - rib.nudge for flap in self.flaps: if self.match_station(flap.start_station, flap.end_station, rib_pos): if rib.part == "flap": if rib.type == "inner": pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.start_bot_str_pos = pos print "flap start bot = " + str(pos) elif rib.type == "outer": pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.end_bot_str_pos = pos print "flap end bot = " + str(pos) elif rib.type == "inner-shared": #pos = rib.find_flap_bottom_front(flap.pos, flap.angle) pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.start_bot_str_pos = pos print "flap start bot = " + str(pos) elif rib.type == "outer-shared": pos = rib.find_flap_bottom_front( flap.pos, flap.angle) flap.end_bot_str_pos = pos print "flap end bot = " + str(pos) else: # add cut lines rib.add_wedge_cut_lines(flap.pos, flap.angle) else: print "skipping rear trim" # rib.trim_rear(flap.pos) for rib in self.left_ribs: rib_pos = rib.pos[0] - rib.nudge for flap in self.flaps: if self.match_station(flap.start_station, flap.end_station, rib_pos): if rib.part == "flap": if rib.type == "inner": pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.start_bot_str_pos = pos print "flap start bot = " + str(pos) elif rib.type == "outer": pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.end_bot_str_pos = pos print "flap end bot = " + str(pos) elif rib.type == "inner-shared": pos = rib.find_flap_bottom_front( flap.pos, flap.angle) pos = rib.trim_front_wedge(flap.pos, flap.angle) flap.start_bot_str_pos = pos print "flap start bot = " + str(pos) elif rib.type == "outer-shared": pos = rib.find_flap_bottom_front( flap.pos, flap.angle) flap.end_bot_str_pos = pos print "flap end bot = " + str(pos) else: # add cut lines rib.add_wedge_cut_lines(flap.pos, flap.angle) else: print "skipping rear trim" # rib.trim_rear(flap.pos) # now place the leading edge bottom stringer for each flap. # This is left until now because this can be very dynamic # depending on the wing layout and control surface blending. for flap in self.flaps: if flap.start_bot_str_pos != None and flap.end_bot_str_pos != None \ and flap.edge_stringer_size != None: xdist = flap.end_station - flap.start_station if math.fabs(xdist) > 0.0001: atstation = flap.start_station ydist = flap.end_bot_str_pos - flap.start_bot_str_pos slope = ydist / xdist half_offset = flap.edge_stringer_size[0] * 0.5 if flap.side == "left": atstation *= -1.0 slope *= -1.0 cutpos = contour.Cutpos(xpos=flap.start_bot_str_pos, \ atstation=atstation, \ slope=slope) cutpos.move(half_offset) cutout = contour.Cutout(surf="bottom", \ orientation="tangent", \ cutpos=cutpos, \ xsize=flap.edge_stringer_size[0], \ ysize=flap.edge_stringer_size[1] ) print "making bottom stringer: " + str( flap.start_station) + " - " + str(flap.end_station) stringer = Stringer(cutout, flap.start_station, flap.end_station, "flap") stringer.side = flap.side self.stringers.append(stringer) else: print "skipped building a flap bottom stringer" print str(flap.start_bot_str_pos) print str(flap.end_bot_str_pos) print str(flap.edge_stringer_size) # do all the cutouts now at the end after we've made and # positioned all the ribs for the wing and the control # surfaces for rib in self.right_ribs: self.make_rib_cuts(rib) for rib in self.left_ribs: self.make_rib_cuts(rib) # a quick pass to update labels on "flap" parts after the # cutouts so there is half a chance the label ends up on the # part itself for rib in self.right_ribs: if rib.part == "flap": rib.relabel_flap() for rib in self.left_ribs: if rib.part == "flap": rib.relabel_flap()