예제 #1
0
def pearson4cdf(X, m, nu, a, _lambda, mu, sigma):
    # pearson4pdf
    #   p = pearson4pdf(X,m,nu,a,lambda)
    #
    #   Returns the pearson type IV probability density function with
    #   parameters m, nu, a and lambda at the values of X.
    #
    #   Example
    #
    #   See also
    #       pearson4pdf betapdf normpdf
    #       pearspdf pearsrnd
    #
    Xx = (X - _lambda) / a
    
    if Xx < -sqrt(3):    
        p1 = fx(X, m, nu, a, _lambda) * a / (2 * m - 1) * (1j - Xx) * hyp2f1(1, m + nu / 2 * 1j, 2 * m, 2 / (1 - 1j * Xx))    
        p = float(p1.real)   
    elif Xx > sqrt(3):    
        p1 = 1 - fx(-X, m, -nu, a, -_lambda) * a / (2 * m - 1) * (1j + Xx) * hyp2f1(1, m - nu / 2 * 1j, 2 * m, 2 / (1 + 1j * Xx))  
        p = float(p1.real)    
    elif Xx < 0 and Xx > -sqrt(3) and abs(nu) < (4 - 2 * sqrt(3)) * m:    
        p1 = norm.cdf(X, mu, sigma)    
        p = float(p1.real)   
    elif Xx < 0 and Xx > -sqrt(3) and abs(nu) > (4 - 2 * sqrt(3)) * m:    
        p1 = (1 - exp(-(nu + 1j * 2 * m) * pi)) ** (-1) - (1j * a * fx(X, m, nu, a, _lambda)) / (1j * nu - 2 * m + 2) * (1 + Xx ** 2) * hyp2f1(1, 2 - 2 * m, 2 - m + 1j * nu / 2, (1 + 1j * Xx) / 2)    
        p = float(p1.real)   
    elif Xx > 0 and Xx < sqrt(3) and abs(nu) < (4 - 2 * sqrt(3)) * m:    
        p1 = norm.cdf(X, mu, sigma)    
        p = float(p1.real)  
    else:     
        p1 = 1 - (1 - exp(-(-nu + 1j * 2 * m) * pi)) ** (-1) + (1j * a * fx(-X, m, -nu, a, -_lambda)) / (1j * (-nu) - 2 * m + 2) * (1 + (-Xx) ** 2) * hyp2f1(1,2-2*m,2-m-1j*nu/2,(1-1j*Xx)/2)    
        p = float(p1.real)
    
    return p
예제 #2
0
def e_ratio(a, b, e, x):
    # Get S
    bt2 = mp.beta(a, b - 1.0)  # Beta function
    bix = mp.betainc(a, b + 1.0, 0.0, e)  # Incomplete Beta function
    hf = mp.hyp2f1(1.0, a, a + b - 1.0,
                   -1.0)  # 2F1, Gauss' hypergeometric function
    hfre = mp.re(hf)
    Sval = bix - x * bt2 * hfre
    # Get U
    c1 = mp.mpc(1.0 + a)
    c2 = mp.mpc(-b)
    c3 = mp.mpc(1.0)
    c4 = mp.mpc(2.0 + a)
    Uval = mp.appellf1(c1, c2, c3, c4, e, -e)
    Ure = mp.re(Uval)
    # Get P & Q
    Pval = mp.hyp2f1(a + 1.0, 1.0 - b, a + 2.0,
                     e)  # 2F1, Gauss' hypergeometric function
    Pre = mp.re(Pval)
    Qval = mp.hyp2f1(a + 1.0, 2.0 - b, a + 2.0,
                     e)  # 2F1, Gauss' hypergeometric function
    Qre = mp.re(Qval)
    # Get T
    Tval = ((e**(1.0 + a)) / (1.0 + a)) * (3.0 * Pre + 2.0 * Qre - Ure)
    Tval = Tval + 4.0 * Sval
    # Get Rval (ratio)
    Rval = 0.25 * (1.0 - e * e) * (
        (1.0 - e)**(1.0 - b)) * (e**(1.0 - a)) * Tval
    return Rval
