def lnProb_rhoA2rhoB2_given_rhoA2orhoB2o( rhoA2, rhoB2, rhoA2o, rhoB2o ):
    '''
    return ln( p(rhoA2,rhoB2|rhoA2o,rhoB2o) )

    NOTE: essentially 2 independent chi2 distributions
    '''
    types = (int,float)
    if isinstance(rhoA2, types) and isinstance(rhoB2, types) \
      and isinstance(rhoA2o, types) and isinstance(rhoB2o, types):
        return np.log(0.25) - 0.5*(rhoA2 + rhoB2 + rhoA2o + rhoB2o) \
            + float(mpmath.log(mpmath.besseli(0, (rhoA2*rhoA2o)**0.5))) \
            + float(mpmath.log(mpmath.besseli(0, (rhoB2*rhoB2o)**0.5)))
    else:
        N = len(rhoA2)
        assert N==len(rhoB2), 'rhoA2 and rhoB2 do not have the same length'
        assert N==len(rhoA2o), 'rhoA2 and rhoA2o do not have the same length'
        assert N==len(rhoB2o), 'rhoA2 and rhoB2o do not have the same length'

        log25 = np.log(0.25)
        ans = [log25 - 0.5*(rhoa2 + rhob2 + rhoa2o + rhob2o) \
            + float(mpmath.log(mpmath.besseli(0, (rhoa2*rhoa2o)**0.5))) \
            + float(mpmath.log(mpmath.besseli(0, (rhob2*rhob2o)**0.5))) \
            for rhoa2, rhob2, rhoa2o, rhob2o in zip(rhoA2, rhoB2, rhoA2o, rhoB2o)
        ]
        if isinstance(rhoA2, np.ndarray) or isinstance(rhoB2, np.ndarray) or isinstance(rhoA2o, np.ndarray) or isinstance(rhoB2o, np.ndarray):
            ans = np.array(ans)

        ans[ans!=ans] = -np.infty ### get rid of nans
                              ### FIXME we may want to be smarter about this and 
                              ### prevent nans from showing up in the first place
        return ans
Exemple #2
0
def inlineeval(INLINE_INPUTS_, INLINE_INPUTEXPR_, INLINE_EXPR_):
    import numpy as np
    from mpmath import besseli
    INLINE_OUT_ = []
    print(INLINE_INPUTS_)
    k = INLINE_INPUTS_[0]
    print(k[1])
    J = INLINE_INPUTS_[1]
    kb_m = 0
    alpha = 14.04
    kb_m_bi = abs(kb_m)
    ii = np.abs(k) < J / 2
    f = np.sqrt(1 - (k[ii] / (J / 2))**2)
    f = np.expand_dims(f, axis=1)

    denom = besseli(kb_m_bi, alpha)
    kb = np.zeros(np.shape(f))

    for j in range(0, len(kb)):
        kb[j] = np.float(besseli(kb_m_bi, alpha * f[j][0]))

    kb_1 = np.zeros(np.shape(k)).flatten()

    ii = ii.flatten()
    a = ((f**kb_m) * kb) / np.float(denom)
    d = 0
    for u in range(0, len(ii)):
        if ii[u] != 0:
            kb_1[u] = a[d]
            d = d + 1

    kb = np.reshape(kb_1, np.shape(k))

    return kb
