def gamma_likelihoods(data, k, theta, xmin, xmax=False, discrete=False): if k<=0 or theta<=0: from numpy import tile from sys import float_info return tile(10**float_info.min_10_exp, len(data)) data = data[data>=xmin] if xmax: data = data[data<=xmax] from numpy import exp from mpmath import gammainc # from scipy.special import gamma, gammainc #Not NEARLY numerically accurate enough for the job if not discrete: likelihoods = (data**(k-1)) / (exp(data/theta) * (theta**k) * float(gammainc(k))) #Calculate how much probability mass is beyond xmin, and normalize by it normalization_constant = 1 - float(gammainc(k, 0, xmin/theta, regularized=True)) #Mpmath's regularized option divides by gamma(k) likelihoods = likelihoods/normalization_constant if discrete: if not xmax: xmax = max(data) if xmax: from numpy import arange X = arange(xmin, xmax+1) PDF = (X**(k-1)) / (exp(X/theta) * (theta**k) * float(gammainc(k))) PDF = PDF/sum(PDF) likelihoods = PDF[(data-xmin).astype(int)] from sys import float_info likelihoods[likelihoods==0] = 10**float_info.min_10_exp return likelihoods
def getnum_zfourge_single(M, z): """ Converts stellar mass to number density at the given redshift using the ZFOURGE mass functions by linearly interpolating the integrated fits between neighboring redshift bins. Parameters ========== M : Stellar mass in units of log(Msun), must be a single value (not an array). z : Redshift Returns ======= N : Comoving cumulative number density in units of log(Mpc^-3) """ from mpmath import gammainc par1, par2 = zfourgeparams(z) x = 10.**(M-par1[1]) g1 = gammainc(par1[2]+1,a=x) g2 = gammainc(par1[4]+1,a=x) N1 = np.log10(10.**(par1[3])*float(g1) + 10.**(par1[5])*float(g2)) x = 10.**(M-par2[1]) g1 = gammainc(par2[2]+1,a=x) g2 = gammainc(par2[4]+1,a=x) N2 = np.log10(10.**(par2[3])*float(g1) + 10.**(par2[5])*float(g2)) return (N1*(par2[0]-z)+N2*(z-par1[0]))/(par2[0]-par1[0])
def muzzin_function(M, par, target=0): from mpmath import gammainc x = 10.**(M-par[1]) g1 = gammainc(par[2]+1,a=x) g2 = gammainc(par[4]+1,a=x) return np.log10(par[3]*float(g1) + par[5]*float(g2))-target
def gaussian_logx_given_r(r, sigma, n_dim): """ Returns logx coordinate corresponding to r values for a Gaussian prior with the specificed standard deviation and dimension Uses mpmath package for arbitary precision. Parameters ---------- r: float or numpy array Radial coordinates at which to evaluate logx. sigma: float Standard deviation of Gaussian. n_dim: int Number of dimensions. Returns ------- logx: float or numpy array Logx coordinates corresponding to input radial coordinates. """ exponent = 0.5 * (r / sigma) ** 2 if isinstance(r, np.ndarray): # needed to ensure output is numpy array logx = np.zeros(r.shape) for i, expo in enumerate(exponent): logx[i] = float(mpmath.log(mpmath.gammainc(n_dim / 2., a=0, b=expo, regularized=True))) return logx else: return float(mpmath.log(mpmath.gammainc(n_dim / 2., a=0, b=exponent, regularized=True)))
def liwhite_function(M, par, target=0): from mpmath import gammainc h = 0.7 # log(M*), alpha, Phi*, par_high = [10.71 - np.log10(h**2), -1.99, 0.0044*h**3] par_mid = [10.37 - np.log10(h**2), -0.9, 0.0132*h**3] par_low = [9.61 - np.log10(h**2), -1.13, 0.0146*h**3] # Pre-tabulated integrals hightot = 0.000280917465551 # Total contribution from high-mass piece subtractmid = 0.000245951678324549 # Value of middle Schechter fn integrated down to first break midtot = 0.00748165061711 # Total contribution from mid-mass piece subtractlow = 0.00266964412065 if M > 10.67 - np.log10(h**2): x = 10.**(M-par_high[0]) g = gammainc(par_high[1]+1,a=x) return np.log10(par_high[2]*float(g))-target elif M > 9.33 - np.log10(h**2): x = 10.**(M-par_mid[0]) g = gammainc(par_mid[1]+1,a=x) return np.log10(par_mid[2]*float(g)-subtractmid+hightot)-target else: x = 10.**(M-par_low[0]) g = gammainc(par_low[1]+1,a=x) return np.log10(par_low[2]*float(g)-subtractlow+midtot+hightot)-target
def hmodel(theta, Mlow_choice, Mhigh_choice, zlow_choice, zhigh_choice): logno, beta, gamma, alpha, delta = theta no = 10.0**(logno) # Msol cancels from t = M/(10^7Msol) Mlow = float(Mlow_choice) # 10.0**6.0 #Msol Mhigh = float(Mhigh_choice) #10.0**11.0 #Msol tlow = Mlow / (10.0**(7.0 + delta)) thigh = Mhigh / (10.0**(7.0 + delta)) Mincomplete_gamma_fns = (mpmath.gammainc( ((5.0 / 3.0) - alpha), tlow) - mpmath.gammainc( ((5.0 / 3.0) - alpha), thigh)) # zintegral from 0 to 5 OmegaM = 0.3 OmegaL = 0.7 zlow = float(zlow_choice) #0.0 zhigh = float(zhigh_choice) #5.0 zfn = lambda zi: (((1.0 + zi)**(beta - (4.0 / 3.0)) * np.exp(-zi / gamma)) / ((OmegaM * (1.0 + zi)**3.0 + OmegaL)**(1.0 / 2.0))) Zint = quad(zfn, zlow, zhigh, epsabs=1.49e-12, epsrel=1.49e-12) h2 = no * (10.0**(delta * ( (5.0 / 3.0) - alpha))) * Mincomplete_gamma_fns * Zint[0] * (1.0 / np.log(10)) h_no_constants = h2**(1.0 / 2.0) h = h_no_constants * constants() return h
def calculate_U_cold(self, rho): self.checkmat(rho) self.calculate_P_cold(self.rho) self.calculate_grun_cold(self.rho) if type(self.U_c) is not np.ndarray: self.U_c = np.zeros_like(self.rho) for i in range(len(self.rho)): if (self.rho[i] >= self.rho0): d = (1. - self.A1) / self.A1 xae = (self.A0 / self.A1) K = (self.B0 * math.exp(xae) / (self.A1 * self.A0 * self.rho0)) * xae**(-d) n = (self.A1 + self.A2) / self.A1 b = 1. / self.A1 xe = xae * (self.eta[i])**(-self.A1) C = xae**(n - 1.) * mp.gammainc(1 - n, a=xae) Fc1 = xae**(self.A2 / self.A1) * (1. / b * (xe**b * mp.gammainc(1 - n, a=xe) - mp.gammainc(1 - n + b, a=xe))) Fc2 = C * xe**(d + 1.) / (d + 1.) Fc10 = xae**(self.A2 / self.A1) * self.G2_const Fc20 = C * xae**(d + 1.) / (d + 1.) self.U_c[i] = -K * (Fc1 - Fc2 - Fc10 + Fc20) else: K = self.B0 / (self.Pexp_const_a - self.Pexp_const_b) a = self.Pexp_const_a b = self.Pexp_const_b self.U_c[i] = K * (self.rho[i]**(a - 1.) / (self.rho0**(a) * (a - 1.)) + (self.rho[i]**(b - 1.)) / (self.rho0**(b) * (1. - b)))
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 series(z): if z == 1: z = 1 - 1e-8 # avoid a division by zero # sd: the definitions of gamma functions differ between packages, # and specifically between mpmath (used here) and scipy.special # See https://mpmath.org/doc/current/functions/expintegrals.html return (exp(c * z) / (1 - z)) * norm * (gammainc(c + 1, c * z) - gammainc(c + 1, c))
def zfourge_function(M, par, target=0): from mpmath import gammainc x = 10.**(M-par[1]) g1 = gammainc(par[2]+1,a=x) g2 = gammainc(par[4]+1,a=x) N = np.log10(10.**(par[3])*float(g1) + 10.**(par[5])*float(g2)) return N-target
def avTtmp(x, g, l): if (l > 0) & (l < 1): return ((mm.gamma(g * l) * mm.gamma(g * (1 - l)) * l**(1 - g * l) * (1 - l)**(1 - g * (1 - l)) * g**(1 - g / 2)) * mm.gammainc(g, a=np.sqrt(g) * x + g, regularized=True) * (x + np.sqrt(g))**(-g) * mm.exp(np.sqrt(g) * x + g)) else: return ((mm.gamma(g) * g**(-g / 2)) * mm.gammainc(g, a=np.sqrt(g) * X[i] + g, regularized=True) * (x + np.sqrt(g))**(-g) * mm.exp(np.sqrt(g) * x + g))
def MSD_generic(x0, H, lambd, sigma, t): y = np.zeros((len(t), 1)) for i in range(0, len(t)): y[i, 0] = (x0**2) * ((1 - exp(-lambd * t[i]))**2).real + (sigma**2) * ( t[i]**(2 * H)) * exp(-lambd * t[i]).real + (sigma**2) / ( 2 * (lambd**(2 * H))) * (complex( gamma(2 * H + 1) - gammainc(2 * H + 1, lambd * t[i], inf) ) + exp(-2 * 1j * pi * H) * exp(-2 * lambd * t[i]) * complex( gamma(2 * H + 1) - gammainc(2 * H + 1, -lambd * t[i], inf)) ).real return y
def cdf_truncpl(x, alpha, xmin, xmax): # alpha=-1.0, xmin=1, xmax=np.inf): xvals = np.sort(x / xmin) / xmax if alpha <= -2: xvals = mpfv(xvals.tolist()) cdf_theoretical = 1 - gammainc(alpha, a=xvals) /\ gammainc(alpha, a=(xmin / xmax)) return(cdf_theoretical.astype('float')) else: cdf_theoretical = 1 - gammaincplus2(alpha, xvals) /\ gammaincplus2(alpha, 1.0 / xmax) return(cdf_theoretical)
def test_gammaincc(): # Check that the gammaincc in special._precompute.gammainc_data # agrees with mpmath's gammainc. assert_mpmath_equal(lambda a, x: gammaincc(a, x, dps=1000), lambda a, x: mp.gammainc(a, a=x, regularized=True), [Arg(20, 100), Arg(20, 100)], nan_ok=False, rtol=1e-17, n=50, dps=1000) # Test the fast integer path assert_mpmath_equal(gammaincc, lambda a, x: mp.gammainc(a, a=x, regularized=True), [IntArg(1, 100), Arg(0, 100)], nan_ok=False, rtol=1e-17, n=50, dps=50)
def test_gdtrix(self): _assert_inverts( sp.gdtrix, lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), 2, [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False), ProbArg()], rtol=1e-7, endpt_atol=[None, 1e-7, 1e-10])
def test_gdtrib(self): # Use small values of a and x or mpmath doesn't converge _assert_inverts( sp.gdtrib, lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), 1, [Arg(0, 1e2, inclusive_a=False), ProbArg(), Arg(0, 1e3, inclusive_a=False)], rtol=1e-5)
def test_gdtrix(self): _assert_inverts( sp.gdtrix, lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), 2, [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False), ProbArg()], rtol=1e-7, endpt_atol=[None, 1e-10, 1e-10])
def gammaincc(a, x, dps=50, maxterms=10*10*10*10*10*10*10*10): """Compute gammaincc exactly like mpmath does but allow for more terms in hypercomb. See mpmath/functions/expintegrals.py#L187 in the mpmath github repository. """ with mp.workdps(dps): z, a = a, x if mp.isint(z): try: # mpmath has a fast integer path return mpf2float(mp.gammainc(z, a=a, regularized=True)) except mp.libmp.NoConvergence: pass nega = mp.fneg(a, exact=True) G = [z] # Use 2F0 series when possible; fall back to lower gamma representation try: def h(z): r = z-1 return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] return mpf2float(mp.hypercomb(h, [z], force_series=True)) except mp.libmp.NoConvergence: def h(z): T1 = [], [1, z-1], [z], G, [], [], 0 T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a return T1, T2 return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
def equations(p): alpha, kappa0, kappaC, P0, k_bar = p return (alpha - 1 + (kappa0 / kappaC)**(gamma - 2), P0 - (gamma - 1) * (alpha * kappa0)**(gamma - 1) * mpmath.gammainc(1 - gamma, alpha * kappa0), k_max_obs - alpha * kappaC, k_bar * alpha**2 - (1 - P0) * k_bar_obs, kappa0 * (gamma - 1) - k_bar * (gamma - 2))
def truncated_power_law_likelihoods(data, alpha, gamma, xmin, xmax=False, discrete=False): if alpha<0 or gamma<0: from numpy import tile from sys import float_info return tile(10**float_info.min_10_exp, len(data)) data = data[data>=xmin] if xmax: data = data[data<=xmax] from numpy import exp if not discrete: from mpmath import gammainc # likelihoods = (data**-alpha)*exp(-gamma*data)*\ # (gamma**(1-alpha))/\ # float(gammainc(1-alpha,gamma*xmin)) likelihoods = (gamma**(1-alpha))/\ ( (data**alpha) * exp(gamma*data) * gammainc(1-alpha,gamma*xmin) ).astype(float) #Simplified so as not to throw a nan from infs being divided by each other if discrete: if not xmax: xmax = max(data) if xmax: from numpy import arange X = arange(xmin, xmax+1) PDF = (X**-alpha)*exp(-gamma*X) PDF = PDF/sum(PDF) likelihoods = PDF[(data-xmin).astype(int)] from sys import float_info likelihoods[likelihoods==0] = 10**float_info.min_10_exp return likelihoods
def lin_Ez_theo_sigma_r(plasma, beam, zeta_array): Ez = -np.sign(beam.Z) * np.sqrt(2 * math.pi) * beam.n/plasma.n * plasma.k_p*beam.sigma_z \ * np.exp(-1 * (plasma.k_p*beam.sigma_z)**2/2) * np.cos( plasma.k_p * (zeta_array - beam.zeta_0) ) \ * (plasma.k_p*beam.sigma_r)**2/2 * np.exp((plasma.k_p*beam.sigma_r)**2/2) * mpmath.gammainc(0.0,(plasma.k_p*beam.sigma_r)**2/2) return Ez
def equations(p): alpha, kappa0,kappaC,P0,k_bar = p return (alpha-1+(kappa0/kappaC)**(gamma-2), P0- (gamma-1)*(alpha*kappa0)**(gamma-1)*mpmath.gammainc(1-gamma,alpha*kappa0), k_max_obs-alpha*kappaC, k_bar*alpha**2-(1-P0)*k_bar_obs, kappa0*(gamma-1)-k_bar*(gamma-2))
def gammaincc(a, x, dps=50, maxterms=10**8): """Compute gammaincc exactly like mpmath does but allow for more terms in hypercomb. See mpmath/functions/expintegrals.py#L187 in the mpmath github repository. """ with mp.workdps(dps): z, a = a, x if mp.isint(z): try: # mpmath has a fast integer path return mpf2float(mp.gammainc(z, a=a, regularized=True)) except mp.libmp.NoConvergence: pass nega = mp.fneg(a, exact=True) G = [z] # Use 2F0 series when possible; fall back to lower gamma representation try: def h(z): r = z-1 return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] return mpf2float(mp.hypercomb(h, [z], force_series=True)) except mp.libmp.NoConvergence: def h(z): T1 = [], [1, z-1], [z], G, [], [], 0 T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a return T1, T2 return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
def plot_fit(alpha, Lambda, xmin, pdf, ccdf, degs, title=None, ax=None): C = Lambda**(1 - alpha) / (mpmath.gammainc(1 - alpha, Lambda * xmin)) pdf_hat = degs[degs >= xmin]**-alpha * np.exp( -Lambda * degs[degs >= xmin]) * C ccdf_hat = 1 - np.cumsum(pdf_hat) if not ax: fig = plt.figure(figsize=(12, 9)) ax = fig.add_subplot(111) ax.scatter(degs, pdf, marker='o', label='True', color=sns.xkcd_rgb["deep blue"]) ax.plot(degs[degs >= xmin], pdf_hat, marker='*', label='Fit', color=sns.xkcd_rgb["pale red"]) ax.set_xscale('log') ax.set_yscale('log') ax.set_ylabel('Proportion') ax.set_xlabel('Degree') if title: ax.set_title(title) ax.legend() plot_text_x = 10**(np.mean(np.log10(ax.get_xlim()))) plot_text_y = plot_text_x**-alpha * np.exp(-Lambda * plot_text_x) * C ax.annotate(r'$\alpha=%.2f$, $\lambda=%.2g$, ' % (alpha, Lambda), xy=(plot_text_x, plot_text_y), color=sns.xkcd_rgb["pale red"]) plt.show()
def calculate_P_cold(self, rho): self.checkmat(rho) if type(self.P_c) is not np.ndarray: self.P_c = np.zeros_like(self.rho) for i in range(len(self.rho)): if (self.rho[i] >= self.rho0): x2 = self.A0 / self.A1 d = self.B0 * math.exp(x2) / self.A1 x1 = x2 * self.eta[i]**(-self.A1) n = (self.A1 + self.A2) / self.A1 g1 = x1**(n - 1) * mp.gammainc(1 - n, a=x1) P1 = 0 P2 = 0 eta = self.eta[i] if (self.rho[i] > self.rho_critical): eta = self.etacrit P2 = self.C * self.rho[i]**( 5. / 3.) - self.D * self.rho[i]**( 4. / 3.) - self.E * self.rho[i] P1 = self.C * self.rho_critical**( 5. / 3.) - self.D * self.rho_critical**( 4. / 3.) - self.E * self.rho_critical Ppoly = d * (eta**self.A2 * g1 - self.G1_const) self.P_c[i] = (Ppoly - P1) + P2 else: self.P_c[i] = self.Bexp0 * ( self.eta[i]**self.Pexp_const_a - self.eta[i]**self.Pexp_const_b)
def corr_func(i, j, k, cube_half_length, beta, outer_scale, sigma): mpmath.mp.dps = 10 x = math.sqrt( pow(i - cube_half_length, 2) + pow(j - cube_half_length, 2) + pow(k - cube_half_length, 2)) y = ((math.exp(pow(sigma, 2)) - 1) / 2 * mpmath.re( pow(x, beta - 3) * (pow(1j, 3 - beta) * mpmath.gammainc(2 - beta, a=-x * 1.0j / 2.54) + pow(-1j, 3 - beta) * mpmath.gammainc(2 - beta, a=x * 1.0j / 2.54))) + 1) y = mpmath.log(y) return float(mpmath.nstr(y))
def interval_prob(x1, x2, k, theta): """ Compute the probability of x in [x1, x2] for the log-gamma distribution. Mathematically, this is the same as loggamma.cdf(x2, k, theta) - loggamma.cdf(x1, k, theta) but when the two CDF values are nearly equal, this function will give a more accurate result. x1 must be less than or equal to x2. k is the shape parameter of the gamma distribution. theta is the scale parameter of the log-gamma distribution. """ if x1 > x2: raise ValueError('x1 must not be greater than x2') with mpmath.extradps(5): x1 = mpmath.mpf(x1) x2 = mpmath.mpf(x2) k = mpmath.mpf(k) theta = mpmath.mpf(theta) z1 = x1 / theta z2 = x2 / theta return mpmath.gammainc(k, mpmath.exp(z1), mpmath.exp(z2), regularized=True)
def exp_cts(th, config,prior,Xt): '''calc's the expected counts in bins with endpoints defined by Xt, with pulses def'd by th th: J x 7 np.array for J pulses, 7 parameters per pulse. config, prior: bunchs of parameters Xt: list of times (truncated according to the parameters in config) returns: exp_counts: 4 x (len(Xt)-1) nparray with the expected counts in the len(Xt)-1 bins for the 4 channels. note that nchan is hardcoded here. ''' int_length=np.array([float(Xt[ind+1]-Xt[ind]) for ind in xrange(len(Xt)-1)]) k = len(th) # number of pulses drms = config.drms out = 0 quad_nodes = drms.quad_nodes n_intervals = len(int_length) n_chan = len(config.B) exp_counts = np.zeros((4,n_intervals)) thinned_counts = np.zeros((4,n_intervals)) energy_int = [] for j in range(k): T,A,gam,lam,alpha,bet,Ec = th[j] temp = (Ec)*((Ec/100.)**alpha*mpmath.gammainc(alpha+1,a = 10.*(1./Ec), ) )/lam energy_int.append(temp ) E_l, E_u = drms.E_l, drms.E_u exp_cts_0 = np.zeros((4,n_intervals)) for i in range(n_intervals): for j in range(k): gam = th[j,2] if gam >= 0: lower = 100*np.exp( ((Xt[i+1]+Xt[i])/2 - th[j,0] )/(-th[j,2]) ) l = round(max(lower, E_l),2) u = E_u if gam < 0: upper = 100*np.exp( ((Xt[i+1]+Xt[i])/2 - th[j,0] )/(-th[j,2]) ) l = E_l u = round(min(E_u,upper),2) Range = [l,u] if l>=u: Range = None if Range != None: nodes, wts = mbs_quad_nodes_wts(l, u,config) exp_cts_0[:,i] += np.copy(np.sum(K(np.array([Xt[i],Xt[i+1]]),nodes,np.array([th[j]]))*wts, axis = 1))/energy_int[j] exp_counts[:,i] = np.array(config.B)*int_length[i]+ np.array(exp_cts_0[:,i]) return exp_counts
def test_gammainc(): # Quick check that the gammainc in # special._precompute.gammainc_data agrees with mpmath's # gammainc. assert_mpmath_equal(gammainc, lambda a, x: mp.gammainc(a, b=x, regularized=True), [Arg(0, 100, inclusive_a=False), Arg(0, 100)], nan_ok=False, rtol=1e-17, n=50, dps=50)
def indef_mon_exp_int(x, order, scale, t): """ Evaluates the indefinite integral of x^order * exp(scale*(t - x))) with the constant of integration arbitrarily set to 0. """ return prod([-np.exp(scale * t), x**(order + 1), (scale * x)**(-1 - order), complex(gammainc(1 + order, scale * x))])
def test_gamma_inc(n=50, tol=1e-16): mp.mp.dps = 64 for i in range(n): s = cplx_rand(-5, 5, -5, 5) z = cplx_rand(-5, 5, -5, 5) g = cf.gamma_inc(s, z, tol) g_mp = mp.gammainc(s, z) assert (abs(g - complex(g_mp))) / abs(complex(g_mp)) < tol
def boys(n, x): if x > 0.0: f = 2.0*x**(n + 0.5) g = gamma(n + 0.5) gi = 1.0 - gammainc(n + 0.5, x, regularized=True) return g*gi/f else: return 1.0/(n*2 + 1)
def analyticaloccnum(self, theta): """ This is the analytical form of HOD number from either CSMFunction or CLFunction based on Cacciato et al 2009 MNRAS 394. """ Msmin, Msmax, color = theta params = self.paramtable() Mhost = params['logMh'] phis = params['phi'] alphas = params['alpha'] lgMcs = params['lgMc'] sigss = params['sigs'] nbins = 300 ncen = np.zeros(nbins) nsat = np.zeros(nbins) mbins = np.linspace(12.17, 14.5, nbins) for i in range(nbins): logMh = mbins[i] if color == 0: phi = np.interp(logMh, Mhost, phis[0, :]) alpha = np.interp(logMh, Mhost, alphas[0, :]) lgMc = np.interp(logMh, Mhost, lgMcs[0, :]) sigs = np.interp(logMh, Mhost, sigss[0, :]) if color == 1: phi = np.interp(logMh, Mhost, phis[1, :]) alpha = np.interp(logMh, Mhost, alphas[1, :]) lgMc = np.interp(logMh, Mhost, lgMcs[1, :]) sigs = np.interp(logMh, Mhost, sigss[1, :]) if color == 2: phi = np.interp(logMh, Mhost, phis[2, :]) alpha = np.interp(logMh, Mhost, alphas[2, :]) lgMc = np.interp(logMh, Mhost, lgMcs[2, :]) sigs = np.interp(logMh, Mhost, sigss[2, :]) ncen[i] = 0.5 * (erf((Msmax - lgMc)) - erf(Msmin - lgMc)) tmp1 = 0.5 * alpha + 0.5 tmp2 = (10.0**(Msmin - (lgMc - 0.25)))**2.0 tmp3 = (10.0**(Msmax - (lgMc - 0.25)))**2.0 gamma1 = mpmath.gammainc(tmp1, tmp2) gamma2 = mpmath.gammainc(tmp1, tmp3) nsat[i] = 0.5 * phi * (gamma1 - gamma2) return {'Mhrange': mbins, 'Occen': ncen, 'Ocsat': nsat}
def sf(k, lam): """ Survival function of the Poisson distribution. """ if k < 0: return mpmath.mp.one with mpmath.extradps(5): lam = mpmath.mpf(lam) return mpmath.gammainc(k + 1, 0, lam, regularized=True)
def cdf(k, lam): """ CDF of the Poisson distribution. """ if k < 0: return mpmath.mp.zero with mpmath.extradps(5): lam = mpmath.mpf(lam) return mpmath.gammainc(k + 1, lam, regularized=True)
def sf(x, k, theta): """ Survival function of the gamma distribution. """ _validate_k_theta(k, theta) x = mpmath.mpf(x) k = mpmath.mpf(k) theta = mpmath.mpf(theta) return mpmath.gammainc(k, x/theta, mpmath.inf, regularized=True)
def cuflux(n, s, c=1000000., e_th=1.0, norm_crab=3.45e-11, si_crab=2.63): f = -1. #if ((c==0) | (c>=100000)): if (all((in1d(c, 0)) | greater_equal(c, 100000))): f = n / norm_crab * (1. - si_crab) / (1. - s) * e_th**(si_crab - s) else: if (isinstance(n, ndarray) | isinstance(s, ndarray) | isinstance(c, ndarray)): #array operations seems to fail due to use of 'mpf' in gammainc #using loop instead i = 0 for ni, si, ci in zip(n, s, c): f = -ni / norm_crab * ci**(1. - si) * (1. - si_crab) * e_th**( -1. + si_crab) * gammainc(1. - si, e_th / ci) i += 1 else: f = -n / norm_crab * c**(1. - s) * (1. - si_crab) * e_th**( -1. + si_crab) * gammainc(1. - s, e_th / c) return f
def band(engs, params, flux): alpha = float(params[0]) # low-energy index beta = float(params[1]) # high-energy index efold = float(params[2]) # e-folding energy, E_0 for i in range(len(engs)-1): if engs[i] < ((alpha - beta) * efold): multiplier = ((100**(-alpha)) * (efold**(alpha+1.))) lowIntegral = float(mpmath.gammainc(alpha + 1., (engs[i]/efold))) highIntegral = float(mpmath.gammainc(alpha + 1., (engs[i+1]/efold))) val = multiplier * (lowIntegral - highIntegral) flux[i] = val else: multiplier = ((1./(beta + 1.))* ((100**(-alpha)) * ((alpha - beta)**(alpha-beta)) * -exp(beta-alpha) * (efold**(alpha-beta)))) lowIntegral = engs[i]**(beta+1.) highIntegral = engs[i+1]**(beta+1.) val = multiplier * (lowIntegral - highIntegral) flux[i] = val
def int_himf_res(phi, mstar, alpha, mlow, mhigh, foot, beam, nres): """ An adapted integration of the HIMF where mass limits are overruled by requiring the main HI disk to be resolved by at least "nres" "beam" """ #first, find the maximum distance to which mhigh is resolved #this is the upper limit dmax = get_dist_res(np.log10(mhigh), beam * u.arcsec, nres) dmax = dmax.value #set the survey area in steradian omega = foot * (np.pi / 180.)**2 #set the bins d_bins = np.arange(0, dmax, dmax / 1000.) #set numbers before iteration dn_full = phi * (mp.gammainc((alpha + 1), mlow / mstar) - mp.gammainc( (alpha + 1), mhigh / mstar)) #number density for full range N = 0. vol = 0. for d in d_bins: #print(d,omega*d**2*(dmax/1000.),vol) #for each shell calc number of sources #first have to figure out mhi_min mhi_min = get_mass_resolved(d * u.Mpc, beam * u.arcsec, nres) mhi_min = mhi_min.value if mhi_min < mlow: #just use number density times volume of shell N = N + dn_full * omega * d**2 * dmax / 1000. #print(N) elif mhi_min < mhigh: dn = phi * (mp.gammainc( (alpha + 1), mhi_min / mstar) - mp.gammainc( (alpha + 1), mhigh / mstar) ) #have to cal w/ limited lower mass N = N + dn * omega * d**2 * dmax / 1000. vol = vol + omega * d**2 * dmax / 1000. return dmax, np.float(N)
def chisquare(observed, expected): """ Pearson's chi-square test. Test whether the observed frequency distribution differs from the expected frequency distribution. """ chi2 = sum((obs - exp)**2 / exp for obs, exp in zip(observed, expected)) df = len(observed) - 1 p = mpmath.gammainc(df / 2, chi2 / 2) / mpmath.gamma(df / 2) return chi2, p
def creatematerial(self, rho0, B0, dBdP0, AA, ZZ, tmin, delta): self.rho0 = float(rho0) self.B0 = float(B0) self.dBdP0 = float(dBdP0) self.AA = float(AA) self.ZZ = float(ZZ) self.tmin = float(tmin) self.delta = float(delta) self.findA() self.etacrit = float(self.rho_critical / self.rho0) x2 = self.A0 / self.A1 n = (self.A1 + self.A2) / self.A1 b = 1. / self.A1 self.G1_const = x2**(n - 1) * mp.gammainc(1 - n, a=x2) self.G2_const = ( 1. / b * (x2**b * mp.gammainc(1 - n, a=x2) - mp.gammainc(1 - n + b, a=x2))) self.rho = np.array([float(self.rho0)]) self.grun0, self.grun_q0, self.grun_lamb0 = self.calculate_grun_cold( self.rho0)
def def_mon_exp_int(x_start, x_end, order, scale, t): """ Evaluates the integral from `x_start` to `x_end` of x^order * exp(scale*(t - x)). """ if x_start == 0.0: return prod([x_end**order / scale, (scale * x_end)**(-order), np.exp(scale * t), fctrl(order) - complex(gammainc(order + 1, scale * x_end))]) else: return indef_mon_exp_int(x_end, order, scale, t) -\ indef_mon_exp_int(x_start, order, scale, t)
def cdf(x, k): """ CDF for the chi distribution. """ _validate_k(k) if x <= 0: return mpmath.mp.zero with mpmath.extradps(5): x = mpmath.mpf(x) k = mpmath.mpf(k) c = mpmath.gammainc(k/2, a=0, b=x**2/2, regularized=True) return c
def sf(x, k): """ Survival function for the chi distribution. """ _validate_k(k) if x <= 0: return mpmath.mp.one with mpmath.extradps(5): x = mpmath.mpf(x) k = mpmath.mpf(k) s = mpmath.gammainc(k/2, a=x**2/2, b=mpmath.inf, regularized=True) return s
def _cdf_notTruncated(self, a, b, dps): """ Compute the probability of being in the interval (a, b) for a variable with a chi distribution (not truncated) Parameters ---------- a, b : float Bounds of the interval. Can be infinite. dps : int Decimal precision (decimal places). Used in mpmath Returns ------- p : float The probability of being in the intervals (a, b) P( a < X < b) for a non truncated variable """ scale = self._scale k = self._k dps_temp = mp.mp.dps mp.mp.dps = dps a = max(0, a) b = max(0, b) sf = mp.gammainc(1./2 * k, 1./2*((a/scale)**2), 1./2*((b/scale)**2), regularized=True) mp.mp.dps = dps_temp return sf
#!/usr/bin/python """ """ import mpmath as mp import numpy as np import sys mp.mp.dps = 60 z = float(sys.argv[1]) a_lo = float(sys.argv[2]) a_hi = float(sys.argv[3]) n = int (sys.argv[4]) for x in np.logspace(a_lo, a_hi, 1000) : x = mp.mpf(x) print x, mp.gammainc(z, 0, x, regularized=True)
def cdf_truncpl(x, alpha=-1.0, xmin=1, xmax=np.inf): xvals = np.sort(x) / xmax xvals = mpfv(xvals.tolist()) cdf_theoretical = 1 - gammainc(alpha, a=xvals) /\ gammainc(alpha, a=(xmin / xmax)) return(cdf_theoretical.astype('float'))
def test_gammainc(self): assert_mpmath_equal(sc.gammainc, _exception_to_nan( lambda z, b: mpmath.gammainc(z, b=b)/mpmath.gamma(z)), [Arg(a=0), Arg(a=0)])
def rootfinding(luminosity,luminosityParameter,nold): return np.log10(luminosityParameter[0][0])+float(mpmath.log10(mpmath.gammainc(luminosityParameter[2][0]+1,luminosity/luminosityParameter[1][0])))-float(nold)
def test_chdtriv(self): _assert_inverts( sp.chdtriv, lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True), 0, [ProbArg(), IntArg(1, 100)], rtol=1e-4)
def LuminosityFunction(luminosityParameter,luminosity): return np.log10(luminosityParameter[0])+float(mpmath.log10(mpmath.gammainc(luminosityParameter[2]+1,luminosity/luminosityParameter[1])))
#This code is used to compute the mean number of galaxies with luminosities #above a certain threshold. It uses the Press-Schechter luminosity function #with parameters obtained from Blanton et al 2003. For details see: # http://www.astro.virginia.edu/class/whittle/astr553/Topic04/Lecture_4.html import numpy as np import mpmath #used to compute the incomplete gamma function ########################### INPUT ############################## M = -20.5 #This is maximum magnitude of the galaxies in the sample ################################################################ #### Press-Schechter parameter: taken form Blanton et al. 2003 M_star = -20.44 alpha = -1.05 n_star = 1.49e-2 #galaxies h^3 / Mpc^3 ratio_L = 10**(0.4*(M_star-M)) density = n_star * mpmath.gammainc(1.0+alpha,ratio_L) #galaxies h^3 / Mpc^3 print density,'galaxies / (Mpc/h)^3 with M - 5*log10(h) <',M
def ExpPL_Wolf(x): return E_c*(-k_norm)*(x**(-gamma))*((x/E_c)**gamma)*mpmath.gammainc(1. - gamma, x/E_c)