예제 #3
0
def e_ratio(a,b,e,x):
  # Get S
  bt2 = mp.beta(a,b-1.0)             # Beta function
  bix = mp.betainc(a,b+1.0,0.0,e)    # Incomplete Beta function
  hf = mp.hyp2f1(1.0,a,a+b-1.0,-1.0) # 2F1, Gauss' hypergeometric function
  hfre = mp.re(hf)
  Sval = bix - x*bt2*hfre
  # Get U
  c1 = mp.mpc(1.0 + a)
  c2 = mp.mpc(-b)
  c3 = mp.mpc(1.0)
  c4 = mp.mpc(2.0 + a)
  Uval = mp.appellf1(c1,c2,c3,c4,e,-e)
  Ure = mp.re(Uval)
  # Get P & Q
  Pval = mp.hyp2f1(a+1.0,1.0-b,a+2.0,e) # 2F1, Gauss' hypergeometric function
  Pre = mp.re(Pval)
  Qval = mp.hyp2f1(a+1.0,2.0-b,a+2.0,e) # 2F1, Gauss' hypergeometric function
  Qre = mp.re(Qval)
  # Get T
  Tval = ( (e**(1.0+a)) / (1.0+a) )*( 3.0*Pre + 2.0*Qre - Ure )
  Tval = Tval + 4.0*Sval
  # Get Rval (ratio)
  Rval = 0.25*(1.0-e*e)*( (1.0-e)**(1.0-b) )*( e**(1.0-a) )*Tval
  return Rval
예제 #4
0
def log_prob_m_bursty_rep(max_m, k_burst, mean_burst, kR_on, kR_off):
    """
    log_prob_m_bursty_rep(max_m, k_burst, mean_burst, kR_on, kR_off)

    Computes log prob of observing m mRNA for all m s.t. 0 <= m <= m_max,
    given model parameters. The computation uses eq 76 in SI
    of Shahrezai & Swain 2008. The implementation uses mpmath to compute
    2F1 for max_m and max_m+1, then uses the minimal solution of the
    (+00) recursion relation run backwards to efficiently compute the rest.
    """

    # first compute alpha, beta, gamma, the parameters in the 2F1 gen fcn
    # recall the gen fcn is 2F1(alpha, beta, gamma, mean_burst*(z-1))
    rate_sum = k_burst + kR_off + kR_on
    sqrt_discrim = np.sqrt((rate_sum)**2 - 4 * k_burst * kR_off)
    alpha = (rate_sum + sqrt_discrim) / 2.0
    beta = (rate_sum - sqrt_discrim) / 2.0
    gamma = kR_on + kR_off

    # now compute a, b, c, z, the parameters in the recursion relation,
    # in terms of alpha, beta, gamma, & mean_burst
    a = alpha
    b = gamma - beta
    c = 1.0 + alpha - beta
    z = (1.0 + mean_burst)**(-1)

    # next set up recursive calculation of 2F1
    m = np.arange(0, max_m + 1)
    # note 1+a-c is strictly > 0 so we needn't worry about signs in gammafcn
    lgamma_numer = gammaln(1 + a - c + m)
    lgamma_denom = gammaln(1 + a + b - c + m)
    twoFone = np.zeros_like(np.asfarray(m))
    # initialize recursion with starting values...
    twoFone[-1] = hyp2f1(a + m[-1], b, 1 + a + b - c + m[-1], 1 - z)
    twoFone[-2] = hyp2f1(a + m[-2], b, 1 + a + b - c + m[-2], 1 - z)
    # ...adjusted by gamma prefactors
    twoFone[-2:] *= np.exp(lgamma_numer[-2:] - lgamma_denom[-2:])
    # now run the recursion backwards (i.e., decreasing n)
    # python indexing rules make the indexing here horribly confusing,
    # haven't yet figured out a better/more transparent way
    for i, k in enumerate(np.arange(m[-1] - 1, m[0], -1)):
        apk = a + k
        prefac_k = 2 * apk - c + (b - apk) * z
        prefac_kplus1 = apk * (z - 1)
        denom = c - apk
        twoFone[-(3 + i)] = -(prefac_k * twoFone[-(2 + i)] +
                              prefac_kplus1 * twoFone[-(1 + i)]) / denom
    # when recursion is finished, cancel off prefactor of gammas
    logtwoFone = np.log(twoFone) + lgamma_denom - lgamma_numer

    # now compute prefactors in P(m), combine, done
    gamma_prefac = (gammaln(alpha + m) - gammaln(alpha) + gammaln(beta + m) -
                    gammaln(beta) - gammaln(gamma + m) + gammaln(gamma) -
                    gammaln(1 + m))
    bern_p = mean_burst / (1 + mean_burst)
    burst_prefac = m * np.log(bern_p) + alpha * np.log(1 - bern_p)
    return gamma_prefac + burst_prefac + logtwoFone
예제 #5
0
파일: m_critico.py 프로젝트: cimarieta/usp
def viavel(beta, c, alpha, m, n):
    if c == 0.:
        return 2*alpha*beta/(2*n*m+1)
    if c == 1.:
        return -1.
    if m == 0.:
        return 1
    k = 2*n*m-1
    q = 2*alpha*beta
    return (1-c)*float(hyp2f1(1,1,k+2,c))-q*(-k-2+(k+1)*float(hyp2f1(1,1,k+3,c)))/(k+2) - 1 
