def _evaluate(self,R,z,phi=0.,t=0.,_forceFloatEval=False):
     """
     NAME:
        _evaluate
     PURPOSE:
        evaluate the potential at R,z
     INPUT:
        R - Galactocentric cylindrical radius
        z - vertical height
        phi - azimuth
        t - time
     OUTPUT:
        Phi(R,z)
     HISTORY:
        2010-07-09 - Started - Bovy (NYU)
     """
     if not _forceFloatEval and not self.integerSelf == None:
         return self.integerSelf._evaluate(R,z,phi=phi,t=t)
     elif self.beta == 3.:
         r= numpy.sqrt(R**2.+z**2.)
         return (1./self.a)\
             *(r-self.a*(r/self.a)**(3.-self.alpha)/(3.-self.alpha)\
                   *special.hyp2f1(3.-self.alpha,
                                   2.-self.alpha,
                                   4.-self.alpha,
                                   -r/self.a))/(self.alpha-2.)/r
     else:
         r= numpy.sqrt(R**2.+z**2.)
         return special.gamma(self.beta-3.)\
             *((r/self.a)**(3.-self.beta)/special.gamma(self.beta-1.)\
                   *special.hyp2f1(self.beta-3.,
                                   self.beta-self.alpha,
                                   self.beta-1.,
                                   -self.a/r)
               -special.gamma(3.-self.alpha)/special.gamma(self.beta-self.alpha))/r
Example #2
0
def demon(n, d, g, kgiven=0):
    ks = np.arange(n + 1)
    c1, c2 = [], []
    for k in ks:
        a = hyp2f1(1, n - k + 1, n + 2, 1 - d)
        b = 0 if g == 0 else hyp2f1(1, n - k + 1, n + 2, 1 - d * g)
        c1.append(a * d - b * d * g)
        c2.append(a)
    plt.plot(ks / n, c1, label='c1')
    plt.plot(ks / n, c2, label='c2')
    plt.xlabel('k / n')
    plt.ylabel('Effective n / n')
    plt.legend()

    plt.figure()
    S = [100 * generalised_entropy_gain(n, k, d, g) for k in ks]
    plt.plot(ks / n, S, label='S')
    plt.xlabel('k / n')
    plt.ylabel('information gain')

    plt.figure()
    dif = np.logspace(-1, 1, 100)
    S = [100 * generalised_entropy_gain(n, kgiven, d, g) for d in dif]
    plt.semilogx(dif, S, label='S')
    plt.xlabel('difficulty')
    plt.ylabel('information gain')
def Power_Spectrum_Real_Space_e1(f,x,modes_number):
    n = modes_number + 1
    if (n<2):
       print "ERROR: It can not calculate the power spectrum of real space because the number of input points are not enough."
       return 0
    else:
       mode = zeros(n)
       amp  = zeros(n)

       amp[0] = float('inf')
#       for j in range(1,len(t)):
#          pk[0] += 0.5*(t[j]-t[j-1])*(x[j]+x[j-1])/2.0

       for i in range(1,n):
          A = 0.0
          B = 0.0
          for j in range(1,len(x)-1):
             A += ( f[j]*sqrt(16.0*float(i+1)*float(i+2)/pi)*cos(x[j])**3*hyp2f1(-i,3+i,1.5,sin(x[j])**2)*tan(x[j])**2 \
            + f[j-1]*sqrt(16.0*float(i+1)*float(i+2)/pi)*cos(x[j-1])**3*hyp2f1(-i,3+i,1.5,sin(x[j-1])**2)*tan(x[j-1])**2 ) \
                  * (x[j]-x[j-1])/2.0
#             B += -4.0*sqrt(2.0+3.0*float(i)+float(i)**2)/(3.0*(3.0+2.0*float(i))*sqrt(pi)) \
#                 *( f[j]*sin(x[j])*(4.0*float(i)*(3.0+float(i))*cos(x[j])**4*hyp2f1(1-i,4+i,2.5,sin(x[j])**2) \
#                                + 9.0*cos(x[j])**2*hyp2f1(-i,3+i,1.5,sin(x[j])**2) )*tan(x[j])**2\
#                   +f[j-1]*sin(x[j-1])*(4.0*float(i)*(3.0+float(i))*cos(x[j-1])**4*hyp2f1(1-i,4+i,2.5,sin(x[j-1])**2) \
#                                + 9.0*cos(x[j-1])**2*hyp2f1(-i,3+i,1.5,sin(x[j-1])**2) )*tan(x[j-1])**2 )\
#                  * (x[j]-x[j-1])/2.0

          mode[i]= float(i)
          amp[i] = (A**2 + B**2)/2.0

          print "mode = ", mode[i], " & Amplitude = ", amp[i]

       return (mode,amp)
Example #4
0
    def _A_0(params, freq, rec, T):
        x = freq
        r, alpha, s, beta = params
        max_alpha_beta = max(alpha, beta)
        min_alpha_beta = min(alpha, beta)
        t = s + 1. if alpha > beta else r + x
        r_s_x = r + s + x

        return special.hyp2f1(r_s_x, t, r_s_x + 1., (max_alpha_beta - min_alpha_beta) / (max_alpha_beta + rec)) / (max_alpha_beta + rec) ** r_s_x\
            - special.hyp2f1(r_s_x, t, r_s_x + 1., (max_alpha_beta - min_alpha_beta) / (max_alpha_beta + T)) / (max_alpha_beta + T) ** r_s_x
Example #5
0
    def _log_A_0(params, freq, rec, age):

        r, alpha, s, beta = params
        min_ab, max_ab, t = (alpha, beta, r + freq) if alpha < beta else (beta, alpha, s + 1)
        abs_ab = max_ab - min_ab
        rsx = r + s + freq
        p_1, q_1 = special.hyp2f1(rsx, t, rsx + 1., abs_ab / (max_ab + rec)), (max_ab + rec)
        p_2, q_2 = special.hyp2f1(rsx, t, rsx + 1., abs_ab / (max_ab + age)), (max_ab + age)
        sign = np.ones(len(freq))
        return misc.logsumexp([log(p_1) + rsx * log(q_2), log(p_2) + rsx * log(q_1)],
            axis=0, b=[sign, -sign]) - rsx * log(q_1 * q_2)
Example #6
0
def generalised_entropy_gain(n, k, d, g):
    if abs(d - 1) < 1e-6: d = 1 + 1e-6
    a = hyp2f1(1, n - k + 1, n + 2, 1 - d)
    b = 0 if g == 0 else hyp2f1(1, n - k + 1, n + 2, 1 - d * g)
    x = (a * d - b * d * g) * ((1 - g) * d * a - (1 - g * d)) / (d - 1)  # * (k+1)/(n+2)#
    y = a * (1 - g) * d * (1 - a) / (d - 1)  # (n-k+1)/(n+2)#
    H1 = H(k) - np.log(k + 1)
    H2 = H(n - k) - np.log(n - k + 1)
    Hn = H(n + 1) - np.log(n + 2) - 1. / (n + 2)
    dS = (x * H1 + y * H2 - (x + y) * Hn)
    return dS  # , a*d - b*d*g, a
