Beispiel #1
0
    def __init__(self, alpha, beta, K):
        """
        Note alpha/beta = mean, alpha/beta^2 = variance
        @param alpha:
            shape parameter
        @param beta:
            inverse scale parameter
        @param K:
            number of bins
        """
        if alpha <= 0:
            raise Exception("alpha = %f <= 0" % alpha)
        if beta <= 0:
            raise Exception("beta = %f <= 0" % beta)
        if K < 1:
            raise Exception("Num bins = %d < 1" % K)

        # find upper boundaries of each bin
        max_prob = gammainc(alpha, self.MAX_RATE)
        bin_prob = max_prob / K
        targets = np.arange(bin_prob, max_prob+bin_prob/2, bin_prob)
        #XXX: not sure why we don't divide targets / beta
        bin_ubounds = gammaincinv(alpha, targets) / beta

        bin_lbounds = np.zeros(K)
        bin_lbounds[1:] = bin_ubounds[:-1]
        tmp = gammainc(alpha+1, bin_ubounds * beta) - gammainc(alpha+1, bin_lbounds * beta)
        bin_rates = tmp * alpha / beta * K

        # Rate of middle of each bin
        self.bin_rates = bin_rates
        # Probability mass of each bin
        self.bin_probs = np.zeros(K) + bin_prob
Beispiel #2
0
def truncated_gamma(shape=None, alpha=1., beta=1., x_min=None, x_max=None):
    """
    Generate random variates from a lower-and upper-bounded gamma distribution.

    @param shape: shape of the random sample
    @param alpha: shape parameter (alpha > 0.)
    @param beta:  scale parameter (beta >= 0.)
    @param x_min: lower bound of variate
    @param x_max: upper bound of variate    
    @return: random variates of lower-bounded gamma distribution
    """
    from scipy.special import gammainc, gammaincinv
    from numpy.random import gamma
    from numpy import inf

    if x_min is None and x_max is None:
        return gamma(alpha, 1 / beta, shape)
    elif x_min is None:
        x_min = 0.
    elif x_max is None:
        x_max = inf
        
    x_min = max(0., x_min)
    x_max = min(1e300, x_max)

    a = gammainc(alpha, beta * x_min)
    b = gammainc(alpha, beta * x_max)

    return probability_transform(shape,
                                 lambda x, alpha=alpha: gammaincinv(alpha, x),
                                 a, b) / beta
Beispiel #3
0
    def integrate(self,lower,upper,method=None,**kwargs):
        """
        Analytically Compute Schechter integral using incomplete gamma
        functions. If `method` is not None, numerical integration will be used.
        The gamma functions break down for alpha<=-1, so numerical is used if
        that is the case.
        """
        if self.alpha<=-1:
            method = True #use default numerical method, because gamma functions fail for alpha<=-1
        if method is not None:
            return FunctionModel1D.integrate(self,lower,upper,method,**kwargs)
        
        
        from scipy.special import gamma,gammainc,gammaincc
            
        s = self.alpha+1
        u = upper/self.Lstar
        l = lower/self.Lstar
        
        if upper==np.inf and lower<=0:
            I = gamma(s)
        elif upper==np.inf:
            I = gammaincc(s,l)*gamma(s)
        elif lower==0:
            I = gammainc(s,u)*gamma(s)
        else:
            I = (gammainc(s,u) - gammainc(s,l))*gamma(s)

        return self.phistar*I
    def dldtheta(self,dat):
        """
        Evaluates the gradient of the Gamma function with respect to the primary parameters.

        :param dat: Data on which the gradient should be evaluated.
        :type dat: DataModule.Data
        :returns:   The gradient
        :rtype:     numpy.array
        """
        
        m = dat.numex()
        grad = zeros((len(self.primary),m))
        s = self.param['s']
        p = self.param['p']
        u = array([self.param['a'],self.param['b']])
        cab = .5 + 0.5*sign(u)*gammainc(1/p,abs(u)**p /s)
        for ind,key in enumerate(self.primary):
            if key == 's':
                U = -.5*sign(u)*(abs(u) *exp(-abs(u)**p/s))/(s**(1/p+1)*gammafunc(1/p))
                grad[ind,:] = -1.0/p/s + abs(squeeze(dat.X))**p/s**2 - (U[1]-U[0])/(cab[1]-cab[0])
            if key == 'p':
                f = lambda x: 1/x
                df = lambda x: -1/x**2
                g = lambda x,k: abs(u[k])**x/s
                dg = lambda x,k: abs(u[k])**x*log(abs(u[k]))/s
                dIncGamma = array([totalDerivativeOfIncGamma(p,f,lambda v: g(v,0),df,lambda v: dg(v,0)),\
                                   totalDerivativeOfIncGamma(p,f,lambda v: g(v,1),df,lambda v: dg(v,1))])

                U = .5*sign(u) * (dIncGamma/float(gammafunc(1/p)) + gammainc(1/p,abs(u)**p/s)*digamma(1/p)/p**2)
                grad[ind,:] = 1/p + 1/p**2*log(s) + digamma(1/p)*1/p**2 - abs(squeeze(dat.X))**p*log(abs(squeeze(dat.X)))/s - (U[1]-U[0])/(cab[1]-cab[0])

                
        return grad
Beispiel #5
0
def new_BD_ratio(P, zp):
	MB, ReB, nB, M1, M2, h1, h2, R_brk = P.values
	I01, I02, IeB = convert_I(M1, zp), convert_I(M2, zp), convert_I(MB, zp)
	disc1 = I01 * h1 * h1 * gammainc(2., R_brk / h1)
	disc2 = I02 * h2 * h2 * (1 - gammainc(2., R_brk / h2))
	bn = get_b_n(nB)
	bulge = np.exp(bn) * IeB * ReB * ReB * gamma((2 * nB) + 1) / (bn**(2.*nB))
	return bulge / (2* (disc2 + disc1))
Beispiel #6
0
def dndx_rvir(Lrng=(0.001, 10), nL=1000, beta=0.2, rvir_Lstar=250.*u.kpc,
         phi_str_pref = 1.49, alpha = -1.05, Mstar = -20.44,
         cosmo=None):  #  ; M* - 5 log h
    """ Estimate dN/dX for a set of CGM assuming unit covering fraction
    Following Prochaska+11

    Use beta=0 and rvir_Lstar=300kpc for a constant CGM to 300kpc

    Parameters
    ----------
    Lrng : tuple, optional
      Range to integrate luminosity in terms of L*
    nL : int, optional
      Number of evaluations of L in that interval
    beta : float, optional
      Parameterization of rvir with L
       r_vir = 250 kpc * (L/L*)^beta
    phi_str, alpha, Mstar : float, float, float
        Blanton lum function
          Phi(M) = 0.4 log(10) Phi* 10^(-0.4 [M-M*][alpha+1]) exp(-
                    ; 10^(-0.4[M-M*] ) )
          Phi(L) = Phi* (L/L*)^alpha exp(-L/L*)
          Phi* has the funny units of 1e-2 h^3 Mpc^-3
    cosmo : Cosmology, optional
      Defaults to Planck15

    Returns
    -------
    Lval : ndarray
      Luminosities of evaluation
    dNdX : float
      Cumulative dNdX

    """
    # Cosmology
    if cosmo is None:
        cosmo = Planck15
    hubb = cosmo.H0.value / 100.
    # Constants
    phi_str_cgs = (phi_str_pref * 1e-2 * hubb**3) / u.Mpc**3
    dndx_const = (const.c / cosmo.H0).cgs
    # Cumulative
    Lval = np.linspace(Lrng[0], Lrng[1], nL)
    x = alpha + 1 + beta
    # Integrate
    if gflg:
        igmma = np.zeros_like(Lval)
        i0 = float(gammainc(x,Lrng[1]))
        for kk,iLval in enumerate(Lval):
            igmma[kk] = i0 - float(gammainc(x,iLval))
    else:
        igmma = gammainc(x,Lrng[1]) - gammainc(x,Lval)
    dNdx_rvir = (dndx_const * phi_str_cgs * (np.pi * rvir_Lstar**2) * (
        gamma(x) * igmma)).decompose().value

    # Return
    return Lval, dNdx_rvir
