Example #1
0
def noisy_shot_noise(X, g, e):
    """
    Returns the pdf of a normalized gamma distributed process with additive noise.
    Let z ~ Gamma(g,A), y ~ Normal(0,s^2), x = z+y.
    Input:
        X: The normalized variable X = (x-<x>)/x_rms, 1d numpy array
        g: shape parameter
        e: noise parameter, e=y_rms^2 / z_rms^2.
    Output:
        F: The pdf of X.
    """
    F = np.zeros(len(X))
    # print 'g = ', g, ', type(g) = ', type(g)
    # print 'e = ', e, ', type(e) = ', type(e)
    assert (g > 0)
    assert (e > 0)
    g = mm.mpf(g)
    e = mm.mpf(e)
    for i in range(len(X)):
        x = mm.mpf(X[i])
        # F[i] = (g/2)**(g/2)*e**(g/2-1)*(1+e)**(1/2)*mm.exp( - ((1+e)**(1/2)*x+g**(1/2))**2 / (2*e) ) *\
        #( e**(1/2)*mm.hyp1f1(g/2,1/2, ((1+e)**(1/2)*x+g**(1/2)*(1-e))**2 / (2*e) ) / (2**(1/2) * mm.gamma((1+g)/2)) +\
        #( (1+e)**(1/2)*x+g**(1/2)*(1-e) )*mm.hyp1f1((1+g)/2,3/2, ((1+e)**(1/2)*x+g**(1/2)*(1-e))**2 / (2*e) ) / mm.gamma(g/2) )

        F[i] = (g * 0.5)**(g * 0.5) * e**(g * 0.5 - 1.) * (1. + e)**(0.5) * mm.exp(-((1. + e)**(0.5) * x + g**(0.5))**(2.0) / (2.0 * e) ) *\
               (e ** (0.5) * mm.hyp1f1(0.5 * g, 0.5, ((1. + e)**(0.5) * x + g**(0.5) * (1. - e))**2 / (2. * e)) / (2.**(0.5) * mm.gamma((1. + g) * 0.5)) +
                ((1. + e)**(0.5) * x + g**(0.5) * (1. - e)) * mm.hyp1f1((1. + g) * 0.5, 1.5, ((1. + e)**(0.5) * x + g**(0.5) * (1. - e))**2 / (2. * e)) / mm.gamma(g * 0.5))
    return F
def dump_reference_json():
    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))
    mp.dps = 200
    data = []
    for l in range(20):
        for n in range(20):
            # z > 660 will lead to larger than double::max() values for a > 19
            for z in [
                    1e-2,
                    1e-1,
                    1,
                    10,
                    20,
                    30,
                    40,
                    60,
                    80,
                    100,
                    150,
                    200,
                    500,
                    660,
            ]:
                a = 0.5 * (n + l + 3)
                b = l + 1.5

                val = float(hyp1f1(a, b, z))
                der = float(a / b * hyp1f1(a + 1, b + 1, z))
                data.append(dict(a=a, b=b, z=z, val=val, der=der))
    print(len(data))
    with open(os.path.join(root, dump_path, "hyp1f1_reference.ubjson"),
              "wb") as f:
        ubjson.dump(data, f)
Example #3
0
def U_Kummer_mpmath(a, x):
    factor = np.sqrt(np.pi) * 2**(-0.25 - 1 / 2. * a)
    factor_2 = np.sqrt(np.pi) * 2**(0.25 - 1 / 2. * a) * x
    first_term = factor * mpmath.hyp1f1(
        0.5 * a + 0.25, 0.5, 0.5 * x**2) / mpmath.gamma(0.75 + 0.5 * a)
    second_term = factor_2 * mpmath.hyp1f1(
        0.5 * a + 0.75, 1.5, 0.5 * x**2) / mpmath.gamma(0.25 + 0.5 * a)
    return first_term + second_term
