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 rv_pqw(k, p, ecc, nu): r"""Returns r and v vectors in perifocal frame. .. math:: \vec{r} = \frac{h^2}{\mu}\frac{1}{1 + e\cos(\theta)}\begin{bmatrix} \cos(\theta)\\ \sin(\theta)\\ 0 \end{bmatrix} \\\\\\ \vec{v} = \frac{h^2}{\mu}\begin{bmatrix} -\sin(\theta)\\ e+\cos(\theta)\\ 0 \end{bmatrix} Parameters ---------- k : float Standard gravitational parameter (km^3 / s^2). p : float Semi-latus rectum or parameter (km). ecc : float Eccentricity. nu: float True anomaly (rad). Returns ------- r: ndarray Position. Dimension 3 vector v: ndarray Velocity. Dimension 3 vector Examples -------- >>> from poliastro.constants import GM_earth >>> k = GM_earth #Earth gravitational parameter >>> ecc = 0.3 #Eccentricity >>> h = 60000e6 #Angular momentum of the orbit [m^2]/[s] >>> nu = np.deg2rad(120) #True Anomaly [rad] >>> p = h**2 / k #Parameter of the orbit >>> r, v = rv_pqw(k, p, ecc, nu) >>> #Printing the results r = [-5312706.25105345 9201877.15251336 0] [m] v = [-5753.30180931 -1328.66813933 0] [m]/[s] Note ---- These formulas can be checked at Curtis 3rd. Edition, page 110. Also the example proposed is 2.11 of Curtis 3rd Edition book. """ 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 get_declination(app_long: FlexNum, oblique_corr: FlexNum): """ solar declination angle at ref_datetime""" sal = radians(app_long) oc = radians(oblique_corr) declination = degrees(arcsin((sin(oc) * sin(sal)))) return declination
def get_zenith(declination: FlexNum, hour_angle: FlexNum, lat_r: FlexNum): """ calculates solar zenith angle at ref_datetime""" d = radians(declination) ha = radians(hour_angle) lat = lat_r zenith = degrees(arccos(sin(lat) * sin(d) + cos(lat) * cos(d) * cos(ha))) return zenith
def get_sun_eq_of_center(ajc: FlexNum, geomean_anom: FlexNum): """calculates the suns equation of center""" gma = radians(geomean_anom) sun_eq_of_center = \ sin(gma) * (1.914602 - ajc * (0.004817 + 0.000014 * ajc)) + \ sin(2 * gma) * (0.019993 - 0.000101 * ajc) + \ sin(3 * gma) * 0.000289 return sun_eq_of_center
def get_distance(locA, locB): # use haversine forumla print "ayyo" earth_rad = 6371.0 dlat = deg2rad(locB[0] - locA[0]) dlon = deg2rad(locB[1] - locA[1]) a = sin(dlat / 2) * sin(dlat / 2) + \ cos(deg2rad(locA[0])) * cos(deg2rad(locB[0])) * \ sin(dlon / 2) * sin(dlon / 2) c = 2 * arctan2(sqrt(a), sqrt(1 - a)) return earth_rad * c
def lat_lon_alt_to_ecef_xyz(R): """ see [1] p. 512 :param R: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) :return: (X,Y,Z) -- coordinates in ECEF (numpy array) """ # WGS 84 constants a2 = 6378137.0 ** 2 # Equatorial Radius [m] b2 = 6356752.314245 ** 2 # Polar Radius [m] radius = lambda phi: sqrt(a2 * (cos(phi)) ** 2 + b2 * (sin(phi)) ** 2) f, t, h = np.deg2rad(R[0]), np.deg2rad(R[1]), R[2] X = cos(t) * cos(f) * (h + a2 / radius(f)) Y = sin(t) * cos(f) * (h + a2 / radius(f)) Z = sin(f) * (h + b2 / radius(f)) return np.array([X, Y, Z])
def lat_lon_alt_to_ecef_xyz(R): """ see [1] p. 512 :param R: (φ,θ,h) -- lat [deg], lon [deg], alt in WGS84 (numpy array) :return: (X,Y,Z) -- coordinates in ECEF (numpy array) """ # WGS 84 constants a2 = 6378137.0**2 # Equatorial Radius [m] b2 = 6356752.314245**2 # Polar Radius [m] radius = lambda phi: sqrt(a2 * (cos(phi))**2 + b2 * (sin(phi))**2) f, t, h = np.deg2rad(R[0]), np.deg2rad(R[1]), R[2] X = cos(t) * cos(f) * (h + a2 / radius(f)) Y = sin(t) * cos(f) * (h + a2 / radius(f)) Z = sin(f) * (h + b2 / radius(f)) return np.array([X, Y, Z])
def gauss_from_twiss(emit, beta, alpha): phi = 2 * pi * np.random.rand() u = np.random.rand() a = sqrt(-2 * np.log((1 - u)) * emit) x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * (sin(phi) + alpha * cos(phi)) return (x, xp)
def drawCreatures(self): for i in range(0, len(self.gameField.creatures)): c = self.gameField.creatures[i] # creature drawEfCircle(FIELD_X_OFFSET + c.xy.x, c.xy.y, CREATURE_SIZE, 10, GL_POLYGON, 0, c.fitness / STARTING_FITNESS, 0) # creature direction drawLine(int(FIELD_X_OFFSET + c.xy.x), int(c.xy.y), int(FIELD_X_OFFSET + (c.xy.x + cos(c.direction) * CREATURE_SIZE)), int((c.xy.y + sin(c.direction) * CREATURE_SIZE)), 1, 0.3, 0.3, 1) # creature's sight direction if not (c.debug_info[0] > 10000): # inf drawLine(int(FIELD_X_OFFSET + c.xy.x), int(c.xy.y), int(FIELD_X_OFFSET + (c.xy.x + cos(c.debug_info[1]) * c.debug_info[0])), int((c.xy.y + sin(c.debug_info[1]) * c.debug_info[0])), 1, 1, 0.3, 0.3)
def gauss_from_twiss(emit, beta, alpha): phi = 2*pi * np.random.rand() u = np.random.rand() a = sqrt(-2*np.log( (1-u)) * emit) x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * ( sin(phi) + alpha * cos(phi) ) return (x, xp)
def basis_function(k): k_00 = 1e-1 if abs(k) <= k_00: return 1 - 1 / 18 * k**2 + 1 / 792 * k**4 else: return 105.0 / k**7 * (k * (k * k - 15) * cos(k) - (6 * k * k - 15) * sin(k))
def sin(self): if self.unit.is_angle(): return umath.sin( self.value * self.unit.conversion_factor_to(_unit_table['rad'])) else: raise TypeError('Argument of sin must be an angle')
def update_metric(self, pos_mat, ang_vec): #This method allows us to update the flocking model with the Metric model #Each new velocity is constructed by averaging over all of the velocities within #the radius selected, self.r. #Inputs -- x-coordinates, y-coordinates, trajectories for time = t #Outputs -- x-coordinates, y-coordinates, trajectories for time = t + (delta t) avg_sin = 0 * ang_vec avg_cos = 0 * ang_vec for j in range(0, self.N): #find distances for all particles dist_vec = self.calc_dist(pos_mat, j) #find indicies that are within the radius ngbs_idx_vec = np.where(dist_vec <= self.r)[0] if len(ngbs_idx_vec) == 0: avg_sin[j] = 0 avg_cos[j] = 0 else: #find average velocity of those inside the radius sint = np.average(sin(ang_vec[ngbs_idx_vec])) cost = np.average(cos(ang_vec[ngbs_idx_vec])) avg_sin[j] = sint avg_cos[j] = cost #construct the noise noise = self.theta_noise() #update velocities and positions cosi = (self.ep) * avg_cos + (1 - self.ep) * np.cos(ang_vec) sini = (self.ep) * avg_sin + (1 - self.ep) * np.sin(ang_vec) new_ang_vec = arctan2(sini, cosi) + noise mask = self.status_vec == 1 new_ang_vec[mask] += np.pi new_mod_ang_vec = np.mod(new_ang_vec, 2 * np.pi) pos_mat[:, 0] = pos_mat[:, 0] + self.dt * self.v * cos(new_mod_ang_vec) pos_mat[:, 1] = pos_mat[:, 1] + self.dt * self.v * sin(new_mod_ang_vec) #Make sure that the positions are not outside the boundary. #If so, correct for periodicity pos_mat = self.check_boundary(pos_mat) #Outputs returned return (pos_mat, new_ang_vec)
def get_right_ascension(app_long: FlexNum, oblique_corr: FlexNum): """ calculates the suns right ascension angle """ sal = radians(app_long) oc = radians(oblique_corr) right_ascension = degrees(arctan2(cos(oc) * sin(sal), cos(sal))) return right_ascension
def predict_next_state(scenario: Scenario, current: MyState) -> MyState: next: MyState = deepcopy(current) delta_x: float = cos( next.state.orientation) * next.state.velocity * scenario.dt delta_y: float = sin( next.state.orientation) * next.state.velocity * scenario.dt next.state.position[0] += delta_x next.state.position[1] += delta_y return next
def get_equation_of_time(oblique_corr: FlexNum, geomean_long: FlexNum, geomean_anom: FlexNum, earth_eccent: FlexNum): """ calculates the equation of time in minutes """ oc = radians(oblique_corr) gml = radians(geomean_long) gma = radians(geomean_anom) ec = earth_eccent vary = tan(oc / 2)**2 equation_of_time = 4 * degrees( vary * sin(2 * gml) - 2 * ec * sin(gma) + \ 4 * ec * vary * sin(gma) * cos(2 * gml) - \ 0.5 * vary * vary * sin(4 * gml) - \ 1.25 * ec * ec * sin(2 * gma)) return equation_of_time
def rotation_matrix(angle, axis): c = cos(angle) s = sin(angle) if axis == 0: return np.array([[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]) elif axis == 1: return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [s, 0.0, c]]) elif axis == 2: return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) else: raise ValueError("Invalid axis: must be one of 'x', 'y' or 'z'")
def sunposIntermediate(iYear, iMonth, iDay, dHours, dMinutes, dSeconds): # Calculate difference in days between the current Julian Day # and JD 2451545.0, which is noon 1 January 2000 Universal Time # Calculate time of the day in UT decimal hours dDecimalHours = dHours + (dMinutes + dSeconds / 60.0) / 60.0 # Calculate current Julian Day liAux1 = (iMonth - 14) / 12 liAux2 = (1461 * (iYear + 4800 + liAux1)) / 4 + ( 367 * (iMonth - 2 - 12 * liAux1)) / 12 - (3 * ( (iYear + 4900 + liAux1) / 100)) / 4 + iDay - 32075 dJulianDate = liAux2 - 0.5 + dDecimalHours / 24.0 # Calculate difference between current Julian Day and JD 2451545.0 dElapsedJulianDays = dJulianDate - 2451545.0 # Calculate ecliptic coordinates (ecliptic longitude and obliquity of the # ecliptic in radians but without limiting the angle to be less than 2*Pi # (i.e., the result may be greater than 2*Pi) dOmega = 2.1429 - 0.0010394594 * dElapsedJulianDays dMeanLongitude = 4.8950630 + 0.017202791698 * dElapsedJulianDays # Radians dMeanAnomaly = 6.2400600 + 0.0172019699 * dElapsedJulianDays dEclipticLongitude = dMeanLongitude + 0.03341607 * sin( dMeanAnomaly) + 0.00034894 * sin( 2 * dMeanAnomaly) - 0.0001134 - 0.0000203 * sin(dOmega) dEclipticObliquity = 0.4090928 - 6.2140e-9 * dElapsedJulianDays + 0.0000396 * cos( dOmega) # Calculate celestial coordinates ( right ascension and declination ) in radians # but without limiting the angle to be less than 2*Pi (i.e., the result may be # greater than 2*Pi) dSin_EclipticLongitude = sin(dEclipticLongitude) dY = cos(dEclipticObliquity) * dSin_EclipticLongitude dX = cos(dEclipticLongitude) dRightAscension = arctan2(dY, dX) if dRightAscension < 0.0: dRightAscension = dRightAscension + 2 * pi dDeclination = arcsin(sin(dEclipticObliquity) * dSin_EclipticLongitude) dGreenwichMeanSiderealTime = 6.6974243242 + 0.0657098283 * dElapsedJulianDays + dDecimalHours return (dRightAscension, dDeclination, dGreenwichMeanSiderealTime)
def m_from_twiss(Tw1, Tw2): #% Transport matrix M for two sets of Twiss parameters (alpha,beta,psi) b1 = Tw1[1] a1 = Tw1[0] psi1 = Tw1[2] b2 = Tw2[1] a2 = Tw2[0] psi2 = Tw2[2] psi = psi2-psi1 cosp = cos(psi) sinp = sin(psi) M = np.zeros((2, 2)) M[0, 0] = sqrt(b2/b1)*(cosp+a1*sinp) M[0, 1] = sqrt(b2*b1)*sinp M[1, 0] = ((a1-a2)*cosp-(1+a1*a2)*sinp)/sqrt(b2*b1) M[1, 1] = sqrt(b1/b2)*(cosp-a2*sinp) return M
def m_from_twiss(Tw1, Tw2): #% Transport matrix M for two sets of Twiss parameters (alpha,beta,psi) b1 = Tw1[1] a1 = Tw1[0] psi1 = Tw1[2] b2 = Tw2[1] a2 = Tw2[0] psi2 = Tw2[2] psi = psi2 - psi1 cosp = cos(psi) sinp = sin(psi) M = np.zeros((2, 2)) M[0, 0] = sqrt(b2 / b1) * (cosp + a1 * sinp) M[0, 1] = sqrt(b2 * b1) * sinp M[1, 0] = ((a1 - a2) * cosp - (1 + a1 * a2) * sinp) / sqrt(b2 * b1) M[1, 1] = sqrt(b1 / b2) * (cosp - a2 * sinp) return M
def f(x1, x2): return sign(x2 - x1 + (0.25 * sin(pi * x1)))
def waterbag_from_twiss(emit, beta, alpha): phi = 2*pi * np.random.rand() a = sqrt(emit) * np.random.rand() x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * ( sin(phi) + alpha * cos(phi) ) return (x, xp)
def pol2cart(rho: float, phi: float) -> ndarray: x = rho * cos(phi) y = rho * sin(phi) return array([x, y])
def _hc(k, cs, rho, omega): return (cs / sin(omega) * (rho ** k) * sin(omega * (k + 1)) * greater(k, -1))
def _hc(k, cs, rho, omega): return (cs / sin(omega) * (rho**k) * sin(omega * (k + 1)) * greater(k, -1))
def sin(self): if self.unit.isAngle(): return umath.sin(self.value * self.unit.conversionFactorTo(_unit_table["rad"])) else: raise TypeError("Argument of sin must be an angle")
def sinc(x): """sinc(x) returns sin(pi*x)/(pi*x) at all points of array x. """ y = pi * where(x == 0, 1.0e-20, x) return sin(y) / y
# numbers = logspace(1, 40, 5) # [1.00000000e+01 5.62341325e+10 3.16227766e+20 1.77827941e+30 # 1.00000000e+40] print(numbers) print("%.2g" % numbers[0]) # 10 print("%.2g" % numbers[1]) # 5.6e+10 print("%.3g" % numbers[2]) # 3.16e+20 print("%.4g" % numbers[3]) # 1.778e+30 print("%.5g" % numbers[4]) # 1e+40 # ------------------------------------------------------------------------------------------------------------- a1 = array([1, 2, 3, 4, 5]) a1 = a1 + 5 print(a1) # [ 6 7 8 9 10] a2 = array([6, 1, 9, 3, 2]) a3 = a1 + a2 # vectorized operation print(a3) # [12 8 17 12 12] # min, max, sqrt, pow, sort, etc print(sin(a1)) # [-0.2794155 0.6569866 0.98935825 0.41211849 -0.54402111] print(cos(a2)) # [ 0.96017029 0.54030231 -0.91113026 -0.9899925 -0.41614684] print(log(a3)) # [2.48490665 2.07944154 2.83321334 2.48490665 2.48490665] a4 = concatenate((a1, a2)) print(a4) # [ 6 7 8 9 10 6 1 9 3 2]
def random_ABCD(n, p, q, pRepeat=0.01, pReal=0.5, pBCmask=0.90, pDmask=0.8, pDzero=0.5): """ Generate ONE n-th order random stable state-spaces, with q inputs and p outputs copy/adapted from control-python library (Richard Murray): https://sourceforge.net/projects/python-control/ (thanks guys!) possibly already adpated/copied from Mathworks or Octave Parameters: - n: number of states (default: random between 5 and 10) - p: number of outputs (default: 1) - q: number of inputs (default: 1) - pRepeat: Probability of repeating a previous root (default: 0.01) - pReal: Probability of choosing a real root (default: 0.5). Note that when choosing a complex root, the conjugate gets chosen as well. So the expected proportion of real roots is pReal / (pReal + 2 * (1 - pReal)) - pBCmask: Probability that an element in B or C will not be masked out (default: 0.90) - pDmask: Probability that an element in D will not be masked out (default: 0.8) - pDzero: Probability that D = 0 (default: 0.5) Returns a four numpy matrices A,B,C,D """ # Make some poles for A. Preallocate a complex array. poles = zeros(n) + zeros(n) * 0.j i = 0 while i < n: if rand() < pRepeat and i != 0 and i != n - 1: # Small chance of copying poles, if we're not at the first or last element. if poles[i - 1].imag == 0: poles[i] = poles[i - 1] # Copy previous real pole. i += 1 else: poles[i:i + 2] = poles[ i - 2:i] # Copy previous complex conjugate pair of poles. i += 2 elif rand() < pReal or i == n - 1: poles[i] = 2. * rand() - 1. # No-oscillation pole. i += 1 else: mag = rand() # Complex conjugate pair of oscillating poles. phase = 2. * pi * rand() poles[i] = complex(mag * cos(phase), mag * sin(phase)) poles[i + 1] = complex(poles[i].real, -poles[i].imag) i += 2 # Now put the poles in A as real blocks on the diagonal. A = zeros((n, n)) i = 0 while i < n: if poles[i].imag == 0: A[i, i] = poles[i].real i += 1 else: A[i, i] = A[i + 1, i + 1] = poles[i].real A[i, i + 1] = poles[i].imag A[i + 1, i] = -poles[i].imag i += 2 while True: # Finally, apply a transformation so that A is not block-diagonal. T = randn(n, n) try: A = dot(solve(T, A), T) # A = T \ A * T break except LinAlgError: # In the unlikely event that T is rank-deficient, iterate again. pass # Make the remaining matrices. B = randn(n, q) C = randn(p, n) D = randn(p, q) # Make masks to zero out some of the elements. while True: Bmask = rand(n, q) < pBCmask if not Bmask.all(): # Retry if we get all zeros. break while True: Cmask = rand(p, n) < pBCmask if not Cmask.all(): # Retry if we get all zeros. break if rand() < pDzero: Dmask = zeros((p, q)) else: while True: Dmask = rand(p, q) < pDmask if not Dmask.all(): # Retry if we get all zeros. break # Apply masks. B *= Bmask C *= Cmask # D *= Dmask return A, B, C, D
def sind(x): return sin(deg2rad(x))
def func3(x): return x - (e**x + sin(x) - 4) / (e**x + cos(x))
import pickle #创建二维样本数据 from numpy.core.umath import pi, cos, sin n = 200 #两个正态分布数据集 class_1 = 0.6 * randn(n,2) class_2 = 1.2 * randn(n,2) + array([5,1]) labels = hstack((ones(n), -ones(n))) #Stack arrays in sequence horizontally (column wise). #用pickle保存 with open('points_normal_test.pkl', 'w') as f: # with open('points_normal.pkl', 'w') as f: pickle.dump(class_1, f) pickle.dump(class_2, f) pickle.dump(labels,f) #正态分布,并使数据成环绕状分布 class_1 = 0.6 * randn(n,2) r = 0.8 * randn(n,1) + 5 angle = 2*pi*randn(n,1) class_2 = hstack((r*cos(angle), r*sin(angle))) labels = hstack((ones(n), -ones(n))) with open('points_ring_test.pkl','w') as f: # with open('points_ring.pkl','w') as f: pickle.dump(class_1, f) pickle.dump(class_2, f) pickle.dump(labels,f)
def move(self): self.__change_angle() x = self.x + cos(self.angle) * self.STEP_SIZE y = self.y + sin(self.angle) * self.STEP_SIZE return self.__change_position(x, y)
def sinc(x): """sinc(x) returns sin(pi*x)/(pi*x) at all points of array x. """ y = pi* where(x == 0, 1.0e-20, x) return sin(y)/y
def func(x): return sin(x) - x + pi/4.0
def _hs(k, cs, rho, omega): c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) / (1 - 2 * rho * rho * cos(2 * omega) + rho**4)) gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega) ak = abs(k) return c0 * rho**ak * (cos(omega * ak) + gamma * sin(omega * ak))
def waterbag_from_twiss(emit, beta, alpha): phi = 2 * pi * np.random.rand() a = sqrt(emit) * np.random.rand() x = a * sqrt(beta) * cos(phi) xp = -a / sqrt(beta) * (sin(phi) + alpha * cos(phi)) return (x, xp)
def _hs(k, cs, rho, omega): c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) / (1 - 2 * rho * rho * cos(2 * omega) + rho ** 4)) gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega) ak = abs(k) return c0 * rho ** ak * (cos(omega * ak) + gamma * sin(omega * ak))