Beispiel #7
0
    def getMass(self,sigCrit=1.):
        import numpy
        from math import pi
        from scipy.special import gammainc,gamma

        b,n,re = self.b,self.n,self.re
        k = 2.*n-1./3+4./(405.*n)+46/(25515.*n**2)
        amp = b*b*k**(2*n)/(2*n*re**2*(gamma(2*n)*gammainc(2*n,k*(b/re)**(1/n))))
        return 2*pi*sigCrit*re**2*amp*gamma(2*n)*n/k**(2*n)
        ###
        amp = b*b*k**(2*n)/(numpy.exp(k)*2*n*re**2*(gamma(2*n)*gammainc(2*n,k*(b/re)**(1/n))))
        return 2*pi*sigCrit*re**2*amp*gamma(2*n)*n/(numpy.exp(k)*k**(2*n))
    def cdf(self,dat):
        '''

        Evaluates the cumulative distribution function on the data points in dat. 

        :param dat: Data points for which the c.d.f. will be computed.
        :type dat: natter.DataModule.Data
        :returns:  A numpy array containing the probabilities.
        :rtype:    numpy.array
           
        '''
        u = array([self.param['a'],self.param['b']])
        u = .5 + 0.5*sign(u)*gammainc(1/self.param['p'],abs(u)**self.param['p'] / self.param['s'])
        return squeeze(.5 + 0.5*sign(dat.X)*gammainc(1/self.param['p'],abs(dat.X)**self.param['p'] / self.param['s']) - u[0])/(u[1]-u[0])
Beispiel #9
0
    def sfr_avg(self, tage=None, dt=0.1):
        """
        The average SFR between time ``tage``-``dt`` and ``tage``, given the
        SFH parameters, for ``sfh=1`` or ``sfh=4``.  Like SFHSTAT in FSPS.
        Requires scipy, as it uses gamma functions.

        :param tage: (default, None)
            The ages (in Gyr) at which the average SFR over the last ``dt`` is
            desired.  if ``None``, uses the current value of the ``tage`` in
            the parameter set. Scalar or iterable.

        :param dt: (default: 0.1)
            The time interval over which the recent SFR is averaged, in Gyr.
            defaults to 100 Myr (i.e. sfr8).

        :returns sfr_avg:
            The SFR at ``tage`` averaged over the last ``dt`` Gyr, in units of
            solar masses per year.
        """
        from scipy.special import gammainc
        assert self.params['sf_trunc'] <= 0, \
          "sfr_avg not supported for sf_trunc > 0"
        if self.params['sfh'] == 1:
            power = 1
        elif self.params['sfh'] == 4:
            power = 2
        else:
            raise ValueError("sfr_avg not supported for this SFH type.")

        tau, sf_start = self.params['tau'], self.params['sf_start']
        if tage is None:
            tage = np.atleast_1d(self.params['tage'])
        else:
            tage = np.atleast_1d(tage)
        if tage[0] <= 0:
            tage = 10**(self.log_age - 9)

        tb = (self.params['tburst'] - sf_start) / tau
        tmax = (tage[-1] - sf_start) / tau
        normalized_times = (np.array([tage, tage - dt]).T - sf_start) / tau

        tau_mass_frac = gammainc(power, normalized_times) / gammainc(power, tmax)
        burst_in_past = tb <= normalized_times
        mass = (tau_mass_frac * (1 - self.params['const'] - self.params['fburst']) +
                self.params['const'] * normalized_times / tmax +
                burst_in_past * self.params['fburst'])

        avsfr = (mass[..., 0] - mass[..., 1]) / dt / 1e9  # Msun/yr
        return np.clip(avsfr, 0, np.inf)
 def _getInterpProbs(self, n, log_s):
     #These values come from:
     #http://ned.ipac.caltech.edu/level5/March05/Graham/Graham2.html
     b_n = 1.9992*n-0.3271
     x = b_n*numpy.power(10,log_s)**(1./n)
     probs = gammainc(2*n, x)
     return interp1d(probs, log_s), numpy.min(probs), numpy.max(probs)
Beispiel #11
0
def det_tau_r(E_f, V_f, m_list, mu_xi, dp_tau, dp_r, tau_range, r_range, sV0):
    w_arr = np.linspace(0, 20, 300)
    tau_arr = np.linspace(tau_range[0], tau_range[1], dp_tau)
    r_arr = np.linspace(r_range[0], r_range[1], dp_tau)
    e_arr = orthogonalize([tau_arr, r_arr])
    x_axis = e_arr[0]
    y_axis = e_arr[1]
    for mi in m_list:
            res_array = np.zeros((dp_tau, dp_r))
            for i_tau, taui in enumerate(tau_arr):
                    for i_r, ri in enumerate(r_arr):
                        s = get_scale(mu_xi, mi, taui, ri)
                        print s
                        #sV0 = float(s * (pi * mu_r ** 2) ** (1. / mi))
                        T = 2. * taui / ri
                        s0 = ((T * (mi + 1) * sV0 ** mi) / (2. * E_f * pi * ri ** 2)) ** (1. / (mi + 1))
                        print s0
                        k = np.sqrt(T / E_f)
                        ef0 = k * np.sqrt(w_arr)
                        G = 1 - np.exp(-(ef0 / s0) ** (mi + 1))
                        mu_int = ef0 * E_f * V_f * (1 - G)
                        I = s0 * gamma(1 + 1. / (mi + 1)) * gammainc(1 + 1. / (mi + 1), (ef0 / s0) ** (mi + 1))
                        mu_broken = E_f * V_f * I / (mi + 1)
                        result = mu_int + mu_broken
                        sigma_c = np.max(result)
                        if sigma_c == result[-1]:
                            print "w_arr too short"
                            pass
                        res_array[i_tau, i_r] = sigma_c
                    
            mlab.surf(x_axis, y_axis, res_array / 100.)
    mlab.xlabel("det tau")
    mlab.ylabel("det r")
    mlab.zlabel("sigma")
    mlab.show()
Beispiel #12
0
    def _rhov2int(self, phi, r, ra):
        """Compute dimensionless pressure integral for phi, r """

        # Isotropic case first (equation 9, GZ15)
        rhov2r = exp(phi)*gammainc(self.g + 2.5, phi)
        rhov2  = 3*rhov2r
        rhov2t = 2*rhov2r

        # Add anisotropy, add parts depending explicitly on r
        # (see equations 12, 13, and 14 of GZ15)
        if (ra < self.ramax) and (r>0) and (phi>0):
            p, g = r/ra, self.g
            p2 = p**2
            p12 = 1+p2
            g3, g5, g7, fp2 = g+1.5, g+2.5, g+3.5, phi*p2

            P1 = p2*phi**g5/gamma(g7)
            H1 = hyp1f1(1, g7, -fp2) if fp2 <self.max_arg_exp else g5/fp2
            H2 = hyp1f1(2, g7, -fp2) if fp2 <self.max_arg_exp else g5*g3/fp2**2

            rhov2r += P1*H1
            rhov2r /= p12

            rhov2t /= p12
            rhov2t += 2*P1*(H1/p12 + H2)
            rhov2t /= p12

            rhov2 = rhov2r + rhov2t
        return rhov2, rhov2r, rhov2t
def deterministic_r():
    E_f, V_f, tau, m, sV0 = 200e3, 0.01, .1, 7.0, 3.e-3
    for ri in [0.005, 0.01, 0.015]:
        T = 2. * tau / ri
        w_arr = np.linspace(0,1.2,1000)