Example #4
0
def recurrence_step_feedback(prms, M, precision=500):
    """Compute feedback model solution via the recurrence method.

    Arguments:
    parameters -- List of the five rate parameters: ru, rb, th, su, sb
    M -- Number of terms evaluated by the recursion relation
    precision -- Decimal precision used by the mpmath mpf type"""

    mpm.mp.dps = precision

    def update(nn, h0m2, h0m1, h1m2, h1m1):
        n = mpm.mpf(nn)

        u1 = mpm.mpf(1)/(sb*n)*((th + su)*h1m1 + su*h1m2 - \
            (sb + mpm.mpf(1))*(n - mpm.mpf(1))*h0m1 + ru*h0m2)
        u2 = (rb + su) / n * h1m1 - (sb + mpm.mpf(1)) * u1 + ru / n * h0m1
        return [u1, u2]

    # Set up parameters
    ru = mpm.mpf(prms[0])
    rb = mpm.mpf(prms[1])
    th = mpm.mpf(prms[2])
    su = mpm.mpf(prms[3])
    sb = mpm.mpf(prms[4])

    Sb = mpm.mpf(1) + sb
    Rr = ru - rb * Sb
    Cc = (Sb - mpm.mpf(1)) / Sb
    al = th + su / Rr * (ru - rb)
    bet = mpm.mpf(1) + th + mpm.mpf(1) / Sb * (su + ru * Cc)
    w_1 = Rr * (Sb - mpm.mpf(1)) / (Sb**mpm.mpf(2))

    Aa = mpm.mpf(1)/(Sb*al/(sb*ru)*mpm.hyp1f1((al + 1), (bet), (w_1)) + \
        (mpm.mpf(1) + (th - al)/(ru - rb))*mpm.hyp1f1((al), (bet), (w_1)))
    h0Ini = Aa*(Sb*al/(sb*ru)*mpm.hyp1f1((al + 1), (bet), (w_1)) + \
        ((th - al)/(ru - rb))*mpm.hyp1f1((al), (bet), (w_1)))
    h1Ini = Aa * mpm.hyp1f1((al), (bet), (w_1))
    h01Ini = mpm.mpf(1) / sb * (th + su) * h1Ini

    hh = [[h0Ini, h1Ini]]
    u2 = (rb + su) * h1Ini - (sb + mpm.mpf(1)) * h01Ini + ru * h0Ini
    hh.append([h01Ini, u2])

    for n in range(2, M):
        hh.append(
            update(n, hh[n - 2][0], hh[n - 1][0], hh[n - 2][1], hh[n - 1][1]))

    G = np.sum(hh, 1)

    return G
Example #5
0
def kummer_log(a,b,x):
    ## First try using the funcion in the library.
    ## If it is 0 or inf then we try to use our own implementation with logs
    ## If it does not converge, then we return None !!
    a = float(a); b = float(b); x = float(x)
    
#    f_scipy = scipy_hyp1f1(a,b,x)
    f_mpmath = mpmath.hyp1f1(a,b,x)
    f_log = float(mpmath.log(f_mpmath))
    if (np.isinf(f_log) == True):
#        warnings.warn("hyp1f1() is 'inf', trying log version,  (a,b,x) = (%f,%f,%f)" %(a,b,x),UserWarning, stacklevel=2)
        f_log = kummer_own_log(a,b,x)
#        print f_log
        
    elif(f_mpmath == 0):
#        warnings.warn("hyp1f1() is '0', trying log version, (a,b,x) = (%f,%f,%f)" %(a,b,x),UserWarning, stacklevel=2)
        raise RuntimeError('Kummer function is 0. Kappa = %f', "Kummer_is_0", x)
#        f_log = kummer_own_log(a,b,x)  # TODO: We cannot do negative x, the functions is in log
    else:
#        f_log = np.log(f_scipy)
        f_log = f_log
#        print (a,b,x)
#        print f_log
        
    f_log = float(f_log)
    return f_log
Example #6
0
def kummer_log(a, b, x):
    ## First try using the funcion in the library.
    ## If it is 0 or inf then we try to use our own implementation with logs
    ## If it does not converge, then we return None !!
    a = float(a)
    b = float(b)
    x = float(x)

    #    f_scipy = scipy_hyp1f1(a,b,x)
    f_mpmath = mpmath.hyp1f1(a, b, x)
    f_log = float(mpmath.log(f_mpmath))
    if (np.isinf(f_log) == True):
        #        warnings.warn("hyp1f1() is 'inf', trying log version,  (a,b,x) = (%f,%f,%f)" %(a,b,x),UserWarning, stacklevel=2)
        f_log = kummer_own_log(a, b, x)
#        print f_log

    elif (f_mpmath == 0):
        #        warnings.warn("hyp1f1() is '0', trying log version, (a,b,x) = (%f,%f,%f)" %(a,b,x),UserWarning, stacklevel=2)
        raise RuntimeError('Kummer function is 0. Kappa = %f', "Kummer_is_0",
                           x)
#        f_log = kummer_own_log(a,b,x)  # TODO: We cannot do negative x, the functions is in log
    else:
        #        f_log = np.log(f_scipy)
        f_log = f_log


#        print (a,b,x)
#        print f_log

    f_log = float(f_log)
    return f_log
