def mp_comb(N, k): """ The number of combinations of N things taken k at a time, with multiprecision floating-point output. This is often expressed as "N choose k". Parameters ---------- N : int, ndarray Number of things. k : int, ndarray Number of elements taken. Returns ------- val : int, The total number of combinations, with floating-point multiprecision. Notes ----- - Array arguments accepted only for exact=False case. - If k > N, N < 0, or k < 0, then a 0 is returned. Examples -------- >>> n = 80000 >>> k = 40000 >>> mp_comb(n, k) 7.0802212521852e+24079 """ import mpmath as mp val = mp.factorial(N) / (mp.factorial(k) * mp.factorial(N - k)) return val
def mp_comb(N,k): """ The number of combinations of N things taken k at a time, with multiprecision floating-point output. This is often expressed as "N choose k". Parameters ---------- N : int, ndarray Number of things. k : int, ndarray Number of elements taken. Returns ------- val : int, The total number of combinations, with floating-point multiprecision. Notes ----- - Array arguments accepted only for exact=False case. - If k > N, N < 0, or k < 0, then a 0 is returned. Examples -------- >>> n = 80000 >>> k = 40000 >>> mp_comb(n, k) 7.0802212521852e+24079 """ import mpmath as mp val = mp.factorial(N)/(mp.factorial(k)*mp.factorial(N-k)) return val
def sorted_coefficients(H_M): M = sym.simplify(sym.log(H_M.shape[0]) / sym.log(2)) return sym.Matrix([ 1 / sym.Integer(factorial(M)) * sym.simplify(H_M[0, 0]), 1 / sym.Integer(factorial(M - 1)) * sym.simplify(H_M[1, 1]), 1 / sym.Integer(factorial(M - 2)) * sym.simplify(H_M[1, 2]) ])
def integral(pos, shift, poles): """ Returns the inner product of two monic monomials with respect to the positive measure prefactor that turns a `PolynomialVector` into a rational approximation to a conformal block. """ single_poles = [] double_poles = [] ret = mpmath.mpf(0) for p in poles: p = mpmath.mpf(str(p)) if (p - shift) in single_poles: single_poles.remove(p - shift) double_poles.append(p - shift) elif (p - shift) < 0: single_poles.append(p - shift) for i in range(0, len(single_poles)): denom = mpmath.mpf(1) pole = single_poles[i] other_single_poles = single_poles[:i] + single_poles[i + 1:] for p in other_single_poles: denom *= pole - p for p in double_poles: denom *= (pole - p)**2 ret += (mpmath.mpf(1) / denom) * (rho_cross**pole) * ( (-pole)**pos) * mpmath.factorial(pos) * mpmath.gammainc( -pos, a=pole * mpmath.log(rho_cross)) for i in range(0, len(double_poles)): denom = mpmath.mpf(1) pole = double_poles[i] other_double_poles = double_poles[:i] + double_poles[i + 1:] for p in other_double_poles: denom *= (pole - p)**2 for p in single_poles: denom *= pole - p # Contribution of the most divergent part ret += (mpmath.mpf(1) / (pole * denom)) * ((-1)**(pos + 1)) * mpmath.factorial(pos) * ( (mpmath.log(rho_cross))**(-pos)) ret -= (mpmath.mpf(1) / denom) * (rho_cross**pole) * ( (-pole)**(pos - 1)) * mpmath.factorial(pos) * mpmath.gammainc( -pos, a=pole * mpmath.log(rho_cross)) * (pos + pole * mpmath.log(rho_cross)) factor = 0 for p in other_double_poles: factor -= mpmath.mpf(2) / (pole - p) for p in single_poles: factor -= mpmath.mpf(1) / (pole - p) # Contribution of the least divergent part ret += (factor / denom) * (rho_cross**pole) * ( (-pole)**pos) * mpmath.factorial(pos) * mpmath.gammainc( -pos, a=pole * mpmath.log(rho_cross)) return (rho_cross**shift) * ret
def L(m, n, d): list1 = range(m * n + 1, m * n + m + 1 + 1) prod1 = fprod(list1) list2 = [] for k in range(m + 1): list2.append(((-1)**(m * n + m + k)) * comb(m, k) / prod0(m, n, k)) return (1 + d)**(m + 3 / 2) * prod1 / factorial(m) * sqrt( factorial(m * n + m) * fsum(list2))
def xyz2sph_real(lx, ly, lz, m): ''' Factor of xyz component for normalized real spherical harmonic functions r^l*Y(l,m) = \sum_{lx+ly+lz=l} x^lx*y^lyz^lz * c(l,m,lx,ly,lz) Y(l,m) is a real spherical harmonic function with Condon-Shortley phase convention Ref: H. B. Schlegel and M. J. Frisch, Int. J. Quant. Chem., 54(1995), 83-87. ''' if (lx + ly + m) % 2: return 0 l = lx + ly + lz j = (lx + ly - abs(m)) // 2 num = (2 * l + 1) * mpmath.factorial(l - abs(m)) div = mpmath.factorial(l + abs(m)) c0 = mpmath.sqrt(num / (div * 4 * mpmath.pi)) * (.5**l) / mpmath.factorial(l) cp = 0 for i in range(max(0, j), (l - abs(m)) // 2 + 1): cp0 = binomial(l,i) * binomial(i,j) \ * mpmath.factorial(2*l-2*i) / mpmath.factorial(l-abs(m)-2*i) if i % 2: cp -= cp0 else: cp += cp0 c0 = c0 * cp cp = 0 if m >= 0: for k in range(max(0, (lx - abs(m) + 1) // 2), min(j, lx // 2) + 1): cp0 = binomial(j, k) * binomial(abs(m), lx - 2 * k) r = (abs(m) - lx + 2 * k) % 4 if r == 0: cp = cp + cp0 elif r == 2: cp = cp - cp0 if m == 0: c = c0 * cp else: c = mpmath.sqrt(2) * c0 * cp else: for k in range(max(0, (lx - abs(m) + 1) // 2), min(j, lx // 2) + 1): cp0 = binomial(j, k) * binomial(abs(m), lx - 2 * k) r = (abs(m) - lx + 2 * k) % 4 if r == 1: cp = cp - cp0 elif r == 3: cp = cp + cp0 c = -mpmath.sqrt(2) * c0 * cp return c
def projectToRelativeCoordinateBasis_mpmathVersion(r, s, m, M): sumRange = range(max([0, r - M]), min([r, m]) + 1) x = mpmath.factorial(r) / mpmath.factorial(m) y = mpmath.factorial(s) / mpmath.factorial(M) z = 2**(m + M) upFrontFactor = mpmath.sqrt(x * y / z) return sum([ upFrontFactor * nCrMP(m, a) * nCrMP(M, r - a) * ((-1)**a) for a in sumRange ])
def sample_coefs(k, sigma, interaction=False, intercept=False): coefs = [] n_int_terms = 0 for i in range(k): if interaction: if i > 1: n_int_terms = int(factorial(i) / (factorial(2) * factorial(i - 2))) coefs += [np.random.normal(0, sigma, size=i + n_int_terms + 1)] if not intercept: for coef in coefs: coef[0] = 0 return coefs
def factorial(B): """ ! B """ B = fuzzyInteger(B) try: if isinstance(B, int): return int(mpmath.factorial(B)) return float(mpmath.factorial(B)) except ValueError: assertError("DOMAIN ERROR")
def norm2(n, magneticLength): """ Computes <m|m> where <z|m> = z^m*usual exp factor. """ return math.pi * mpmath.factorial(n) * (2**(n + 1)) * magneticLength**(2 * (n + 1))
def twothree_n(parameters, n): """Analytic solution to the 2^3 multistate model for a single copy number n. Arguments: parameters -- List of the ten rate parameters: lamda0,mu0,lamda1,mu1,lamda2,mu2, KB,k0,k1,k2 n -- Copy number at which the distribution is evaluated.""" # Set up the parameters lamda0, mu0, lamda1, mu1, lamda2, mu2, KB, k0, k1, k2 = parameters k0A, k1A = mpm.mpf(KB), mpm.mpf(k0 + KB) k0B, k1B = mpm.mpf(0), mpm.mpf(k1) k0C, k1C = mpm.mpf(0), mpm.mpf(k2) # Obtain list of all possible combinations of r_i r_combinations = [(i, j, k, n - i - j - k) for i in range(n + 1) for j in range(n + 1 - i) for k in range(n + 1 - i - j)] p = mpm.mpf(0) for rc, r0, r1, r2 in r_combinations: p += multinomial_mpm(r_combinations) * power_mpm_memo(KB,rc) * exp_mpm_memo(-KB) * \ power_mpm_memo(k0,r0)*fracrise_mpm_memo(lamda0, mu0, r0) * hyp_mpm_memo(lamda0, mu0, k0, r0) * \ power_mpm_memo(k1,r1)*fracrise_mpm_memo(lamda1, mu1, r1) * hyp_mpm_memo(lamda1, mu1, k1, r1) * \ power_mpm_memo(k2,r2)*fracrise_mpm_memo(lamda2, mu2, r2) * hyp_mpm_memo(lamda2, mu2, k2, r2) return p / mpm.factorial(n)
def compute_single_item_loss_list(u, node_capacity, n_seats, p0): u_to_the_n = math.power(u, node_capacity) C_fact = math.factorial(n_seats) C_to_the_n_minus_c = math.power(n_seats, (node_capacity - n_seats)) denominator = math.fmul(C_fact, C_to_the_n_minus_c) fraction = math.fdiv(u_to_the_n, denominator) return math.fmul(fraction, p0)
def tcaf(y): """ Find an x such that x! =~ y, ie Gamma(x + 1) =~ y. """ x = mpmath.findroot(lambda t: mpmath.factorial(t) - y, (1, 100), solver="bisect") return x
def __dip__(self, p: int, kmax: int, f: LambdaType, x: list, eps: float) -> tuple: """ Calculates the df(s) = (s-1)-th derivative of f at O , for s = 1 .. p+1. Uses k-th degree polynomial for some k satisfying p <= k <= kmax. If the relative change in df(s) from k - 1 to k is less than eps then this determines k and success is true. Otherwise k = kmax and success is false. :param p: maximum derivative to calculate; p <= length(x) <= kmax :param kmax: maximum degree of the interpolating polynomial :param f: function to derive :param x: array of values around 0 :param eps: desired tolerance :return: array of derivatives at 0 """ self.C = mp.zeros(1, int(kmax * (kmax + 3) / 2) + 1) df = mp.zeros(1, p + 1) for k in range(0, kmax + 1): self.__update__(int(k), int(p), x, f(x[int(k)])) if k < p: continue self.r = mp.mpf(1) for s in range(0, p + 1): if self.r: self.r = mp.mpf( mp.fabs(self.C[k - s] - df[s]) <= eps * mp.fabs(self.C[k - s])) df[s] = self.C[k - s] if self.r: break for s in range(1, p + 1): df[s] = mp.factorial(s) * df[s] return df
def H_eff_n(self, n): # k<=m => j<=(n)/2 r = 0 for j in xrange(1, int(math.ceil( n/2. )) + 1 ): b = 2*(2**(2*j)-1)*mpmath.bernoulli(2*j)/mpmath.factorial(2*j) r += b*self.P_0.dot(self.S_k(2*j-1,n-1)).dot(self.P_0) return r
def revert(coeffs, taylor=True): """ Series reversion. Given `coeffs`, the Taylor coefficients of a function, find the Taylor coefficients of the compositional inverse of the function. The calculation here is based on the formulas for the coefficients of the inverse in terms of Bell polynomials: https://en.wikipedia.org/wiki/Bell_polynomials#Reversion_of_series If the argument `taylor` is True, the coefficients must be the Taylor series coefficients. If it is not True, the coefficients are the derivatives. That is, they are the Taylor coefficients multiplied by the factorial terms. """ c0 = coeffs[0] if coeffs[1] == 0: raise ValueError('coeffs[1] must be nonzero.') if taylor: # Rescale the coefficients to the derivative values. f = [c * mpmath.factorial(i) for i, c in enumerate(coeffs)] else: f = coeffs m = len(f) f_hat = [f[k + 1] / ((k + 1) * f[1]) for k in range(1, m - 1)] # inv_derivs will be the series of derivatives of the inverse. g = [0] * m g[1] = 1 / f[1] for n in range(2, m): s = sum((-1)**k * mpmath.rf(n, k) * _bell_incomplete_poly(n - 1, k, f_hat[:n - k]) for k in range(1, n)) g[n] = s / f[1]**n if taylor: # Convert the derivatives to the Taylor coefficients inv_coeffs = [c / mpmath.factorial(k) for k, c in enumerate(g)] else: inv_coeffs = g return inv_coeffs, c0
def zetac_series(N): coeffs = [] with mpmath.workdps(100): coeffs.append(-1.5) for n in range(1, N): coeff = mpmath.diff(mpmath.zeta, 0, n) / mpmath.factorial(n) coeffs.append(coeff) return coeffs
def H_eff_n(self, n): # k<=m => j<=(n)/2 r = 0 for j in xrange(1, int(math.ceil(n / 2.)) + 1): b = 2 * (2**(2 * j) - 1) * mpmath.bernoulli( 2 * j) / mpmath.factorial(2 * j) r += b * self.P_0.dot(self.S_k(2 * j - 1, n - 1)).dot(self.P_0) return r
def zetac_series(N): coeffs = [] with mpmath.workdps(100): coeffs.append(-1.5) for n in range(1, N): coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n) coeffs.append(coeff) return coeffs
def main(): func = lambda x: mpmath.exp(mpmath.power(x, 2)) precision = sys.argv[1].split('**') precision = math.pow(int(precision[0]), int(precision[1])) x = mpmath.mpf(float(sys.argv[2])) print "expected value = %f" % mpmath.quad(func, [0, x]) print "precision = %f" % precision print "x = %f" % x print "max Taylor degree to try = %s" % sys.argv[3] print "" upperbound = int(sys.argv[3]) lowerbound = 0 lowestn = 0 # find the degree logarithmically, this is usually faster than trying 0..n while lowerbound < upperbound: n = (lowerbound + upperbound) / 2 # estimate the remainder diff = mpmath.diff(func, x, n) rn = diff / mpmath.factorial(n + 1) rn = rn * mpmath.power(x, n + 1) # is it good enough? if rn < precision: upperbound = n lowestn = n else: lowerbound = n + 1 if lowestn: print "lowest Taylor degree needed = %d" % lowestn coefficients = [] # find the coefficients of our Taylor polynomial for k in reversed(range(lowestn + 1)): if k > 0: coefficients.append(mpmath.diff(func, 0, k - 1) / mpmath.factorial(k)) # compute the value of the polynomial (add 0 for the free variable, the value of the indefinite integral at 0) p = mpmath.polyval(coefficients + [0], x) print "computed value = %f" % p else: print "max n is too low"
def test_sf(k, lam): with mpmath.extradps(5): sf = poisson.sf(k, lam) S = sum([mpmath.power(lam, i) / mpmath.factorial(i) for i in range(k+1)]) expected = 1 - mpmath.exp(-lam) * S assert abs(sf - expected) < 1e-40
def test_power_series(self, A, T, depth=15): A_t = -A * T A_i = A_t series = eye(4) for i in xrange(1, depth): print i series = series + A_i / mp.factorial(i + 1) A_i = A_i * A_t return T * series
def pmf(k, lam): """ Probability mass function of the Poisson distribution. """ if k < 0: return mpmath.mp.zero with mpmath.extradps(5): lam = mpmath.mpf(lam) return mpmath.power(lam, k) * mpmath.exp(-lam) / mpmath.factorial(k)
def u_binom(N): out = np.zeros((len(x),len(t))) out = out + 0.5*W(0)[...,None]*np.ones(len(t)) with mpmath.workdps(workdps): for n in range(1,N): coeff = np.zeros(len(x)) for m in range(n): coeff = coeff + (-1)**((n-1)-m)*mpmath.binomial(n-1,m)*W(m+1) out = out + coeff[...,None]*((t/(2*tau))**n)/mpmath.factorial(n) return out
def getCoefficient(self, i: int) -> float: '''Return the i'th coefficient. :param i: the index :returns: the coefficient of x^i''' # we need to adapt the step distance for the integration # so that it is smaller than 1 / i step = 1 / (numpy.ceil((i + 1) / 99) * 100) return float((self._differentiate(0.0, i, dx=step) / factorial(i)).real)
def zeta_even_integers(N): values = [] for n in range(0, N + 1): zeta_2n = ( (-1)**(n + 1) * mpmath.bernoulli(2 * n) * (2 * mpmath.pi)**(2 * n) / (2 * mpmath.factorial(2 * n)) ) values.append(zeta_2n) return values
def GetAnalyticalPDF(kon,koff,kdeg,ksyn): """ Get the analytical probability density function. The analytical solution is taken from Sharezaei and Swain 2008 - Analytical distributions for stochastic gene expression """ import mpmath mpmath.mp.pretty = True x_values = np.linspace(0,50,10000) y_values = [] for m in x_values: a = ((ksyn/kdeg)**m)*np.exp(-ksyn/kdeg)/mpmath.factorial(m) b = mpmath.mp.gamma((kon/kdeg)+m) * mpmath.mp.gamma(kon/kdeg + koff/kdeg)/ (mpmath.mp.gamma(kon/kdeg + koff/kdeg + m)* mpmath.mp.gamma(kon/kdeg)) c = mpmath.mp.hyp1f1(koff/kdeg,kon/kdeg + koff/kdeg + m,ksyn/kdeg) y_values.append(a*b*c) return x_values,y_values
def sigma_plus(n, l, E, Z): """Cross section for bound-free absorption from (n, l) through dipole transition to E with angular momentum l+1""" eta = (Z**2 * Ry_in_erg / E)**.5 rho = eta / n nu = E / h GlA = G_l(l + 1, -(l + 1 - n), eta, rho) GlB = G_l(l + 1, -(l - n), eta, rho) prefactor = 2**(4 * l + 6) / 3 * np.pi * e_e**2 / m_e / c / nu A = 1 for l_i in range(l + 1): A *= ((l_i + 1)**2 + eta**2) B = (l + 1)**2 * factorial(n + l) / (2 * l + 1) / factorial(2 * l + 1) / \ factorial(2 * l + 2) / factorial(n - l - 1) / ((l + 1)**2 + eta**2)**2 C = np.exp(-4 * eta * np.arctan2(1, rho)) / (1 - np.exp(-2 * np.pi * eta)) D = rho**(2 * l + 4) * eta**2 / (1 + rho**2)**(2 * n) E = ((l + 1 - n) * GlA + (l + 1 + n) / (1 + rho**2) * GlB)**2 return prefactor * A * B * C * D * E
def summed_score_pv(sum_score, num_segments, raw=True): """ Compute p-value over sum of scores for top r segments. As opposed to multi_segment_pv, this considers the total sum of scores for the top r scoring segments together. Computes formula [5] in Karlin & Altschul, PNAS 1993 Prob(Tr >= x) ~ exp(-x) * x**(r-1) / r! * (r - 1)! where Tr = S1' + ... + Sr' is the sum over the normalized scores of the top r segments :param sum_score: :param num_segments: :param raw: return raw P-value instead of -log10(pv) :return: """ with mpm.workprec(NUM_PREC_KA_PV): x = mpm.convert(sum_score) r = mpm.convert(str(num_segments)) rm1 = mpm.fsub(r, mpm.convert('1')) enum = mpm.fmul(mpm.exp(mpm.fneg(x)), mpm.power(x, rm1)) denom = mpm.fmul(mpm.factorial(r), mpm.factorial(rm1)) res = mpm.fdiv(enum, denom) if not raw: res = mpm.fneg(mpm.log10(res)) res = float(res) # Equivalent implementation using Python standard library: # # r = num_segments # x = sum_score # enum = math.exp(-x) * math.pow(x, (r - 1)) # denom = math.factorial(r) * math.factorial(r - 1) # res = enum / denom # if not raw: # res = -1 * math.log10(res) return res
def sigma_minus(n, l, E, Z): """Cross section for bound-free absorption from (n, l) through dipole transition to E with angular momentum l-1""" eta = (Z**2 * Ry_in_erg / E)**.5 nu = E / h if l == 0: return 0 rho = eta / n GlA = G_l(l, -(l + 1 - n), eta, rho) GlB = G_l(l, -(l - 1 - n), eta, rho) prefactor = 2**(4 * l) / 3 * np.pi * e_e**2 / m_e / c / nu A = 1 for l_i in range(1, l): A *= (l_i**2 + eta**2) B = l**2 * factorial(n + l) / factorial(2 * l + 1) / \ factorial(2 * l - 1) / factorial(n - l - 1) C = np.exp(-4 * eta * np.arctan2(1, rho)) / (1 - np.exp(-2 * np.pi * eta)) D = rho**(2 * l + 2) / (1 + rho**2)**(2 * n - 2) E = (GlA - (1 + rho**2)**(-2) * GlB)**2 return prefactor * A * B * C * D * E
def _S(self, n): if n < 1: raise ValueError("i must be greater than or equal to zero.") elif n == 1: return self.L(self.V_od) elif n == 2: return -self.L(self.hat(self.V_d, self.S(1))) else: r = -self.L(self.hat(self.V_d, self.S(n-1))) # k<=m => j<=(n-1)/2 for j in xrange(1, int(math.ceil( (n-1)/2 )) + 1 ): a = 2**(2*j) * mpmath.bernoulli(2*j) / mpmath.factorial(2*j) r += a * self.L(self.S_k(2*j, n-1)) return r
def get_args(): """ Parse argv """ import smartparse as argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("y", type=float, default=1.0, help="Spec to intersect to_spec with") args = parser.parse_args() if args.y < 1.0 or args.y > mpmath.factorial(100): parser.error("y should be >= 1 and <= 100!") return args
def _S(self, n): if n < 1: raise ValueError("i must be greater than or equal to zero.") elif n == 1: return self.L(self.V_od) elif n == 2: return -self.L(self.hat(self.V_d, self.S(1))) else: r = -self.L(self.hat(self.V_d, self.S(n - 1))) # k<=m => j<=(n-1)/2 for j in xrange(1, int(math.ceil((n - 1) / 2)) + 1): a = 2**(2 * j) * mpmath.bernoulli(2 * j) / mpmath.factorial( 2 * j) r += a * self.L(self.S_k(2 * j, n - 1)) return r
def analytic_twostate(parameters, N): """ Analytic steady state distribution for a two-state model (leaky telegraph). Requires computation at high precision via mpm for accurate convergence of the summation. Arguments: parameters -- List of the four rate parameters: v12,v21,K0,K1 N -- Maximal mRNA copy number. The distribution is evaluated for n=0:N-1""" v12 = mpm.mpf(parameters[0]) v21 = mpm.mpf(parameters[1]) K0 = mpm.mpf(parameters[2]) K1 = mpm.mpf(parameters[3]) P = mpm.matrix(np.zeros(N)) # Preallocate at high precision for n in range(N): for r in range(n + 1): mpmCalc = mpm.power(K1,n-r) * mpm.power(K0-K1,r) * mpm.exp(-K0) * \ mpm.hyp1f1(v12,v12+v21+r,K0-K1) / (mpm.factorial(n-r) * mpm.factorial(r)) P[n] += mpmCalc * fracrise_mpm(v21, v21 + v12, r) P = np.array([float(p) for p in P]) return P / P.sum()
def I_graph(m, µ, σ): """ Return two array x, y representing the graph of I (with mean value m, mean log_pgen µ, var log_pgen σ) """ rg = np.linspace(0, 3 * m * µ, 1000) S = [(k, scipy.stats.poisson.pmf(k, m)) for k in np.arange(1, max(int(3*m), 200))] Is = [float(mpmath.fsum(1/mpmath.sqrt(2 * np.pi * σ**2 * k) * mpmath.exp(-m) * mpmath.power(m, k) / mpmath.factorial(k) * mpmath.exp(-(x - μ*k)**2/(2 * σ**2 * k)) for k, s in S if s > 1e-6)) + (scipy.stats.poisson.pmf(0, m) if x == 0. else 0) for x in rg] return np.array(rg), np.array(Is)
def compute_formula_second_term(u_divided_by_nseat, node_capacity, n_seats, u): u_to_c_over_c_fact = math.fdiv(math.power(u, n_seats), math.factorial(n_seats)) second_fraction = 0 if u_divided_by_nseat == 1: second_fraction = node_capacity - n_seats + 1 else: u_div_C_to_K_minus_C_plus1 = math.power(u_divided_by_nseat, (node_capacity - n_seats + 1)) one_minus_u_div_C = math.fsub(1, u_divided_by_nseat) second_fraction_numerator = math.fsub(1, u_div_C_to_K_minus_C_plus1) second_fraction = math.fdiv(second_fraction_numerator, one_minus_u_div_C) return math.fmul(u_to_c_over_c_fact, second_fraction)
def GetAnalyticalPDF(kon, koff, kdeg, ksyn): """ Get the analytical probability density function. The analytical solution is taken from Sharezaei and Swain 2008 - Analytical distributions for stochastic gene expression """ import mpmath mpmath.mp.pretty = True x_values = np.linspace(0, 50, 10000) y_values = [] for m in x_values: a = ((ksyn / kdeg)**m) * np.exp(-ksyn / kdeg) / mpmath.factorial(m) b = mpmath.mp.gamma((kon / kdeg) + m) * mpmath.mp.gamma(kon / kdeg + koff / kdeg) / ( mpmath.mp.gamma(kon / kdeg + koff / kdeg + m) * mpmath.mp.gamma(kon / kdeg)) c = mpmath.mp.hyp1f1(koff / kdeg, kon / kdeg + koff / kdeg + m, ksyn / kdeg) y_values.append(a * b * c) return x_values, y_values
def test_int(self, A, B, steady_state): x_0 = Matrix([[self.initial[i]] for i in xrange(len(self.initial))]) rho = Matrix([[self.input[i]] for i in xrange(len(self.input))]) t = symbols("t") t_e = 0.3 print "Calc matrix exponentials" A = A.subs([(self.q[i], self.initial[i]) for i in xrange(len(self.q) - 1)]) A = A.subs([(self.qdot[i], self.initial[i + len(self.qdot) - 1]) for i in xrange(len(self.qdot) - 1)]) B = B.subs([(self.q[i], self.initial[i]) for i in xrange(len(self.q) - 1)]) B = B.subs([(self.qdot[i], self.initial[i + len(self.qdot) - 1]) for i in xrange(len(self.qdot) - 1)]) print "A:" print A print "B:" print N(B) A_exp1 = exp(t_e * A) A_exp2 = exp(-t * A) #A_exp1 = A_exp1.subs([(self.q[i], self.initial[i]) for i in xrange(len(self.q))]) #A_exp1 = A_exp1.subs([(self.qdot[i], self.initial[i + len(self.qdot)]) for i in xrange(len(self.qdot))]) #A_exp2 = A_exp2.subs([(self.q[i], self.initial[i]) for i in xrange(len(self.q))]) #A_exp2 = A_exp2.subs([(self.qdot[i], self.initial[i + len(self.qdot)]) for i in xrange(len(self.qdot))]) print "calculate integral" #integral = integrate(A_exp2, (t, 0, t_e)) t0 = time.time() integral = self.test_power_series(A, t_e, 15) print "Integration took " + str(time.time() - t0) + " seconds" #print integral print "====================" print "integral " + str(integral) f = A_exp1 * x_0 + A_exp1 * integral * B * rho f = f.subs(t, t_e) print f print N(f) print "factorial " + str(mp.factorial(4)) sleep
def eqn8(N, B): sumterms = [power(B, n) / factorial(n) for n in range(int(N) + 1)] return 1. / (exp(-B) * fsum(sumterms))
def _mpmath_kraft_burrows_nousek(N, B, CL): '''Upper limit on a poisson count rate The implementation is based on Kraft, Burrows and Nousek in `ApJ 374, 344 (1991) <http://adsabs.harvard.edu/abs/1991ApJ...374..344K>`_. The XMM-Newton upper limit server used the same formalism. Parameters ---------- N : int Total observed count number B : float Background count rate (assumed to be known with negligible error from a large background area). CL : float Confidence level (number between 0 and 1) Returns ------- S : source count limit Notes ----- Requires the `mpmath <http://mpmath.org/>`_ library. See `~astropy.stats.scipy_poisson_upper_limit` for an implementation that is based on scipy and evaluates faster, but runs only to about N = 100. ''' from mpmath import mpf, factorial, findroot, fsum, power, exp, quad N = mpf(N) B = mpf(B) CL = mpf(CL) def eqn8(N, B): sumterms = [power(B, n) / factorial(n) for n in range(int(N) + 1)] return 1. / (exp(-B) * fsum(sumterms)) eqn8_res = eqn8(N, B) factorial_N = factorial(N) def eqn7(S, N, B): SpB = S + B return eqn8_res * (exp(-SpB) * SpB**N / factorial_N) def eqn9_left(S_min, S_max, N, B): def eqn7NB(S): return eqn7(S, N, B) return quad(eqn7NB, [S_min, S_max]) def find_s_min(S_max, N, B): ''' Kraft, Burrows and Nousek suggest to integrate from N-B in both directions at once, so that S_min and S_max move similarly (see the article for details). Here, this is implemented differently: Treat S_max as the optimization parameters in func and then calculate the matching s_min that has has eqn7(S_max) = eqn7(S_min) here. ''' y_S_max = eqn7(S_max, N, B) if eqn7(0, N, B) >= y_S_max: return 0. else: def eqn7ysmax(x): return eqn7(x, N, B) - y_S_max return findroot(eqn7ysmax, (N - B) / 2.) def func(s): s_min = find_s_min(s, N, B) out = eqn9_left(s_min, s, N, B) return out - CL S_max = findroot(func, N - B, tol=1e-4) S_min = find_s_min(S_max, N, B) return float(S_min), float(S_max)
def __init__(self,rang=10,acc=100): # Generates the coefficients of Legendre polynomial of n-th order. # acc is the number of decimal characters of the coefficients. # self.cf is the list with coefficients. self.rang = rang self.acc = mp.dps = acc cn = mpf(0.0) k = mpf(0) n = mpf(rang) m = mpf(n/2) cf = [] for k in range(n+1): cn = (- 1)**(n+k)*factorial(n+k)/(factorial(nk)*factorial(k)*factorial(k)) cf.append(cn) cf.reverse() # Generates the coefficients of of the implicit Runge-Kutta scheme of Gauss-Legendre type. # acc is the number of the decimal characters of the coefficients. # Gives back the cortege (r,b,a), the terms of which correspond to Butcher scheme # # r1 | a11 . . . а1n # . | . . # . | . . # . | . . # rn | an1 . . . ann # ---+-------------- # | b1 . . . bn self.r = polyroots(cf) A1 = matrix(rang) for j in range(n): for k in range(n): A1[k,j] = self.r[j]**k bn = [] for j in range(n): bn.append(mpf(1.0)/mpf(j+1)) B = matrix(bn) self.b = lu_solve(A1,B) self.a = matrix(rang) for i in range(1,n+1): A1 = matrix(rang) cil = [] for l in range(1,n+1): cil.append(mpf(self.r[i- 1])**l/mpf(l)) for j in range(n): A1[l-1,j] = self.r[j]**(l-1) Cil = matrix(cil) an = lu_solve(A1,Cil) for k in range(n): self.a[i-1,k] = an[k] def init(self,f,t,h,initvalues): self.size = len(initvalues) self.f = f 31 self.t = t self.h = h self.yb = matrix(initvalues) self.ks = matrix(self.size,self.rang) for k in range(self.size): for i in range(self.rang): self.ks[k,i] = self.r[i] self.tn = matrix(1,self.rang) for i in range(self.rang): self.tn[i] = t + h*self.r[i] self.y = matrix(self.size,self.rang) for k in range(self.size): for i in range(self.rang): self.y[k,i] = self.yb[k] temp = mpf(0.0) for j in range(self.rang): temp += self.a[i,j]*self.ks[k,j] self.y[k,i] += temp self.yn = matrix(self.yb) def iterate(self,tn,y,yn,ks): # Generates the coefficients of the implicit Runge-Kutta scheme for the given step # with the method of the simple iteration with an initial value, coinciding with the coefficients, # calculated at the previous step. At sufficiently small step this must # work. There exists such a value of the step, Under which convergence is guaranteed. # No automatic re-setup of the step is foreseen in this procedure. mp.dps = self.acc y0 = matrix(yn) norme = mpf(1.0) #eps0 = pow(eps,mpf(3.0)/mpf(4.0)) eps0 = sqrt(eps) ks1 = matrix(self.size,self.rang) yt = matrix(1,self.size) count = 0 while True: count += 1 for i in range(self.rang): for k in range(self.size): yt[k] = y[k,i] for k in range(self.size): ks1[k,i] = self.f(tn,yt)[k] norme = mpf(0.0) 2 for k in range(self.size): for i in range(self.rang): norme += (ks1[k,i]- ks[k,i])*(ks1[k,i]-ks[k,i]) norme = sqrt(norme) for k in range(self.size): for i in range(self.rang): ks[k,i] = ks1[k,i] for k in range(self.size): for i in range(self.rang): y[k,i] = y0[k] for j in range(self.rang): y[k,i] += self.h*self.a[i,j]*ks[k,j] if norme <= eps0: break if count >= 100: print unicode('No convergence','UTF-8') exit(0) return ks1 def step(self): mp.dps = self.acc self.ks = self.iterate(self.tn,self.y,self.yn,self.ks) for k in range(self.size): for i in range(self.rang): self.yn[k] += self.h*self.b[i]*self.ks[k,i] for k in range(self.size): for i in range(self.rang): self.y[k,i] = self.yn[k] for j in range(self.rang): self.y[k,i] += self.a[i,j]*self.ks[k,j] self.t += self.h for i in range(self.rang): self.tn[i] = self.t + self.h*self.r[i] return self.yn
Backend.engineFunction("+", lambda op: op[0] + op[1]) Backend.engineFunction("-", lambda op: op[0] - op[1]) Backend.engineFunction("mul", lambda op: op[0] * op[1]) Backend.engineFunction("div", lambda op: op[0] / op[1]) Backend.engineFunction("^", lambda op: op[0] ** op[1]) Backend.engineFunction("10^x", lambda op: 10 ** op, operands=1) Backend.engineFunction("x^2", lambda op: op ** 2, operands=1) Backend.engineFunction("neg", lambda op: op * -1, operands=1) Backend.engineFunction("%", lambda op: op[0] * op[1] / 100) Backend.engineFunction("inv", lambda op: 1 / op, operands=1) Backend.engineFunction("sqrt", lambda op: mpmath.sqrt(op), operands=1) Backend.engineFunction("nthroot", lambda op: mpmath.root(op[0], op[1])) Backend.engineFunction("log", lambda op: mpmath.log(op, b=10), operands=1) Backend.engineFunction("ln", lambda op: mpmath.log(op), operands=1) Backend.engineFunction("e^x", lambda op: mpmath.exp(op), operands=1) Backend.engineFunction("factorial", lambda op: mpmath.factorial(op), operands=1) @Backend.engineFunction(operands=-1) def addall(op): expr = op[0] for i in range(1, len(op)): expr = expr + op[i] return expr @Backend.engineFunction(operands=-1) def suball(op): expr = op[0] for i in range(1, len(op)): expr = expr - op[i] return expr
def eval(self, z): return mpmath.factorial(z)
def T_n( n, rho_mean, z, M, R, h_mass, profile, omegab, omegac, slope, r_char, sigma, alpha, A, M_1, gamma_1, gamma_2, b_0, b_1, b_2, ): np.seterr(divide="ignore", over="ignore", under="ignore", invalid="ignore") """ Takes some global variables! Be carefull if you remove or split some stuff to different container! """ n = np.float64(n) if len(M.shape) == 0: T = np.ones(1) M = np.array([M]) R = np.array([R]) else: T = np.ones(len(M), dtype=np.longdouble) if profile == "dm": for i in range(len(M)): i_range = np.linspace(0, R[i], 100) Ti = (mp.mpf(4.0 * np.pi) / (M[i] * (mp.factorial(2.0 * n + 1.0)))) * mp.mpf( Integrate((i_range ** (2.0 * (1.0 + n))) * (NFW(rho_mean, Con(z, M[i]), i_range)), i_range) ) T[i] = ld.string2longdouble(str(Ti)) elif profile == "gas": for i in range(len(M)): i_range = np.linspace(0, R[i], 100) Ti = (mp.mpf(4.0 * np.pi) / (M[i] * (mp.factorial(2.0 * n + 1.0)))) * mp.mpf( Integrate( (i_range ** (2.0 * (1.0 + n))) * (baryons.u_g(np.float64(i_range), slope, r_char[i], omegab, omegac, M[i])), i_range, ) ) T[i] = ld.string2longdouble(str(Ti)) elif profile == "stars": for i in range(len(M)): i_range = np.linspace(0, R[i], 100) Ti = (mp.mpf(4.0 * np.pi) / (M[i] * (mp.factorial(2.0 * n + 1.0)))) * mp.mpf( Integrate( (i_range ** (2.0 * (1.0 + n))) * ( baryons.u_s( np.float64(i_range), slope, r_char[i], h_mass, M[i], sigma, alpha, A, M_1, gamma_1, gamma_2, b_0, b_1, b_2, ) ), i_range, ) ) T[i] = ld.string2longdouble(str(Ti)) return T
def sph_jn_power(n, z, terms=100): zm = mpmathify(z) s = sum((-zm**2/2)**k/(factorial(k) * fac2(2*n + 2*k + 1)) for k in xrange(terms)) return zm**n * s