#         analytical solution
        s0 = ((T * (m+1) * sV0**m)/(2. * E_f * pi * ri ** 2))**(1./(m+1))
        k = np.sqrt(T/E_f)
        ef0 = k*np.sqrt(w_arr)
        G = 1 - np.exp(-(ef0/s0)**(m+1))
        mu_int = ef0 * E_f * V_f * (1-G)
        I = s0 * gamma(1 + 1./(m+1)) * gammainc(1 + 1./(m+1), (ef0/s0)**(m+1))
        mu_broken = E_f * V_f * I / (m+1)
        plt.plot(w_arr, mu_int + mu_broken, lw = 2, color = 'black')
    plt.ylim(0, 16)
    plt.xlim(0, 1.25)
    plt.show()

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()

    for mi in [4.0, 5.0, 7.0]:
        r_arr = np.linspace(0.001, 0.01, 100)
        T = 2. * tau / r_arr
        s0 = ((T * (mi+1) * sV0**mi)/(2. * E_f * pi * r_arr ** 2))**(1./(mi+1))
        wstar = E_f / T * s0**2 * mi**(-2./(mi+1))
        zeta = mi**(-1./(mi+1.)) * np.exp(-1./mi) + 1. / (mi + 1.) * gamma(1 + 1./(mi+1)) * gammainc(1 + 1./(mi+1), 1./mi)
        strength = E_f * V_f * s0 * zeta
        ax1.loglog(r_arr, strength, lw=2, color='black')
        ax1.set_ylim(10,100)
        ax2.loglog(r_arr, wstar, lw=2, color='black', ls='dashed')
        ax2.set_ylim(0.1,1)
    plt.xlim(0,0.01)
    plt.show()
Beispiel #14
0
def int_sfh_2(t1, t2, tage, tau, sf_start, tburst=0, fburst=0):
    """Use Gamma functions
    """
    normalized_times = (np.array([t1, t2, tage]) - sf_start) / tau
    mass = gammainc(2, normalized_times)
    intsfr = (mass[1] - mass[0]) / mass[2]
    return intsfr
Beispiel #15
0
 def deflections(self, xin, yin):
     import numpy
     from math import cos, sin, pi
     from scipy.special import gammainc
     x, y = self.align_coords(xin, yin)
     q = self.q
     if q == 1.:
         q = 1. - 1e-7  # Avoid divide-by-zero errors
     b, n, re = self.b, self.n, self.re
     k = 2. * n - 1. / 3 + 4. / (405. * n) + 46 / (25515. * n**2)
     amp = (b / re)**2 / gammainc(2 * n, k * (b / re)**(1 / n))
     r0 = re / q**0.5
     o = numpy.ones(x.size).astype(x.dtype)
     eval = numpy.array(
         [abs(x).ravel() / r0,
          abs(y).ravel() / r0, n * o, q * o]).T
     xout = numpy.sign(x) * (amp * self.xmod.eval(eval) * r0).reshape(
         x.shape)
     yout = numpy.sign(y) * (amp * self.ymod.eval(eval) * r0).reshape(
         y.shape)
     theta = -(self.theta - pi / 2.)
     ctheta = cos(theta)
     stheta = sin(theta)
     x = xout * ctheta + yout * stheta
     y = yout * ctheta - xout * stheta
     return x, y
def deterministic_tau():
    E_f, V_f, r, m, sV0 = 200e3, 0.01, 0.01, 7., 3.e-3
    w_arr = np.linspace(0, 1.2, 300)
    for taui in [0.05, .1, .2]:
        T = 2. * taui / r
        s0 = ((T * (m+1) * sV0**m)/(2. * E_f * pi * r ** 2))**(1./(m+1))
        k = np.sqrt(T/E_f)
        ef0 = k*np.sqrt(w_arr)
        G = 1 - np.exp(-(ef0/s0)**(m+1))
        mu_int = ef0 * E_f * V_f * (1-G)
        I = s0 * gamma(1 + 1./(m+1)) * gammainc(1 + 1./(m+1), (ef0/s0)**(m+1))
        mu_broken = E_f * V_f * I / (m+1)
        plt.plot(w_arr, mu_int + mu_broken, lw = 2, color = 'black')
    plt.ylim(0, 16)
    plt.xlim(0, 1.25)
    plt.show()

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()

    for mi in [4.0, 5.0, 7.0]:
        tau_arr = np.linspace(0.05, .2, 5)
        T = 2. * tau_arr / r
        s0 = ((T * (mi+1) * sV0**mi)/(2. * E_f * pi * r ** 2))**(1./(mi+1))
        wstar = E_f / T * s0**2 * mi**(-2./(mi+1))
        zeta = mi**(-1./(mi+1.)) * np.exp(-1./mi) + 1. / (mi + 1.) * gamma(1 + 1./(mi+1)) * gammainc(1 + 1./(mi+1), 1./mi)
        strength = E_f * V_f * s0 * zeta
        ax1.loglog(tau_arr, strength, lw=2, color='black')
        ax1.set_ylim(0,15)
        ax2.loglog(tau_arr, wstar, lw=2, color='black', ls='dashed')
        ax2.set_ylim(0.1,1.)
    plt.xlim(0.05,.2)
    plt.ylim(0)
    plt.show()
Beispiel #17
0
    def _draw_gamma_rates(self):
        '''
            Function to draw and assign rates from a discretized gamma distribution, if specified. By default, 4 categories are drawn.
        '''       
        if self.rate_probs is not None:
            print("\nThe provided value for the `rate_probs` argument will be ignored since gamma-distributed heterogeneity has been specified with the alpha parameter.")        
        if type(self.k_gamma) is not int:
            raise TypeError("\nProvided argument `num_categories` must be an integer.")

        #### Note that this code is adapted from gamma.c in PAML ####
        rv = gamma(self.alpha, scale = 1./self.alpha)
        freqK = np.zeros(self.k_gamma)  ### probs
        rK = np.zeros(self.k_gamma)     ### rates

        for i in range(self.k_gamma-1):
            raw=rv.ppf( (i+1.)/self.k_gamma )
            freqK[i] = gammainc(self.alpha + 1, raw*self.alpha)

        rK[0] = freqK[0] * self.k_gamma
        rK[self.k_gamma-1] = (1-freqK[self.k_gamma-2]) * self.k_gamma
        for i in range(1,self.k_gamma-1):
            rK[i] = self.k_gamma * (freqK[i] -freqK[i-1])    
        #############################################################
        
        self.rate_probs = np.repeat(1./self.k_gamma, self.k_gamma)
        self.rate_factors = deepcopy(rK)

        if self.pinv > ZERO:          
            self.rate_probs = list(self.rate_probs - self.pinv/self.k_gamma) + [self.pinv]
            self.rate_factors = list(self.rate_factors) + [0.0]
            
            self.rate_probs = np.array( self.rate_probs )
            self.rate_factors = np.array( self.rate_factors )
Beispiel #18
0
 def cdf(self,x,nu=None,var_2=None,var_3=None,var_4=None):
   """cumulative distribution function
   """
   lamb = 0.5
   k      = nu*.5
   P = spec.gammainc(k,lamb*x)
   return P
Beispiel #19
0
def integrate_sfh_ben(t1, t2, tage, tau, sf_start, tburst=0, fburst=0):

    normalized_times = (np.array([t1, t2, tage]) - sf_start) / tau
    mass = gammainc(2, normalized_times)
    intsfr = (mass[1] - mass[0]) / mass[2]

    return intsfr
  def _testCompareToExplicitDerivative(self, dtype):
    """Compare to the explicit reparameterization derivative.

    Verifies that the computed derivative satisfies
    dsample / dalpha = d igammainv(alpha, u) / dalpha,
    where u = igamma(alpha, sample).

    Args:
      dtype: TensorFlow dtype to perform the computations in.
    """
    delta = 1e-3
    np_dtype = dtype.as_numpy_dtype
    try:
      from scipy import misc  # pylint: disable=g-import-not-at-top
      from scipy import special  # pylint: disable=g-import-not-at-top

      alpha_val = np.logspace(-2, 3, dtype=np_dtype)
      alpha = constant_op.constant(alpha_val)
      sample = random_ops.random_gamma([], alpha, np_dtype(1.0), dtype=dtype)
      actual = gradients_impl.gradients(sample, alpha)[0]

      (sample_val, actual_val) = self.evaluate((sample, actual))

      u = special.gammainc(alpha_val, sample_val)
      expected_val = misc.derivative(
          lambda alpha_prime: special.gammaincinv(alpha_prime, u),
          alpha_val, dx=delta * alpha_val)

      self.assertAllClose(actual_val, expected_val, rtol=1e-3, atol=1e-3)
    except ImportError as e:
      tf_logging.warn("Cannot use special functions in a test: %s" % str(e))
 def cdf(self, y):
     a = self.a
     b = self.b
     p = self.p
     z = (y/b)**a
     cdf = gammainc(p, z)
     return cdf 