예제 #6
0
def Ptrue(Qp, I, R, S, Q, b, replacement=True):
    """
    Returns the probability of testing with replacement,
    in which tested individuals can be retested on the same day.
    
    Args
    ----
    Qp (int): number of positive tests.
    I (int): number of infecteds.
    R (int): number of recovered.
    S (int): number of suceptibles.
    Q (int): number of tests.
    b (float): biased-testing factor.
    replacement (boolean): testing with/without replacement.
    
    """

    if replacement:
        f0 = (I + R) / (S + I + R)
        Ptrue = binomial(Q, Qp) * power(f0 * exp(b), Qp) * power(
            1 - f0, Q - Qp)
        Ptrue /= power(1 + (exp(b) - 1) * f0, Q)

    else:
        product = [(I + R - k) / (S - Q + Qp - k) for k in range(Qp)]

        Ptrue = binomial(Q, Qp) * fprod(product) * exp(Qp*b) * \
                1/hyp2f1( -I - R, -Q, S - Q + 1, exp(b) )

    return Ptrue
예제 #7
0
def test_hyp2f1_strange_points():
    pts = [(2, -1, -1, 0.7), (2, -2, -2, 0.7)]
    kw = dict(eliminate=True)
    dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #8
0
def G(eta_i, eta_f, k_i, k_f, l):
    """something dumb helper"""
    temp1 = abs((k_f - k_i) / (k_f + k_i))**(1j * eta_i + 1j * eta_f)
    temp2 = hyp2f1(l + 1 - 1j * eta_f, l + 1 - 1j * eta_i, 2. * l + 2,
                   -4. * k_i * k_f / (k_i - k_f)**2)

    return (temp1 * temp2).real
예제 #9
0
def hyp_2F1(a, b, c, z):
    """
    http://docs.sympy.org/0.7.1/modules/mpmath/functions/hypergeometric.html
    """
    import mpmath as mp

    return mp.hyp2f1(a, b, c, z)
예제 #10
0
 def B_01(Non, Noff, alpha):
     Ntot = Non + Noff
     gam = (1 + 2 * Noff) * power(alpha, (0.5 + Ntot)) * gamma(0.5 + Ntot)
     delta = ((2 * power((1 + alpha), Ntot)) * gamma(1 + Ntot) *
              hyp2f1(0.5 + Noff, 1 + Ntot, 1.5 + Noff, (-1 / alpha)))
     c1_c2 = sqrt(pi) / (2 * atan(1 / sqrt(alpha)))
     return gam / (c1_c2 * delta)
예제 #11
0
파일: rld.py 프로젝트: bio-phys/hplusminus
def SI_number_of_positive_signs(N, nPlus, nc, ncPlus):
    """
    Parameters
    ----------
    N: int
        Total number of signs.
    nPlus: int
        Number of positive signs.
    nc: int
        Number of runs.
    ncPlus: int
        Number of runs with positive signs.
    Returns
    -------
    float
        Neg. log-probability observing nPlus signs with +1, given N signs, nc runs, and ncPlus runs with signs +1.
    """

    ncMinus = nc - ncPlus
    nMinus = N - nPlus
    if nc > 1:
        if ncMinus > 1:
            h2f1 = -mpmath.log(mpmath.hyp2f1(ncPlus, ncPlus + ncMinus - N, 1 + ncPlus - N, 1))
            norm = -log_binomial(N - 1 - ncPlus, ncMinus - 1) + h2f1
        else:
            norm = -log_binomial(N - 1, ncPlus - 1) - np.log((N - ncPlus) / float(ncPlus))

        res = -log_binomial(nPlus - 1, ncPlus - 1) - log_binomial(nMinus - 1, ncMinus - 1) - norm
        return res
    elif nc == 1:
        return 0.
    else:
        return 0.
예제 #12
0
def test_hyp2f1_real_some_points():
    pts = [
        (1,2,3,0),
        (1./3, 2./3, 5./6, 27./32),
        (1./4, 1./2, 3./4, 80./81),
        (2,-2,-3,3),
        (2,-3,-2,3),
        (2,-1.5,-1.5,3),
        (1,2,3,0),
        (0.7235, -1, -5, 0.3),
        (0.25, 1./3, 2, 0.999),
        (0.25, 1./3, 2, -1),
        (2,3,5,0.99),
        (3./2,-0.5,3,0.99),
        (2,2.5,-3.25,0.999),
        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
        (-10,900,-10.5,0.99),
        (-10,900,10.5,0.99),
        (-1,2,1,1.0),
        (-1,2,1,-1.0),
        (-3,13,5,1.0),
        (-3,13,5,-1.0),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    olderr = np.seterr(invalid='ignore')
    try:
        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
    finally:
        np.seterr(**olderr)
예제 #13
0
def test_hyp2f1_real_some_points():
    pts = [
        (1, 2, 3, 0),
        (1. / 3, 2. / 3, 5. / 6, 27. / 32),
        (1. / 4, 1. / 2, 3. / 4, 80. / 81),
        (2, -2, -3, 3),
        (2, -3, -2, 3),
        (2, -1.5, -1.5, 3),
        (1, 2, 3, 0),
        (0.7235, -1, -5, 0.3),
        (0.25, 1. / 3, 2, 0.999),
        (0.25, 1. / 3, 2, -1),
        (2, 3, 5, 0.99),
        (3. / 2, -0.5, 3, 0.99),
        (2, 2.5, -3.25, 0.999),
        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
        (-10, 900, -10.5, 0.99),
        (-10, 900, 10.5, 0.99),
        (-1, 2, 1, 1.0),
        (-1, 2, 1, -1.0),
        (-3, 13, 5, 1.0),
        (-3, 13, 5, -1.0),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)), ) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #14