Example #7
0
def ComovingDistance(z):
    """
    line-of-sight comoving distance to a source at redshift z
    units will be the same as D_H, defined above.

    if O_K==0, this will compute the result analytically, using
    hypergeometric functions.

    if O_K!=0, this will compute the result using numerical integration
    of the function 1/H(z). this case is omitted here.
    """
    check(O_K_is_zero, 'the universe should be flat!')

    return D_H*2/sqrt(O_M)*(hyp2f1(1./6, 1./2, 7./6, -O_L/O_M) - hyp2f1(1./6, 1./2, 7./6, -O_L/O_M/(1+z)**3) / sqrt(1+z))
Example #8
0
    def next_item(self, subtopic):
        ids, difficulty, types, costs = self.items[subtopic]
        n, k = subtopic.n, subtopic.k
        dS = [generalised_entropy_gain(n, k, d, g) for d, g in zip(difficulty, types)]
        dS /= costs
        maxind = np.argmax(dS)

        mask = list(xrange(maxind)) + list(xrange(maxind + 1, len(difficulty)))
        # print maxind, mask
        self.items[subtopic] = np.vstack((ids[mask], difficulty[mask], types[mask], costs[mask]))  # remove after test

        d, g = difficulty[maxind], types[maxind]
        a = hyp2f1(1, n - k + 1, n + 2, 1 - d)
        b = 0 if g == 0 else hyp2f1(1, n - k + 1, n + 2, 1 - d * g)
        return (ids[maxind], d, g, costs[maxind]), a * d - b * d * g, a
Example #9
0
def getExpectations(r, alpha, a, b, numdays):
    expectations = dict()
    for tt in range(1, numdays + 1):
        t = tt / 7.0
        x = special.hyp2f1(r, b, a + b - 1, t / (alpha + t))
        expectations[tt] = ((a + b - 1) / (a - 1)) * ( 1 - ( (alpha / (alpha + t)) ** r ) * x)
    return expectations
Example #10
0
def SHOREmatrix_odf(radial_order, zeta, sphere_vertices):
    """Compute the SHORE matrix"

    Parameters
    ----------
    radial_order : unsigned int,
        Radial Order
    zeta : unsigned int,
        scale factor
    sphere_vertices : array, shape (N,3)
        vertices of the odf sphere
    """

    r, theta, phi = cart2sphere(sphere_vertices[:, 0], sphere_vertices[:, 1], sphere_vertices[:, 2])
    theta[np.isnan(theta)] = 0
    counter = 0
    upsilon = np.zeros(
        (len(sphere_vertices), (radial_order + 1) * ((radial_order + 1) / 2) * (2 * radial_order + 1)))
    for n in range(radial_order + 1):
        for l in range(0, n + 1, 2):
            for m in range(-l, l + 1):
                upsilon[:, counter] = (-1) ** (n - l / 2.0) * __kappa_odf(zeta, n, l) * \
                    hyp2f1(l - n, l / 2.0 + 1.5, l + 1.5, 2.0) * \
                    real_sph_harm(m, l, theta, phi)
                counter += 1

    return upsilon[:, 0:counter]
Example #11
0
    def expected_number_of_purchases_up_to_time(
        self, 
        t
    ):
        """
        Calculate the expected number of repeat purchases up to time t.

        Calculate repeat purchases for a randomly chosen individual from the
        population.

        Equivalent to equation (9) of [2]_.

        Parameters
        ----------
        t: array_like
            times to calculate the expection for

        Returns
        -------
        array_like

        References
        ----------
        .. [2] Fader, Peter S., Bruce G.S. Hardie, and Ka Lok Lee (2005a),
        "Counting Your Customers the Easy Way: An Alternative to the
        Pareto/NBD Model," Marketing Science, 24 (2), 275-84.
        """

        r, alpha, a, b = self._unload_params("r", "alpha", "a", "b")
        hyp = hyp2f1(r, b, a + b - 1, t / (alpha + t))

        return (a + b - 1) / (a - 1) * (1 - hyp * (alpha / (alpha + t)) ** r)
Example #12
0
    def conditional_expected_number_of_purchases_up_to_time(
            self, t, frequency, recency, T):
        """
        Conditinal expected number of repeat purchases up to time t.

        Calculate the expected number of repeat purchases up to time t for a
        randomly choose individual from the population, given they have
        purchase history (frequency, recency, T)
        See Wagner, U. and Hoppe D. (2008).

        Parameters:
            t: a scalar or array of times.
            frequency: a scalar: historical frequency of customer.
            recency: a scalar: historical recency of customer.
            T: a scalar: age of the customer.

        Returns: a scalar or array

        """
        x = frequency
        r, alpha, a, b = self._unload_params('r', 'alpha', 'a', 'b')

        hyp_term = hyp2f1(r + x, b + x + 1, a + b + x, t / (alpha + T + t))
        first_term = (a + b + x) / (a - 1)
        second_term = (1 - hyp_term * ((alpha + T) / (alpha + t + T))**(r + x))
        numerator = first_term * second_term

        denominator = (1 + (a / (b + x)) * ((alpha + T) /
                                            (alpha + recency))**(r + x))

        return numerator / denominator
Example #13
0
    def msd(self):
        r""" Calculates the analytical mean squared displacement (MSD) [1]_

        ..math::
            :nowrap:
                \begin{equation}
                    MSD:{DSI}=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}
                    \int_{-\infty}^{\infty} P(\hat{\mathbf{r}}) \cdot
                    \hat{\mathbf{r}}^{2} \ dr_x \ dr_y \ dr_z
                \end{equation}

        where $\hat{\mathbf{r}}$ is a point in the 3D propagator space (see Wu
        et al. [1]_).

        References
        ----------
        .. [1] Wu Y. et al., "Hybrid diffusion imaging", NeuroImage, vol 36,
        p. 617-629, 2007.
        """
        msd = 0
        c = self._shore_coef

        for n in range(int(self.radial_order / 2) + 1):
            msd += c[n] * (-1) ** n *\
                (9 * (gamma(n + 1.5)) / (8 * np.pi ** 6 * self.zeta ** 3.5 *
                                         factorial(n))) ** 0.5 *\
                hyp2f1(-n, 2.5, 1.5, 2)

        return np.clip(msd, 0, msd.max())
Example #14
0
    def odf_sh(self):
        r""" Calculates the real analytical ODF in terms of Spherical
        Harmonics.
        """
        # Number of Spherical Harmonics involved in the estimation
        J = (self.radial_order + 1) * (self.radial_order + 2) // 2

        # Compute the Spherical Harmonics Coefficients
        c_sh = np.zeros(J)
        counter = 0

        for n in range(self.radial_order + 1):
            for l in range(0, n + 1, 2):
                for m in range(-l, l + 1):

                    j = int(l + m + (2 * np.array(range(0, l, 2)) + 1).sum())

                    Cnl = (((-1)**
                            (n - l / 2)) / (2.0 * (4.0 * np.pi**2 * self.zeta)**(3.0 / 2.0)) * (
                                (2.0 * (4.0 * np.pi**2 * self.zeta)**
                                 (3.0 / 2.0) * factorial(n - l)) / (gamma(n + 3.0 / 2.0)))**
                           (1.0 / 2.0))
                    Gnl = (gamma(l / 2 + 3.0 / 2.0) * gamma(3.0 / 2.0 + n)) / \
                        (gamma(l + 3.0 / 2.0) * factorial(n - l)) * \
                        (1.0 / 2.0) ** (-l / 2 - 3.0 / 2.0)
                    Fnl = hyp2f1(-n + l, l / 2 + 3.0 / 2.0, l + 3.0 / 2.0, 2.0)

                    c_sh[j] += self._shore_coef[counter] * Cnl * Gnl * Fnl
                    counter += 1

        return c_sh