Beispiel #22
0
def F(nu,x):
    """
    Boys function.

    INPUT:
        NU: Boys function index
        X: Boys function variable

    OUTPUT:
        FF: Value of the Boys function for index NU evaluated at X

    Source:
        Evaluation of the Boys Function using Analytical Relations
        I. I. Guseinov and B. A. Mamedov
        Journal of Mathematical Chemistry
        2006
    """

    if x < 1e-8:
        # Taylor expansion for argument close or equal to zero (avoid division by zero)
        ff =  1 / (2 * nu + 1) - x / (2 * nu + 3)
    else:
        # Evaluate Boys function with incomplete and complete Gamma functions
        ff = 0.5 / x**(nu+0.5) * spec.gamma(nu+0.5)*spec.gammainc(nu+0.5,x)

    return ff
Beispiel #23
0
    def df(self, *arg):
        """
        Returns the normalised DF, can only be called after Poisson solver
        Arguments can be:
          - r, v                   (isotropic single-mass models)
          - r, v, j                (isotropic multi-mass models)
          - r, v, theta, j         (anisotropic models)
          - x, y, z, vx, vy, vz, j (all models)
        Here j specifies the mass bin, j=0 for single mass
        Works with scalar and array input

        """

        if (len(arg)<2)|(len(arg)==5)|(len(arg)==6)|(len(arg)>7):
            raise ValueError("Error: df needs 2, 3, 4 or 7 arguments")

        if len(arg) == 2:
            r, v = (self._tonp(q) for q in arg)
            j = 0

        if len(arg) == 3:
            r, v = (self._tonp(q) for q in arg[:-1])
            j = arg[-1]

        if len(arg) == 4:
            r, v, theta = (self._tonp(q) for q in arg[:-1])
            j = arg[-1]

        if len(arg) < 7: r2, v2 = r**2, v**2

        if len(arg) == 7:
            x, y, z, vx, vy, vz = (self._tonp(q) for q in arg[:-1])
            j = arg[-1]
            r2 = x**2 + y**2 + z**2
            v2 = vx**2 + vy**2 + vz**2
            r, v = sqrt(r2), sqrt(v2)

        phi = self.interp_phi(r)
        vesc2 = 2.0*phi                        # Note: phi > 0

        DF = numpy.zeros([max(r.size, v.size)])
        c = (r<self.rt)&(v2<vesc2)

        E = (phi-0.5*v2)/self.sig2[j]          # Dimensionless positive energy
        DF[c] = exp(E[c])

        # Float truncation parameter 
        # Following Gomez-Leyton & Velazquez 2014, J. Stat. Mech. 4, 6

        if (self.g>0): DF[c] *= gammainc(self.g, E[c])

        if (self.raj[j] < self.ramax):
            if (len(arg)==7): J2 = v2*r2 - (x*vx + y*vy + z*vz)**2
            if (len(arg)==4): J2 = sin(theta)**2*v2*r2

            DF[c] *= exp(-J2[c]/(2*self.raj[j]**2*self.sig2[j]))

        DF[c] *= self.A[j]

        return DF
Beispiel #24
0
def qtimedelay(set_par,deltim=1.):
    '''
    gamma-function based weight function to control the runoff delay
    '''
    alpha=3.0
    print set_par['mut']
    alamb = alpha/set_par['mut']
    psave=0.0
    set_par['frac_future']=np.zeros(500.)  #Parameter added
    ntdh = set_par['frac_future'].size
    
    deltim=1.
    print 'qtimedelay is calculated with a unit of',deltim,'hours'
    
    for jtim in range(ntdh):
#        print jtim
        tfuture=jtim*deltim
#        print alamb*tfuture
        cumprob= special.gammainc(alpha, alamb*tfuture)# hoeft niet want verschil wordt genomen: /special.gamma(alpha)
#        print cumprob
        set_par['frac_future'][jtim]=max(0.,cumprob-psave)
        if set_par['frac_future'][jtim] > 0.0001:
            print set_par['frac_future'][jtim]
        psave = cumprob
    
    if cumprob < 0.99:
        print 'not enough bins in the frac_future'

    #make sure sum to one
    set_par['frac_future'][:]=set_par['frac_future'][:]/set_par['frac_future'][:].sum()
    
    return set_par
Beispiel #25
0
 def deflections(self, xin, yin):
     from numpy import ones, arctan as atan, arctanh as atanh
     from math import cos, sin, pi, exp
     from numpy import arcsin as asin, arcsinh as asinh
     from scipy.special import gammainc, gamma
     x, y = self.align_coords(xin, yin)
     q = self.q
     if q == 1.:
         q = 1. - 1e-7  # Avoid divide-by-zero errors
     from sersic import sersicdeflections as sd
     b, n, re = self.b, self.n, self.re
     k = 2. * n - 1. / 3 + 4. / (405. * n) + 46 / (25515. * n**2)
     b = b / q**0.5
     re = re / q**0.5
     amp = b * b * k**(2 * n) / (
         2 * n * re**2 * (gamma(2 * n) * gammainc(2 * n,
                                                  k * (b / re)**(1 / n))))
     if x.ndim > 1:
         yout, xout = sd(-1 * y.ravel(), x.ravel(), amp, re, n, q)
         xout, yout = xout.reshape(x.shape), -1 * yout.reshape(y.shape)
     else:
         yout, xout = sd(-1 * y, x, amp, re, n, q)
         yout = -1 * yout
     theta = -(self.theta - pi / 2.)
     ctheta = cos(theta)
     stheta = sin(theta)
     x = xout * ctheta + yout * stheta
     y = yout * ctheta - xout * stheta
     return x, y
Beispiel #26
0
 def IRF3(self, parameters):
     A1 = parameters['A1'].value
     a1 = parameters['a1'].value
     n1 = parameters['n1'].value
     t = np.arange(1.0, 10000)
     Fs = A1 * t**n1 * (t/a1)**-n1 * gammainc(n1, t/a1)  # Step response function based on pearsonIII
     return np.append(0, Fs[1:] - Fs[0:-1])  # block reponse function
Beispiel #27
0
    def loglik(self,dat):
        '''

        Computes the loglikelihood of the data points in dat. 

        :param dat: Data points for which the loglikelihood will be computed.
        :type dat: natter.DataModule.Data
        :returns:  An array containing the loglikelihoods.
        :rtype:    numpy.array
         
           
        '''
        sigma,kappa,delta,gamma,n,p,s = \
                        self.param['sigma'],self.param['kappa'],self.param['delta'],\
                        self.param['gamma'],self.param['n'],self.param['p'],self.param['s']
        r = squeeze(dat.X)

        if delta == 0.0:
            addTerm =  - log(gammainc(n/p,kappa**p/2.0/s))
        else:
            addTerm = 0
            
        ll = log(p) + n*log(kappa) + (n*gamma+2.0*n*delta-2.0)/2.0 * log(r)\
             + log(2.0*delta*(r**gamma + sigma**2.0) + gamma*sigma**2.0)\
             -gammaln(n/p) - n/p*log(s) - (n+p)/p * log(2.0) - (n+2.0)/2.0 *log(sigma**2 + r**gamma) \
             - r**(p*gamma/2.0 + p*delta)*kappa**p/2.0/s/(sigma**2+r**gamma)**(p/2.0) + addTerm
 
        return ll
