def hillshade(data,scale=10.0,azdeg=165.0,altdeg=45.0): ''' This code thanks to Ran Novitsky Nof http://rnovitsky.blogspot.co.uk/2010/04/using-hillshade-image-as-intensity.html Repeated here to make my cyclopean uk_map code prettier. convert data to hillshade based on matplotlib.colors.LightSource class. input: data - a 2-d array of data scale - scaling value of the data. higher number = lower gradient azdeg - where the light comes from: 0 south ; 90 east ; 180 north ; 270 west altdeg - where the light comes from: 0 horison ; 90 zenith output: a 2-d array of normalized hilshade ''' from pylab import pi, gradient, arctan, hypot, arctan2, sin, cos # convert alt, az to radians az = azdeg*pi/180.0 alt = altdeg*pi/180.0 # gradient in x and y directions dx, dy = gradient(data/float(scale)) slope = 0.5*pi - arctan(hypot(dx, dy)) aspect = arctan2(dx, dy) intensity = sin(alt)*sin(slope) + cos(alt)*cos(slope)*cos(-az - aspect - 0.5*pi) intensity = (intensity - intensity.min())/(intensity.max() - intensity.min()) return intensity
def main(): # Create the grid x = arange(-100, 101) y = arange(-100, 101) # Create the meshgrid Y, X = meshgrid(x, y) A = 1 B = 2 V = 6*pi / 201 W = 4*pi / 201 F = A*sin(V*X) + B*cos(W*Y) Fx = V*A*cos(V*X) Fy = W*B*-sin(W*Y) # Show the images show_image(F) show_image(Fx) show_image(Fy) # Create the grid for the quivers xs = arange(-100, 101, 10) ys = arange(-100, 101, 10) # Here we determine the direction of the quivers Ys, Xs = meshgrid(ys, xs) FFx = V*A*cos(V*Xs) FFy = W*B*-sin(W*Ys) # Draw the quivers and the image clf() imshow(F, cmap=cm.gray, extent=(-100, 100, -100, 100)) quiver(ys, xs, -FFy, FFx, color='red') show()
def tests(): x = pylab.arange(0.0, 2*pylab.pi, 0.01) list_y = (pylab.sin(x),pylab.sin(2*x)) plot_and_format((x,), (list_y[0],)) exportplot('test/test1_one_curve.png') pylab.clf() list_x = (x, x) plot_and_format(list_x, list_y) exportplot('test/test2_two_curves.png') pylab.clf() list_format = ('k-', 'r--') plot_and_format(list_x, list_y, list_format=list_format) exportplot('test/test3_two_curves_formatting.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xlabel='hello x axis') exportplot('test/test4_two_curves_formatting_xlab.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, legend=['sin($x$)', 'sin($2x$)']) exportplot('test/test5_two_curves_formatting_legend.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xticks={'ticks': [0, pylab.pi, 2*pylab.pi], 'labels':['0', '$\pi$', '$2\pi$']}) exportplot('test/test6_two_curves_formatting_xticks.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xticks={'ticks': [0, pylab.pi, 2*pylab.pi], 'labels':['0', '$\pi$', '$2\pi$']}, xlim=[0,2*pylab.pi]) exportplot('test/test7_two_curves_formatting_xticks_xlim.png') pylab.clf()
def findcurve(psi1,psi2,n=3,nn_fit=4,nn_out=100): ''' Function to find the elastica curve for start and end orientations psi1 and psi2. It finds the best curve across all directions from start and end, i.e. the direction independent elastica curve. Inputs ------------ psi1,psi2: start and end orientations. n: degree of estimation polynomial. nn: number of points on the curve. - nn_fit: for fittin purposes - nn_out: for the output Outputs ------------ Returns a tuple (s,psi). s: points on the curve. psi: curvature of the curve as a function of s. E: curvature energy of the curve ''' # # define the starting conditions a0 = pl.zeros(n+1) # Set a high energy: E_best = 10000 # and predfine output curve s = pl.linspace(0,1,nn_out) # points on the curve psi_out = pl.zeros(nn_out) # curvature at points in curve # across all the start and end directions find the curve with the lowest energy for dpsi1 in (-pl.pi,0,pl.pi): for dpsi2 in (-pl.pi,0,pl.pi): # For the starting variables, # the first two polygon variables can be estimated from the Sharon paper derivation # For different starting variables the solution can be hard to find a0[-2] = 4*( pl.arcsin(- (pl.sin(psi1+dpsi1)+ pl.sin(psi2+dpsi2))/4) -(psi1+dpsi1+psi2+dpsi2)/2 ) a0[-1] = 2*a0[-2]/pl.cos( (psi1+dpsi1+psi2+dpsi2)/2 + a0[-2]/4 ) # find the best variables to minimize the elastica energy fit = fsolve(errors,a0,args=(psi1+dpsi1,psi2+dpsi2,nn_fit)) # find the curve and its derivative for the fitted variables a = fit[:-1] psi = Psi(a,s,psi1+dpsi1,psi2+dpsi2) dpsi = dPsi(a,s,psi1+dpsi1,psi2+dpsi2) # find the energy of this curve E = sum(dpsi**2)*s[1] # check against the lowest energy if E_best > E: E_best = E psi_out[:] = pl.copy(psi) return (s,psi_out,E_best)
def get_touchdown(self, t, y, params): """ Compute the touchdown position of the leg w.r.t. CoM velocity :args: t (float): time y (6x float): state of the CoM params (4x float): leg parameter: stiffness, l0, alpha, beta :returns: [xFoot, yFoot, zFoot] the position of the leg tip """ k, l0, alpha, beta = params vx, vz = y[3], y[5] a_v_com = -arctan2(vz, vx) # correct with our coordinate system #for debugging #print "v_com_angle:", a_v_com * 180. / pi xf = y[0] + l0 * cos(alpha) * cos(beta + a_v_com) yf = y[1] - l0 * sin(alpha) zf = y[2] - l0 * cos(alpha) * sin(beta + a_v_com) #for debugging #print "foot: %2.3f,%2.3f,%2.3f," % ( xf,yf, zf) return array([xf, yf, zf])
def sortAnglesCW(t1,t2): """ Sort angles so that t2>t1 in a clockwise sense idea from `StackOverflow <http://stackoverflow.com/questions/242404/sort-four-points-in-clockwise-order>`_ more description: `SoftSurfer <http://softsurfer.com/Archive/algorithm_0101/algorithm_0101.htm>`_ If the signed area of the triangle formed between the points on a unit circle with angles t1 and t2 and the origin is positive, the angles are sorted counterclockwise. Otherwise, the angles are sorted in a counter-clockwise manner. Here we want the angles to be sorted CCW, so if area is negative, swap angles Area obtained from the cross product of a vector from origin to 1 and a vector to point 2, so use right hand rule to get sign of cross product with unit length """ while (cos(t1)*sin(t2)-sin(t1)*cos(t2)>0): ##Swap angles temp=t1; t1=t2; t2=temp; #Make t1 between 0 and 2pi while (t1<0 or t1> 2.0*pi): if t1>2.0*pi: t1=t1-2*pi else: t1=t1+2*pi #Want t2 to be less than t1, but no more than 2*pi less while (t2<t1 and t1-t2>2*pi): t2=t2+2*pi while (t2>t1): t2=t2-2*pi return (t1,t2)
def specgram_demo(): ''' the demo in matplotlib. But calls interactive.specgram ''' from pylab import arange, sin, where, logical_and, randn, pi dt = 0.0005 t = arange(0.0, 20.0, dt) s1 = sin(2*pi*100*t) s2 = 2*sin(2*pi*400*t) # create a transient "chirp" mask = where(logical_and(t>10, t<12), 1.0, 0.0) s2 = s2 * mask # add some noise into the mix nse = 0.01*randn(len(t)) x = s1 + s2 + nse # the signal NFFT = 1024 # the length of the windowing segments Fs = int(1.0/dt) # the sampling frequency from ifigure.interactive import figure, specgram, nsec, plot, isec, clog, hold figure() hold(True) nsec(2) isec(0) plot(t, x) isec(1) specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900) clog()
def haversine (latlong1, latlong2, r): deltaLatlong = latlong1 - latlong2 dLat = deltaLatlong[0] dLon = deltaLatlong[1] lat1 = latlong1[0] lat2 = latlong2[0] a = (sin (dLat/2) * sin (dLat/2) + sin (dLon/2) * sin (dLon/2) * cos (lat1) * cos (lat2)) c = 2 * arctan2 (sqrt (a), sqrt (1-a)) d = r * c # initial bearing y = sin (dLon) * cos (lat2) x = (cos (lat1)*sin (lat2) - sin (lat1)*cos (lat2)*cos (dLon)) b1 = arctan2 (y, x); # final bearing dLon = -dLon dLat = -dLat tmp = lat1 lat1 = lat2 lat2 = tmp y = sin (dLon) * cos (lat2) x = (cos (lat1) * sin (lat2) - sin (lat1) * cos (lat2) * cos (dLon)) b2 = arctan2 (y, x) b2 = mod ((b2 + pi), 2*pi) return (d, b1, b2)
def haversine(location1, location2=None): # calculates great circle distance __doc__ = """Returns the great circle distance of the given coordinates. INPUT: location1 = ((lat1, lon1), ..., n(lat1, lon1)) *location2 = ((lat2, lon2), ..., n(lat2, lon2)) *if location2 is not given a square matrix of distances for location1 will be put out OUTPUT: distance in km (dist1 ... ndist : : ndist1 ... ndist) shape will depend on the input METHOD: a = sin(dLat / 2) * sin(dLat / 2) + sin(dLon / 2) * sin(dLon / 2) * cos(lat1) * cos(lat2) c = 2 * arctan2(sqrt(a), sqrt(1 - a)) d = R * c where R is the earth's radius (6371 km) and d is the distance in km""" from itertools import product, combinations from pylab import deg2rad, sin, cos, arctan2, \ meshgrid, sqrt, array, arange if location2: location1 = array(location1, ndmin=2) location2 = array(location2, ndmin=2) elif location2 is None: location1 = array(location1, ndmin=2) location2 = location1.copy() # get all combinations using indicies ind1 = arange(location1.shape[0]) ind2 = arange(location2.shape[0]) ind = array(list(product(ind1, ind2))) # using combination inds to get lats and lons lat1, lon1 = location1[ind[:,0]].T lat2, lon2 = location2[ind[:,1]].T # setting up variables for haversine R = 6371. dLat = deg2rad(lat2 - lat1) dLon = deg2rad(lon2 - lon1) lat1 = deg2rad(lat1) lat2 = deg2rad(lat2) # haversine formula a = sin(dLat / 2) * sin(dLat / 2) + \ sin(dLon / 2) * sin(dLon / 2) * \ cos(lat1) * cos(lat2) c = 2 * arctan2(sqrt(a), sqrt(1 - a)) d = R * c # reshape accodring to the input D = d.reshape(location1.shape[0], location2.shape[0]) return D
def calculateFDunc(self): #Calculates the uncertainty of the FFT according to: # - J. M. Fornies-Marquina, J. Letosa, M. Garcia-Garcia, J. M. Artacho, "Error Propagation for the transformation of time domain into frequency domain", IEEE Trans. Magn, Vol. 33, No. 2, March 1997, pp. 1456-1459 #return asarray _tdData #Assumes tha the amplitude of each time sample is statistically independent from the amplitude of the other time #samples # Calculates uncertainty of the real and imaginary part of the FFT and ther covariance unc_E_real = [] unc_E_imag = [] cov = [] for f in self.getfreqs(): unc_E_real.append(py.sum((py.cos(2*py.pi*f*self._tdData.getTimes())*self._tdData.getUncEX())**2)) unc_E_imag.append(py.sum((py.sin(2*py.pi*f*self._tdData.getTimes())*self._tdData.getUncEX())**2)) cov.append(-0.5*sum(py.sin(4*py.pi*f*self._tdData.getTimes())*self._tdData.getUncEX()**2)) unc_E_real = py.sqrt(py.asarray(unc_E_real)) unc_E_imag = py.sqrt(py.asarray(unc_E_imag)) cov = py.asarray(cov) # Calculates the uncertainty of the modulus and phase of the FFT unc_E_abs = py.sqrt((self.getFReal()**2*unc_E_real**2+self.getFImag()**2*unc_E_imag**2+2*self.getFReal()*self.getFImag()*cov)/self.getFAbs()**2) unc_E_ph = py.sqrt((self.getFImag()**2*unc_E_real**2+self.getFReal()**2*unc_E_imag**2-2*self.getFReal()*self.getFImag()*cov)/self.getFAbs()**4) t=py.column_stack((self.getfreqs(),unc_E_real,unc_E_imag,unc_E_abs,unc_E_ph)) return self.getcroppedData(t)
def hillshade(data, scale=10.0, azdeg=165.0, altdeg=45.0): ''' Convert data to hillshade based on matplotlib.colors.LightSource class. Args: data - a 2-d array of data scale - scaling value of the data. higher number = lower gradient azdeg - where the light comes from: 0 south ; 90 east ; 180 north ; 270 west altdeg - where the light comes from: 0 horison ; 90 zenith Returns: a 2-d array of normalized hilshade ''' # convert alt, az to radians az = azdeg*pi/180.0 alt = altdeg*pi/180.0 # gradient in x and y directions dx, dy = gradient(data/float(scale)) slope = 0.5*pi - arctan(hypot(dx, dy)) aspect = arctan2(dx, dy) az = -az - aspect - 0.5*pi intensity = sin(alt)*sin(slope) + cos(alt)*cos(slope)*cos(az) mi, ma = intensity.min(), intensity.max() intensity = (intensity - mi)/(ma - mi) return intensity
def f_mdl(mdl, phi, maxord): """ given a periodic function "mdl" consisting of n data points (ranging from [0,2pi)), a fourier model of order maxord is computed for all phases in phi :args: mdl (1-by-k array): datapoints of the reference model, ranging from [0, 2pi). Length in datapoints is arbitrary. phi (1-by-n array): phases at which to evaluate the model maxord (int): order of the Fourier model to compute :returns: mdl_val (1-by-n array): value of the Fourier model obtained from mdl for the given phases phi """ spec_fy = fft.fft(mdl) as_, ac_ = spec_fy.imag, spec_fy.real sigout = zeros(len(phi)) for order in range(maxord): sigout -= sin(order * phi) * as_[order] sigout += cos(order * phi) * ac_[order] sigout += cos(order * phi) * ac_[-order] sigout += sin(order * phi) * as_[-order] sigout /= len(mdl) return sigout
def get_first_init(x0,epsilon,N): x_new = pl.copy(x0) print('getting the first initial condition') print('fiducial initial: '+str(x0)) # multi particle array layout [nth particle v, (n-1)th particle v , ..., 0th v, nth particle x, x, ... , 0th particle x] # we will use a change of coordinates to get the location of the particle relative to x0. First # we just find some random point a distace epsilon from the origin. # need 2DN random angles angle_arr = pl.array([]) purturbs = pl.array([]) # This is just an n-sphere for i in range(2*N): angle_arr = pl.append(angle_arr,random.random()*2.0*pl.pi) cur_purt = epsilon for a,b in enumerate(angle_arr[:-1]): cur_purt *= pl.sin(b) if i == (2*N-1): cur_purt = pl.sin(angle_arr[i]) else: cur_purt = pl.cos(angle_arr[i]) purturbs = pl.append(purturbs,cur_purt) print('sqrt of sum of squars should be epsilon -> is it? --> ' +str(pl.sqrt(pl.dot(purturbs,purturbs)))) print('len(purturbs) == 2N ? ' +str(len(purturbs)==(2*N))) return x_new+purturbs
def measureDistance(lat1, lon1, lat2, lon2): R = 6383.137 # Radius of earth at Chajnantor aprox. in KM dLat = (lat2 - lat1) * np.pi / 180. dLon = (lon2 - lon1) * np.pi / 180. a = pl.sin(dLat/2.) * pl.sin(dLat/2.) + pl.cos(lat1 * np.pi / 180.) * pl.cos(lat2 * np.pi / 180.) * pl.sin(dLon/2.) * pl.sin(dLon/2.) c = 2. * atan2(pl.sqrt(a), pl.sqrt(1-a)) d = R * c return d * 1000. # meters
def rotated_rectangle(x0,y0,w,h,rot): x = np.array([-w/2,w/2,w/2,-w/2,-w/2]) y = np.array([-h/2,-h/2,h/2,h/2,-h/2]) xrot = x*cos(rot)-y*sin(rot) yrot = x*sin(rot)+y*cos(rot) return xrot+x0, yrot+y0
def random_euler_angles(): r1,r2,r3 = pylab.random(3) q1 = pylab.sqrt(1.0-r1)*pylab.sin(2.0*pylab.pi*r2) q2 = pylab.sqrt(1.0-r1)*pylab.cos(2.0*pylab.pi*r2) q3 = pylab.sqrt(r1)*pylab.sin(2.0*pylab.pi*r3) q4 = pylab.sqrt(r1)*pylab.cos(2.0*pylab.pi*r3) phi = math.atan2(2.0*(q1*q2+q3*q4), 1.0-2.0*(q2**2+q3**2)) theta = math.asin(2.0*(q1*q3-q4*q2)) psi = math.atan2(2.0*(q1*q4+q2*q3), 1.0-2.0*(q3**2+q4**2)) return [phi,theta,psi]
def plot_trace(X, scale=1., angle=0.): fig = pl.figure(figsize=(12,4.75)) ax1 = fig.add_subplot(1, 2, 1) # plot boundary t = pl.arange(0,2*pl.pi,.01) ax1.plot(pl.cos(angle)*pl.cos(t) - pl.sin(angle)*pl.sin(t)/scale, pl.cos(angle)*pl.sin(t)/scale + pl.sin(angle)*pl.cos(t), 'k:') # plot samples if isinstance(X, mc.Stochastic): tr = [X.trace()[:,0], X.trace()[:,1]] else: tr = [X[0].trace(), X[1].trace()] ax1.plot(tr[0], tr[1], 'ko-') # decorate plot book_graphics.set_font() pl.xlabel('$X_1$') pl.ylabel('$X_2$', rotation=0) pl.axis([-1.1,1.1,-1.1,1.1]) pl.text(-1,1,'(a)', fontsize=16, va='top', ha='left') for i in range(2): if i == 0: ax2 = fig.add_subplot(2, 4, 3+4*i) ax2.plot(tr[i], 'k', drawstyle='steps-mid') else: ax2a = fig.add_subplot(2, 4, 3+4*i, sharex=ax2) ax2a.plot(tr[i], 'k', drawstyle='steps-mid') pl.xlabel('Sample') pl.xticks([25,50,75]) pl.yticks([-.5,0,.5]) pl.ylabel('$X_%d$'%(i+1), rotation=0) pl.axis([-5,105,-1.5,1.5]) pl.text(-1,1.25,'(%s)'%'bc'[i], fontsize=16, va='top', ha='left') if i == 0: ax3 = fig.add_subplot(2, 4, 4+4*i) ax3.acorr(tr[i].reshape(100), color='k') else: ax3a = fig.add_subplot(2, 4, 4+4*i, sharex=ax3) ax3a.acorr(tr[i].reshape(100), color='k') pl.xlabel('Autocorrelation') pl.xticks([-5,0,5]) pl.yticks([0., .5, 1]) pl.axis([-12,12,-.1,1.1]) pl.text(-10,1,'(%s)'%'de'[i], fontsize=16, va='top', ha='left') pl.setp(ax2.get_xticklabels(), visible=False) pl.setp(ax3.get_xticklabels(), visible=False) pl.subplots_adjust(wspace=.55, hspace=.1, bottom=.14,left=.13)
def Rot_y(self,y): """ Returns rotation matrix in y direction Parameters ---------- y: float Angle to rotate the matrix with """ return matrix([[cos(y), 0, -sin(y)], [ 0, 1, 0], [sin(y), 0, cos(y)]])
def Rot_x(self,x): """ Returns rotation matrix in x direction Parameters ---------- x: float Angle to rotate the matrix with """ return matrix([[1, 0, 0], [0, cos(x), sin(x)], [0,-sin(x), cos(x)]])
def Rot_z(self,z): """ Returns rotation matrix in z direction Parameters ---------- z: float Angle to rotate the matrix with """ return matrix([[ cos(z), sin(z), 0], [-sin(z), cos(z), 0], [ 0, 0, 1]])
def CoordsOrbScroll(theta,geo,shaveOn=True, just_involutes = False, Ndict = {}): from PDSim.scroll import scroll_geo shaveDelta=None if shaveOn==True: shaveDelta = pi/2 else: shaveDelta = 1e-16 (xshave, yshave) = Shave(geo, theta, shaveDelta) Nphi = Ndict.get('phi',500) Narc1 = Ndict.get('arc1',100) Nline = Ndict.get('line',100) Narc2 = Ndict.get('arc2',100) phi = np.linspace(geo.phi_ois, geo.phi_oie, Nphi) (x_oi,y_oi) = scroll_geo.coords_inv(phi,geo,theta,flag="oi") phi = np.linspace(geo.phi_oos, geo.phi_ooe - shaveDelta, Nphi) (x_oo,y_oo) = scroll_geo.coords_inv(phi,geo,theta,flag="oo") xarc1=geo.xa_arc1+geo.ra_arc1*cos(np.linspace(geo.t2_arc1,geo.t1_arc1,Narc1)) yarc1=geo.ya_arc1+geo.ra_arc1*sin(np.linspace(geo.t2_arc1,geo.t1_arc1,Narc1)) xline=np.linspace(geo.t1_line,geo.t2_line,Nline) yline=geo.m_line*xline+geo.b_line xarc2=geo.xa_arc2+geo.ra_arc2*cos(np.linspace(geo.t1_arc2,geo.t2_arc2,Narc2)) yarc2=geo.ya_arc2+geo.ra_arc2*sin(np.linspace(geo.t1_arc2,geo.t2_arc2,Narc2)) ro = geo.rb*(pi-geo.phi_fi0+geo.phi_fo0) om = geo.phi_fie-theta+3.0*pi/2.0 xarc1_o=-xarc1+ro*cos(om) yarc1_o=-yarc1+ro*sin(om) xline_o=-xline+ro*cos(om) yline_o=-yline+ro*sin(om) xarc2_o=-xarc2+ro*cos(om) yarc2_o=-yarc2+ro*sin(om) if just_involutes: x=np.r_[x_oo,x_oi[::-1]] y=np.r_[y_oo,y_oi[::-1]] else: if shaveOn: x=np.r_[x_oo,xshave,x_oi[::-1],xarc1_o,xline_o,xarc2_o] y=np.r_[y_oo,yshave,y_oi[::-1],yarc1_o,yline_o,yarc2_o] else: x=np.r_[x_oo,x_oi[::-1],xarc1_o,xline_o,xarc2_o] y=np.r_[y_oo,y_oi[::-1],yarc1_o,yline_o,yarc2_o] #Output as a column vector x=x.reshape(len(x),1) y=y.reshape(len(y),1) return x,y
def fromEulerTuple(self, euler): hea, att, ban = euler c1 = cos(hea/2) c2 = cos(att/2) c3 = cos(ban/2) s1 = sin(hea/2) s2 = sin(att/2) s3 = sin(ban/2) self.q[0] = c1*c2*c3 - s1*s2*s3 self.q[1] = s1*s2*c3 + c1*c2*s3 self.q[2] = s1*c2*c3 + c1*s2*s3 self.q[3] = c1*s2*c3 - s1*c2*s3
def plotHint(self, data,errordata,absfac=1,absnum=None, det='Pilatus', hroi=[0, 1023], vroi=[0, 1023], cen=None, ax_type='Pixels', wavelength=None,s2d_dist=None,pix_size=0.172,sh=None,alpha=None, mon=None): """plots the Integrated Intensity along horizontal direction as a function of pixels along vertical direction""" self.sumFiles(data,errordata, absfac=absfac,absnum=absnum,det=det,mon=mon) y=np.arange(vroi[0], vroi[1]+1) hint=np.sum(self.imageData[vroi[0]:vroi[1]+1, hroi[0]:hroi[1]+1], axis=1) hinterr=np.sqrt(np.sum(self.errorData[vroi[0]:vroi[1]+1, hroi[0]:hroi[1]+1]**2, axis=1)) if ax_type=='Angles': y=(-np.arange(vroi[0]-cen[1], vroi[1]-cen[1]+1)*pix_size+sh)*180.0/s2d_dist/np.pi elif ax_type=='Q': y=(-np.arange(vroi[0]-cen[1], vroi[1]-cen[1]+1)*pix_size-sh)/s2d_dist y=(pylab.sin(y)+pylab.sin(alpha))*2*pylab.pi/wavelength self.hintData=np.vstack((y, hint, hinterr)).transpose()
def rotecef (lat, long): clat = cos (lat) slat = sin (lat) clong = cos (long) slong = sin (long); zer = zeros (clat.shape); R = array([[-slat*clong, -slat*slong, clat], [-slong, clong, zer], [-clat*clong, -clat*slong, -slat]]) return R
def get_upstream_phi_res(p4Up, sigMatrix) : """Get the upstream phi resoluiton from it's four-vector and significance matrix""" # rotate so that upstream pt is pointing in x direction phi = -p4Up.Phi() R = ROOT.TMatrixD(2,2) R[0][0] = R[1][1]= cos(phi) R[0][1] = sin(phi) R[1][0] = -sin(phi) RI = copy(R) # R inverse RI.Invert() rotSig = RI*sigMatrix*R return sqrt(rotSig(1,1)/p4Up.Pt()**2)
def RotFromAngles(a): """See Tait - Bryan X1 - Y2 - Z3 on Wikipedia.""" h1 = a[0] h2 = a[1] h3 = a[2] c1 = cos(h1) s1 = sin(h1) c2 = cos(h2) s2 = sin(h2) c3 = cos(h3) s3 = sin(h3) return array([ [c2 * c3, - c2 * s3, s2], [c1 * s3 + c3 * s1 * s2, c1 * c3 - s1 * s2 * s3, - c2 * s1], [s1 * s3 - c1 * c3 * s2, c3 * s1 + c1 * s2 * s3, c1 * c2]])
def test(): test_file = 'visual_logging_test.zip' if os.path.exists(test_file): os.remove(test_file) basicConfig(test_file, level=DEBUG) xdata = pylab.arange(0, 2*pylab.pi, 0.02*pylab.pi) debug(pylab.sin(xdata), xdata, 'x', 'sin(x)', 'visual_logging test 1') flush() debug(0.5*pylab.sin(2*xdata-0.3), xdata, 'x', 'sin(2x-0.3)/2') debug(pylab.sqrt(xdata), xdata, 'x', 'sqrt(x)') flush() zf = zipfile.ZipFile(test_file, 'r') print zf.namelist() assert len(zf.namelist()) == 3, zf.namelist() zf.close()
def noise(noise_fun=pylab.rand, **params): """ :: Generate noise according to params dict params - parameter dict containing sr, and num_harmonics elements [None=default_noise_params()] noise_fun - the noise generating function [pylab.rand] """ params = _check_noise_params(**params) noise_dB = params['noise_dB'] num_harmonics = params['num_harmonics'] num_points = params['num_points'] cf = params['cf'] bw = params['bw'] sr = params['sr'] g = 10**(noise_dB / 20.0) * noise_fun(num_points) [b, a] = scipy.signal.filter_design.butter(4, bw * 2 * pylab.pi / sr, btype='low', analog=0, output='ba') g = scipy.signal.lfilter(b, a, g) # Phase modulation with *filtered* noise (side-band modulation should be narrow-band at bw) x = pylab.sin((2.0 * pylab.pi * cf / sr) * pylab.arange(num_points) + g) return x
def ICcircle_to_ICeuklid(IC): """ converts from IC in cirle parameters to IC in euklidean space (rotational invariant). The formats are: IC_euklid: [x, y, z, vx, vy, vz] IC_circle: [y, vy, |v|, |l|, phiv], where |v| is the magnitude of CoM velocity, |l| is the distance from leg1 (assumed to be at [0,0,0]) to CoM, and phiv the angle of the velocity in horizontal plane wrt x-axis *NOTE* for re-conversion, the leg position is additionally required, assumed to be [0,0,0] Further, it is assumed that the axis foot-CoM points in x-axis :args: IC (5x float): the initial conditions in circular coordinates :returns: IC (6x float): the initial conditions in euklidean space """ y, vy, v, l, phiv = IC z = 0 xsq = l**2 - y**2 if xsq < 0: raise RuntimeError('Error in initial conditions: y > l!') x = -sqrt(xsq) vhsq = v**2 - vy**2 if vhsq < 0: raise RuntimeError('Error in initial conditions: |vy| > |v|!') v_horiz = sqrt(vhsq) vx = v_horiz * cos(phiv) #vz = v_horiz * sin(phiv) vz = v_horiz * sin(phiv) return [x, y, z, vx, vy, vz]
def plot_fill(fig): t = arange(0.0, 1.01, 0.01) s = sin(2*2*pi*t) axes = fig.gca() axes.fill(t, s*exp(-5*t), 'r') axes.grid(True)
def _proj_onto_yd(self, x, y, beta): # unit vector pointing in the +xbeta direction ubeta = np.array([-cos(beta), sin(beta)]) r = np.array([x, y]) proj = np.dot(r, ubeta) * ubeta return proj
def eq_to_gal(ra, dec): """ expects dec between -pi/2 and pi/2 compares to pyephem within 0.45 arcsec returns lon, lat in radians """ alpha = galactic_north_equatorial[0] delta = galactic_north_equatorial[1] la = angles.from_degrees(122.932 - 90.0) b = arcsin(sin(dec) * sin(delta) + cos(dec) * cos(delta) * cos(ra - alpha)) l = arctan2( sin(dec) * cos(delta) - cos(dec) * sin(delta) * cos(ra - alpha), cos(dec) * sin(ra - alpha)) + la l += 2.0 * pylab.pi * (l < 0) l = l % (2.0 * pylab.pi) return l, b
def PhenomGW(M, eta, d, t0, phi0): f_merge = (0.29740 * eta**2. + 0.044810 * eta + 0.095560) / (pi * M) f_ring = (0.59411 * eta**2. + 0.089794 * eta + 0.19111) / (pi * M) sigma_ph = (0.50801 * eta**2. + 0.077515 * eta + 0.022369) / (pi * M) f_cut = (0.84845 * eta**2. + 0.12848 * eta + 0.27299) / (pi * M) w_ph = pi * sigma_ph / 2. * (f_merge / f_ring)**(2. / 3) C = 4.96e-6 * (M**5. / (f_merge)**7.)**(1. / 6) / d / pi**(2. / 3) * (5. * eta / 6.)**0.5 Psi = (0.17516 * eta**2. + 0.079483 * eta - 0.072390) Waveform = zeros([2, Nbins_f]) for i in range(0, Nbins_f): A_GW = 0. f_GW = Freq_BinCenter[i] * 4.96e-6 if (f_GW < f_merge): A_GW = C * (f_merge / f_GW)**(7. / 6.) else: if (f_GW < f_ring): A_GW = C * (f_merge / f_GW)**(2. / 3.) else: if (f_GW < f_cut): A_GW = C * w_ph * sigma_ph / 2. / pi / ( (f_GW - f_ring)**2. + sigma_ph**2. / 4.) Phi_GW = phi0 + 2. * pi * t0 * f_GW / 4.96e-6 + Psi / eta * ( pi * M * f_GW)**(-5. / 3.) Waveform[0, i] = A_GW * cos(Phi_GW) Waveform[1, i] = A_GW * sin(Phi_GW) return Waveform
def forward(self, length): if self._reset: self.clear() self._reset = False fig = self.fig ax = self.ax dx = length * py.cos(py.radians(self.angle)) dy = length * py.sin(py.radians(self.angle)) if self.pen == 'down': ax.plot([self.x, self.x + dx], [self.y, self.y + dy], color=self.color, linestyle='-') self.data.append([ [self.x, self.x + dx], [self.y, self.y + dy], self.color, ]) else: self.data.append([ [self.x, self.x + dx], [self.y, self.y + dy], None, ]) self.x += dx self.y += dy
def _example_matplotlib_plot(): import pylab from pylab import arange, pi, sin, cos, sqrt # Generate data x = arange(-2 * pi, 2 * pi, 0.01) y1 = sin(x) y2 = cos(x) # Plot data pylab.ioff() # print 'Plotting data' pylab.figure(1) pylab.clf() # print 'Setting axes' pylab.axes([0.125, 0.2, 0.95 - 0.125, 0.95 - 0.2]) # print 'Plotting' pylab.plot(x, y1, 'g:', label='sin(x)') pylab.plot(x, y2, '-b', label='cos(x)') # print 'Labelling' pylab.xlabel('x (radians)') pylab.ylabel('y') pylab.legend() print 'Saving to fig1.eps' pylab.savefig('fig1.eps') pylab.ion()
def lodnplot_mumodebug(di='.', num=0, I=1, nf=8, Nt=16): x, y, u = lod_vfield(di, num) ts = pl.linspace(0, 2 * pi, Nt + 1) up = pl.zeros([len(x), len(ts)]) for i in range(len(ts)): up[:, i] = u['X'][0, :].T print('0 mode: \tnorm:\t' + str(pl.norm(pl.norm(u['X']) + pl.norm(u['Y']) + pl.norm(u['Z'])))) for m in range(nf): x, y, uc = lod_vfield(di, 2 * m + 1 + i) x, y, us = lod_vfield(di, 2 * m + 2 + num) norc = 0 nors = 0 norc += pl.norm(uc['X']) nors += pl.norm(us['X']) for t in range(len(ts)): up[:, i] += uc['X'][:, 0] * cos(m * t) + us['X'][:, 0] * sin(m * t) print('c mode: ' + str(m) + '\tnorm:\t' + str(norc)) print('s mode: ' + str(m) + '\tnorm:\t' + str(nors)) # plot_vfield(x, y, u, I) pl.figure() # pl.plot(x, u['X'][0,:], '.-', label=r'$t='+str(t/pl.pi)+'\pi$') # pl.title(r'$t='+str(t/pl.pi)+'\pi$') pl.xlabel(r'$x$') pl.ylabel(r'$u$') pl.legend(loc=0) return x, y, u
def functions_one(): x = pylab.linspace(-20, 20, 1001) y1 = pylab.log(1 / (pylab.cos(x)**2)) y2 = pylab.log(1 / (pylab.sin(x)**2)) pylab.plot(x, y1) pylab.plot(x, y2) pylab.show()
def get_transform_Local2Global(angle): c = py.cos(angle) s = py.sin(angle) T_L2G = py.array([[c**2 ,s**2 ,-2*c*s], [s**2 ,c**2 ,2*c*s], [c*s ,-c*s ,c**2-s**2]]) return(T_L2G)
def getGradientImageInfo(gray): temp1=gray gx=np.array(0) gy=np.array(0) gd=gray gm=gray gx=cv2.Sobel(temp1, cv2.CV_16S, 1, 0, gx, 3, 1, 0, cv2.BORDER_DEFAULT) gy=cv2.Sobel(temp1, cv2.CV_16S, 0, 1, gy, 3, 1, 0, cv2.BORDER_DEFAULT) gm=cv2.add(cv2.pow(gx, 2), cv2.pow(gy, 2)) gm=pylab.sqrt(gm) gd=cv2.add(np.arctan(gx), np.arctan(gy))*(180/math.pi) resolution=5 gx=gx[::resolution*-1,::resolution] gy=gy[::resolution*-1,::resolution] gm=gm[::resolution*-1,::resolution] gd=gd[::resolution*-1,::resolution] X,Y = np.meshgrid( np.arange(0,2*math.pi,.2),np.arange(0,2*math.pi,.2)) U = pylab.cos(X) V = pylab.sin(Y) q=matplotlib.pyplot.quiver(gx,gy) # key=matplotlib.pyplot.quiverkey(q, 1, 1, 5, 'test', coordinates='data', color='b') #matplotlib.pyplot.show() matplotlib.pyplot.close() #cv2.imshow('gd', gd) return gx,gy,gm,gd, resolution
def calc_xy(self, num): start = 0.0 stop = 2 * self.pi step = 0.01 x = pylab.arange(start, stop, step) y = pylab.sin(num * x) return x, y
def testDetrend(): import pylab #something random to test with data = [[ (sin(random.gauss(0,1)*.01+float(i)/(n/51.0)))*(cos(random.gauss(0,1)*.01+float(i)/(n/31.0))) for i in range(n)] ] plot(data,'--',label="Original Data") detrend(data,channels = 1) plot(data,label="Detrended Data")
def plot_interface(n, length, lamda, delta_A): import pylab xs = pylab.linspace(0, length, n) ys = [-delta_A * pylab.sin(2 * pi / lamda * x) for x in xs] pylab.plot(xs, ys) pylab.show()
def xytToEcef(lat, long, height, bearing, radius): x = (radius + height) * cos(lat) * cos(long) y = (radius + height) * cos(lat) * sin(long) z = (radius + height) * sin(lat) Rtmp = rotecef(lat, long) R = coord_xfms.rotz(bearing).dot(Rtmp) rph = coord_xfms.rot2rph(R.transpose()) pose = array([]) pose = append(pose, array([x, y, z])) pose = append(pose, rph) return pose
def idft(s): N = len(s) out = pl.zeros(N) k = pl.arange(0, N) for t in range(0, N): out[t] = sum(s * (pl.cos(2 * pl.pi * k * t / N) + 1j * pl.sin(2 * pl.pi * k * t / N))) return out.real
def dft(s): N = len(s) out = pl.zeros(N) * 1j for k in range(0, N): for t in range(0, N): out[k] += s[t] * (pl.cos(2 * pl.pi * k * t / N) - 1j * pl.sin(2 * pl.pi * k * t / N)) return out / N
def idft(s): N = len(s) out = pl.zeros(N); for t in range(0,N): for k in range(0, N): out[k] += s[t]*(pl.cos(2*pl.pi*k*t/N) + 1j*pl.sin(2*pl.pi*k*t/N)) return out.real
def plot_sin(figure): from pylab import arange, sin, pi t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) axes = figure.gca() axes.plot(t, s, linewidth=1.0) axes.set_title('title')
def dft(s): N = len(s) out = pl.zeros(N)+0j; t = pl.arange(0,N) for k in range(0,N): out[k] = pl.sum(s*(pl.cos(2*pl.pi*k*t/N) - 1j*pl.sin(2*pl.pi*k*t/N))) return out/N
def getSine(min, max, n): # x = pylab.arange(0, n, 0.1) - XXX parametrize this x = pylab.arange(0, n, 0.0060) ys = pylab.sin(x) final_y = [] for y in ys: final_y.append(int(min + (max - min) / 2 + y * (max - min) / 2)) return final_y[:n]
def circle(xo, yo, r, N=100): x = np.zeros(N) y = np.zeros(N) t = np.linspace(0, 2 * pi, N) for i in arange(N): x[i] = xo + r * cos(t[i]) y[i] = yo + r * sin(t[i]) return (x, y)
def distance_check(): f0 = 0 distance = 0 distance_f = 0 frameN = pylab.arange(1, 600) phi = random.uniform(0, 2 * math.pi) for n in frameN: i = 2 * math.pi * (n / 600) f = (pylab.sin(i + phi) + pylab.sin(2 * i + phi) + pylab.sin(4 * i + phi)) / 3 distance_f = math.fabs(f - f0) distance += distance_f f0 = f print(distance)
def GetNoise(): Noise = zeros([2, Nbins_f]) for i in range(0, Nbins_f): A_n = rn.randn() * Noise_Ampl[i] / sqrt(2) Phi_n = rn.rand() * 2. * pi Noise[0, i] = A_n * cos(Phi_n) Noise[1, i] = A_n * sin(Phi_n) return Noise
def animate(delay=0.05, skip=1, figsize=(5, 5)): # delay will be per 100 units global _t from IPython.display import clear_output import time i = 0 interrupt_count = 0 while True: try: clear_output(wait=True) fig = py.figure(figsize=_t.figsize) ax = fig.add_subplot(111) ax.clear() ax.set_facecolor(_t.facecolor) ax.axis('equal') ax.axis(_t.limits) for x, y, t, k in _t.texts: ax.text(x, y, t, **k) for x, y, c, a, ps in _t.data[:i]: if c is not None: ax.plot(x, y, color=c, linestyle='-', linewidth=ps) x, y, c, a, ps = _t.data[i - 1] ax.plot( [x[1]], [y[1]], 'g', marker=(3, 0, a - 90), markersize=20, ) ax.plot([x[1] + 2 * py.cos(py.radians(a))], [y[1] + 2 * py.sin(py.radians(a))], 'r.') py.show() # each step is a delay time.sleep(delay) if i == len(_t.data): break i += skip if i > len(_t.data): # make sure to plot the last one i = len(_t.data) except KeyboardInterrupt: interrupt_count += 1 if interrupt_count == 1: delay = 0 else: i = len(_t.data)
def simulate_car_movement(self, cars, baseStations, scatter, com_lines): # temporal variables points = [[], []] scatter.remove() nodes = cars + baseStations while com_lines: com_lines[0].remove() del(com_lines[0]) # iterate over each car for car in cars: # get all the properties of the car velocity = round(np.random.uniform(car.speed[0], car.speed[1])) position_x = car.properties[0] position_y = car.properties[1] car.params['position'] = position_x, position_y, 0 angle = car.properties[2] # calculate new position of the car position_x = position_x + velocity * cos(angle) * self.time_per_iteraiton position_y = position_y + velocity * sin(angle) * self.time_per_iteraiton if (position_x < car.properties[3] or position_x > car.properties[4]) \ or (position_y < car.properties[5] or position_y > car.properties[6]): self.repeat(car) points[0].append(car.initial[0]) points[1].append(car.initial[1]) else: car.properties[0] = position_x car.properties[1] = position_y points[0].append(position_x) points[1].append(position_y) for node in nodes: if nodes == car: continue else: # compute to see if vehicle is in range inside = math.pow((node.properties[0] - position_x), 2) + math.pow((node.properties[1] - position_y), 2) if inside <= math.pow(node.params['range'], 2): if node.type == 'accessPoint': color = 'black' else: color = 'r' line = plot2d.plotLine2d([position_x, node.properties[0]], [position_y, node.properties[1]], color=color) com_lines.append(line) plot2d.plotLine(line) plot2d.graphUpdate(car) eval(mobility.continuePlot) scatter = plot2d.plotScatter(points[0], points[1]) plot2d.plotDraw() return [scatter, com_lines]
def get_undef_blade(): blade = {} blade["tower"] = py.array( [[0.0, 4.15 / 2, 4.15 / 2, -4.15 / 2, -4.15 / 2, 0.0], [0.0, 0.0, 115.63, 115.63, 0.0, 0.0]]) blade["shaft"] = py.array( [[ blade["tower"][0, 1], blade["tower"][0, 1] - 7.1 * py.cos(5 * py.pi / 180) ], [ blade["tower"][1, 2] + 2.75, blade["tower"][1, 2] + 2.75 + abs(7.1) * py.sin(5 * py.pi / 180) ]]) shaft_tan = py.diff(blade["shaft"]) shaft_tan = shaft_tan[0] + 1j * shaft_tan[1] shaft_tan /= abs(shaft_tan) shaft_normal = shaft_tan * 1j blade["hub_fun"] = lambda r: blade["shaft"][0, -1] + 1j * blade["shaft"][ 1, -1] + r * shaft_normal blade["hub"] = py.array( [[py.real(blade["hub_fun"](0)), py.real(blade["hub_fun"](2.8))], [py.imag(blade["hub_fun"](0)), py.imag(blade["hub_fun"](2.8))]]) cone = -2.5 * py.pi / 180 # Cone angle blade_normal = (py.cos(cone) + 1j * py.sin(cone)) * shaft_normal blade["blade_fun"] = lambda r, R, defl: blade["hub"][0, -1] + 1j * blade[ "hub" ][ 1, -1 ] + r * blade_normal + r / R * 2.332 * blade_normal / 1j + defl * blade_normal / 1j R = 86.366 blade["blade"] = py.array([[ py.real(blade["blade_fun"](0, R, 0)), py.real(blade["blade_fun"](R, R, 0)) ], [ py.imag(blade["blade_fun"](0, R, 0)), py.imag(blade["blade_fun"](R, R, 0)) ]]) #print(py.angle(blade_normal)*180/py.pi,py.angle(shaft_normal)*180/py.pi) return (blade)
def check_matplotlib_backends(): # from http://stackoverflow.com/questions/5091993/list-of-all-available-matplotlib-backends # get the directory where the backends live backends_dir = os.path.dirname(matplotlib.backends.__file__) # filter all files in that directory to identify all files which provide a backend backend_fnames = filter(is_backend_module, os.listdir(backends_dir)) backends = [backend_fname_formatter(fname) for fname in backend_fnames] print("supported backends: \t" + str(backends)) # validate backends backends_valid = [] for b in backends: try: plt.switch_backend(b) backends_valid += [b] except: continue print("valid backends: \t" + str(backends_valid)) # try backends performance for b in backends_valid: pylab.ion() try: plt.switch_backend(b) pylab.clf() tstart = time.time() # for profiling x = range(0,2*pylab.pi,0.01) # x-array line, = pylab.plot(x,pylab.sin(x)) for i in range(1,200): line.set_ydata(pylab.sin(x+i/10.0)) # update the data pylab.draw() # redraw the canvas print(b + ' FPS: \t' , 200/(time.time()-tstart)) pylab.ioff() except: print(b + " error :(")
def tests(): x = pylab.arange(0.0, 2 * pylab.pi, 0.01) list_y = (pylab.sin(x), pylab.sin(2 * x)) plot_and_format((x, ), (list_y[0], )) exportplot('test/test1_one_curve.png') pylab.clf() list_x = (x, x) plot_and_format(list_x, list_y) exportplot('test/test2_two_curves.png') pylab.clf() list_format = ('k-', 'r--') plot_and_format(list_x, list_y, list_format=list_format) exportplot('test/test3_two_curves_formatting.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xlabel='hello x axis') exportplot('test/test4_two_curves_formatting_xlab.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, legend=['sin($x$)', 'sin($2x$)']) exportplot('test/test5_two_curves_formatting_legend.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xticks={ 'ticks': [0, pylab.pi, 2 * pylab.pi], 'labels': ['0', '$\pi$', '$2\pi$'] }) exportplot('test/test6_two_curves_formatting_xticks.png') pylab.clf() plot_and_format(list_x, list_y, list_format=list_format, xticks={ 'ticks': [0, pylab.pi, 2 * pylab.pi], 'labels': ['0', '$\pi$', '$2\pi$'] }, xlim=[0, 2 * pylab.pi]) exportplot('test/test7_two_curves_formatting_xticks_xlim.png') pylab.clf()
def haversinus(vinkel): """Haversinus funksjonen Brukes for å regne ut vinkelen mellom to punkt på et kuleskall Du kan lese om denne funksjonen her https://en.wikipedia.org/wiki/Versine """ return sin(vinkel / 2)**2
def z_rotation(self, theta): """ This method rotates the SimpleCell object in 3D space around the z-axis by a user-specified number of degrees. """ theta *= (pylab.pi / 180) for section in self.all: for point in range(int(h.n3d(sec=section))): xold = h.x3d(point, sec=section) yold = h.y3d(point, sec=section) xnew = xold * pylab.cos(theta) - yold * pylab.sin(theta) ynew = xold * pylab.sin(theta) + yold * pylab.cos(theta) h.pt3dchange(point, xnew, ynew, h.z3d(point, sec=section), h.diam3d(point, sec=section), sec=section)
def get_touchdown(self, t, y, params): """ Compute the touchdown position of the leg. Overwrite this for different leg parameters! :args: t (float): time y (6x float): state of the CoM params (4x float): leg parameter: stiffness, l0, alpha, beta :returns: [xFoot, yFoot, zFoot] the position of the leg tip """ k, l0, alpha, beta = params xf = y[0] + l0 * cos(alpha) * cos(beta) yf = y[1] - l0 * sin(alpha) zf = y[2] - l0 * cos(alpha) * sin(beta) return array([xf, yf, zf])