Example #7
0
def binMRlogL(n, Ic, Is):
    '''
    Given a light curve, calculate the Log likelihood that
    its intensity distribution follows a blurred modified Rician with Ic, Is.

    INPUTS:
        n: 1d array containing the (binned) intensity as a function of time, i.e. a lightcurve [counts/sec]. Bin size must be fixed.
        Ic: Coherent portion of MR [1/second]
        Is: Speckle portion of MR [1/second]
    OUTPUTS:
        [float] the Log likelihood.

    '''
    lnL = np.zeros(len(n))
    tmp = np.zeros(len(n))
    for ii in range(len(n)):  # hyp1f1 can't do numpy arrays because of its data type, which is mpf
        tmp[ii] = float(hyp1f1(n[ii] + 1, 1, Ic / (Is ** 2 + Is)))
    # dprint(np.log(1. / (Is + 1)))
    # dprint(- n * np.log(1 + 1. / Is))
    # dprint(- Ic / Is)
    # dprint(np.log(tmp))
    lnL = np.log(1. / (Is + 1)) - n * np.log(1 + 1. / Is) - Ic / Is + np.log(tmp)
    # dprint(np.sum(lnL))

    return np.sum(lnL)
Example #8
0
def blurredMR(n, Ic, Is):
    """
    Calculates the probability of getting a bin with n counts given Ic & Is. 
    n, Ic, Is must have the same units. 
    
    INPUTS:
        n - array of the number of counts you want to know the probability of encountering. numpy array, can have length = 1. Units are the same as Ic & Is
        Ic - the constant part of the speckle pattern [counts/time]. User needs to keep track of the bin size. 
        Is - the random part of the speckle pattern [units] - same as Ic
    OUTPUTS:
        p - array of probabilities
        
    EXAMPLE:
        n = np.arange(8)
        Ic,Is = 4.,6.
        p = blurredMR(n,Ic,Is)
        plt.plot(n,p)
        #plot the probability distribution of the blurredMR vs n
        
        n = 5
        p = blurredMR(n,Ic,Is)
        #returns the probability of getting a bin with n counts
    
    """

    n = n.astype(int)
    p = np.zeros(len(n))
    for ii in range(len(n)):
        p[ii] = 1 / (Is + 1) * (1 + 1 / Is)**(-n[ii]) * np.exp(
            -Ic / Is) * hyp1f1(float(n[ii]) + 1, 1, Ic / (Is**2 + Is))
    return p
Example #9
0
def make_plot(a, b, z, title, maxterms):
    approx, terms = optimal_terms.asymptotic_series(a, b, z, maxterms)
    ref = np.float64(mpmath.hyp1f1(a, b, z))

    cd = correct_digits(approx, ref)
    termsize = np.abs(terms/terms[0])

    fig, ax1 = plt.subplots()
    ax1.plot(cd, '-', linewidth=2, color=GREEN)
    ax1.set_ylim(0, 17)
    ax1.set_xlabel('term number')
    # Make the y-axis label and tick labels match the line color.
    ax1.set_ylabel('correct digits', color=GREEN)
    for tl in ax1.get_yticklabels():
        tl.set_color(GREEN)

    ax2 = ax1.twinx()
    cmap, norm = colors.from_levels_and_colors([-np.inf, 0, np.inf],
                                               [BLUE, RED])
    ax2.scatter(np.arange(termsize.shape[0]), termsize,
                c=terms, cmap=cmap, norm=norm, edgecolors='')
    # ax2.semilogy(termsize, 'r--', linewidth=2)
    ax2.set_yscale('log')
    ax2.set_ylabel('relative term size', color=RED)
    # Set the limits, with a little margin.
    ax2.set_xlim(0, termsize.shape[0])
    ax2.set_ylim(np.min(termsize), np.max(termsize))
    for tl in ax2.get_yticklabels():
        tl.set_color(RED)

    ax1.set_title("a = {:.2e}, b = {:.2e}, z = {:.2e}".format(a, b, z))

    plt.savefig("{}.png".format(title))
Example #10
0
def multiprec_pdf(df, mu, x):
    df = mp.mpf(str(df))
    mu = mp.mpf(str(mu))
    x = mp.mpf(str(x))
    pdf = (mp.exp(-mu**2 / 2) * 2**(-df) * df**(df/2) * mp.gamma(df+1) * \
           ((mp.sqrt(2) * x * mu * (x**2+df)**(-df/2-1) * mp.hyp1f1(df/2+1,1.5,(mu**2 * x**2)/(2 * (x**2+df))))/(mp.gamma((df+1)/2))+((x**2+df)**(-df/2-0.5) * mp.hyp1f1((df+1)/2,0.5,(mu**2 * x**2)/(2 * (x**2+df))))/(mp.gamma(df/2+1))))/(mp.gamma(df/2))
    return pdf