Beispiel #28
0
def delta_chi2(ptarg, ndeg):
    """ Find delta chi2 corresponding to the given probability for n
    degrees of freedom (number of data points - number of free
    parameters).

    ptarg is the target probability (ptarg=0.9 correponds to 90%).

    ptarg is the probability that a model fitted to data with the
    given number of degrees of freedom will have a chisq val
    delta_chi2 larger than the minimum chisq value for the
    best-fitting parameters.
    """
    assert 0 <= ptarg <= 1
    d0, d1 = 0, 1e5
    a = 0.5 * ndeg
    while True:
        d = 0.5*(d0 + d1)
        p = gammainc(a, 0.5*d)
        #print ptarg, p, d, d0, d1
        if p > ptarg:
            d1 = d
        else:
            d0 = d
        if abs(p - ptarg) < 1e-4:
            break

    return d
Beispiel #29
0
    def _rhov2int(self, phi, r, ra):
        """Compute product of density and mean square velocity """

        # Isotropic case first
        rhov2r = exp(phi)*gammainc(self.g + 2.5, phi)
        rhov2  = 3*rhov2r
        rhov2t = 2*rhov2r

        # Add anisotropy
        if (ra < self.ramax)&(r>0)&(phi>0):
            p, g = r/ra, self.g
            p2 = p**2
            p12 = 1+p2
            g3, g5, g7, fp2 = g+1.5, g+2.5, g+3.5, phi*p2

            P1 = p2*phi**g5/gamma(g7)
            H1, H2 = hyp1f1(1, g7, -fp2), hyp1f1(2, g7, -fp2)

            rhov2r += P1*H1
            rhov2r /= p12

            rhov2t /= p12
            rhov2t += 2*P1*(H1/p12 + H2)
            rhov2t /= p12

            rhov2 = rhov2r + rhov2t
        return rhov2, rhov2r, rhov2t
def sersic_L_Rcut(Ieff,Reff,ndex,Rcut=100):
    bn = 2.0*ndex-1/3.0+0.009876/ndex
    xtmp = bn*(Rcut)**(1.0/ndex)
    res = 2.0*np.pi*Ieff*Reff**2.0*ndex*(np.e**bn/(bn**(2.0*ndex)))*spf.gammainc(2.0*ndex,xtmp)*spf.gamma(2.0*ndex)

    #res = np.pi*Ieff*Reff**2.0*(2.0*ndex)*(np.e**bn/(bn**(2.0*ndex)))*spf.gamma(2.0*ndex)
    return res
Beispiel #31
0
def likelihood(p, f, nswitch):
    if nswitch == 1:
        ecc, pa, r_e, g_x, g_y = p  #Galaxy position, eccentricity, position
        x, y, N, area, max_rad, E_bg, n = f  #angle, half-light radius, background density
    else:
        ecc, pa, r_e, n, g_x, g_y = p
        x, y, N, area, max_rad, E_bg = f

#     rand = np.random.choice(len(x),size=(int(round(area*E_bg))),replace=False)
#
#     mask = np.zeros(len(x))
#     mask[rand] = 1
#     x = np.ma.masked_array(x,mask)
#     y = np.ma.masked_array(y,mask)
#     N = len(x) - int(round(area*E_bg))
# Eqn from Martin, De Jong, Rix 2008

    ellip_r = np.sqrt(((1 - ecc)**-1 * ((x - g_x) * np.cos(pa) -
                                        (y - g_y) * np.sin(pa)))**2 +
                      ((x - g_x) * np.sin(pa) + (y - g_y) * np.cos(pa))**2)

    b_n = 1.9992 * n - .3271
    ##Normalization term comes from Graham and Driver, 2005
    norm_term = ((N - E_bg * area) * b_n**(2 * n) / (r_e**2 * 2 * np.pi * n *
                                                     (1 - ecc)) /
                 (gammainc(2 * n,
                           b_n * (max_rad / r_e)**(1. / n)) * gamma(2 * n)))

    fcn = (np.sum(
        np.log(norm_term * np.exp(-b_n * ((ellip_r / r_e)**(1. / n))) + E_bg)))

    ########David Sand's LL fcn
    #     N_ = N - area * E_bg
    #     S0 = N_ / (2 * np.pi * (r_e / b_n)**2 * (1 - ecc))
    #     fcn = np.sum(np.log(S0 * np.exp(-b_n* (ellip_r / r_e)) + E_bg))

    #     b_n = 1.9992*n - .3271
    # #     N = N - E_bg*area
    #     fcn = (-2 * N * np.log(r_e)
    #           + N * np.log(b_n**(2*n) / n
    #           			  / (gammainc(2*n,b_n * (max_rad/r_e)**(1./n)) * gamma(2*n))
    #           			  )
    #           - N * np.log(2 * np.pi)
    #           - N * np.log(1-ecc)
    #           - b_n * np.sum(ellip_r ** (1/n)) / r_e ** (1/n)
    # #           + np.log(E_bg)
    #           )

    if (np.min(x) < g_x < np.max(x) and np.min(y) < g_y < np.max(y)
            and 0 <= ecc < 1 and 0 <= pa < np.pi and  # 0 < r_e < 10
            .3 < n < 10 and 0 < r_e < 10
            #and 0 <= E_bg < N/area
        ):
        return (fcn)
    else:
        return (-np.inf)
def Iq(q, rg=60.0, porod_exp=3.0):
    """
    :param q:         Input q-value (float or [float, float])
    :param rg:        Radius of gyration
    :param porod_exp: Porod exponent
    :return:          Calculated intensity
    """
    usub = (q * rg)**2 * (2.0 / porod_exp + 1.0) * (2.0 / porod_exp +
                                                    2.0) / 6.0
    with errstate(divide='ignore', invalid='ignore'):
        upow = power(usub, -0.5 * porod_exp)
        # Note: scipy gammainc is "regularized", being gamma(s,x)/Gamma(s),
        # so need to scale by Gamma(s) to recover gamma(s, x).
        result = (porod_exp * upow *
                  (gamma(0.5 * porod_exp) * gammainc(0.5 * porod_exp, usub) -
                   upow * gamma(porod_exp) * gammainc(porod_exp, usub)))
    result[q <= 0] = 1.0

    return result
def singinhomobremss(
    freq, S_norm, alpha, p, peak_frequency
):  # Single inhomogeneous free-free emission model
    return (
        S_norm
        * (p + 1)
        * ((freq / peak_frequency) ** (2.1 * (p + 1) - alpha))
        * special.gammainc((p + 1), ((freq / peak_frequency) ** (-2.1)))
        * special.gamma(p + 1)
    )
Beispiel #34
0
    def mass(self, r):

        x = r / self._rs
        gamma = spfn.gamma(3. / self._alpha)

        return 4*np.pi*self._rhos*np.power(self._rs,3)/self._alpha* \
            np.exp(2./self._alpha)* \
            np.power(2./self._alpha,-3./self._alpha)* \
            gamma*spfn.gammainc(3./self._alpha,
                                (2./self._alpha)*np.power(x,self._alpha))
Beispiel #35
0
    def _rhoint_rot(self, phi, r, theta):
        # Compute eq 3 for scalar phi, r and theta
        g, om = self.g, self.omega
        Q = 3 * sqrt(2) * r * sin(theta)
        # Eq 3
        integ = quad(
            lambda x: exp(phi - x) * gammainc(g, phi - x) * numpy.sinh(
                om * Q * x**0.5), 0, phi)[0]

        return integ / (om * Q * gamma(1.5))