0
파일: kernels.py 프로젝트: iw381/mcfit
def Mellin_DoubleSphericalBesselJ(alpha, nu1, nu2):
    import mpmath
    from numpy import frompyfunc
    hyp2f1 = frompyfunc(lambda *a: complex(mpmath.hyp2f1(*a)), 4, 1)
    if 0 < alpha < 1:

        def MK(z):
            return pi * exp(log(2)*(z-3) + log(alpha)*nu2 + loggamma(0.5*(nu1+nu2+z))
                            - loggamma(0.5*(3+nu1-nu2-z)) - loggamma(1.5+nu2)) \
                    * hyp2f1(0.5*(-1-nu1+nu2+z), 0.5*(nu1+nu2+z), 1.5+nu2, alpha**2)
    elif alpha > 1:

        def MK(z):
            return pi * exp(log(2)*(z-3) + log(alpha)*(-nu1-z) + loggamma(0.5*(nu1+nu2+z))
                            - loggamma(0.5*(3-nu1+nu2-z)) - loggamma(1.5+nu1)) \
                    * hyp2f1(0.5*(-1+nu1-nu2+z), 0.5*(nu1+nu2+z), 1.5+nu1, alpha**-2)
    elif alpha == 1:

        def MK(z):
            return pi * exp(
                log(2) *
                (z - 3) + loggamma(2 - z) + loggamma(0.5 * (nu1 + nu2 + z)) -
                loggamma(0.5 * (3 + nu1 - nu2 - z)) -
                loggamma(0.5 *
                         (3 - nu1 + nu2 - z)) - loggamma(0.5 *
                                                         (4 + nu1 + nu2 - z)))
    else:
        raise ValueError
    return MK
예제 #15
0
def rho2(r, rho0, rc, gmma):
    '''
    verifying my integral for rho
    '''
    a = np.array([
        float(
            mp.hyp2f1(0.5, 0.5 / gmma, 1 + 0.5 / gmma, -(ri / rc)**(2 * gmma)))
        for ri in r
    ])
    b = -r**(2 * gmma) / (2 + 4 * gmma) * np.array([
        float(
            mp.hyp2f1(1.5, (2 * gmma + 1) /
                      (2 * gmma), 2 + 0.5 / gmma, -(ri / rc)**(2 * gmma)))
        for ri in r
    ]) * (2 * gmma / rc**(2 * gmma))

    return rho0 * (a + b)
예제 #16
0
def tauMinus(n1, n2, l):
    if l == 0:
        return 0.0
    tmp = 2**(2. * l) / factorial(2. * l - 1)
    tmp *= (gamma(n1 + l + 1) * gamma(n2 + l) / gamma(n1 - l) /
            gamma(n2 - l + 1))**0.5
    tmp *= (n1 * n2)**(l + 1)
    tmp /= (n1 + n2)**(n1 + n2)
    tmp *= (n1 - n2)**(n1 - 2 - l)
    tmp *= (n2 - n1)**(n2 - l)

    tmp2 = hyp2f1(l + 1 - n1, l - n2, 2 * l, -4. * n1 * n2 / (n1 - n2)**2)
    tmp2 -= ((n1 - n2) /
             (n1 + n2))**2 * hyp2f1(l - 1 - n1, l - n2, 2 * l, -4. * n1 * n2 /
                                    (n1 - n2)**2)

    return tmp * tmp2
예제 #17
0
def test_hyp2f1_strange_points():
    pts = [
        (2,-1,-1,3),
        (2,-2,-2,3),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
예제 #18
0
def test_hyp2f1_strange_points():
    pts = [
        (2, -1, -1, 3),
        (2, -2, -2, 3),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)), ) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #19