def test_bounds_for_Q1():
    """
    These bounds are from:

        Jiangping Wang and Dapeng Wu,
        "Tight bounds for the first order Marcum Q-function"
        Wireless Communications and Mobile Computing,
        Volume 12, Issue 4, March 2012, Pages 293-301.

    """
    with mpmath.workdps(50):
        sqrt2 = mpmath.sqrt(2)
        sqrthalfpi = mpmath.sqrt(mpmath.pi / 2)
        for b in [mpmath.mp.mpf(1), mpmath.mp.mpf(10)]:
            for a in [b / 16, 0.5 * b, 0.875 * b, b]:
                q1 = marcumq(1, a, b)

                sinhab = mpmath.sinh(a * b)
                i0ab = mpmath.besseli(0, a * b)

                # lower bound when 0 <= a <= b
                lb = (mpmath.sqrt(mpmath.pi / 8) * b * i0ab / sinhab *
                      (mpmath.erfc((b - a) / sqrt2) - mpmath.erfc(
                          (b + a) / sqrt2)))
                assert lb < q1

                # upper bound when 0 <= a <= b
                ub = ((i0ab + 3) / (mpmath.exp(a * b) + 3) * (
                    mpmath.exp(-(b - a)**2 / 2) + a * sqrthalfpi * mpmath.erfc(
                        (b - a) / sqrt2) + 3 * mpmath.exp(-(a**2 + b**2) / 2)))
                assert q1 < ub, ("marcumq(1, a, b) < ub for a = %s,  b = %s" %
                                 (a, b))

        for a in [mpmath.mp.mpf(1), mpmath.mp.mpf(10)]:
            for b in [b / 16, 0.5 * b, 0.875 * b, b]:
                q1 = marcumq(1, a, b)

                sinhab = mpmath.sinh(a * b)
                i0ab = mpmath.besseli(0, a * b)

                # lower bound when 0 <= b <= a
                lb = (1 - sqrthalfpi * b * i0ab / sinhab *
                      (mpmath.erf(a / sqrt2) - mpmath.erf(
                          (a - b) / sqrt2) / 2 - mpmath.erf(
                              (a + b) / sqrt2) / 2))
                assert lb < q1

                # upper bound when 0 <= b <= a
                ub = (
                    1 - i0ab / (mpmath.exp(a * b) + 3) *
                    (4 * mpmath.exp(-a**2 / 2) - mpmath.exp(-(b - a)**2 / 2) -
                     3 * mpmath.exp(-(a**2 + b**2) / 2) + a * sqrthalfpi *
                     (mpmath.erfc(-a / sqrt2) - mpmath.erfc((b - a) / sqrt2))))
                assert q1 < ub, ("marcumq(1, a, b) < ub for a = %s,  b = %s" %
                                 (a, b))
def test_Q1_identities():
    with mpmath.workdps(50):
        for a in [mpmath.mp.mpf(1), mpmath.mp.mpf(13)]:
            q1 = marcumq(1, a, a)
            expected = 0.5 * (1 + mpmath.exp(-a**2) * mpmath.besseli(0, a**2))
            assert mpmath.almosteq(q1, expected)

        for a, b in [(1, 2), (10, 3.5)]:
            total = marcumq(1, a, b) + marcumq(1, b, a)
            expected = 1 + mpmath.exp(-(a**2 + b**2) / 2) * mpmath.besseli(
                0, a * b)
            assert mpmath.almosteq(total, expected)
def dpint(f,snr):
	'''Integrand of the detection probability of single sources. Since it contains a modified Bessel function, which gets very big values, it has to be defined in a special way.'''
	big=mpmath.log(mpmath.besseli(1,snr*np.sqrt(2.*f)))
	small=mpmath.mpf(-f-0.5*snr**2.)
	normal=mpmath.log(np.sqrt(2.*f)*1./snr)
	result=mpmath.exp(mpmath.fsum([big,small,normal]))
	return float(result) #In the end the result should be between 0 and some sizeable number, so a float should be enough.