Example #15
0
 def _zforce(self, R, z, phi=0., t=0.):
     """
     NAME:
        _zforce
     PURPOSE:
        evaluate the vertical force for this potential
     INPUT:
        R - Galactocentric cylindrical radius
        z - vertical height
        phi - azimuth
        t - time
     OUTPUT:
        the vertical force
     HISTORY:
        2010-07-09 - Written - Bovy (NYU)
     """
     if self._specialSelf is not None:
         return self._specialSelf._zforce(R, z, phi=phi, t=t)
     else:
         r = numpy.sqrt(R**2. + z**2.)
         return -z/r**self.alpha*self.a**(self.alpha-3.)/(3.-self.alpha)\
             *special.hyp2f1(3.-self.alpha,
                             self.beta-self.alpha,
                             4.-self.alpha,
                             -r/self.a)
Example #16
0
    def conditional_expected_number_of_purchases_up_to_time(self, t, frequency, recency, T):
        """
        Calculate the expected number of repeat purchases up to time t for a randomly choose individual from
        the population, given they have purchase history (frequency, recency, T)
        See Wagner, U. and Hoppe D. (2008).

        Parameters:
            t: a scalar or array of times.
            frequency: a scalar: historical frequency of customer.
            recency: a scalar: historical recency of customer.
            T: a scalar: age of the customer.

        Returns: a scalar or array
        """
        x = frequency
        r, alpha, a, b = self._unload_params('r', 'alpha', 'a', 'b')

        hyp_term = special.hyp2f1(r + x, b + x + 1, a + b + x, t / (alpha + T + t))
        first_term = (a + b + x) / (a - 1)
        second_term = (1 - hyp_term * ((alpha + T) / (alpha + t + T)) ** (r + x))
        numerator = first_term * second_term

        denominator = 1 + (a / (b + x)) * ((alpha + T) / (alpha + recency)) ** (r + x)

        return numerator / denominator
 def _Rforce(self, R, z, phi=0., t=0., _forceFloatEval=False):
     """
     NAME:
        _Rforce
     PURPOSE:
        evaluate the radial force for this potential
     INPUT:
        R - Galactocentric cylindrical radius
        z - vertical height
        phi - azimuth
        t - time
     OUTPUT:
        the radial force
     HISTORY:
        2010-07-09 - Written - Bovy (NYU)
     """
     if not _forceFloatEval and not self.integerSelf == None:
         return self.integerSelf._Rforce(R, z, phi=phi, t=t)
     else:
         r = numpy.sqrt(R**2. + z**2.)
         return -R/r**self.alpha*self.a**(self.alpha-3.)/(3.-self.alpha)\
             *special.hyp2f1(3.-self.alpha,
                             self.beta-self.alpha,
                             4.-self.alpha,
                             -r/self.a)
Example #18
0
    def msd(self):
        r""" Calculates the analytical mean squared displacement (MSD) [1]_

        ..math::
            :nowrap:
                \begin{equation}
                    MSD:{DSI}=\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}
                    \int_{-\infty}^{\infty} P(\hat{\mathbf{r}}) \cdot
                    \hat{\mathbf{r}}^{2} \ dr_x \ dr_y \ dr_z
                \end{equation}

        where $\hat{\mathbf{r}}$ is a point in the 3D propagator space (see Wu
        et. al [1]_).

        References
        ----------
        .. [1] Wu Y. et. al, "Hybrid diffusion imaging", NeuroImage, vol 36,
        p. 617-629, 2007.
        """
        msd = 0
        c = self._shore_coef

        for n in range(int(self.radial_order / 2) + 1):
            msd += c[n] * (-1) ** n *\
                (9 * (gamma(n + 1.5)) / (8 * np.pi ** 6 * self.zeta ** 3.5 *
                                         factorial(n))) ** 0.5 *\
                hyp2f1(-n, 2.5, 1.5, 2)

        return np.clip(msd, 0, msd.max())
Example #19
0
    def resid_anscombe(self, Y, mu):
        """
        The Anscombe residuals for the negative binomial family

        Parameters
        ----------
        Y : array-like
            Endogenous response variable
        mu : array-like
            Fitted mean response variable

        Returns
        -------
        resid_anscombe : array
            The Anscombe residuals as defined below.

        Notes
        -----
        `resid_anscombe` = (hyp2f1(-alpha*Y)-hyp2f1(-alpha*mu)+\
                1.5*(Y**(2/3.)-mu**(2/3.)))/(mu+alpha*mu**2)**(1/6.)

        where hyp2f1 is the hypergeometric 2f1 function parameterized as
        hyp2f1(x) = hyp2f1(2/3.,1/3.,5/3.,x)
        """

        hyp2f1 = lambda x: special.hyp2f1(2 / 3., 1 / 3., 5 / 3., x)
        return (hyp2f1(-self.alpha*Y)-hyp2f1(-self.alpha*mu)+1.5*(Y**(2/3.)-\
                mu**(2/3.)))/(mu+self.alpha*mu**2)**(1/6.)
Example #20
0
def test_hyp2f1_battin_scalar():
    x = np.linspace(0, 1, num=11)
    expected_res = special.hyp2f1(3, 1, 5/2, x)

    for ii, x_i in enumerate(x):
        res = hyper.hyp2f1(3, 1, 5/2, x_i)
        assert_almost_equal(res, expected_res[ii])
Example #21
0
    def odf_sh(self):
        r""" Calculates the real analytical ODF in terms of Spherical
        Harmonics.
        """
        # Number of Spherical Harmonics involved in the estimation
        J = (self.radial_order + 1) * (self.radial_order + 2) // 2

        # Compute the Spherical Harmonics Coefficients
        c_sh = np.zeros(J)
        counter = 0

        for l in range(0, self.radial_order + 1, 2):
            for n in range(l, int((self.radial_order + l) / 2) + 1):
                for m in range(-l, l + 1):

                    j = int(l + m + (2 * np.array(range(0, l, 2)) + 1).sum())

                    Cnl = (
                        ((-1) ** (n - l / 2)) /
                        (2.0 * (4.0 * np.pi ** 2 * self.zeta) ** (3.0 / 2.0)) *
                        ((2.0 * (4.0 * np.pi ** 2 * self.zeta) ** (3.0 / 2.0) *
                          factorial(n - l)) /
                         (gamma(n + 3.0 / 2.0))) ** (1.0 / 2.0)
                    )
                    Gnl = (gamma(l / 2 + 3.0 / 2.0) * gamma(3.0 / 2.0 + n)) / \
                        (gamma(l + 3.0 / 2.0) * factorial(n - l)) * \
                        (1.0 / 2.0) ** (-l / 2 - 3.0 / 2.0)
                    Fnl = hyp2f1(-n + l, l / 2 + 3.0 / 2.0, l + 3.0 / 2.0, 2.0)

                    c_sh[j] += self._shore_coef[counter] * Cnl * Gnl * Fnl
                    counter += 1

        return c_sh
