def sphere_edge_area(x, y, r): """ Area of a sphere 'edge' of sphere with radius R that is bounded by two perpendicular flat planes `h0`, `h1` from the origin. h >= 0, h < R""" p = np.sqrt(r**2 - x**2 - y**2) A = (r - x - y)*np.pi - 2*r*np.arctan(x*y/(p*r)) + \ 2*x*np.arctan(y/p) + 2*y*np.arctan(x/p) return A*r
def remlplen_ichige(fp, fs, dp, ds): """Determine the length of the low pass filter with passband frequency fp, stopband frequency fs, passband ripple dp, and stopband ripple ds. fp and fs must be normalized with respect to the sampling frequency. Note that the filter order is one less than the filter length. References ---------- K. Ichige, M. Iwaki, and R. Ishii, Accurate Estimation of Minimum Filter Length for Optimum FIR Digital Filters, IEEE Transactions on Circuits and Systems, 47(10):1008-1017, October 2000. """ dF = fs-fp v = lambda dF,dp:2.325*((-log10(dp))**-0.445)*dF**(-1.39) g = lambda fp,dF,d:(2.0/pi)*arctan(v(dF,dp)*(1.0/fp-1.0/(0.5-dF))) h = lambda fp,dF,c:(2.0/pi)*arctan((c/dF)*(1.0/fp-1.0/(0.5-dF))) Nc = ceil(1.0+(1.101/dF)*(-log10(2.0*dp))**1.1) Nm = (0.52/dF)*log10(dp/ds)*(-log10(dp))**0.17 N3 = ceil(Nc*(g(fp,dF,dp)+g(0.5-dF-fp,dF,dp)+1.0)/3.0) DN = ceil(Nm*(h(fp,dF,1.1)-(h(0.5-dF-fp,dF,0.29)-1.0)/2.0)) N4 = N3+DN return int(N4)
def connect_edges(self): """Connect detected edges based on their slopes.""" # Fitting a straight line to each edge. p0 = [0., 0.] radian2angle = 180. / np.pi for edge in self.edges: p1, s = leastsq(self.residuals, p0, args=(edge['x'][:-1], edge['y'][:-1])) edge['slope'] = p1[0] edge['intercept'] = p1[1] edge['slope_angle'] = np.arctan(edge['slope']) * radian2angle # Connect by the slopes of two edges. len_edges = len(self.edges) for i in range(len_edges - 1): for j in range(i + 1, len_edges): if np.abs(self.edges[i]['slope_angle'] - self.edges[j]['slope_angle']) <= \ self.connectivity_angle: # Then, the slope between the centers of the two edges # should be similar with the slopes of # the two lines of the edges as well. c_slope = (self.edges[i]['y_center'] - self.edges[j]['y_center']) / \ (self.edges[i]['x_center'] - self.edges[j]['x_center']) c_slope_angle = np.arctan(c_slope) * radian2angle if np.abs(c_slope_angle - self.edges[i]['slope_angle']) <= \ self.connectivity_angle and \ np.abs(c_slope_angle - self.edges[j]['slope_angle']) <= \ self.connectivity_angle: self.edges[i]['connectivity'] = self.edges[j]['index'] break
def hertz_to_bark(cf): """ :: Convert frequency in Hz to Bark band """ return 13 * np.arctan(0.00076 * cf) + 3.5 * np.arctan( (cf / 7500.)**2)
def _fgreen3d(self, z, y, x): ''' Return the periodic integrated greens funcion on the 'original' domain Qiang, Lidia, Ryne,Limborg-Deprey, PRSTAB 10, 129901 (2007) Args: x,y,z: arrays, e.g. x, y, z = np.meshgrid(xx, yy, zz) ''' abs_r = np.sqrt(x * x + y * y + z * z) inv_abs_r = 1./abs_r tmpfgreen = (-( + z*z * np.arctan(x*y*inv_abs_r/z) + y*y * np.arctan(x*z*inv_abs_r/y) + x*x * np.arctan(y*z*inv_abs_r/x) )/2. + y*z*np.log(x+abs_r) + x*z*np.log(y+abs_r) + x*y*np.log(z+abs_r)) fgreen = np.zeros((2 * self.mesh.nz, 2 * self.mesh.ny, 2 * self.mesh.nx), dtype=np.complex128) # evaluate the indefinite integral per cell (int_a^b f = F(b) - F(a)) fgreen[:self.mesh.nz, :self.mesh.ny, :self.mesh.nx] = ( tmpfgreen[ 1:, 1:, 1:] -tmpfgreen[:-1, 1:, 1:] -tmpfgreen[ 1:, :-1, 1:] +tmpfgreen[:-1, :-1, 1:] -tmpfgreen[ 1:, 1:, :-1] +tmpfgreen[:-1, 1:, :-1] +tmpfgreen[ 1:, :-1, :-1] -tmpfgreen[:-1, :-1, :-1] ) * 1./self.mesh.volume_elem # divide by vol_elem to average! return fgreen
def _select_events_outside_pie(sources, events, pointing_position, fov_radius): """The index table of the events outside the pie Parameters ---------- sources : `~astropy.table.Table` Table of excluded sources. Required columns: RA, DEC, Radius events : `gammapy.data.EventList` List of events for one observation pointing_position : `~astropy.coordinates.SkyCoord` Coordinates of the pointing position fov_radius : `~astropy.coordinates.Angle` Field of view radius Returns ------- idx : `~numpy.array` coord of the events that are outside the pie """ sources = _add_column_and_sort_table(sources, pointing_position) radius = Angle(sources["Radius"])[0] phi = Angle(sources["phi"])[0] separation = Angle(sources["separation"])[0] if separation > fov_radius: return np.arange(len(events)) else: phi_min = phi - np.arctan(radius / separation) phi_max = phi + np.arctan(radius / separation) phi_events = pointing_position.position_angle(events.radec) idx = np.where((phi_events > phi_max) | (phi_events < phi_min)) return idx[0]
def calc_theta(x_predicted, y_predicted, x_true, y_true, x_ref, y_ref): """ Calculate the angle the predicted position and the true position, where the zero degree corresponds to the line joing the true halo position and the reference point given. Arguments: x_predicted, y_predicted: vector for predicted x- and y-positions (1 to 3 elements) x_true, y_true: vector for known x- and y-positions (1 to 3 elements) Note that the input of these are matched up so that the first elements of each vector are associated with one another x_ref, y_ref: scalars of the x,y coordinate of reference point Returns: Theta: A vector containing the angles of the predicted halo w.r.t the true halo with the vector joining the reference point and the halo as the zero line. """ num_halos=len(x_predicted) theta=np.zeros([num_halos+1],float) #Set up the array which will pass back the values psi = np.arctan( (y_true-y_ref)/(x_true-x_ref) ) # Angle at which the halo is at #with respect to the reference poitn phi = np.arctan((y_predicted-y_true)/(x_predicted-x_true)) # Angle of the estimate #wrt true halo centre #Before finding the angle with the zero line as the line joiing the halo and the reference #point I need to convert the angle produced by Python to an angle between 0 and 2pi phi =convert_to_360(phi, x_predicted-x_true,\ y_predicted-y_true) psi = convert_to_360(psi, x_true-x_ref,\ y_true-y_ref) theta = phi-psi #The angle with the baseline as the line joing the ref and the halo theta[theta< 0.0]=theta[theta< 0.0]+2.0*mt.pi #If the angle of the true pos wrt the ref is #greater than the angle of predicted pos #and the true pos then add 2pi return theta
def Crit_points(self,Data,xfl=None): Im = pp.Image() if xfl is None: xfl = 5.0 Vpol = np.sqrt(Data.v1**2 + Data.v2**2) Bpol = np.sqrt(Data.b1**2 + Data.b2**2) Btot = np.sqrt(Data.b1**2 + Data.b2**2 + Data.b3**2) Valfven = Bpol/np.sqrt(Data.rho) Vfast = Btot/np.sqrt(Data.rho) Varat = Vpol/Valfven Vfrat = Vpol/Vfast Dummy = np.zeros(shape=Valfven.shape) fldict = Im.field_line(Data.b1,Data.b2,Data.x1,Data.x2,Data.dx1,Data.dx2,xfl,0.001) Qx = fldict['qx'] Qy = fldict['qy'] Fl_Varat = np.zeros(shape=(2,len(Qx))) Fl_Vfrat = np.zeros(shape=(2,len(Qx))) for i in range(len(Qx)): Fl_Varat[:,i] = Im.field_interp(Varat,Dummy,Data.x1,Data.x2,Data.dx1,Data.dx2,Qx[i],Qy[i]) Fl_Vfrat[:,i] = Im.field_interp(Vfrat,Dummy,Data.x1,Data.x2,Data.dx1,Data.dx2,Qx[i],Qy[i]) Val1 = [Qx[np.abs(Fl_Varat[0,:]-1.0).argmin()],Qy[np.abs(Fl_Varat[0,:]-1.0).argmin()]] Val2 = [Qx[np.abs(Fl_Vfrat[0,:]-1.0).argmin()],Qy[np.abs(Fl_Vfrat[0,:]-1.0).argmin()]] print '------------------------------------------------' print '[Qx,Qy] at Alfven :', Val1 print '[Qx,Qy] at Fast :', Val2 print 'Opening Angle at Alfven :',90.0-(180.0/np.pi)*np.arctan(Val1[1]/(Val1[0]-xfl)) print 'Opening Angle at Fast :',90.0-(180.0/np.pi)*np.arctan(Val2[1]/(Val2[0]-xfl)) print '------------------------------------------------' return [Val1,Val2,90.0-(180.0/np.pi)*np.arctan(Val1[1]/(Val1[0]-xfl)),90.0-(180.0/np.pi)*np.arctan(Val2[1]/(Val2[0]-xfl))]
def _compute_static_prob(tri, com): """ For an object with the given center of mass, compute the probability that the given tri would be the first to hit the ground if the object were dropped with a pose chosen uniformly at random. Parameters ---------- tri: (3,3) float, the vertices of a triangle cm: (3,) float, the center of mass of the object Returns ------- prob: float, the probability in [0,1] for the given triangle """ sv = [(v - com) / np.linalg.norm(v - com) for v in tri] # Use L'Huilier's Formula to compute spherical area a = np.arccos(min(1, max(-1, np.dot(sv[0], sv[1])))) b = np.arccos(min(1, max(-1, np.dot(sv[1], sv[2])))) c = np.arccos(min(1, max(-1, np.dot(sv[2], sv[0])))) s = (a + b + c) / 2.0 # Prevents weirdness with arctan try: return 1.0 / np.pi * np.arctan(np.sqrt(np.tan(s / 2) * np.tan( (s - a) / 2) * np.tan((s - b) / 2) * np.tan((s - c) / 2))) except BaseException: s = s + 1e-8 return 1.0 / np.pi * np.arctan(np.sqrt(np.tan(s / 2) * np.tan( (s - a) / 2) * np.tan((s - b) / 2) * np.tan((s - c) / 2)))
def kappa(self, r): from numpy import arctanh, arctan, arctan2, log, sin, cos, pi, logspace x = self.b / self.rs if x < 1.: norm = x**2 / (4 * arctanh( ((1 - x) / (1 + x))**0.5) / (1 - x**2)**0.5 + 2 * log(x / 2)) elif x == 1.: norm = 1. / (2. + 2 * log(0.5)) else: norm = x**2 / (4 * arctan( ((x - 1) / (x + 1))**0.5) / (x**2 - 1)**0.5 + 2 * log(x / 2)) x = r / self.rs A = x * 0. C = x < 1. X = x[C].copy() A[C] = (1. - 2 * arctanh( ((1. - X) / (1. + X))**0.5) / (1 - X**2)**0.5) / (X**2 - 1.) C = x == 1. A[C] = 1. / 3 C = x > 1. X = x[C].copy() A[C] = (1. - 2 * arctan( ((X - 1.) / (1. + X))**0.5) / (X**2 - 1.)**0.5) / (X**2 - 1.) return norm * A
def xzCrossingTime(self): """ Calculate times of crossing the xz-plane. This method calculates the times at which the xz-plane is crossed by the orbit. This is equivalent to finding the times where y=0. Returns ------- Time 1 : float First crossing time defined as having POSITIVE x position. Time 2 : float Second crossing time defined as having NEGATIVE x position. """ f = -self._w - arctan(tan(self._Omega)/cos(self._i)) E = 2.*arctan(sqrt((1-self.e)/(1.+self.e)) * tan(f/2.)) t1 = (E - self.e*sin(E))/self._n + self.tau p1 = self.xyzPos(t1) f += pi E = 2.*arctan(sqrt((1-self.e)/(1.+self.e)) * tan(f/2.)) t2 = (E - self.e*sin(E))/self._n + self.tau t1 -= self._per * numpy.floor(t1/self._per) t2 -= self._per * numpy.floor(t2/self._per) if p1[0] >= 0.0: # y position of p1 is > 0 return (t1, t2) else: return (t2, t1)
def exact(self, t): # Valid for linear s(u) k, b, m, A_F, w_F, I, V = self.k, self.b, self.m, \ self.A_F, self.w_F, self.I, self.V b_crit = 2*np.sqrt(k*m) w_e = np.sqrt(k/m) zeta = b/b_crit zeta1p = zeta + np.sqrt(zeta**2 - 1) zeta1m = zeta - np.sqrt(zeta**2 - 1) zeta2 = np.sqrt(zeta**2 - 1) if zeta > 1: # No oscillations sol1 = (V + w_e*zeta1p*I)/(2*w_e*zeta2)*np.exp(-w_e*zeta1m*t) sol2 = (V + w_e*zeta1m*I)/(2*w_e*zeta2)*np.exp(-w_e*zeta1p*t) u_h = sol1 - sol2 elif zeta == 1: u_h = (I + (V + w_e*I)*t)*np.exp(-w_e*t) else: # Oscillations A = np.sqrt(I**2 + ((V + zeta*w_e*I)/(w_e*zeta2))**2) phi = np.arctan((V + zeta*w_e*I)/(I*w_e*zeta2)) u_h = A*np.exp(-zeta*w_e*t)*np.cos(zeta2*w_e*t - phi) # Excitation: F=F_0*cos(w_F*t) # F_0 and w_F must be extracted from F......? phi_0 = np.arctan(b*w_F/(k - m*w_F**2)) A_0 = A_F/np.sqrt((k - m*w_F**2)**2 + (b*w_F)**2) u_p = A_0*np.cos(omega*t - phi_0) # Test: all special cases... return u_h + u_p
def deflections(self, xin, yin): from numpy import arctanh, arctan, arctan2, log, sin, cos #x,y = self.align_coords(xin,yin) x = xin - self.x y = yin - self.y b, rs = self.b, self.rs X = b / rs if X < 1.: amp = X**2 / (8 * arctanh( ((1 - X) / (1 + X))**0.5) / (1 - X**2)**0.5 + 4 * log(X / 2.)) elif X == 1: amp = 0.25 / (1. + log(0.5)) else: amp = X**2 / (8 * arctan( ((X - 1) / (1 + X))**0.5) / (X**2 - 1)**0.5 + 4 * log(X / 2.)) r2 = (x**2 + y**2) / rs**2 r = r2**0.5 F = r * 0. F[r < 1.] = arctanh((1 - r2[r < 1.])**0.5) / (1 - r2[r < 1.])**0.5 F[r == 1.] = 1. F[r > 1.] = arctan((r2[r > 1.] - 1.)**0.5) / (r2[r > 1.] - 1)**0.5 dr = 4 * amp * rs * (log(r / 2) + F) / r A = arctan2(y, x) return dr * cos(A), dr * sin(A)
def test_vector(Simulator, nl): """A network that represents sin(t), cos(t), arctan(t).""" N = 40 m = nengo.Network(label='test_vector', seed=123) with m: m.config[nengo.Ensemble].neuron_type = nl() input = nengo.Node( output=lambda t: [np.sin(t), np.cos(t), np.arctan(t)]) A = nengo.Ensemble(N * 3, 3, radius=2) nengo.Connection(input, A) in_p = nengo.Probe(input, 'output') A_p = nengo.Probe(A, 'decoded_output', synapse=0.02) sim = Simulator(m) sim.run(5) with Plotter(Simulator, nl) as plt: t = sim.trange() plt.plot(t, sim.data[in_p], label='Input') plt.plot(t, sim.data[A_p], label='Neuron approximation, pstc=0.02') plt.legend(loc='best', prop={'size': 10}) plt.savefig('test_ensemble.test_vector.pdf') plt.close() target = np.vstack((np.sin(np.arange(5000) / 1000.), np.cos(np.arange(5000) / 1000.), np.arctan(np.arange(5000) / 1000.))).T logger.debug("In RMSE: %f", npext.rmse(target, sim.data[in_p])) assert npext.rmse(target, sim.data[in_p]) < 0.01 assert npext.rmse(target, sim.data[A_p]) < 0.1
def expected(scheme, angle_degrees): angle = angle_degrees * np.pi / 180.0 cohesion = 10 friction_degrees = 20 tip_smoother = 4 mean = -10 friction = friction_degrees * np.pi / 180.0 if (scheme == "native"): coh = cohesion fric = friction elif (scheme == "outer_tip"): coh = 2 * np.sqrt(3) * cohesion * np.cos(friction) / (3.0 - np.sin(friction)) fric = np.arctan(2 * np.sin(friction) / np.sqrt(3) / (3.0 - np.sin(friction))) elif (scheme == "inner_tip"): coh = 2 * np.sqrt(3) * cohesion * np.cos(friction) / (3.0 + np.sin(friction)) fric = np.arctan(2 * np.sin(friction) / np.sqrt(3) / (3.0 + np.sin(friction))) elif (scheme == "lode_zero"): coh = cohesion * np.cos(friction) fric = np.arctan(np.sin(friction) / 3.0) elif (scheme == "inner_edge"): coh = 3 * cohesion * np.cos(friction) / np.sqrt(9.0 + 3.0 * np.power(np.sin(friction), 2)) fric = np.arctan(np.sin(friction) / np.sqrt(9.0 + 3.0 * np.power(np.sin(friction), 2))) bar = np.sqrt(np.power(coh - mean * 3.0 * np.tan(fric), 2) - np.power(tip_smoother, 2)) x = bar * np.cos(angle) y = bar * np.sin(angle) return (x, y)
def grad_A(self, x): k = self.k.value x0 = self.x0.value if self.minimum_at_zero: return offset + np.arctan(k * (x - x0)) else: return np.arctan(k * (x - x0))
def _filter_small_slopes(hgt, dx, min_slope=0): """Masks out slopes with NaN until the slope if all valid points is at least min_slope (in degrees). """ min_slope = np.deg2rad(min_slope) slope = np.arctan(-np.gradient(hgt, dx)) # beware the minus sign # slope at the end always OK slope[-1] = min_slope # Find the locs where it doesn't work and expand till we got everything slope_mask = np.where(slope >= min_slope, slope, np.NaN) r, nr = label(~np.isfinite(slope_mask)) for objs in find_objects(r): obj = objs[0] i = 0 while True: i += 1 i0 = objs[0].start-i if i0 < 0: break ngap = obj.stop - i0 - 1 nhgt = hgt[[i0, obj.stop]] current_slope = np.arctan(-np.gradient(nhgt, ngap * dx)) if i0 <= 0 or current_slope[0] >= min_slope: break slope_mask[i0:obj.stop] = np.NaN out = hgt.copy() out[~np.isfinite(slope_mask)] = np.NaN return out
def generate_q_bins(rmax, qmax, pixel_size, distance, wavelength): """ Generate the Q bins at the resolution of the detector Parameters ----------- rmax: float The maximum radial distance on the detector qmax: float The maximum Q on the detector pixel_size: float The size of the pixels, in the same units as rmax distance: float The sample to detector distance, in the same units as rmax wavelength: float The wavelength of the x-rays Returns ------- ndarray: The bin edges, suitable for np.histogram or scipy.stats.binned_statistic """ base_pixels = np.arange(0, rmax, pixel_size) pixel_bottom = base_pixels pixel_top = base_pixels + pixel_size tthb = np.arctan(pixel_bottom / distance) ttht = np.arctan(pixel_top / distance) dq = twotheta_to_q(ttht, wavelength) - twotheta_to_q(tthb, wavelength) fq = np.linspace(0, qmax, len(dq)) b = np.zeros(len(fq) + 1) b[1:] = dq + fq return b
def __reverse_lambert(self,x,y): p = math.pi ln = np.log power = np.power sin = np.sin cos = np.cos tan = np.tan cot = lambda x: 1./tan(x) sec = lambda x: 1./cos(x) ra0 = np.deg2rad(self.center[0]) dec0 = np.deg2rad(self.center[1]) dec1 = np.deg2rad(self.ref_dec1) dec2 = np.deg2rad(self.ref_dec2) n = ln(cos(dec1)*sec(dec2))/ln(tan(p/4+dec2/2)*cot(p/4+dec1/2)) F = cos(dec1)*power(tan(p/4+dec1/2),n)/n rho0 = F*power(cos(p/4+dec0/2)/sin(p/4+dec0/2),n) rho = np.sign(n)*np.sqrt(x**2+(rho0-y)**2) theta = np.arctan(x/(rho0-y)) dec = 2.*np.arctan(np.power((F/rho),(1./n))) - p/2 ra = ra0 + theta/n return np.rad2deg(ra), np.rad2deg(dec)
def place_label(x,y,label,indice=None,cotan=False,color='k'): """ Routine qui se débrouille pour mettre un label semi-transparent au niveau de la courbe données par ses coordonnées x et y. Si on sait que le label sera presque vertical avec possibilité de dépasser 90°, on peut utiliser cotan=True pour corriger (considération purement esthétique). 'indice' correspond à la position dans les tableaux x et y où devra s'afficher le label demandé. """ print(x[0],y[0],label) # un peu de feedback pour savoir ce qu'on calcule N = len(x)//2 # Emplacement par défaut if indice: N=indice # sauf si l'utilisateur impose la valeur xi,xf = plt.xlim() # Les limites en x du graphe yi,yf = plt.ylim() # Pareil en y Xsize = xf - xi # La largeur # Pour la hauteur et la pente, cela dépend si les ordonnées sont en repère # logarithmique ou non. if Plogscale: Ysize = np.log10(yf) - np.log10(yi) a = (np.log10(y[N+1])-np.log10(y[N-1]))/(x[N+1]-x[N-1]) * Xsize/Ysize else: Ysize = yf - yi a = (y[N+1]-y[N-1])/(x[N+1]-x[N-1]) * Xsize/Ysize bbox = plt.gca().get_window_extent() # Récupération de la taille de la figure a *= bbox.height / bbox.width # Correction de la pente avec la taille rot = np.degrees(np.arctan(a)) # Calcul de l'angle de rotation if cotan: # Si on dépasse la verticale rot = 90 - np.degrees(np.arctan(1/a)) t = plt.text(x[N],y[N],label, # On met le texte au bon endroit ha='center',va='center',color=color,rotation = str(rot)) # Avec la bonne rotation # On se débrouille pour que la "boîte" d'écriture soit semi-transparente #t.set_bbox(dict(facecolor='w',edgecolor='None',alpha=0.8)) t.set_bbox(dict(boxstyle="round",facecolor='w',edgecolor='None',alpha=0.85))
def _inline_label(self,xv,yv,x=None,y=None): """ This will give the coordinates and rotation required to align a label with a line on a plot in SI units. """ if y is None and x is not None: trash=0 (xv,yv)=self._to_pixel_coords(xv,yv) #x is provided but y isn't (x,trash)=self._to_pixel_coords(x,trash) #Get the rotation angle and y-value x,y,dy_dx = BasePlot.get_x_y_dydx(xv,yv,x) rot = np.arctan(dy_dx)/np.pi*180. elif x is None and y is not None: #y is provided, but x isn't _xv = xv[::-1] _yv = yv[::-1] #Find x by interpolation x = interpolate_values_1d(yv, xv, x_points=y) trash=0 (xv,yv)=self._to_pixel_coords(xv,yv) (x,trash)=self._to_pixel_coords(x,trash) #Get the rotation angle and y-value x,y,dy_dx = BasePlot.get_x_y_dydx(xv,yv,x) rot = np.arctan(dy_dx)/np.pi*180. (x,y)=self._to_data_coords(x,y) return (x,y,rot)
def calcAngle(accel): angle = np.array([ np.arctan(accel[0]/np.sqrt(accel[1]**2+accel[2]**2))+1.5707963267948966, np.arctan(accel[1]/np.sqrt(accel[0]**2+accel[2]**2))+1.5707963267948966, np.arctan(accel[2]/np.sqrt(accel[1]**2+accel[0]**2))+1.5707963267948966, ]) return angle
def rotMatrixfromXYZ(station,mode='LBA'): """Return a rotation matrix which will rotate a station to (0,0,1)""" loc=station.antField.location[mode] longRotMat=rotationMatrix(0.,0.,-1.*n.arctan(loc[1]/loc[0])) loc0=n.dot(longRotMat,loc) latRotMat=rotationMatrix(0.,n.arctan(loc0[0,2]/loc0[0,0]),0.) return n.dot(latRotMat,longRotMat)
def evalExactφ(sqp,sqpnext,sqpdesired): a=sqp/sqpdesired b=sqpnext/sqpdesired if(abs(a+1) > float("1e-12") and (a*a + b*b - 1)>0): φ1=2*np.arctan( ( b - (a*a + b*b - 1)**0.5 )/(a+1) ) φ2=2*np.arctan( ( b + (a*a + b*b - 1)**0.5 )/(a+1) ) if(np.isnan(φ1)): print("Ok nan found, locating butter chicken") print( (a*a + b*b -1) ) print( (b + (a*a + b*b -1)**0.5 ) ) φ1=np.arcsin(np.sin(φ1)) φ2=np.arcsin(np.sin(φ2)) if(abs(φ1)<abs(φ2)): print(φ1,φ2) return φ1 else: print(φ2,φ1) return φ2 else: print("Glaba, something went globular :P") return 0
def extend_and_norm_feature(element, feature, command, num_elems): feature['element'] = element feature['tagname_edit'] = str_util.get_mean_distance_of_words(command, [feature['tagname']]) # alt. str_util.get_normed_dist_for_words or str_util.get_mean_distance_of_words distance = str_util.new_dist feature['text_words_edit'] = distance(command, feature['text_words']) feature['sibling_text_words_edit'] = distance(command, feature['sibling_text_words']) feature['n_children'] = 1 - float(feature['n_children']) / num_elems w,h = feature['width'], feature['height'] mx, my, sx, sy = 54.611, 25.206, 43.973, 6.467 prior = 0.02 likelihood_button, marginal = likelihood_and_marginal(w, h) if marginal != 0: feature['button_model'] = ((likelihood_button * prior) / marginal) - .147 else: feature['button_model'] = 0 # relative x and y can be more than 1 because things can be beyond the edge of the window # so nudge things to be between -1 and 1 feature['relative_x'] = np.arctan(1 * (feature['relative_x'] + 0.5)) / (np.pi / 2) feature['relative_y'] = np.arctan(1 * feature['relative_y']) / (np.pi / 2) # Feature ideas: # new on page? # position (relative to last action?) # color # relative tab index # text specificity return feature
def kep_eqtnP(del_t, p, mu=Earth.mu): """Parabolic solution to Kepler's Equation (Algorithm 3) A trigonometric approach to solving Kepler's Equation for parabolic orbits. For reference, see Algorithm 3 in Vallado (Fourth Edition), Section 2.2 (pg 69). Parameters ---------- del_t: double Change in time p: double Semi-parameter mu: double, optional, default = Earth.mu Gravitational parameter; defaults to Earth Returns ------- B: double Parabolic Anomaly (radians) """ p3 = p**3 n_p = 2.0*np.sqrt(mu/p3) s = 0.5*np.arctan(2.0/(3.0*n_p*del_t)) w = np.arctan((np.tan(s))**(1/3.0)) B = 2.0/np.tan(2.0*w) return B
def getPossibleCoordinates(fromPos, cvSize, a=None): a = DEFLECTIONBORDERLENGTH/2. if a is None else a counter = 0 while(True): counter+=1 if(counter==1000): print("Warning: needed 1000 attempts to find new coordinates for trajectory") newPos = [None, None] alpha = uniform(0, 2*np.pi) translationLength = uniform(TRANSLATIONLENGTH[0],TRANSLATIONLENGTH[1]) if(a==0): x = math.floor(fromPos[0]+np.cos(alpha)*translationLength) y = math.floor(fromPos[1]-np.sin(alpha)*translationLength) return [x,y] else: if(fromPos[0] < cvSize[0]/2.): alpha1 = np.arctan(fromPos[0]/a) if(alpha < np.pi/2. + alpha1 or alpha > np.pi*3/2. - alpha1): newPos[0] = math.floor(fromPos[0]+np.cos(alpha)*translationLength) else: alpha1 = np.arctan((cvSize[0]-fromPos[0])/a) if(alpha > np.pi/2. - alpha1 and alpha < np.pi*3/2. + alpha1): newPos[0] = math.floor(fromPos[0]+np.cos(alpha)*translationLength) if(fromPos[1]<cvSize[1]/2.): alpha2 = np.arctan(fromPos[1]/a) if(alpha < alpha2 or alpha > np.pi-alpha2): newPos[1] = math.floor(fromPos[1]-np.sin(alpha)*translationLength) else: alpha2 = np.arctan((cvSize[1]-fromPos[1])/a) if(alpha < np.pi+alpha2 or alpha > 2*np.pi - alpha2): newPos[1] = math.floor(fromPos[1]-np.sin(alpha)*translationLength) if(newPos[0] is not None and newPos[1] is not None and keepMiddlepointOnCanvas(cvSize, newPos)): return newPos
def remap(self): """ warp the linear pixel coordinates to a spherical corrected representation. Function is called when the monitor object is initialized and populate the `deg_coord_x` and `deg_coord_y` attributes. """ resolution = [0, 0] resolution[0] = self.resolution[0] / self.downsample_rate resolution[1] = self.resolution[1] / self.downsample_rate map_coord_x, map_coord_y = np.meshgrid(range(resolution[1]), range(resolution[0])) new_map_x = np.zeros(resolution, dtype=np.float32) new_map_y = np.zeros(resolution, dtype=np.float32) for j in range(resolution[1]): new_map_x[:, j] = ((180.0 / np.pi) * np.arctan(self.lin_coord_x[0, j] / self.dis)) dis2 = np.sqrt(np.square(self.dis) + np.square(self.lin_coord_x[0, j])) for i in range(resolution[0]): new_map_y[i, j] = ((180.0 / np.pi) * np.arctan(self.lin_coord_y[i, 0] / dis2)) self.deg_coord_x = new_map_x + self.center_coordinates[1] self.deg_coord_y = new_map_y + self.center_coordinates[0]
def calcMultipliers(meanM, stdM, Cfactors, phiShifts, coeffs, intercept, T): K = int(len(coeffs)/2) C = np.zeros(K) phi = np.zeros(K) for k in range(K): C[k] = np.sqrt(coeffs[2*k]**2 + coeffs[2*k+1]**2) if coeffs[2*k] > 0: phi[k] = np.arctan(coeffs[2*k+1]/coeffs[2*k]) elif coeffs[2*k] < 0: phi[k] = np.arctan(coeffs[2*k+1]/coeffs[2*k]) + math.pi else: phi[k] = math.pi/2 y1 = np.zeros(T) y2 = np.zeros(T) for t in range(T): y1[t] = y1[t] + intercept y2[t] = y2[t] + intercept for k in range(K): y1[t] = y1[t] + C[k]*np.cos((2*math.pi*(k+1)*(t+1)/T)-phi[k]) y2[t] = y2[t] + C[k]*Cfactors[k]*np.cos((2*math.pi*(k+1)*(t+1)/T)-(phi[k]-phiShifts[k])) meanMultipliers = meanM * y2 / y1 stdMultipliers = stdM * np.ones(len(meanMultipliers)) return meanMultipliers, stdMultipliers
def main(): from model import Model #print(rotate([[2,0,0],[0,1,0],[0,0,1]], 90, 'y')) #print(calc_rot_array_from_hkl(19,-24,28)) modelfile = sys.argv[1] m = Model(modelfile) #rot_arr = calc_rot_array_from_hkl(41,60,-6) rot_arr = calculate_rotation_array(30, 60, 90) rotate(m, rot_arr) #m.write_real_xyz('temp.real.xyz') return # Below is a (the?) rotation matrix of Pei's t1 that gives some planes. Oriented for a specific plane ~. #rot_arr = [ -0.977103, -0.123352, -0.173361, -0.130450, 0.990997, 0.030118, 0.168085, 0.052043, -0.984398 ] #rot(m,rot_arr) # Angles in radians # Note that these are semi difficult to figure out from the vesta rotation matrix, # partly because there are negative angles, so you may need to do 2pi - angle you found. #t1 = np.pi*2 - 0.0371505 #t2 = 0.162790 #t3 = 0 #rot_arr = calc_rot_array(m,t1,t2,t3) #rot(m,rot_arr) kx = -0.76094085 ky = 0.028182994 kz = -0.648208872 t2 = np.arctan(-ky/kx) t3 = 0.0 t1 = np.arctan( (kx*np.cos(t2)-ky*cos(t2))/kz ) t1 = 0.0 print(t1,t2,t3) rot_arr = calc_rot_array(t1,t2,t3) rot(m,rot_arr)
def GeneralShear(pts, st1, gamma, kk, ninc): ''' GeneralShear computes displacement paths, kinematic vorticity numbers and progressive finite strain history, for general shear with a pure shear stretch, no area change, and a single shear strain USE: paths,wk,pfs = GeneralShear(pts,st1,gamma,kk,ninc) pts = npoints x 2 matrix with X1 and X3 coord. of points st1 = Pure shear stretch parallel to shear zone gamma = Engineering shear strain kk = An integer that indicates whether the maximum finite stretch is parallel (kk = 0), or perpendicular (kk=1) to the shear direction ninc = number of strain increments paths = displacement paths of points wk = Kinematic vorticity number pfs = progressive finite strain history. column 1 = orientation of maximum stretch with respect to X1, column 2 = maximum stretch magnitude NOTE: Intermediate principal stretch is 1.0 (Plane strain). Output orientations are in radians Python function translated from the Matlab function GeneralShear in Allmendinger et al. (2012) ''' # Compute minimum principal stretch and incr. stretches st1inc = st1**(1.0 / ninc) st3 = 1.0 / st1 st3inc = st3**(1.0 / ninc) # Incremental engineering shear strain gammainc = gamma / ninc # Initialize displacement paths npts = np.size(pts, 0) # Number of points paths = np.zeros((ninc + 1, npts, 2)) paths[0, :, :] = pts # Initial points of paths # Initialize figure fig = plt.figure(figsize=(15, 5)) # Define the size ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) # Calculate incremental deformation gradient tensor # If max. stretch parallel to shear direction Eq. 8.45 if kk == 0: F = np.zeros((2, 2)) F[0, ] = [ st1inc, (gammainc * (st1inc - st3inc)) / (2.0 * np.log(st1inc)) ] F[1, ] = [0.0, st3inc] # If max. stretch perpendicular to shear direction Eq. 8.46 elif kk == 1: F = np.zeros((2, 2)) F[0, ] = [ st3inc, (gammainc * (st3inc - st1inc)) / (2.0 * np.log(st3inc)) ] F[1, ] = [0.0, st1inc] # Compute displacement paths for i in range(0, npts): # for all points for j in range(0, ninc + 1): # for all strain increments for k in range(0, 2): for L in range(0, 2): paths[j, i, k] = F[k, L] * paths[j - 1, i, L] + paths[j, i, k] # Plot displacement path of point xx = paths[:, i, 0] yy = paths[:, i, 1] ax1.plot(xx, yy, 'k.-') # Plot initial and final polygons inpol = np.zeros((npts + 1, 2)) inpol[0:npts, ] = paths[0, 0:npts, :] inpol[npts, ] = inpol[0, ] ax1.plot(inpol[:, 0], inpol[:, 1], 'b-') finpol = np.zeros((npts + 1, 2)) finpol[0:npts, ] = paths[ninc, 0:npts, :] finpol[npts, ] = finpol[0, ] ax1.plot(finpol[:, 0], finpol[:, 1], 'r-') # Set axes ax1.set_xlabel('X1') ax1.set_ylabel('X3') ax1.grid() ax1.axis('equal') # Determine the eigenvectors of the flow (apophyses) # Since F is not symmetrical, use function eig _, V = np.linalg.eig(F) theta2 = np.arctan(V[1, 1] / V[0, 1]) wk = np.cos(theta2) # Initalize progressive finite strain history. # We are not including the initial state pfs = np.zeros((ninc, ninc)) # Calculate progressive finite strain history for i in range(1, ninc + 1): # Determine the finite deformation gradient tensor finF = np.linalg.matrix_power(F, i) # Determine Green deformation tensor G = np.dot(finF, finF.conj().transpose()) # Stretch magnitude and orientation: Maximum # eigenvalue and their corresponding eigenvectors # of Green deformation tensor D, V = np.linalg.eigh(G) pfs[i - 1, 0] = np.arctan(V[1, 1] / V[0, 1]) pfs[i - 1, 1] = np.sqrt(D[1]) # Plot progressive finite strain history ax2.plot(pfs[:, 0] * 180 / np.pi, pfs[:, 1], 'k.-') ax2.set_xlabel('Θ deg') ax2.set_ylabel('Maximum finite stretch') ax2.set_xlim(-90, 90) ax2.set_ylim(1, max(pfs[:, 1]) + 0.5) ax2.grid() # Show plot plt.show() return paths, wk, pfs
def umba(x,y,z,Vtot,Theta, Psi, SpinRate, TiltH, Tiltm, SpinE, Yang, Zang, LorR, i, seamsOn, FullRot): """ The inputs are: x, y, z, Initial Ball Speed, vertical release angle, horizontal release angle, Spin Rate, Tilt in Hours, Tilt in minutes, Spin Efficiency, Y seam orientation angle, Z seam orientation angle, Primay inputs are: initial position, x0, y0, and z0 with origin at the point of home plate, x to the rright of the catcher, y from the catcher towards the pitcher, and z straight up. Initial velocities u0, v0, and w0 which are the speeds of the ball in x, y, and z respectivley. And spin rates UMBA1.0: This code uses a constant Cd and rod cross's model for CL Predictions. Seam Orientation is not accounted for. Air Density is considered only at sea level at 60% relative humidity. but can be easily altered UMBA2.0 Adding seam positions and attempting to model CL from seams. """ Yang = (Yang) * np.pi/180 Zang = -Zang * np.pi/180 # seamsOn = True frameRate = 0.002 Tilt = TimeToTilt(TiltH, Tiltm) if LorR == 'l': Gyro = np.arcsin(SpinE/100) elif LorR =='r': Gyro = np.pi - np.arcsin(SpinE/100) else: while LorR != 'l' or LorR != 'r': if LorR == 'l': Gyro = np.arcsin(SpinE/100) elif LorR =='r': Gyro = np.pi - np.arcsin(SpinE/100) else: LorR = input('please type in an "l" or an "r" for which pole goes forward') positions,NGfinal = (PitchedBallTraj(x, y, z, Vtot, Theta, Psi, SpinRate, Tilt, Gyro, Yang, Zang, i, frameRate, seamsOn, FullRot)) plotting.Plotting(positions) pX = (positions[0]) pY = (positions[1]) pZ = (positions[2]) IX = (positions[3]) IY = (positions[4]) IZ = (positions[5]) DX = (positions[6]) DY = (positions[7]) DZ = (positions[8]) FX = (positions[9]) FY = (positions[10]) FZ = (positions[11]) TF = (positions[12]) aX = (positions[13]) aY = (positions[14]) aZ = (positions[15]) TiltDeg = np.arctan2((NGfinal[0] - x + ((60-y)*np.arctan(Psi*np.pi/180))), (NGfinal[2] - z - (60-z)*np.arctan(Theta*np.pi/180)))*180/np.pi TiltTime = TiltToTime(-TiltDeg) print('Apparent Tilt = ',TiltTime[0],':',TiltTime[1]) return(pX,pY,pZ,IX,IY,IZ,DX,DY,DZ,FX,FY,FZ,TF,aX,aY,aZ,TiltTime)
weight_theta = b.local_colatitude_weights(1) weight_r = b.local_radial_weights(1) reducer = GlobalArrayReducer(d.comm_cart) vol_test = np.sum(weight_r * weight_theta + 0 * T['g']) * np.pi / (Lmax + 1) / L_dealias vol_test = reducer.reduce_scalar(vol_test, MPI.SUM) vol_correction = 4 * np.pi / 3 / vol_test # Main loop start_time = time.time() while solver.ok: if solver.iteration % 10 == 0: E0 = np.sum(vol_correction * weight_r * weight_theta * T['g'].real**2) E0 = 0.5 * E0 * (np.pi) / (Lmax + 1) / L_dealias E0 = reducer.reduce_scalar(E0, MPI.SUM) logger.info("t = %f, E = %.15e" % (solver.sim_time, E0)) t_list.append(solver.sim_time) E_list.append(E0) solver.step(dt) end_time = time.time() logger.info('Run time: %f', (end_time - start_time)) analytic_solution = -(r**4 - 1) / 20 + (r**2 - 1) / 6 - 2 * np.arctan( r) / r + 2 * np.arctan(1) - np.log(1 + r**2) + np.log(2) analytic_solution = analytic_solution[0, 0] numerical_solution = T['g'][0, 0] logger.info("max fractional error: %e" % np.max( np.abs(analytic_solution - numerical_solution) / np.abs(analytic_solution))) logger.info("we can decrease the error by decreasing the timestep.")
def arctan(x): local_requires_grad = is_zhangliang_requires_grad(x) a_ = Zhangliang(x) values = np.arctan(a_.values) return Zhangliang(values, dtype=values.dtype, requires_grad=local_requires_grad and graph.is_grad_enabled())
n, m = 300, 2 # generate random sample, two components np.random.seed(0) C = np.array([[0., -0.7], [3.5, .7]]) X = np.r_[np.dot(np.random.randn(n, 2), C), np.random.randn(n, 2) + np.array([3, 3])] clf = mixture.GMM(n_states=2, cvtype='full') clf.fit(X) splot = pl.subplot(111, aspect='equal') color_iter = itertools.cycle(['r', 'g', 'b', 'c']) Y_ = clf.predict(X) for i, (mean, covar, color) in enumerate(zip(clf.means, clf.covars, color_iter)): v, w = np.linalg.eigh(covar) u = w[0] / np.linalg.norm(w[0]) pl.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color) angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) pl.show()
def xyz_2_coorxy(xs, ys, zs, H, W): us = np.arctan2(xs, -ys) vs = -np.arctan(zs / np.sqrt(xs**2 + ys**2)) coorx = (us / (2 * np.pi) + 0.5) * W coory = (vs / np.pi + 0.5) * H return coorx, coory
def diagonal_filter(window, n, slope=1.0, angle=None, zero_mean=False): '''Build a two-dimensional diagonal filter. This is primarily used for smoothing recurrence or self-similarity matrices. Parameters ---------- window : string, tuple, number, callable, or list-like The window function to use for the filter. See `get_window` for details. Note that the window used here should be non-negative. n : int > 0 the length of the filter slope : float The slope of the diagonal filter to produce angle : float or None If given, the slope parameter is ignored, and angle directly sets the orientation of the filter (in radians). Otherwise, angle is inferred as `arctan(slope)`. zero_mean : bool If True, a zero-mean filter is used. Otherwise, a non-negative averaging filter is used. This should be enabled if you want to enhance paths and suppress blocks. Returns ------- kernel : np.ndarray, shape=[(m, m)] The 2-dimensional filter kernel Notes ----- This function caches at level 10. ''' if angle is None: angle = np.arctan(slope) win = np.diag(get_window(window, n, fftbins=False)) if not np.isclose(angle, np.pi / 4): win = scipy.ndimage.rotate(win, 45 - angle * 180 / np.pi, order=5, prefilter=False) np.clip(win, 0, None, out=win) win /= win.sum() if zero_mean: win -= win.mean() return win
def get_ctrl_output(self): # if in velocity control mode, just return the goal velocity if self.ctrl_mode == 'open': cmd_vel = Twist() cmd_vel.linear.x = self.vel_g[0] cmd_vel.angular.y = self.vel_g[1] goal_reached = Bool() goal_reached.data = False return cmd_vel, goal_reached try: # update position information (translation, rotation) = self.trans_listener.lookupTransform( "/map", "/base_footprint", rospy.Time(0)) self.x = translation[0] self.y = translation[1] self.theta = tf.transformations.euler_from_quaternion(rotation)[2] except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): rospy.logerr("Cannot localize robot!") # use self.x self.y and self.theta to compute the right control input here # compute rho and alpha, beta x_g = self.x_g y_g = self.y_g th_g = self.th_g # Distance to goal rho = np.sqrt((x_g - self.x)**2 + (y_g - self.y)**2) # Direction to goal ang = np.arctan2(y_g - self.y, x_g - self.x) # Difference between heading and ang alpha = self.wrapToPi(ang - self.theta) # Difference between heading and th_g beta = self.wrapToPi(th_g - self.theta) # check if near goal # Only reset if double the threshold from goal. Adds robustness to map jumping if not self.near_goal: self.near_goal = rho < self.goal_reached_thresh else: self.near_goal = 0.5 * rho < self.goal_reached_thresh if not self.near_goal: V = 0.5 - np.absolute(np.arctan(alpha * 5.0) / (np.pi)) - max(0, -0.5 / 0.2 * rho + 0.5) om = np.arctan(alpha * 2.5) / (np.pi / 2.0) else: V = 0 om = np.arctan(beta * 2.5) / (np.pi / 2.0) # Apply saturation limits V = np.sign(V) * min(0.3, np.abs(V)) om = np.sign(om) * min(1, np.abs(om)) cmd = Twist() cmd.linear.x = V cmd.angular.z = om # check if goal is reached goal_reached = Bool() near_theta = np.absolute(self.theta - th_g) < self.theta_goal_thresh goal_reached.data = self.near_goal and near_theta #if np.linalg.norm(rho) < self.goal_reached_thresh and (np.absolute(self.theta - th_g) < self.theta_goal_thresh): # goal_reached.data = True #else: # goal_reached.data = False return cmd, goal_reached
import matplotlib.pyplot as plt import numpy as np import sympy as sp # 求函数 y=arctan(1/x) 的左右极限 x = sp.Symbol('x') fr = sp.atan(1 / x) xl = sp.limit(fr, x, 0, dir='-') xr = sp.limit(fr, x, 0, dir='+') print('%s 左极限是:%s' % (str(fr), str(xl))) print('%s 右极限是:%s' % (str(fr), str(xr))) # 绘制函数 y=arctan(1/x) 的图像 x = np.arange(-6, 6, 0.01) y = np.arctan(1 / x) plt.title('y=arctan(1/x)') plt.plot(x, y) plt.show()
if key != 'price' and key != 'symboling' and df[key].dtype != 'O': print(key) # print(ohe[key].shape, ohe['price'].shape) slope, intercept, r_value, p_value, std_err = sp.stats.linregress( df[key], df['price']) # save plot for visual inspection fig = plt.figure() sns.regplot(x=key, y="price", data=df) plt.title('Slope: ' + str(slope) + '; Intercept: ' + str(intercept)) plt.savefig('plots/feature-influence/06-a-reg-plot-' + key + '.png') plt.close(fig) print('saved plot for: ', key, '; reg-line slope: ', slope, '; slope-angle: ', np.rad2deg(np.arctan(slope))) # from visual inspection of correlation plots, any regression line with an abolsute value of 5000 is assumed to indicate a strong correlation between predictor and target; only those will be used to train the neural net; the rest of the predictor variables will be dropped # if abs(slope) < 4000: # df = df.drop(columns=[key]) # print(key, slope) ### NARROW DOWN FEATURES: ====================================================== # this one-hot encoding makes a total of 69 predictor variables to predict the target (price) variable # the dataset contains 159 observations, and 69 features (after one-hot-ecoding) leads to NaN outputs # the output mostly result in NaNs # so only a few features will be used at a time to train models; # the correlation charts are consulted, and the predictors with strong correlation are chosen
fx = np.zeros_like(gau, dtype=np.float32) K_size = 3 pad = K_size // 2 for y in range(H): for x in range(W): fy[pad + y, pad + x] = np.sum(KSV * gau[y:y + K_size, x:x + K_size]) fx[pad + y, pad + x] = np.sum(KSH * gau[y:y + K_size, x:x + K_size]) fx = fx[pad:pad + H, pad:pad + W] fy = fy[pad:pad + H, pad:pad + W] # Non-maximum suppression edge = np.sqrt(np.power(fx, 2) + np.power(fy, 2)) fx[fx == 0] = 1e-5 tan = np.arctan(fy / fx) ## Angle quantization angle = np.zeros_like(tan, dtype=np.uint8) angle[np.where((tan > -0.4142) & (tan <= 0.4142))] = 0 angle[np.where((tan > 0.4142) & (tan < 2.4142))] = 45 angle[np.where((tan >= 2.4142) | (tan <= -2.4142))] = 95 angle[np.where((tan > -2.4142) & (tan <= -0.4142))] = 135 for y in range(H): for x in range(W): if angle[y, x] == 0: dx1, dy1, dx2, dy2 = -1, 0, 1, 0 elif angle[y, x] == 45: dx1, dy1, dx2, dy2 = -1, 1, 1, -1 elif angle[y, x] == 90: dx1, dy1, dx2, dy2 = 0, -1, 0, 1
def sig(x, x0, dx, dsig, sig0): func = ((np.arctan( (x - x0) / dx * np.sign(dsig)) + np.pi / 2) * np.abs(dsig) / np.pi + sig0) return func
def draw_neural_net(ax, left, right, bottom, top, layer_sizes, actfun_hid, actfun_out, coefs_, intercepts_, n_iter_, loss_): ''' Draw a neural network cartoon using matplotilb. :usage: >>> fig = plt.figure(figsize=(12, 12)) >>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2]) :parameters: - ax : matplotlib.axes.AxesSubplot The axes on which to plot the cartoon (get e.g. by plt.gca()) - left : float The center of the leftmost node(s) will be placed here - right : float The center of the rightmost node(s) will be placed here - bottom : float The center of the bottommost node(s) will be placed here - top : float The center of the topmost node(s) will be placed here - layer_sizes : list of int List of layer sizes, including input and output dimensionality ''' n_layers = len(layer_sizes) v_spacing = (top - bottom) / float(max(layer_sizes)) h_spacing = (right - left) / float(len(layer_sizes) - 1) # Input-Arrows layer_top_0 = v_spacing * (layer_sizes[0] - 1) / 2. + (top + bottom) / 2. for m in range(layer_sizes[0]): plt.arrow(left - 0.18, layer_top_0 - m * v_spacing, 0.12, 0, lw=1, head_width=0.01, head_length=0.02) # Nodes for n, layer_size in enumerate(layer_sizes): layer_top = v_spacing * (layer_size - 1) / 2. + (top + bottom) / 2. for m in range(layer_size): circle = plt.Circle( (n * h_spacing + left, layer_top - m * v_spacing), v_spacing / 8., color='w', ec='green' if n == 0 else 'red' if n == len(layer_sizes) - 1 else 'k', zorder=4) if n == 0: plt.text(left - 0.125, layer_top - m * v_spacing, r'$X_{' + str(m + 1) + '}$', fontsize=15) elif (n_layers == 3) & (n == 1): plt.text(n * h_spacing + left + 0.00, layer_top - m * v_spacing + (v_spacing / 8. + 0.01 * v_spacing), r'$H_{' + str(m + 1) + '}$', fontsize=15) elif n == n_layers - 1: plt.text(n * h_spacing + left + 0.10, layer_top - m * v_spacing, r'$y_{' + str(m + 1) + '}$', fontsize=15) ax.add_artist(circle) # Bias-Nodes for n, layer_size in enumerate(layer_sizes): if n < n_layers - 1: x_bias = (n + 0.5) * h_spacing + left y_bias = top + 0.005 circle = plt.Circle((x_bias, y_bias), v_spacing / 8., color='w', ec='k', zorder=4) plt.text(x_bias - (v_spacing / 8. + 0.10 * v_spacing + 0.01), y_bias, r'$1$', fontsize=15) ax.add_artist(circle) # Edges # Edges between nodes for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])): layer_top_a = v_spacing * (layer_size_a - 1) / 2. + (top + bottom) / 2. layer_top_b = v_spacing * (layer_size_b - 1) / 2. + (top + bottom) / 2. for m in range(layer_size_a): for o in range(layer_size_b): color = 'k' if coefs_[n][m, o] == 0: color = 'red' line = plt.Line2D( [n * h_spacing + left, (n + 1) * h_spacing + left], [layer_top_a - m * v_spacing, layer_top_b - o * v_spacing], c=color) ax.add_artist(line) xm = (n * h_spacing + left) xo = ((n + 1) * h_spacing + left) ym = (layer_top_a - m * v_spacing) yo = (layer_top_b - o * v_spacing) rot_mo_rad = np.arctan((yo - ym) / (xo - xm)) rot_mo_deg = rot_mo_rad * 180. / np.pi xm1 = xm + (v_spacing / 8. + 0.05) * np.cos(rot_mo_rad) if n == 0: if yo > ym: ym1 = ym + (v_spacing / 8. + 0.12) * np.sin(rot_mo_rad) else: ym1 = ym + (v_spacing / 8. + 0.05) * np.sin(rot_mo_rad) else: if yo > ym: ym1 = ym + (v_spacing / 8. + 0.12) * np.sin(rot_mo_rad) else: ym1 = ym + (v_spacing / 8. + 0.04) * np.sin(rot_mo_rad) plt.text( xm1, ym1,\ str(round(coefs_[n][m, o],4)),\ rotation = rot_mo_deg, \ fontsize = 10) # Edges between bias and nodes for n, (layer_size_a, layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])): if n < n_layers - 1: layer_top_a = v_spacing * (layer_size_a - 1) / 2. + (top + bottom) / 2. layer_top_b = v_spacing * (layer_size_b - 1) / 2. + (top + bottom) / 2. x_bias = (n + 0.5) * h_spacing + left y_bias = top + 0.005 for o in range(layer_size_b): line = plt.Line2D([x_bias, (n + 1) * h_spacing + left], [y_bias, layer_top_b - o * v_spacing], c='k') ax.add_artist(line) xo = ((n + 1) * h_spacing + left) yo = (layer_top_b - o * v_spacing) rot_bo_rad = np.arctan((yo - y_bias) / (xo - x_bias)) rot_bo_deg = rot_bo_rad * 180. / np.pi xo2 = xo - (v_spacing / 8. + 0.01) * np.cos(rot_bo_rad) yo2 = yo - (v_spacing / 8. + 0.01) * np.sin(rot_bo_rad) xo1 = xo2 - 0.05 * np.cos(rot_bo_rad) yo1 = yo2 - 0.05 * np.sin(rot_bo_rad) plt.text( xo1, yo1,\ str(round(intercepts_[n][o],4)),\ rotation = rot_bo_deg, \ fontsize = 10) # Output-Arrows layer_top_0 = v_spacing * (layer_sizes[-1] - 1) / 2. + (top + bottom) / 2. for m in range(layer_sizes[-1]): plt.arrow(right + 0.015, layer_top_0 - m * v_spacing, 0.16 * h_spacing, 0, lw=1, head_width=0.01, head_length=0.02) plt.text(0.5, bottom - 0.005 * v_spacing, 'Hidden,Output: ' + str(actfun_hid) + ',' + str(actfun_out) + '\nSteps:' + str(n_iter_) + '\nLoss:' + str(loss_), horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, fontsize=12, color='blue') plt.show()
def parse(file, psfTable, outFolder, pixelPlane): ''' a parser for G4output. It's easier to parallelize if written as a separate function. ''' # initialization lineNum = 0 nTrk = 0 # count number of tracks # prepare files print 'parsing # ', file f = open(file, 'r') lines = f.readlines() fileIdx = re.split('\.', file)[0] x_tmp = [] y_tmp = [] z_tmp = [] dE_tmp = [] xDir = -1 yDir = -1 if os.path.isfile('%s/%s.fits' % (outFolder, fileIdx)): return for line in lines: if line[0] == '*' and x_tmp: print 'see * in ', file elif 'physiTracker' not in line: continue elif 'physiTracker' in line: lineSplit = re.split(r'\s*[(), \s]\s*', line) if lineSplit[0] == '': lineSplit = lineSplit[1:] if not x_tmp: xDir = float(lineSplit[7]) yDir = float(lineSplit[8]) xInit = float(lineSplit[0]) yInit = float(lineSplit[1]) eInit = float(lineSplit[5]) x_tmp.append(float(lineSplit[0])) y_tmp.append(float(lineSplit[1])) z_tmp.append(float(lineSplit[2])) dE_tmp.append(float(lineSplit[6])) else: # executed after 'for' terminates normally # when 'for' terminates normally, it reaches the end of file if x_tmp: x = [] y = [] z = [] dE = [] x = np.array(x_tmp) y = np.array(y_tmp) - 2000. z = np.array(z_tmp) dE = np.array(dE_tmp) alpha_true = rad2deg(arctan(xDir / yDir)) if alpha_true < 0: alpha_true += 360. del x_tmp, y_tmp, z_tmp, dE_tmp track, row0_pos_um, col0_pos_um = XYZdE2track( x, y, z, dE, psfTable, pixelPlane) h = fits.Header() h['row0_um'] = row0_pos_um h['col0_um'] = col0_pos_um h['alphaT'] = alpha_true h['xInit'] = xInit h['yInit'] = yInit h['eInit'] = eInit prihdu = fits.PrimaryHDU(track, header=h) row_pix = (y - row0_pos_um) / 10.5 col_pix = (x - col0_pos_um) / 10.5 row = fits.Column(name='row', format='F', array=row_pix) col = fits.Column(name='col', format='F', array=col_pix) tbhdu = fits.BinTableHDU.from_columns(fits.ColDefs([row, col])) hdulist = fits.HDUList([prihdu, tbhdu]) hdulist.writeto('%s/%s.fits' % (outFolder, fileIdx)) f.close()
def __init__( self, center, A, B, C, e0, tilt, fields=None, ds=None, field_parameters=None, data_source=None, ): validate_center(center) validate_float(A) validate_float(B) validate_float(C) validate_3d_array(e0) validate_float(tilt) validate_sequence(fields) validate_object(ds, Dataset) validate_object(field_parameters, dict) validate_object(data_source, YTSelectionContainer) YTSelectionContainer3D.__init__(self, center, ds, field_parameters, data_source) # make sure the magnitudes of semi-major axes are in order if A < B or B < C: raise YTEllipsoidOrdering(ds, A, B, C) # make sure the smallest side is not smaller than dx self._A = self.ds.quan(A, "code_length") self._B = self.ds.quan(B, "code_length") self._C = self.ds.quan(C, "code_length") if self._C < self.index.get_smallest_dx(): raise YTSphereTooSmall(self.ds, self._C, self.index.get_smallest_dx()) self._e0 = e0 = e0 / (e0**2.0).sum() ** 0.5 self._tilt = tilt # find the t1 angle needed to rotate about z axis to align e0 to x t1 = np.arctan(e0[1] / e0[0]) # rotate e0 by -t1 RZ = get_rotation_matrix(t1, (0, 0, 1)).transpose() r1 = (e0 * RZ).sum(axis=1) # find the t2 angle needed to rotate about y axis to align e0 to x t2 = np.arctan(-r1[2] / r1[0]) """ calculate the original e1 given the tilt about the x axis when e0 was aligned to x after t1, t2 rotations about z, y """ RX = get_rotation_matrix(-tilt, (1, 0, 0)).transpose() RY = get_rotation_matrix(-t2, (0, 1, 0)).transpose() RZ = get_rotation_matrix(-t1, (0, 0, 1)).transpose() e1 = ((0, 1, 0) * RX).sum(axis=1) e1 = (e1 * RY).sum(axis=1) e1 = (e1 * RZ).sum(axis=1) e2 = np.cross(e0, e1) self._e1 = e1 self._e2 = e2 self.set_field_parameter("A", A) self.set_field_parameter("B", B) self.set_field_parameter("C", C) self.set_field_parameter("e0", e0) self.set_field_parameter("e1", e1) self.set_field_parameter("e2", e2)
import numpy as np import sympy as sp wn = 374 zet = 0.925 a = wn * zet w = np.sqrt(1 - zet**2) * wn T = 1e-3 phi = np.arctan(-a / w) z = sp.symbols("z") Gz = (z - 1) / z / (a**2 + w**2) * ( z / (z - 1) - (z**2 - z * np.exp(-a * T) / np.cos(phi) * np.cos(w * T - phi)) / (z**2 - 2 * z * np.exp(-a * T) * np.cos(w * T) + np.exp(-2 * a * T))) Gz = sp.simplify(Gz) coeffs = np.array(sp.Poly(sp.denom(Gz), z).coeffs()) print(np.roots(sp.Poly(sp.denom(Gz), z).coeffs())) coeffs /= coeffs[0] np.savetxt("data/observer_coeffs.txt", coeffs) print("Observer equation is") print(coeffs) print("Observer roots are") print(np.roots(coeffs))
def twopointcor(point1, point2): """point1 = (x1,y1),point2 = (x2,y2)""" deltxy = point2 - point1 corner = np.arctan(deltxy[1] / deltxy[0]) * 180 / np.pi return corner
def propag_system(self, sInd, currentTimeNorm): """Propagates planet time-dependant parameters: position, velocity, planet-star distance, apparent separation, phase function, surface brightness of exo-zodiacal light, delta magnitude, working angle, and the planet current time array. This method uses the Kepler state transition matrix to propagate a planet's state (position and velocity vectors) forward in time using the Kepler state transition matrix. Args: sInd (integer): Index of the target system of interest currentTimeNorm (astropy Quantity): Current mission time normalized to zero at mission start in units of day """ PPMod = self.PlanetPhysicalModel ZL = self.ZodiacalLight TL = self.TargetList assert np.isscalar(sInd), "Can only propagate one system at a time, \ sInd must be scalar." # check for planets around this target pInds = np.where(self.plan2star == sInd)[0] if not np.any(pInds): return # check for positive time increment dt = currentTimeNorm - self.planTime[pInds][0] assert dt >= 0, "Time increment (dt) to propagate a planet must be positive." if dt == 0: return # Initial positions in AU and velocities in AU/day rold = self.r[pInds].to('AU').value vold = self.v[pInds].to('AU/day').value # stack dimensionless positions and velocities x0 = np.array([]) for i in xrange(len(rold)): x0 = np.hstack((x0, rold[i], vold[i])) # calculate system's distance and masses sDist = TL.dist[[sInd]] Ms = TL.MsTrue[[sInd]]*const.M_sun Mp = self.Mp[pInds] # calculate vector of gravitational parameter mu = (const.G*(Mp + Ms)).to('AU3/day2').value # use keplerSTM.py to propagate the system prop = planSys(x0, mu, epsmult=10.) try: prop.takeStep(dt.to('day').value) except ValueError: #try again with larger epsmult and two steps to force convergence prop = planSys(x0, mu, epsmult=100.) try: prop.takeStep(dt.to('day').value/2.) prop.takeStep(dt.to('day').value/2.) except ValueError: raise ValueError('planSys error') # split off position and velocity vectors x1 = np.array(np.hsplit(prop.x0, 2*len(rold))) rind = np.array(range(0,len(x1),2)) # even indices vind = np.array(range(1,len(x1),2)) # odd indices # update planets' position, velocity, planet-star distance, apparent # separation, phase function, exozodi surface brightness, delta magnitude, # working angle, and current time self.r[pInds] = x1[rind]*u.AU self.v[pInds] = x1[vind]*u.AU/u.day self.d[pInds] = np.sqrt(np.sum(self.r[pInds]**2, axis=1)) self.s[pInds] = np.sqrt(np.sum(self.r[pInds,0:2]**2, axis=1)) self.phi[pInds] = PPMod.calc_Phi(np.arcsin(self.s[pInds]/self.d[pInds])) self.fEZ[pInds] = ZL.fEZ(TL, sInd, self.I[pInds],self.d[pInds]) self.dMag[pInds] = deltaMag(self.p[pInds],self.Rp[pInds],self.d[pInds],self.phi[pInds]) self.WA[pInds] = np.arctan(self.s[pInds]/sDist).to('mas') self.planTime[pInds] = currentTimeNorm
plt.plot(X[:200],dt) plt.plot(X[:199],dt2) plt.grid() plt.show() '''---------------------------------------------------------''' #Ej3 x=[2.5,3.5,5,6,7.5,10,12.5,15,17.5,20] x=N.array(x) y=[7,5.5,3.9,3.6,2.1,2.8,2.6,2.4,2.3,2.3] y=N.array(y) #Ajuste mediante polinomio de segundo grado: funcrec=lambda x,a,b: x/(a*x+b) funarc=lambda x,a,b,c,d: a*N.arctan(b*x-c)+d coef1=N.polyfit(x,y,2) #pol.grado 2 coef2=N.polyfit(1/x,1/y,1) #crecimiento coef3,cov3=SO.curve_fit(funarc,x,y)#arctang coef4,cov4=SO.curve_fit(funcrec,x,y)#crecimiento X = N.linspace(x[0],x[-1],201) plt.figure() plt.plot(x,y,'ro') plt.plot(X,z,label='Ajuste quadratic Spline') #Función interpolada con Cubic Spline plt.plot(X,N.polyval(coef1,X),label='poly2') plt.plot(X,1./(N.polyval(coef2,1./X)),label='Crecimiento lineal') plt.plot(X,funcrec(X,*coef4),label='Crecimiento no lineal') plt.plot(X,funarc(X,*coef3),label='Arcontangente') plt.legend()
def _tile_to_latlon(x, y, zoom): n = 2. ** zoom lon_deg = (x / n) * 360 - 180 lat_rad = np.arctan(np.sinh(np.pi * (1 - 2 * y / n))) return np.rad2deg(lat_rad), lon_deg
def get_predicted_pa(shear): return np.arctan(2 / 5 * np.sqrt(4 - 2 * shear) / shear)
def directionality(image): image = np.array(image, dtype='int64') h = image.shape[0] w = image.shape[1] convH = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) convV = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) deltaH = np.zeros([h, w]) deltaV = np.zeros([h, w]) theta = np.zeros([h, w]) # calc for deltaH for hi in range(h)[1:h - 1]: for wi in range(w)[1:w - 1]: deltaH[hi][wi] = np.sum( np.multiply(image[hi - 1:hi + 2, wi - 1:wi + 2], convH)) for wi in range(w)[1:w - 1]: deltaH[0][wi] = image[0][wi + 1] - image[0][wi] deltaH[h - 1][wi] = image[h - 1][wi + 1] - image[h - 1][wi] for hi in range(h): deltaH[hi][0] = image[hi][1] - image[hi][0] deltaH[hi][w - 1] = image[hi][w - 1] - image[hi][w - 2] # calc for deltaV for hi in range(h)[1:h - 1]: for wi in range(w)[1:w - 1]: deltaV[hi][wi] = np.sum( np.multiply(image[hi - 1:hi + 2, wi - 1:wi + 2], convV)) for wi in range(w): deltaV[0][wi] = image[1][wi] - image[0][wi] deltaV[h - 1][wi] = image[h - 1][wi] - image[h - 2][wi] for hi in range(h)[1:h - 1]: deltaV[hi][0] = image[hi + 1][0] - image[hi][0] deltaV[hi][w - 1] = image[hi + 1][w - 1] - image[hi][w - 1] deltaG = (np.absolute(deltaH) + np.absolute(deltaV)) / 2.0 deltaG_vec = np.reshape(deltaG, (deltaG.shape[0] * deltaG.shape[1])) # calc the theta for hi in range(h): for wi in range(w): if (deltaH[hi][wi] == 0 and deltaV[hi][wi] == 0): theta[hi][wi] = 0 elif (deltaH[hi][wi] == 0): theta[hi][wi] = np.pi else: theta[hi][wi] = np.arctan( deltaV[hi][wi] / deltaH[hi][wi]) + np.pi / 2.0 theta_vec = np.reshape(theta, (theta.shape[0] * theta.shape[1])) n = 16 t = 12 cnt = 0 hd = np.zeros(n) dlen = deltaG_vec.shape[0] for ni in range(n): for k in range(dlen): if ((deltaG_vec[k] >= t) and (theta_vec[k] >= (2 * ni - 1) * np.pi / (2 * n)) and (theta_vec[k] < (2 * ni + 1) * np.pi / (2 * n))): hd[ni] += 1 hd = hd / np.mean(hd) hd_max_index = np.argmax(hd) fdir = 0 for ni in range(n): fdir += np.power((ni - hd_max_index), 2) * hd[ni] return fdir
plt.plot(rangof, FFT_ecg_one_lead, label='Sin Filtrar') plt.plot(rangof, FFT_ecg_f_notch, label='Notch') plt.grid() plt.legend() plt.show() w, h = sig.freqz(b, a) plt.figure(3) plt.title('Respuesta del Filtro') plt.subplot(211) plt.plot(w * nyq_frec / np.pi, abs(h)) plt.grid() plt.ylabel('Modulo') plt.subplot(212) plt.plot(w * nyq_frec / np.pi, np.arctan(h.imag / h.real)) plt.grid() plt.ylabel('Fase') plt.show() import scipy.signal as sig import numpy as np import matplotlib.pyplot as plt import scipy.io as sio #------APERTURA DE LA SEÑAL------- mat_struct = sio.loadmat( '/home/luciasucunza/git_proyecto_ecg/Filtros/TP4_ecg.mat') ecg_one_lead = mat_struct['ecg_lead'] ecg_one_lead = ecg_one_lead.flatten()
def minimize(phi): return np.arctan(cD_ges / cL) - self.alpha + phi
def _calc_eta_eff(η_k): return 22.743 * arctan(0.04715 * η_k)
def compute_naca_4series_lines(x,camber,camber_loc,thickness): """Computes the camber, thickness, and the angle of the camber line at a given point along the airfoil. Assumptions: None Source: Similar to http://airfoiltools.com/airfoil/naca4digit Inputs: camber [-] Maximum camber as a fraction of chord camber_loc [-] Maximum camber location as a fraction of chord thickness [-] Maximum thickness as a fraction of chord Outputs: zt [-] Thickness zc [-] Camber th [radians] Angle of the camber line Properties Used: N/A """ xx = x*x # thickness zt = thickness/0.2 * ( 0.2969*np.sqrt(x) - 0.1260*(x) - 0.3516*(xx) + 0.2843*(x*xx) - 0.1015*(xx*xx) ) # symmetric if ( camber<=0.0 or camber_loc<=0.0 or camber_loc>=1.0 ): zc = 0.0 th = 0.0 else: # camber if x < camber_loc: zc = (camber/(camber_loc*camber_loc)) * \ (2.0*camber_loc*x - xx) else: zc = (camber/((1.0 - camber_loc)*(1.0 - camber_loc))) * \ (1.0 - 2.0*camber_loc + 2.0*camber_loc*x - xx) # finite difference theta xo = x + 0.00001; xoxo = xo*xo; if xo < camber_loc: zo = (camber/(camber_loc*camber_loc)) * \ (2.0*camber_loc*xo - xoxo) else: zo = (camber/((1.0 - camber_loc)*(1.0 - camber_loc))) * \ (1.0 - 2.0*camber_loc + 2.0*camber_loc*xo - xoxo) th = np.arctan( (zo - zc)/0.00001 ) return zt,zc,th
def ellipse_angle_of_rotation( a ): b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0] return 0.5*np.arctan(2*b/(a-c))
def MIT_walls(system, H): # Add main walls as a box wall_t = 0.1 wall_h = 3 / 2 * H texture_wall = 'textures/yellow_brick.jpg' scale = [10, 10] # Texture scale pos_3_3 = np.array([-4.5, 0 + 3 / 2 * H, 8.16 + wall_t]) pos_3_4 = np.array([-4.5 - wall_t, 5 / 2 * H, 8.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, 11, H / 2, wall_t, pos_3_3, texture_wall, [10, 10]) # Positive z direction MiroAPI.add_boxShapeHemi(system, 11 - wall_t, H / 2, wall_t, pos_3_4, texture_wall, [10, 10]) # Positive z direction # Add support colums as a box beam_h = 3 / 2 * H beam_w = 0.08 beam_pos_1 = np.array([4, 0 + beam_h, 5]) # Close left of stair beam_pos_2 = np.array([-0.8, 0 + 4 / 3 * beam_h, 5]) # Left of stair beam_pos_3 = np.array([8.5, 0 + beam_h, 0.5]) # Close right of stair beam_pos_4 = np.array([8.5, 0 + beam_h, -4.3]) # Right of stair beam_pos_5 = np.array([8.5, 0 + beam_h, 5]) # Middle beam MiroAPI.add_boxShapeHemi(system, beam_w, beam_h, beam_w, beam_pos_1, 'textures/white concrete.jpg', scale) MiroAPI.add_boxShapeHemi(system, beam_w, 2 / 3 * beam_h, beam_w, beam_pos_2, 'textures/white concrete.jpg', scale) MiroAPI.add_boxShapeHemi(system, beam_w, beam_h, beam_w, beam_pos_3, 'textures/white concrete.jpg', scale) MiroAPI.add_boxShapeHemi(system, beam_w, beam_h, beam_w, beam_pos_4, 'textures/white concrete.jpg', scale) MiroAPI.add_boxShapeHemi(system, beam_w, beam_h, beam_w, beam_pos_5, 'textures/white concrete.jpg', scale) # Beams along wall for beam in range(5): x = 12.75 + beam * 0.46 z = 8.16 + 0.05 + wall_t - beam * 4.47 beam_pos = np.array([x, 0 + beam_h, z]) MiroAPI.add_boxShapeHemi(system, beam_w, beam_h, beam_w, beam_pos, 'textures/white concrete.jpg', scale) #-------------2nd floor--------------- # Add wall, 2nd floor towards MIT place bWall_height = H / 2 - wall_t pos = np.array([-1.82, 0 + bWall_height, 5 + wall_t]) MiroAPI.add_boxShapeHemi(system, 3.48, bWall_height, wall_t, pos, 'textures/storage_wall.jpg', [12, 15]) # Add wall, 2nd floor towards NA (positive z direction) pos = np.array([-7, H / 2, 8.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, 8.75 - wall_t, H / 2, wall_t, pos, 'textures/yellow_brick.jpg', [5, 5]) # Add entrence wall (positive x direction) pos = np.array([12.7 + wall_t, 0 + H / 2 - 0.1, 10.18]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.1, 1.9, pos, 'textures/yellow_brick.jpg', [5, 5]) # Add entrence wall (negative x direction) pos = np.array([-0.4, 0 + H / 2 - 0.16, 9.86]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.16, 1.5, pos, 'textures/door_cs.jpg', [4, 3], Collide=False) # Add entrence corridor (negative x direction) pos = np.array([0.65, 0 + H / 2 - 0.1, 11.41]) MiroAPI.add_boxShapeHemi(system, 1, H / 2 - 0.1, wall_t, pos, 'textures/white concrete.jpg', [5, 5]) # Add 2nd entrence wall (negative x direction) pos = np.array([1.6, 0 + H / 2 - 0.1, 6.5 + wall_t + 0.01 + 0.05]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.1, 1.5 + wall_t + 0.05, pos, 'textures/yellow_brick.jpg', [5, 5]) #-------------3rd floor--------------- # Add wall, 3rd floor (negative x direction) MIT info screen pos = np.array([6.5 - wall_t, 0 + 3 / 2 * H - 0.16, 10.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.16, 2 - wall_t, pos, 'textures/yellow_brick.jpg', [5, 5]) # Add wall, 3rd floor towards NA 1 (negative z direction) pos = np.array([-7.6, 0 + 3 / 2 * H, 5.65]) MiroAPI.add_boxShapeHemi(system, 1.75, H / 2, wall_t, pos, 'textures/white concrete.jpg', [10, 7]) # Add wall, 3rd floor towards NA 2 (negative z direction) pos = np.array([-11.3, 0 + 3 / 2 * H, 5.65]) MiroAPI.add_boxShapeHemi(system, 0.25, H / 2, wall_t, pos, 'textures/yellow_brick.jpg', [1, 1], False) # Add wall, 3rd floor corridor towards NTK (negative x direction) for wall in range(2): x = -11.05 + wall * (1.71 + wall_t) pos = np.array([x, 0 + 3 / 2 * H, 5.25]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2, 0.4, pos, 'textures/yellow_brick.jpg', [1, 1], False) # Add wall, 3rd floor NTK door (negative z direction) # pos = np.array([-10.2, 0+3/2*H, 5]) # MiroAPI.add_boxShapeHemi(system, 0.85, H/2, wall_t, pos, 'textures/door_ntk.jpg', [-4,-3], False) # Add wall, 3rd floor NA corridor end (negative x direction) pos = np.array([-11.55, 3 / 2 * H - 0.16, 6.95]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.16, 1.25, pos, 'textures/mit_3rd_na2.jpg', [4, 3]) # Add wall, 3rd floor towards MIT fountain pos = np.array([11.65, 3 / 2 * H, 12.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, 5.15, H / 2, wall_t, pos, 'textures/yellow_brick.jpg', [5, 5]) # Add wall, 3rd floor wall, left hand side towards UMU library (negative z direction) pos = np.array([18.3, 3 / 2 * H - wall_t, 12.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, 1.5, H / 2 - wall_t, wall_t, pos, 'textures/white concrete.jpg', [3, 3]) # Add wall, 3rd floor UMU library end (negative x direction) pos = np.array([19.9, 3 / 2 * H - 0.16, 10.56]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2 - 0.16, 1.6, pos, 'textures/mit_3rd_sam.jpg', [-4, -3]) #-------------4th floor--------------- # Add wall, 4th floor flower pot (Negative x direction) pos = np.array([6.5 - wall_t + 0.01, 5 / 2 * H, 7.08 + wall_t + 0.01]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2, 2.08 + wall_t, pos, 'textures/white concrete.jpg', [5, 5]) # Add wall, 4th floor data cooridor (negative x direction) pos = np.array([5.5 - wall_t, 0 + 5 / 2 * H, 10.66 + wall_t]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2, 1.5 - wall_t, pos, 'textures/door_cs.jpg', [4, 3], Collide=False) # Add 4th floor wall (positive x direction) pos = np.array([12.7 + wall_t, 0 + 5 / 2 * H, 10.18]) MiroAPI.add_boxShapeHemi(system, wall_t, H / 2, 1.9, pos, 'textures/yellow_brick.jpg', [2, 2]) # Add wall, 4th floor towards NA (negative z direction) pos = np.array([-9.3 - wall_t, 0 + 5 / 2 * H, 5 - wall_t]) MiroAPI.add_boxShapeHemi(system, 4 - wall_t, H / 2, wall_t, pos, 'textures/yellow_brick.jpg', [10, 7], False) # Add wall, 4th floor wall towards MIT fountain pos = np.array([9, 5 / 2 * H, 12.16 + wall_t]) MiroAPI.add_boxShapeHemi(system, 3.5, H / 2, wall_t, pos, 'textures/white concrete.jpg', [5, 5]) #----------------Other---------------- # Add white wall extension, technology pos = np.array([9.9, 3 / 2 * H, -8.8 - wall_t]) MiroAPI.add_boxShapeHemi(system, 1.4, 3 / 2 * H, wall_t, pos, 'textures/white concrete.jpg', [5, 5]) # Add wall towards technology building (negative x direction) pos = np.array([8.5 - wall_t + 2.8, 0 + 3 / 2 * H, -11.8 - wall_t + 1.1]) MiroAPI.add_boxShapeHemi(system, wall_t, 3 / 2 * H, 1.9 - wall_t, pos, 'textures/white concrete.jpg', [10, 10]) # Add office cooridor wall (negative x direction) pos = np.array([-11.05, 0 + 3 / 2 * H, -7]) MiroAPI.add_boxShapeHemi(system, wall_t, 3 / 2 * H, 12, pos, 'textures/white concrete.jpg', [10, 10]) # Add office wall (negative x direction) pos = np.array([-9.35, 0 + 3 / 2 * H, -1.9]) MiroAPI.add_boxShapeHemi(system, wall_t, 3 / 2 * H, 6.9, pos, 'textures/white concrete.jpg', [10, 10]) # Add office wall (negative z direction) pos = np.array([1.5, 0 + 3 / 2 * H, -12.6]) MiroAPI.add_boxShapeHemi(system, 7, 3 / 2 * H, wall_t, pos, 'textures/white concrete.jpg', [10, 10]) # Add office cooridor wall (negative z direction) pos = np.array([1.5, 0 + 3 / 2 * H, -14.3]) MiroAPI.add_boxShapeHemi(system, 7, 3 / 2 * H, wall_t, pos, 'textures/white concrete.jpg', [10, 10]) # Add office end pos = np.array([-8.5, 0 + 3 / 2 * H, -19]) MiroAPI.add_boxShapeHemi(system, 2.65, 3 / 2 * H, wall_t, pos, 'textures/white concrete.jpg', [10, 10]) # Add elevator shaft for floor in range(3): y_pos = H * floor + H / 2 pos = np.array([10.7, y_pos, 12.1]) MiroAPI.add_boxShapeHemi(system, 2.034, H / 2, wall_t, pos, 'textures/elevator.png', [4, 3]) # Add end wall, towards technology texture = [ 'textures/mit_4th.jpg', 'textures/mit_4th.jpg', 'textures/mit_4th.jpg' ] for floor in range(3): y_pos = H * floor + H / 2 pos = np.array([10.5 + 2.8 - 0.23, y_pos, -17 + 2.2 + 2.2]) MiroAPI.add_boxShapeHemi(system, 1.77, H / 2, wall_t, pos, texture[floor], [-4, -3], Collide=False) #Add oblique walls n = np.array([0, 1, 0]) # Normal vector for rotation alpha = -np.arctan(211 / 1380 - 0.05) # Rotation angle for positive x wall #Add oblique wall towards umu libary pos_1 = np.array([16.3, 3 / 2 * H - wall_t, 0.34 + 8.16 + wall_t]) dim_1 = np.array([wall_t, H / 2, 3.6]) ang_1 = np.pi * (0.5 - 0.03) sca_1 = [10, 10] #Add oblique wall towards NA pos_2 = np.array([-5.6 - wall_t, 3 / 2 * H, 5.3]) dim_2 = np.array([wall_t, H / 2, 0.545]) ang_2 = -(np.pi / 4) #Main wall in positive x direction pos_3 = np.array([13.775 + wall_t, 0, -2.2]) + np.array([0, wall_h, 0]) ang_3 = alpha dim_3 = np.array([wall_t, wall_h, 10.58]) pos_ob = [pos_1, pos_2, pos_3] dim = [dim_1, dim_2, dim_3] ang = [ang_1, ang_2, ang_3] textures = [texture_wall, 'textures/white concrete.jpg', texture_wall] scale = [sca_1, sca_1, sca_1] for i in range(len(pos_ob)): # Create a box MiroAPI.add_boxShapeHemi(system, dim[i][0], dim[i][1], dim[i][2], pos_ob[i], rotY=ang[i], rotDegrees=False, texture=textures[i], scale=scale[i])
def atan(x): return np.arctan(x)
def animate(i): if not app.pause: graph_data = open('tmpData.csv', 'r').read() lines = graph_data.split('\n') xs = [] ys = [] fs = [] ts = [] cs = [] zs = [] ms = [] # fs[np.where(fs > ulim)] = ulim # fs[np.where(fs < llim)] = np.nan resistanceData = [] reactanceData = [] gainFactor = (1 / 10) / (13370) pi = 3.141592654 for line in lines: if len(line) > 8: c, f, x, y, t = line.split(',') xs.append(float(x)) ys.append(float(y)) fs.append(float(f)) ts.append(float(f)) cs.append(float(c)) if float(x)**2 + float(y)**2 > 0: magnitude = math.sqrt((float(x)**2) + (float(y)**2)) impedance = 1 / (gainFactor * magnitude) ms.append(magnitude) zs.append(impedance) else: ms.append(0) zs.append(0) x = float(x) y = float(y) calibration_phase_mid_point = 0 if x > 0 < y: theta = np.arctan( x / y) # theta = arctan (imaginary part/real part) phase2 = (theta * 180) / pi phase2 = phase2 - calibration_phase_mid_point # convert from radians to degrees impedance = 1 / (gainFactor * math.sqrt((float(x)**2) + (float(y)**2))) resistanceData.append(impedance * np.cos(phase2)) reactanceData.append(impedance * np.sin(phase2)) if x > 0 > y: theta = np.arctan( x / y) # 4th quadrant theta = minus angle phase2 = ((theta * 180) / pi) + 360 phase2 = phase2 - calibration_phase_mid_point impedance = 1 / (gainFactor * math.sqrt((float(x)**2) + (float(y)**2))) resistanceData.append(impedance * np.cos(phase2)) reactanceData.append(impedance * np.sin(phase2)) if x < 0 > y: theta = -pi + np.arctan( x / y) # 3rd quadrant theta img/real is positive phase2 = (theta * 180) / pi phase2 = phase2 - calibration_phase_mid_point impedance = 1 / (gainFactor * math.sqrt((float(x)**2) + (float(y)**2))) resistanceData.append(impedance * np.cos(phase2)) reactanceData.append(impedance * np.sin(phase2)) if x < 0 < y: theta = pi + np.arctan( x / y) # 2nd quadrant img/real is neg phase2 = (theta * 180) / pi phase2 = phase2 - calibration_phase_mid_point impedance = 1 / (gainFactor * math.sqrt((float(x)**2) + (float(y)**2))) resistanceData.append(impedance * np.cos(phase2)) reactanceData.append(impedance * np.sin(phase2)) ax2.clear() ax2.scatter(resistanceData, reactanceData, s=10, c='C3') ax2.set_title('Nyquist', loc='left') ax2.set_xlabel("Resistance (kOhms)") ax2.set_ylabel("Reactance (kOhms)") ax3.clear() ax3.set_title('DFT', loc='left') ax3.set_xlabel("R") ax3.set_ylabel("I") ax3.plot(xs, ys, color='C1', linewidth=2) ax4.clear() ax4.set_title('Impedance', loc='left') ax4.set_xlabel("f (kHz)") ax4.set_ylabel("Z (kOhms)") #ax4.set_yscale("log", nonposy='clip') ax4.plot(fs, zs, color='C2', linewidth=0.9) ax5.clear() ax5.set_title('Magnitude', loc='left') ax5.set_xlabel("f (kHz)") ax5.set_ylabel("Magnitude (raw)") #ax4.set_yscale("log", nonposy='clip') ax5.plot(fs, ms, color='C4', linewidth=0.9)