def e_ratio(a, b, e, x): # Get S bt2 = mp.beta(a, b - 1.0) # Beta function bix = mp.betainc(a, b + 1.0, 0.0, e) # Incomplete Beta function hf = mp.hyp2f1(1.0, a, a + b - 1.0, -1.0) # 2F1, Gauss' hypergeometric function hfre = mp.re(hf) Sval = bix - x * bt2 * hfre # Get U c1 = mp.mpc(1.0 + a) c2 = mp.mpc(-b) c3 = mp.mpc(1.0) c4 = mp.mpc(2.0 + a) Uval = mp.appellf1(c1, c2, c3, c4, e, -e) Ure = mp.re(Uval) # Get P & Q Pval = mp.hyp2f1(a + 1.0, 1.0 - b, a + 2.0, e) # 2F1, Gauss' hypergeometric function Pre = mp.re(Pval) Qval = mp.hyp2f1(a + 1.0, 2.0 - b, a + 2.0, e) # 2F1, Gauss' hypergeometric function Qre = mp.re(Qval) # Get T Tval = ((e**(1.0 + a)) / (1.0 + a)) * (3.0 * Pre + 2.0 * Qre - Ure) Tval = Tval + 4.0 * Sval # Get Rval (ratio) Rval = 0.25 * (1.0 - e * e) * ( (1.0 - e)**(1.0 - b)) * (e**(1.0 - a)) * Tval return Rval
def e_ratio(a,b,e,x): # Get S bt2 = mp.beta(a,b-1.0) # Beta function bix = mp.betainc(a,b+1.0,0.0,e) # Incomplete Beta function hf = mp.hyp2f1(1.0,a,a+b-1.0,-1.0) # 2F1, Gauss' hypergeometric function hfre = mp.re(hf) Sval = bix - x*bt2*hfre # Get U c1 = mp.mpc(1.0 + a) c2 = mp.mpc(-b) c3 = mp.mpc(1.0) c4 = mp.mpc(2.0 + a) Uval = mp.appellf1(c1,c2,c3,c4,e,-e) Ure = mp.re(Uval) # Get P & Q Pval = mp.hyp2f1(a+1.0,1.0-b,a+2.0,e) # 2F1, Gauss' hypergeometric function Pre = mp.re(Pval) Qval = mp.hyp2f1(a+1.0,2.0-b,a+2.0,e) # 2F1, Gauss' hypergeometric function Qre = mp.re(Qval) # Get T Tval = ( (e**(1.0+a)) / (1.0+a) )*( 3.0*Pre + 2.0*Qre - Ure ) Tval = Tval + 4.0*Sval # Get Rval (ratio) Rval = 0.25*(1.0-e*e)*( (1.0-e)**(1.0-b) )*( e**(1.0-a) )*Tval return Rval
def next_upper_bracket(t, z_function): current_sign = np.sign( mp.re( z_function(t) ) ) next_sign = current_sign while current_sign == next_sign: t += 1 next_sign = np.sign( mp.re( z_function(t) ) ) return t
def one_side(x,y): m = ((-1 + x)*(1 + y))/((1 + x)*(-1 + y)) k = sqrt(m) u = asin(1/k) EE = ellipe(m) EF = re(ellipf(u,m)) n = (-1 + x)/(-1 + y) EPI = ellippi(n/m,1/m)/k #EPI = ellippi(n,u,m) return re(-(EE*(1 + x)*(-1 + y) + (x - y)*(EF + EPI*(x-y) + EF*y))/sqrt(((1 + x)*(1 - y))))
def v(x,t,s,b): """ inverse map of w(v) = x+i\tau --> x-t. """ # c is atrificial parameter for findroot. c = 10**(-9) if x>b: return j*mp.findroot(lambda y: re(w(j*y,s,b)-(x-t)), [-s/2+c,0-c],"bisect") elif x<-b: return j*mp.findroot(lambda y: re(w(j*y,s,b)-(x-t)), [0+c,s/2-c],"bisect") else: return 1/2+j*mp.findroot(lambda y: re(w(1/2+j*y,s,b)-(x-t)), 0)
def alpha(z, x, beta): """ Eq. (A4) from Ref[1] Note that 'x' here corresponds to 'chi = x/rho', and 'z' here corresponds to 'xi = z/2/rho' in the paper. """ arg1 = sqrt(2 * fabs(m(z, x, beta))) arg2 = -2 * (m(z, x, beta) + nu(x, beta)) arg3 = 2 * eta(z, x, beta) / arg1 if z < 0: return re(1 / 2 * (-arg1 + sqrt(fabs(arg2 + arg3)))) else: return re(1 / 2 * (arg1 + sqrt(fabs(arg2 - arg3))))
def FDoubleDisc(x1,x2,t,s,b): """ inside of log() for disconnected HEE. We take single interval subsystem A=[x1,x2]. This has very complicated minimizasion because the configuration of boundary surface Q varys by Hawking-Page transition. """ v1 = v(x1,t,s,b) v2 = v(x2,t,s,b) vb1 = vb(x1,t,s,b) vb2 = vb(x2,t,s,b) h1 = v1-vb1 hp1 = h1+j*s/2 hm1 = h1-j*s/2 h2 = v2-vb2 hp2 = h2+j*s/2 hm2 = h2-j*s/2 F = (pi**(-4))*Dw(v1,s,b)*(-Dw(-vb1,s,b))*Dw(v2,s,b)*(-Dw(-vb2,s,b)) if s<1: g1 = min([re(sinh(pi*hp1/s)**2),re(sinh(pi*hm1/s)**2)]) g2 = min([re(sinh(pi*hp2/s)**2),re(sinh(pi*hm2/s)**2)]) return F * (s**4)*g1*g2 else: m1 = (sin(pi*hp1)*sin(pi*hp2))**2 m2 = ((sin(pi*hp1)*sin(pi*hm2))**2)*exp(2*pi*s) m3 = ((sin(pi*hm1)*sin(pi*hp2))**2)*exp(2*pi*s) m4 = (sin(pi*hm1)*sin(pi*hm2))**2 return F * min([re(m1),re(m2),re(m3),re(m4)])
def S_single_hol(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)) conn = (z1 - z2) * (zb1 - zb2) disconn = (z1 - zb1) * (z2 - zb2) return min([re(log(deriv * conn)), re(log(deriv * disconn))]) / 6 - log((x2 - x1)**2) / 6
def v(x, t, s, b): # c is atrificial parameter for findroot. c = 10**(-10) if x > b: return j * mp.findroot(lambda y: re(w(j * y, s, b) - (x - t)), [-s / 2 + c, 0 - c], "bisect") elif x < -b: return j * mp.findroot(lambda y: re(w(j * y, s, b) - (x - t)), [0 + c, s / 2 - c], "bisect") else: tolerant = 10**(-20) normparam = 10**11 return 1 / 2 + j * mp.findroot( lambda y: tanh(re(w(1 / 2 + j * y, s, b) - (x - t)) / normparam), 0, tol=tolerant)
def nPDF(self, x): p = np.zeros(x.size) for i, xx in enumerate(x): gil_pelaez = lambda t: mp.re( self.char_fn(t) * mp.exp(-1j * t * xx)) cutoff = self.find_cutoff(1e-30) # Instead of finding roots, break up quadrature into degrees proportional to the # expected number of oscillations of e^(i xx t) within t = [0, cutoff] nosc = cutoff / (1 / max(10, np.abs(xx - self.mean()))) # roots = self.find_roots(gil_pelaez, cutoff) # if np.abs(xx - self.mean()) < 3 * np.sqrt(self.variance()): I = mp.quad(gil_pelaez, np.linspace(0, cutoff, nosc), maxdegree=10) # I = mp.quadosc(gil_pelaez, (0, cutoff), zeros=roots) # else: # For now, do not trust any results out greater than 3sigma # I = 0 # if np.abs(xx - self.mean()) >= 2 * np.sqrt(self.variance()): # I = self.asymptotic_expansion(xx) p[i] = 1 / np.pi * float(I) print(i) return p
def mp_get_Psca_from_expansion(k, R, dist, zeta): csqrs = [] rhos = [] lbda = mp_get_lagrange_mul_from_expansion(k, R, dist, zeta, csqrs, rhos) limit = len(csqrs) print(limit) print(lbda) i = 0 lhs = mpmath.mpf(0.0) rhs = lhs oldlhs = lhs oldrhs = rhs tol = 1e-6 while (i < limit): if (i == len(csqrs)): #here the l quantum number is i+1 cNl = mp_get_normalized_RgNl0_coeff_for_zdipole_field( k, R, dist, i + 1) csqrs.append(mpmath.re(mpmath.conj(cNl) * cNl)) rhos.append(mp_rho_N(i + 1, k * R)) denom = 1.0 + lbda * zeta * rhos[i] lhs += zeta * csqrs[i] * (1.0 + lbda) * ( 1.0 + 2 * zeta * rhos[i] * lbda) / 4 / denom**2 rhs += zeta * csqrs[i] * (1.0 + lbda) * lbda / 4 / denom**2 i += 1 if (i == limit) and ((lhs - oldlhs) > tol * lhs or (rhs - oldrhs) > tol * rhs): limit = int(np.ceil(limit * 1.2)) oldlhs = lhs oldrhs = rhs return 0.5 * k * (lhs - rhs)
def loop(): global a, listindex, pointer, loopdict realpart = mpmath.re(a[listindex]) impart = mpmath.im(a[listindex]) if mpmath.workdps(mpmath.mp.dps * 3 / 4)( mpmath.chop)(realpart - impart) > 0: pointer = loopdict[pointer]
def getNthKFibonacciNumber( n, k ): if real( n ) < 0: raise ValueError( 'non-negative argument expected' ) if real( k ) < 2: raise ValueError( 'argument <= 2 expected' ) if n < k - 1: return 0 nth = int( n ) + 4 precision = int( fdiv( fmul( n, k ), 8 ) ) if ( mp.dps < precision ): mp.dps = precision poly = [ 1 ] poly.extend( [ -1 ] * int( k ) ) roots = polyroots( poly ) nthPoly = getNthFibonacciPolynomial( k ) result = 0 exponent = fsum( [ nth, fneg( k ), -2 ] ) for i in range( 0, int( k ) ): result += fdiv( power( roots[ i ], exponent ), polyval( nthPoly, roots[ i ] ) ) return floor( fadd( re( result ), fdiv( 1, 2 ) ) )
def write_g_im(filename, e, sigma): nlines = len(e) with open(filename, 'w') as f: for iw in range(0, nlines): s = '{0:18.8f}{1:18.12f}{2:18.12f}\n'. \ format(float(im(e[iw])), float(re(sigma[iw])), float(im(sigma[iw]))) f.write(s)
def F1_cubic(hstar,kappa): ''' F1 function corresponding to a cubic viscosity profile (Nieuwstadt 1983) Parameters ---------- hstar: float Non-dimensional boundary-layer height hstar = h*fc/utau kappa: float Von Karman constant Returns ------- F1: float Value of F1 function ''' C = hstar/kappa alpha = 0.5+0.5*np.sqrt(1+4j*C) F1 = np.zeros((1),dtype=np.float64) F1[0] = 1./kappa*(-np.log(hstar)+ mpmath.re( mpmath.digamma(alpha+1)+ mpmath.digamma(alpha-1)- 2*mpmath.digamma(1.0) ) ) return np.asscalar(F1)
def end(): global a, listindex, pointer, loopdict realpart = mpmath.re(a[listindex]) impart = mpmath.im(a[listindex]) if mpmath.workdps(mpmath.mp.dps * 3 / 4)( mpmath.chop)(realpart - impart) <= 0: pointer = next(key for key, value in loopdict.items() if value == pointer)
def generate(c, num_iterations=200): orbit_re = [] orbit_im = [] z = mpmath.mpc(real='0.0', imag='0.0') for _ in range(num_iterations): z = mpmath.fadd(mpmath.fmul(z, z), c) orbit_re.append(mpmath.nstr(mpmath.re(z))) orbit_im.append(mpmath.nstr(mpmath.im(z))) return [orbit_re, orbit_im]
def get_moments(coef): # returns moments of function calculated from coefficients of Pade decomposition n = len(coef) / 2 # for i in range(0, n): # p[i] = coef[i] # q[i] = coef[i + n] # m[0] = re(p[n - 1]) # m[1] = re(p[n - 2] - m[0] * q[n - 1]) # m[2] = re(p[n - 3] - p[n - 1] * q[n - 2] - (p[n - 2] - p[n - 1] * q[n - 1]) * q[n - 1]) m = [1025.615, 2025.615, 3025.615] m[0] = float(re(coef[n - 1])) m[1] = float(re(coef[n - 2] - coef[n - 1] * coef[2 * n - 1])) m[2] = float( re(coef[n - 3] - coef[n - 1] * coef[2 * n - 2] - (coef[n - 2] - coef[n - 1] * coef[2 * n - 1]) * coef[2 * n - 1])) # m[1] = float(re(coef[n-2] - m[0] * coef[2*n-1])) return m
def formatOutput( output ): # filter out text strings for c in output: if c in '+-.': continue # anything with embedded whitespace is a string if c in string.whitespace or c in string.punctuation: return output #print( ) #print( 'formatOutput 1:', output ) # override settings with temporary settings if needed # if g.tempCommaMode: # comma = True # else: # comma = g.comma # output settings, which may be overrided by temp settings outputRadix = g.outputRadix integerGrouping = g.integerGrouping leadingZero = g.leadingZero if g.tempHexMode: integerGrouping = 4 leadingZero = True outputRadix = 16 if g.tempLeadingZeroMode: leadingZero = True if g.tempOctalMode: integerGrouping = 3 leadingZero = True outputRadix = 8 mpOutput = mpmathify( output ) imaginary = im( mpOutput ) real = re( mpOutput ) result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping ) if negative: result = '-' + result if imaginary != 0: strImaginary, negativeImaginary = formatNumber( imaginary, outputRadix, leadingZero ) result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )' #print( 'formatOutput 2:', output ) #print( ) return result
def formatOutput( output ): # filter out text strings for c in output: if c in '+-.': continue # anything with embedded whitespace is a string if c in string.whitespace or c in string.punctuation: return output # output settings, which may be overrided by temp settings outputRadix = g.outputRadix integerGrouping = g.integerGrouping leadingZero = g.leadingZero integerDelimiter = g.integerDelimiter # override settings with temporary settings if needed if g.tempCommaMode: integerGrouping = 3 # override whatever was set on the command-line leadingZero = False # this one, too integerDelimiter = ',' if g.tempHexMode: integerGrouping = 4 leadingZero = True outputRadix = 16 if g.tempLeadingZeroMode: leadingZero = True if g.tempOctalMode: integerGrouping = 3 leadingZero = True outputRadix = 8 mpOutput = mpmathify( output ) imaginary = im( mpOutput ) real = re( mpOutput ) result, negative = formatNumber( real, outputRadix, leadingZero, integerGrouping, integerDelimiter, g.decimalDelimiter ) if negative: result = '-' + result if imaginary != 0: strImaginary, negativeImaginary = \ formatNumber( imaginary, outputRadix, leadingZero, integerGrouping, integerDelimiter, g.DecimalDelimiter ) result = '( ' + result + ( ' - ' if negativeImaginary else ' + ' ) + strImaginary + 'j )' #print( 'formatOutput 2:', output ) #print( ) return result
def hilbert(d): ''' Compute Hilbert Class Polynomial. Follows pseudo code from Algorithm 7.5.8 Args: d: fundamental discriminant Returns: Hilbert class number, Hilbert class polynomial, and all reduced forms ''' # initialize t = [1] b = d % 2 r = floor(sqrt((-d)/3)) h = 0 red = set() reduced_forms = reduced_form(d) # print h1 a_inverse_sum = sum(1/mpf(form[0]) for form in reduced_forms) precision = round(pi*sqrt(-d)*a_inverse_sum / log(10)) + 10 mpmath.mp.dps = precision # outer loop while b <= r: m = (b*b - d) / 4 m_sqrt = int(floor(sqrt(m))) for a in range(1, m_sqrt+1): if m % a != 0: continue c = m/a if b > a: continue # optional polynomial setup tau = (-b + 1j * sqrt(-d)) / (2*a) f = power(dedekind_eta(2 * tau, precision) / dedekind_eta(tau, precision), 24) j = power((256 * f + 1), 3) / f if b==a or c==a or b==0: # T = T * (X-j) t = polynomial_mul(t, [-j, 1]) h += 1 red.add((a, b, c)) else: poly = [j.real * j.real + j.imag * j.imag, -2 * j.real, 1] t = polynomial_mul(t, poly) h += 2 red.add((a, b, c)) red.add((a, -b, c)) b += 2 if red != reduced_forms: raise ValueError('Reduced form inconsistent.') return h, [int(floor(mpmath.re(p) + 0.5)) for p in t], red
def root_find_mp(func, x_loc, y_loc, step_size, points, solver='halley', wordy=True, tol=1e-15): jump_limit = 0.1 maxsteps = 200 try: grad = ((points[-1, 1] - points[-2, 1]) + (points[-1, 1] - 2*points[-2, 1] + points[-3, 1])) * \ np.abs(step_size/(points[-1, 0] - points[-2, 0])) root_mp = mp.findroot(func, points[-1, 1] + grad, solver, tol) root = float(mp.re(root_mp)) + 1j * float(mp.im(root_mp)) if np.abs(root-points[-1, 1]) < 0.1: points = np.vstack([points, [x_loc, root]]) else: raise ValueError('Jump of {:.5f} at x = {:.5f}, y = {:.5f}'.format( np.abs(root-points[-1, 1]), points[-1, 0], points[-1, 1]+grad)) x_error = None except IndexError: if points.all() == 0: root_mp = mp.findroot(func, y_loc, solver, tol, maxsteps) root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp)) points[0,] = x_loc, root elif points.shape == (1, 2): root_mp = mp.findroot(func, points[-1, 1], solver, tol, maxsteps) root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp)) points = np.vstack([points, [x_loc, root]]) elif points.shape == (2, 2): grad = (points[-1, 1] - points[-2, 1]) *\ np.abs(step_size/(points[-1, 0] - points[-2, 0])) root_mp = mp.findroot(func, points[-1, 1] + grad, solver, tol, maxsteps) root = float(mp.re(root_mp)) + 1j*float(mp.im(root_mp)) if np.abs(root - points[-1, 1]) < jump_limit: points = np.vstack([points, [x_loc, root]]) else: raise ValueError('Jump of {:.5f} at x = {:.5f}, y = {:.5f}'.format( np.abs(root-points[-1, 1]), points[-1, 0], points[-1, 1]+grad)) x_error = None return points, np.abs(step_size), x_error, x_loc
def S_double_hol_conn(x1, x2, t, s, b): v1, v2, vb1, vb2 = v(x1, t, s, b), v(x2, t, s, b), vb(x1, t, s, b), vb(x2, t, s, b) deriv = (pi**(-4)) * Dw(v1, s, b) * (-Dw(-vb1, s, b)) * Dw( v2, s, b) * (-Dw(-vb2, s, b)) if s < 1: conn = (s**2) * sinh(pi * (v1 - v2) / s) * sinh(pi * (vb1 - vb2) / s) else: conn = sin(pi * (v1 - v2)) * sin(pi * (vb1 - vb2)) return re(log(deriv * conn**2)) / 12 - log((x2 - x1)**2) / 6
def find_root(t, method="riemann_siegel"): # Finds root at the point nearest >= t. n_max = 100000 eps = 1e-11 if t < 14: lower = 14 else: lower = t if method == "euler": z_function = lambda t: euler.calculate_z(t) elif method == "dirichlet": z_function = lambda t: dirichlet.calculate_z(t) else: z_function = lambda t: riemann_siegel.calculate_z(t) # Need to find the lowest upper bracketing value. upper = next_upper_bracket(t=t, z_function=z_function) n = 0 while n <= n_max: mid = (upper + lower) / 2 value = z_function(mid) # print "Trying between {} and {}".format(lower, upper) # print "Got Z({}) = {}".format(mid, value) if abs(value) < eps: # Found a root. print "The root closest to t={} in the upward direction is {}.".format(t, mid) return mid else: n += 1 if np.sign( mp.re(z_function(lower)) ) == np.sign( mp.re(z_function(mid)) ): lower = mid else: upper = mid return None
def select(): global lastop, a, listindex, argindex, theFile if lastop == 0: print( 'Parse Error: SELECT. came before corresponding EXP. or LOG. at instruction ' + str(pointer)) print(greporig(pointer)) left = val middle = a[listindex] right = val if listindex > 0: left = a[listindex - 1] if listindex < len(a) - 1: right = a[listindex + 1] print('Nearby Tape Values: ' + mpmath.nstr(left) + ',' + mpmath.nstr(middle) + ',' + mpmath.nstr(right)) sys.exit() elif lastop == 1: if a[argindex] != 0 or mpmath.im( a[listindex]) != 0 or a[listindex] >= 0: try: a[argindex] = mpmath.power(a[argindex], a[listindex]) except OverflowError: print( 'Number too large to represent. Try increasing precision or moving default tape value closer to 1.' ) print(greporig(pointer)) a[argindex] = mpmath.chop(a[argindex], tol) else: a[argindex] = mpmath.mpc('inf') else: if a[listindex] == 1: print('Tried to take a log base one at instruction ' + str(pointer)) print(greporig(pointer)) left = val middle = a[listindex] right = val if listindex > 0: left = a[listindex - 1] if listindex < len(a) - 1: right = a[listindex + 1] print('Nearby Tape Values: ' + mpmath.nstr(left) + ',' + mpmath.nstr(middle) + ',' + mpmath.nstr(right)) sys.exit() a[argindex] = mpmath.log(a[argindex], a[listindex]) #patch up nans when arg is infinite, since we usually want zero for the real part then if mpmath.isinf(mpmath.im(a[argindex])) and mpmath.isnan( mpmath.re(a[argindex])): a[argindex] = mpmath.mpc(0, mpmath.im(a[argindex])) a[argindex] = mpmath.chop(a[argindex], tol) oparg = 0
def __call__(self, r, z=1e-10): """ Returns the intensity distribution near the focal spot. """ u = self.normalized_distance(z) v = self.normalized_radius(r) α = self.alpha() β = self.beta(u, v) I = 2 * α**2 * mp.exp(-α) / (mp.cosh(α) - 1) / (u**2 + 4 * α**2) if mp.sqrt(u**2 + 4 * α**2) < v: U1 = lommelU(u, v, 1) U2 = lommelU(u, v, 2) U1s = mp.re(U1) U1c = mp.im(U1) U2s = mp.re(U2) U2c = mp.im(U2) return I * ((U1c + U2s)**2 + (U1s - U2c)**2) if mp.sqrt(u**2 + 4 * α**2) > v: V0 = lommelV(u, v, 0) V1 = lommelV(u, v, 1) V0s = mp.re(V0) V0c = mp.im(V0) V1s = mp.re(V1) V1c = mp.im(V1) exp = mp.exp(α * (1 - β)) cos = mp.cos(u * (1 + β) / 2) sin = mp.sin(u * (1 + β) / 2) return I * ((V0c - V1s - exp * cos)**2 + (V0s + V1c + exp * sin)**2) raise ValueError('invalid coordinates')
def linear_equilibrium(mu1, mu2, complex_guess_1, complex_guess_2): """The linear equilibrium function finds a two dimensional vector solution. The solutions we are looking for are real. Many solutions that can be found are complex and because of the numerical methods in which python finds these solutions we have decided to use the mpmath modules. This method of finding the solution for our non linear heat flux uses the muller method of numerical calculation. For more information on mpmath root finding: http://mpmath.org/doc/1.1.0/calculus/optimization.html""" import numpy as np import sympy import mpmath #List of Constants I0 = 1367.0 #Solar constant W/m^2 a = 2.8 #Unitless parameter needed for linear albedo feedback relationships more info in Budyko 1969 b = .009 #Another parameter needed for linear feedback relationship more info in Budyko 1969 sig = 5.67 * 10**-8 #Stephan boltzmann constant m^2 kg s^-2 K^-1 e = .64 #Emmisivity of earth A = 2.7 #Heat flux parameter for linear heat forcing solution_array = [] for x in mu1: for y in mu2: #Below we find the two-dimensional vector solutions in form of [polar_solution, tropical_solution] f = [ lambda T1, T2: (.156 * x * I0 * (1 - a) + .156 * x * I0 * b * T1 - e * sig * (T1**4) + (A * (T2 - T1))), lambda T1, T2: (.288 * y * I0 * (1 - a) + .288 * y * I0 * b * T2 - e * sig * (T2**4) + (A * (T1 - T2))) ] solution = np.array( mpmath.findroot(f, ([complex_guess_1, complex_guess_2]), solver='muller', verify=False)) if abs(mpmath.im(solution[0])) > 1e-10: solution[0] = np.nan if abs(mpmath.im(solution[1])) > 1e-10: solution[1] = np.nan solution_array.append( [mpmath.re(solution[0]), mpmath.re(solution[1]), x, y]) return (solution_array)
def propagate(self, T): """ Returns new Gaussian beam with updated parameters from transfer matrix. """ z = self.origin k = self.wavenumber q = self.parameter q = (T[0, 0] * q + T[0, 1]) / (T[1, 0] * q + T[1, 1]) z = mp.re(q) + z w = mp.sqrt(2 * mp.im(q) / k) return Gaussian(waist=w, origin=z, wavelength=self.wavelength)
def S_double_dirac(x1, x2, t, s, b): v1, v2, vb1, vb2 = v(x1, t, s, b), v(x2, t, s, b), vb(x1, t, s, b), vb(x2, t, s, b) deriv = ((2 * pi)**(-4)) * Dw(v1, s, b) * (-Dw(-vb1, s, b)) * Dw( v2, s, b) * (-Dw(-vb2, s, b)) conn = jt1(v1 - v2, j * s) * jt1(vb2 - vb1, j * s) / eta(j * s)**6 disconn = jt1(v1 - vb1 + j * s / 2, j * s) * jt1(v2 - vb2 + j * s / 2, j * s) cross = jt1(v1 - vb2 + j * s / 2, j * s) * jt1(v2 - vb1 + j * s / 2, j * s) return re(log(deriv * (conn * disconn / cross)**2)) / 12 - log( (x2 - x1)**2) / 6
def S_single_dirac(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)) conn = (z1 - z2) * (zb1 - zb2) disconn = (z1 - zb1) * (z2 - zb2) cross = (z1 - zb2) * (z2 - zb1) return re(log(deriv * conn * disconn / cross)) / 6 - log((x2 - x1)**2) / 6
def non_linear_albedo_solver(mu1, mu2, guess_1, guess_2): """This solution is a modeling of a situation where solar intensity is decreased sufficiently until the earth produces enough ice that the earth will reflect sufficient radiation to keep the earth in an ice age. Ice ages are still subject to a heat flux, the below function finds the equilibria for the ice ages for made with a non-linear heat flux.""" import numpy as np import sympy import mpmath #List of Constants I0 = 1367.0 #Solar constant W/m^2 a = 2.8 #Unitless parameter needed for linear albedo feedback relationships more info in Budyko 1969 b = .009 #Another parameter needed for linear feedback relationship more info in Budyko 1969 sig = 5.67 * 10**-8 #Stephan boltzmann constant m^2 kg s^-2 K^-1 e = .64 #Emmisivity of earth A = 600 #Heat flux parameter for non-linear heat forcing solution_array = [] for x in mu1: for y in mu2: #Below we find the two-dimensional vector solutions in form of [polar_solution, tropical_solution] f = [ lambda T1, T2: (.156 * x * I0 * (1 - .75) - e * sig * (T1**4) + (A / (T2 - T1))), lambda T1, T2: (.288 * y * I0 * (1 - .75) - e * sig * (T2**4) + (A / (T1 - T2))) ] solution = np.array( mpmath.findroot(f, ([guess_1, guess_2]), solver='muller', verify=False)) if abs(mpmath.im(solution[0])) > 1e-10: solution[0] = np.nan if abs(mpmath.im(solution[1])) > 1e-10: solution[1] = np.nan solution_array.append( [mpmath.re(solution[0]), mpmath.re(solution[1]), x, y]) return (solution_array)
def put_price_calc(given, op): #Option data K = given[0] #Strike R = given[1] #Risk free rate of return (in %) T = given[2] #Time to expiry y = given[3] #Annual dividend yield S0 = given[4] #Stock price #Parameters over which data is being optimized sigma = op[0] #Log return diffusion lemu = op[1] #Arrival rate of up jumps lemd = op[2] #Arrival rate of down jumps etau = op[3] #Strength of up jump etad = op[4] #Strength of down jump k = math.log(K) #Log of strike rate r = R / 100 #Risk free rate of return mu = r - y - lemu / (etau - 1) + lemd / ( etad + 1) #Mu for the given data and parameters #Risk neutral probability of finishing in the money pi2 = 0.5 + mp.fdiv(1, mp.pi) * mp.quad( lambda u: mp.re( mp.fdiv( mp.exp(-mp.mpc(0, 1) * u * k) * char_fun( u, mu, sigma, lemu, lemd, etau, etad, T, S0), mp.mpc(0, 1) * u)), [0, mp.inf]) #Delta of the option pi1 = 0.5 + mp.fdiv(1, mp.pi) * mp.quad( lambda u: mp.re( mp.fdiv( mp.exp(-mp.mpc(0, 1) * u * k) * char_fun( u - mp.mpc(0, 1), mu, sigma, lemu, lemd, etau, etad, T, S0), mp.mpc(0, 1) * u * char_fun(-mp.mpc(0, 1), mu, sigma, lemu, lemd, etau, etad, T, S0))), [0, mp.inf]) #Price of the put option P_alternate = K * mp.exp(-r * T) * (1 - pi2) - S0 * mp.exp( -y * T) * (1 - pi1) return P_alternate
def S_double_hol_disconn(x1, x2, t, s, b): v1, v2, vb1, vb2 = v(x1, t, s, b), v(x2, t, s, b), vb(x1, t, s, b), vb(x2, t, s, b) #difference from mirror twist op p1, n1, p2, n2 = v1 - vb1 + j * s / 2, v1 - vb1 - j * s / 2, v2 - vb2 + j * s / 2, v2 - vb2 - j * s / 2 deriv = (pi**(-4)) * Dw(v1, s, b) * (-Dw(-vb1, s, b)) * Dw( v2, s, b) * (-Dw(-vb2, s, b)) if s < 1: g1 = min([re(sinh(pi * p1 / s)**2), re(sinh(pi * n1 / s)**2)]) g2 = min([re(sinh(pi * p2 / s)**2), re(sinh(pi * n2 / s)**2)]) disconnSquare = (s**4) * g1 * g2 else: m1 = sin(pi * p1) * sin(pi * p2) m2 = sin(pi * p1) * sin(pi * n2) * exp(pi * s) m3 = sin(pi * n1) * sin(pi * p2) * exp(pi * s) m4 = sin(pi * n1) * sin(pi * n2) disconnSquare = min([re(m1**2), re(m2**2), re(m3**2), re(m4**2)]) return re(log(deriv * disconnSquare)) / 12 - log((x2 - x1)**2) / 6
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 getNthPadovanNumber( arg ): n = fadd( real( arg ), 4 ) a = root( fsub( fdiv( 27, 2 ), fdiv( fmul( 3, sqrt( 69 ) ), 2 ) ), 3 ) b = root( fdiv( fadd( 9, sqrt( 69 ) ), 2 ), 3 ) c = fadd( 1, fmul( mpc( 0, 1 ), sqrt( 3 ) ) ) d = fsub( 1, fmul( mpc( 0, 1 ), sqrt( 3 ) ) ) e = power( 3, fdiv( 2, 3 ) ) r = fadd( fdiv( a, 3 ), fdiv( b, e ) ) s = fsub( fmul( fdiv( d, -6 ), a ), fdiv( fmul( c, b ), fmul( 2, e ) ) ) t = fsub( fmul( fdiv( c, -6 ), a ), fdiv( fmul( d, b ), fmul( 2, e ) ) ) return nint( re( fsum( [ fdiv( power( r, n ), fadd( fmul( 2, r ), 3 ) ), fdiv( power( s, n ), fadd( fmul( 2, s ), 3 ) ), fdiv( power( t, n ), fadd( fmul( 2, t ), 3 ) ) ] ) ) )
def isKthPower( n, k ): if not isint( k, gaussian=True ) and isint( k ): raise ValueError( 'integer arguments expected' ) if k == 1: return 1 elif k < 1: raise ValueError( 'a positive power k is expected' ) if im( n ): # I'm not sure why this is necessary... if re( n ) == 0: return isKthPower( im( n ), k ) # We're looking for a Gaussian integer among any of the roots. for i in [ autoprec( root )( n, k, i ) for i in arange( k ) ]: if isint( i, gaussian=True ): return 1 return 0 else: rootN = autoprec( root )( n, k ) return 1 if isint( rootN, gaussian=True ) else 0
def g(theta,phi): R = abs(re(spherharm(l,m,theta,phi))) x = R*cos(phi)*sin(theta) y = R*sin(phi)*sin(theta) z = R*cos(theta) return [x,y,z]
def handleOutput( valueList, indent=0, file=sys.stdout ): ''' Once the evaluation of terms is complete, the results need to be translated into output. If the result is a list or a generator, special formatting turns those into text output. Date-time values and measurements also require special formatting. Setting file to an io.StringIO objects allows for 'printing' to a string, which is used by makeHelp.py to generate actual rpn output for the examples. ''' if valueList is None: return file indentString = ' ' * indent if len( valueList ) != 1: if g.checkForSingleResults: print( 'valueList', valueList ) raise ValueError( 'unexpected multiple results!' ) valueList = [ valueList ] if isinstance( valueList[ 0 ], RPNFunction ): print( indentString + 'rpn: unexpected end of input in function definition', file=file ) else: mp.pretty = True result = valueList.pop( ) if result is nan: return file if g.comma: g.integerGrouping = 3 # override whatever was set on the command-line g.leadingZero = False # this one, too g.integerDelimiter = ',' else: g.integerDelimiter = ' ' if isinstance( result, RPNGenerator ): formatListOutput( result.getGenerator( ), indent=indent, file=file ) elif isinstance( result, list ): formatListOutput( result, indent=indent, file=file ) else: # single result if isinstance( result, RPNDateTime ): outputString = formatDateTime( result ) elif isinstance( result, str ): result = checkForVariable( result ) outputString = result else: # output the answer with all the extras according to command-line arguments # handle the units if we are displaying a measurement if isinstance( result, RPNMeasurement ): outputString = formatOutput( nstr( result.value, g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) outputString += ' ' + formatUnits( result ) # handle a complex output (mpmath type: mpc) elif isinstance( result, mpc ): #print( 'result', result, type( result ) ) #print( 'im', im( result ), type( im( result ) ) ) #print( 're', re( result ), type( re( result ) ) ) imaginary = im( result ) if im( result ) > 0: outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \ ' + ' + formatOutput( nstr( mpmathify( im( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + 'j)' elif im( result ) < 0: outputString = '(' + formatOutput( nstr( mpmathify( re( result ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + \ ' - ' + formatOutput( nstr( fneg( mpmathify( im( result ) ) ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) + 'i)' else: outputString = formatOutput( nstr( re( result ), g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) # otherwise, it's a plain old mpf else: outputString = formatOutput( nstr( result, g.outputAccuracy, min_fixed=-g.maximumFixed - 1 ) ) print( indentString + outputString, file=file ) # handle --identify if g.identify: handleIdentify( result, file ) saveResult( result ) if g.timer or g.tempTimerMode: print( '\n' + indentString + '{:.3f} seconds'.format( time.process_time( ) - g.startTime ), file=file )
def g(theta,phi): R = abs(re(a*spherharm(l,m1,theta,phi)+b*spherharm(l,m2,theta,phi)))**2 x = R*cos(phi)*sin(theta) y = R*sin(phi)*sin(theta) z = R*cos(theta) return [x,y,z]
def z_function(t, N=100000): zeta = zeta_function(1/2 + (1.j)*t, N) return mp.re( np.exp( 1.j * riemann_siegel_theta(t) ) * zeta )
def isPower( n, k ): #print( 'log( n )', log( n ) ) #print( 'log( k )', log( k ) ) #print( 'divide', autoprec( lambda n, k: fdiv( re( log( n ) ), re( log( k ) ) ) )( n, k ) ) return isInteger( autoprec( lambda n, k: fdiv( re( log( n ) ), re( log( k ) ) ) )( n, k ) )
def arFpDensity(Da, r0a, La, ta): D, r0, L, t = (m.mpmathify(str(x)) for x in (Da, r0a, La, ta)) pref = m.exp(-r0 ** 2 / (4 * D * t)) * D / (4 * m.sqrt(m.pi) * (D * t) ** 1.5) z = (1j * L * r0) / (2 * D * t) q = m.exp(-L ** 2 / (D * t)) return float(m.re(2 * pref * (r0 * m.jtheta(4, z, q) - 0 * 1j * L * m.djtheta(4, z, q))))
def getReal( n ): return re( n )