Example #22
0
def shore_matrix_odf(radial_order, zeta, sphere_vertices):
    r"""Compute the SHORE ODF matrix [1]_"

    Parameters
    ----------
    radial_order : unsigned int,
        an even integer that represent the order of the basis
    zeta : unsigned int,
        scale factor
    sphere_vertices : array, shape (N,3)
        vertices of the odf sphere

    References
    ----------
    .. [1] Merlet S. et. al, "Continuous diffusion signal, EAP and
    ODF estimation via Compressive Sensing in diffusion MRI", Medical
    Image Analysis, 2013.
    """

    r, theta, phi = cart2sphere(sphere_vertices[:, 0], sphere_vertices[:, 1],
                                sphere_vertices[:, 2])
    theta[np.isnan(theta)] = 0
    F = radial_order / 2
    n_c = np.round(1 / 6.0 * (F + 1) * (F + 2) * (4 * F + 3))
    upsilon = np.zeros((len(sphere_vertices), n_c))
    counter = 0
    for l in range(0, radial_order + 1, 2):
        for n in range(l, int((radial_order + l) / 2) + 1):
            for m in range(-l, l + 1):
                upsilon[:, counter] = (-1) ** (n - l / 2.0) * _kappa_odf(zeta, n, l) * \
                    hyp2f1(l - n, l / 2.0 + 1.5, l + 1.5, 2.0) * \
                    real_sph_harm(m, l, theta, phi)
                counter += 1

    return upsilon
Example #23
0
def self_gravity_omega(R,disk):
    R2 = R * R 
    
    omega = math.pi * np.sqrt(math.pi) * disk.gravityG * 2.0**(disk.p/4.0) * disk.rho0 * R2 / disk.R_0 * spec.gamma(disk.p/2.0 + 0.5)/ spec.gamma(disk.p/2.0) \
            * spec.hyp2f1(disk.p/2.0 + 0.5, 1.5, 2.0, - R2 / disk.R_0 / disk.R_0)
    
    return omega
 def _zforce(self,R,z,phi=0.,t=0.,_forceFloatEval=False):
     """
     NAME:
        _zforce
     PURPOSE:
        evaluate the vertical force for this potential
     INPUT:
        R - Galactocentric cylindrical radius
        z - vertical height
        phi - azimuth
        t - time
     OUTPUT:
        the vertical force
     HISTORY:
        2010-07-09 - Written - Bovy (NYU)
     """
     if not _forceFloatEval and not self.integerSelf == None:
         return self.integerSelf._zforce(R,z,phi=phi,t=t)
     else:
         r= numpy.sqrt(R**2.+z**2.)
         return -z/r**self.alpha*self.a**(self.alpha-3.)/(3.-self.alpha)\
             *special.hyp2f1(3.-self.alpha,
                             self.beta-self.alpha,
                             4.-self.alpha,
                             -r/self.a)
Example #25
0
    def resid_anscombe(self, endog, mu):
        """
        The Anscombe residuals for the negative binomial family

        Parameters
        ----------
        endog : array-like
            Endogenous response variable
        mu : array-like
            Fitted mean response variable

        Returns
        -------
        resid_anscombe : array
            The Anscombe residuals as defined below.

        Notes
        -----
        `resid_anscombe` = (hyp2f1(-alpha*endog)-hyp2f1(-alpha*mu)+\
                1.5*(endog**(2/3.)-mu**(2/3.)))/(mu+alpha*mu**2)**(1/6.)

        where hyp2f1 is the hypergeometric 2f1 function parameterized as
        hyp2f1(x) = hyp2f1(2/3.,1/3.,5/3.,x)
        """

        hyp2f1 = lambda x : special.hyp2f1(2/3., 1/3., 5/3., x)
        return ((hyp2f1(-self.alpha * endog) - hyp2f1(-self.alpha * mu) +
                 1.5 * (endog**(2/3.)-mu**(2/3.))) /
                (mu + self.alpha*mu**2)**(1/6.))
def get_kbar_lam_approx(lam, n, R, a, alpha1, alpha2, beta1, beta2,
                        verbose = 0):
    """Function to compute the expected degree as a function of
       the latent parameter lam approximately. See Appendix of
       the WHSCM paper for details of approximation.

    Args:
        lam (float): The latent parameter lambda of a node.
        n (int): The number of nodes in a graph.
        R (float): The R parameter of the WHSCM.
        a (float): The a parameter of the WHSCM.
        alpha1 (float): The alpha1 parameter of the WHSCM.
        alpha2 (float): The alpha2 parameter of the WHSCM.
        beta1 (float): The beta1 parameter of the WHSCM.
        beta2 (float): The beta2 parameter of the WHSCM.

    Returns:
        kbar_lam_approx (float): The expected degree of a node
                                 with the latent parameter lambda
                                 in the WHSCM.
    """
    lam_c = get_lam_c(a, R, beta1)
    A1 = get_A1_const(alpha1, alpha2, lam_c)
    A2 = get_A2_const(alpha1, alpha2, lam_c, A1)

    if lam >= 1 and lam <= lam_c:
        term1 = (n*A1*(lam**(1.+beta1)))/(a * (alpha1-2.) * np.exp(2*R))
        term2 = special.hyp2f1(1., (alpha1-2.)/beta1, 1. + (alpha1-2.)/beta1, - (lam**beta1))
        term3 = (lam_c**(2.-alpha1)) * special.hyp2f1(1., (alpha1-2.)/beta1, 1. + (alpha1-2.)/beta1, - ((lam/lam_c)**beta1))
        term4 = (n * A2 * (lam_c)**(1.-alpha2)) / (alpha2 - 1.)
        term5 = special.hyp2f1(1., alpha2 - 1., alpha2, -(a * np.exp(2*R))/(lam_c * lam**(1.+beta1)))
        kbar_lam_approx = term1 * (term2 - term3) + term4*term5

    elif lam > lam_c:
        term1 = n * A1 / (alpha1-1.)
        term2 = special.hyp2f1(1., (alpha1-1.)/(1.+beta1), (alpha1+beta1)/(1.+beta1), -(a*np.exp(2.*R))/lam)
        term3 = ((lam_c)**(1.-alpha1)) * special.hyp2f1(1., (alpha1-1.)/(1+beta1), (alpha1+beta1)/(1.+beta1), -(a*np.exp(2.*R))/(lam*(lam_c)**(1.+beta1)))
        term4 = (n * A2 * (lam_c)**(1.-alpha2)) / (alpha2 - 1.)
        kbar_lam_approx = term1 * (term2 - term3) + term4

    else:
        if verbose == 1:
            print "ERROR (get_kbar_lam_approx): Lambda parameter "+\
                  "has to be between 1 and infinity."
        kbar_lam_approx = None

    return kbar_lam_approx
