def ExactIntegrationOfSinus(t, a=None, b=None): with precision(300): if a == None and b == None: return 0.5 * math.pi * math.sqrt(t) * (mpmath.angerj(0.5, t) - mpmath.angerj(-0.5, t)) elif a == None and b != None: a = 0 elif b == None: b = t mpmath.mp.dps = 50 mpmath.mp.pretty = True pi = mpmath.mp.pi pi = +pi fcos = mpmath.fresnelc fsin = mpmath.fresnels arg_b = mpmath.sqrt(2 * (t - b) / pi) if a == "MinusInfinity": return mpmath.sqrt( 0.5 * mpmath.mp.pi) * (-2 * mpmath.sin(t) * fcos(arg_b) + 2 * mpmath.cos(t) * fsin(arg_b) + mpmath.sin(t) - mpmath.cos(t)) else: arg_a = mpmath.sqrt(2 * (t - a) / pi) return mpmath.sqrt(2 * mpmath.mp.pi) * ( (fsin(arg_b) - fsin(arg_a)) * mpmath.cos(t) + (fcos(arg_a) - fcos(arg_b)) * mpmath.sin(t))
def cos_gamma(_a: float, incl: float, tol=10e-5) -> float: """Calculate the cos of the angle gamma""" if abs(incl) < tol: return 0 else: return mpmath.cos(_a) / mpmath.sqrt( mpmath.cos(_a)**2 + mpmath.cot(incl)**2) # real
def _view_cone_calc(lat_geoc, lon_geoc, sat_pos, sat_vel, q_max, m): """Semi-private: Performs the viewing cone visibility calculation for the day defined by m. Note: This function is based on a paper titled "rapid satellite-to-site visibility determination based on self-adaptive interpolation technique" with some variation to account for interaction of viewing cone with the satellite orbit. Args: lat_geoc (float): site location in degrees at the start of POI lon_geoc (float): site location in degrees at the start of POI sat_pos (Vector3D): position of satellite (at the same time as sat_vel) sat_vel (Vector3D): velocity of satellite (at the same time as sat_pos) q_max (float): maximum orbital radius m (int): interval offsets (number of days after initial condition) Returns: Returns 4 numbers representing times at which the orbit is tangent to the viewing cone, Raises: ValueError: if any of the 4 formulas has a complex answer. This happens when the orbit and viewing cone do not intersect or only intersect twice. Note: With more analysis it should be possible to find a correct interval even in the case where there are only two intersections but this is beyond the current scope of the project. """ lat_geoc = (lat_geoc * mp.pi) / 180 lon_geoc = (lon_geoc * mp.pi) / 180 # P vector (also referred to as orbital angular momentum in the paper) calculations p_unit_x, p_unit_y, p_unit_z = cross(sat_pos, sat_vel) / (mp.norm(sat_pos) * mp.norm(sat_vel)) # Following are equations from Viewing cone section of referenced paper r_site_magnitude = earth_radius_at_geocetric_lat(lat_geoc) gamma1 = THETA_NAUGHT + mp.asin((r_site_magnitude * mp.sin((mp.pi / 2) + THETA_NAUGHT)) / q_max) gamma2 = mp.pi - gamma1 # Note: atan2 instead of atan to get the correct quadrant. arctan_term = mp.atan2(p_unit_x, p_unit_y) arcsin_term_gamma, arcsin_term_gamma2 = [(mp.asin((mp.cos(gamma) - p_unit_z * mp.sin(lat_geoc)) / (mp.sqrt((p_unit_x ** 2) + (p_unit_y ** 2)) * mp.cos(lat_geoc)))) for gamma in [gamma1, gamma2]] angle_1 = (arcsin_term_gamma - lon_geoc - arctan_term + 2 * mp.pi * m) angle_2 = (mp.pi - arcsin_term_gamma - lon_geoc - arctan_term + 2 * mp.pi * m) angle_3 = (arcsin_term_gamma2 - lon_geoc - arctan_term + 2 * mp.pi * m) angle_4 = (mp.pi - arcsin_term_gamma2 - lon_geoc - arctan_term + 2 * mp.pi * m) angles = [angle_1, angle_2, angle_3, angle_4] # Check for complex answers if any([not isinstance(angle, mp.mpf) for angle in angles]): raise ValueError() # Map all angles to 0 to 2*pi for idx in range(len(angles)): while angles[idx] < 0: angles[idx] += 2 * mp.pi while angles[idx] > 2 * mp.pi: angles[idx] -= 2 * mp.pi # Calculate the corresponding time for each angle and return return [mp.nint((1 / ANGULAR_VELOCITY_EARTH) * angle) for angle in angles]
def any_f_to_poly(f, a, b, order): # remap [a, b] to [-1, 1] for better conditioning p = mpmath.lu_solve( vandermonde(mpmath.matrix([a, b]), 2), mpmath.matrix([-1., 1.]) ) # fit polynomial to [-1, 1], then compose with mapping function p_x = mpmath.matrix( [mpmath.cos((i + .5) * mpmath.pi / order) for i in range(order)] ) x = mpmath.matrix( [a + (b - a) * (.5 + .5 * p_x[i]) for i in range(order)] ) q = utils.poly.compose( mpmath.lu_solve(vandermonde(p_x, order), f(x)), p ) # checking p_x = mpmath.matrix( [mpmath.cos(i * mpmath.pi / order) for i in range(order + 1)] ) x = mpmath.matrix( [a + (b - a) * (.5 + .5 * p_x[i]) for i in range(order + 1)] ) y = utils.poly.eval_multi(q, x) - f(x) est_err = max([abs(y[i]) for i in range(y.rows)]) print('est_err', est_err) return q
def integrand(theta, phi): evals[0] += 1 qab = q * mp.sin(theta) qa = qab * mp.cos(phi) qb = qab * mp.sin(phi) qc = q * mp.cos(theta) Zq = KERNEL_MP(qa, qb, qc)**2 return Zq * mp.sin(theta)
def easom(data): """ Easom’s function Whose global minimum is f∗ = −1 at x∗ = (π, π) within −100 ≤ x, y ≤ 100. It has many local minima. """ return float(-mp.cos(data[0]) * mp.cos(data[1]) * mp.exp(-(data[0] - mp.pi)**2 - (data[1] - mp.pi)**2))
def get_dtheta_at(self, phi, covered_r): from math import asin, cos, sqrt, pi if covered_r >= sqrt(2) * cos(phi): # In this case, the confidence radius is so large such that it covers the whole orbit and the north pole. dtheta = pi else: dtheta = 2 * asin((.5 * covered_r) / cos(phi)) return dtheta
def sec_der(x_val: Real) -> mp.mpf: """Define the actual second derivative.""" x_squared = mp.power(x_val, 2) return ( mp.cos(x_val) + (-4 * x_squared) * mp.cos(x_squared) + -2 * mp.sin(x_squared) + mp.sin(x_val) )
def f2(x): """ Another angular integral in electron noise calculation. """ term1 = 2*x**3 * (2*mp.si(2*x)-mp.si(x)) term2 = 2*x**2 * (mp.cos(2*x) - mp.cos(x)) term3 = x * (mp.sin(2*x) - 2*mp.sin(x)) - (mp.cos(2*x) - 4* mp.cos(x) + 3) return (term1 + term2 + term3)/(12 * x**2)
def get_rotation_matrix_north_pole_to(theta, phi): from numpy import array, matmul from math import sin, cos Rx = array([[1, 0, 0], [0, sin(phi), cos(phi)], [0, -cos(phi), sin(phi)]]) Rz = array([[sin(theta), cos(theta), 0], [-cos(theta), sin(theta), 0], [0, 0, 1]]) rotation_matrix = matmul(Rz, Rx) return rotation_matrix
def FSingleDisc(x1,x2,t,a): """ inside of log() for connected HEE. We take single interval subsystem A=[x1,x2]. """ t1 = T(x1,t,a) t2 = T(x2,t,a) tb1 = TB(x1,t,a) tb2 = TB(x2,t,a) num = (a**4)*( (exp(j*t1)-exp(-j*tb1))*(exp(j*t2)-exp(-j*tb2)) )**2 den = exp(j*(t1-tb1+t2-tb2))*((cos(t1)*cos(tb1)*cos(t2)*cos(tb2))**2) return num/den
def S_single_hol_disconn(x1, x2, t, a): t1, t2, tb1, tb2 = theta(x1, t, a), theta(x2, t, a), thetaB(x1, t, a), thetaB(x2, t, a) z1, z2, zb1, zb2 = j * exp(j * t1), j * exp(j * t2), j * exp( -j * tb1), j * exp(-j * tb2) deriv = a**2 / (exp(j * (t1 - tb1 + t2 - tb2) / 2) * cos(t1) * cos(t2) * cos(tb1) * cos(tb2)) disconn = (z1 - zb1) * (z2 - zb2) return re(log(deriv * disconn)) / 6 - log((x2 - x1)**2) / 6
def getAntiprismVolumeOperator(n, k): result = getProduct([ fdiv( fprod([ n, sqrt(fsub(fmul(4, cos(cos(fdiv(pi, fmul(n, 2))))), 1)), sin(fdiv(fmul(3, pi), fmul(2, n))) ]), fmul(12, sin(sin(fdiv(pi, n))))), sin(fdiv(fmul(3, pi), fmul(2, n))), getPower(k, 3) ]) return result.convert('meter^3')
def Diagonalizzazione(I): α = AngoloDiRotazione(I) Iη = I[0] Iξ = I[1] Iηξ = I[2] if α != 0: Iy = Iη * mpmath.cos(α)**2 + Iξ * mpmath.sin( α)**2 - 2 * Iηξ * mpmath.cos(α) * mpmath.sin(α) Iz = Iξ * mpmath.sin(α)**2 + Iξ * mpmath.cos( α)**2 + 2 * Iηξ * mpmath.cos(α) * mpmath.sin(α) J = [Iy, Iz] return J else: return I
def elliptic_core_g(x,y): x = x/2 y = y/2 factor = (cos(x)/sin(y) + sin(y)/cos(x) - (cos(y)/tan(y)/cos(x) + sin(x)*tan(x)/sin(y)))/pi k = tan(x)/tan(y) m = k*k n = (sin(x)/sin(y))*(sin(x)/sin(y)) u = asin(tan(y)/tan(x)) complete = ellipk(m) - ellippi(n, m) incomplete = ellipf(u,m) - ellippi(n/k/k,1/m)/k #incomplete = ellipf(u,m) - ellippi(n,u,m) return re(1.0 - factor*(incomplete + complete))
def calculate_coordinates(input_angles): # Constants scalling_const = np.sqrt(.3) f = 195 * scalling_const * math.power(10, -3) t = 375 * scalling_const * math.power(10, -3) coord_list = [] for angle in input_angles: T_1 = angle[0] - np.pi T_2 = angle[1] - np.pi x = float((f * math.cos(T_1) + t * math.cos( (T_1 - T_2))) * math.power(10, 3)) y = float((f * math.sin(T_1) + t * math.sin( (T_1 - T_2))) * math.power(10, 3)) coord_list.append([x, y]) return coord_list
def family_graphical_combination(t, c, angle_alpha_prime): """ Aberdeen family of graphical operators """ if not (isinstance(t, Opinion) and isinstance(c, Opinion) \ and t.check() and c.check()): raise Exception("Two valid Opinions are required!") if mpmath.almosteq(angle_alpha_prime, -mpmath.pi / 3, epsilon): new_magnitude = c.get_magnitude_ratio() * ( mpmath.mpf("2") * t.getUncertainty() / mpmath.sqrt(mpmath.mpf("3"))) #new_magnitude = 0 elif mpmath.almosteq(angle_alpha_prime, mpmath.mpf("2/3") * mpmath.pi, epsilon): new_magnitude = c.get_magnitude_ratio() * ( mpmath.mpf("2") * (mpmath.mpf("1") - t.getUncertainty()) / mpmath.sqrt(mpmath.mpf("3"))) #new_magnitude = 0 elif mpmath.almosteq(angle_alpha_prime, mpmath.mpf("1/2") * mpmath.pi, epsilon): #new_magnitude = 1 - t.getUncertainty() new_magnitude = 2 * t.getBelief() else: new_magnitude = c.get_magnitude_ratio() * (mpmath.mpf("2") * \ (mpmath.sqrt(mpmath.power(mpmath.tan(angle_alpha_prime), mpmath.mpf("2")) +1 ) / ( mpmath.absmax(mpmath.tan(angle_alpha_prime) + mpmath.sqrt(mpmath.mpf("3"))) ) ) * \ t.getBelief()) new_uncertainty = t.getUncertainty( ) + mpmath.sin(angle_alpha_prime) * new_magnitude new_disbelief = t.getDisbelief() + ( t.getUncertainty() - new_uncertainty) * mpmath.cos( mpmath.pi / 3) + mpmath.cos(angle_alpha_prime) * mpmath.sin( mpmath.pi / 3) * new_magnitude if mpmath.almosteq(new_uncertainty, 1, epsilon): new_uncertainty = mpmath.mpf("1") if mpmath.almosteq(new_uncertainty, 0, epsilon): new_uncertainty = mpmath.mpf("0") if mpmath.almosteq(new_disbelief, 1, epsilon): new_disbelief = mpmath.mpf("1") if mpmath.almosteq(new_disbelief, 0, epsilon): new_disbelief = mpmath.mpf("0") return Opinion(1 - new_disbelief - new_uncertainty, new_disbelief, new_uncertainty, "1/2")
def cos(arg): """Cosine. This function is a wrapper around a lower level function. If the argument is a standard *float* or *int*, the function from the builtin :mod:`math` module will be used. If the argument is an :mod:`mpmath` float, the corresponding multiprecision function, if available, will be used. Otherwise, the argument is assumed to be a series type and a function from the piranha C++ library is used. :param arg: cosine argument :returns: cosine of *arg* :raises: :exc:`TypeError` if the type of *arg* is not supported, or any other exception raised by the invoked low-level function >>> from .types import poisson_series, polynomial, rational, short >>> t = poisson_series(polynomial(rational,short))() >>> cos(2 * t('x')) cos(2*x) >>> cos('y') # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: invalid argument type(s) """ if isinstance(arg,float) or isinstance(arg,int): import math return math.cos(arg) try: from mpmath import mpf, cos if isinstance(arg,mpf): return cos(arg) except ImportError: pass from ._core import _cos return _cpp_type_catcher(_cos,arg)
def calc_J(chi, En, Lz, Q, aa, slr, ecc): """ Schmidt's J function. Parameters: chi (float): radial angle En (float): energy Lz (float): angular momentum Q (float): Carter constant aa (float): spin slr (float): semi-latus rectum ecc (float): eccentricity Returns: J (float) """ En2 = En * En ecc2 = ecc * ecc aa2 = aa * aa Lz2 = Lz * Lz slr2 = slr * slr eta = 1 + ecc * cos(chi) eta2 = eta * eta J = ((1 - ecc2) * (1 - En2) + 2 * (1 - En2 - (1 - ecc2) / slr) * eta + (((3 + ecc2) * (1 - En2)) / (1 - ecc2) + ((1 - ecc2) * (aa2 * (1 - En2) + Lz2 + Q)) / slr2 - 4 / slr) * eta2) return J
def CalculateCoefSum(n, m, k): # define a[k_] as per Paul D. Beale a_coef = (1 + x*x)**2 - b*mp.cos(np.pi*k/n) c2_coef_sum = 0 for j in range(0, m+2, 2): # should include endpoint so m --> m+2 c2_coef_sum += sy.expand((mh.factorial(m)/mh.factorial(j)/mh.factorial(m-j))*(a_coef**2 - b*b)**(j//2) * a_coef**(m - j)) return c2_coef_sum
def cos(arg): """Cosine. This function is a wrapper around a lower level function. If the argument is a standard *float* or *int*, the function from the builtin :mod:`math` module will be used. If the argument is an :mod:`mpmath` float, the corresponding multiprecision function, if available, will be used. Otherwise, the argument is assumed to be a series type and a function from the piranha C++ library is used. :param arg: cosine argument :rtype: cosine of *arg* :raises: :exc:`TypeError` if the type of *arg* is not supported, or any other exception raised by the invoked low-level function >>> from . import get_series >>> t = get_series('poisson_series<polynomial<rational,short>>') >>> cos(2 * t('x')) cos(2x) >>> cos('y') # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: invalid argument type(s) """ if isinstance(arg, float) or isinstance(arg, int): import math return math.cos(arg) try: from mpmath import mpf, cos if isinstance(arg, mpf): return cos(arg) except ImportError: pass from ._core import _cos return _cpp_type_catcher(_cos, arg)
def Pprime(self, z): # A+S 18.9. from mpmath import ellipfun, sqrt, cos, sin, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0, 1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = -2 * sqrt( (e1 - e3)**3) * ellipfun('cn', u=zs, m=m) * ellipfun( 'dn', u=zs, m=m) / (ellipfun('sn', u=zs, m=m)**3) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert (H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = -4 * sqrt(H2**3) * ellipfun('sn', u=zp, m=m) * ellipfun( 'dn', u=zp, m=m) / ((1 - ellipfun('cn', u=zp, m=m))**2) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = -2 / (z**3) else: c = e1 / 2 A = sqrt(3 * c) retval = -6 * c * A * cos(A * z) / (sin(A * z))**3 if self.__ng3: return mpc(0, -1) * retval else: return retval
def get_angle_beta(self): if mpmath.almosteq(self.getDisbelief(), 1, epsilon): return mpmath.pi / 3 return mpmath.atan( (self.getUncertainty() * mpmath.sin(mpmath.pi / mpmath.mpf("3"))) / (mpmath.mpf("1") - (self.getDisbelief() + self.getUncertainty() * mpmath.cos(mpmath.pi / mpmath.mpf("3")))))
def d_theta(angle,k_v,R_v,alpha_v,An): '''Off-axis level, :math:`D_{\\theta}`, for piston in a sphere Parameters ---------- angle : mpmath.mpf Azimuth/elevation angle in radians k_v : mpmath.mpf Wavenumber alpha: mpmath.mpf Piston equivalent aperture in radians. An : mpmath.matrix An is a required pre-calculated matrix which results from the satisfying the conditions of the model - specific to each parameter set. Returns ------- abs(rel_level()) : mpmath.mpf The off-axis value at angle :math:`\theta` ''' num = 4 N_v = An.rows denom = (k_v**2)*(R_v**2)*mpmath.sin(alpha_v)**2 part1 = num/denom jn_matrix = mpmath.matrix([I**f for f in range(N_v)]) legendre_matrix = mpmath.matrix([legendre(n_v, mpmath.cos(angle)) for n_v in range(N_v)]) Anjn = HP(An,jn_matrix).doit() part2_matrix = HP(Anjn,legendre_matrix).doit() part2 = sum(part2_matrix) rel_level = lambdify([], -part1*part2, 'mpmath') return abs(rel_level())
def rotate_point(x, y, degrees): radians = math.radians(degrees) cos_theta = math.cos(radians) sin_theta = math.sin(radians) return x * cos_theta - y * sin_theta, \ x * sin_theta + y * cos_theta
def test_rationalize(): from mpmath import cos, pi, mpf assert rationalize(cos(pi / 3)) == S.Half assert rationalize(mpf("0.333333333333333")) == Rational(1, 3) assert rationalize(mpf("-0.333333333333333")) == Rational(-1, 3) assert rationalize(pi, maxcoeff=250) == Rational(355, 113)
def get_angle_alpha(self): if (mpmath.almosteq(self.getBelief(), 1, epsilon)): return mpmath.mpf("0") return mpmath.atan( (self.getUncertainty() * mpmath.sin(mpmath.pi / mpmath.mpf("3"))) / (self.getDisbelief() + self.getUncertainty() * mpmath.cos(math.pi / mpmath.mpf("3"))))
def Pprime(self,z): # A+S 18.9. from mpmath import ellipfun, sqrt, cos, sin, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0,1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = -2 * sqrt((e1 - e3)**3) * ellipfun('cn',u=zs,m=m) * ellipfun('dn',u=zs,m=m) / (ellipfun('sn',u=zs,m=m)**3) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = -4 * sqrt(H2**3) * ellipfun('sn',u=zp,m=m) * ellipfun('dn',u=zp,m=m) / ((1 - ellipfun('cn',u=zp,m=m))**2) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = -2 / (z**3) else: c = e1 / 2 A = sqrt(3 * c) retval = -6 * c * A * cos(A * z) / (sin(A * z))**3 if self.__ng3: return mpc(0,-1) * retval else: return retval
def invcdf(p): """ Inverse of the CDF of the raised cosine distribution. """ with mpmath.extradps(5): p = mpmath.mpf(p) if p < 0 or p > 1: return mpmath.nan if p == 0: return -mpmath.pi if p == 1: return mpmath.pi if p < 0.094: x = _poly_approx(mpmath.cbrt(12 * mpmath.pi * p)) - mpmath.pi elif p > 0.906: x = mpmath.pi - _poly_approx(mpmath.cbrt(12 * mpmath.pi * (1 - p))) else: y = mpmath.pi * (2 * p - 1) y2 = y**2 x = y * _p2(y2) / _q2(y2) solver = 'mnewton' x = mpmath.findroot(f=lambda t: cdf(t) - p, x0=x, df=lambda t: (1 + mpmath.cos(t)) / (2 * mpmath.pi), df2=lambda t: -mpmath.sin(t) / (2 * mpmath.pi), solver=solver) return x
def test_odefun_harmonic(): mp.dps = 15 # Harmonic oscillator f = odefun(lambda x, y: [-y[1], y[0]], 0, [1, 0]) for x in [0, 1, 2.5, 8, 3.7]: # we go back to 3.7 to check caching c, s = f(x) assert c.ae(cos(x)) assert s.ae(sin(x))
def getAntiprismVolume( n, k ): if real( n ) < 3: raise ValueError( 'the number of sides of the prism cannot be less than 3,' ) if not isinstance( k, RPNMeasurement ): return getAntiprismVolume( n, RPNMeasurement( real( k ), 'meter' ) ) if k.getDimensions( ) != { 'length' : 1 }: raise ValueError( '\'antiprism_volume\' argument 2 must be a length' ) result = getProduct( [ fdiv( fprod( [ n, sqrt( fsub( fmul( 4, cos( cos( fdiv( pi, fmul( n, 2 ) ) ) ) ), 1 ) ), sin( fdiv( fmul( 3, pi ), fmul( 2, n ) ) ) ] ), fmul( 12, sin( sin( fdiv( pi, n ) ) ) ) ), sin( fdiv( fmul( 3, pi ), fmul( 2, n ) ) ), getPower( k, 3 ) ] ) return result.convert( 'meter^3' )
def _root_approx(n, k): # Tricomi approximation with mpmath.extradps(5): n = mpmath.mpf(n) k = mpmath.mpf(k) c = 1 + (1 / (8 * n**2)) * (-1 + 1 / n) a = mpmath.pi * (4 * k - 1) / (4 * n + 2) return c * mpmath.cos(a)
def invFourier(x,F): k1 = r2*mpm.pi f = [] for xi in x: kx = k1*(xi/Lx) f.append( mpm.fsum( F[ki]*mpm.cos(kx*mpm.mpf(ki)) \ for ki in xrange(len(F)) ) ) return f
def error(coefs, progress=True): (a, b) = coefs xs = (x * mp.pi / mp.mpf(4096) for x in range(-4096, 4097)) err = max(fabs(cos(x) - f(x, a, b)) for x in xs) if progress: print('(a, b, c): ({}, {}, {})'.format(a, b, c(a, b))) print('evaluated error: ', err) print() return float(err)
def spin_vector(t): import numpy ht = self.__ht_time(t) H = self.__H_time(t) G = d_eval['G'] Gt = d_eval['\\tilde{G}'] Hts = d_eval['\\tilde{H}_\\ast'] Gtxys = sqrt(Gt**2-(Hts-H)**2) return numpy.array([x.real for x in [Gtxys*sin(ht),-Gtxys*cos(ht),Hts-H]])
def rotate_point_around_anchor(self, x, y, anchor_x, anchor_y, angle): anglefrac = angle.as_integer_ratio() radian_qty = radians(anglefrac[0] / anglefrac[1]) old_x = x - anchor_x old_y = y - anchor_y coord = matrix([float(old_x), float(old_y)]) transform = matrix([[cos(radian_qty), -sin(radian_qty)], [sin(radian_qty), cos(radian_qty)]]) result = transform * coord new_x = Decimal(str(result[0])) new_y = Decimal(str(result[1])) new_x += anchor_x new_y += anchor_y return new_x, new_y
def test_odefun_sinc_large(): mp.dps = 15 # Sinc function; test for large x f = sinc g = odefun(lambda x, y: [(cos(x) - y[0]) / x], 1, [f(1)], tol=0.01, degree=5) assert abs(f(100) - g(100)[0]) / f(100) < 0.01
def orbit_vector(t): import numpy ht = self.__ht_time(t) hs = self.__hs_time(t) h = hs + ht H = self.__H_time(t) G = d_eval['G'] Gxy = sqrt(G**2-H**2) return numpy.array([x.real for x in [Gxy*sin(h),-Gxy*cos(h),H]])
def polar_cubic(a, q, r): ''' The polar coordinate solution of the cubic function; for use when Q^3+R^2 < 0 This version formulated to work with mpmath for arbitrary floating point precision and numpy arrays. ''' theta = mpmath.acos(r / numpy.power(mpf('-1') * numpy.power(q, mpf('3')), mpf('0.5'))) return mpmath.cos(theta / mpf('3')) * numpy.power(mpf('-1') * q, mpf('0.5')) * mpf('2') - a / mpf('3')
def sph_yn_exact(n, z): """Return the value of y_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E4 . """ zm = mpmathify(z) s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1)) s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(0, int((n-1)/2) + 1)) return -cos(zm - n*pi/2)*s1 + sin(zm - n*pi/2)*s2
def Fourier(N,f): k1 = r2*mpm.pi x = [-r1/r2+mpm.mpf(i)/mpm.mpf(2*N) for i in xrange(2*N)] fx = [f(Lx*xi) for xi in x] F = [] for ki in xrange(N): kx = k1*mpm.mpf(ki) F.append( mpm.fsum( fi*mpm.cos(kx*xi) for xi,fi in zip(x,fx) ) ) F[-1] /= mpm.mpf(N) F[0] /= r2 # scale the first coefficient (mean value) return F
def obliquity(t): from mpmath import acos, cos, sqrt H = self.__H_time(t) hs = self.__hs_time(t) G = d_eval['G'] Gt = d_eval['\\tilde{G}'] Hts = d_eval['\\tilde{H}_\\ast'] Gxy = sqrt(G**2-H**2) Gtxys = sqrt(Gt**2-(Hts-H)**2) retval = (Gxy*Gtxys*cos(hs)+H*(Hts-H))/(G*Gt) return acos(retval)
def __init__(self,params): import sympy from mpmath import mpf, sqrt, cos from copy import deepcopy self.__set_original_H() # Set up constants. self.__eps_val = (1./mpf(299792458.))**2 self.__GG_val = mpf(6.673E-11) # Setup names. names = ['m2','r2','rot2','r1','rot1','i_a','ht','a','e','i','h'] if not all([s in params for s in names]): raise ValueError('invalid set of parameters') # Convert all the values to mpf and introduce convenience shortcuts. m2, r2, rot2, r1, rot1, i_a, ht_in, a, e, i, h_in = [mpf(params[s]) for s in names] L_in = sqrt(self.__GG_val * m2 * a) G_in = L_in * sqrt(1. - e**2) H_in = G_in * cos(i) Gt_in = (2 * r1**2 * rot1) / 5 Ht_in = Gt_in * cos(i_a) Hts_in = H_in + Ht_in hs_in = h_in - ht_in Gxy_in = sqrt(G_in**2 - H_in**2) Gtxys_in = sqrt(Gt_in**2 - Ht_in**2) J2 = (2 * m2 * r2**2 * rot2) / 5 II_1 = mpf(5) / (2 * r1**2) # Evaluation dictionary. eval_names = [sympy.Symbol(s) for s in ['L','G','H','\\tilde{G}','\\tilde{H}_\\ast','h_\\ast','m_2','\\mathcal{G}','J_2',\ '\\varepsilon','\\mathcal{I}_1','\\tilde{h}','g']] eval_values = [sympy.Float(x) for x in [L_in,G_in,H_in,Gt_in,Hts_in,hs_in,m2,self.__GG_val,J2,self.__eps_val,II_1,ht_in,0]] d_eval = dict(zip(eval_names,eval_values)) self.__init_d_eval = deepcopy(d_eval) def diff_f(x,_): from sympy import Symbol H = x[0] hs = x[2] d_eval[Symbol('H')] = H d_eval[Symbol('h_\\ast')] = hs return [d.evalf(subs = d_eval) for d in self.__diffs] self.__diff_f = diff_f
def ExactIntegrationOfSinusKernel(t, a = None, b = None): with precision(300): if a == None and b == None: return 0.5 * math.pi * math.sqrt(t) * (mpmath.angerj(0.5, t) - mpmath.angerj(-0.5, t)) if a == None and b != None: a = t elif b == None: b = 0. mpmath.mp.pretty = True pi = mpmath.mp.pi pi = +pi fcos = mpmath.fresnelc fsin = mpmath.fresnels arg_a = mpmath.sqrt(2 * (t - a) / mpmath.mp.pi) arg_b = mpmath.sqrt(2 * (t - b) / mpmath.mp.pi) return mpmath.sqrt(2 * mpmath.mp.pi) * ((fsin(arg_b) - fsin(arg_a)) * mpmath.cos(t) + (fcos(arg_a) - fcos(arg_b)) * mpmath.sin(t))
def rotate(self, identifier, angles, step=1): ang_num = 2*math.pi/360 rotateZ = [math.cos(angles[0]*ang_num),-math.sin(angles[0]*ang_num),0,math.sin(angles[0]*ang_num),math.cos(angles[0]*ang_num),0,0,0,1] rotateY = [math.cos(angles[1]*ang_num),0,-math.sin(angles[1]*ang_num),0,1,0,math.sin(angles[1]*ang_num),0,math.cos(angles[1]*ang_num)] rotateX = [1,0,0,0,math.cos(angles[2]*ang_num),-math.sin(angles[2]*ang_num),0,math.sin(angles[2]*ang_num),math.cos(angles[2]*ang_num)] antirotateZ = [math.cos(-angles[0]*ang_num),-math.sin(-angles[0]*ang_num),0,math.sin(-angles[0]*ang_num),math.cos(-angles[0]*ang_num),0,0,0,1] antirotateY = [math.cos(-angles[1]*ang_num),0,-math.sin(-angles[1]*ang_num),0,1,0,math.sin(-angles[1]*ang_num),0,math.cos(-angles[1]*ang_num)] antirotateX = [1,0,0,0,math.cos(-angles[2]*ang_num),-math.sin(-angles[2]*ang_num),0,math.sin(-angles[2]*ang_num),math.cos(-angles[2]*ang_num)] #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateZ)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateZ)) #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateY)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateY)) #self.command("transform "+identifier+""+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(rotateX)) self.command("transform "+identifier+"."+str(step+1)+"{ {%s %s %s} {%s %s %s} {%s %s %s} }"%tuple(antirotateX)) for i in range(0,3): self.orientation[i] += angles[i]
T0 = time.clock() THk = [] N2 , a2 = N**2 , a**2 k1 = r2*mpm.pi/Lx for ki in range(Nk): k = k1*mpm.mpf(ki) k2 = k**2 PHI = a2*(k2+l**2) + N2 tmp = mpm.sqrt(PHI**2 - r4*a2*k2*N2) PSIs2 = PHI + tmp PSIg2 = PHI - tmp den = r2*tmp Os = mpm.sqrt(PSIs2/r2) Og = mpm.sqrt(PSIg2/r2) theta = THk0[ki] \ * ( (mpm.mpf(2)*N2-PSIg2)/den * mpm.cos(Os*t) \ +(PSIs2-mpm.mpf(2)*N2)/den * mpm.cos(Og*t) ) THk.append(theta) TH = invFourier((xi-U*t+(Lx/r2-xc) for xi in x),THk) T1 = time.clock() print('Computation time: %f'%(T1-T0)) py.figure(3) py.plot( \ [float(xi+xc) for xi in x] , \ [float(ti) for ti in TH0], \ 'k-', label='initial condition') py.plot( \ [float(xi+Lx/r2) for xi in x] , \
def test_rationalize(): from mpmath import cos, pi, mpf assert rationalize(cos(pi/3)) == Rational(1, 2) assert rationalize(mpf("0.333333333333333")) == Rational(1, 3) assert rationalize(mpf("-0.333333333333333")) == Rational(-1, 3) assert rationalize(pi, maxcoeff = 250) == Rational(355, 113)
def ftot(t): return mp.cos(mp.cos(t)) * mp.sin(t) * mp.exp(1j * omega * mp.sin(t))
def test_rationalize(): from mpmath import cos, pi, mpf assert rationalize(cos(pi/3)) == sympify("1/2") assert rationalize(mpf("0.333333333333333")) == sympify("1/3") assert rationalize(mpf("-0.333333333333333")) == sympify("-1/3") assert rationalize(pi, maxcoeff = 250) == sympify("355/113")
# generate the cordic luts import mpmath, operator mpmath.mp.prec = 100 tangents = [mpmath.mpf(0.5) ** i for i in range(0, 61)] angles = [mpmath.atan(tan) for tan in tangents] circle_fracs = [angle / (mpmath.pi / 2) for angle in angles] # To speed up the cordic function, we can ignore fractions that are too # small circle_fracs = [cf for cf in circle_fracs if cf >= mpmath.mpf(0.5) ** (frac_bits + 2)] cordic_lut = [decimal.Decimal(str(c)) for c in circle_fracs] ps = [mpmath.cos(angle) for angle in angles] p = decimal.Decimal(str(reduce(operator.mul, ps))) cordic_p = decimal_to_fix_extrabits(p, internal_frac_bits) with args["lutfile"] as f: lutc = "#ifndef LUT_H\n" lutc += "#define LUT_H\n" lutc += "\n" lutc += '#include "base.h"\n' lutc += '#include "internal.h"\n' lutc += "\n" lutc += make_c_internal_define_lut(internal_inv_integer_lut, "INT_INV_LUT", "LUT_int_inv_integer") lutc += "\n" lutc += make_c_internal_defines(ln_coef_lut, "FIX_LN_COEF") lutc += "\n" lutc += make_c_internal_defines(log2_coef_lut, "FIX_LOG2_COEF") lutc += "\n"
TEST_YELLOW = pygame.Color(255, 0, 255, 255)#-16711681 TEST_BLUE = pygame.Color(0, 0, 255, 255)#-65536 #Visibility flags SHOW_ALL = 0 ONLY_SHOW_EXPOSED = 1 #135 degrees THETA = 3 * mp.pi / 4 #Isometric Unprojection UNPROJECT = mp.matrix([[1, 0, 0], [0, -1, 0], #NOTE: the y coordinate has to be inverted because my [0, 0, 1]]) #grid coordinates are a bit weird UNPROJECT *= mp.matrix([[ mp.cos(THETA), mp.sin(THETA), 0], [-mp.sin(THETA), mp.cos(THETA), 0], [ 0, 0, 1]]) UNPROJECT *= mp.matrix([[1, 0, 0], [0, 2, 0], [0, 0, 1]]) class OutOfIt(Exception): def __init__(self, msg, value): self.msg = msg self.value = value def __repr__(self):
# coding: utf-8 # In[1]: import mpmath import random # In[4]: scurve_1=lambda x:x scurve_inf=lambda x:0.5*(1-mpmath.cos(x*mpmath.pi)) class WrapNoise: def __init__(self, kappa=0.001, frequency=1.0, scurve=scurve_inf, seed=0): self._kappa = mpmath.mpf(kappa) self._period = 1.0/self._kappa self.frequency = frequency self._tau = 2*mpmath.pi self._seed = seed self._rng = random.Random(self._seed) self.scurve = scurve self.initialise_cache() def scale_t(self,t): return t*self.frequency def tau(self): return self._tau def initialise_cache(self): self._angle_cache = {} self._wrap_cache = {}
def cart_state(self,tau): from mpmath import cos, sin xi,eta,phi = self.state(tau) return xi*eta*cos(phi),xi*eta*sin(phi),(xi**2 - eta**2)/2
def cos(op): op = convertToRadians(op) return mpmath.cos(op)
def __set_params(self,d): from copy import deepcopy from mpmath import mpf, sqrt, polyroots, cos, acos, pi, mp from weierstrass_elliptic import weierstrass_elliptic as we names = ['m2','r2','rot2','r1','rot1','i_a','ht','a','e','i','h'] if not all([s in d for s in names]): raise ValueError('invalid set of parameters') # Convert all the values to mpf and introduce convenience shortcuts. m2, r2, rot2, r1, rot1, i_a, ht_in, a, e, i, h_in = [mpf(d[s]) for s in names] L_in = sqrt(self.__GG_val * m2 * a) G_in = L_in * sqrt(1. - e**2) H_in = G_in * cos(i) Gt_in = (2 * r1**2 * rot1) / 5 Ht_in = Gt_in * cos(i_a) Hts_in = H_in + Ht_in hs_in = h_in - ht_in Gxy_in = sqrt(G_in**2 - H_in**2) Gtxys_in = sqrt(Gt_in**2 - Ht_in**2) J2 = (2 * m2 * r2**2 * rot2) / 5 II_1 = mpf(5) / (2 * r1**2) # Evaluation dictionary. eval_names = ['L','G','H','\\tilde{G}','\\tilde{H}_\\ast','h_\\ast','\\tilde{G}_{xy\\ast}','m_2','\\mathcal{G}','J_2','G_{xy}',\ '\\varepsilon','\\mathcal{I}_1'] eval_values = [L_in,G_in,H_in,Gt_in,Hts_in,hs_in,Gtxys_in,m2,self.__GG_val,J2,Gxy_in,self.__eps_val,II_1] d_eval = dict(zip(eval_names,eval_values)) # Evaluate Hamiltonian with initial conditions. HHp_val = self.__HHp.trim().evaluate(d_eval) # Add the value of the Hamiltonian to the eval dictionary. d_eval['\\mathcal{H}^\\prime'] = HHp_val # Evaluate g2 and g3. g2_val, g3_val = self.__g2.trim().evaluate(d_eval), self.__g3.trim().evaluate(d_eval) # Create the Weierstrass object. wp = we(g2_val,g3_val) # Store the period. self.__wp_period = wp.periods[0] # Now let's find the roots of the quartic polynomial. # NOTE: in theory here we could use the exact solution for the quartic. p4coeffs = [t[0] * t[1].trim().evaluate(d_eval) for t in zip([1,4,6,4,1],self.__f4_cf)] p4roots, err = polyroots(p4coeffs,error = True, maxsteps = 1000) # Find a reachable root. Hr, H_max, n_lobes, lobe_idx = self.__reachable_root(p4roots,H_in) # Determine t_r t_r = self.__compute_t_r(n_lobes,lobe_idx,H_in,Hr,d_eval,p4roots,p4coeffs[0]) # Now evaluate the derivatives of the polynomial. We will need to replace H_in with Hr in the eval dict. d_eval['H'] = Hr _, f4Hp, f4Hpp, _, _ = self.__f4 f4p_eval = f4Hp.trim().evaluate(d_eval) f4pp_eval = f4Hpp.trim().evaluate(d_eval) # Build and store the expression for H(t). self.__H_time = lambda t: Hr + f4p_eval / (4 * (wp.P(t - t_r) - f4pp_eval / 24)) # H will not be needed any more, replace with H_r del d_eval['H'] d_eval['H_r'] = Hr # Inject the invariants and the other two constants into the evaluation dictionary. d_eval['g_2'] = g2_val d_eval['g_3'] = g3_val d_eval['A'] = f4p_eval / 4 d_eval['B'] = f4pp_eval / 24 # Verify the formulae in solutions.py self.__verify_solutions(d_eval) # Assuming g = 0 as initial angle. self.__g_time = spin_gr_theory.__get_g_time(d_eval,t_r,0.) self.__hs_time = spin_gr_theory.__get_hs_time(d_eval,t_r,hs_in) self.__ht_time = spin_gr_theory.__get_ht_time(d_eval,t_r,ht_in) def obliquity(t): from mpmath import acos, cos, sqrt H = self.__H_time(t) hs = self.__hs_time(t) G = d_eval['G'] Gt = d_eval['\\tilde{G}'] Hts = d_eval['\\tilde{H}_\\ast'] Gxy = sqrt(G**2-H**2) Gtxys = sqrt(Gt**2-(Hts-H)**2) retval = (Gxy*Gtxys*cos(hs)+H*(Hts-H))/(G*Gt) return acos(retval) self.__obliquity_time = obliquity def spin_vector(t): import numpy ht = self.__ht_time(t) H = self.__H_time(t) G = d_eval['G'] Gt = d_eval['\\tilde{G}'] Hts = d_eval['\\tilde{H}_\\ast'] Gtxys = sqrt(Gt**2-(Hts-H)**2) return numpy.array([x.real for x in [Gtxys*sin(ht),-Gtxys*cos(ht),Hts-H]]) self.__spin_vector_time = spin_vector def orbit_vector(t): import numpy ht = self.__ht_time(t) hs = self.__hs_time(t) h = hs + ht H = self.__H_time(t) G = d_eval['G'] Gxy = sqrt(G**2-H**2) return numpy.array([x.real for x in [Gxy*sin(h),-Gxy*cos(h),H]]) self.__orbit_vector_time = orbit_vector # Store the params of the system. self.__params = dict(zip(names,[mpf(d[s]) for s in names])) # Final report. rad_conv = 360 / (2 * pi()) print("\x1b[31mAccuracy in the identification of the poly roots:\x1b[0m") print(err) print("\n\x1b[31mPeriod (years):\x1b[0m") print(wp.periods[0] / (3600*24*365)) print("\n\x1b[31mMin and max orbital inclination (deg):\x1b[0m") print(acos(Hr/G_in) * rad_conv,acos(H_max/G_in) * rad_conv) print("\n\x1b[31mMin and max axial inclination (deg):\x1b[0m") print(acos((Hts_in - Hr)/Gt_in) * rad_conv,acos((Hts_in-H_max)/Gt_in) * rad_conv) print("\n\x1b[31mNumber of lobes:\x1b[0m " + str(n_lobes)) print("\n\x1b[31mLobe idx:\x1b[0m " + str(lobe_idx)) # Report the known results for simplified system for comparison. H = H_in HHp,G,L,GG,eps,m2,Hts,Gt,J2 = [d_eval[s] for s in ['\\mathcal{H}^\\prime','G','L','\\mathcal{G}',\ '\\varepsilon','m_2','\\tilde{H}_\\ast','\\tilde{G}','J_2']] print("\n\x1b[31mEinstein (g):\x1b[0m " + str((3 * eps * GG**4 * m2**4/(G**2*L**3)))) print("\n\x1b[31mLense-Thirring (g):\x1b[0m " + str(((eps * ((-6*H*J2*GG**4*m2**3)/(G**4*L**3)+3*GG**4*m2**4/(G**2*L**3)))))) print("\n\x1b[31mLense-Thirring (h):\x1b[0m " + str((2*eps*J2*GG**4*m2**3/(G**3*L**3)))) # These are the Delta_ constants of quasi-periodicity. f_period = self.wp_period print("\n\x1b[31mDelta_g:\x1b[0m " + str(self.g_time(f_period) - self.g_time(0))) print("\n\x1b[31mg_rate:\x1b[0m " + str((self.g_time(f_period) - self.g_time(0))/f_period)) Delta_hs = self.hs_time(f_period) - self.hs_time(0) print("\n\x1b[31mDelta_hs:\x1b[0m " + str(Delta_hs)) print("\n\x1b[31mhs_rate:\x1b[0m " + str(Delta_hs/f_period)) Delta_ht = self.ht_time(f_period) - self.ht_time(0) print("\n\x1b[31mDelta_ht:\x1b[0m " + str(Delta_ht)) print("\n\x1b[31mht_rate:\x1b[0m " + str(Delta_ht/f_period)) print("\n\x1b[31mDelta_h:\x1b[0m " + str(Delta_ht+Delta_hs)) print("\n\x1b[31mh_rate:\x1b[0m " + str((Delta_ht+Delta_hs)/f_period)) print("\n\n")
def test_odefun_sinc_large(): mp.dps = 15 # Sinc function; test for large x f = sinc g = odefun(lambda x, y: [(cos(x)-y[0])/x], 1, [f(1)], tol=0.01, degree=5) assert abs(f(100) - g(100)[0])/f(100) < 0.01
def ftot(t): cos2t = mp.cos(t) ** 2 return mp.exp(-z1 / cos2t) / cos2t * mp.exp(1j * omega * mp.cos(t - beta) / cos2t)
def solveCubicPolynomial( a, b, c, d ): if mp.dps < 50: mp.dps = 50 if a == 0: return solveQuadraticPolynomial( b, c, d ) f = fdiv( fsub( fdiv( fmul( 3, c ), a ), fdiv( power( b, 2 ), power( a, 2 ) ) ), 3 ) g = fdiv( fadd( fsub( fdiv( fmul( 2, power( b, 3 ) ), power( a, 3 ) ), fdiv( fprod( [ 9, b, c ] ), power( a, 2 ) ) ), fdiv( fmul( 27, d ), a ) ), 27 ) h = fadd( fdiv( power( g, 2 ), 4 ), fdiv( power( f, 3 ), 27 ) ) # all three roots are the same if h == 0: x1 = fneg( root( fdiv( d, a ), 3 ) ) x2 = x1 x3 = x2 # two imaginary and one real root elif h > 0: r = fadd( fneg( fdiv( g, 2 ) ), sqrt( h ) ) if r < 0: s = fneg( root( fneg( r ), 3 ) ) else: s = root( r, 3 ) t = fsub( fneg( fdiv( g, 2 ) ), sqrt( h ) ) if t < 0: u = fneg( root( fneg( t ), 3 ) ) else: u = root( t, 3 ) x1 = fsub( fadd( s, u ), fdiv( b, fmul( 3, a ) ) ) real = fsub( fdiv( fneg( fadd( s, u ) ), 2 ), fdiv( b, fmul( 3, a ) ) ) imaginary = fdiv( fmul( fsub( s, u ), sqrt( 3 ) ), 2 ) x2 = mpc( real, imaginary ) x3 = mpc( real, fneg( imaginary ) ) # all real roots else: j = sqrt( fsub( fdiv( power( g, 2 ), 4 ), h ) ) k = acos( fneg( fdiv( g, fmul( 2, j ) ) ) ) if j < 0: l = fneg( root( fneg( j ), 3 ) ) else: l = root( j, 3 ) m = cos( fdiv( k, 3 ) ) n = fmul( sqrt( 3 ), sin( fdiv( k, 3 ) ) ) p = fneg( fdiv( b, fmul( 3, a ) ) ) x1 = fsub( fmul( fmul( 2, l ), cos( fdiv( k, 3 ) ) ), fdiv( b, fmul( 3, a ) ) ) x2 = fadd( fmul( fneg( l ), fadd( m, n ) ), p ) x3 = fadd( fmul( fneg( l ), fsub( m, n ) ), p ) return [ chop( x1 ), chop( x2 ), chop( x3 ) ]
def eval(self, z): return mpmath.cos(z)