def filtro(wp, wr):

    wc = (wp + wr) / 2
    d = 0.01
    Ap = 20 * math.log10((1 + d) / (1 - d))
    Ar = -20 * math.log10(d)

    if Ar < 21:
        b = 0
        D = .9222

    elif Ar < 50:
        b = 0.5842 * (Ar - 21)**0.4 + 0.07886 * (Ar - 21)
        D = (Ar - 7.95) / 14.36
    else:
        b = .1102 * (Ar - 8.7)
        D = (Ar - 7.95) / 14.36

    k = math.ceil(math.pi * D / (wr - wp) - .5)
    M = 2 * k + 1

    n = np.arange(-k, k + 1, 1)

    #w = besseli(0,b*np.sqrt(1-(4/M**2)*n**2))

    w = np.i0(b * np.sqrt(1 - (4 / M**2) * n**2))
    w = np.divide(w, besseli(0, b))

    h = wc / math.pi * np.sinc(wc * n / math.pi) * w

    return h
def kaiser_bessel_ft(u,J,alpha,kb_m,d):
    import numpy as np
    import math
    from mpmath import besselj, besseli 
    import cmath

    z = map(cmath.sqrt,( (2*math.pi*(J/2)*u)**2 - alpha**2 ))
    print(J)
    
    
    nu = d/2.0 + kb_m
    
    a = np.shape(z)[0]
    bslj = np.zeros(a,np.complex128)
    for i in range(0,a):
        bslj[i] = np.array(np.complex(besselj(nu,z[i])))

    z_sqrt = map(cmath.sqrt, z)
    
    

    a = (2*math.pi)**(d/2.0)*(J/2)**d*alpha**kb_m
    b = a/float(besseli(kb_m,alpha))*bslj
    y = b/(z_sqrt)
        
    y = reale(y)
    
    return y
def Newton_kappa_log(kappa0,D,R, Niter = None):
    kappa = kappa0
    D = float(D)
    
#    print "Init kappa: ", kappa, "Init R: " , R
    for i in range(Niter):
#        print kappa
        Ap_num = mpmath.besseli(D/2,float(kappa))
        Ap_den = mpmath.besseli(D/2-1,float(kappa))
        
        Ap = Ap_num/Ap_den
#        print Ap
        num = Ap - R
        den = 1 - Ap*Ap - ((D-1)/kappa)*Ap
#        print "delta_kappa:", num/den
        kappa = kappa - num/den
    
    return np.array(float(kappa))
def VMFMeanDirDensity(x, k, p):

    for i in range(0, len(x)):
        if (x[i] < -1.0 or x[i] > 1.0):
            sys.exit('Input of x must be within -1 to 1')
    coeff = float((k / 2)**(p / 2 - 1) * (mpmath.gamma(
        (p - 1) / 2) * mpmath.gamma(1 / 2) * mpmath.besseli(p / 2 - 1, k))
                  **(-1))
    #sp.special.gamma((p-1)/2) becoming infinity
    y = coeff * np.exp(k * x) * np.power((1 - np.square(x)), ((p - 2) / 2))
    return y
def lnProb_rhoA2_given_rhoA2o( rhoA2, rhoA2o ):
    '''
    return ln( p(rhoA2 | rhoA2o) )

    NOTE: essentially a chi2 distribution
    '''
    if isinstance(rhoA2, (int,float)) and isinstance(rhoA2o, (int,float)):
        return np.log(0.5) - 0.5*(rhoA2 + rhoA2o) \
            + float(mpmath.log(mpmath.besseli(0, (rhoA2*rhoA2o)**0.5)))
    else:
        assert len(rhoA2)==len(rhoA2o), 'rhoA2 and rhoA2o do not have the same length'

        log5 = np.log(0.5)
        ans = [log5 - 0.5*(rhoa2 + rhoa2o) \
            + float(mpmath.log(mpmath.besseli(0, (rhoa2*rhoa2o)**0.5))) \
            for rhoa2, rhoa2o in zip(rhoA2, rhoA2o)
        ]
        if isinstance(rhoA2, np.ndarray) or isinstance(rhoA2o, np.ndarray):
            ans = np.array(ans)

        return ans