0
def zk(z, k):
    """
    modified dispersion function for Kappa distribution.
    (Mace and Hellberg, 1995)
    
    """
    i = mp.mpc(0, 1)
    coeff = i * (k + 0.5) * (k-0.5) / (mp.sqrt(k**3) * (k+1))
    return coeff * hyp2f1(1, 2*k+2, k+2, (1-z/(i * mp.sqrt(k)))/2)
예제 #20
0
def DeltaHypergeometric(x1, x2):
    """ Difference of squared hypergeometric functions evaluated at x1 and x2, respectively.

    @param x1 : First argument.
    @param x2 : Second argument.

    @return   : | F(-x1+1, -x2, 1, -4 x1 x2 /(x1-x2)^2) |^2 - | F(-x2+1, -x1, 1, -4 x1 x2 /(x1-x2)^2) |^2
    """

    # x variable:
    y = -4. * x1 * x2 / (x1 - x2)**2

    f1 = (hyp2f1(-x1 + 1, -x2, 1., y))**2
    f2 = (hyp2f1(-x2 + 1, -x1, 1., y))**2

    Delta = f1 - f2

    return Delta
예제 #21
0
def _student_t_cdf(df, t, dps=None):
    if dps is None:
        dps = mpmath.mp.dps
    with mpmath.workdps(dps):
        df, t = mpmath.mpf(df), mpmath.mpf(t)
        fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df)
        fac *= t*mpmath.gamma(0.5*(df + 1))
        fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df)
        return 0.5 + fac
예제 #22
0
def _student_t_cdf(df, t, dps=None):
    if dps is None:
        dps = mpmath.mp.dps
    with mpmath.workdps(dps):
        df, t = mpmath.mpf(df), mpmath.mpf(t)
        fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df)
        fac *= t*mpmath.gamma(0.5*(df + 1))
        fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df)
        return 0.5 + fac
