def createP_sigma(lx, ly, band): C = table.C_Sigma(ly / (2 / mp.sqrt(3)), lx / (mp.sqrt(3) / 2), band) #Values tabulated on a rectangular grid, flipped and compensated for. C = [ C[0], C[1], C[2], C[3] / (3**(1 / 2)), C[4] / (3**(1 / 2)), C[5] / (3**(1 / 2)) ] #For sqrt(3) normalisation, see paper for reference. f = lambda kx, ky, kz: C[0] * fi_As(lx, ly, kx, ky, kz) + C[1] * fi_Ax( lx, ly, kx, ky, kz) + C[2] * fi_Ay(lx, ly, kx, ky, kz) + C[3] * fi_Bs( lx, ly, kx, ky, kz) + C[4] * fi_Bx(lx, ly, kx, ky, kz) + C[ 5] * fi_By(lx, ly, kx, ky, kz) nrm = 1 / mp.sqrt( mp.conj(C[0]) * C[0] + mp.conj(C[1]) * C[1] + mp.conj(C[2]) * C[2] + 3 * (mp.conj(C[3]) * C[3] + mp.conj(C[4]) * C[4] + mp.conj(C[5]) * C[5]) + 2 * mp.re((mp.conj(C[0]) * C[3] * pss + mp.conj(C[0]) * C[4] * psx + mp.conj(C[0]) * C[5] * psy + mp.conj(C[1]) * C[3] * psx + mp.conj(C[1]) * C[4] * pxx + mp.conj(C[1]) * C[5] * pxy + mp.conj(C[2]) * C[3] * psy + mp.conj(C[2]) * C[4] * pxy + mp.conj(C[2]) * C[5] * pyy) * (mp.exp(1j * mp.fdot([lx, ly, 0], R_1)) + mp.exp(1j * mp.fdot([lx, ly, 0], R_2)) + mp.exp(1j * mp.fdot([lx, ly, 0], R_3))))) return lambda kx, ky, kz: f(kx, ky, kz) * nrm
def cumulants(self, gamma): """ Compute .. math:: \Lambda(\gamma) = \log\left(\int_{\mathbb{R}^n} e^{\gamma \|z\|^2_2} F(dz)\right) as well as its first two derivatives with respect to $\gamma$, where $F$ is the empirical distribution of `self.sample`. """ norm_squared = self.sample M = norm_squared.mean() M0 = float(np.mean([mp.exp(gamma * (ns - M)) for ns in norm_squared])) M0 *= mp.exp(gamma * M) M1 = np.mean([ np.exp(float(gamma * ns + np.log(ns) - mp.log(M0))) for ns in norm_squared ]) M2 = np.mean([ np.exp(float(gamma * ns + 2 * np.log(ns) - mp.log(M0))) for ns in norm_squared ]) return M0, M1, (M2 - M1**2)
def test_gauss_quadrature_dynamic(verbose = False): n = 5 A = mp.randmatrix(2 * n, 1) def F(x): r = 0 for i in xrange(len(A) - 1, -1, -1): r = r * x + A[i] return r def run(qtype, FW, R, alpha = 0, beta = 0): X, W = mp.gauss_quadrature(n, qtype, alpha = alpha, beta = beta) a = 0 for i in xrange(len(X)): a += W[i] * F(X[i]) b = mp.quad(lambda x: FW(x) * F(x), R) c = mp.fabs(a - b) if verbose: print(qtype, c, a, b) assert c < 1e-5 run("legendre", lambda x: 1, [-1, 1]) run("legendre01", lambda x: 1, [0, 1]) run("hermite", lambda x: mp.exp(-x*x), [-mp.inf, mp.inf]) run("laguerre", lambda x: mp.exp(-x), [0, mp.inf]) run("glaguerre", lambda x: mp.sqrt(x)*mp.exp(-x), [0, mp.inf], alpha = 1 / mp.mpf(2)) run("chebyshev1", lambda x: 1/mp.sqrt(1-x*x), [-1, 1]) run("chebyshev2", lambda x: mp.sqrt(1-x*x), [-1, 1]) run("jacobi", lambda x: (1-x)**(1/mp.mpf(3)) * (1+x)**(1/mp.mpf(5)), [-1, 1], alpha = 1 / mp.mpf(3), beta = 1 / mp.mpf(5) )
def FreeFermions(eigvec, subsystem, FermiVector): r=range(FermiVector) Cij=mp.matrix([[mp.fsum([eigvec[i,k]*eigvec[j,k] for k in r]) for i in subsystem] for j in subsystem]) C_eigval=mp.eigsy(Cij, eigvals_only=True) EH_eigval=mp.matrix([mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0),x),x)) for x in C_eigval]) S=mp.re(mp.fsum([mp.log(mp.mpf(1.0)+mp.exp(-x))+mp.fdiv(x,mp.exp(x)+mp.mpf(1.0)) for x in EH_eigval])) return(S)
def abeff_lemmabound(N, y, t, cond): sigma1 = 0.5 * (1 + y) sum1, sum2, sum3, sum5 = [0.0 for _ in range(4)] b1 = 1 a1 = mp.power(N, -0.4) xN = 4 * mp.pi() * N * N - mp.pi() * t / 4.0 xNp1 = 4 * mp.pi() * (N + 1) * (N + 1) - mp.pi() * t / 4.0 delta = mp.pi() * y / (2 * (xN - 6 - (14 + 2 * y) / mp.pi())) + 2 * y * ( 7 + y) * mp.log(abs(1 + y + 1j * xNp1) / (4 * mp.pi)) / (xN * xN) expdelta = mp.exp(delta) for n in range(2, 30 * N + 1): nf = float(n) denom = mp.power(nf, sigma1 + (t / 4.0) * mp.log(N * N)) #print([cond[n][i] for i in range(1,9)]) common1 = mp.exp((t / 4.0) * mp.power(mp.log(nf), 2)) common2 = common1 * mp.power(nf / N, y) common3 = expdelta * (mp.exp(t * y * mp.log(n) / (2 * (xN - 6))) - 1) bn, bn2, bn3, bn5 = [common1 * cond[n][2 * i - 1] for i in range(1, 5)] an, an2, an3, an5 = [common2 * cond[n][2 * i] for i in range(1, 5)] en, en2, en3, en5 = an * common3, an2 * common3, an3 * common3, an5 * common3 sum1 += (en + max( (1 - a1) * abs(bn + an) / (1 + a1), abs(bn - an))) / denom sum2 += (en2 + max( (1 - a1) * abs(bn2 + an2) / (1 + a1), abs(bn2 - an2))) / denom sum3 += (en3 + max( (1 - a1) * abs(bn3 + an3) / (1 + a1), abs(bn3 - an3))) / denom sum5 += (en5 + max( (1 - a1) * abs(bn5 + an5) / (1 + a1), abs(bn5 - an5))) / denom return [N, expdelta] + [1 - a1 - j for j in [sum1, sum2, sum3, sum5]]
def abeff_trianglebound(N, y, t, cond): sigma1 = 0.5 * (1 + y) sum1, sum2, sum3, sum5 = [0.0 for _ in range(4)] b1 = 1 a1 = mp.power(N, -0.4) xN = 4 * mp.pi() * N * N - mp.pi() * t / 4.0 xNp1 = 4 * mp.pi() * (N + 1) * (N + 1) - mp.pi() * t / 4.0 delta = mp.pi() * y / (2 * (xN - 6 - (14 + 2 * y) / mp.pi())) + 2 * y * ( 7 + y) * mp.log(abs(1 + y + 1j * xNp1) / (4 * mp.pi)) / (xN * xN) expdelta = mp.exp(delta) for n in range(1, 30 * N + 1): nf = float(n) denom = mp.power(nf, sigma1 + (t / 4.0) * mp.log(N * N)) common1 = mp.exp((t / 4.0) * mp.power(mp.log(nf), 2)) common2 = common1 * mp.power(nf / N, y) * expdelta * mp.exp( t * y * mp.log(n) / (2 * (xN - 6))) bn, bn2, bn3, bn5 = [ common1 * abs(cond[n][2 * i - 1]) for i in range(1, 5) ] an, an2, an3, an5 = [ common2 * abs(cond[n][2 * i]) for i in range(1, 5) ] sum1 += (bn + an) / denom sum2 += (bn2 + an2) / denom sum3 += (bn3 + an3) / denom sum5 += (bn5 + an5) / denom return [N, expdelta] + [2 - j for j in [sum1, sum2, sum3, sum5]]
def system(t, y): # Variables i, a, m, z, s = y # Auxiliary equations g = i + a + m tot = g + s star_elem = m + α * a τS = star_elem**(1 / 3.0) / (K * g**(1 / 3.0) * tot**(2 / 3.0)) ψ = star_elem / τS ηion = ηi_lim * (1 - mp.exp(-a / Σion)) ηdiss = ηd_lim * (1 - mp.exp(-m / Σdiss)) Z = z / g τR = C2 * (1 + T1 * ψ / (Twarm * g)) / (g * tot) τC = C4 * (1 + T1 * ψ / (Tcold * g)) * Zsun / (g * tot * (Z + Zeff)) recombination = i / τR cloud_formation = a / τC # ODE system return [ -recombination + (ηion + R) * ψ, -cloud_formation + recombination + (ηdiss - ηion - α * a / star_elem) * ψ, cloud_formation - (ηdiss + m / star_elem) * ψ, (Zsn * R - Z) * ψ, (1 - R) * ψ, ]
def test_levin_2(): # [2] A. Sidi - "Pratical Extrapolation Methods" p.373 mp.dps = 17 z = mp.mpf(10) eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method="sidi", variant="t") n = 0 while 1: s = (-1)**n * mp.fac(n) * z**(-n) v, e = L.step(s) n += 1 if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp(-x) / (1 + x / z), [0, mp.inf]) # there is also a symbolic expression for the integral: # exact = z * mp.exp(z) * mp.expint(1,z) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-1)**n * mp.fac(n) * z**(-n), [0, mp.inf], method="sidi", levin_variant="t") assert err < eps
def test_levin_3(): mp.dps = 17 z = mp.mpf(2) eps = mp.mpf(mp.eps) with mp.extraprec( 7 * mp.prec ): # we need copious amount of precision to sum this highly divergent series L = mp.levin(method="levin", variant="t") n, s = 0, 0 while 1: s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4**n)) n += 1 v, e = L.step_psum(s) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.8 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp(-x * x / 2 - z * x**4), [0, mp.inf]) * 2 / mp.sqrt(2 * mp.pi) # there is also a symbolic expression for the integral: # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4**n)), [0, mp.inf], method="levin", levin_variant="t", workprec=8 * mp.prec, steps=[2] + [1 for x in xrange(1000)]) err = abs(v - w) assert err < eps
def system(t, y): # Variables i, a, m, z, s = y # Auxiliary equations g = i + a + m tot = g + s star_elem = m + α * a τS = star_elem**(1 / 3.0) / (K * g**(1 / 3.0) * tot**(2 / 3.0)) ψ = star_elem / τS Ii = ΣI * mp.exp(-t / τ) / (τ * (1.0 - mp.exp(-T / τ))) outflow = ω * ψ / g Oi = outflow * i Oa = outflow * a Om = outflow * m Oz = outflow * z ηion = ηi_lim * (1 - mp.exp(-a / Σion)) ηdiss = ηd_lim * (1 - mp.exp(-m / Σdiss)) Z = z / g τR = C2 * (1 + T1 * ψ / (Twarm * g)) / (g * tot) τC = C4 * (1 + T1 * ψ / (Tcold * g)) * Zsun / (g * tot * (Z + Zeff)) recombination = i / τR cloud_formation = a / τC # ODE system return [ Ii - Oi - recombination + (ηion + R) * ψ, -Oa - cloud_formation + recombination + (ηdiss - ηion - α * a / star_elem) * ψ, -Om + cloud_formation - (ηdiss + m / star_elem) * ψ, -Oz + (Zsn * R - Z) * ψ, (1 - R) * ψ, ]
def xmultibound(x): N = int(mp.sqrt(0.25 * x / mp.pi())) sum1_1, sum1_2, sum12_1, sum12_2, sum123_1, sum123_2, sum1235_1, sum1235_2 = [ 0.0 for i in range(8) ] factor2 = 1 - 1 / mp.power(2.0, 0.7 + 0.1 * mp.log(N * N / 2.0)) factor3 = 1 - 1 / mp.power(3.0, 0.7 + 0.1 * mp.log(N * N / 3.0)) factor5 = 1 - 1 / mp.power(5.0, 0.7 + 0.1 * mp.log(N * N / 5.0)) factorN = 1 / mp.power(N, 0.4) pow2, pow3, pow5, pow6, pow10, pow15, pow30 = [ mp.power(j, 0.4) for j in [2, 3, 5, 6, 10, 15, 30] ] expo2, expo3, expo5 = 0.2 * mp.log(2), 0.2 * mp.log(3), 0.2 * mp.log(5) expo6, expo10, expo15, expo30 = expo2 + expo3, expo2 + expo5, expo3 + expo5, expo2 + expo3 + expo5 exp23, exp25, exp35 = mp.exp(0.2 * mp.log(2) * mp.log(3)), mp.exp( 0.2 * mp.log(2) * mp.log(5)), mp.exp(0.2 * mp.log(3) * mp.log(5)) exp235 = exp23 * exp25 * exp35 for n in range(1, 30 * N + 1): L1 = deltaN(n, N) L2 = deltaN(n, 2 * N) * divdelta(n, 2) if L2 > 0: L2 /= mp.power((n / 2.0), expo2) L3 = deltaN(n, 3 * N) * divdelta(n, 3) if L3 > 0: L3 /= mp.power((n / 3.0), expo3) L5 = deltaN(n, 5 * N) * divdelta(n, 5) if L5 > 0: L5 /= mp.power((n / 5.0), expo5) L6 = deltaN(n, 6 * N) * divdelta(n, 6) if L6 > 0: L6 /= (mp.power((n / 6.0), expo6) * exp23) L10 = deltaN(n, 10 * N) * divdelta(n, 10) if L10 > 0: L10 /= (mp.power((n / 10.0), expo10) * exp25) L15 = deltaN(n, 15 * N) * divdelta(n, 15) if L15 > 0: L15 /= (mp.power((n / 15.0), expo15) * exp35) L30 = deltaN(n, 30 * N) * divdelta(n, 30) if L30 > 0: L30 /= (mp.power((n / 30.0), expo30) * exp235) R1 = L1 R2 = L2 / pow2 R3 = L3 / pow3 R5 = L5 / pow5 R6 = L6 / pow6 R10 = L10 / pow10 R15 = L15 / pow15 R30 = L30 / pow30 n = float(n) denom1 = mp.power(n, 0.7 + 0.1 * mp.log(N * N / n)) denom2 = mp.power(n, 0.3 + 0.1 * mp.log(N * N / n)) sum1_1 += abs(L1) / denom1 sum1_2 += abs(R1) / denom2 sum12_1 += abs(L1 - L2) / denom1 sum12_2 += abs(R1 - R2) / denom2 sum123_1 += abs(L1 - L2 - L3 + L6) / denom1 sum123_2 += abs(R1 - R2 - R3 + R6) / denom2 sum1235_1 += abs(L1 - L2 - L3 - L5 + L6 + L10 + L15 - L30) / denom1 sum1235_2 += abs(R1 - R2 - R3 - R5 + R6 + R10 + R15 - R30) / denom2 finalsum1 = sum1_1 - 1 + sum1_2 * factorN finalsum12 = (sum12_1 - 1 + sum12_2 * factorN) / factor2 finalsum123 = (sum123_1 - 1 + sum123_2 * factorN) / (factor2 * factor3) finalsum1235 = (sum1235_1 - 1 + sum1235_2 * factorN) / (factor2 * factor3 * factor5) return [finalsum1, finalsum12, finalsum123, finalsum1235]
def fi_Bx(lx, ly, kx, ky, kz): return (mp.exp(1j * mp.fdot( [lx + kx / ct.hbar, ly + ky / ct.hbar, kz / ct.hbar], R_1)) + mp.exp(1j * mp.fdot( [lx + kx / ct.hbar, ly + ky / ct.hbar, kz / ct.hbar], R_2)) + mp.exp(1j * mp.fdot( [lx + kx / ct.hbar, ly + ky / ct.hbar, kz / ct.hbar], R_3)) ) * w2px(kx, ky, kz)
def phi_decay(u,n_max=100): running_sum=0 u=mp.mpc(u) for n in range(1,n_max+1): term1=2*PI_sq*mp.power(n,4)*mp.exp(9*u) - 3*PI*mp.power(n,2)*mp.exp(5*u) term2=mp.exp(-1*PI*mp.power(n,2)*mp.exp(4*u)) running_sum += term1*term2 #print n,term1, term2, running_sum return running_sum
def XGEON_integrand_nBA(y, n, RA, RB, rh, l, pm1, Om, lam, sig, deltaphi): bA = mp.sqrt(RA**2 - rh**2) / l bB = mp.sqrt(RB**2 - rh**2) / l K = 1 alp2 = bA**2 * bB**2 / 2 / (bA**2 + bB**2) / sig**2 bet2 = (bA + bB) * bA * bB / (bA**2 + bB**2) E = (bB - bA) / fp.sqrt(2) / fp.sqrt(bB**2 + bA**2) * ( (bB + bA) * y / 2 / sig + fp.j * sig * Om) return K*mp.exp(-alp2*y**2)*mp.exp(-fp.j*bet2*Om*y) *fp.erfc(E) \ * XGEON_denoms_n(y,n,RA,RB,rh,l,pm1,Om,lam,sig,deltaphi)
def FreeFermions(subsystem, C): C = mp.matrix([[C[x, y] for x in subsystem] for y in subsystem]) C_eigval = mp.eigh(C, eigvals_only=True) EH_eigval = mp.matrix( [mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0), x), x)) for x in C_eigval]) S = mp.re( mp.fsum([ mp.log(mp.mpf(1.0) + mp.exp(-x)) + mp.fdiv(x, mp.exp(x) + mp.mpf(1.0)) for x in EH_eigval ])) return (S)
def FreeFermions(subsystem, C_t): #implements free fermion technique by peschel C = mp.matrix([[C_t[x, y] for x in subsystem] for y in subsystem]) C_eigval = mp.eigh(C, eigvals_only=True) EH_eigval = mp.matrix( [mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0), x), x)) for x in C_eigval]) S = mp.re( mp.fsum([ mp.log(mp.mpf(1.0) + mp.exp(-x)) + mp.fdiv(x, mp.exp(x) + mp.mpf(1.0)) for x in EH_eigval ])) return (S)
def f02(y, n, R, rh, l, pm1, Om, lam, sig): K = lam**2 * sig / 2 / fp.sqrt(2 * fp.pi) a = (R**2 - rh**2) * l**2 / 4 / sig**2 / rh**2 b = fp.sqrt(R**2 - rh**2) * Om * l / rh Zp = mp.mpf((R**2 + rh**2) / (R**2 - rh**2)) if Zp - mp.cosh(y) > 0: return fp.mpf(K * mp.exp(-a * y**2) * mp.cos(b * y) / mp.sqrt(Zp - mp.cosh(y))) elif Zp - mp.cosh(y) < 0: return fp.mpf(-K * mp.exp(-a * y**2) * mp.sin(b * y) / mp.sqrt(mp.cosh(y) - Zp)) else: return 0
def calc_lmsr_marginal_price(token_count, token_index, net_outcome_tokens_sold, funding): mp.dps = 100 mp.pretty = True b = mpf(funding) / mp.log(len(net_outcome_tokens_sold)) result = b * mp.log( sum( mp.exp(share_count / b + token_count / b) for share_count in net_outcome_tokens_sold) - sum( mp.exp(share_count / b) for index, share_count in enumerate(net_outcome_tokens_sold) if index != token_index)) - net_outcome_tokens_sold[token_index] return result
def fn1(y, n, R, rh, l, pm1, Om, lam, sig): K = lam**2 * sig / 2 / fp.sqrt(2 * fp.pi) a = (R**2 - rh**2) * l**2 / 4 / sig**2 / rh**2 b = fp.sqrt(R**2 - rh**2) * Om * l / rh Zm = mp.mpf(rh**2 / (R**2 - rh**2) * (R**2 / rh**2 * fp.cosh(2 * fp.pi * rh / l * n) - 1)) if Zm == mp.cosh(y): return 0 elif Zm - fp.cosh(y) > 0: return fp.mpf(K * mp.exp(-a * y**2) * mp.cos(b * y) / mp.sqrt(Zm - mp.cosh(y))) else: return fp.mpf(-K * mp.exp(-a * y**2) * mp.sin(b * y) / mp.sqrt(mp.cosh(y) - Zm))
def get_rate_constants(self): """This function calculates all rate constants based on the DFT energies for each species. No coverage dependence is included. """ # Gas phase entropies kbT = kb * self.T # in eV dE = self.get_rxn_energies() dS = self.get_rxn_entropies() Ea = self.get_Eacts() STS = self.get_TS_entropies() ZPEs = self.get_ZPEs_rxn() TSZPEs = self.get_ZPEs_act() dE += ZPEs Ea += TSZPEs nlevels = self.nlevels if self.alkali_promotion: for level in range(nlevels): dE[level] += 0.02 # N2 inc by 0.01 Ea[level] -= 0.15 # Barrier lowered by 0.15 dE[level + 2] += 0.24 - 0.01 # NH inc by 0.24 dE[level + 3] += 0.27 - 0.24 # NH2 inc by 0.27 dE[level + 4] += 0 - 0.27 # NH3 inc by 0.54, but not adsorbed self.dE = dE self.dS = dS self.Ea = Ea self.STS = STS self.ZPEs = ZPEs self.TSZPEs = TSZPEs # Calculate equilibrium and rate constants K = np.zeros(len(dE)) # equilibrium constants kf = np.zeros(len(dE)) # forward rate constants kr = np.zeros(len(dE)) # reverse rate constants for i in range(len(dE)): dG = dE[i] - self.T * dS[i] K[i] = mp.exp(-dG / kbT) Ea[i] = max([0, dE[i], Ea[i]]) # Enforce Ea > 0, and Ea > dE kf[i] = kbT / h * mp.exp(STS[i] / kb) * mp.exp(-Ea[i] / kbT) kr[i] = kf[i] / K[i] # enforce thermodynamic consistency self.kf = kf self.kr = kr return (kf, kr)
def test_svd_test_case(): # a test case from Golub and Reinsch # (see wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).) eps = mp.exp(0.8 * mp.log(mp.eps)) a = [[22, 10, 2, 3, 7], [14, 7, 10, 0, 8], [-1, 13, -1, -11, 3], [-3, -2, 13, -2, 4], [ 9, 8, 1, -2, 4], [ 9, 1, -7, 5, -1], [ 2, -6, 6, 5, 1], [ 4, 5, 0, -2, 2]] a = mp.matrix(a) b = mp.matrix([mp.sqrt(1248), 20, mp.sqrt(384), 0, 0]) S = mp.svd_r(a, compute_uv = False) S -= b assert mp.mnorm(S) < eps S = mp.svd_c(a, compute_uv = False) S -= b assert mp.mnorm(S) < eps
def Ht_AFE_A(z, t): """ This is the much more accurate approx functional eqn posted by Terry at https://terrytao.wordpress.com/2018/02/02/polymath15-second-thread-generalising-the-riemann-siegel-approximate-functional-equation/#comment-492182 :param z: point at which H_t is computed :param t: the "time" parameter :return: the A part in Ht """ z, t = mp.mpc(z), mp.mpc(t) s = (1 + 1j * z.real - z.imag) / 2 tau = mp.sqrt(s.imag / (2 * mp.pi())) N = int(tau) A_pre = (1/16) * s * (s-1) \ * mp.power(mp.pi(), -1*s/2) * mp.gamma(s/2) A_sum = 0.0 for n in range(1, N + 1): if t.real > 0: A_sum += mp.exp( (t / 16) * mp.power(mp.log( (s + 4) / (2 * mp.pi() * n * n)), 2)) / mp.power(n, s) else: A_sum += 1 / mp.power(n, s) return A_pre * A_sum
def run_hessenberg(A, verbose=0): if verbose > 1: print("original matrix (hessenberg):\n", A) n = A.rows Q, H = mp.hessenberg(A) if verbose > 1: print("Q:\n", Q) print("H:\n", H) B = Q * H * Q.transpose_conj() eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for x in xrange(n): for y in xrange(n): err0 += abs(A[y, x] - B[y, x]) err0 /= n * n err1 = 0 for x in xrange(n): for y in xrange(x + 2, n): err1 += abs(H[y, x]) if verbose > 0: print("difference (H):", err0, err1) if verbose > 1: print("B:\n", B) assert err0 < eps assert err1 == 0
def plot_C_pi(): C = [] for m in [0, 1]: Cm = [] for i in range(0, len(lmx)): Crow = [] for j in range(0, len(lmy)): if m == 0: Crow.append(1) if m == 1: Crow.append( float( mp.norm(-mp.exp(1j * (mp.atan( mp.im(eq5.fl(lmx[i][j], lmy[i][j], 0)) / mp.re(eq5.fl(lmx[i][j], lmx[i][j], 0)))))))) Cm.append(Crow) C.append(Cm) for m in range(0, len(C)): plt.figure() plt.title("C matrix for band pi, element number " + str(m)) plt.contourf(lmx, lmy, C[m], cmap=plt.get_cmap("coolwarm")) plt.colorbar() plt.xlabel(r'$l_x$ $[m^{-1}]$') plt.ylabel(r'$l_y$ $[m^{-1}]$')
def run_eig(A, verbose=0): if verbose > 1: print("original matrix (eig):\n", A) n = A.rows E, EL, ER = mp.eig(A, left=True, right=True) if verbose > 1: print("E:\n", E) print("EL:\n", EL) print("ER:\n", ER) eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for i in xrange(n): B = A * ER[:, i] - E[i] * ER[:, i] err0 = max(err0, mp.mnorm(B)) B = EL[i, :] * A - EL[i, :] * E[i] err0 = max(err0, mp.mnorm(B)) err0 /= n * n if verbose > 0: print("difference (E):", err0) assert err0 < eps
def run_hessenberg(A, verbose = 0): if verbose > 1: print("original matrix (hessenberg):\n", A) n = A.rows Q, H = mp.hessenberg(A) if verbose > 1: print("Q:\n",Q) print("H:\n",H) B = Q * H * Q.transpose_conj() eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for x in xrange(n): for y in xrange(n): err0 += abs(A[y,x] - B[y,x]) err0 /= n * n err1 = 0 for x in xrange(n): for y in xrange(x + 2, n): err1 += abs(H[y,x]) if verbose > 0: print("difference (H):", err0, err1) if verbose > 1: print("B:\n", B) assert err0 < eps assert err1 == 0
def run_eig(A, verbose = 0): if verbose > 1: print("original matrix (eig):\n", A) n = A.rows E, EL, ER = mp.eig(A, left = True, right = True) if verbose > 1: print("E:\n", E) print("EL:\n", EL) print("ER:\n", ER) eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for i in xrange(n): B = A * ER[:,i] - E[i] * ER[:,i] err0 = max(err0, mp.mnorm(B)) B = EL[i,:] * A - EL[i,:] * E[i] err0 = max(err0, mp.mnorm(B)) err0 /= n * n if verbose > 0: print("difference (E):", err0) assert err0 < eps
def run_eigsy(A, verbose = False): if verbose: print("original matrix:\n", str(A)) D, Q = mp.eigsy(A) B = Q * mp.diag(D) * Q.transpose() C = A - B E = Q * Q.transpose() - mp.eye(A.rows) if verbose: print("eigenvalues:\n", D) print("eigenvectors:\n", Q) NC = mp.mnorm(C) NE = mp.mnorm(E) if verbose: print("difference:", NC, "\n", C, "\n") print("difference:", NE, "\n", E, "\n") eps = mp.exp( 0.8 * mp.log(mp.eps)) assert NC < eps assert NE < eps return NC
def w(sigma, t, T0dash): wterm1 = 1 + (sigma**2) / (T0dash**2) wterm2 = 1 + ((1 - sigma)**2) / (T0dash**2) wterm3 = (sigma - 1) * mp.log(wterm1) / 4.0 + nonnegative( (T0dash / 2.0) * mp.atan(sigma / T0dash) - sigma / 2.0) + 1 / (12.0 * (T0dash - 0.33)) return mp.sqrt(wterm1) * mp.sqrt(wterm2) * mp.exp(wterm3)
def run_eigsy(A, verbose=False): if verbose: print("original matrix:\n", str(A)) D, Q = mp.eigsy(A) B = Q * mp.diag(D) * Q.transpose() C = A - B E = Q * Q.transpose() - mp.eye(A.rows) if verbose: print("eigenvalues:\n", D) print("eigenvectors:\n", Q) NC = mp.mnorm(C) NE = mp.mnorm(E) if verbose: print("difference:", NC, "\n", C, "\n") print("difference:", NE, "\n", E, "\n") eps = mp.exp(0.8 * mp.log(mp.eps)) assert NC < eps assert NE < eps return NC
def Ht_AFE_B(z, t): """ This is the much more accurate approx functional eqn posted by Terry at https://terrytao.wordpress.com/2018/02/02/polymath15-second-thread-generalising-the-riemann-siegel-approximate-functional-equation/#comment-492182 :param z: point at which H_t is computed :param t: the "time" parameter :return: the B part in Ht """ z, t = mp.mpc(z), mp.mpc(t) s = (1 + 1j * z.real - z.imag) / 2 tau = mp.sqrt(s.imag / (2 * mp.pi())) M = int(tau) B_pre = (1 / 16.0) * s * (s - 1) * mp.power(mp.pi(), 0.5 * (s - 1)) * mp.gamma(0.5 * (1 - s)) B_sum = 0.0 for m in range(1, M + 1): if t.real > 0: B_sum += mp.exp( (t / 16.0) * mp.power(mp.log( (5 - s) / (2 * mp.pi() * m * m)), 2)) / mp.power(m, 1 - s) else: B_sum += 1 / mp.power(m, 1 - s) return B_pre * B_sum
def log_likelihood(self, x, S=10): # define the posterior q(z|x) / encode x into q(z|x) qz = self.posterior(x) # define the prior p(z) pz = self.prior(batch_size=x.size(0)) # sample S samples from the posterior per data point x z = qz.rsample([S]) # [S, batchsize, latentdim] # define the observation model p(x|z) = B(x | g(z)) px = self.observation_model(z) # Calculating Monte Carlo Estimate of log likelihood sum_log_lik = px.log_prob(x).sum(-1) + pz.log_prob(z).sum( -1) - qz.log_prob(z).sum(-1) log_lik = torch.zeros(x.shape[0]) for i in range(x.shape[0]): tmp = mp.log( sum([mp.exp(t) for t in sum_log_lik[:, i].detach().numpy()]) / S) log_lik[i] = float(tmp) ave_log_lik = log_lik.mean() n_in_ave = x.shape[0] return { "log_like": log_lik, "average_log_like": ave_log_lik, "n": n_in_ave }
def abtoy_generalbound(N, numfactors=1): pset = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] pset = pset[:numfactors] pprod = reduce(mul, pset) ppset = powerset(pset)[1:] L_sum, R_sum = 0.0, 0.0 factorN = 1 / mp.power(N, 0.4) for n in range(1, pprod * N + 1): lcond = deltaN(n, N) rcond = deltaN(n, N) for comb in ppset: combprod = reduce(mul, comb) if len(comb) > 1: subcomb = findsubsets(comb, 2) subcombprods = [mp.log(i[0]) * mp.log(i[1]) for i in subcomb] sumexpcombprod = mp.exp(0.2 * sum(subcombprods)) denom2 = mp.power(n / float(combprod), 0.2 * mp.log(combprod)) * sumexpcombprod else: denom2 = mp.power(n / float(combprod), 0.2 * mp.log(combprod)) lterm = ((-1)**len(comb)) * deltaN(n, combprod * N) * divdelta( n, combprod) / denom2 rterm = lterm / mp.power(combprod, 0.4) lcond += lterm rcond += rterm L_sum += abs(lcond) / mp.power(n, 0.7 + 0.1 * mp.log(N * N / n)) R_sum += abs(rcond) / mp.power(n, 0.3 + 0.1 * mp.log(N * N / n)) L_sum = L_sum - 1 R_sum = R_sum * factorN return [N, pset, L_sum, R_sum, 1 - L_sum - R_sum]
def cumulants(self, gamma): """ Compute .. math:: \Lambda(\gamma) = \log\left(\int_{\mathbb{R}^n} e^{\gamma \|z\|^2_2} F(dz)\right) as well as its first two derivatives with respect to $\gamma$, where $F$ is the empirical distribution of `self.sample`. """ norm_squared = self.sample M = norm_squared.mean() M0 = float(np.mean([mp.exp(gamma*(ns-M)) for ns in norm_squared])) M0 *= mp.exp(gamma*M) M1 = np.mean([np.exp(float(gamma*ns+np.log(ns)-mp.log(M0))) for ns in norm_squared]) M2 = np.mean([np.exp(float(gamma*ns+2*np.log(ns)-mp.log(M0))) for ns in norm_squared]) return M0, M1, (M2-M1**2)
def test_levin_2(): # [2] A. Sidi - "Pratical Extrapolation Methods" p.373 mp.dps = 17 z=mp.mpf(10) eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "sidi", variant = "t") n = 0 while 1: s = (-1)**n * mp.fac(n) * z ** (-n) v, e = L.step(s) n += 1 if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp(-x)/(1+x/z),[0,mp.inf]) # there is also a symbolic expression for the integral: # exact = z * mp.exp(z) * mp.expint(1,z) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-1) ** n * mp.fac(n) * z ** (-n), [0, mp.inf], method = "sidi", levin_variant = "t") assert err < eps
def test_levin_3(): mp.dps = 17 z=mp.mpf(2) eps = mp.mpf(mp.eps) with mp.extraprec(7*mp.prec): # we need copious amount of precision to sum this highly divergent series L = mp.levin(method = "levin", variant = "t") n, s = 0, 0 while 1: s += (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)) n += 1 v, e = L.step_psum(s) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.8 * mp.log(eps)) exact = mp.quad(lambda x: mp.exp( -x * x / 2 - z * x ** 4), [0,mp.inf]) * 2 / mp.sqrt(2 * mp.pi) # there is also a symbolic expression for the integral: # exact = mp.exp(mp.one / (32 * z)) * mp.besselk(mp.one / 4, mp.one / (32 * z)) / (4 * mp.sqrt(z * mp.pi)) err = abs(v - exact) assert err < eps w = mp.nsum(lambda n: (-z)**n * mp.fac(4 * n) / (mp.fac(n) * mp.fac(2 * n) * (4 ** n)), [0, mp.inf], method = "levin", levin_variant = "t", workprec = 8*mp.prec, steps = [2] + [1 for x in xrange(1000)]) err = abs(v - w) assert err < eps
def test_cohen_alt_0(): mp.dps = 17 AC = mp.cohen_alt() S, s, n = [], 0, 1 while 1: s += -((-1) ** n) * mp.one / (n * n) n += 1 S.append(s) v, e = AC.update_psum(S) if e < mp.eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(mp.eps)) err = abs(v - mp.pi ** 2 / 12) assert err < eps
def test_cohen_alt_1(): mp.dps = 17 A = [] AC = mp.cohen_alt() n = 1 while 1: A.append( mp.loggamma(1 + mp.one / (2 * n - 1))) A.append(-mp.loggamma(1 + mp.one / (2 * n))) n += 1 v, e = AC.update(A) if e < mp.eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") v = mp.exp(v) err = abs(v - 1.06215090557106) assert err < 1e-12
def entropy(NMZ, NM, NZ, NZW, M, K, J, alpha, phi): ''' compute perplexity as a function of entropy of the model ''' AK = K * alpha N = 0 ent = 0 for m, d in enumerate(DTM): #print "m:", m #print "d", d theta = NMZ[m, :] / (M + AK) #print theta ent -= mp.log(np.inner(dryrun[:,m],theta)) #print "ent:", ent N += M return mp.exp(ent/N)
def run_schur(A, verbose = 0): if verbose > 1: print("original matrix (schur):\n", A) n = A.rows Q, R = mp.schur(A) if verbose > 1: print("Q:\n", Q) print("R:\n", R) B = Q * R * Q.transpose_conj() C = Q * Q.transpose_conj() eps = mp.exp(0.8 * mp.log(mp.eps)) err0 = 0 for x in xrange(n): for y in xrange(n): err0 += abs(A[y,x] - B[y,x]) err0 /= n * n err1 = 0 for x in xrange(n): for y in xrange(n): if x == y: C[y,x] -= 1 err1 += abs(C[y,x]) err1 /= n * n err2 = 0 for x in xrange(n): for y in xrange(x + 1, n): err2 += abs(R[y,x]) if verbose > 0: print("difference (S):", err0, err1, err2) if verbose > 1: print("B:\n", B) assert err0 < eps assert err1 < eps assert err2 == 0
def test_levin_nsum(): mp.dps = 17 with mp.extraprec(mp.prec): z = mp.mpf(10) ** (-10) a = mp.nsum(lambda n: n**(-(1+z)), [1, mp.inf], method = "l") - 1 / z assert abs(a - mp.euler) < 1e-10 eps = mp.exp(0.8 * mp.log(mp.eps)) a = mp.nsum(lambda n: (-1)**(n-1) / n, [1, mp.inf], method = "sidi") assert abs(a - mp.log(2)) < eps z = 2 + 1j f = lambda n: mp.rf(2 / mp.mpf(3), n) * mp.rf(4 / mp.mpf(3), n) * z**n / (mp.rf(1 / mp.mpf(3), n) * mp.fac(n)) v = mp.nsum(f, [0, mp.inf], method = "levin", steps = [10 for x in xrange(1000)]) exact = mp.hyp2f1(2 / mp.mpf(3), 4 / mp.mpf(3), 1 / mp.mpf(3), z) assert abs(exact - v) < eps
def test_levin_1(): mp.dps = 17 eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "levin", variant = "v") A, n = [], 1 while 1: s = mp.mpf(n) ** (2 + 3j) n += 1 A.append(s) v, e = L.update(A) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) err = abs(v - mp.zeta(-2-3j)) assert err < eps w = mp.nsum(lambda n: n ** (2 + 3j), [1, mp.inf], method = "levin", levin_variant = "v") err = abs(v - w) assert err < eps
def test_levin_0(): mp.dps = 17 eps = mp.mpf(mp.eps) with mp.extraprec(2 * mp.prec): L = mp.levin(method = "levin", variant = "u") S, s, n = [], 0, 1 while 1: s += mp.one / (n * n) n += 1 S.append(s) v, e = L.update_psum(S) if e < eps: break if n > 1000: raise RuntimeError("iteration limit exceeded") eps = mp.exp(0.9 * mp.log(eps)) err = abs(v - mp.pi ** 2 / 6) assert err < eps w = mp.nsum(lambda n: 1/(n * n), [1, mp.inf], method = "levin", levin_variant = "u") err = abs(v - w) assert err < eps
def run_svd_r(A, full_matrices = False, verbose = True): m, n = A.rows, A.cols eps = mp.exp(0.8 * mp.log(mp.eps)) if verbose: print("original matrix:\n", str(A)) print("full", full_matrices) U, S0, V = mp.svd_r(A, full_matrices = full_matrices) S = mp.zeros(U.cols, V.rows) for j in xrange(min(m, n)): S[j,j] = S0[j] if verbose: print("U:\n", str(U)) print("S:\n", str(S0)) print("V:\n", str(V)) C = U * S * V - A err = mp.mnorm(C) if verbose: print("C\n", str(C), "\n", err) assert err < eps D = V * V.transpose() - mp.eye(V.rows) err = mp.mnorm(D) if verbose: print("D:\n", str(D), "\n", err) assert err < eps E = U.transpose() * U - mp.eye(U.cols) err = mp.mnorm(E) if verbose: print("E:\n", str(E), "\n", err) assert err < eps
from mpmath import mp mp.dps = 50 N = long(sys.argv[1]) if len(sys.argv) > 1 else 1000000 inicio = -1*mp.pi fim = 1*mp.pi dx = (fim-inicio)/(N-1) Idx = mp.mpf(1/dx) with open('RealExponencial.h', 'w') as f: f.write("\n".join([ 'using namespace std;', '', '#define R_EXP_N {N}', '#define R_EXP_inicio {inicio}', '#define R_EXP_fim {fim}', '', '', ]).format(**locals())) f.write('const double RealExponencial[] = {') for i in range(N): value = mp.exp(i*dx + inicio) v = "%.50e" % value f.write( v + ' ,\n') f.write('\n};')
def make_f(m): return lambda x: (0.5 * (1 + mp.erf( (x - E_w)/mp.sqrt(2*V_w/m) )))**power * 1/(mp.sqrt(2 * mp.pi * V_c/m)) * mp.exp( -(x-E_c)**2/(2*V_c/m) )
h = mp.mpf(h.value) k_B = mp.mpf(k_B.value) for f in files: t = mp.mpf(rrlmod.str2val(f.split('_')[3])) data = np.loadtxt(f, dtype=str) bn = data[:,-1] freq = crrls.n2f(map(float, data[:,0]), line, n_max=float(data[-1,0])+1) dn = fc.set_dn(line) beta = np.empty(len(bn), dtype=mp.mpf) betabn = np.empty(len(bn), dtype=mp.mpf) for i in xrange(len(bn)): if i < len(bn)-dn: #bnn = np.divide(bn[i+dn,-1], bn[i,-1]) nu = mp.mpf(freq[i]) bnn = mp.mpf(bn[i+dn]) / mp.mpf(bn[i]) e = mp.mpf(-h*nu*1e6/(k_B*t)) exp = mp.exp(e) beta[i] = (mp.mpf('1') - bnn*exp)/(mp.mpf('1') - exp) if beta[i]*mp.mpf(bn[i]) != 'None': betabn[i] = beta[i]*mp.mpf(bn[i]) else: betabn[i] = -9999 np.savetxt('{0}/bbn2_{1}/{2}bn_beta'.format(cwd, line, f), np.column_stack((data[:-30,0], betabn[:-30])), fmt=('%s', '%s')) os.chdir(cwd)
def _mp_fn(x): """ Actual function that gets evaluated. The caller just vectorizes. """ #return mp.mpf(2)*mp.j1(x)/x return mp.exp(mp.loggamma(x))
B = int((((Vmax_float**2)*rho*e)/(pn - pc_float))) A = int(Rmax_float)**int(B) print Rmax_float print B wind_speed = [] radius_roci = [] print range(1,int(roci_float)) for i in range(1,int(roci_float),1): Vg = (mp.sqrt((((A*B*(pn - int(pc_float)))*mp.exp(int(-A)/(int(i)**int(B))))/(((int(rho)*int(i)**int(B) + ((int(i)**2*int(f)**2)/4))))))) - (((int(i)* int(f))/2)) wind_speed.append(float(Vg)) radius_roci.append(i) print Vg df_windspeed = pd.DataFrame(wind_speed) df_radius = pd.DataFrame(radius_roci) plot_dataframe = pd.DataFrame({'Radius (km)' : radius_roci, 'Windspeed' : wind_speed}) #print plot_dataframe #print datetime #print forecast_time plt.figure()