Beispiel #36
0
    def _polymerexclvol(self, x):
        
        sc = self.params['scale']
        rg = self.params['rg']
        mm  = self.params['m']
        bg = self.params['background']
    
        nu = 1.0 / mm
    
        Xx = x * x * rg * rg *(2.0 * nu + 1.0) * (2.0 * nu + 2.0) / 6.0
        onu = 1.0 / nu
        o2nu = 1.0 /(2.0 * nu)
        Ps =(1.0 / (nu * pow(Xx,o2nu))) * (gamma(o2nu)*gammainc(o2nu,Xx) - \
                        1.0 / pow(Xx,o2nu) * gamma(onu)*gammainc(onu,Xx))

        if x == 0:
            Ps = 1.0

        return (sc * Ps + bg);
Beispiel #37
0
    def get_mass(self,r):
        """galpy power-law mass

        be careful of the scipy gamma incomplete gamma function definition!

        inputs
        ---------------
        r    : radius to compute enclosed mass for
        """
        return 2.*np.pi*self.rho0*self.rcut**(3.-self.alpha)*gammainc(1.5-self.alpha/2.,(r/self.rcut)**2.)*gamma(1.5-self.alpha/2.)
Beispiel #38
0
    def test_incomplete_gamma_p(self, N, percentile):

        inverse = covid19.inv_incomplete_gamma_p(percentile, N)
        forward = gammainc(N, inverse)
        np.testing.assert_almost_equal(
            percentile,
            forward,
            decimal=6,
            err_msg=
            "Forward and inverse calculations of incomplete gamma don't agree")
Beispiel #39
0
def calculate_r(z, t2, length, alpha, beta, N):
    x1 = np.power(z, 2)
    x1_ = np.cumsum(x1, axis=1)
    x1 = np.outer(x1_, t2)
    x2 = x1.transpose()
    x3 = np.zeros(length)
    x3 = np.c_[x3, x2[:, :-1]]
    x3 = np.tril(x3)
    x4 = (x1 - x3) / 2
    # x5 = (1 - 1 / eta**2) * x4 - N * np.log(eta)
    x5_1 = np.tril(np.log(gammainc(beta + x4, alpha + N / 2)))
    x5_2 = np.tril(gammaln(alpha + N / 2))
    x5_3 = alpha * np.log(beta) - gammaln(alpha) - np.log(gammainc(
        beta, alpha))
    x5_4 = -(alpha + N / 2) * np.tril(np.log(beta + x4))
    x5 = x4 + x5_1 + x5_2 + x5_3 + x5_4
    lmbda = np.tril(np.exp(x5))
    r = np.sum(lmbda.T, axis=0)
    return r
Beispiel #40
0
 def posterior(D):
     """Remember gammainc is normalized to gamma"""
     min_D = sigma2 / dt
     if D <= min_D:
         ln_res = -np.inf
     else:
         ln_res = (p * log(n * V * G3 / (4 * dt * D)) - n * V * G3 /
                   (4 * D * dt) - log(D) -
                   log(gammainc(p, rel_loc_error * G3)) - gammaln(p))
     return np.exp(ln_res)
Beispiel #41
0
def getGamma(k, maxsbins):
    # Space out bins according to shape k+1 so that each bin represents an equal
    # (incomplete) expectation of X in the shape k distribution. Other bin choices are
    # possible, but this is a good one from the point of view of achieving more accuracy
    # using a smaller number of bins.
    l = gammadist.ppf([i / maxsbins for i in range(maxsbins)], k + 1)

    # Calculate:
    #   m0[i]   = P[X < l_i]
    #   m1[i]   = E[X; X < l_i]
    #   susc[i] = E[X | l_i <= X < l_{i+1}], the representative susceptibility for bin i
    #   q[i]    = P(l_i <= X < l_{i+1})
    m0 = np.append(gammainc(k, l), 1)
    m1 = np.append(gammainc(k + 1, l), 1)
    susc = np.array([(m1[i + 1] - m1[i]) / (m0[i + 1] - m0[i])
                     for i in range(maxsbins)])
    q = np.array([m0[i + 1] - m0[i] for i in range(maxsbins)])

    return susc, q
Beispiel #42
0
    def getMass(self, sigCrit=1.):
        from math import pi
        from scipy.special import gammainc, gamma

        b, n, re = self.b, self.n, self.re
        k = 2. * n - 1. / 3 + 4. / (405. * n) + 46 / (25515. * n**2)
        amp = b * b * k**(2 * n) / (
            2 * n * re**2 * (gamma(2 * n) * gammainc(2 * n,
                                                     k * (b / re)**(1 / n))))
        return 2 * pi * sigCrit * re**2 * amp * gamma(2 * n) * n / k**(2 * n)
Beispiel #43
0
def eta_esin(nu, r, tempi, tempe, v):

    theta = boltzmann * tempe / (electronMass * cLight2)
    ne = eDens(r, tempi, tempe, v)
    h = height(r, tempi, tempe)
    tau_es = 2.0 * ne * thomson * h
    s_exp = tau_es * (tau_es + 1.0)
    A = 1.0 + 4.0 * theta * (1.0 + 4.0 * theta)
    etaMax = 3.0 * boltzmann * tempe / (planck * nu)
    jm = np.log(etaMax) / np.log(A)

    gamma1 = sp.gammainc(jm + 1.0, A * s_exp)
    gamma2 = sp.gammainc(jm + 1.0, s_exp)
    aux2 = s_exp * (A - 1.0)

    result = np.where(aux2 < 200.0,
                      np.exp(aux2) * (1.0 - gamma1) + etaMax * gamma2,
                      etaMax * gamma2)
    return result
Beispiel #44
0
  def testIgammaMediumValues(self, dtype, rtol, atol):
    # Test values near zero.
    x = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype)
    a = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype)

    expected_values = sps.gammainc(a, x)
    with self.session() as sess:
      with self.test_scope():
        actual = sess.run(math_ops.igamma(a, x))
    self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol)
Beispiel #45
0
 def expected_grad(sample, concentration, rate):
     u = sp_special.gammainc(
         concentration, sample * rate)
     delta = 1e-3
     return sp_misc.derivative(
         lambda concentration_prime: sp_special.
         gammaincinv(  # pylint:disable=g-long-lambda
             concentration_prime, u),
         concentration,
         dx=delta * concentration) / rate
Beispiel #46
0
def sersic_mag_tot_to_Ieff(mag_tot, Reff, ndex, z, Rcut=100):  # g band
    bn = 2.0 * ndex - 1 / 3.0 + 0.009876 / ndex
    xtmp = bn * (Rcut)**(1.0 / ndex)
    ktmp = 2.0 * np.pi * ndex * (np.e**bn / (bn**(2.0 * ndex))) * spf.gammainc(
        2.0 * ndex, xtmp) * spf.gamma(2.0 * ndex)
    Dl_s = p13.luminosity_distance(z).value * 1e6

    Ieff = 10.0**((5.12 - 2.5 * np.log10(ktmp) - 5.0 * np.log10(Reff) +
                   5.0 * np.log10(Dl_s / 10) - mag_tot) * 0.4)  # L_sun/pc^2
    return Ieff
Beispiel #47
0
 def rho0(self, mass):
     """Central density for the Einasto profile in M_sun/Mpc^3 h^2"""
     alpha = 0.18
     R200 = self.R200(mass)
     conc = self.concentration(mass)
     gamma = special.gammainc(
         3 / alpha, 2 / alpha * conc**alpha) * special.gamma(3 / alpha)
     prefac = 4 * math.pi * np.exp(
         2 / alpha) / alpha * (alpha / 2)**(3 / alpha)
     return mass / gamma / prefac / (R200 / conc)**3
    def cdf(self, dat):
        '''

        Evaluates the cumulative distribution function on the data points in dat. 

        :param dat: Data points for which the c.d.f. will be computed.
        :type dat: natter.DataModule.Data
        :returns:  A numpy array containing the probabilities.
        :rtype:    numpy.array
           
        '''
        u = array([self.param['a'], self.param['b']])
        u = .5 + 0.5 * sign(u) * gammainc(
            1 / self.param['p'],
            abs(u)**self.param['p'] / self.param['s'])
        return squeeze(.5 + 0.5 * sign(dat.X) *
                       gammainc(1 / self.param['p'],
                                abs(dat.X)**self.param['p'] /
                                self.param['s']) - u[0]) / (u[1] - u[0])