Example #11
0
def multiprec_pdf(df, mu, x):
    df = mp.mpf(str(df))
    mu = mp.mpf(str(mu))
    x  = mp.mpf(str(x))
    pdf = (mp.exp(-mu**2 / 2) * 2**(-df) * df**(df/2) * mp.gamma(df+1) * \
           ((mp.sqrt(2) * x * mu * (x**2+df)**(-df/2-1) * mp.hyp1f1(df/2+1,1.5,(mu**2 * x**2)/(2 * (x**2+df))))/(mp.gamma((df+1)/2))+((x**2+df)**(-df/2-0.5) * mp.hyp1f1((df+1)/2,0.5,(mu**2 * x**2)/(2 * (x**2+df))))/(mp.gamma(df/2+1))))/(mp.gamma(df/2))
    return pdf
Example #12
0
def o_function(l, k, r):
    res = mpmath.hyp1f1(-1j / k + l, 2 * l + 2, -2 * 1j * k * r)
    res *= (1. / (2 * l + 1)) * (k * r)**l
    res *= mpmath.gamma(1 + 1j / k)
    res *= mpmath.rf(-1j / k, l)
    res *= (-2j)**l / mpmath.fac(2 * l)
    res *= mpmath.exp(mpmath.pi / (2 * k))
    return res