예제 #23
0
def test_hyp2f1_strange_points():
    pts = [
        (2, -1, -1, 0.7),
        (2, -2, -2, 0.7),
    ]
    kw = dict(eliminate=True)
    dataset = [p + (float(mpmath.hyp2f1(*p, **kw)), ) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #24
0
 def test_hyp2f1_complex(self):
     # Scipy's hyp2f1 seems to have performance and accuracy problems
     assert_mpmath_equal(
         lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
         _exception_to_nan(
             lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
         [Arg(-1e2, 1e2),
          Arg(-1e2, 1e2),
          Arg(-1e2, 1e2),
          ComplexArg()],
         n=10)
예제 #25
0
def test_hyp2f1_real_some():
    dataset = []
    for a in [-10, -5, -1.8, 1.8, 5, 10]:
        for b in [-2.5, -1, 1, 7.4]:
            for c in [-9, -1.8, 5, 20.4]:
                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
                    try:
                        v = float(mpmath.hyp2f1(a, b, c, z))
                    except:
                        continue
                    dataset.append((a, b, c, z, v))
    dataset = np.array(dataset, dtype=np.float_)
    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
예제 #26
0
def test_hyp2f1_real_some():
    dataset = []
    for a in [-10, -5, -1.8, 1.8, 5, 10]:
        for b in [-2.5, -1, 1, 7.4]:
            for c in [-9, -1.8, 5, 20.4]:
                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
                    try:
                        v = float(mpmath.hyp2f1(a, b, c, z))
                    except:
                        continue
                    dataset.append((a, b, c, z, v))
    dataset = np.array(dataset, dtype=np.float_)
    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
예제 #27
0
def test_hyp2f1_some_points_2():
    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
    # was fixed in their SVN since then
    pts = [
        (112, 51./10, -9./10, -0.99999),
        ## Mpmath currently (0.13) fails also for these:
        #(10,-900,10.5,0.99),
        #(10,-900,-10.5,0.99),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
예제 #28
0
def test_hyp2f1_some_points_2():
    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
    # was fixed in their SVN since then
    pts = [(112, (51, 10), (-9, 10), -0.99999), (10, -900, 10.5, 0.99), (10, -900, -10.5, 0.99)]

    def fev(x):
        if isinstance(x, tuple):
            return float(x[0]) / x[1]
        else:
            return x

    dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #29
0
파일: t.py 프로젝트: WarrenWeckesser/mpsci
def sf(x, df):
    """
    Survival function of Student's t distribution.
    """
    if df <= 0:
        raise ValueError('df must be greater than 0')

    with mpmath.extradps(5):
        half = mpmath.mp.one/2
        x = mpmath.mpf(x)
        df = mpmath.mpf(df)
        h = (df + 1) / 2
        p1 = x * mpmath.gamma(h)
        p2 = mpmath.hyp2f1(half, h, 3*half, -x**2/df)
        return half - p1*p2/mpmath.sqrt(mpmath.pi*df)/mpmath.gamma(df/2)
예제 #30
0
def Mellin_DoubleSphericalBesselJ(alpha, l1, l2):
    import mpmath
    from numpy import frompyfunc
    hyp2f1 = frompyfunc(lambda *a: complex(mpmath.hyp2f1(*a)), 4, 1)
    if 0 < alpha <= 1:
        def UK(z):
            return pi * exp(log(2)*(z-3) + log(alpha)*l2 + loggamma(0.5*(l1+l2+z))
                            - loggamma(0.5*(3+l1-l2-z)) - loggamma(1.5+l2)) \
                    * hyp2f1(0.5*(-1-l1+l2+z), 0.5*(l1+l2+z), 1.5+l2, alpha**2)
    elif alpha > 1:
        def UK(z):
            return pi * exp(log(2)*(z-3) + log(alpha)*(-l1-z) + loggamma(0.5*(l1+l2+z))
                            - loggamma(0.5*(3-l1+l2-z)) - loggamma(1.5+l1)) \
                    * hyp2f1(0.5*(-1+l1-l2+z), 0.5*(l1+l2+z), 1.5+l1, alpha**-2)
    else:
        raise ValueError
    return UK
예제 #31
0
def hypergeometric(z):
    #u_3^((2))(x)	=	(-z)^(b-c)(1-z)^(c-a-b)_2F_1(1-b,c-b;a+1-b;z^(-1))
    #u_6^((4))(x)	=	z^(b-c)(1-z)^(c-a-b)_2F_1(c-b,1-b;c+1-a-b;1-z^(-1))
    #u_2^((3))(x)	=	z^(-a)_2F_1(a,a+1-c;a+b+1-c;1-z^(-1))
    #u_3(x)	=	z^(-a)_2F_1(a,a+1-c;a+1-b;z^(-1))
    #ii**(-a)*hyp2f1(a,1+a-c,a+1-b,ii**(-1))

    #u_4(x)	=	z^(-b)_2F_1(b+1-c,b;b+1-a;z^(-1))
    x = []
    for ii in z:
        x.append(((1 + sigma_m0 * ii) / (1 - sigma_m0)))
    #print(x)
    r_list = []
    for ii in x:
        r_list.append(hyp2f1(a, b, c, ii**(-1)))
        #print(ii**(b-c)*(1-ii)**(c-a-b))
    #print(x)
    return r_list
예제 #32
0
def fun1(t, ei, ef):
    kf = np.sqrt(2 * m * ef)
    lf = (z1 + 1) * z2 * aa * np.sqrt(m / 2 / ef)
    ki = np.sqrt(2 * m * ei)
    li = z1 * z2 * aa * np.sqrt(m / 2 / ei)
    x = 2 * (1 - t) / (ki / kf + kf / ki - 2 * t)
    a = 1 + li * 1j
    b = -lf * 1j
    c = 1
    res = mp.hyp2f1(a, b, c, x)
    #checkRes = (1-x)**(c-a-b) * mp.hyp2f1(c-a, c-b, c, x)
    #diff = np.sqrt((res.imag - checkRes.imag)**2 +
    #               (res.real - checkRes.real)**2)
    # if (diff > 1e-9):
    #    print("Error: " + str(diff))
    return (res.real * res.real + res.imag * res.imag) / (
        ki * ki + kf * kf - 2 * ki * kf * t) / (ki * ki + kf * kf -
                                                2 * ki * kf * t)
예제 #33
0
def sigma(n, rho):

    inner0 = n / 2 * mm.log(1 - rho**2)

    inner1 = mm.log(mm.hyp3f2(3 / 2, n / 2, n / 2, 1 / 2, n / 2 + 1, rho**2))

    inner2 = -mm.log(n)
    inner = mm.mp.e**(inner0 + inner1 + inner2)

    outer0 = n / 2 * np.log(1 - rho**2) + np.log(abs(rho))
    outer1 = 2 * sc.gammaln(n / 2 + 1 / 2)
    outer2 = mm.log(mm.hyp2f1(n / 2 + 1 / 2, n / 2 + 1 / 2, n / 2 + 1, rho**2))
    outer3 = -sc.gammaln(n / 2)
    outer4 = -sc.gammaln(n / 2 + 1)
    outer = outer0 + outer1 + outer2 + outer3 + outer4
    outer = 2 * outer

    return float(mm.sqrt(inner - mm.mp.e**(outer)))
예제 #34
0
def test_hyp2f1_real_some():
    dataset = []
    for a in [-10, -5, -1.8, 1.8, 5, 10]:
        for b in [-2.5, -1, 1, 7.4]:
            for c in [-9, -1.8, 5, 20.4]:
                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
                    try:
                        v = float(mpmath.hyp2f1(a, b, c, z))
                    except:
                        continue
                    dataset.append((a, b, c, z, v))
    dataset = np.array(dataset, dtype=np.float_)

    olderr = np.seterr(invalid='ignore')
    try:
        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9,
                 ignore_inf_sign=True).check()
    finally:
        np.seterr(**olderr)
예제 #35
0
def test_hyp2f1_some_points_2():
    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
    # was fixed in their SVN since then
    pts = [
        (112, (51, 10), (-9, 10), -0.99999),
        (10, -900, 10.5, 0.99),
        (10, -900, -10.5, 0.99),
    ]

    def fev(x):
        if isinstance(x, tuple):
            return float(x[0]) / x[1]
        else:
            return x

    dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)), ) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #36