Beispiel #49
0
    def get_rho0(self):
        """solve the mass enclosed at 100rcut to recover the central density

        returned in units of density, mass/(length^3)
        """

        r = 100.*self.rscl
        tmp_mass =  2.*np.pi*self.rcut**(3.-self.alpha)*gammainc(1.5-self.alpha/2.,(r/self.rcut)**2.)*gamma(1.5-self.alpha/2.)

        return self.M/tmp_mass
def randsphere(n_points,ndim,radius,center = []):
    if center == []:
        center = np.array([0]*ndim)
    r = radius
    x = np.random.normal(size=(n_points, ndim))
    ssq = np.sum(x**2,axis=1)
    fr = r*gammainc(ndim/2,ssq/2)**(1/ndim)/np.sqrt(ssq)
    frtiled = np.tile(fr.reshape(n_points,1),(1,ndim))
    p = center + np.multiply(x,frtiled)
    return p, center
Beispiel #51
0
def approximateEntropy(m, sequence):
    n = len(sequence)
    fi1 = get_fi(m, sequence)
    fi2 = get_fi(m + 1, sequence)
    print(fi1 - fi2)
    print(math.log(2) - (fi1 - fi2))
    obs = 2 * n * (math.log(2) - (fi1 - fi2))
    print(obs)
    p = 1 - special.gammainc(math.pow(2, m - 1), obs / 2)
    return p, p >= 0.01