Exemple #11
0
def dist_vs_time_golo_exp(x, t, x0, n0, b):
    res = np.zeros(len(x), dtype=np.float128)
    for n in range(len(x)):
        t = np.where(t < 1E-12, 1E-12, t)
        x_x0 = x[n] / x0
        x = np.where(x_x0 < 1E-8, x0 * 1E-8, x)
        x_x0 = x[n] / x0
        T = 1. - np.exp(-b * n0 * x0 * t)
        T_sqrt = np.sqrt(T)
        z = 2. * x_x0 * T_sqrt
        res[n] = n0 / x0 * (1. - T) * 2.\
                 * mpm.exp( -0.5 * (1. + T) * z / T_sqrt )\
                 * mpm.besseli(1,z) / z
    return res
def get_cp_log(p,kappa):
    p = float(p)
    cp = (p/2-1)*np.log(kappa)
#    bessel_func = ive (p/2-1,kappa) * np.exp(kappa)
#    print ".............."
#    print bessel_func
    bessel_func = mpmath.besseli(p/2-1,float(kappa))
#    bessel_func = float(bessel_func)
#    print bessel_func
    bessel_func_log = float(mpmath.log(bessel_func))
#    print bessel_func_log
    cp += -(p/2)*np.log(2*pi)-bessel_func_log
    
    return cp
def get_cp_log(p, kappa):
    p = float(p)
    cp = (p / 2 - 1) * np.log(kappa)
    #    bessel_func = ive (p/2-1,kappa) * np.exp(kappa)
    #    print ".............."
    #    print bessel_func
    bessel_func = mpmath.besseli(p / 2 - 1, float(kappa))
    #    bessel_func = float(bessel_func)
    #    print bessel_func
    bessel_func_log = float(mpmath.log(bessel_func))
    #    print bessel_func_log
    cp += -(p / 2) * np.log(2 * pi) - bessel_func_log

    return cp
Exemple #14
0
def pdf(x, k, lam):
    """
    PDF for the noncentral chi-square distribution.
    """
    if x < 0:
        return mpmath.mp.zero
    with mpmath.extradps(5):
        x = mpmath.mpf(x)
        k = mpmath.mpf(k)
        lam = mpmath.mpf(lam)
        p = (mpmath.exp(-(x + lam) / 2) * mpmath.power(x / lam,
                                                       (k / 2 - 1) / 2) *
             mpmath.besseli(k / 2 - 1, mpmath.sqrt(lam * x)) / 2)
    return p
Exemple #15
0
def pdf(x, nu, sigma):
    """
    PDF for the Rice distribution.
    """
    if x <= 0:
        return mpmath.mp.zero
    with mpmath.extradps(5):
        x = mpmath.mpf(x)
        nu = mpmath.mpf(nu)
        sigma = mpmath.mpf(sigma)
        sigma2 = sigma**2
        p = ((x / sigma2) * mpmath.exp(-(x**2 + nu**2) / (2 * sigma2)) *
             mpmath.besseli(0, x * nu / sigma2))
    return p
Exemple #16
0
def circ_vmpdf(alpha, thetahat, kappa):
    
    alpha = alpha;
    
    C = 1/(2*math.pi*mpmath.besseli(0,kappa));
    aas = [];
    
    for i in range(len(alpha)):
        a = alpha[i]-thetahat
        aa = math.exp(kappa*math.cos(a));
        aas.append(aa);
    aas = np.array(aas);
    b = aas;
    #b = float( math.exp(kappa*aas));
    p = C * b;
    return p ;
Exemple #17
0
def mean(chi, c):
    """
    Mean of the ARGUS distribution.
    """
    if c <= 0:
        raise ValueError('c must be positive')
    if chi <= 0:
        raise ValueError('chi must be positive')

    with mpmath.extradps(5):
        chi = mpmath.mpf(chi)
        c = mpmath.mpf(c)
        chi2o4 = chi**2 / 4
        p1 = c * mpmath.sqrt(mpmath.pi / 8)
        p2 = chi * mpmath.exp(-chi2o4)
        p3 = mpmath.besseli(1, chi2o4)
        return p1 * p2 * p3 / _psi(chi)
