def calculate_angles(Input_Cords): # Constants scalling_const = np.sqrt(.3) f = 195 * scalling_const t = 375 * scalling_const f = f * (10 ^ -3) t = t * (10 ^ -3) angle_list = [] for coord in Input_Cords: X = (coord[0]) * (10 ^ -3) Y = (-coord[1]) * (10 ^ -3) H = np.sqrt(math.power(X, 2) + math.power(Y, 2)) alpha = math.acos( (math.power(t, 2) - math.power(f, 2) - math.power(H, 2)) / (2 * f * H)) beta = math.atan(Y / X) T_1 = alpha - beta + np.pi T_2 = math.acos( (math.power(H, 2) - math.power(f, 2) - math.power(t, 2)) / (2 * f * t)) + np.pi angles = [T_1, T_2] angle_list.append(angles) return angle_list
def calAngles(target, segments): x = target.x y = target.y z = target.z s1 = segments[0] s2 = segments[1] s3 = segments[2] theta0 = atan(y / x) theta1 = acos((s1**2 - z**2 + (s1 - z)**2)/(2*s1*sqrt(x**2 + y**2 + (s1 - z)**2))) \ + acos((s2**2 - s3**2 + x**2 + y**2 + (s1 - z)**2)/(2*s2*sqrt(x**2 + y**2 + (s1 - z)**2))) theta2 = acos((s2**2 + s3**2 - x**2 - y**2 - (s1 - z)**2) / (2 * s2 * s3)) return [theta0, theta1, theta2]
def get_ang(pos_1, pos_2, pos_3): mmp.mp.dps = 30 x1, y1, z1 = get_each(pos_1) x2, y2, z2 = get_each(pos_2) x3, y3, z3 = get_each(pos_3) cosb = (x1 * x2 + y1 * y2 + z1 * z2)/(mmp.sqrt(x1**2 + y1**2 + z1**2) * mmp.sqrt(x2**2 + y2**2 + z2**2)) cosc = (x1 * x3 + y1 * y3 + z1 * z3)/(mmp.sqrt(x1**2 + y1**2 + z1**2) * mmp.sqrt(x3**2 + y3**2 + z3**2)) cosa = (x3 * x2 + y3 * y2 + z3 * z2)/(mmp.sqrt(x3**2 + y3**2 + z3**2) * mmp.sqrt(x2**2 + y2**2 + z2**2)) sinb = mmp.sin(mmp.acos(cosb)) sinc = mmp.sin(mmp.acos(cosc)) cosA = (cosa - cosb * cosc) /(sinb * sinc) return mmp.acos(cosA)
def Pinv(self, P): from mpmath import ellipf, sqrt, asin, acos, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: P = -P if Delta > 0: m = (e2 - e3) / (e1 - e3) retval = (1 / sqrt(e1 - e3)) * ellipf( asin(sqrt((e1 - e3) / (P - e3))), m=m) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert (H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) retval = 1 / (2 * sqrt(H2)) * ellipf(acos( (e2 - P + H2) / (e2 - P - H2)), m=m) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = 1 / sqrt(P) else: c = e1 / 2 retval = (1 / sqrt(3 * c)) * asin(sqrt((3 * c) / (P + c))) if self.__ng3: retval /= mpc(0, 1) alpha, beta, _, _ = self.reduce_to_fpp(retval) T1, T2 = self.periods return T1 * alpha + T2 * beta
def ellipse(r, a, incl): """Equation of an ellipse, reusing the definition of cos_gamma. This equation can be used for calculations in the Newtonian limit (large P = b, small a) or to visualize the equatorial plane.""" g = mpmath.acos(cos_gamma(a, incl)) b_ = r * mpmath.sin(g) return b_
def Pinv(self,P): from mpmath import ellipf, sqrt, asin, acos, mpc, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: P = -P if Delta > 0: m = (e2 - e3) / (e1 - e3) retval = (1 / sqrt(e1 - e3)) * ellipf(asin(sqrt((e1 - e3)/(P - e3))),m=m) elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) retval = 1 / (2 * sqrt(H2)) * ellipf(acos((e2-P+H2)/(e2-P-H2)),m=m) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = 1 / sqrt(P) else: c = e1 / 2 retval = (1 / sqrt(3 * c)) * asin(sqrt((3 * c)/(P + c))) if self.__ng3: retval /= mpc(0,1) alpha, beta, _, _ = self.reduce_to_fpp(retval) T1, T2 = self.periods return T1 * alpha + T2 * beta
def error(coefs, progress=True): (a, b, c) = coefs xs = (x / mp.mpf(4096) for x in range(-4096, 4097)) err = max(fabs(acos(x) - f(x, a, b, c)) for x in xs) if progress: print('(a, b, c, d): ({}, {}, {}, {})'.format(a, b, c, d(a, b, c))) print('evaluated error: ', err) print() return float(err)
def get_offset_five(positions_old, positions, ligand_length): vec_a = (positions[ligand_length+(len(positions)-len(positions_old))+1]-positions[ligand_length+(len(positions)-len(positions_old))]) vec_b = (positions_old[ligand_length+1]-positions_old[ligand_length]) alpha = math.acos(sum([alem.value_in_unit(unit.angstroms)*blem.value_in_unit(unit.angstroms) for alem, blem in zip(vec_a,vec_b)])/(np.linalg.norm(vec_a.value_in_unit(unit.angstroms))*np.linalg.norm(vec_b.value_in_unit(unit.angstroms)))) alpha_t = 0. #alpha_t = math.pi-113.3*math.pi/360. d_alpha = alpha_t-alpha axis = cross(vec_a.value_in_unit(unit.angstroms),vec_b.value_in_unit(unit.angstroms))/np.linalg.norm(cross(vec_a.value_in_unit(unit.angstroms),vec_b.value_in_unit(unit.angstroms))) offset = positions_old[-1]-positions[len(positions_old)-1] return d_alpha, axis, offset, vec_a, vec_b
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 equiv_cos(x, range1, range2, radians=None, degrees=None, accuracy=2): mpmath.mp.dps = accuracy + 1 range1, range2 = TrigEquivAngle.deg_or_rad([range1, range2], degrees) firstCosAngle = mpmath.acos(x) secondCosAngle = 2 * mpmath.pi - firstCosAngle angles = TrigEquivAngle.create_equiv_angle_list( [firstCosAngle, secondCosAngle], range1, range2, 2 * mpmath.pi) return (TrigEquivAngle.clean_angles_rad_deg(angles, radians, degrees, accuracy))
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 q_eit_standing_wave(Delta, Deltac, Omega, g1d, periodLength, phaseShift): if Delta == Deltac: return 0 gprime = 1 - g1d kd = pi / periodLength Mcell = eye(2) for i in range(periodLength): OmegaAtThisSite = Omega * cos(kd * i + pi * phaseShift) beta3 = (g1d * (Delta - Deltac)) / ( (-2.0j * Delta + gprime) * (Delta - Deltac) + 2.0j * OmegaAtThisSite**2) M3 = matrix([[1 - beta3, -beta3], [beta3, 1 + beta3]]) Mf = matrix([[exp(1j * kd), 0], [0, exp(-1j * kd)]]) Mcell = Mf * M3 * Mcell ret = (1.0 / periodLength) * acos(-0.5 * (Mcell[0, 0] + Mcell[1, 1])) return ret
def getCircleIntersectionTerm( radius1, radius2, separation ): distance = fdiv( fadd( fsub( power( separation, 2 ), power( radius1, 2 ) ), power( radius2, 2 ) ), fmul( 2, separation ) ) #print( 'radius1', radius1 ) #print( 'radius2', radius2 ) #print( 'distance', distance ) #print( 'radius1 - distance', fsub( radius1, distance ) ) #print( 'radius1^2 - distance^2', fsub( power( radius1, 2 ), power( distance, 2 ) ) ) #print( ) if power( distance, 2 ) > power( radius1, 2 ): return fmul( power( radius1, 2 ), fdiv( pi, 2 ) ) return fsub( fmul( power( radius1, 2 ), acos( fdiv( distance, radius1 ) ) ), fmul( distance, sqrt( fsub( power( radius1, 2 ), power( distance, 2 ) ) ) ) )
def calc_theta(mino_t, ups_theta, qz0, zp, zm, En, aa): """ theta in terms of Mino time Parameters: mino_t (float): Mino time ups_theta (float): Mino theta frequency qz0 (float): inital polar phase zp (float): polar root zm (float): polar root En (float): energy aa (float): spin Returns: theta (float) """ eta = ups_theta * mino_t + qz0 return acos(calc_zq(eta, zp, zm, En, aa))
def subspace_angle_V_M_mp(mu, lam, dps=100): r"""Multiprecision implementation computing the subspace angle between V(mu) and M(lam) """ n = len(mu) lam = np.atleast_1d(lam) m = len(lam) with mp.workdps(dps): mu = mp.matrix(mu) lam = mp.matrix(lam) # Construct the Cauchy mass matrix #M = mp.zeros(n,n) #for i,j in product(range(n), range(n)): # M[i,j] = (mu[i] + mu[j].conjugate())**(-1) #ewL, QL = mp.eighe(M) ewL, QL = cauchy_eigen(mu, dps) # Construct the right hand side Mhat matrix Mhat = mp.zeros(2 * m, 2 * m) for i, j in product(range(m), range(m)): Mhat[i, j] = (-lam[i] - lam[j].conjugate())**(-1) Mhat[i, m + j] = (-lam[i] - lam[j].conjugate())**(-2) Mhat[m + i, j] = (-lam[i] - lam[j].conjugate())**(-2).conjugate() Mhat[m + i, m + j] = 2 * (-lam[i] - lam[j].conjugate())**(-3) # Construct the interior matrix A = mp.zeros(n, 2 * m) for i, j in product(range(n), range(m)): A[i, j] = (mu[i] - lam[j])**(-1) A[i, m + j] = (mu[i] - lam[j])**(-2) ewR, QR = mp.eighe(Mhat) AA = mp.diag([1 / mp.sqrt(ewL[i]) for i in range(n)]) * (QL.H * A * QR) * mp.diag( [1 / mp.sqrt(ewR[i]) for i in range(2 * m)]) U, s, VH = mp.svd(AA) phi = np.array([float(mp.acos(si)) for si in s]) return phi
def fpaa_oracle(qc, q, n, clauses, oracle, index): theta = math.pi / clauses delta = pow(2, -0.5 * pow(n, 2)) / 2 _lambda = pow(math.sin(theta), 2) / 4 + pow(1 / 2 - math.cos(theta) / 2, 2) L = int(math.ceil(2 * math.log(2 / delta) / math.sqrt(_lambda))) gamma = mpmath.cos(mpmath.acos(1 / delta) / L) qc.barrier() A_matrix(qc, q, n, clauses, oracle, theta) qc.barrier() for k in range(1, L): alpha = abs(2 * mpmath.acot( mpmath.tan(2 * math.pi * (k) / L) * mpmath.sqrt(1 - 1 / pow(gamma, -2)))) beta = -abs(2 * mpmath.acot( mpmath.tan(2 * math.pi * (L - (k - 1)) / L) * mpmath.sqrt(1 - 1 / pow(gamma, -2)))) qc.h(q[n]) U_matrix(qc, q, n, beta) qc.h(q[n]) Adgr_matrix(qc, q, n, clauses, oracle, theta) U_matrix(qc, q, n, alpha) A_matrix(qc, q, n, clauses, oracle, theta) qc.barrier() qc.h(q[n]) qc.barrier() qc.x(q[n]) qc.x(q[n + 1]) qc.h(q[n + 1]) qc.cx(q[n], q[n + 1]) qc.h(q[n + 1]) qc.x(q[n + 1]) qc.x(q[n])
def eq13(_P: float, _r: float, _a: float, M: float, incl: float, n: int = 0, tol=10e-6) -> float: """Relation between radius (where photon was emitted in accretion disk), a and P. P can be converted to b, yielding the polar coordinates (b, a) on the photographic plate""" zinf = zeta_inf(_P, M) Qvar = Q(_P, M) m_ = k2( _P, M ) # modulus of the elliptic integrals. mpmath takes m = k² as argument. ellinf = F(zinf, m_) # Elliptic integral F(zinf, k) g = mpmath.acos(cos_gamma(_a, incl)) # real # Calculate the argument of sn (mod is m = k², same as the original elliptic integral) # WARNING: paper has an error here: \sqrt(P / Q) should be in denominator, not numerator # There's no way that \gamma and \sqrt(P/Q) can end up on the same side of the division if n: # higher order image ellK = K(m_) # calculate complete elliptic integral of mod m = k² ellips_arg = (g - 2. * n * np.pi) / ( 2. * mpmath.sqrt(_P / Qvar)) - ellinf + 2. * ellK else: # direct image ellips_arg = g / (2. * mpmath.sqrt(_P / Qvar)) + ellinf # complex # sn is an Jacobi elliptic function: elliptic sine. ellipfun() takes 'sn' # as argument to specify "elliptic sine" and modulus m=k² sn = mpmath.ellipfun('sn', ellips_arg, m=m_) sn2 = sn * sn # sn2 = float(sn2.real) term1 = -(Qvar - _P + 2. * M) / (4. * M * _P) term2 = ((Qvar - _P + 6. * M) / (4. * M * _P)) * sn2 s = 1. - _r * (term1 + term2) # solve this for zero return s
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 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.acos(z)
def sarkar_embedding(tree, root, **kwargs): ''' Embed a tree in the Poincare disc using Sarkar's algorithm from "Low Distortion Delaunay Embedding of Trees in Hyperbolic Plane. Args: tree (networkx.Graph) : The tree represented with int node labels. Weighted trees should have the edge attribute "weight" root (int): The node to use as the root of the embedding Keyword Args: weighted (bool): True if the tree is weighted (default True) tau (float): the scaling factor for distances. By default it is calculated based on statistics of the tree. epsilon (float): parameter >0 controlling distortion bound (default 0.1). precision (int): number of bits of precision to use. By default it is calculated based on tau and epsilon. Returns: size N x 2 mpmath.matrix containing the coordinates of embedded nodes ''' eps = kwargs.get("epsilon",0.1) weighted = kwargs.get("weighted", True) tau = kwargs.get("tau") max_deg = max(tree.degree)[1] if tau is None: tau = (1+eps)/eps * mpm.log(2*max_deg/ mpm.pi) prc = kwargs.get("precision") if prc is None: prc = _embedding_precision(tree,root,eps) mpm.mp.dps = prc n = tree.order() emb = mpm.zeros(n,2) place = [] # place the children of root for i, v in enumerate(tree[root]): if weighted: r = mpm.tanh( tau*tree[root][v]["weight"]) else: r = mpm.tanh(tau) theta = 2*i*mpm.pi / tree.degree[root] emb[v,0] = r*mpm.cos(theta) emb[v,1] = r*mpm.sin(theta) place.append((root,v)) # TODO parallelize this while place: u, v = place.pop() # u is the parent of v p, x = emb[u,:], emb[v,:] rp = poincare_reflect0(x, p, precision=prc) arg = mpm.acos(rp[0]/mpm.norm(rp)) if rp[1] < 0: arg = 2*mpm.pi - arg theta = 2*mpm.pi / tree.degree[v] i=0 for w in tree[v]: if w == u: continue i+=1 if weighted: r = mpm.tanh(tau*tree[v][w]["weight"]) else: r = mpm.tanh(tau) w_emb = r * mpm.matrix([mpm.cos(arg+theta*i),mpm.sin(arg+theta*i)]).T w_emb = poincare_reflect0(x, w_emb, precision=prc) emb[w,:] = w_emb place.append((v,w)) return emb
from units import * from copy import copy def sqrt(x): if hasattr(x,'unit'): return math.sqrt(x.number) | x.unit**0.5 return math.sqrt(x) #trigonometric convenience functions which are "unit aware" sin=lambda x: math.sin(1.*x) cos=lambda x: math.cos(1.*x) tan=lambda x: math.tan(1.*x) cot=lambda x: math.cot(1.*x) asin=lambda x: math.asin(x) | rad acos=lambda x: math.acos(x) | rad atan=lambda x: math.atan(x) | rad atan2=lambda x,y: math.atan2(x,y) | rad #~ cos=math.cos #~ sin=math.sin #~ tan=math.tan #~ cosh=math.cosh #~ sinh=math.sinh #~ tanh=math.tanh #~ acos=math.acos #~ asin=math.asin #~ atan=math.atan acosh=math.acosh asinh=math.asinh atanh=math.atanh
def fermat_length(a,x): F = mp.ellipf(mp.acos((0.5-x) / (0.5+x)), 0.5) return a*(F + sqrt(2*x*(4*x**2+1))) / sqrt(18)
def vector_angle(vec1, vec2): abs_vec1 = absolute(vec1) abs_vec2 = absolute(vec2) prod_12 = sum([alem*blem for alem,blem in zip(vec1, vec2)]) return math.acos(prod_12/(abs_vec1*abs_vec2))
def solveCubicPolynomial( a, b, c, d ): # pylint: disable=invalid-name ''' This function applies the cubic formula to solve a polynomial with coefficients of a, b, c and 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 ) ]
'root': ['primitive', [lambda x, y: mp.root(x, y[0]), None]], # y's root 'unitroots': ['primitive', [lambda x, y: Vector(mp.unitroots(x)), None]], # 'hypot': ['primitive', [lambda x, y: mp.hypot(x, y[0]), None]], # sqrt(x**2+y**2) # 'sin': ['primitive', [lambda x, y: mp.sin(x), None]], 'cos': ['primitive', [lambda x, y: mp.cos(x), None]], 'tan': ['primitive', [lambda x, y: mp.tan(x), None]], 'sinpi': ['primitive', [lambda x, y: mp.sinpi(x), None]], #sin(x * pi) 'cospi': ['primitive', [lambda x, y: mp.cospi(x), None]], 'sec': ['primitive', [lambda x, y: mp.sec(x), None]], 'csc': ['primitive', [lambda x, y: mp.csc(x), None]], 'cot': ['primitive', [lambda x, y: mp.cot(x), None]], 'asin': ['primitive', [lambda x, y: mp.asin(x), None]], 'acos': ['primitive', [lambda x, y: mp.acos(x), None]], 'atan': ['primitive', [lambda x, y: mp.atan(x), None]], 'atan2': ['primitive', [lambda x, y: mp.atan2(y[0], x), None]], 'asec': ['primitive', [lambda x, y: mp.asec(x), None]], 'acsc': ['primitive', [lambda x, y: mp.acsc(x), None]], 'acot': ['primitive', [lambda x, y: mp.acot(x), None]], 'sinc': ['primitive', [lambda x, y: mp.sinc(x), None]], 'sincpi': ['primitive', [lambda x, y: mp.sincpi(x), None]], 'degrees': ['primitive', [lambda x, y: mp.degrees(x), None]], #radian - >degree 'radians': ['primitive', [lambda x, y: mp.radians(x), None]], #degree - >radian # 'exp': ['primitive', [lambda x, y: mp.exp(x), None]], 'expj': ['primitive', [lambda x, y: mp.expj(x), None]], #exp(x*i) 'expjpi': ['primitive', [lambda x, y: mp.expjpi(x), None]], #exp(x*i*pi)
def arccos_degrees(x): """Return arccosine of x in degrees.""" return normalized_degrees_from_radians(acos(x))
def acos(op): expr = mpmath.acos(op) return convertFromRadians(expr)
def move(self, alpha, v, t): if alpha == 0: self.x1 += v * t self.x2 += v * t return reverse_alpha = False reverse_v = False alpha = mpmath.radians(alpha) if alpha < 0: alpha = -alpha reverse_alpha = True if v < 0: v = -v reverse_v = True R = self.l * mpmath.cot(alpha) + 0.5 * self.d # outer radius r = self.l * mpmath.cot(alpha) - 0.5 * self.d # inner radius w = v / R # angular velocity beta = w * t # angle that has been turned after the move viewed from the center of the circle assert (beta < mpmath.pi) # make sure it still forms a triangle theta = 0.5 * beta # the angle of deviation from the original orientation m = 2 * R * mpmath.sin(theta) # displacement of outer rear wheel n = 2 * r * mpmath.sin(theta) # displacement of inner rear wheel if not reverse_alpha and not reverse_v: delta_x1, delta_y1 = mpmath.cos(theta) * m, mpmath.sin(theta) * m delta_x2, delta_y2 = mpmath.cos(theta) * n, mpmath.sin(theta) * n elif reverse_alpha and not reverse_v: delta_x2, delta_y2 = mpmath.cos(theta) * m, -mpmath.sin(theta) * m delta_x1, delta_y1 = mpmath.cos(theta) * n, -mpmath.sin(theta) * n elif not reverse_alpha and reverse_v: delta_x1, delta_y1 = -mpmath.cos(theta) * m, mpmath.sin(theta) * m delta_x2, delta_y2 = -mpmath.cos(theta) * n, mpmath.sin(theta) * n else: delta_x2, delta_y2 = -mpmath.cos(theta) * m, -mpmath.sin(theta) * m delta_x1, delta_y1 = -mpmath.cos(theta) * n, -mpmath.sin(theta) * n delta_x1 = float(delta_x1) delta_y1 = float(delta_y1) delta_x2 = float(delta_x2) delta_y2 = float(delta_y2) # the current calculation is based on this relative reference system # we need to map this coordinate in the relative reference system back to the absolute system # use the dot product of the rear wheel line to find the rotation from the relative reference system to the absolute system if self.y1 != 0 or self.y2 != 10: # no rotation is needed bottom = np.sqrt(((self.x2 - self.x1) * (self.x2 - self.x1) + (self.y2 - self.y1) * (self.y2 - self.y1))) * 10 top = (self.y2 - self.y1) * 10 cosine_value = float(top / bottom) rotation = mpmath.acos(cosine_value) # print(rotation) if self.x1 < self.x2: # since arccos does not give direction, we need to do a check here rotation = -rotation # let A be the linear transformation that maps a relative referenced coordinate to an absolute referenced coordinate A = np.asarray( [[float(mpmath.cos(rotation)), float(-mpmath.sin(rotation))], [float(mpmath.sin(rotation)), float(mpmath.cos(rotation))]]) # then we map delta_1 and delta_2 to the absolute reference system relative_delta_1 = np.asarray([delta_x1, delta_y1]) relative_delta_2 = np.asarray([delta_x2, delta_y2]) absolute_delta_1 = np.matmul(A, relative_delta_1) absolute_delta_2 = np.matmul(A, relative_delta_2) delta_x1 = absolute_delta_1[0] delta_y1 = absolute_delta_1[1] delta_x2 = absolute_delta_2[0] delta_y2 = absolute_delta_2[1] # make vector addition in the absolute reference system self.x1 += delta_x1 self.x2 += delta_x2 self.y1 += delta_y1 self.y2 += delta_y2 dist = mpmath.sqrt((self.x1 - self.x2) * (self.x1 - self.x2) + (self.y2 - self.y1) * (self.y2 - self.y1)) assert abs(dist - self.d) <= self.d * 1e-4
def alpha(phi: float, incl: float): """Returns observer coordinate of photon given phi (BHF) and inclination (BHF)""" return mpmath.acos(cosAlpha(phi, incl))