Beispiel #52
0
def v_esc_theory_flat_lambda(theta,z_c,alpha,rho_2_1e14,r_2,beta,little_h,omega_DE):
    """cosmology"""
    H_z = H_z_function(z_c, [omega_DE,little_h],'flat_lambda')
    q_z= q_z_function(z_c,omega_DE,'flat_lambda')

    """Einasto"""
    ### map betweenEinasto params and Miller et al params###
    rho_2 = rho_2_1e14*1e14

    n = 1/alpha
    rho_0 = rho_2 * np.exp(2.*n)
    h = r_2 / (2.*n)**n

    d_n = (3*n) - (1./3.) + (8./1215.*n) + (184./229635.*n**2.) + (1048./31000725.*n**3.) - (17557576./1242974068875. * n**4.) 
    gamma_3n = 2 * ((ss.gammainc(3*n , d_n) ) * ss.gamma(3*n))
    Mtot = 4. * np.pi * rho_0 * Msun * (h**3.) * n * gamma_3n #kg

    G_newton = astroc.G.to( u.Mpc *  u.km**2 / u.s**2 / u.kg).value #Mpc km2/s^2 kg

    r_eq_cubed = -((G_newton*Mtot) / (q_z * H_z**2.)) #Mpc ^3
    r_eq = (r_eq_cubed)**(1.0/3.0)# Mpc

    """if r_eq -> infinity then return vanilla Einasto"""
    if q_z < 0.:
        ### phi orig ###
        s_orig = r/h

        part1_orig = 1. - ( ( ss.gammaincc(3.*n,s_orig**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_orig = (s_orig *  ss.gammaincc(2.*n,s_orig**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_orig =  -(G_newton* Mtot/(s_orig*h)) * (part1_orig+part2_orig)

        ### phi r_eq ###
        s_req = r_eq/h

        part1_req = 1. - ( ( ss.gammaincc(3.*n,s_req**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_req = (s_req *  ss.gammaincc(2.*n,s_req**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_req =  -(G_newton* Mtot/(s_req*h)) * (part1_req+part2_req)

        v_esc = np.sqrt(-2.*( phi_ein_orig - phi_ein_req ) - q_z * (H_z**2.) * (r**2 - r_eq**2) )

    elif q_z >= 0.:
        ### phi orig ###
        s_orig = r/h

        part1_orig = 1. - ( ( ss.gammaincc(3.*n,s_orig**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_orig = (s_orig *  ss.gammaincc(2.*n,s_orig**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_orig =  -(G_newton* Mtot/(s_orig*h)) * (part1_orig+part2_orig)

        v_esc = np.sqrt(-2.*( phi_ein_orig  )) 

    v_esc_projected = v_esc / np.sqrt(g_beta(beta))
    return v_esc_projected
Beispiel #53
0
def v_esc_theory_non_flat_lil(theta,z_c,alpha,rho_2_1e14,r_2,beta,lil_omega_M,lil_omega_lambda):
    """cosmology"""
    qHsquared = ( (0.5 * lil_omega_M * (1+z_c)**3.)- lil_omega_lambda) * 100.**2.

    """Einasto"""
    ### map betweenEinasto params and Miller et al params###
    rho_2 = rho_2_1e14*1e14

    n = 1/alpha
    rho_0 = rho_2 * np.exp(2.*n)
    h = r_2 / (2.*n)**n

    d_n = (3*n) - (1./3.) + (8./1215.*n) + (184./229635.*n**2.) + (1048./31000725.*n**3.) - (17557576./1242974068875. * n**4.) 
    gamma_3n = 2 * ((ss.gammainc(3*n , d_n) ) * ss.gamma(3*n))
    Mtot = 4. * np.pi * rho_0 * Msun * (h**3.) * n * gamma_3n #kg

    G_newton = astroc.G.to( u.Mpc *  u.km**2 / u.s**2 / u.kg).value #Mpc km2/s^2 kg

    r_eq_cubed = -(G_newton*Mtot) / qHsquared #Mpc ^3
    r_eq = (r_eq_cubed)**(1.0/3.0)# Mpc


    """if r_eq -> infinity then return vanilla Einasto"""
    if math.isnan(r_eq) == False:
        ### phi orig ###
        s_orig = r/h

        part1_orig = 1. - ( ( ss.gammaincc(3.*n,s_orig**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_orig = (s_orig *  ss.gammaincc(2.*n,s_orig**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_orig =  -(G_newton* Mtot/(s_orig*h)) * (part1_orig+part2_orig)

        ### phi r_eq ###
        s_req = r_eq/h

        part1_req = 1. - ( ( ss.gammaincc(3.*n,s_req**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_req = (s_req *  ss.gammaincc(2.*n,s_req**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_req =  -(G_newton* Mtot/(s_req*h)) * (part1_req+part2_req)

        v_esc = np.sqrt(-2.*( phi_ein_orig - phi_ein_req ) - qHsquared * (r**2 - r_eq**2) )

    elif math.isnan(r_eq) == True:
        ### phi orig ###
        s_orig = r/h

        part1_orig = 1. - ( ( ss.gammaincc(3.*n,s_orig**(1./n)) * ss.gamma(3.*n) ) / gamma_3n )
        part2_orig = (s_orig *  ss.gammaincc(2.*n,s_orig**(1./n)) * ss.gamma(2.*n) ) / gamma_3n

        phi_ein_orig =  -(G_newton* Mtot/(s_orig*h)) * (part1_orig+part2_orig)

        v_esc = np.sqrt(-2.* phi_ein_orig  ) 

    v_esc_projected = v_esc / np.sqrt(g_beta(beta))
    return v_esc_projected
Beispiel #54
0
def mole_gammainc(m, z):
    """
    Compute incomplete gamma function defined below
    .    F_m(z) = Int_0^1 t^{2m} Exp[-zt^2]dt
    Impled with scipy.special.gammainc(a,x) defined below
    .    1/Gamma[a] Int_0^x t^{a-1} Exp[-t] dt
    Variable transformation 
    .    t->(t^2)/x
    .    dt -> (2t/x) dt
    .    gammainc(a,x) = x^{1-a} /Gamma[a]  Int_0^1 t^{2a-2} (2t/x) Exp[-(t^2)/x] dt
    .                  = 2 (x^(-a))/gamma[a] Int_0^1 t^{2a-1} Exp[-(t^2)/x] dt
    .   F_m(z) = (1/2) gamma[a] x^a 

    Special case
    .  z = 0
    .  F_m(0) = Int_0^1 t^{2m} dt 
    .         = (2m+1)^{-1} [t^{2m+1}]_0^1 
    .         = (2m+1)^{-1}
    """

    eps = 10.0**(-14.0)

    if (abs(z) < eps):
        return 1 / (2 * m + 1.0)

    if (m == 0):
        a = m + 0.5
        res = gamma(a) / (2 * z**a) * gammainc(a, z)


#        res = sqrt(pi/z)/2 * erf(sqrt(z))
    else:
        a = m + 0.5
        res = gamma(a) / (2 * z**a) * gammainc(a, z)

    if ((not res < 1) and (not res > -1)):
        raise RuntimeError("""gammain failed
        res: {2}
        m: {0}
        z: {1}
        """.format(m, z, res))
    return res
Beispiel #55
0
def qminus_esin_fast(r, tempi, tempe, v):
    nuMin = 1.0e6
    nuMax = 1.0e21
    iter = 30
    paso = np.power(nuMax / nuMin, 1.0 / float(iter - 1))
    sum = 0.0
    nu = nuMin

    theta = boltzmann * tempe / (electronMass * cLight2)
    ne = eDens(r, tempi, tempe, v)
    h = height(r, tempi, tempe)
    k_es = ne * thomson
    tau_es = 2.0 * k_es * h
    A = 1.0 + 4.0 * theta * (1.0 + 4.0 * theta)
    for i in range(iter):
        x = planck * nu / (electronMass * cLight2) / (3.0 * theta)
        bnu = blackbody_nu(nu, tempe).value
        bnu2 = 4.0 * np.pi * bnu
        xi = xiBremss(nu, r, tempi, tempe, v) + xiSync(nu, r, tempi, tempe, v)
        #k_nu = np.where(bnu2 > 1.0e-2*xi*h,xi/bnu2,50.0)
        k_nu = xi / bnu2
        #l_eff = 1.0/np.sqrt(k_nu*(k_nu+k_es))
        #tau_es = 2.0*k_es*np.where(l_eff<h,l_eff,h)

        s_exp = tau_es * (tau_es + 1.0)
        etaMax = 3.0 * boltzmann * tempe / (planck * nu)
        jm = np.log(etaMax) / np.log(A)

        gamma1 = sp.gammainc(jm + 1.0, A * s_exp)
        gamma2 = sp.gammainc(jm + 1.0, s_exp)
        aux2 = s_exp * (A - 1.0)

        #etaa = np.where(aux2<200.0,np.exp(aux2)*(1.0-gamma1)+etaMax*gamma2,etaMax*gamma2)
        etaa = np.exp(aux2) * (1.0 - gamma1) + etaMax * gamma2

        tau_nu = np.sqrt(np.pi) / 2.0 * k_nu * h
        fluxx = 2.0*np.pi/np.sqrt(3.0) * bnu * \
            (1.0-np.exp(-2.0*np.sqrt(3.0)*tau_nu))
        dnu = nu * (np.sqrt(paso) - 1.0 / np.sqrt(paso))
        sum += fluxx * etaa * dnu
        nu = nu * paso
    return sum * 2.0 / (np.sqrt(np.pi) * h)
Beispiel #56
0
def compute_deff_prime(alpha_ice, g_ice, sigma_a, delta_a1, delta_a2, sigma_v,
                       delta_v1, delta_v2, Dr, x):

    alpha_a1_g_ice = (alpha_ice + delta_a1 + 1) / g_ice
    alpha_a2_g_ice = (alpha_ice + delta_a2 + 1) / g_ice

    t_k = (1 / x) * (Dr**g_ice)
    #coordinate transform for limit of integration

    gamma_fun_a1 = gm.gamma(alpha_a1_g_ice)
    inc_gamma_fun_a1 = gm.gammainc(t_k, alpha_a1_g_ice)
    gamma_fun_a2 = gm.gamma(alpha_a2_g_ice)
    inc_gamma_fun_a2 = gm.gammainc(t_k, alpha_a2_g_ice)

    alpha_v1_g_ice = (alpha_ice + 2 * delta_v1 + 1) / g_ice
    alpha_v2_g_ice = (alpha_ice + 2 * delta_v2 + 1) / g_ice

    gamma_fun_v1 = gm.gamma(alpha_v1_g_ice)
    inc_gamma_fun_v1 = gm.gammainc(t_k, alpha_v1_g_ice)
    gamma_fun_v2 = gm.gamma(alpha_v2_g_ice)
    inc_gamma_fun_v2 = gm.gammainc(t_k, alpha_v2_g_ice)

    A = Dr**(-2 * delta_v1) * inc_gamma_fun_v1 * gamma_fun_v1
    B = Dr**(-2 * delta_v2) * (1 - inc_gamma_fun_v2) * gamma_fun_v2
    C = Dr**(-delta_a1) * inc_gamma_fun_a1 * gamma_fun_a1
    G = Dr**(-delta_a2) * (1 - inc_gamma_fun_a2) * gamma_fun_a2

    area_factor = (C * x**(delta_a1 / g_ice) + G * x**(delta_a2 / g_ice))

    deff_prime = (A * x**(2 * delta_v1 / g_ice) +
                  B * x**(2 * delta_v2 / g_ice)) / area_factor

    deff_prime = Dr * deff_prime**0.25 * (sigma_v**2 / sigma_a)**0.25

    #compute average area of particle in square microns.
    ave_area = sigma_a * (np.pi / 4) * Dr**2 * area_factor / gm.gamma(
        (alpha_ice + 1) / g_ice)
    ave_area *= 1e-12
    LOG.debug('ave_area')
    LOG.debug(ave_area)

    return deff_prime, ave_area
Beispiel #57
0
def boys(n, x):
    import scipy.special as sp
    # x -> 0: the denominator goes to 0, zero deviation error will occur.
    # thus, have to return 0-limit value(x->0.)
    if x < 0.: raise
    radius = 0.0001
    if x < radius:  return 1. / (2.0 * n + 1.0)
    else:
        numerator =  sp.gammainc(n+0.5, x)  * sp.gamma(n + 0.5)
        denominator = 2.0 * math.pow(x, n + 0.5)
        return numerator /denominator
Beispiel #58
0
 def Q(self, nu, chisq):
     """
     Calculate the probability that a normally distributed random numbers produce a chi squared value greater than
     measured. The distribution is described by an incomplete gamma function and should only be used for models that
     are linear or close to linear in their parameters.
     [1] pg. 778-780.
     :param nu: Number of degrees of freedom.
     :param chisq: Measured chi squared value.
     :return: The probability that random noise will produce a chi squared greater than the measured value.
     """
     return 1 - spsp.gammainc(nu / 2, chisq / 2)
Beispiel #59
0
    def _cdf(self, x):
        k = self.k
        mu = self.mu
        p = self.p
        sumand = (k * (-p + 1) * gamma(k) * gammainc(k, mu * x)) / (
            (factorial(k - 1) * gamma(k + 1)))

        if mu == 0:
            return sumand + mu * p * x
        else:
            return sumand + mu * p * (-(1 / mu) * np.exp(-mu * x))
Beispiel #60
0
def gamma_dist(k, theta, n=400):
    assert k > 0 and theta > 0
    assert type(n) == int and n > 2
    dist = np.zeros((n, 2))
    dist[:, 0] = np.linspace(0,
                             k * theta + 5 * np.sqrt(k) * theta,
                             n,
                             endpoint=False)
    cumdist = np.concatenate((sp.gammainc(k, dist[:, 0] / theta), [1]))
    dist[:, 1] = np.diff(cumdist)
    return dist