def posterior(x, n, p1, p2):
    """
    Calculates the posterior probability that the probability of developing
    severe side effects falls within a specific range given the data:

    x is the number of patients that develop severe side effects
    n is the total number of patients observed
    p1 is the lower bound on the range
    p2 is the upper bound on the range
    You can assume the prior beliefs of p follow a uniform distribution
    If n is not a positive integer, raise a ValueError with the message n must
    be a positive integer
    If x is not an integer that is greater than or equal to 0, raise a
    ValueError with the message x must be an integer that is greater than or
    equal to 0
    If x is greater than n, raise a ValueError with the message x cannot be
    greater than n
    If p1 or p2 are not floats within the range [0, 1], raise a ValueError with
    the message {p} must be a float in the range [0, 1] where {p} is the
    corresponding variable
    if p2 <= p1, raise a ValueError with the message p2 must be greater than p1
    The only import you are allowed to use is from scipy import special

    Returns: the posterior probability that p is within the range [p1, p2]
    given x and n
    """
    if not isinstance(n, int) or n <= 0:
        raise ValueError("n must be a positive integer")
    if not isinstance(x, (int, float)) or (x < 0):
        mg = "x must be an integer that is greater than or equal to 0"
        raise ValueError(mg)
    if x > n:
        raise ValueError("x cannot be greater than n")
    if not isinstance(p1, float) or p1 < 0 or p1 > 1:
        raise ValueError("p1 must be a float in the range [0, 1]")
    if not isinstance(p2, float) or p2 < 0 or p2 > 1:
        raise ValueError("p2 must be a float in the range [0, 1]")
    if p2 <= p1:
        raise ValueError("p2 must be greater than p1")

    num = (math.factorial(n+1))
    den = (math.factorial(x) * math.factorial(n - x))
    fct = num / den
    hp1 = special.hyp2f1(x+1, x-n, x+2, p1)
    hp2 = special.hyp2f1(x+1, x-n, x+2, p2)

    return fct * (((p2**(x+1))*hp2)-((p1**(x+1))*hp1))/(x+1)
Example #28
0
def olvers(a, b, c, x):
    # Olver's hypergeometric function
    # See https://dlmf.nist.gov/15.1
    # Note that hyp2f1 does not exist for c=0,-1,-2,...
    if np.abs(c % (-1)) < 0.1:
        print('Oops, too close to a pole!')
        # maybe build alternate definition here
    return hyp2f1(a, b, c, x) / gamma(c)
def posterior(x, n, p1, p2):
    """
        calculates the posterior probability that the probability of
        developing severe side effects falls within a specific range
        given the data

        - x is the number of patients that develop severe side effects
        - n is the total number of patients observed
        - p1 is the lower bound on the range
        - p2 is the upper bound on the range

        the prior beliefs of p follow a uniform distribution

        If n is not a positive integer, raise a ValueError
            with the message: n must be a positive integer
        If x is not an integer that is greater than or equal to 0,
            raise a ValueError with the message:
            x must be an integer that is greater than or equal to 0
        If x is greater than n, raise a ValueError with the message:
            x cannot be greater than n
        If p1 or p2 are not floats within the range [0, 1], raise a
            ValueError with the message:
            "{p} must be a float in the range [0, 1]"
            where {p} is the corresponding variable
        if p2 <= p1, raise a ValueError with the message:
            "p2 must be greater than p1"
    """
    if not isinstance(n, int) or n < 1:
        raise ValueError("n must be a positive integer")
    if type(x) != int or x < 0:
        mg = "x must be an integer that is greater than or equal to 0"
        raise ValueError(mg)
    if x > n:
        raise ValueError("x cannot be greater than n")
    if not isinstance(p1, float) or p1 < 0 or p1 > 1:
        raise ValueError("p1 must be a float in the range [0, 1]")
    if not isinstance(p2, float) or p2 < 0 or p2 > 1:
        raise ValueError("p2 must be a float in the range [0, 1]")
    if p2 <= p1:
        raise ValueError("p2 must be greater than p1")
    y = n - x
    f = math.factorial(n + 1) / (math.factorial(x) * math.factorial(y))
    h_1 = special.hyp2f1(x + 1, x - n, x + 2, p1)
    h_2 = special.hyp2f1(x + 1, x - n, x + 2, p2)
    posterior = f * (((p2**(x + 1)) * h2) - ((p1**(x + 1)) * h1)) / (x + 1)
    return posterior
Example #30
0
    def log_a0(r, alpha, s, beta, freq, rec, age):

        # check if alpha >= beta for format of A0 is slightly from when beta >= alpha
        max_ab, min_ab, b = (alpha, beta, s+1.) if alpha > beta else (beta, alpha, r + freq)
        ai = r + s + freq
        ci = ai + 1.
        zt = (max_ab - min_ab) / (max_ab + rec)
        zT = (max_ab - min_ab) / (max_ab + age)
        # F(a,b,c,z) is Gaussian hypergeometric function
        ft, fT = hyp2f1(ai, b, ci, zt), hyp2f1(ai, b, ci, zT)
        sign = ones(len(freq))
        # result = log(ft * (max_ab + age) ** ai -fT * (max_ab + rec) ** ai) - ai * log((max_ab + rec)*(max_ab + age))
        # logsumexp function is used for calculating the log ratio of A0.
        # why use logsumexp: when computing with very small numbers, it is very common to keep the numbers in logspace.
        # Most of the time, you only want to add up numbers in an array which could be done using log(sum(exp(a)))
        result = logsumexp([log(ft) + ai * log(max_ab + age), log(fT) + ai * log(max_ab + rec)], axis=0, b=[sign, -sign]) - ai * log((max_ab + rec) * (max_ab + age))
        return result
Example #31
0
def g2(x, a, T):
    """
    Kernel applicable to fSABR process
    """
    H = a + 0.5
    cH = np.sqrt(2 * H * math.gamma(3 / 2 - H) /
                 (math.gamma(2 - 2 * H) * math.gamma(H + 1 / 2)))
    return cH * (x**a) * hyp2f1(H - 0.5, 0.5 - H, H + 0.5, -x / (T - x))
Example #32
0
 def _mass_integral(self, x, slope=8):
     """
     Returns the analitic result of the integral appearing in mass expression
     :param slope: exponent entering the profile
     :return: integral result
     """
     hypF = np.real(hyp2f1(3. / 2, slope, 5. / 2, -x**2))
     return 1. / 3 * x**3 * hypF
Example #33
0
    def test_unital_argument(self, hyp2f1_test_case):
        """Tests for case z = 1, c - a - b > 0.

        Expected answers computed using mpmath.
        """
        a, b, c, z, expected, rtol = hyp2f1_test_case
        assert z == 1 and c - a - b > 0  # Tests the test
        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
def qli(l, i, alpha, beta):
    """Return the scalar (q_\phi^{l})_{i}."""
    if i % 2 == 0:
        return B(alpha, l + beta - i / 2) * hyp2f1(
            -i / 2, alpha, l + alpha + beta - i / 2, -1
        )
    else:
        return 0.0
