def hgs_to_hcc(heliogcoord, heliocframe): """ Convert from Heliographic Stonyhurst to Heliograpic Carrington. """ hglon = heliogcoord.lon hglat = heliogcoord.lat r = heliogcoord.radius.to(u.m) l0b0_pair = [heliocframe.L0, heliocframe.B0] l0_rad = l0b0_pair[0].to(u.rad) b0_deg = l0b0_pair[1] lon = np.deg2rad(hglon) lat = np.deg2rad(hglat) cosb = np.cos(b0_deg.to(u.rad)) sinb = np.sin(b0_deg.to(u.rad)) lon = lon - l0_rad cosx = np.cos(lon) sinx = np.sin(lon) cosy = np.cos(lat) siny = np.sin(lat) x = r * cosy * sinx y = r * (siny * cosb - cosy * cosx * sinb) zz = r * (siny * sinb + cosy * cosx * cosb) representation = CartesianRepresentation(x.to(u.km), y.to(u.km), zz.to(u.km)) return heliocframe.realize_frame(representation)
def kdtree_fast(latvar,lonvar,lat0,lon0): ''' :param latvar: :param lonvar: :param lat0: :param lon0: :return: ''' rad_factor = pi/180.0 # for trignometry, need angles in radians # Read latitude and longitude from file into numpy arrays latvals = latvar[:] * rad_factor lonvals = lonvar[:] * rad_factor ny,nx = latvals.shape clat,clon = cos(latvals),cos(lonvals) slat,slon = sin(latvals),sin(lonvals) # Build kd-tree from big arrays of 3D coordinates triples = list(zip(ravel(clat*clon), ravel(clat*slon), ravel(slat))) kdt = cKDTree(triples) lat0_rad = lat0 * rad_factor lon0_rad = lon0 * rad_factor clat0,clon0 = cos(lat0_rad),cos(lon0_rad) slat0,slon0 = sin(lat0_rad),sin(lon0_rad) dist_sq_min, minindex_1d = kdt.query([clat0*clon0, clat0*slon0, slat0]) iy_min, ix_min = unravel_index(minindex_1d, latvals.shape) return iy_min,ix_min
def to_SQL(self, RAname, DECname): if self.DECdeg != 90.0 and self.DECdeg != -90.0: RAmax = self.RAdeg + \ 360.0 * np.arcsin(np.sin(0.5*self.radius) / np.cos(self.DEC))/np.pi RAmin = self.RAdeg - \ 360.0 * np.arcsin(np.sin(0.5*self.radius) / np.cos(self.DEC))/np.pi else: #just in case, for some reason, we are looking at the poles RAmax = 360.0 RAmin = 0.0 DECmax = self.DECdeg + self.radiusdeg DECmin = self.DECdeg - self.radiusdeg #initially demand that all objects are within a box containing the circle #set from the DEC1=DEC2 and RA1=RA2 limits of the haversine function bound = ("%s between %f and %f and %s between %f and %f " % (RAname, RAmin, RAmax, DECname, DECmin, DECmax)) #then use the Haversine function to constrain the angular distance form boresite to be within #the desired radius. See http://en.wikipedia.org/wiki/Haversine_formula bound = bound + ("and 2 * ASIN(SQRT( POWER(SIN(0.5*(%s - %s) * PI() / 180.0),2)" % (DECname,self.DECdeg)) bound = bound + ("+ COS(%s * PI() / 180.0) * COS(%s * PI() / 180.0) " % (DECname, self.DECdeg)) bound = bound + ("* POWER(SIN(0.5 * (%s - %s) * PI() / 180.0),2)))" % (RAname, self.RAdeg)) bound = bound + (" < %s " % self.radius) return bound
def test_genz_oscillatory_exact_d4(): exact = np.sin(29988 - 7*np.pi/34) * \ np.sin(51)*np.sin(2601/2)*np.sin(6273/2)*np.sin(25500) / \ 784125 calculated = ti.genz_oscillatory_exact(51, np.array([2, 123, 51, 1000]), 11/17) assert np.allclose([exact], [calculated])
def spherical_to_cartesian(lons, lats, depths): """ Return the position vectors (in Cartesian coordinates) of list of spherical coordinates. For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html. Parameters are components of spherical coordinates in a form of scalars, lists or numpy arrays. ``depths`` can be ``None`` in which case it's considered zero for all points. :returns: ``numpy.array`` of 3d vectors representing points' coordinates in Cartesian space. The array has the same shape as parameter arrays. In particular it means that if ``lons`` and ``lats`` are scalars, the result is a single 3d vector. Vector of length ``1`` represents distance of 1 km. See also :func:`cartesian_to_spherical`. """ phi = numpy.radians(lons) theta = numpy.radians(lats) if depths is None: rr = EARTH_RADIUS else: rr = EARTH_RADIUS - numpy.array(depths) cos_theta_r = rr * numpy.cos(theta) xx = cos_theta_r * numpy.cos(phi) yy = cos_theta_r * numpy.sin(phi) zz = rr * numpy.sin(theta) vectors = numpy.array([xx.transpose(), yy.transpose(), zz.transpose()]) \ .transpose() return vectors
def get_gabors(self, rf): lams = float(rf[0])/self.sfs # lambda = 1./sf #1./np.array([.1,.25,.4]) sigma = rf[0]/2./np.pi # rf = [100,100] gabors = np.zeros(( len(oris),len(phases),len(lams), rf[0], rf[1] )) i = np.arange(-rf[0]/2+1,rf[0]/2+1) #print i j = np.arange(-rf[1]/2+1,rf[1]/2+1) ii,jj = np.meshgrid(i,j) for o, theta in enumerate(self.oris): x = ii*np.cos(theta) + jj*np.sin(theta) y = -ii*np.sin(theta) + jj*np.cos(theta) for p, phase in enumerate(self.phases): for s, lam in enumerate(lams): fxx = np.cos(2*np.pi*x/lam + phase) * np.exp(-(x**2+y**2)/(2*sigma**2)) fxx -= np.mean(fxx) fxx /= np.linalg.norm(fxx) #if p==0: #plt.subplot(len(oris),len(lams),count+1) #plt.imshow(fxx,cmap=mpl.cm.gray,interpolation='bicubic') #count+=1 gabors[o,p,s,:,:] = fxx plt.show() return gabors
def func1(self,i,theta,vtheta): S=np.sin(theta[0]-theta[1]) C=np.cos(theta[0]-theta[1]) if i==0: return (S*vtheta[1]**2+C*S*vtheta[0]**2+2*self.g*np.sin(theta[0])-self.g*C*np.sin(theta[1]))/(C**2-2) elif i==1: return (C*S*vtheta[1]**2+2*S*vtheta[0]**2+2*self.g*C*np.sin(theta[0])-2*self.g*np.sin(theta[1]))/(2-C**2)
def test_arclength_half_circle(): """ Here we define the tests for the lenght computer of our ArcLengthParametrizer, we try it with a half a circle and a fan. We test it both in 2d and 3d.""" # Number of interpolation points minus one n = 5 toll = 1.e-6 points = np.linspace(0, 1, (n+1) ) R = 1 P = 1 control_points_2d = np.asmatrix(np.zeros([n+1,2]))#[np.array([R*np.cos(5*i * np.pi / (n + 1)), R*np.sin(5*i * np.pi / (n + 1)), P * i]) for i in range(0, n+1)] control_points_2d[:,0] = np.transpose(np.matrix([R*np.cos(1 * i * np.pi / (n + 1))for i in range(n+1)])) control_points_2d[:,1] = np.transpose(np.matrix([R*np.sin(1 * i * np.pi / (n + 1))for i in range(n+1)])) control_points_3d = np.asmatrix(np.zeros([n+1,3]))#[np.array([R*np.cos(5*i * np.pi / (n + 1)), R*np.sin(5*i * np.pi / (n + 1)), P * i]) for i in range(0, n+1)] control_points_3d[:,0] = np.transpose(np.matrix([R*np.cos(1 * i * np.pi / (n + 1))for i in range(n+1)])) control_points_3d[:,1] = np.transpose(np.matrix([R*np.sin(1 * i * np.pi / (n + 1))for i in range(n+1)])) control_points_3d[:,2] = np.transpose(np.matrix([P*i for i in range(n+1)])) vsl = AffineVectorSpace(UniformLagrangeVectorSpace(n+1),0,1) dummy_arky_2d = ArcLengthParametrizer(vsl, control_points_2d) dummy_arky_3d = ArcLengthParametrizer(vsl, control_points_3d) length2d = dummy_arky_2d.compute_arclength()[-1,1] length3d = dummy_arky_3d.compute_arclength()[-1,1] # print (length2d) # print (n * np.sqrt(2)) l2 = np.pi * R l3 = 2 * np.pi * np.sqrt(R * R + (P / (2 * np.pi)) * (P / (2 * np.pi))) print (length2d, l2) print (length3d, l3) assert (length2d - l2) < toll assert (length3d - l3) < toll
def rotate(data, interpArray, rotation_angle): for i in range(interpArray.shape[0]): for j in range(interpArray.shape[1]): i1 = i - (interpArray.shape[0] / 2. - 0.5) j1 = j - (interpArray.shape[1] / 2. - 0.5) x = i1 * numpy.cos(rotation_angle) - j1 * numpy.sin(rotation_angle) y = i1 * numpy.sin(rotation_angle) + j1 * numpy.cos(rotation_angle) x += data.shape[0] / 2. - 0.5 y += data.shape[1] / 2. - 0.5 if x >= data.shape[0] - 1: x = data.shape[0] - 1.1 x1 = numpy.int32(x) if y >= data.shape[1] - 1: y = data.shape[1] - 1.1 y1 = numpy.int32(y) xGrad1 = data[x1 + 1, y1] - data[x1, y1] a1 = data[x1, y1] + xGrad1 * (x - x1) xGrad2 = data[x1 + 1, y1 + 1] - data[x1, y1 + 1] a2 = data[x1, y1 + 1] + xGrad2 * (x - x1) yGrad = a2 - a1 interpArray[i, j] = a1 + yGrad * (y - y1) return interpArray
def delta(phase,inc, ecc = 0, omega=0): """ Compute the distance center-to-center between planet and host star. ___ INPUT: phase: orbital phase in radian inc: inclination of the system in radian OPTIONAL INPUT: ecc: omega: // OUTPUT: distance center-to-center, double-float number. ___ """ phase = 2*np.pi*phase if ecc == 0 and omega == 0: delta = np.sqrt(1-(np.cos(phase)**2)*(np.sin(inc)**2)) else: delta = (1.-ecc**2.)/(1.-ecc*np.sin(phase-omega))* np.sqrt((1.-(np.cos(phase))**2.*(np.sin(inc))**2)) return delta
def rv_pqw(k, p, ecc, nu): """Returns r and v vectors in perifocal frame. """ r_pqw = (np.array([cos(nu), sin(nu), 0 * nu]) * p / (1 + ecc * cos(nu))).T v_pqw = (np.array([-sin(nu), (ecc + cos(nu)), 0]) * sqrt(k / p)).T return r_pqw, v_pqw
def createFringe(width, height, xFreq, xOffset, yFreq, yOffset): """Create a fringe frame. Parameters ---------- width, height : `int` Size of image. xFreq, yFreq : `float` Frequency of sinusoids in x and y. xOffset, yOffset : `float` Phase of sinusoids in x and y. Returns ------- exp : `lsst.afw.image.ExposureF` Fringe frame. """ image = afwImage.ImageF(width, height) array = image.getArray() x, y = np.indices(array.shape) array[x, y] = np.sin(xFreq*x + xOffset) + np.sin(yFreq*y + yOffset) mi = afwImage.makeMaskedImage(image) exp = afwImage.makeExposure(mi) exp.setFilter(afwImage.Filter('FILTER')) return exp
def get(self): """Build mesh from the tree of triangles created by reflections.""" # get n n, k, a, b = self.pad(self.values) # adjust defaults based on n self.full[2:4] = self.shape[n] # get all parameters n, k, a, b = self.pad(self.values) if n == -1: self.vertices = self.bothvertices[k] else: tree = self.trees[(n, k)] self.triangles = [] # angles are 2pi/a, 2pi/b side = np.sin(2 * pi / b) / np.sin(pi - 2 * pi / a - 2 * pi / b) self.vertices = [ np.array([0.0, 0.0]), np.array([1.0, 0.0]), np.array( [side * np.cos(2 * pi / a), side * np.sin(2 * pi / a)])] self.generate(tree, [0, 1, 2]) mesh = Mesh() editor = MeshEditor() editor.open(mesh, 2, 2) editor.init_vertices(len(self.vertices)) editor.init_cells(len(self.triangles)) for i, v in enumerate(self.vertices): editor.add_vertex(i, *v) for i, t in enumerate(self.triangles): editor.add_cell(i, *t) editor.close() return mesh
def axis_rotation_matrix( theta, u_x, u_y, u_z ): ''' http://en.wikipedia.org/wiki/Rotation_matrix ''' return numpy.array( [ [ cos(theta) + u_x**2 * ( 1 - cos(theta)) , u_x*u_y*(1-cos(theta)) - u_z*sin(theta) , u_x*u_z*(1-cos(theta)) + u_y*sin(theta) ] , [ u_y*u_x*(1-cos(theta)) + u_z*sin(theta) , cos(theta) + u_y**2 * (1-cos(theta)) , u_y*u_z*(1-cos(theta)) - u_x*sin(theta )] , [ u_z*u_x*(1-cos(theta)) - u_y*sin(theta) , u_z*u_y*(1-cos(theta)) + u_x*sin(theta) , cos(theta) + u_z**2*(1-cos(theta)) ] ])
def visualfeatures_to_world(a): alpha = a[0] dist_A = a[1] dist_B = a[2] vant_A = np.array([a[3], a[4], a[5]]) vant_A /= np.linalg.norm(vant_A) vant_B = np.array([a[6], a[7], a[8]]) vant_B /= np.linalg.norm(vant_B) PA = np.array([a[9], a[10], a[11]]) PB = np.array([a[12], a[13], a[14]]) PAB = PA - PB # manifold surface generated by interpolated alpha ?? # intersect manifold with vantage vectors # calculate distance dist_A_alpha = dist_A dist_B_alpha = dist_B # calculate lambda # sinusoid taking as input the angle between vantage and line AB (separating the two targets) line_AB = np3_to_vector3(PAB).perpendicular() angle_A = py_ang(vector3_to_np3(line_AB), vant_A) #line_AB.directedAngle(line_AB, np3_to_vector3(vant_A)) angle_B = py_ang(vector3_to_np3(line_AB), vant_B) lambda_A = np.sin(angle_A) lambda_B = np.sin(angle_B) F = PA + PB F += (vant_A * (dist_A + dist_A_alpha * lambda_A) / (1 + lambda_A)) F += (vant_B * (dist_B + dist_B_alpha * lambda_B) / (1 + lambda_B)) F *= 0.5 return F
def test_cmac(self): input_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) input_train_before = input_train.copy() input_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1)) input_test_before = input_test.copy() target_train = np.sin(input_train) target_train_before = target_train.copy() target_test = np.sin(input_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(input_train, target_train, epochs=100) predicted_test = cmac.predict(input_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(target_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm didn't modify data samples np.testing.assert_array_equal(input_train, input_train_before) np.testing.assert_array_equal(input_train, input_train_before) np.testing.assert_array_equal(target_train, target_train_before)
def lomb(t, y, freq): r"""Calculates Lomb periodogram.""" # Sets constants. nfreq = len(freq) fmax, fmin = freq[-1], freq[0] power = np.zeros(nfreq) f4pi = freq * 4 * np.pi pi2 = np.pi * 2. n = len(y) cosarg = np.zeros(n) sinarg = np.zeros(n) argu = np.zeros(n) var = np.cov(y) # Variance. yn = y - y.mean() # Do one Lomb loop. for fi in range(nfreq): sinsum = np.sum(np.sin(f4pi[fi]) * t) cossum = np.sum(np.cos(f4pi[fi]) * t) tau = np.arctan2(sinsum, cossum) argu = pi2 * freq[fi] * (t - tau) cosarg = np.cos(argu) cfi = np.sum(yn * cosarg) cosnorm = np.sum(cosarg ** 2) sinarg = np.sin(argu) sfi = np.sum(yn * sinarg) sinnorm = np.sum(sinarg ** 2) power[fi] = (cfi ** 2 / cosnorm + sfi ** 2 / sinnorm) / 2 * var return power
def test_connected(Simulator): m = nengo.Network(label='test_connected', seed=123) with m: input = nengo.Node(output=lambda t: np.sin(t), label='input') output = nengo.Node(output=lambda t, x: np.square(x), size_in=1, label='output') nengo.Connection(input, output, synapse=None) # Direct connection p_in = nengo.Probe(input, 'output') p_out = nengo.Probe(output, 'output') sim = Simulator(m) runtime = 0.5 sim.run(runtime) with Plotter(Simulator) as plt: t = sim.trange() plt.plot(t, sim.data[p_in], label='sin') plt.plot(t, sim.data[p_out], label='sin squared') plt.plot(t, np.sin(t), label='ideal sin') plt.plot(t, np.sin(t) ** 2, label='ideal squared') plt.legend(loc='best') plt.savefig('test_node.test_connected.pdf') plt.close() sim_t = sim.trange() sim_sin = sim.data[p_in].ravel() sim_sq = sim.data[p_out].ravel() t = 0.001 * np.arange(len(sim_t)) assert np.allclose(sim_t, t) # 1-step delay assert np.allclose(sim_sin[1:], np.sin(t[:-1])) assert np.allclose(sim_sq[1:], sim_sin[:-1] ** 2)
def rotate (x, y, angle) : angle = angle*2*np.pi/360. rotMatrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]], dtype=np.float64) newx = x*rotMatrix[0,0] + y*rotMatrix[0,1] newy = x*rotMatrix[1,0] + y*rotMatrix[1,1] return newx,newy
def rotateAboutXaxis (x, y, z, alpha, verbose = 0) : if verbose : print "\t x axis rotation of ", alpha, "given ", x[0], y[0], z[0] alpha = alpha*2*np.pi/360. xp = x yp = y*np.cos(alpha) - z*np.sin(alpha) zp = y*np.sin(alpha) + z*np.cos(alpha) return xp,yp,zp
def rotateAboutZaxis (x, y, z, alpha, verbose = 0) : if verbose : print "\t z axis rotation of ", alpha, "given ", x[0], y[0], z[0] alpha = alpha*2*np.pi/360. xp = x*np.cos(alpha) - y*np.sin(alpha) yp = x*np.sin(alpha) + y*np.cos(alpha) zp = z return xp,yp,zp
def sphToCartesian(ra0, ra, dec, r=1) : ra = (ra-(ra0-90))*2*np.pi/360. dec = dec*2*np.pi/360. x = r * np.cos(ra)*np.cos(dec) y = r * np.sin(ra)*np.cos(dec) z = r * np.sin(dec) return x,y,z
def __find_index(self, lat, lon, latvar, lonvar, n=1): if self._kdt.get(latvar.name) is None: latvals = latvar[:] * RAD_FACTOR lonvals = lonvar[:] * RAD_FACTOR clat, clon = np.cos(latvals), np.cos(lonvals) slat, slon = np.sin(latvals), np.sin(lonvals) triples = np.array(list(zip(np.ravel(clat * clon), np.ravel(clat * slon), np.ravel(slat)))) self._kdt[latvar.name] = KDTree(triples) del clat, clon del slat, slon del triples if not hasattr(lat, "__len__"): lat = [lat] lon = [lon] lat = np.array(lat) lon = np.array(lon) lat_rad = lat * RAD_FACTOR lon_rad = lon * RAD_FACTOR clat, clon = np.cos(lat_rad), np.cos(lon_rad) slat, slon = np.sin(lat_rad), np.sin(lon_rad) q = np.array([clat * clon, clat * slon, slat]).transpose() dist_sq_min, minindex_1d = self._kdt[latvar.name].query( np.float32(q), k=n ) iy_min, ix_min = np.unravel_index(minindex_1d, latvar.shape) return iy_min, ix_min, dist_sq_min * EARTH_RADIUS
def get_new_cell(self): """Returns new basis vectors""" a = np.sqrt(self.a) b = np.sqrt(self.b) c = np.sqrt(self.c) ad = self.atoms.cell[0] / np.linalg.norm(self.atoms.cell[0]) Z = np.cross(self.atoms.cell[0], self.atoms.cell[1]) Z /= np.linalg.norm(Z) X = ad - np.dot(ad, Z) * Z X /= np.linalg.norm(X) Y = np.cross(Z, X) alpha = np.arccos(self.x / (2 * b * c)) beta = np.arccos(self.y / (2 * a * c)) gamma = np.arccos(self.z / (2 * a * b)) va = a * np.array([1, 0, 0]) vb = b * np.array([np.cos(gamma), np.sin(gamma), 0]) cx = np.cos(beta) cy = (np.cos(alpha) - np.cos(beta) * np.cos(gamma)) \ / np.sin(gamma) cz = np.sqrt(1. - cx * cx - cy * cy) vc = c * np.array([cx, cy, cz]) abc = np.vstack((va, vb, vc)) T = np.vstack((X, Y, Z)) return np.dot(abc, T)
def dist(lon1, lat1, lon2, lat2): R = 6371.004 lon1, lat1 = angle_conversion(lon1), angle_conversion(lat1) lon2, lat2 = angle_conversion(lon2), angle_conversion(lat2) l = R*np.arccos(np.cos(lat1)*np.cos(lat2)*np.cos(lon1-lon2)+\ np.sin(lat1)*np.sin(lat2)) return l
def test_SeedCoherenceAnalyzer(): """ Test the SeedCoherenceAnalyzer """ methods = (None, {"this_method": 'welch', "NFFT": 256}, {"this_method": 'multi_taper_csd'}, {"this_method": 'periodogram_csd', "NFFT": 256}) Fs = np.pi t = np.arange(256) seed1 = np.sin(10 * t) + np.random.rand(t.shape[-1]) seed2 = np.sin(10 * t) + np.random.rand(t.shape[-1]) target = np.sin(10 * t) + np.random.rand(t.shape[-1]) T = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs) T_seed1 = ts.TimeSeries(seed1, sampling_rate=Fs) T_seed2 = ts.TimeSeries(np.vstack([seed1, seed2]), sampling_rate=Fs) T_target = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs) for this_method in methods: if this_method is None or this_method['this_method']=='welch': C1 = nta.CoherenceAnalyzer(T, method=this_method) C2 = nta.SeedCoherenceAnalyzer(T_seed1, T_target, method=this_method) C3 = nta.SeedCoherenceAnalyzer(T_seed2, T_target, method=this_method) npt.assert_almost_equal(C1.coherence[0, 1], C2.coherence[1]) npt.assert_almost_equal(C2.coherence[1], C3.coherence[0, 1]) npt.assert_almost_equal(C1.phase[0, 1], C2.relative_phases[1]) npt.assert_almost_equal(C1.delay[0, 1], C2.delay[1]) else: npt.assert_raises(ValueError,nta.SeedCoherenceAnalyzer, T_seed1, T_target, this_method)
def test_SparseCoherenceAnalyzer(): Fs = np.pi t = np.arange(256) x = np.sin(10 * t) + np.random.rand(t.shape[-1]) y = np.sin(10 * t) + np.random.rand(t.shape[-1]) T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs) C1 = nta.SparseCoherenceAnalyzer(T, ij=((0, 1), (1, 0))) C2 = nta.CoherenceAnalyzer(T) # Coherence symmetry: npt.assert_equal(np.abs(C1.coherence[0, 1]), np.abs(C1.coherence[1, 0])) npt.assert_equal(np.abs(C1.coherency[0, 1]), np.abs(C1.coherency[1, 0])) # Make sure you get the same answers as you would from the standard # CoherenceAnalyzer: npt.assert_almost_equal(C2.coherence[0, 1], C1.coherence[0, 1]) # This is the PSD (for the first time-series in the object): npt.assert_almost_equal(C2.spectrum[0, 0], C1.spectrum[0]) # And the second (for good measure): npt.assert_almost_equal(C2.spectrum[1, 1], C1.spectrum[1]) # The relative phases should be equal npt.assert_almost_equal(C2.phase[0, 1], C1.relative_phases[0, 1]) # But not the absolute phases (which have the same shape): npt.assert_equal(C1.phases[0].shape, C1.relative_phases[0, 1].shape) # The delay is equal: npt.assert_almost_equal(C2.delay[0, 1], C1.delay[0, 1]) # Make sure that you would get an error if you provided a method other than # 'welch': npt.assert_raises(ValueError, nta.SparseCoherenceAnalyzer, T, method=dict(this_method='foo'))
def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight, data, variables, rotate=0): """Convert data dictionary (of arrays) into a multiband GeoTiff :param newRasterfn: filename to save to :param rasterOrigin: location of top left corner :param pixelWidth: e-w pixel size :param pixelHeight: n-s pixel size :param data: dictionary containing the data arrays :param variables: list of which keys from the dictionary to output :param rotate: Optional rotation angle (in radians) """ cols = len(data['longitude']) rows = len(data['latitude']) originX = rasterOrigin[0] originY = rasterOrigin[1] we_res = np.cos(rotate) * pixelWidth rotX = np.sin(rotate) * pixelWidth rotY = -np.sin(rotate) * pixelHeight ns_res = np.cos(rotate) * pixelHeight driver = gdal.GetDriverByName('GTiff') nbands = len(variables) outRaster = driver.Create(newRasterfn, cols, rows, nbands, gdal.GDT_Float32) outRaster.SetGeoTransform((originX, we_res, rotX, originY, rotY, ns_res)) for band,key in enumerate(variables, 1): outband = outRaster.GetRasterBand(band) outband.SetNoDataValue(0) outband.WriteArray(data[key]) outband.FlushCache() outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromEPSG(4326) outRaster.SetProjection(outRasterSRS.ExportToWkt())
def calc_Tb(thetak=np.pi/3., phik=np.pi/8., thetan=np.pi/3., phin=np.pi/4., delta=0., Ts=11.1, Tg=57.23508, z=20, verbose=False, xalpha=34.247221, xc=0.004176, xB=0.365092, x1s=1.): """ Calculates brightness-temperature fluctuation T[K] from eq 1 of Paper II. NOTE: Magnetic-field direction is along the z-axis! It takes x's (all unitless), temperatures in [K], and angles in [rad].""" k_dot_n = np.cos(thetan)*np.cos(thetak) + np.sin(thetan)*np.sin(thetak)*np.cos(phin)*np.cos(phik) + np.sin(thetan)*np.sin(thetak)*np.sin(phin)*np.sin(phik) summ = 0. for i,m in enumerate( np.array([-2,-1,0,1,2]) ): summand = Y2( m,thetak,phik ) * np.conjugate( Y2( m,thetan,phin ) ) / (1. + xalpha + xc - 1j*m*xB) summ += summand.real first_term = 1 + delta + delta*k_dot_n**2 second_term = 1 + 2.*delta + 2.*delta*k_dot_n**2 - delta*4.*np.pi/75.*summ res = x1s * ( 1 - Tg/Ts ) * np.sqrt( (1 + z)/10. ) * ( 26.4 * first_term - 0.128 * x1s * ( Tg/Ts ) * np.sqrt( (1 + z)/10. ) * second_term) if verbose: print '\n' print 'xalpha = %f' % xalpha print 'xc = %f' % xc print 'xB = %f' % xB print 'k_dot_n=%f' % k_dot_n print 'summ=%f' % summ print 'first=%f' % 26.4*first_term print 'second=%f' % second_term return res/1000. #this is to make it to K from mK.
def sph2cart(*args): """Convert from spherical coordinates (elevation, azimuth, radius) to cartesian (x,y,z) usage: array3xN[x,y,z] = sph2cart(array3xN[el,az,rad]) OR x,y,z = sph2cart(elev, azim, radius) """ if len(args)==1: #received an Nx3 array elev = args[0][0,:] azim = args[0][1,:] radius = args[0][2,:] returnAsArray = True elif len(args)==3: elev = args[0] azim = args[1] radius = args[2] returnAsArray = False z = radius * numpy.sin(radians(elev)) x = radius * numpy.cos(radians(elev))*numpy.cos(radians(azim)) y = radius * numpy.cos(radians(elev))*numpy.sin(radians(azim)) if returnAsArray: return numpy.asarray([x, y, z]) else: return x, y, z
# tlu=tlu-tlu[0] # ti=np.linspace(0, tlu[-1], resolution) # th=interpolate.interp1d(tlu,thsl,'slinear') # th = th(ti) # th=np.tan(th) # th=th-th[0] # th=th/np.max(th) ''' Hz ''' ti=np.linspace(0,1,resolution) han2 = np.vectorize(lambda ti:(1-lam3)*(1-cos(2*pi*ti))+lam2*(1-cos(4*pi*ti))+lam3*(1-cos(6*pi*ti))) han2 = han2(ti) thsl=thi+(thf-thi)*han2/max(han2) tlu = np.cumsum(np.sin(thsl))*ti[1] tlu=tlu-tlu[0] ti=np.linspace(0, tlu[-1], resolution) th=interpolate.interp1d(tlu,thsl,'slinear') th = th(ti) th=1/np.tan(th) th=th-th[0] th=th/min(th) global H0 N = 3 # g = 0.004 * 2 * np.pi wq= np.array([5.00 , 4.62 ]) * 2 * np.pi eta_q= np.array([-0.250 , -0.250]) * 2 * np.pi
def drop(qstart, color, pose, list_len, object_pose): """ This function plans a path to drop objects to a target location :param qstart: initial pose of the robot (1x6). :param color: string of color of the robot we are using (blue or red) :param pose: position (3 dimensional) of the previously dropped object :param list_len: Number of objects already on the dropping area :param object_pose: pose (4x4) of the current dropping object :return: path - Nx6 path until the object is dropped """ ############################################# # Compute transformation matrix of drop pose ############################################# # Initialize FK and offsets between Gripper center and object center (currently grabbed by the gripper) FK = calculateFK() X_offset = 0 Y_offset = 0 # 3 drop points p1, p2, p3; (or drop "areas" since the object will not land at exactly the same x,y) # stack a max of 3 objects at p1, stack a max of 2 objects at p2, keep stacking onto p3 for the subsequent objects grabbed # Height and drop location # Case no object is present at the first drop point p1, drop to p1 area if (len(pose) == 0 or list_len == 0): height = 50.0 d_drop0_blue = np.array([120., 520., height, 1]).reshape((4, 1)) d_drop0_red = np.array([-120., -520., height, 1]).reshape((4, 1)) # Case already 3 objects at p1, switch to the next drop point p2 elif (list_len == 3): height = 50.0 d_drop0_blue = np.array([70., 520., height, 1]).reshape((4, 1)) d_drop0_red = np.array([-70., -520., height, 1]).reshape((4, 1)) # Case already 2 objects at p2 (a total of 5 objects on the platform), drop to the 3rd location p3 elif (list_len == 5): height = 50.0 d_drop0_blue = np.array([120., 470., height, 1]).reshape((4, 1)) d_drop0_red = np.array([-120., -470., height, 1]).reshape((4, 1)) # else drop on top of the previously dropped object (the top object on the stack at drop point p_i) else: height = pose[-1] + 28.0 d_drop0_blue = np.array([pose[0], pose[1], height, 1]).reshape((4, 1)) d_drop0_red = np.array([pose[0], pose[1], height, 1]).reshape((4, 1)) if (str(color).lower() == 'blue'): T01 = np.array([[-1, 0, 0, 200], [0, -1, 0, 200], [0, 0, 1, 0], [0, 0, 0, 1]]) d_drop1_blue = np.matmul(T01, d_drop0_blue) #drop location in base frame d_drop1_blue = d_drop1_blue[0:3, :] # Angle btw X_base axis and drop location (vector) d_drop1_blue_xy = np.array([d_drop1_blue[0], d_drop1_blue[1], 0]) cos_theta = ((np.array([1, 0, 0]).dot(d_drop1_blue_xy)) / np.linalg.norm(d_drop1_blue_xy))[0] theta = np.arccos(cos_theta) # Update Height and calculate x,y offset based on relative position of the grabbed object wrt the gripper if (len(object_pose)): obj_0 = np.matmul(T01, np.array(object_pose)) Z_obj = obj_0[2, -1] X_obj = obj_0[0, -1] Y_obj = obj_0[1, -1] positions, _ = FK.forward(qstart) Z_e = positions[-1, 2] height += (Z_e - Z_obj) X_offset = positions[-1, 0] - X_obj Y_offset = positions[-1, 1] - Y_obj # Te1: drop off pose ; apply the offset to the desired gripper position for dropping the object at drop point p_i Te1 = np.array( [[np.sin(theta), 0, cos_theta, d_drop1_blue[0, 0] + X_offset], [cos_theta, 0, -np.sin(theta), d_drop1_blue[1, 0] - 3], [0, 1, 0, height], [0, 0, 0, 1]]) # same implemenation as the 'blue' elif (str(color).lower() == 'red'): T01 = np.array([[1, 0, 0, 200], [0, 1, 0, 200], [0, 0, 1, 0], [0, 0, 0, 1]]) d_drop1_red = np.matmul(T01, d_drop0_red) #drop location in base frame d_drop1_red = d_drop1_red[0:3, :] # Angle btw X_base axis and drop location d_drop1_red_xy = np.array([d_drop1_red[0], d_drop1_red[1], 0]) cos_theta = ((np.array([1, 0, 0]).dot(d_drop1_red_xy)) / np.linalg.norm(d_drop1_red_xy))[0] theta = np.arccos(cos_theta) # Update Height if (len(object_pose)): obj_0 = np.matmul(T01, np.array(object_pose)) Z_obj = obj_0[2, -1] X_obj = obj_0[0, -1] Y_obj = obj_0[1, -1] positions, _ = FK.forward(qstart) Z_e = positions[-1, 2] height += (Z_e - Z_obj) X_offset = positions[-1, 0] - X_obj Y_offset = positions[-1, 1] - Y_obj Te1 = np.array( [[np.sin(theta), 0, cos_theta, d_drop1_red[0, 0] + X_offset], [cos_theta, 0, -np.sin(theta), d_drop1_red[1, 0] - 3], [0, 1, 0, height], [0, 0, 0, 1]]) else: print("incorrect color input") return ############################################# # Compute IK for Drop off pose ############################################# print("height") print(height) print("offsets") print(X_offset, Y_offset) IK = calculateIK() q_drop, isPos = IK.inverse(Te1) ############################################# # Plan Path to Drop off pose ############################################# path = [] if (not isPos): print('Not feasible pose') return path # Define intermediate point Tinter1 = deepcopy(Te1) Tinter1[0:3, -1] = np.array([Te1[0, -1] - 30, Te1[1, -1] + 70, height + 70]) q_inter, isPos = IK.inverse(Tinter1) # Add intermediate pose q_inter = np.append(np.ravel(q_inter)[range(5)], 0) q_inter[-2] = -np.pi / 2 path.append(q_inter) # Add drop pose q_drop = np.append(np.ravel(q_drop)[range(5)], 0) q_drop[-2] = -np.pi / 2 path.append(q_drop) # Release and return q_release = deepcopy(q_drop) release_count = 1 while (q_release[-1] < 25): dq2 = [0, 0, 0, 0, 0, 5] dq2[-1] += release_count q_release = q_release + dq2 path.append(q_release) release_count += 1 for i in range(10): q_release[1] -= 0.03 q_release[2] -= 0.01 path.append(q_release) return path
def parametricCircle(t, center, radius, positive): x = center.x + radius*cos(t) y = center.y + radius*sin(t) if positive else center.y - radius*sin(t) return x, y
def psk_symbol(m,M): theta = 2 * np.pi * (m-1) / M s = np.array([np.cos(theta), -np.sin(theta)]) return(s)
def setup(self): self.system = signal.lti(1.0, [1, 0, 1]) self.t = np.arange(0, 100, 0.5) self.u = np.sin(2 * self.t)
except: continue if do_bootstrap: cosmean, coserr = bootstrap(cosamp) sinmean, sinerr = bootstrap(sinamp) else: cosmean = np.mean(cosamp) sinmean = np.mean(sinamp) coserr = np.std(cosamp) / np.sqrt(ngood) sinerr = np.std(sinamp) / np.sqrt(ngood) cosamps[iline] = cosmean sinamps[iline] = sinmean coserrs[iline] = coserr sinerrs[iline] = sinerr ffac = 2 * np.pi * fline * t template += cosmean*np.cos(ffac) + sinmean*np.sin(ffac) iline += 1 ind = np.argsort(linefreq) if col == '': lw = 5 else: lw = 2 plt.subplot(3, 1, 1) plt.errorbar(linefreq[ind], cosamps[ind]*scale, coserrs[ind]*scale, fmt='-o', label=det+col, lw=lw) plt.subplot(3, 1, 2) plt.errorbar(linefreq[ind], sinamps[ind]*scale, sinerrs[ind]*scale, fmt='-o', label=det+col, lw=lw)
def main(input_file, output_file, model_path, weight_path, plot_output, model_output, max_depth, use_distance_prior): input = read_input(input_file) tt_path = os.path.join(os.environ['SINGLESTATION'], 'data', 'bodywave', input['model_name']) if not model_path: model_path = os.path.join(tt_path, '%s.models' % input['model_name']) if not weight_path: weight_path = os.path.join(tt_path, '%s.weights' % input['model_name']) files, weights, models_all, weights_all = read_model_list( model_path, weight_path) tt, dep, dis, tt_P = load_tt(files=files, tt_path=tt_path, phase_list=input['phase_list'], freqs=input['freqs'], backazimuth=input['backazimuth'], idx_ref=input['idx_ref']) # Total sigma is sigma of modelled travel time plus picking uncertainty sigma = np.sqrt(input['sigma_model']**2. + input['sigma']**2. + input['sigma_ref']**2.) # depth prior depth_prior = np.exp(-(dep / max_depth)**2) # distance prior if use_distance_prior: distance_prior = np.sin(np.deg2rad(dis)) else: distance_prior = None # Calculate probability p = calc_p(dep, dis, sigma, tt, input['tt_meas'], weights, depth_prior=depth_prior, distance_prior=distance_prior) if np.max(p, axis=None) < 1E-60: raise ValueError('Travel times are incompatible \n' + ' highest p: %8.2e\n' % np.max(p, axis=None) + ' threshold: %8.2e\n ' % 1e-30) if plot_output: plot(p, dep=dep, dis=dis, depth_prior=depth_prior, distance_prior=distance_prior) plot_phases(tt, p, input['phase_list'], input['freqs'], input['tt_meas'], input['sigma']) plot_models(p, dep=dep, dis=dis, weights=weights, files=files, tt_path=tt_path) write_result(file_out=output_file, model_output=model_output, modelset_name=input['model_name'], p=p, dep=dep, dis=dis, phase_list=input['phase_list'], freqs=input['freqs'], tt_meas=input['tt_meas'], sigma=input['sigma'], baz=input['backazimuth'], tt_P=tt_P, t_ref=input['tt_ref'], weights=weights_all, model_names=models_all)
nodesfile.write("%5d %10e %10e %3d\n" %(counter+1,Lx,i*Ly/(np_right),0)) counter+=1 if i<np_right-1: counter_segment+=1 segmentfile.write("%5d %5d %5d %5d \n" %(counter_segment,counter,counter+1,0)) #------------------------------------------------------------------------------ # object: #------------------------------------------------------------------------------ if experiment==1 or experiment==2: for i in range (0,np_object): angle=2*np.pi/(np_object-1)*i x=xobject+rad*np.cos(angle) y=yobject+rad*np.sin(angle) nodesfile.write("%5d %10e %10e %3d\n" %(counter+1,x,y,0)) counter+=1 if i<np_object-1: counter_segment+=1 segmentfile.write("%5d %5d %5d %5d \n" %(counter_segment,counter,counter+1,0)) if experiment==3: for i in range (0,n_p): x=xobject-size/2+i*size/n_p y=yobject-size/2 nodesfile.write("%5d %10e %10e %3d\n" %(counter+1,x,y,0)) counter+=1 if i<n_p-1: counter_segment+=1
def sind(x): return np.sin(np.deg2rad(x))
def gen_tone(amplitude, tone_duration, frequency): x = np.arange(44100) tone = amplitude * np.sin(2 * np.pi * frequency / 44100 * x) return tone
# Author B. Seignovert # [email protected] # V1.1 - 2016/04/29 # -*- coding: utf-8 -*- import os,sys import numpy as np from fractals import DB, DRAW n = 128 k = 1 r = 10 if len(sys.argv) > 1: n = int(sys.argv[1]) if len(sys.argv) > 2: k = int(sys.argv[2]) if len(sys.argv) > 3: r = int(sys.argv[3]) db = DB('','fractals.db') for rr in range(r): ang = np.radians(rr*360./r) agg = DRAW(n,k) for (x,y,z) in db.get(n,k): agg.add(x*np.cos(ang)-z*np.sin(ang),y,x*np.sin(ang)+z*np.cos(ang)) agg.save(width=750,height=750,zoom=750,fname='Fractal_%i-%i-rot-%.2i' % (n,k,rr))
def __init__(self, xyz=None, channels=None, system='cartesian', unit='degree', title=None, title_color='black', title_size=20., line_color='black', line_width=4., chan_size=12., chan_offset=(0., 0., 0.), chan_mark_color='white', chan_mark_symbol='disc', chan_txt_color='black', bgcolor='white', cbar=True, cb_txt_size=10., margin=.05, parent=None): """Init.""" # ======================== VARIABLES ======================== self._bgcolor = color2vb(bgcolor) scale = 800. # fix GL bugs for small plots pos = np.zeros((1, 3), dtype=np.float32) # Colors : title_color = color2vb(title_color) line_color = color2vb(line_color) chan_txt_color = color2vb(chan_txt_color) self._chan_mark_color = color2vb(chan_mark_color) self._chan_mark_symbol = chan_mark_symbol # Disc interpolation : self._interp = .1 self._pix = 64 csize = int(self._pix / self._interp) if self._interp else self._pix l = csize / 2 # ======================== NODES ======================== # Main topoplot node : self.node = scene.Node(name='Topoplot', parent=parent) self.node.transform = vist.STTransform(scale=[scale] * 3) # Headset + channels : self.node_headfull = scene.Node(name='HeadChan', parent=self.node) # Headset node : self.node_head = scene.Node(name='Headset', parent=self.node_headfull) # Channel node : self.node_chan = scene.Node(name='Channels', parent=self.node_headfull) self.node_chan.transform = vist.STTransform(translate=(0., 0., -10.)) # Cbar node : self.node_cbar = scene.Node(name='Channels', parent=self.node) # Dictionaries : kw_line = {'width': line_width, 'color': line_color, 'parent': self.node_head} # ======================== PARENT VISUALS ======================== # Main disc : self.disc = visuals.Image(pos=pos, name='Disc', parent=self.node_head, interpolation='bilinear') # Title : self.title = visuals.Text(text=title, pos=(0., .6, 0.), name='Title', parent=self.node, font_size=title_size, color=title_color, bold=True) self.title.font_size *= 1.1 # ======================== HEAD / NOSE / EAR ======================== # ------------------ HEAD ------------------ # Head visual : self.head = visuals.Line(pos=pos, name='Head', **kw_line) # Head circle : theta = np.arange(0, 2 * np.pi, 0.001) head = np.full((len(theta), 3), -1., dtype=np.float32) head[:, 0] = l * (1. + np.cos(theta)) head[:, 1] = l * (1. + np.sin(theta)) self.head.set_data(pos=head) # ------------------ NOSE ------------------ # Nose visual : self.nose = visuals.Line(pos=pos, name='Nose', **kw_line) # Nose data : wn, hn = csize * 50. / 512., csize * 30. / 512. nose = np.array([[l - wn, 2 * l - wn, 2.], [l, 2 * l + hn, 2.], [l, 2 * l + hn, 2.], [l + wn, 2 * l - wn, 2.] ]) self.nose.set_data(pos=nose, connect='segments') # ------------------ EAR ------------------ we, he = csize * 10. / 512., csize * 30. / 512. ye = l + he * np.sin(theta) # Ear left data : self.earL = visuals.Line(pos=pos, name='EarLeft', **kw_line) # Ear left visual : ear_l = np.full((len(theta), 3), 3., dtype=np.float32) ear_l[:, 0] = 2 * l + we * np.cos(theta) ear_l[:, 1] = ye self.earL.set_data(pos=ear_l) # Ear right visual : self.earR = visuals.Line(pos=pos, name='EarRight', **kw_line) # Ear right data : ear_r = np.full((len(theta), 3), 3., dtype=np.float32) ear_r[:, 0] = 0. + we * np.cos(theta) ear_r[:, 1] = ye self.earR.set_data(pos=ear_r) # ================== CHANNELS ================== # Channel's markers : self.chanMarkers = visuals.Markers(pos=pos, name='ChanMarkers', parent=self.node_chan) # Channel's text : self.chanText = visuals.Text(pos=pos, name='ChanText', parent=self.node_chan, anchor_x='center', color=chan_txt_color, font_size=chan_size) # ================== CAMERA ================== self.rect = ((-scale / 2) * (1 + margin), (-scale / 2) * (1 + margin), scale * (1. + cbar * .3 + margin), scale * (1.11 + margin)) # ================== CBAR ================== if cbar: self.cbar = CbarVisual(cbtxtsz=1.2 * cb_txt_size, txtsz=cb_txt_size, txtcolor=title_color, cbtxtsh=2., parent=self.node_cbar) self.node_cbar.transform = vist.STTransform(scale=(.6, .4, 1.), translate=(.6, 0., 0.)) # ================== COORDINATES ================== auto = self._get_channel_coordinates(xyz, channels, system, unit) if auto: eucl = np.sqrt(self._xyz[:, 0]**2 + self._xyz[:, 1]**2).max() self.node_head.transform = vpnormalize(head, dist=2 * eucl) # Rescale between (-1:1, -1:1) = circle : circle = vist.STTransform(scale=(.5 / eucl, .5 / eucl, 1.)) self.node_headfull.transform = circle # Text translation : tr = np.array([0., .8, 0.]) + np.array(chan_offset) else: # Get coordinates of references along the x and y-axis : ref_x, ref_y = self._get_ref_coordinates() # Recenter the topoplot : t = vist.ChainTransform() t.prepend(vprecenter(head)) # Rescale (-ref_x:ref_x, -ref_y:ref_y) (ref_x != ref_y => ellipse) coef_x = 2 * ref_x / head[:, 0].max() coef_y = 2 * ref_y / head[:, 1].max() t.prepend(vist.STTransform(scale=(coef_x, coef_y, 1.))) self.node_head.transform = t # Rescale between (-1:1, -1:1) = circle : circle = vist.STTransform(scale=(.5 / ref_x, .5 / ref_y, 1.)) self.node_headfull.transform = circle # Text translation : tr = np.array([0., .04, 0.]) + np.array(chan_offset) self.chanText.transform = vist.STTransform(translate=tr) # ================== GRID INTERPOLATION ================== # Interpolation vectors : x = y = np.arange(0, self._pix, 1) xnew = ynew = np.arange(0, self._pix, self._interp) # Grid interpolation function : def _grid_interpolation(grid): f = interp2d(x, y, grid, kind='linear') return f(xnew, ynew) self._grid_interpolation = _grid_interpolation
pcm = ax[0].pcolor(X, Y, Z1, norm=colors.LogNorm(vmin=Z1.min(), vmax=Z1.max()), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') pcm = ax[1].pcolor(X, Y, Z1, cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') fig.show() ''' PowerNorm: Here a power-law trend in X partially obscures a rectified sine wave in Y. We can remove the power law using a PowerNorm. ''' X, Y = np.mgrid[0:3:complex(0, N), 0:2:complex(0, N)] Z1 = (1 + np.sin(Y * 10.)) * X**(2.) fig, ax = plt.subplots(2, 1) pcm = ax[0].pcolormesh(X, Y, Z1, norm=colors.PowerNorm(gamma=1./2.), cmap='PuBu_r') fig.colorbar(pcm, ax=ax[0], extend='max') pcm = ax[1].pcolormesh(X, Y, Z1, cmap='PuBu_r') fig.colorbar(pcm, ax=ax[1], extend='max') fig.show() ''' SymLogNorm: two humps, one negative and one positive, The positive with 5-times the amplitude. Linearly, you cannot see detail in the negative hump. Here we logarithmically scale the positive and
if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta) ** 2 * np.sin(2 * a_gamma) ** 2 - 0.5 * np.sin(4 * a_beta) * np.sin(4 * a_gamma)) * ( 1 + np.cos(4 * a_gamma) ** 2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot =3962 writefile = open("../data/startQiskit_Class86.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = BasicAer.get_backend('statevector_simulator') circuit1 = transpile(prog, FakeYorktown())
dtype = [("id", int), ("name", object), ('score', int)] np_cources = np.array(cources, dtype=dtype) print np_cources print np_cources['id'] print np_cources['score'] == 150 print np_cources[np_cources['score'] == 150] # 获取分数大于150的数据 print np_cources['id'][::-1] a7 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print np.log(a7) print np.sin(a7) print np.cos(a7) print a7 print np.diff(a7,axis=1) print np.diff(a7,axis=0) print np.std(a7) print np.var(a7,axis=0) r1 = np.random.rand(3, 4) r2 = np.random.rand(4, 3) print r1 print r2
def plotMixvMises1X2(res_vonMF, im_path, n_X): """ To plot the fitted mixture of von Mises distributions Parameters: ----------- res_vonMF : array-like, shape=(n_clust,4), the results stored im_path : string, the name of the image file n_X : the normalized intensity Output: ----------- fig_name : an image .png file """ from PIL import Image, ImageDraw #import os.path img_0 = Image.open(im_path) draw_0 = ImageDraw.Draw(img_0) temp_path, im_name = os.path.split(im_path) im_name_0 = os.path.splitext(im_name)[0] draw_0.text((-1, 0), text=im_name, fill=100) im_cen = img_0.size pYmax = im_cen[1] #cen_x = int(min(im_cen)/2) #cen_y = int(max(im_cen)/2) cen_x = int(im_cen[0] / 2) cen_y = int(im_cen[1] / 2) angles = n_X[:, 0] nvalls = n_X[:, 1] xlim_min = min(angles) xlim_max = max(angles) rlim_min = np.radians(xlim_min) rlim_max = np.radians(xlim_max) n_clus = len(res_vonMF) # plot the distributions: # x = np.linspace(-np.pi/2, np.pi/2, num=100) x = np.linspace(rlim_min, rlim_max, num=100) xdegs = np.degrees(x) fX_tot = np.zeros(len(x), ) fig, axes = plt.subplots(1, 3, figsize=(12, 6)) #axes[2].imshow(np.asarray(img_0), cmap='gray'); for i in range(n_clus): temp_r = res_vonMF[i, 0] # location in rads temp_d = np.round(res_vonMF[i, 1], decimals=2) # location in degrees temp_c = res_vonMF[i, 2] # concentration temp_w = res_vonMF[i, 3] # weights str_1 = 'von Mises for X_' + str(i + 1) fX_i = stats.vonmises(temp_c, temp_r) #fX_i = stats.vonmises(res_vonMF[i,2], res_vonMF[i,0]) axes[0].plot(xdegs, fX_i.pdf(x), label=str_1) # str_2 = 'weighted von Mises for X_' + str(i+1) str_2 = 'von Mises X_' + str(i + 1) axes[1].plot(xdegs, temp_w * fX_i.pdf(x), '--', label=str_2) # sum individual distributions weighted to get total mixture von Mises: fX_tot += temp_w * fX_i.pdf(x) # annotate as text the locations of the individual von Mises: axes[1].annotate( temp_d, xy=(temp_d, temp_w*fX_i.pdf(temp_r)), \ xytext=(temp_d, temp_w*fX_i.pdf(temp_r)), \ arrowprops=dict(facecolor='black', shrink=0.5), ) #tmpThe = temp_r - np.pi/2 start_x = cen_x * (1 - np.cos(temp_r)) start_y = cen_y * (1 - np.sin(temp_r)) start_y = pYmax - start_y end_x = cen_x * (1 + np.cos(temp_r)) end_y = cen_y * (1 + np.sin(temp_r)) end_y = pYmax - end_y draw_0.line([(start_x, start_y), (end_x, end_y)], fill=i + 1 + i * 50, width=2) axes[2].annotate( temp_d, xy=(end_x,end_y), xytext=(end_x,end_y), \ color='g') axes[1].plot(xdegs, fX_tot, 'r', label="combined von Mises") axes[1].plot(angles, nvalls, 'k--', label="normalized data") axes[1].set_title(im_name) axes[1].set_xlabel('degrees') axes[1].set_ylabel('pdf') # axes[1].legend(loc=1) # axes[1].legend(loc=9, bbox_to_anchor=(0.5, -0.1), ncol=3) axes[1].legend(bbox_to_anchor=(0.75, 0.99), loc=2, borderaxespad=0., ncol=2) axes[0].legend() axes[2].imshow(np.asarray(img_0), cmap='gray') # create a name for the output image file: #fig_name = 'Res_' + im_name.replace(".png","") + '_' + str(n_clus) + 'vM' fig_name = 'Res_' + im_name_0 + '_' + str(n_clus) + 'vM' + '_fit' fig_name_path = temp_path + '/' + fig_name # save the .png and .eps files: fig.savefig(fig_name_path + '.png') fig.savefig(fig_name_path + '.eps') return
def calculate_vector_components(self): """Calculate components of incident fields.""" self.theta = np.deg2rad(self.theta) self.phi = np.deg2rad(self.phi) self.psi = np.deg2rad(self.psi) # Components of incident unit wavevector self.kx = np.sin(self.theta) * np.cos(self.phi) self.ky = np.sin(self.theta) * np.sin(self.phi) self.kz = np.cos(self.theta) # Components of incident field vectors self.Exinc = np.cos(self.psi) * np.sin(self.phi) - np.sin(self.psi) * np.cos(self.theta) * np.cos(self.phi) self.Eyinc = -np.cos(self.psi) * np.cos(self.phi) - np.sin(self.psi) * np.cos(self.theta) * np.sin(self.phi) self.Ezinc = np.sin(self.psi) * np.sin(self.theta) self.Hxinc = np.sin(self.psi) * np.sin(self.phi) + np.cos(self.psi) * np.cos(self.theta) * np.cos(self.phi) self.Hyinc = -np.sin(self.psi) * np.cos(self.phi) + np.cos(self.psi) * np.cos(self.theta) * np.sin(self.phi) self.Hzinc = -np.cos(self.psi) * np.sin(self.theta)
def drawRing(radius, number2, spot): #two images being created, the first will contain full spots, the second the corresponding centroids #the shape can be changed as desired blankImage = np.zeros(shape=(120,120), dtype=np.float32) blankImageCentroid = np.zeros(shape=(120,120), dtype=np.float32) #centre of image is determined (xCen, yCen) = getCentrePixel(blankImage) #this will place spots on image for i in range(spot): #some blurring introduced according to Gaussian distribution centered at radius with 1.5 pixel spread blurring = np.random.normal(radius, 1.5) ringRadius = blurring #setting up while loop which picks sin angles at random and checks if they are valid, once valid angle picked, loop is broken keepLoop = True while keepLoop: number = random.uniform(0, 1) sinAngle = (number*np.pi) if validAngle(number): keepLoop = False #phi angle picked randomly phiAngle = (random.uniform(0,1)*2*np.pi) #the x and y positions are calculated xPos = ringRadius * np.cos(sinAngle) yPos = ringRadius * np.sin(sinAngle) * np.cos(phiAngle) #shifted by the centre position xPos += xCen yPos += yCen #this picks a file out of the folderSpots based on a random number (range must be number of files in folder and #it is assumed that files are named according to convention (see line 9-10)), it will check that the file exists as well findFile = True while findFile: filenamePosition = random.randint(0, 5193) if os.path.exists(""): img = cv.imread("", 0) imgCentroid = cv.imread("", 0) findFile = False #the commented out lines do the same as the 7 lines above, without the need for picking a random number, however work significantly #slower, so if folderSpots contains a lot of files, the method above is much faster """ filename = random.choice(os.listdir(folderSpots)) img = cv.imread(folderSpots + "/" + filename, 0) imgCentroid = cv.imread(folderCentroids + "/centroid" + filename, 0) """ #failsafe for testing type of image if type(img) == np.ndarray: rows, cols = img.shape #scanning across image for m in range(rows): for k in range(cols): #finding centroid in the centroid image and shifting positions so that centroid will be placed in that pixel, #while the rest of the spot intensity is shifted accordingly if imgCentroid[m, k] != 0: (y, x) = (m, k) yPos -= y xPos -= x #placing spot and centroid into their respective positions, note that intensity will cap at 255 for image containing full spots for j in range(rows): for f in range(cols): blankImage[int(yPos+j),int(xPos+f)] += img[j,f] if imgCentroid[j,f] != 0: blankImageCentroid[int(yPos+j),int(xPos+f)] = 255 #saves images to the respective folder, the folderCreatedImages also should contain folders with number of spots, followed by folders named #Image and centroidImage cv.imwrite("", blankImage) cv.imwrite("", blankImageCentroid)
if __name__ == '__main__': n = 4 V = np.arange(0, n, 1) E = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0), (3, 2, 1.0), (3, 1, 1.0)] G = nx.Graph() G.add_nodes_from(V) G.add_weighted_edges_from(E) step_size = 0.1 a_gamma = np.arange(0, np.pi, step_size) a_beta = np.arange(0, np.pi, step_size) a_gamma, a_beta = np.meshgrid(a_gamma, a_beta) F1 = 3 - (np.sin(2 * a_beta)**2 * np.sin(2 * a_gamma)**2 - 0.5 * np.sin( 4 * a_beta) * np.sin(4 * a_gamma)) * (1 + np.cos(4 * a_gamma)**2) result = np.where(F1 == np.amax(F1)) a = list(zip(result[0], result[1]))[0] gamma = a[0] * step_size beta = a[1] * step_size prog = make_circuit(4) sample_shot = 5600 writefile = open("../data/startQiskit_Class621.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) backend = BasicAer.get_backend('statevector_simulator') circuit1 = transpile(prog, FakeYorktown())
def test_structural(): # Clear warnings structural.__warningregistry__ = {} np.random.seed(38947) nobs = 100 eps = np.random.normal(size=nobs) exog = np.random.normal(size=nobs) eps1 = np.zeros(nobs) eps2 = np.zeros(nobs) eps2[49] = 1 eps3 = np.zeros(nobs) eps3[50:] = 1 # AR(1) mod1 = structural.UnobservedComponents([0], autoregressive=1) mod2 = sarimax.SARIMAX([0], order=(1, 0, 0)) actual = mod1.simulate([1, 0.5], nobs, state_shocks=eps, initial_state=np.zeros(mod1.k_states)) desired = mod2.simulate([0.5, 1], nobs, state_shocks=eps, initial_state=np.zeros(mod2.k_states)) assert_allclose(actual, desired) # ARX(1) mod1 = structural.UnobservedComponents(np.zeros(nobs), exog=exog, autoregressive=1) mod2 = sarimax.SARIMAX(np.zeros(nobs), exog=exog, order=(1, 0, 0)) actual = mod1.simulate([1, 0.5, 0.2], nobs, state_shocks=eps, initial_state=np.zeros(mod2.k_states)) desired = mod2.simulate([0.2, 0.5, 1], nobs, state_shocks=eps, initial_state=np.zeros(mod2.k_states)) assert_allclose(actual, desired) # Irregular mod = structural.UnobservedComponents([0], 'irregular') actual = mod.simulate([1.], nobs, measurement_shocks=eps, initial_state=np.zeros(mod.k_states)) assert_allclose(actual, eps) # Fixed intercept # (in practice this is a deterministic constant, because an irregular # component must be added) with warnings.catch_warnings(): warnings.simplefilter("ignore") mod = structural.UnobservedComponents([0], 'fixed intercept') actual = mod.simulate([1.], nobs, measurement_shocks=eps, initial_state=[10]) assert_allclose(actual, 10 + eps) # Deterministic constant mod = structural.UnobservedComponents([0], 'deterministic constant') actual = mod.simulate([1.], nobs, measurement_shocks=eps, initial_state=[10]) assert_allclose(actual, 10 + eps) # Local level mod = structural.UnobservedComponents([0], 'local level') actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=np.zeros(mod.k_states)) assert_allclose(actual, eps + eps3) # Random walk mod = structural.UnobservedComponents([0], 'random walk') actual = mod.simulate([1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=np.zeros(mod.k_states)) assert_allclose(actual, eps + eps3) # Fixed slope # (in practice this is a deterministic trend, because an irregular # component must be added) with warnings.catch_warnings(): warnings.simplefilter("ignore") mod = structural.UnobservedComponents([0], 'fixed slope') actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=[0, 1]) assert_allclose(actual, eps + np.arange(100)) # Deterministic trend mod = structural.UnobservedComponents([0], 'deterministic trend') actual = mod.simulate([1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=[0, 1]) assert_allclose(actual, eps + np.arange(100)) # Local linear deterministic trend mod = structural.UnobservedComponents( [0], 'local linear deterministic trend') actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=[0, 1]) desired = eps + np.r_[np.arange(50), 1 + np.arange(50, 100)] assert_allclose(actual, desired) # Random walk with drift mod = structural.UnobservedComponents([0], 'random walk with drift') actual = mod.simulate([1.], nobs, state_shocks=eps2, initial_state=[0, 1]) desired = np.r_[np.arange(50), 1 + np.arange(50, 100)] assert_allclose(actual, desired) # Local linear trend mod = structural.UnobservedComponents([0], 'local linear trend') actual = mod.simulate([1., 1., 1.], nobs, measurement_shocks=eps, state_shocks=np.c_[eps2, eps1], initial_state=[0, 1]) desired = eps + np.r_[np.arange(50), 1 + np.arange(50, 100)] assert_allclose(actual, desired) actual = mod.simulate([1., 1., 1.], nobs, measurement_shocks=eps, state_shocks=np.c_[eps1, eps2], initial_state=[0, 1]) desired = eps + np.r_[np.arange(50), np.arange(50, 150, 2)] assert_allclose(actual, desired) # Smooth trend mod = structural.UnobservedComponents([0], 'smooth trend') actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps1, initial_state=[0, 1]) desired = eps + np.r_[np.arange(100)] assert_allclose(actual, desired) actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=[0, 1]) desired = eps + np.r_[np.arange(50), np.arange(50, 150, 2)] assert_allclose(actual, desired) # Random trend mod = structural.UnobservedComponents([0], 'random trend') actual = mod.simulate([1., 1.], nobs, state_shocks=eps1, initial_state=[0, 1]) desired = np.r_[np.arange(100)] assert_allclose(actual, desired) actual = mod.simulate([1., 1.], nobs, state_shocks=eps2, initial_state=[0, 1]) desired = np.r_[np.arange(50), np.arange(50, 150, 2)] assert_allclose(actual, desired) # Seasonal (deterministic) mod = structural.UnobservedComponents([0], 'irregular', seasonal=2, stochastic_seasonal=False) actual = mod.simulate([1.], nobs, measurement_shocks=eps, initial_state=[10]) desired = eps + np.tile([10, -10], 50) assert_allclose(actual, desired) # Seasonal (stochastic) mod = structural.UnobservedComponents([0], 'irregular', seasonal=2) actual = mod.simulate([1., 1.], nobs, measurement_shocks=eps, state_shocks=eps2, initial_state=[10]) desired = eps + np.r_[np.tile([10, -10], 25), np.tile([11, -11], 25)] assert_allclose(actual, desired) # Cycle (deterministic) mod = structural.UnobservedComponents([0], 'irregular', cycle=True) actual = mod.simulate([1., 1.2], nobs, measurement_shocks=eps, initial_state=[1, 0]) x1 = [np.cos(1.2), np.sin(1.2)] x2 = [-np.sin(1.2), np.cos(1.2)] T = np.array([x1, x2]) desired = eps states = [1, 0] for i in range(nobs): desired[i] += states[0] states = np.dot(T, states) assert_allclose(actual, desired) # Cycle (stochastic) mod = structural.UnobservedComponents([0], 'irregular', cycle=True, stochastic_cycle=True) actual = mod.simulate([1., 1., 1.2], nobs, measurement_shocks=eps, state_shocks=np.c_[eps2, eps2], initial_state=[1, 0]) x1 = [np.cos(1.2), np.sin(1.2)] x2 = [-np.sin(1.2), np.cos(1.2)] T = np.array([x1, x2]) desired = eps states = [1, 0] for i in range(nobs): desired[i] += states[0] states = np.dot(T, states) + eps2[i] assert_allclose(actual, desired)
def target_func(self, x): return np.sin(5 * x)
def pos_estimate(): global x_old,acc,omega,P_old,m9a_low_old,m9g_low_old,x_new start =time.time() s_phi = np.sin(x_old[6]) c_phi = np.cos(x_old[6]) s_the = np.sin(x_old[7]) c_the = np.cos(x_old[7]) t_the = np.tan(x_old[7]) s_psi = np.sin(x_old[8]) c_psi = np.cos(x_old[8]) x_pre = np.array([[x_old[0]+x_old[3]*del_t], [x_old[1]+x_old[4]*del_t], [x_old[2]+x_old[5]*del_t], [x_old[3]+c_the*c_psi*acc[0]*del_t+(s_the*c_psi*s_phi-s_psi*c_phi)*acc[1]*del_t+(s_the*c_psi*c_phi+s_psi*s_phi)*acc[2]*del_t], [x_old[4]+c_the*s_psi*acc[0]*del_t+(s_the*s_psi*s_phi+c_psi*c_phi)*acc[1]*del_t+(s_the*s_psi*c_phi-c_psi*s_phi)*acc[2]*del_t], [x_old[5]-s_the*acc[0]*del_t+c_the*s_phi*acc[1]*del_t+c_the*c_phi*acc[2]*del_t+g*del_t], [x_old[6] + omega[0]*del_t+s_phi*t_the*omega[1]*del_t + c_phi*t_the*omega[2]*del_t], [x_old[7] + c_phi*omega[1]*del_t - s_phi*omega[2]*del_t], [x_old[8] + s_phi/c_the*omega[1]*del_t + c_phi/c_the*omega[2]*del_t] ],dtype=np.float) #print x_old[3]+c_the*c_psi*acc[0]*del_t+(s_the*c_psi*s_phi-s_psi*c_phi)*acc[1]*del_t+(s_the*c_psi*c_phi+s_psi*s_phi)*acc[2]*del_t ######################################################################################## AA = np.array([[1,0,0,del_t,0,0,0,0,0], [0,1,0,0,del_t,0,0,0,0], [0,0,1,0,0,del_t,0,0,0], [0,0,0,1,0,0, (s_the*c_psi*c_phi+s_psi*s_phi)*acc[1]*del_t + (-s_the*c_psi*s_phi+s_psi*c_phi)*acc[2]*del_t, -s_the*c_psi*acc[0]*del_t + c_the*c_psi*s_phi*acc[1]*del_t + c_the*c_psi*c_phi*acc[2]*del_t, -c_the*s_psi*acc[0]*del_t + (-s_the*s_psi*s_phi-c_psi*c_phi)*acc[1]*del_t + (-s_the*s_psi*c_phi+c_psi*s_phi)*acc[2]*del_t], [0,0,0,0,1,0, (s_the*s_psi*c_phi-c_psi*s_phi)*acc[1]*del_t + (-s_the*s_psi*s_phi-c_psi*c_phi)*acc[2]*del_t, -s_the*s_psi*acc[0]*del_t + c_the*s_psi*s_phi*acc[1]*del_t + c_the*s_psi*s_phi*acc[2]*del_t, c_the*c_psi*acc[0]*del_t + (s_the*s_psi*s_phi-s_psi*c_phi)*acc[1]*del_t + (s_the*c_psi*c_phi+s_psi*s_phi)*acc[2]*del_t], [0,0,0,0,0,1, c_the*c_phi*acc[1]*del_t - c_the*s_phi*acc[2]*del_t, -c_the*acc[0]*del_t - s_the*s_phi*acc[1] - s_the*c_phi*acc[2]*del_t,0], [0,0,0,0,0,0, 1+c_phi*t_the*omega[1]*del_t-s_phi*t_the*omega[2]*del_t, s_phi/(c_the*c_the)*omega[1]*del_t+c_phi/(c_the*c_the)*omega[2]*del_t,0], [0,0,0,0,0,0, -s_phi*omega[1]*del_t-c_phi*omega[2]*del_t,1,0], [0,0,0,0,0,0, c_phi/c_the*omega[1]*del_t-s_phi/c_the*omega[2]*del_t, s_phi*t_the/c_the*omega[1]*del_t+c_phi*t_the/c_the*omega[2]*del_t,0] ],dtype=np.float) s_phi_pre = np.sin(x_pre[6]) c_phi_pre = np.cos(x_pre[6]) s_the_pre = np.sin(x_pre[7]) c_the_pre = np.cos(x_pre[7]) AA1 = np.sqrt(pow(x_pre[:,0][0]-anchor1[0] ,2) + pow(x_pre[:,0][1]-anchor1[1] ,2) + pow(x_pre[:,0][2]-anchor1[2] ,2)) AA2 = np.sqrt(pow(x_pre[:,0][0]-anchor2[0] ,2) + pow(x_pre[:,0][1]-anchor2[1] ,2) + pow(x_pre[:,0][2]-anchor2[2] ,2)) AA3 = np.sqrt(pow(x_pre[:,0][0]-anchor3[0] ,2) + pow(x_pre[:,0][1]-anchor3[1] ,2) + pow(x_pre[:,0][2]-anchor3[2] ,2)) AA4 = np.sqrt(pow(x_pre[:,0][0]-anchor4[0] ,2) + pow(x_pre[:,0][1]-anchor4[1] ,2) + pow(x_pre[:,0][2]-anchor4[2] ,2)) CC = np.array([[0,0,0,0,0,0,0,c_the_pre*g,0], [0,0,0,0,0,0,-c_the_pre*c_phi_pre*g,s_the_pre*s_phi_pre*g,0], [0,0,0,0,0,0, c_the_pre*s_phi_pre*g,s_the_pre*c_phi_pre*g,0], [(x_pre[:,0][0]-anchor1[0])/AA1, (x_pre[:,0][1]-anchor1[1])/AA1, (x_pre[:,0][2]-anchor1[2])/AA1, 0,0,0,0,0,0], [(x_pre[:,0][0]-anchor2[0])/AA2, (x_pre[:,0][1]-anchor2[1])/AA2, (x_pre[:,0][2]-anchor2[2])/AA2, 0,0,0,0,0,0], [(x_pre[:,0][0]-anchor3[0])/AA3, (x_pre[:,0][1]-anchor3[1])/AA3, (x_pre[:,0][2]-anchor3[2])/AA3, 0,0,0,0,0,0], [(x_pre[:,0][0]-anchor4[0])/AA4, (x_pre[:,0][1]-anchor4[1])/AA4, (x_pre[:,0][2]-anchor4[2])/AA4, 0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0] ],dtype=np.float) ######################################################################################### P_pre = AA.dot(P_old.dot(AA.T)) + QQ G1 = la.inv(CC.dot(P_pre.dot(CC.T)) + RR) GG = P_pre.dot((CC.T).dot(G1)) ######################################################################################### h_pre = np.array([[s_the_pre*g], [-c_the_pre*s_phi_pre*g], [-c_the_pre*c_phi_pre*g], [np.sqrt(pow(x_pre[:,0][0]-anchor1[0] ,2) + pow(x_pre[:,0][1]-anchor1[1] ,2) + pow(x_pre[:,0][2]-anchor1[2] ,2))], [np.sqrt(pow(x_pre[:,0][0]-anchor2[0] ,2) + pow(x_pre[:,0][1]-anchor2[1] ,2) + pow(x_pre[:,0][2]-anchor2[2] ,2))], [np.sqrt(pow(x_pre[:,0][0]-anchor3[0] ,2) + pow(x_pre[:,0][1]-anchor3[1] ,2) + pow(x_pre[:,0][2]-anchor3[2] ,2))], [np.sqrt(pow(x_pre[:,0][0]-anchor4[0] ,2) + pow(x_pre[:,0][1]-anchor4[1] ,2) + pow(x_pre[:,0][2]-anchor4[2] ,2))], [x_pre[:,0][2]] ], dtype=np.float) m9a, m9g, m9m = imu.getMotion9() #measure m9a_low = m9a_low_old * alfa + m9a * (1-alfa) m9g_low = m9g_low_old * alfa + m9g * (1-alfa) #print h_pre[5] m9a_low_old = m9a_low m9g_low_old = m9g_low acc = np.array([-m9a_low[0],-m9a_low[1],-m9a_low[2]]) #results[5] = adc.read(5) #measure omega = np.array([(m9g[0]-bias_gyro_x),(m9g[1]-bias_gyro_y),m9g[2]-bias_gyro_z]) DD[3]= DD[3].strip('\r\n') if (int(DD[0]) < 2000 and int(DD[1]) < 2000 and int(DD[2]) < 2000 and int(DD[3]) < 2000): dd1 = int(DD[0])*0.01 dd2 = int(DD[1])*0.01 dd3 = int(DD[2])*0.01 dd4 = int(DD[3])*0.01 height = float(hh*0.001) yy = np.array([[-m9a_low[0]], [-m9a_low[1]], [-m9a_low[2]], [dd1], [dd2], [dd3], [dd4], [height] ],dtype=np.float) P_new = (I_9-GG.dot(CC)).dot(P_pre) x_new = x_pre + GG.dot(yy-h_pre) #SS=GG.dot(yy-h_pre) #print dd1,dd2,dd3 # phi = np.arctan(-m9a[1]/m9a[2])*180/np.pi print "{:+7.3f}".format(x_new[:,0][0]),",","{:+7.3f}".format(x_new[:,0][1]),",","{:+7.3f}".format(x_new[:,0][2]) # print "{:+7.3f}".format(x_new[:,0][3]),",","{:+7.3f}".format(x_new[:,0][4]) # print "{:+7.3f}".format(x_new[:,0][8]*180/np.pi)#,",","{:+7.3f}".format(x_new[:,0][7]*180/np.pi),",","{:+7.3f}".format(x_new[:,0][6]*180/np.pi)#,",","{:+7.3f}".format(dd1),",","{:+7.3f}".format(dd2),",","{:+7.3f}".format(dd3) # print "{:+7.3f}".format(m9a[0]),",","{:+7.3f}".format(m9a[1]),",","{:+7.3f}".format(m9a[2]) #print(x_new[:,0][6]*180/np.pi,x_new[:,0][7]*180/np.pi) elapsed_time = time.time() - start #print(x_new[:,0][6]*180/np.pi,x_new[:,0][7]*180/np.pi,x_new[:,0][8]*180/np.pi) #print(elapsed_time) # sleep_time = 0.01 - elapsed_time # time.sleep(sleep_time) if elapsed_time < 0.01: sleep_time = 0.01 - elapsed_time time.sleep(sleep_time) P_old = P_new#[:,0] x_old = x_new[:,0] return x_new[:,0][0],x_new[:,0][1],x_new[:,0][2],x_new[:,0][6],x_new[:,0][7],x_new[:,0][8]
def fixed_objective_function(x): target = np.sin(x * 50) t_max = np.max(target) t_min = np.min(target) return (target - t_min) / (t_max - t_min)
def radial_samples_reacting(case_path): # this one has to be correct and is different for inert and reacting try: scalarTail = '_f_BilgerMean_f_BilgerPrime2Mean_TMean_TPrime2Mean_CH4Mean_CH4Prime2Mean_H2OMean_H2OPrime2Mean_CO2Mean_CO2Prime2Mean_O2Mean_O2Prime2Mean_COMean_COPrime2Mean_H2Mean_H2Prime2Mean.xy' except: scalarTail = '_f_BilgerMean_f_BilgerPrime2Mean_TMean_TPrime2Mean_CH4Mean_' \ 'CH4Prime2Mean_H2OMean_H2OPrime2Mean_CO2Mean_CO2Prime2Mean_O2Mean_O2Prime2Mean_COMean_COPrime2Mean_H2Mean_H2Prime2Mean.xy' print('NO DIFFUSIVE FLUXES ARE PRESENT!') print(scalarTail + '\n') # initialize arrays datapoints = 200 noFiles = 40 # represents the different locations you defined in the sample dict file nLocation = [0, 1, 2, 3, 4] location_dict = ['01', '03', '05', '10', '20'] # get all time steps times = listdir(case_path + '/postProcessing/sampleDict/') # remove the .txt files in the times list as they are also stored in the sampleDict folder times = [f for f in times if f[-3:] != 'txt'] # loop over the time steps for averaging for n in range(0, len(nLocation)): arrayT = np.zeros((datapoints)) arrayTRMS = np.zeros((datapoints)) arrayCH4 = np.zeros((datapoints)) arrayCH4RMS = np.zeros((datapoints)) arrayCO = np.zeros((datapoints)) arrayCORMS = np.zeros((datapoints)) arrayCO2 = np.zeros((datapoints)) arrayCO2RMS = np.zeros((datapoints)) arrayH2O = np.zeros((datapoints)) arrayH2ORMS = np.zeros((datapoints)) arrayH2 = np.zeros((datapoints)) arrayH2RMS = np.zeros((datapoints)) arrayO2 = np.zeros((datapoints)) arrayO2RMS = np.zeros((datapoints)) arrayf = np.zeros((datapoints)) arrayfRMS = np.zeros((datapoints)) arrayU = np.zeros((datapoints)) arrayURMS = np.zeros((datapoints)) arrayV = np.zeros((datapoints)) arrayVRMS = np.zeros((datapoints)) arrayW = np.zeros((datapoints)) arrayWRMS = np.zeros((datapoints)) arrayJ_r_sgs = np.zeros((datapoints)) arrayJ_r_lam = np.zeros((datapoints)) arrayJsgs_r = np.zeros((datapoints)) arrayJlam_r = np.zeros((datapoints)) arrayVol = np.zeros((datapoints)) # Koordinate Position #arrayYPos = np.zeros((datapoints)) #arrayZPos = np.zeros((datapoints)) #arrayDist = np.zeros((datapoints)) for time in times: for j in range(0, noFiles): try: dataScalar = np.loadtxt(case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + scalarTail) except: print( 'Check the file name and/or path of scalar fields! Something is wrong' ) print(case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + scalarTail) # there is the position of the T column in your data set; # check for consistency! they are summed up for different j arrayf += dataScalar[:, 3] arrayfRMS += np.sqrt(dataScalar[:, 4]) arrayT += dataScalar[:, 5] arrayTRMS += np.sqrt(dataScalar[:, 6]) arrayCH4 += dataScalar[:, 7] arrayCH4RMS += np.sqrt(dataScalar[:, 8]) arrayH2O += dataScalar[:, 9] arrayH2ORMS += np.sqrt(dataScalar[:, 10]) arrayCO2 += dataScalar[:, 11] arrayCO2RMS += np.sqrt(dataScalar[:, 12]) arrayO2 += dataScalar[:, 13] arrayO2RMS += np.sqrt(dataScalar[:, 14]) arrayCO += dataScalar[:, 15] arrayCORMS += np.sqrt(dataScalar[:, 16]) arrayH2 += dataScalar[:, 17] arrayH2RMS += np.sqrt(dataScalar[:, 18]) # compute the radius only once at the beginning if j == 0 and time == times[0]: arrayYPos = dataScalar[:, 1] # m arrayZPos = dataScalar[:, 2] # m arrayDist = np.sqrt(arrayYPos * arrayYPos + arrayZPos * arrayZPos) #READ IN U ONLY IF PRESENT try: dataU = np.loadtxt(case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + '_UMean.xy') winkel = 2 * j / noFiles * 3.14 arrayU += dataU[:, 3] arrayV += np.sin(winkel) * dataU[:, 4] + np.cos( winkel) * dataU[:, 5] arrayW += np.cos(winkel) * dataU[:, 4] + np.sin( winkel) * dataU[:, 5] except: print('Check the file name of U! Something is wrong') # RMS try: try: dataURMS = np.loadtxt(case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + '_UPrime2Mean.xy') except: dataURMS = np.loadtxt( case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + '_UPrime2Mean_J_sgsPrime2Mean_J_lamPrime2Mean.xy') except: print('Check the file name of U! Something is wrong') winkel = 2 * j / noFiles * 3.14 arrayURMS += np.sqrt(dataURMS[:, 3]) arrayVRMS += np.sqrt( np.sin(winkel) * dataURMS[:, 4] + np.cos(winkel) * dataURMS[:, 5]) arrayWRMS += np.sqrt( np.cos(winkel) * dataURMS[:, 4] + np.sin(winkel) * dataURMS[:, 5]) # IN CASE THE MEAN SCALAR FLUXES ARE PRESENT try: dataJ = np.loadtxt(case_path + '/postProcessing/sampleDict/' + time + '/line_x' + str(nLocation[n]) + '-r' + str(j) + '_UMean_J_sgsMean_J_lamMean.xy') winkel = 2 * j / noFiles * 3.14 # get the U data again, just in case dataU was not read in arrayU += dataJ[:, 3] arrayV += np.sin(winkel) * dataJ[:, 4] + np.cos( winkel) * dataJ[:, 5] arrayW += np.cos(winkel) * dataJ[:, 4] + np.sin( winkel) * dataJ[:, 5] #arrayJ_sgs += dataJ[:,6] arrayJsgs_r += np.sqrt((np.sin(winkel) * dataJ[:, 7] + np.cos(winkel) * dataJ[:, 8])**2 + (np.cos(winkel) * dataJ[:, 7] + np.sin(winkel) * dataJ[:, 8])**2) arrayJlam_r += np.sqrt((np.sin(winkel) * dataJ[:, 10] + np.cos(winkel) * dataJ[:, 11])**2 + (np.cos(winkel) * dataJ[:, 10] + np.sin(winkel) * dataJ[:, 11])**2) except: print('NO J_SGS_MEAN AVAILABLE!') ## READ IN THE CELL VOLUME IF PRESENT # try: # dataScalar = np.loadtxt(case_path+'/postProcessing/sampleDict/' + time + '/line_x' + # str(nLocation[n]) + '-r' + str(j) + '_cellVolumes.xy') # # # there is the position of the T column in your data set; check for consistency! they are summed up for different j # arrayVol += dataScalar[:, 3] # # except: # print('NO CELL VOLUME INFORMATION!') # loop 2 end # set up to write the output file! Output_np = np.array( (arrayDist, arrayf, arrayT, arrayCH4, arrayH2O, arrayCO2, arrayO2, arrayCO, arrayH2, arrayU, arrayV, arrayW, arrayfRMS, arrayTRMS, arrayCH4RMS, arrayH2ORMS, arrayCO2RMS, arrayO2RMS, arrayCORMS, arrayH2RMS, arrayURMS, arrayVRMS, arrayWRMS, arrayJsgs_r, arrayJlam_r, arrayVol)) # Divide by the number of files and times and transpose Output_T = Output_np.T Output_T = Output_T / (noFiles * len(times)) # set up dataframe to write as CSV Output_df = pd.DataFrame(Output_T) # Name correctly the output columns Output_df.columns = [ 'r_in_m', 'Z_mean', 'T_mean', 'CH4_mean', 'H2O_mean', 'CO2_mean', 'O2_mean', 'CO_mean', 'H2_mean', 'U_axial_mean', 'U_radial_mean', 'U_teta_mean', 'Z_rms', 'T_rms', 'CH4_rms', 'H2O_rms', 'CO2_rms', 'O2_rms', 'CO_rms', 'H2_rms', 'U_axial_rms', 'U_radial_rms', 'U_teta_rms', 'J_sgs_mean', 'J_lam_mean', 'cellVolume_mean' ] Output_df['r_in_m'] = arrayDist # remove the nan Output_df = Output_df.fillna(0) # write one output file for each position output_name = case_path + '/postProcessing/sampleDict/' + 'line_xD' + location_dict[ n] + '_OxyFuel.txt' pd.DataFrame.to_csv(Output_df, output_name, index=False, sep='\t')
def volume(t): theta = t * omega + IVC * np.pi / 180 #theta in radian; TDC corresponds to theta=0 v = V_min * (1 + ((r_c - 1) / 2) * (L / a + 1 - np.cos(theta) - np.sqrt(pow(L / a, 2) - pow(np.sin(theta), 2)))) return v
def rotate_coords(v, w, theta): v, w = np.asarray(v), np.asarray(w) return v * np.cos(theta) - w * np.sin(theta), v * np.sin(theta) + w * np.cos(theta)
import numpy as np import pylab import cv2 x1 = np.linspace(0, np.pi * 2.0, 60.0) y1 = x1.copy() x2 = x1 - np.pi / 4.0 y2 = x2.copy() xy1 = np.meshgrid(x1, y1)[0] xy2 = np.meshgrid(x2, y2)[0] img1 = np.sin(xy1) + np.sin(xy1).T + np.random.normal(0, 0.5, xy1.shape) img2 = np.sin(xy2) + np.sin(xy2).T + np.random.normal(0, 0.5, xy2.shape) shift = lambda x: np.fft.fftshift(x) ishift = lambda x: np.fft.ifftshift(x) imgf1 = shift(cv2.dft(img1 - img1.mean(), flags=cv2.DFT_COMPLEX_OUTPUT)) imgf2 = shift(cv2.dft(img2 - img2.mean(), flags=cv2.DFT_COMPLEX_OUTPUT)) imgfi1 = cv2.idft(ishift(imgf1), flags=cv2.DFT_COMPLEX_OUTPUT) imgfi2 = cv2.idft(ishift(imgf2), flags=cv2.DFT_COMPLEX_OUTPUT) pylab.figure(figsize=(16, 6)) pylab.subplot(1, 3, 1) pylab.pcolormesh(img1) pylab.axis('equal') pylab.colorbar()
def vel(t): #Note - the only input to the passed through function is time theta = t * omega + IVC * np.pi / 180 #TDC corresponds to theta=0 z = np.sqrt(pow(L / a, 2) - pow(np.sin(theta), 2)) v = omega * (V_min / A_p) * ( (r_c - 1) / 2) * np.sin(theta) * (1 + np.cos(theta) / z) return v
def computeRiseSet(self, rsAlt=0.0): """Compute rise, transit and set times for the Sun, as well as their azimuths/altitude. Parameters: rsAlt (float): Altitude to return rise/set data for (radians; optional, default=0.0 meaning actual rise/set). Set rsAlt>pi/2 to compute transit only. Note: - if rsAlt == 0.0, actual rise and set times are computed - if rsAlt != 0.0, the routine calculates when alt = rsAlt is reached - returns times, rise/set azimuth and transit altitude in the class riseSet See: - subroutine riset() in riset.f90 from libTheSky (libthesky.sf.net) for more info """ rsa = -0.8333 / self._R2D # Standard altitude for the Sun in radians if (abs(rsAlt) > 1.e-9): rsa = rsAlt # Use a user-specified altitude tmRad = np.zeros(3) azalt = np.zeros(3) alt = 0.0 ha = 0.0 h0 = 0.0 # We need a local SolTrack instance for the same location (but in radians!), but with different settings # (radians, south=0, need equatorial coordinates but not the distance), and independent times and # positions: if (self.param._useDegrees): st = self.__class__(self.geoLongitude / self._R2D, self.geoLatitude / self._R2D, useDegrees=False, useNorthEqualsZero=False, computeRefrEquatorial=True, computeDistance=False) else: st = self.__class__(self.geoLongitude, self.geoLatitude, useDegrees=False, useNorthEqualsZero=False, computeRefrEquatorial=True, computeDistance=False) # Set date and time to midnight of the desired date: st.setDateAndTime(self.year, self.month, self.day, 0, 0, 0.0) # Compute the Sun's position: st.computePosition() # Compute transit, rise and set times: agst0 = st._agst # AGST for midnight evMax = 3 # Compute transit, rise and set times by default (1-3) cosH0 = (np.sin(rsa) - np.sin(st.geoLatitude) * np.sin(st._declinationUncorr)) / ( np.cos(st.geoLatitude) * np.cos(st._declinationUncorr)) if (abs(cosH0) > 1.0): # Body never rises/sets evMax = 1 # Compute transit time and altitude only else: h0 = np.arccos(cosH0) % self._PI # Should probably work without % tmRad[0] = (st._rightAscensionUncorr - st.geoLongitude - st._agst ) % self._TWOPI # Transit time in radians; lon0 > 0 for E if (evMax > 1): tmRad[1] = (tmRad[0] - h0) % self._TWOPI # Rise time in radians tmRad[2] = (tmRad[0] + h0) % self._TWOPI # Set time in radians accur = 1.0e-5 # Accuracy; 1e-5 rad ~ 0.14s. Don't make this smaller than 1e-16 for evi in range(evMax): # Loop over transit, rise, set iter = 0 dTmRad = np.inf while (abs(dTmRad) > accur): th0 = agst0 + 1.002737909350795 * tmRad[ evi] # Solar day in sidereal days in 2000 st.second = tmRad[ evi] * self._R2H * 3600.0 # Radians -> seconds - w.r.t. midnight (h=0,m=0) st.computePosition() ha = self._revPI( th0 + st.geoLongitude - st._rightAscensionUncorr) # Hour angle: -PI - +PI alt = np.arcsin( np.sin(st.geoLatitude) * np.sin(st._declinationUncorr) + np.cos(st.geoLatitude) * np.cos(st._declinationUncorr) * np.cos(ha)) # Altitude # Correction to transit/rise/set times: if (evi == 0): # Transit dTmRad = -self._revPI(ha) # -PI - +PI else: # Rise/set dTmRad = (alt - rsa) / (np.cos(st._declinationUncorr) * np.cos(st.geoLatitude) * np.sin(ha)) tmRad[evi] = tmRad[evi] + dTmRad # Print debug output to stdOut: # print(" %4i %2i %2i %2i %2i %9.3lf " % (st.year,st.month,st.day, st.hour,st.minute,st.second)) # print(" %3i %4i %9.3lf %9.3lf %9.3lf \n" % (evi,iter, tmRad[evi]*24,abs(dTmRad)*24,accur*24)) iter += 1 if (iter > 30): break # The while loop doesn't seem to converge # while(abs(dTmRad) > accur) if (iter > 30): # Convergence failed print( '\n *** WARNING: riset(): Riset failed to converge: %i %9.3lf ***\n' % (evi, rsAlt)) tmRad[evi] = -np.inf azalt[evi] = -np.inf else: # Result converged, store it if (evi == 0): azalt[evi] = alt # Transit altitude else: azalt[evi] = np.arctan2( np.sin(ha), (np.cos(ha) * np.sin(st.geoLatitude) - np.tan(st._declinationUncorr) * np.cos(st.geoLatitude) )) # Rise,set hour angle -> azimuth if (tmRad[evi] < 0.0 and abs(rsAlt) < 1.e-9): tmRad[evi] = -np.inf azalt[evi] = -np.inf # for-loop evi # Set north to zero radians for azimuth if desired (use the original parameters!): if (self.param._useNorthEqualsZero): azalt[1] = (azalt[1] + self._PI ) % self._TWOPI # Add PI and fold between 0 and 2pi azalt[2] = (azalt[2] + self._PI ) % self._TWOPI # Add PI and fold between 0 and 2pi # Convert resulting angles to degrees if desired (use the original parameters!): if (self.param._useDegrees): azalt[0] *= self._R2D # Transit altitude azalt[1] *= self._R2D # Rise azimuth azalt[2] *= self._R2D # Set azimuth # Store results: self.transitTime = tmRad[ 0] * self._R2H # Transit time - radians -> hours self.riseTime = tmRad[1] * self._R2H # Rise time - radians -> hours self.setTime = tmRad[2] * self._R2H # Set time - radians -> hours self.transitAltitude = azalt[0] # Transit altitude self.riseAzimuth = azalt[1] # Rise azimuth self.setAzimuth = azalt[2] # Set azimuth return
def new_state(self, x_near, u, dt): nx = x_near[0] + np.cos(u) * dt ny = x_near[1] + np.sin(u) * dt return (nx, ny)