def J(self,t): # the -1 in the lines below is for the right rounding with int() # x1 is position of p1 (particle 1) x1 = self.sol[int(t/self.dt)-1,2] # x2 is velocity of p1 x2 = self.sol[int(t/self.dt)-1,0] # x3 is position of p2 x3 = self.sol[int(t/self.dt)-1,3] # x4 is velocity of p2 x4 = self.sol[int(t/self.dt)-1,1] # These are the differentials of the forces of the particles. Writen like this to make the # matrix below easier to read f14 is force of p2 on p1 _dx1 is derivitive with respect to x1 # Note on 1/r2 part -> goes to cubic so it will always retain its sign. df13_dx1 = -2.0/(x1-x3)**3 + (polygamma(2,1.0+(x1-x3)/self.d)+polygamma(2,1.0-(x1-x3)/self.d))/self.d**3 # the final deriviative of -x3 just gives you the negative of everything above df13_dx3 = -df13_dx1 df31_dx1 = 2.0/(x3-x1)**3 - (polygamma(2,1.0-(x3-x1)/self.d)+polygamma(2,1.0+(x3-x1)/self.d))/self.d**3 df31_dx3 = -df31_dx1 # define the matrix elements of the time dependent jacobian jacobian = pl.array([ \ [0.0 , 1.0 , 0.0 , 0.0], [self.A*pl.cos(x1)*pl.cos(t)+df13_dx1, -self.beta, df13_dx3 , 0.0], [0.0 , 0.0 , 0.0 , 1.0], [df31_dx1 , 0.0 , self.A*pl.cos(x3)*pl.cos(t)+df31_dx3, -self.beta]\ ]) return jacobian
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 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 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 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 lat_2_R(lat): """Takes a geodetic latitude and puts out the distance from the center of an ellipsoid Earth to the surface Arguments: lat (float): Geodetic Latitude angle [degrees]. Returns: (float): Geocentric distance [km] """ R_polar = 6356.752314245 R_eq = 6378.137 lat = lat / 180 * pi R = sqrt( ((R_eq ** 2 * cos(lat)) ** 2 + (R_polar ** 2 * sin(lat)) ** 2) / ((R_eq * cos(lat)) ** 2 + (R_polar * sin(lat)) ** 2) ) # e = sqrt(1-R_polar**2/R_eq**2) # R = R_eq/sqrt(1-e**2*sin(lat/180*pi)**2) # R = sqrt( ( (R_eq**2*cos(lat))**2 + (R_polar**2*sin(lat))**2 ) / ( (R_eq*cos(lat))**2 + (R_polar*sin(lat))**2 ) ) return R
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 SpherePlot( theta, phi, data, title='', xlabel='x', ylabel='y', zlabel='z', color='b', fig=py.figure(), ax=None, pos=111 ): """Plots data in terms of polar angles THETA and PHI. x must be a tuple of meshgrids: Polar angle, THETA, as first element of x, azimuthal angle, PHI, as second element of x. Note: Sphere plots require higher resolution than mesh plots. 300 is good.""" X = py.sin(theta)*py.cos(phi)*data Y = py.sin(theta)*py.sin(phi)*data Z = py.cos(theta)*data if ax is None: ax = fig.add_subplot( pos, projection='3d' ) ax.ticklabel_format(style='sci',scilimits=(-1,2),axis='both') # ax.xaxis.major.formatter._useMathText = True # ax.yaxis.major.formatter._useMathText = True # ax.zaxis.major.formatter._useMathText = True # Sets scientific notation ax.plot_surface( X, Y, Z, color=color ) oldlim = 0 else: ax.plot_surface( X, Y, Z, color=color ) oldlim = ax.get_xlim()[1] lim = py.amax(data) lim = max(lim,oldlim) ax.set_xlim(-lim,lim) ax.set_ylim(-lim,lim) ax.set_zlim(-lim,lim) return fig, ax
def angleDistributionControlData(bin_count): bins = [180.0*x/float(bin_count) for x in range(bin_count + 1)] bin_pairs = zip(bins[:-1],bins[1:]) weights = [pl.cos(b*pl.pi/180) - pl.cos(a*pl.pi/180) for (a,b) in bin_pairs] total = sum(weights) weights = [w/total for w in weights] return bins,weights
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 convert(polar,R): cartesian=pl.zeros((polar.shape[0],4)) cartesian[:,0]=R * pl.sin(polar[:,1]) * pl.cos(polar[:,0]); cartesian[:,1]=R * pl.sin(polar[:,1]) * pl.sin(polar[:,0]) * pl.cos(polar[:,2]); cartesian[:,2]=R * pl.cos(polar[:,1]); cartesian[:,3]=R * pl.sin(polar[:,1]) * pl.sin(polar[:,0]) * pl.sin(polar[:,2]); return cartesian
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 query_nvss(options, ra0, dec0, s=">0.0", proj='SIN'): ''' query_nvss: module which queries the NVSS using the Vizier protocol. inputs: ra0, dec0, s="<20" ra0 = the central ra in degrees dec0 = the central dec in degrees s = the flux cutoff returns L, M (relative coordinates in degrees), N (number of sources), S (1.4GHz Flux Density in mJy) ''' v = Vizier(column_filters={"S1.4":s}) v.ROW_LIMIT = 10000 result = v.query_region(coord.SkyCoord(ra=ra0, dec=dec0, unit=(u.deg, u.deg), frame='icrs'), radius=Angle(1, "deg"), catalog='NVSS') ra = result[0]['_RAJ2000'] dec = result[0]['_DEJ2000'] N = len(result[0]) if proj.upper()=='SIN': L = (ra-ra0)*pl.cos(dec*deg2rad) M = dec-dec0 if proj.upper()=='NCP': L = 57.2957795*pl.cos(deg2rad*dec)*pl.sin(deg2rad*(ra-ra0)) M = 57.2957795*(pl.cos(deg2rad*dec0) - pl.cos(deg2rad*dec)*pl.cos(deg2rad*(ra-ra0)))/pl.sin(deg2rad*dec0) S = result[0]['S1.4'] ascii.write(result[0], options.outfile+'.dat', format='tab') ann_writer(options, result[0]) return L, M, N, S
def plot2D(self,ta): r = (self.h**2/self.ref.mu)*(1.0/(1.0+self.e*cos(ta))) rv = r * array([cos(ta),sin(ta),0]) #v = self.ref.mu / self.h #vv = v * array([-sin(ta),self.e+cos(ta),0]) return rv#,vv)
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 cosBell2(x): "Function defining a different cosine bell as a function of position, x" bell= lambda x: 0.25*(1 - pl.cos(4*pl.pi*x))*(1 - pl.cos(pl.pi*x)**2) #chooses bell(x) where condition is true, else chooses zeros phi = pl.where((x<0.5) | (x>=1.0), bell(x), 0.) return phi
def convert(polar, R): cartesian = pl.zeros((polar.shape[0], 4)) cartesian[:, 0] = R * pl.sin(polar[:, 1]) * pl.cos(polar[:, 0]) cartesian[:, 1] = R * pl.sin(polar[:, 1]) * pl.sin(polar[:, 0]) * pl.cos( polar[:, 2]) cartesian[:, 2] = R * pl.cos(polar[:, 1]) cartesian[:, 3] = R * pl.sin(polar[:, 1]) * pl.sin(polar[:, 0]) * pl.sin( polar[:, 2]) return cartesian
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 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 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 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 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 my_hor_to_eq(az, el, lat, lsts): dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) argument = (sin(el) - sin(lat) * sin(dec)) / (cos(lat) * cos(dec)) argument = clip(argument, -1.0, 1.0) H = arccos(argument) flag = sin(az) > 0 H[flag] = 2.0*pi - H[flag] ra = lsts - H ra %= 2*pi return ra,dec
def eq_to_hor(ra, dec, lat, lst): H = lst - ra el = arcsin(sin(dec) * sin(lat) + cos(dec) * cos(lat) * cos(H)) az = arccos((sin(dec) - sin(lat) * sin(el)) / (cos(lat) * cos(el))) flag = sin(H) > 0 if type(flag) is ndarray: az[flag] = 2.0 * pi - az[flag] elif flag: az = 2.0 * pi - az return az, el
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 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 draw_rand_sphere_pos(self): azimuth = (pl.rand(self.n) - 0.5) * 2 * pl.pi zenith = pl.arccos(2 * pl.rand(self.n) - 1) r = pl.rand(self.n)**(2. / 3.) * self.radius x = r * pl.sin(zenith) * pl.cos(azimuth) y = r * pl.sin(zenith) * pl.sin(azimuth) z = r * pl.cos(zenith) soma_pos = {'xpos': x, 'ypos': y, 'zpos': z, 'r': r} return soma_pos
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_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_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 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 main(): # 3. Create a list A of 600 random numbers bound between (0:10) A = [random.random_integers(0, 10) for i in range(600)] print("\033[1mList A: \n\033[0m", A) # 4. Create an array B with with 500 elements bound in the range [-3*pi:2*pi] B = plb.linspace(-3 * plb.pi, 2 * plb.pi, 500, endpoint=True) print("\n\033[1mArray B: \n \033[0m", B) # 7. Return the result from the function to C C = functionOverwriter(A) print("\n\033[1mC: \033[0m", type(C)) print(C) # 8. Cast C as an array C = array(C) print("\n\033[1mC: \033[0m", type(C)) print(C) # 9. Add C to B (think of C as noise) and record the result in D D = B + C[:B.size] print("\n\033[1mD: \033[0m", D) # 10. Create a figure, give it a title and specify your own size and dpi plb.figure(figsize=(10, 6), dpi=120) plb.title("Sin(D)") # 11. Plot the sin of D, in the (2,1,1) location of the figure plb.subplot(2, 1, 1) plb.plot(plb.sin(D), color="r", label="Sin") # 12. Overlay a plot of cos using D, with different color, thickness and type of line plb.plot(plb.cos(D), color="b", linewidth=2, linestyle="-.", label="Cos") # 13. Create some space on top and bottom of the plot (on the y axis) and show the grid plb.ylim(min(plb.cos(D)) - .5, max(plb.cos(D)) + .5) plb.grid() # 14. Specify the following: title, Y-axis label and legend to fit in the best way plb.title("Sin(D) and Cos(D)") plb.legend() plb.ylabel("Y-axis") plb.legend(loc="upper right") # 15. Plot the tan of D, in location (2,1,2) with grid showing, X-axis label, Y-axis label # and legend on top right plb.subplot(2, 1, 2) plb.plot(plb.tan(D), color="g", label="Tan") plb.ylabel("Y-axis") plb.xlabel("X-axis") plb.legend(loc="upper right") plb.show()
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 get_xy_coords_for_circles(circles): for i in range(len(circles)): x_coor = circles[i]["lon"] * 111.320 * cos( np.radians(circles[i]["lat"])) * 1000 y_coor = circles[i]["lat"] * 110.54 * 1000 # converting from lat, lon to coordinates in metre from (0,0). c_xc = np.full(np.size(x_coor, 1), np.nan) c_yc = np.full(np.size(x_coor, 1), np.nan) c_r = np.full(np.size(x_coor, 1), np.nan) for j in range(np.size(x_coor, 1)): a = ~np.isnan(x_coor.values[:, j]) if a.sum() > 4: c_xc[j], c_yc[j], c_r[j], _ = cf.least_squares_circle([ (k, l) for k, l in zip(x_coor.values[:, j], y_coor.values[:, j]) if ~np.isnan(k) ]) circle_y = np.nanmean(c_yc) / (110.54 * 1000) circle_x = np.nanmean(c_xc) / (111.320 * cos(np.radians(circle_y)) * 1000) circle_diameter = np.nanmean(c_r) * 2 xc = [None] * len(x_coor.T) yc = [None] * len(y_coor.T) xc = np.mean(x_coor, axis=0) yc = np.mean(y_coor, axis=0) delta_x = x_coor - xc # *111*1000 # difference of sonde long from mean long delta_y = y_coor - yc # *111*1000 # difference of sonde lat from mean lat circles[i]["platform_id"] = circles[i].platform_id.values[0] circles[i]["flight_altitude"] = circles[i].flight_altitude.mean( ).values circles[i]["circle_time"] = ( circles[i].launch_time.mean().values.astype("datetime64")) # circles[i].encoding["circle_time"] = { # "units": "seconds since 2020-01-01", # "dtype": "datetime64[ns]", # } circles[i]["circle_lon"] = circle_x circles[i]["circle_lat"] = circle_y circles[i]["circle_diameter"] = circle_diameter circles[i]["dx"] = (["sounding", "alt"], delta_x) circles[i]["dy"] = (["sounding", "alt"], delta_y) return print("Circles ready for regression")
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 cos(self,nmax=5): if type(self) == Dual: return Dual(pl.cos(self.fun), -self.der*pl.sin(self.fun)) elif type(self) == Taylor: self = autoPromocion(self,max(gradoMaxTaylor(self),nmax)) n = gradoMaxTaylor(self) C = Taylor([0]*n) for k in range(n): C += ((-1.)**k)*(self**(2*k))/fact(2*k) return C else: return pl.cos(self)
def hor_to_eq(az, el, lat, lst): dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az)) argument = (sin(el) - sin(lat) * sin(dec)) / (cos(lat) * cos(dec)) argument = pylab.clip(argument, -1.0, 1.0) H = arccos(argument) flag = sin(az) > 0 if type(flag) is ndarray: H[flag] = 2.0 * pi - H[flag] elif flag: H = 2.0 * pi - H ra = lst - H ra %= 2 * pi return ra, dec
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 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 aa(current_data): from pylab import ticklabel_format, xticks, gca, cos, pi, savefig title_hours(current_data) ticklabel_format(format='plain', useOffset=False) xticks(rotation=20) a = gca() a.set_aspect(1. / cos(46.349 * pi / 180.))
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 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 errors(a,psi1,psi2,nn): ''' find the Newton errors, vector of ddPsi(i+1/n+2) + lambda cos(Psi(i+1/n+2)) = 0 (0 <= i < n) and um(w_j sin(Psi_j)) = 0 Inputs ---------- # a = polynomical constants (needs to be in list/array form so len() command works) # s = position along polynomial (needs to be in list/array form so len() command works) # psi1,psi2: start and end orientation # nn: number of interation points Outputs ---------- # v: vector of ddPsi(i+1/n+2) + lambda cos(Psi(i+1/n+2)) = 0 (0 <= i < n) and um(w_j sin(Psi_j)) = 0 ''' n = len(a)-1 v = pl.zeros(n+1) s = (pl.arange(n)+1)/(n+1) v[:-1] = ddPsi(a[:-1],s)+a[-1]*pl.cos(Psi(a[:-1],s,psi1,psi2)) v[-1] = simpssin(nn,psi1,psi2,a[:-1]) return v
def gabor_patch( sigma_deg=2, radius_deg=6, px_deg=50, sf_cyc_deg=2, phase_deg=0, #phase of cosine in degrees contrast=1.0): """Return a gabor patch texture of the given dimensions and parameters.""" height = width = radius_deg * px_deg x = pylab.linspace(-radius_deg, radius_deg, width) X, Y = pylab.meshgrid(x, x) L = pylab.exp(-(X**2 + Y**2) / sigma_deg**2) #gaussian envelope #use around to round towards zero, otherwise you will get banding artifacts #dtype must be int for proper conversion to int and init of image data #I = pylab.array(-pylab.zeros(X.size)*max_range + neutral_gray, dtype='int') I = pylab.array(pylab.around( contrast * pylab.cos(2 * pylab.pi * (sf_cyc_deg) * X + phase_deg * pylab.pi / 180.) * L * max_range) + neutral_gray, dtype='int').ravel() IA = pylab.ones(I.size * 2, dtype='int') * 255 IA[:-1:2] = I #Need alpha=255 otherwise image is mixed with background #Data format for image http://www.pyglet.org/doc/programming_guide/accessing_or_providing_pixel_data.html data = array.array('B', IA) gabor = pyglet.image.ImageData(width, height, 'IA', data.tostring()) return gabor
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 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 synthesis(self,amps,freqs): delta = (freqs - self.fc)*(2*pl.pi*self.h)/self.sr self.phs += delta X = amps*pl.cos(self.phs) + 1j*amps*pl.sin(self.phs) y = istft(X,self.win,self.n) self.n += self.h return y
def lodnplot_mumodebug(di='.', i=0, I=1, nf=8, Nt=16): x, y, u = lod_vfield(di, i) 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 + i) 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 get_first_init(x0,epsilon): # 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. # This is a little more tricky in 4 dimensions theta = random.random()*2.0*pl.pi phi = random.random()*2.0*pl.pi psi = random.random()*2.0*pl.pi x = epsilon*pl.cos(psi) vx = epsilon*pl.sin(psi)*pl.cos(phi) y = epsilon*pl.sin(psi)*pl.sin(phi)*pl.sin(theta) vy = epsilon*pl.sin(psi)*pl.sin(phi)*pl.cos(theta) # change of coordinates return x0 + pl.array([vx,vy,x,y])
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 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 tan(self): if type(self) == Dual: return Dual(pl.tan(self.fun), self.der/(pl.cos(self.fun)**2)) elif type(self) == Taylor: return sin(self)/cos(self) else: return pl.tan(self)
def randgen(std): pl.seed(int(std*100)) a = 0.2*pl.cos(x)*pl.sqrt(repeats) b = pl.zeros(npts) for r in range(repeats): b += (0.5-pl.rand(npts))*std return a+b
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 gradxy(lon, lat, ssh): from numpy import pi, c_, r_, cos, diff, zeros from pylab import meshgrid r = 6371.e3 if lon.ndim == 1: lon, lat = meshgrid(lon, lat) x = 2 * pi * r * cos(lat * pi / 180.) * lon / 360. y = 2 * pi * r * lat / 360. def uv(x, y, ssh): x = c_[x, x[:, -2]] y = r_[y, y[-2, :].reshape(1, -1)] sshx = c_[ssh, ssh[:, -1]] v = diff(sshx, axis=1) / diff(x, axis=1) v[:, -1] = v[:, -2] sshy = r_[ssh, ssh[-1, :].reshape(1, -1)] u = diff(sshy, axis=0) / diff(y, axis=0) u[-2, :] = u[-1, :] return u, v if len(ssh.shape) == 2: return uv(x, y, ssh) elif len(ssh.shape) == 3: u, v = zeros(ssh.shape), zeros(ssh.shape) for i in range(ssh.shape[0]): ut, vt = uv(x, y, ssh[i, :, :]) v[i, :, :] = vt u[i, :, :] = ut return u, v
def mixed(x): "A flat peak in one location and a cosine bell in another" return pl.where((x >= 0.2) & (x <= 0.3), 1, \ pl.where((x >= 0.4) & (x <= 0.8), \ 0.5*(1 + pl.cos(5*pl.pi*(x-0.6))), pl.where((x > 0.1) & (x < 0.2), 10*(x-0.1), pl.where((x > 0.3) & (x < 0.35), 20*(0.35-x), 0))))
def aa_patches(current_data): from pylab import ticklabel_format, xticks, gca, cos, pi, yticks ticklabel_format(format='plain',useOffset=False) xticks([180, 200, 220, 240], rotation=20, fontsize = 28) yticks(fontsize = 28) a = gca() a.set_aspect(1./cos(41.75*pi/180.))