Example #35
0
 def _psi(self,m):
     """\psi(m) = -\int_m^\infty d m^2 \rho(m^2)"""
     if self.twominusalpha == 0.:
         return -2.*self.a**2*(self.a/m)**self.betaminusalpha\
                   /self.betaminusalpha\
             *special.hyp2f1(self.betaminusalpha,
                             self.betaminusalpha,
                             self.betaminusalpha+1,
                             -self.a/m)
     else:
         return -2.*self.a**2\
             *(self.psi_inf-(m/self.a)**self.twominusalpha\
                   /self.twominusalpha\
                   *special.hyp2f1(self.twominusalpha,
                                   self.betaminusalpha,
                                   self.threeminusalpha,
                                   -m/self.a))
 def deflect(self):
     xi =np.sqrt((self.image_x-self.centroid[0])**2+(self.image_y-self.centroid[1])**2)/self.a 
     alpha = 2*self.kappa_0*self.a/xi * (sp.beta((self.n_outer-3)/2.0,(3-self.gamma)/2.0) \
             - sp.beta((self.n_outer-3)/2.0, 3.0/2.0) * (1+xi**2)**((3-self.n_outer)/2.0)\
             * sp.hyp2f1((self.n_outer-3)/2.0,self.gamma/2.0,self.n_outer/2.0,1/(1+xi**2)))
             
     self.alpha_x = alpha*(self.image_x-self.centroid[0])/np.sqrt((self.image_x-self.centroid[0])**2+(self.image_y-self.centroid[1])**2)
     self.alpha_y = alpha*(self.image_y-self.centroid[1])/np.sqrt((self.image_x-self.centroid[0])**2+(self.image_y-self.centroid[1])**2)
 def _psi(self, m):
     """\psi(m) = -\int_m^\infty d m^2 \rho(m^2)"""
     if self.twominusalpha == 0.:
         return -2.*self.a**2*(self.a/m)**self.betaminusalpha\
                   /self.betaminusalpha\
             *special.hyp2f1(self.betaminusalpha,
                             self.betaminusalpha,
                             self.betaminusalpha+1,
                             -self.a/m)
     else:
         return -2.*self.a**2\
             *(self.psi_inf-(m/self.a)**self.twominusalpha\
                   /self.twominusalpha\
                   *special.hyp2f1(self.twominusalpha,
                                   self.betaminusalpha,
                                   self.threeminusalpha,
                                   -m/self.a))
Example #38
0
def corr_error_pdf(r, trueR, n):
    num_const = (n - 2) * fn.gamma(n - 1)
    num_rho = (1 - trueR ** 2) ** ((n - 1) / 2)
    num_r = (1 - r ** 2) ** ((n - 4) / 2)
    den_const = np.sqrt(2 * np.pi) * fn.gamma(n - 0.5)
    den_rhor = (1 - trueR * r) ** (n - 1.5)  # TODO prevent overflow here
    num_hyp = fn.hyp2f1(0.5, 0.5, (2 * n - 1) / 2, (trueR * r + 1) / 2)
    return (num_const * num_rho * num_r * num_hyp) / (den_const * den_rhor)
Example #39
0
 def cdf(n, z):
     d = math.pow(abs(z), 1 - n) * sp.gamma(n / 2) * sp.hyp2f1(
         (n - 1) / 2, n / 2,
         (n + 1) / 2, -1 / z**2) / (2 * math.sqrt(math.pi) * sp.gamma(
             (n + 1) / 2))
     if z > 0:
         return 1 - d
     return d
Example #40
0
    def test_special_case_z_near_minus_1(self, hyp2f1_test_case):
        """Tests for case z ~ -1, c ~ 1 + a - b

        Expected answers computed using mpmath.
        """
        a, b, c, z, expected, rtol = hyp2f1_test_case
        assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15
        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
def In(y,n,x0 = None):
	#defini par l'integrale entre 0 et +infini, donc pas de (-1)^n	
	if x0 is None:
		x = y 
		return   2.**(n/2.-2.)*gamma((1.+n)/2.)/(5.*sqrt(5.*num.pi))*( 
			 10.*(n+1.)*(5.+x**2.)**(-(3.+n)/2.)
			 - 32.*(5.+x**2.)**(-(1.+n)/2.)
			 + 155.*2.**(3.+n)*(1.+n)*(5.+4.*x**2.)**(-(3.+n)/2.)
			 + 2.**(6.+n)*(5.+4.*x**2.)**(-(1.+n)/2.)
			 - 150.*(1.+n)*x**(-(n+3.))*hyp2f1(1./2.,(3.+n)/2.,3./2.,-5./x**2.)
			 - 75.*(1.+n)*x**(-(n+3.))*hyp2f1(1./2.,(3.+n)/2.,3./2.,-5./(4.*x**2.))
			 + 50.*(1.+n)*(3.+n)*x**(-(n+5.))*hyp2f1(1./2.,(5.+n)/2.,3./2.,-5./x**2.)
			 + 25.*(1.+n)*(3.+n)*x**(-(n+5.))*hyp2f1(1./2.,(5.+n)/2.,3./2.,-5./(4.*x**2.)))
	else:
		x_tab = num.linspace(x0,3.*sqrt(n + 3.)/y,1000)
		F = x_tab**n*f(x_tab)*exp(-(x_tab*y)**2./2.)
		return integrate(x_tab,F)
Example #42
0
def cdf(r, params, Rm):
    a = params[2]
    b = params[3]
    g = params[4]

    # Normalisation constant
    x = -Rm**(1.0 / a)
    y = -r**(1.0 / a)
    z = (r / Rm)**(2.0 - g)
    u = a * (b - g)
    v = -a * (g - 2.0)
    w = 1.0 + v

    c = hyp2f1(u, v, w, x)
    d = hyp2f1(u, v, w, y)

    return z * np.abs(d) / np.abs(c)
Example #43
0
def singular_part(PP, run):
    """Computation of the Singular Part of the Self-Force
    PP : class instance
        contains all parameters
    run : int, default 0
        id to distinguish several runs"""

    # Schwarzschild Metric Function f at tbe Particle Location:
    f_p = 1 - 2 / PP.r_p

    # Computing rdot:
    q1 = PP.p_orbit / PP.r_p
    q3 = PP.p_orbit - 2 * q1
    q4 = np.sqrt((PP.p_orbit - 2)**2 - 4 * PP.e_orbit**2)
    q5 = q3 * (q1**2) / (q4 * PP.p_orbit)

    chi_dot = q5 * (np.sqrt(PP.p_orbit - 4 - 2 * q1)) / (PP.p_orbit)

    dr_p_dtau = (PP.Ep * PP.r_p**2 * PP.e_orbit * np.sin(PP.chi_p) * chi_dot /
                 (f_p * PP.p_orbit))

    # Computing other relevant quantities:
    qaux1 = 1 + PP.Lp**2 / PP.r_p**2
    qaux2 = qaux1**(1.5)
    alpha = PP.Lp**2 / (PP.r_p**2 + PP.Lp**2)

    # Computing the Value of some Hypergeometric Functions:
    ff_1d2 = special.hyp2f1(0.5, 0.5, 1, alpha)
    ff_m1d2 = special.hyp2f1(-0.5, 0.5, 1, alpha)

    # Computing Regularization Parameters, not dependent on ell:
    A_r_H = PP.Ep / (f_p * qaux1)
    A_r_I = -PP.Ep / (f_p * qaux1)

    B_r = ((dr_p_dtau**2 - 2 * PP.Ep**2) * ff_1d2 +
           (dr_p_dtau**2 + PP.Ep**2) * ff_m1d2) / (2 * f_p * qaux2)

    # Computing Singular Part of the Self-Force (only the radial component at the moment):
    for ll in range(PP.ell_max + 1):
        PP.SF_S_r_l_H[ll] = PP.charge * (
            (ll + 0.5) * A_r_H + B_r) / (PP.r_p**2)
        PP.SF_S_r_l_I[ll] = PP.charge * (
            (ll + 0.5) * A_r_I + B_r) / (PP.r_p**2)

    logging.info("FRED RUN %d: Singular Part of the Self-Force Computed", run)