Example #13
0
 def test_hyp1f1(self):
     assert_mpmath_equal(
         _inf_to_nan(sc.hyp1f1),
         _exception_to_nan(
             lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
         [Arg(-1e5, 1e5), Arg(-1e5, 1e5),
          Arg()],
         n=2000)
Example #14
0
 def test_hyp1f1_complex(self):
     assert_mpmath_equal(
         _inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
         _exception_to_nan(
             lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
         [Arg(-1e3, 1e3), Arg(-1e3, 1e3),
          ComplexArg()],
         n=2000)
Example #15
0
def reference_value(a, b, z):
    mpmath.mp.dps = 20
    try:
        lo = mpmath.hyp1f1(a, b, z, maxprec=MAXPREC)
    except ZeroDivisionError:
        # Pole in hypergeometric series
        return np.inf

    return np.float64(lo)
Example #16
0
def spherical_hypergeometric(
    max_radial, max_angular, atomic_gaussian_constants, gto_gaussian_constants, all_rij
):
    # Compute everything up to 50 decimal places
    math.mp.dps = 50

    n_rij = len(all_rij)
    n_constants = len(atomic_gaussian_constants)
    values = np.zeros(
        (n_constants, n_rij, max_radial, max_angular + 1), dtype=np.float64
    )
    gradients = np.zeros(
        (n_constants, n_rij, max_radial, max_angular + 1), dtype=np.float64
    )

    for i_atomic_constant, c in enumerate(atomic_gaussian_constants):
        for i_rij, rij in enumerate(all_rij):
            for n in range(max_radial):
                for l in range(max_angular + 1):  # noqa: E741
                    a = (n + l + 3) / 2.0
                    b = l + 1.5
                    d = gto_gaussian_constants[n]

                    z = c * c * rij * rij / (c + d)

                    gamma_ratio = math.gamma(a) / math.gamma(b)

                    value = (
                        gamma_ratio * math.exp(-c * rij * rij) * math.hyp1f1(a, b, z)
                    )
                    values[i_atomic_constant, i_rij, n, l] = value

                    grad_factor = 2.0 * a * c * c * rij / (b * (c + d))
                    grad = (
                        grad_factor
                        * gamma_ratio
                        * math.exp(-c * rij * rij)
                        * math.hyp1f1(a + 1.0, b + 1.0, z)
                    )
                    gradients[i_atomic_constant, i_rij, n, l] = (
                        grad - 2.0 * c * rij * value
                    )

    return values, gradients
def dump_reference_json():
    path = '../'
    sys.path.insert(0, os.path.join(path, 'build/'))
    sys.path.insert(0, os.path.join(path, 'tests/'))
    mp.dps = 200
    data = []
    for l in range(20):
        for n in range(20):
            for z in [1e-2, 1e-1, 1, 10, 20, 30, 40, 60, 80, 100, 150, 200]:
                a = 0.5 * (n + l + 3)
                b = l + 1.5

                val = float(hyp1f1(a, b, z))
                der = float(a / b * hyp1f1(a + 1, b + 1, z))
                data.append(dict(a=a, b=b, z=z, val=val, der=der))
    print(len(data))
    with open(path + "tests/reference_data/hyp1f1_reference.ubjson",
              'wb') as f:
        ubjson.dump(data, f)
Example #18
0
 def G(self,s): # Laplace-Transform
   zz = 2*self.v + 2 + s
   mu = sqrt(self.v**2+2*zz)
   a  = mu/2 - self.v/2 - 1
   b  = mu/2 + self.v/2 + 2
   v1 = (2*self.alp)**(-a)*gamma(b)/gamma(mu+1)/(zz*(zz - 2*(1 + self.v)))
   prec = floor(max(log10(abs(v1)),mp.dps))+self.prec
   # additional precision needed for computation of hyp1f1
   with mp.extradps(prec):
     value = hyp1f1(a,mu + 1,self.beta)*v1
   return value
def e_mean_n(sk, mk, shape, k):
    """
    E(|mean^shape|)
    """

    temp = []
    for cluster in range(k):
        p = (1 / math.sqrt(sk[cluster])) ** shape * 2 ** (shape / 2) * gamma((1 + shape) / 2) / math.sqrt(
            math.pi) * mpmath.hyp1f1(-shape / 2, 1 / 2, -1 / 2 * mk[cluster] ** 2 * sk[0])
        temp.append(p)
    return np.asarray(temp).reshape(-1, 1)
Example #20
0
def Asian(S, K, T, t, sig, r, N):

    #   Assigning multi precision
    S = mpf(S)
    K = mpf(K)
    sig = mpf(sig)
    T = mpf(T)
    t = mpf(t)
    r = mpf(r)

    #   Geman and Yor's variable
    tau = mpf(((sig**2) / 4) * (T - t))
    v = mpf(2 * r / (sig**2) - 1)
    alp = mpf(sig**2 / (4 * S) * K * T)
    beta = mpf(-1 / (2 * alp))
    tau = mpf(tau)
    N = mpf(N)

    #   Initiate the stepsize
    h = 2 * pi / N
    mp.dps = 100

    c1 = mpf('0.5017')
    c2 = mpf('0.6407')
    c3 = mpf('0.6122')
    c4 = mpc('0', '0.2645')

    #   The for loop is evaluating the Laplace inversion at each point theta which is based on the trapezoidal
    #   rule
    ans = 0.0

    for k in range(N / 2):  # N/2 : symmetry
        theta = -pi + (k + 0.5) * h
        z = 2 * v + 2 + N / tau * (c1 * theta / tan(c2 * theta) - c3 +
                                   c4 * theta)
        dz = N / tau * (-c1 * c2 * theta / sin(c2 * theta)**2 +
                        c1 / tan(c2 * theta) + c4)
        zz = N / tau * (c1 * theta / tan(c2 * theta) - c3 + c4 * theta)
        mu = sqrt(v**2 + 2 * z)
        a = mu / 2 - v / 2 - 1
        b = mu / 2 + v / 2 + 2
        G = (2 * alp)**(-a) * gamma(b) / gamma(mu + 1) * hyp1f1(
            a, mu + 1, beta) / (z * (z - 2 * (1 + v)))
        ans += exp(zz * tau) * G * dz

    return 2 * exp(tau * (2 * v + 2)) * exp(
        -r * (T - t)) * 4 * S / (T * sig**2) * h / (2j * pi) * ans
Example #21
0
def equilibrium_biallelic(n, gamma, h, mutation_model, theta):
    """
    n: sample size
    gamma: scaled selection coefficient (2Ns)
    mutation_model: can be ISM or recurrent (or reversible)
    theta: scaled mutation rate.
    """
    if mutation_model == "ISM":
        print("warning:  not implemented for ISM")
        return np.zeros(n + 1)
    elif mutation_model in ["recurrent", "reversible"]:
        if h != 0.5:
            print(
                "warning: with recurrent mutations, steady state only returned "
                " for h = 1/2.")
        if not isinstance(theta, list):
            theta_fd = theta_bd = theta
        else:
            theta_fd, theta_bd = theta
        fs = np.zeros(n + 1)
        if gamma is None or gamma == 0.0:
            for i in range(n + 1):
                fs[i] = (scisp.gammaln(n + 1) - scisp.gammaln(n - i + 1) -
                         scisp.gammaln(i + 1) + scisp.gammaln(i + theta_fd) +
                         scisp.gammaln(n - i + theta_bd))
            fs += (scisp.gammaln(theta_fd + theta_bd) -
                   scisp.gammaln(theta_fd) - scisp.gammaln(theta_bd) -
                   scisp.gammaln(n + theta_fd + theta_bd))
            fs = np.exp(fs)
        else:
            ## unstable for large n
            for i in range(n + 1):
                fs[i] = np.exp(
                    scisp.gammaln(n + 1) - scisp.gammaln(n - i + 1) -
                    scisp.gammaln(i + 1) + scisp.gammaln(i + theta_fd) +
                    scisp.gammaln(n - i + theta_bd) -
                    scisp.gammaln(n + theta_fd + theta_bd)) * hyp1f1(
                        i + theta_fd, n + theta_fd + theta_bd, 2 * gamma)
        return fs / np.sum(fs)
    else:
        raise ValueError(
            f"{mutation_model} is not a valid mutation model, pick "
            "from either ISM or recurrent / reversible")
Example #22
0
def coulomb_wave_function(l, eta, rho):
    # calculate C_l(eta) coef using alternate def
    # norm_factor = 2**l * np.exp(-np.pi * eta / 2) * np.abs(
    #     gamma(l + 1 + 1.0j * eta)) / factorial(2 * l + 1)
    product = np.arange(1.0, l + 1.0)
    if l == 0:
        product = np.array([1.0])
    product = np.add.outer(eta**2, product**2)
    product = np.prod(product, axis=1)
    norm_factor = 2**l * np.sqrt(2 * np.pi * eta / (
        np.exp(np.pi * eta * 2) - 1) * product) / factorial(2 * l + 1)
    # return the f_l function
    return_array = np.zeros(norm_factor.shape, dtype='complex128')
    for idx in np.arange(norm_factor.shape[0]):
        input_0 = complex(l + 1.0 - 1.0j * eta[idx])
        input_1 = complex(2.0 * l + 2.0)
        input_2 = 1.0j * 2.0 * rho[idx]
        hyp = hyp1f1(input_0, input_1, input_2)
        hyp = float(hyp.real) + 1.j * float(hyp.imag)
        return_array[idx] = norm_factor[idx] * rho[idx]**(
            l + 1) * np.exp(-1.0j * rho[idx]) * hyp
    return return_array
Example #23
0
def analytic_twostate(parameters, N):
    """ Analytic steady state distribution for a two-state model (leaky telegraph).

    Requires computation at high precision via mpm for accurate convergence of
    the summation.

    Arguments:
    parameters -- List of the four rate parameters: v12,v21,K0,K1
    N -- Maximal mRNA copy number. The distribution is evaluated for n=0:N-1"""

    v12 = mpm.mpf(parameters[0])
    v21 = mpm.mpf(parameters[1])
    K0 = mpm.mpf(parameters[2])
    K1 = mpm.mpf(parameters[3])

    P = mpm.matrix(np.zeros(N))  # Preallocate at high precision
    for n in range(N):
        for r in range(n + 1):
            mpmCalc = mpm.power(K1,n-r) * mpm.power(K0-K1,r) * mpm.exp(-K0) * \
            mpm.hyp1f1(v12,v12+v21+r,K0-K1) / (mpm.factorial(n-r) * mpm.factorial(r))
            P[n] += mpmCalc * fracrise_mpm(v21, v21 + v12, r)

    P = np.array([float(p) for p in P])
    return P / P.sum()
Example #24
0
def R_final_kl(r, k, l, Z_eff):
    return 4 * pi * (2*k*r)**l * abs( mp.gamma(l+1 - 1j*Z_eff / k / a0) ) * mp.exp(pi * Z_eff /2/k/a0) / mp.factorial(2*l+1) * (mp.expj(-k*r) * mp.hyp1f1(l+1+1j*Z_eff/k/a0, (2*l+2), 2j*k*r, maxterms=1000000)).real
Example #25
0
def blurredMR2(x,Ic,Is):
    p = np.zeros(len(x))
    for ii in x:
        p[ii] = 1/(Is + 1)*(1 + 1/Is)**(-ii)*np.exp(-Ic/Is)*hyp1f1(float(x[ii]) + 1,1,Ic/(Is**2 + Is))
    return p
Example #26
0
def hyp1f1(a, b, z):
    #global mp
    """ Computes the confluent hypergeometric function.

    The parameters a, b, and z may be complex. Further, one or more of them may be numpy arrays. 
    """
    uselib = lib is not None and not use_mpmath
    #if not uselib and mp is None:
    #    mp = __import__("mpmath")

    p = PrmsAndInfo(c_int(max_iter), c_double(tol), c_int(0), c_double(0),
                    c_int(0))
    if (np.ndim(a) + np.ndim(b) + np.ndim(z) > 1):
        l = [len(x) for x in (a, b, z) if hasattr(x, "__len__")]
        if l[1:] != l[:-1]:
            raise TypeError(
                "if more than one parameter is a numpy array, they have to have the same length"
            )
        a, b, z = [
            np.ones(l[0]) * x if not hasattr(x, "__len__") else x
            for x in (a, b, z)
        ]
        if uselib:
            out = np.zeros(l[0], dtype=np.complex128)
            lib.hyp1f1_all_arr(a.astype(np.complex128),
                               b.astype(np.complex128),
                               z.astype(np.complex128), out, len(out),
                               byref(p))
        if not nofallback and p.prec_warning or not uselib:
            out = np.array(
                [mp.hyp1f1(aa, bb, zz) for aa, bb, zz in zip(a, b, z)],
                dtype=np.complex128)
        return out
    if (np.ndim(a) == 1):
        if uselib:
            out = np.zeros(len(a), dtype=np.complex128)
            lib.hyp1f1_a_arr(a.astype(np.complex128), cmpl(b), cmpl(z), out,
                             len(out), byref(p))
        if not nofallback and p.prec_warning or not uselib:
            out = np.array([mp.hyp1f1(aa, b, z) for aa in a],
                           dtype=np.complex128)
        return out
    elif (np.ndim(b) == 1):
        if uselib:
            out = np.zeros(len(b), dtype=np.complex128)
            lib.hyp1f1_b_arr(cmpl(a), b.astype(np.complex128), cmpl(z), out,
                             len(out), byref(p))
        if not nofallback and p.prec_warning or not uselib:
            out = np.array([mp.hyp1f1(a, bb, z) for bb in b],
                           dtype=np.complex128)
        return out
    elif (np.ndim(z) == 1):
        if uselib:
            out = np.zeros(len(z), dtype=np.complex128)
            lib.hyp1f1_z_arr(cmpl(a), cmpl(b), z.astype(np.complex128), out,
                             len(out), byref(p))
        if not nofallback and p.prec_warning or not uselib:
            out = np.array([mp.hyp1f1(a, b, zz) for zz in z],
                           dtype=np.complex128)
        return out
    else:
        if uselib:
            c = lib.hyp1f1(cmpl(a), cmpl(b), cmpl(z), byref(p))
            out = c.re + 1j * c.im
        if not nofallback and p.prec_warning or not uselib:
            out = np.complex128(mp.hyp1f1(a, b, z))
        return out
Example #27
0
def hyp_mpm_memo(lamda, mu, k, r):
    return mpm.hyp1f1(lamda + r, mu + lamda + r, -k)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 22:21:02 2019

@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)
Example #29
0
def recur_cosin_high_dim(x, m):
    fz = hyp1f1(m / 2., 1. / 2., -x)

    if fz.imag > 0:
        print("hyp1f1 has imaginary part")
    return 2 * (1 - fz.real)
Example #30
0
def blurredMR(x, Ic, Is):
    p = np.zeros(len(x))
    for ii in x:
        p[ii] = 1 / (Is + 1) * (1 + 1 / Is)**(-ii) * np.exp(-Ic / Is) * hyp1f1(
            float(x[ii]) + 1, 1, Ic / (Is**2 + Is))
    return p
Example #31
0
 def test_hyp1f1(self):
     assert_mpmath_equal(_inf_to_nan(sc.hyp1f1),
                         _exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
                         [Arg(-1e5, 1e5), Arg(-1e5, 1e5), Arg()],
                         n=2000)
Example #32
0
def float_mp_hyp1f1(a, b, x):
    try:
        return float(mpmath.hyp1f1(a, b, x))
    except TypeError as e:
        return numpy.nan
Example #33
0
        energetic barrier between the inactive and the active state.
    logC : Bool.
        boolean indicating if the concentration is given in log scale

    Returns
    -------
    p_act : float.
        The probability of the repressor being in the active state.
    '''
    return (1 + R / Nns * p_act(C, ka, ki, epsilon, logC) * np.exp(-eRA))**-1


# TWO-STATE PROMOTER
# define a np.frompyfunc that allows us to evaluate the sympy.mp.math.hyp1f1
np_log_hyp = np.frompyfunc(lambda x, y, z:
                           mpmath.ln(mpmath.hyp1f1(x, y, z, zeroprec=1000)), 3, 1)


def log_p_m_unreg(mRNA, kp_on, kp_off, gm, rm):
    '''
    Computes the log probability lnP(m) for an unregulated promoter,
    i.e. the probability of having m mRNA.

    Parameters
    ----------
    mRNA : float.
        mRNA copy number at which evaluate the probability.
    kp_on : float.
        rate of activation of the promoter in the chemical master equation
    kp_off : float.
        rate of deactivation of the promoter in the chemical master equation
Example #34
0
 def test_hyp1f1_complex(self):
     assert_mpmath_equal(_inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
                         _exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
                         [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()],
                         n=2000)
Example #35
0
def analyze():
    # set parameters
    ky = 0.5*math.pi
    kx0 = -2.0*math.pi
    Omega0 = 0.001
    qshear = 1.5
    kappa2 = 2.0*(2.0-qshear)*Omega0**2.0
    cs = 0.001
    constC = 0.5*(cs**2.0*ky**2.0+kappa2)/(qshear*Omega0*cs*ky)
    c1 = -1.82085106245
    c2 = -0.8208057072217868

    # read results of SSEET_SHWAVE
    fname = 'bin/SSHEET_SHWAVE.hst'
    a = athena_read.hst(fname)
    time1 = a['time']
    dvyc1 = a['dvyc']
    dvys1 = a['dvys']
    nf1 = len(time1)
    norm1c = 0.0
    norm1s = 0.0
    for n in range(nf1):
        tau_ = qshear*Omega0*time1[n]+kx0/ky
        T_ = 1.0j * cmath.sqrt(2.0*cs*ky/(qshear*Omega0))*tau_
        exp_ = cmath.exp(-0.25j*T_*T_)
        fterm_ = exp_*mp.hyp1f1(0.25-0.5j*constC, 0.5, 0.5j*T_*T_)
        first_ = fterm_.real
        exp_ = cmath.exp(0.25j*(math.pi-T_*T_))
        sterm_ = exp_*T_*mp.hyp1f1(0.75-0.5j*constC, 1.5, 0.5j*T_*T_)
        second_ = sterm_.real
        advy = c1*first_+c2*second_
        norm1c += abs(dvyc1[n]-advy)
        norm1s += abs(dvys1[n])
    norm1c /= nf1
    norm1s /= nf1

    # read results of SSEET_SHWAVE_ORB
    fname = 'bin/SSHEET_SHWAVE_ORB.hst'
    b = athena_read.hst(fname)
    time2 = b['time']
    dvyc2 = b['dvyc']
    dvys2 = b['dvys']
    nf2 = len(time2)
    norm2c = 0.0
    norm2s = 0.0
    for n in range(nf2):
        tau_ = qshear*Omega0*time2[n]+kx0/ky
        T_ = 1.0j * cmath.sqrt(2.0*cs*ky/(qshear*Omega0))*tau_
        exp_ = cmath.exp(-0.25j*T_*T_)
        fterm_ = exp_*mp.hyp1f1(0.25-0.5j*constC, 0.5, 0.5j*T_*T_)
        first_ = fterm_.real
        exp_ = cmath.exp(0.25j*(math.pi-T_*T_))
        sterm_ = exp_*T_*mp.hyp1f1(0.75-0.5j*constC, 1.5, 0.5j*T_*T_)
        second_ = sterm_.real
        advy = c1*first_+c2*second_
        norm2c += abs(dvyc2[n]-advy)
        norm2s += abs(dvys2[n])
    norm2c /= nf2
    norm2s /= nf2

    logger.warning('[SSHEET_SHWAVE]: L1-Norm Errors')
    msg = '[SSHEET_SHWAVE]: epsilon_c = {}, epsilon_s = {}'
    flag = True
    logger.warning('[SSHEET_SHWAVE]: w/o Orbital Advection')
    logger.warning(msg.format(norm1c, norm1s))
    if norm1c > 0.2:
        logger.warning('[SSHEET_SHWAVE]: dvyc Error is more than 20%.')
        flag = False
    if norm1s > 0.01:
        logger.warning('[SSHEET_SHWAVE]: dvys Error is more than 1%.')
        flag = False

    logger.warning('[SSHEET_SHWAVE]: w/  Orbital Advection')
    logger.warning(msg.format(norm2c, norm2s))
    if norm1c > 0.2:
        logger.warning('[SSHEET_SHWAVE]: dvyc Error is more than 20%.')
        flag = False
    if norm1s > 0.01:
        logger.warning('[SSHEET_SHWAVE]: dvys Error is more than 1%.')
        flag = False

    return flag
def float_mp_hyp1f1(a, b, x):
    try:
        return float(mpmath.hyp1f1(a, b, x))
    except TypeError as e:
        return numpy.nan
Example #37
0
def reghyp1f1(a, b, z):
    """Regularized Hypergeometric 1F1 function."""
    return float(mpmath.hyp1f1(a, b, z) / mpmath.gamma(b))