Exemple #18
0
def VMFMeanDirDensity(x, k, p):
    """
    This function is the tangent direction density of VMF distribution.
    The inputs are:
        x=Tangent value between [-1 1]
        k=kappa parameter
        p=Dimension of the VMF distribution
    The output is y=density of the VMF tangent density 
    """
    for i in range(0, len(x)):
        if (x[i] < -1.0 or x[i] > 1.0):
            sys.exit('Input of x must be within -1 to 1')
    coeff = float((k / 2)**(p / 2 - 1) * (mpmath.gamma(
        (p - 1) / 2) * mpmath.gamma(1 / 2) * mpmath.besseli(p / 2 - 1, k))
                  **(-1))
    #sp.special.gamma((p-1)/2) becoming infinity
    y = coeff * np.exp(k * x) * np.power((1 - np.square(x)), ((p - 2) / 2))
    return y
Exemple #19
0
def psi(index, variable, b, a, beta):

    if b == 0:

        if beta < 0:
            return math.pow(variable, 0.5) * besseli(
                v(beta), sqrt(2 * index * q(a, beta, variable)))
        else:
            return math.pow(variable, 0.5) * besselk(
                v(beta), sqrt(2 * index * q(a, beta, variable)))
    else:

        if beta < 0:
            return math.pow(variable, beta + 0.5) * math.exp(
                0.5 * eps(b, beta) * h(b, a, beta, variable)) * whitm(
                    k(b, beta, index), m(beta), h(b, a, beta, variable))

        else:
            return math.pow(variable, beta + 0.5) * math.exp(
                0.5 * eps(b, beta) * h(b, a, beta, variable)) * whitw(
                    k(b, beta, index), m(beta), h(b, a, beta, variable))
Exemple #20
0
def _noncentral_chi_pdf(t, df, nc):
    res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t))
    res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2
    return res
Exemple #21
0
 def test_besseli_complex(self):
     assert_mpmath_equal(
         lambda v, z: sc.iv(v.real, z),
         _exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
         [Arg(-1e100, 1e100), ComplexArg()])
Exemple #22
0
 def test_besseli(self):
     assert_mpmath_equal(
         sc.iv,
         _exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
         [Arg(-1e100, 1e100), Arg()],
         n=1000)
 def hp_ive(n,x):
     return mpm.exp(-x)*mpm.besseli(n, x)
def f14(x):
    # bessel_I0_scaled
    scale = mpmath.exp(-abs(x))
    y = mpmath.besseli(0, x) * scale
    return y
Exemple #25
0
def sph_i1n_bessel(n, z):
    out = besseli(n + mpf(1)/2, z)*sqrt(pi/(2*z))
    if mpmathify(z).imag == 0:
        return out.real
    else:
        return out
Exemple #26
0
 def test_besseli_complex(self):
     assert_mpmath_equal(lambda v, z: sc.iv(v.real, z),
                         _exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
                         [Arg(-1e100, 1e100), ComplexArg()])
def f28(x):
    # bessel_i2_scaled
    x = mpmath.mpf(x)
    y = mpmath.sqrt(mpmath.pi /
                    (2 * x)) * mpmath.besseli(2.5, x) * mpmath.exp(-abs(x))
def f27(x):
    # bessel_i1_scaled
    x = mpmath.mpf(x)
    y = mpmath.sqrt(mpmath.pi /
                    (2 * x)) * mpmath.besseli(1.5, x) * mpmath.exp(-abs(x))
    return y
Exemple #29
0
def _noncentral_chi_pdf(t, df, nc):
    res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t))
    res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2
    return res
Exemple #30
0
def Gamma0(b):
    return mp.besseli(0, b) * mp.exp(-b)