Example #44
0
def sbpl(engs, params, flux):
	IdxLow = float(params[0]) # low-energy index, aka lambda_1 or alpha
	IdxHig = float(params[1]) # high-energy index, aka lambda_2 or beta
	ebk = float(params[2]) # Ebreak, break energy
	delta = 0.3 # breakscale energy in keV. Uncomment the next line to use as a fit parameter.
	#delta = float(params[3])
	for i in range(len(engs)-1):
		delta = delta
		a = (IdxHig - IdxLow)/2.
		b = (IdxLow + IdxHig)/2.
		# LOG AND LOG10 CONSTANTS TO SIMPLIFY THE FUNCTION
		c1 = 4.60517 # log(100)
		c2 = 0.868589 # 2*(1./log(10)) see also logarithmic properties of log((1+n)/(1-n))
		c3 = 2.30259  # log(10)
		c4 = 0.434294 # 1./log(10)
		c5 = 1.59603 # log(2)*log(10) = log(2)+log(10)
		c6 = 1.15129 # log(10)/2.
		# changed the following to simplify, see orig function commented out below:
		# delta*(-c6*a-c6*b-c6)   to   -c6*delta*(a+b+1.)
		# (a+b+1.)   to   (IdxHig + 1.)
		
		multiplier = ( (1./(IdxHig+1.)) * -exp(-c1*b) * (cosh(c5*a*delta)-sinh(c5*a*delta)))
		
		lowIntegral = (
			engs[i]**(b+1)
			* ( ((engs[i]/ebk)**(-c2/delta) +1.)**(-c3*a*delta))
			* ((((engs[i]/ebk)**(-c4/delta)) + ((engs[i]/ebk)**(c4/delta)))**(c3*a*delta))
			* float(hyp2f1(-c3*a*delta, -c6*delta*(IdxHig+1.), -c6*delta*(IdxHig+1.)+1., -(engs[i]/ebk)**(-c2/delta)))
			* (cosh((c4 * log(engs[i]/ebk))/delta)**(-c3*a*delta))
			* (((1./cosh((c4*(log(1/ebk)+c1))/delta)) * cosh((c4*log(engs[i]/ebk))/delta))**(c3*a*delta))
			)


		highIntegral = (
			engs[i+1]**(b+1)
			* ( ((engs[i+1]/ebk)**(-c2/delta) +1.)**(-c3*a*delta))
			* ((((engs[i+1]/ebk)**(-c4/delta)) + ((engs[i+1]/ebk)**(c4/delta)))**(c3*a*delta))
			* float(hyp2f1(-c3*a*delta, -c6*delta*(IdxHig+1.), -c6*delta*(IdxHig+1.)+1., -(engs[i+1]/ebk)**(-c2/delta)))
			* (cosh((c4 * log(engs[i+1]/ebk))/delta)**(-c3*a*delta))
			* (((1./cosh((c4*(log(1/ebk)+c1))/delta)) * cosh((c4*log(engs[i+1]/ebk))/delta))**(c3*a*delta))
			)


		val = multiplier * (lowIntegral - highIntegral)
		flux[i] = val
 def freq_future_k_days(self, freq, rec, age, k):
     # predict transactions will happen in next k days
     r, alpha, a, b = self.pars
     freq, rec, age = self.check_inputs(freq, rec, age)
     a1 = (a+b+freq-1.)/(a-1.)
     a2 = 1. - power((alpha+age)/(alpha+age+k), r+freq) * hyp2f1(r+freq, b+freq, a+b+freq-1, k/(alpha+age+k))
     a3 = 1. + a/(b+freq-1) * power((alpha+age)/(alpha+rec), r+freq)
     future_freq = a1 * a2 / a3
     return future_freq
Example #46
0
 def laplace_b1_logistic(s):
     location = b1
     scale = 0.06240118068052774
     laplace_b1 = np.exp(location / scale) * (
         1 / (1 + np.exp(location / scale)) -
         s * scale * gamma(1 + s * scale) *
         hyp2f1(1, 1 + s * scale, 2 + s * scale,
                -np.exp(location / scale)) / gamma(2 + s * scale))
     return laplace_b1
Example #47
0
def conditionalExpectation(t, x, tx, T, r, alpha, a, b):
    E = (a + b + x - 1) / (a - 1)

    E *= 1 - (( (alpha + T) / (alpha + T + t) ) ** (r + x)) * special.hyp2f1(r + x, b + x, a + b + x - 1, t / (alpha + T + t))

    if x > 0:
        E /= 1 + (a / (b + x - 1)) * (((alpha + T) / (alpha + tx))**(r + x))

    return E
Example #48
0
 def laplace_bp_pdf_logistic_performance_union(s):
     scale = 0.47738487306528626
     location = bp
     laplace_bp = np.exp(location / scale) * (
         1 / (1 + np.exp(location / scale)) -
         s * scale * gamma(1 + s * scale) *
         hyp2f1(1, 1 + s * scale, 2 + s * scale,
                -np.exp(location / scale)) / gamma(2 + s * scale))
     return laplace_bp
Example #49
0
 def laplace_bp_pdf_logistic(s):
     location = bp
     scale = 0.2980952087304305
     laplace_bp = np.exp(location / scale) * (
         1 / (1 + np.exp(location / scale)) -
         s * scale * gamma(1 + s * scale) *
         hyp2f1(1, 1 + s * scale, 2 + s * scale,
                -np.exp(location / scale)) / gamma(2 + s * scale))
     return laplace_bp
Example #50
0
def genphi(x, alpha = 1, beta = 3, gamma = 1, Vmax = 21.0, rmax = 1.5):
        rs = rmax/2.16
        Ps = (Vmax/0.465)**2.0

        x0 = 10**-12
        p1a = ss.hyp2f1((3-gamma)/alpha, (beta-gamma)/alpha, (3+alpha-gamma)/alpha, -x0**alpha)
        p1b = ss.hyp2f1((3-gamma)/alpha, (beta-gamma)/alpha, (3+alpha-gamma)/alpha,  -x**alpha)
        I1  = ( x0**(3-gamma) * p1a - x**(3-gamma) * p1b ) / (x * (gamma - 3))

        p2  = ss.hyp2f1( (-2+beta)/alpha, (beta-gamma)/alpha, (-2+alpha+beta)/alpha, -x**(-alpha))
        I2  = x**(2-beta) * p2 / (beta -2)
        ans1 = Ps * ( 1 - (I1+I2) )

        #to calculate the factor that gives the same mass within 300pc
        #factor = rhos_correct(.3, alpha, beta, gamma, Vmax, rmax)

        #ans2 = Ps * ( 1 - (np.log(1+x))/x )
        return ans1 #* factor
Example #51
0
	def GrowthFunction(self,a):
		"""
		a is the scale factor
		"""
		a=np.array(a)+1e-15
		D=np.ones(np.size(a))
		H=self.H_0*(self.Omega_matter*(a**(-3))+self.Omega_lambda)**(1/2.)
		D=(H/self.H_0)*a**(5/2.)/np.sqrt(self.Omega_matter)*special.hyp2f1(5/6.,3/2.,11/6.,-a**3*self.Omega_lambda/self.Omega_matter)
		return D