0
def test_hyp2f1_real_some():
    dataset = []
    for a in [-10, -5, -1.8, 1.8, 5, 10]:
        for b in [-2.5, -1, 1, 7.4]:
            for c in [-9, -1.8, 5, 20.4]:
                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
                    try:
                        v = float(mpmath.hyp2f1(a, b, c, z))
                    except:
                        continue
                    dataset.append((a, b, c, z, v))
    dataset = np.array(dataset, dtype=np.float_)

    olderr = np.seterr(invalid='ignore')
    try:
        FuncData(sc.hyp2f1,
                 dataset, (0, 1, 2, 3),
                 4,
                 rtol=1e-9,
                 ignore_inf_sign=True).check()
    finally:
        np.seterr(**olderr)
예제 #37
0
def fun1(t):
    a = 1 + 2j
    b = 3j
    c = 3 + 2j
    x = 0.2
    rez = mp.hyp2f1(a, b, c, x)
    # print(rez)
    ef = send_ef
    ei = send_ei
    kki = math.sqrt(2*m*ei)
    kkf = math.sqrt(2*m*ef)
    #print(kki, kkf, t)
    x = 2*(1-t)/(ki(ei)/kf(ef)+kf(ef)/ki(ei)-2*t)
    # llf = (z1+1)*z2*aa*math.sqrt(m/2/ef)
    # lli = z1*z2*aa*math.sqrt(m/2/ei)
    a = 1 + 2j
    b = 3j
    c = 3 + 2j
    x = 0.2
    # print(rez)
    per = kki*kki+kkf*kkf
    return 1e-300*(rez.real*rez.real+rez.imag*rez.imag)/(per-2*kki*kkf*t)/(per-2*kki*kkf*t)
예제 #38
0
def test_hyp2f1_real_some_points():
    pts = [
        (1, 2, 3, 0),
        (1.0 / 3, 2.0 / 3, 5.0 / 6, 27.0 / 32),
        (1.0 / 4, 1.0 / 2, 3.0 / 4, 80.0 / 81),
        (2, -2, -3, 3),
        (2, -3, -2, 3),
        (2, -1.5, -1.5, 3),
        (1, 2, 3, 0),
        (0.7235, -1, -5, 0.3),
        (0.25, 1.0 / 3, 2, 0.999),
        (0.25, 1.0 / 3, 2, -1),
        (2, 3, 5, 0.99),
        (3.0 / 2, -0.5, 3, 0.99),
        (2, 2.5, -3.25, 0.999),
        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
        (-10, 900, -10.5, 0.99),
        (-10, 900, 10.5, 0.99),
    ]
    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
    dataset = np.array(dataset, dtype=np.float_)

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-10).check()
예제 #39
0
def mp_hyp2f1(a, b, c, z):
    """Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1.

    For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the
    branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch.
    Thus, to generate the right comparison values on the branch cut, we
    evaluate mpmath.hyp2f1 at x + 1e-15*j.

    The exception to this occurs when c-a=-m in which case both mpmath and
    scipy calculate the x + 0j branch on the branch cut. When this happens
    mpmath.hyp2f1 will be evaluated at the original z point.
    """
    on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15
    cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0
    cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0
    # Make sure imaginary part is *exactly* zero
    if on_branch_cut:
        z = z.real + 0.0j
    if on_branch_cut and not (cond1 or cond2):
        z_mpmath = z.real + 1.0e-15j
    else:
        z_mpmath = z
    return complex(mpmath.hyp2f1(a, b, c, z_mpmath))
예제 #40
0
def Perr(Qtildep, Q, Qp, FNR, FPR):
    """
    Returns observed error-prone probability distribution.
    
    Args
    ----
    Qtildep (int): number of positive tests.
    Qp (int): number of positive tests.
    Q (int): number of tests.
    FNR (float): false-negative fraction.
    FPR (float): false-positive fraction.
    
    """

    Qm = Q - Qp

    Perr = power(FNR, Qp) * power(1 - FPR, Qm - Qtildep ) * power(FPR, Qtildep) \
           * binomial( Qm, Qtildep ) * hyp2f1( -Qp, -Qtildep, Qm + 1 - Qtildep, \
           (FNR-1)*(FPR-1)/(FNR*FPR) )

    if isnan(Perr):
        Perr = 0

    return Perr