Exemple #31
0
def Gamma0(b) : return    mp.besseli(0,b)*mp.exp(-b)
def Gamma1(b) : return    mp.besseli(1,b)*mp.exp(-b)
Exemple #32
0
def Gamma0(b) : return mp.besseli(0,b)*mp.exp(-b)

# Plasma Dispersion function
def Z(x): return (1.j * mp.sqrt(mp.pi) * mp.exp(- x**2) * (1 + mp.erf(1.j * x)))
def f12(x):
    # bessel_I0
    return mpmath.besseli(0, x)
Exemple #34
0
 def test_besseli(self):
     assert_mpmath_equal(sc.iv,
                         _exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
                         [Arg(-1e100, 1e100), Arg()],
                         n=1000)
def f13(x):
    # bessel_I1
    return mpmath.besseli(1, x)
def von_Mises_pdf(x,kappa,mu=mpmath.pi):
    return (mpmath.exp(kappa*mpmath.cos(x-mu))/
            (2*mpmath.pi*mpmath.besseli(0,kappa)))
Exemple #37
0
def Gamma1(b) : return    mp.besseli(1,b)*mp.exp(-b)
#def Gamma1(b) : return    #mp.besseli(1,b)*mp.exp(-b)


def getZero(Func, init=(1.+1.j, 1.1+1.j, 1.+1.1j), solver='muller', ftol=1.e-3, tol=1.e-3, maxsteps=600):
Exemple #38
0
def Gamma1(b):
    return mp.besseli(1, b) * mp.exp(-b)
@author: jdesk
"""

import numpy as np
#from mpmath import *
import mpmath as mpm
mpm.mp.dps = 25; mpm.mp.pretty = True
A = mpm.hyp1f1(2, (-1,3), 3.25)

print(A)

print(mpm.hyp1f1(3, 4, 1E20))

B = np.ones(100, dtype = np.float128)


print(B)

for n in range(100):
    B[n] = mpm.exp(10*n)
    print(mpm.exp(20*(-n)))    
    print(mpm.exp(20*(-n))*mpm.exp(20*(n)))    
    
print(B)

C = np.arange(10)

#print(mpm.exp(C))

D = mpm.besseli()
Exemple #40
0
def sph_i2n_bessel(n, z):
    out = besseli(- n - mpf(1)/2, z)*sqrt(pi/(2*z))
    return out
def f15(x):
    # bessel_I1_scaled
    scale = mpmath.exp(-abs(x))
    y = mpmath.besseli(1, x) * scale
    return y
Exemple #42
0
from math import gamma # Been there a while




#has_scipy = False

if has_scipy:
    from scipy.special import lambertw, ellipe, gammaincc, gamma # fluids
    from scipy.special import i1, i0, k1, k0, iv # ht
    from scipy.special import hyp2f1    
    if erf is None:
        from scipy.special import erf
else:
    import mpmath
    # scipy is not available... fall back to mpmath as a Pure-Python implementation
    from mpmath import lambertw # Same branches as scipy, supports .real
    from mpmath import ellipe # seems the same so far        
    

    # Figured out this definition from test_precompute_gammainc.py in scipy
    gammaincc = lambda a, x: mpmath.gammainc(a, a=x, regularized=True)
    iv = mpmath.besseli
    i1 = lambda x: mpmath.besseli(1, x)
    i0 = lambda x: mpmath.besseli(0, x)
    k1 = lambda x: mpmath.besselk(1, x)
    k0 = lambda x: mpmath.besselk(0, x)
    
    if erf is None:
        from mpmath import erf
def von_Mises_entropy_fraction(kappa):
    I0_kappa = mpmath.besseli(0,kappa)
    I1_kappa = mpmath.besseli(1,kappa)
    kappa_entropy = mpmath.ln(2*mpmath.pi*I0_kappa) - kappa*(I1_kappa/I0_kappa)
    return 1-(kappa_entropy/von_Mises_entropy_max())