Example #52
0
def cdf(r,params,Rm):
    rc = params[2]
    a  = params[3]
    b  = params[4]
    g  = params[5]

    # Normalisation constant
    x = - ((rc/Rm)**(-1.0/a))
    y = - ((r/rc)**(1.0/a))
    z = (r/Rm)**(2.0-g)
    u =  a*(b-g)
    v = -a*(g-2.0)
    w = 1.0 + v

    c = hyp2f1(u,v,w,x)
    d = hyp2f1(u,v,w,y)

    return z*d.real/c.real
Example #53
0
def trans_0015(a,b,c,z):
    """ http://functions.wolfram.com/HypergeometricFunctions/Hypergeometric2F1/17/02/09/0015/"""
    # print c-a,b,b-a+1,1/(1-z)
    # print mph2f1(c-a,b,b-a+1,1/(1-z)), hyp2f1(c-a,b,b-a+1,1/(1-z))
    # print mph2f1(b-c+1,a-c+1,2-c,z), hyp2f1(b-c+1,a-c+1,2-c,z)
    # print mph2f1(b-c+1,a-c+1,2-c,z), hyp2f1(b-c+1,a-c+1,2-c,z)
    _ = gammaln(1-a)+gammaln(b-c+1)
    return (np.exp(_-gammaln(b-a+1)-gammaln(1-c)-b*np.log(1-z))*hyp2f1(c-a,b,b-a+1,1/(1-z))+
                np.exp(_+gammaln(c)-gammaln(b)-gammaln(2-c)-gammaln(c-a)+(1-c)*np.log(-z))*hyp2f1(b-c+1,a-c+1,2-c,z))
Example #54
0
    def test_region4(self, hyp2f1_test_case):
        """0.9 <= |z| <= 1 and |1 - z| >= 1.

        This region is unhandled by of the standard transformations and
        needs special care.
        """
        a, b, c, z, expected, rtol = hyp2f1_test_case
        assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 1  # Tests the test
        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
Example #55
0
def trans_15_3_9(a,b,c,z):
    # print mph2f1(a,a-c+1,a+b-c+1,1-1/z), hyp2f1(a,a-c+1,a+b-c+1,1-1/z)
    # print mph2f1(c-a,1-a,c-a-b+1,1-1/z), hyp2f1(c-a,1-a,c-a-b+1,1-1/z)
    # print gammaln(c-b-a)
    # return (np.exp(-a * np.log(z)+gammaln(c)+gammaln(c-b-a)-gammaln(c-b)-gammaln(c-a))*hyp2f1(a,a-c+1,a+b-c+1,1-1/z)+
    #             np.float_power(z,a-c)*np.exp((c-a-b) * np.log(1-z)+gammaln(c)+gammaln(a+b-c)-gammaln(a)-gammaln(b))*hyp2f1(c-a,1-a,c-a-b+1,1-1/z))
    # print pochln2(c-b,-a)
    # print a-c+1, a+b-c+1
    return z**(-a)*np.exp(gammaln(c)+pochln2(c-b,-a)-gammaln(c-a))*hyp2f1(a,a-c+1,a+b-c+1,1-1/z)
Example #56
0
def doublePL_Lintegral(x,a,b):
    '''
    Indefinite integral of a double power law function 
    :math:`f(x,a,b) = (x^a + x^b)^{-1}`.
    '''
    return (b*x**(1-a) / ((a-1)*(a-b)) - 
             x**(1-a)*((a-b)* 
              hyp2f1(1.,(a-1)/(a-b),(a-1)/(a-b)+1,-x**(b-a)) + b) / 
               ((a-1)*(a-b)))
Example #57
0
    def _log_A_0(params, freq, recency, age):

        r, alpha, s, beta = params

        min_of_alpha_beta, max_of_alpha_beta, t = (alpha, beta, r + freq) if alpha < beta else (beta, alpha, s + 1)
        abs_alpha_beta = max_of_alpha_beta - min_of_alpha_beta

        rsf = r + s + freq
        p_1, q_1 = special.hyp2f1(rsf, t, rsf + 1., abs_alpha_beta / (max_of_alpha_beta + recency)), (max_of_alpha_beta + recency)
        p_2, q_2 = special.hyp2f1(rsf, t, rsf + 1., abs_alpha_beta / (max_of_alpha_beta + age)), (max_of_alpha_beta + age)

        try:
            size = len(freq)
            sign = np.ones(size)
        except TypeError:
            sign = 1

        return misc.logsumexp([log(p_1) + rsf * log(q_2), log(p_2) + rsf * log(q_1)], axis=0, b=[sign, -sign]) \
                            - rsf * log(q_1 * q_2)
Example #58
0
def comoving_distance(z):
    """
    line-of-sight comoving distance to a source at redshift z
    units will be the same as D_H, defined above.

    if O_K==0, this will compute the result analytically, using
    hypergeometric functions.

    if O_K!=0, this will compute the result using numerical integration
    of the function 1/H(z)
    """
    if O_K_is_zero:
        return D_H * 2. / numpy.sqrt(O_M) * \
               ( hyp2f1(1./6,1./2,7./6,-O_L/O_M) -\
                 hyp2f1(1./6,1./2,7./6,
                        -O_L/O_M/(1.+z)**3  )/numpy.sqrt(1.+z) )
    else:
        I,err = integrate.quad(H_inv,0,z)
        return D_H * I
Example #59
0
def uLinkage(sigma, mu, V):
    if V < EPS:
        return u0(sigma, mu)
    ret = mu
    if sigma > EPS:
        val = hyp2f1(1.0, V / sigma, 1.0 + V / sigma, 1.0 - u0(sigma, mu) / mu)
        ret = u0(sigma, mu) * val;
    elif sigma < -EPS:
        ret = mu / (math.fabs(sigma) + V) * (u0(sigma, mu) / mu * math.fabs(sigma) + V);
    return ret;
Example #60
0
def rhos_correct(auxr = .3, alpha = 1, beta = 3, gamma = 1, Vmax = 21.0, rmax=1.5):
        rs = rmax/2.16
        Ps = (Vmax/0.465)**2.0

        x0 = 10**-12
        p1a = ss.hyp2f1((3-gamma)/alpha, (beta-gamma)/alpha, (3+alpha-gamma)/alpha, -x0**alpha)

        #to calculate the factor that gives the same mass within 300pc
        auxx = auxr/rs
        alpha0, beta0, gamma0 = [1,3,1]
        p1_a = ss.hyp2f1((3-gamma0)/alpha0, (beta0-gamma0)/alpha0, (3+alpha0-gamma0)/alpha0, -x0**alpha0)
        p1_b = ss.hyp2f1((3-gamma0)/alpha0,(beta0-gamma0)/alpha0,(3+alpha0-gamma0)/alpha0, -auxx**alpha0)
        auxmass0 = ( x0**(3-gamma0) * p1_a - auxx**(3-gamma0) * p1_b ) / ((gamma0 - 3))

        p1_b2 = ss.hyp2f1((3-gamma)/alpha,(beta-gamma)/alpha,(3+alpha-gamma)/alpha, -auxx**alpha)
        auxmass  = ( x0**(3-gamma) * p1a - auxx**(3-gamma) * p1_b2 ) / ((gamma - 3))
        factor = auxmass0/auxmass

        return factor