예제 #41
0
def test_hyp2f1_real_random():
    dataset = []

    npoints = 500
    dataset = np.zeros((npoints, 5), np.float_)

    np.random.seed(1234)
    dataset[:,0] = np.random.pareto(1.5, npoints)
    dataset[:,1] = np.random.pareto(1.5, npoints)
    dataset[:,2] = np.random.pareto(1.5, npoints)
    dataset[:,3] = 2*np.random.rand(npoints) - 1

    dataset[:,0] *= (-1)**np.random.randint(2, npoints)
    dataset[:,1] *= (-1)**np.random.randint(2, npoints)
    dataset[:,2] *= (-1)**np.random.randint(2, npoints)

    for ds in dataset:
        if mpmath.__version__ < '0.14':
            # mpmath < 0.14 fails for c too much smaller than a, b
            if abs(ds[:2]).max() > abs(ds[2]):
                ds[2] = abs(ds[:2]).max()
        ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))

    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9).check()
예제 #42
0
def test_hyp2f1_real_random():
    dataset = []

    npoints = 500
    dataset = np.zeros((npoints, 5), np.float_)

    np.random.seed(1234)
    dataset[:, 0] = np.random.pareto(1.5, npoints)
    dataset[:, 1] = np.random.pareto(1.5, npoints)
    dataset[:, 2] = np.random.pareto(1.5, npoints)
    dataset[:, 3] = 2 * np.random.rand(npoints) - 1

    dataset[:, 0] *= (-1)**np.random.randint(2, npoints)
    dataset[:, 1] *= (-1)**np.random.randint(2, npoints)
    dataset[:, 2] *= (-1)**np.random.randint(2, npoints)

    for ds in dataset:
        if mpmath.__version__ < '0.14':
            # mpmath < 0.14 fails for c too much smaller than a, b
            if abs(ds[:2]).max() > abs(ds[2]):
                ds[2] = abs(ds[:2]).max()
        ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))

    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
예제 #43
0
 def test_hyp2f1(self):
     assert_mpmath_equal(sc.hyp2f1,
                         _exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
                         [Arg(), Arg(), Arg(), Arg()])
예제 #44
0
def G(eta1, eta2, k1, k2, l):
    Gl = abs((k2 - k1) / (k2 + k1))**(1j * eta1 + 1j * eta2) * hyp2f1(
        l + 1 - 1j * eta2, l + 1 - 1j * eta1, 2. * l + 2, -4. * k1 * k2 /
        (k1 - k2)**2)

    return Gl.real
def z(ZZ):
    mpmath.mp.dps = 20
    return N.exp(-N.log(1728*ZZ) / 5) * mpmath.hyp2f1(31.0/60, 11.0/60, 6.0/5, 1.0/ZZ) /\
                                        mpmath.hyp2f1(19.0/60, -1.0/60, 4.0/5, 1.0/ZZ)
 def _mpmath_hyp2f1(self, a, b, c, z):
     result = []
     for a_, b_, c_, z_ in zip(a, b, c, z):
         result.append(np.float64(mpmath.hyp2f1(a_, b_, c_, z_)))
     return np.array(result)
예제 #47
0
 def test_hyp2f1_complex(self):
     # Scipy's hyp2f1 seems to have performance and accuracy problems
     assert_mpmath_equal(lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
                         _exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
                         [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()],
                         n=10)
예제 #48
0
as yet, since it tries to import the libraries from *this* folder, rather than
installation (which doesn't work because the fortran code isn't installed.)
"""
import inspect
import os

#LOCATION = "/".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split("/")[:-1])
import sys
#sys.path.insert(0, LOCATION)
import numpy as np
from halomod import ProjectedCF
from halomod.integrate_corr import projected_corr_gal
from astropy.units import Mpc
from mpmath import gamma,hyp2f1

hyp2f1A = np.frompyfunc(lambda a,b,c,z: float(hyp2f1(a,b,c,z)), 4, 1)

def wprp_pl(rp,r0,g):
    return rp*(rp/r0)**-g * gamma(0.5)*gamma((g-1)/2.0)/gamma(g/2.0)

def wprp_pl_lim(rp,r0,g,rmax):
    return (1/gamma(g/2)) * (h.rp*h.rlim/r0)**-g * gamma((g-1)/2) * \
           (gamma(0.5) * h.rp * h.rlim**g - h.rp**g *h.rlim * gamma(g/2)*\
           hyp2f1A(0.5,(g-1)/2,(g+1)/2,h.rp.value**2/h.rlim.value**2))

class TestProjCorr():
    def __init__(self):
        self.rp = np.logspace(-2,1.2,50)
        self.gamma = 1.85 # Values from S1 sample of Beutler+2011
        self.r0 = 5.14