Example #1
0
 def fun(Ecomplex):
     E = Ecomplex[0] + 1j*Ecomplex[1]
     q = sqrt(2*(E+V0))
     g = sqrt(-2*E)
     y = q*spherical_jn(l, q*a, True)*spherical_kn(l,g*a) \
       - g*spherical_kn(l, g*a, True)*spherical_jn(l,q*a)
     return array([real(y), imag(y)])
 def test_spherical_jn_yn_cross_product_2(self):
     # http://dlmf.nist.gov/10.50.E3
     n = np.array([1, 5, 8])
     x = np.array([0.1, 1, 10])
     left = spherical_jn(n + 2, x) * spherical_yn(n, x) - spherical_jn(n, x) * spherical_yn(n + 2, x)
     right = (2 * n + 3) / x ** 3
     assert_allclose(left, right)
Example #3
0
 def test_spherical_jn_yn_cross_product_1(self):
     # https://dlmf.nist.gov/10.50.E3
     n = np.array([1, 5, 8])
     x = np.array([0.1, 1, 10])
     left = (spherical_jn(n + 1, x) * spherical_yn(n, x) -
             spherical_jn(n, x) * spherical_yn(n + 1, x))
     right = 1/x**2
     assert_allclose(left, right)
Example #4
0
def test_mie_internal_coeffs():
    if os.name == 'nt':
        raise SkipTest()

    m = 1.5 + 0.1j
    x = 50.
    n_stop = miescatlib.nstop(x)
    al, bl = miescatlib.scatcoeffs(m, x, n_stop)
    cl, dl = miescatlib.internal_coeffs(m, x, n_stop)
    n = np.arange(n_stop)+1
    jlx = spherical_jn(n, x)
    jlmx = spherical_jn(n, m*x)
    hlx = jlx + 1.j * spherical_yn(n, x)

    assert_allclose(cl, (jlx - hlx * bl) / jlmx, rtol = 1e-6, atol = 1e-6)
    assert_allclose(dl, (jlx - hlx * al)/ (m * jlmx), rtol = 1e-6, atol = 1e-6)
Example #5
0
def spline_int_jlqr(l, qmax, rcut, numq=None, numr=None):
    r"""
    Compute :math:`j_n(z) = \int_0^{rcut} r^2 j_l(qr) dr`
    where :math:`j_l` is the Spherical Bessel function.

    Args:
        l: Angular momentum
        qmax: Max :math:`|q|` in integral in Ang-1
        rcut: Sphere radius in Angstrom.
        numq: Number of q-points in qmesh.
        numr: Number of r-points for integration.

    Return:
        Spline object.
    """
    numq = numq if numq is not None else _DEFAULTS["numq"]
    numr = numr if numr is not None else _DEFAULTS["numr"]

    rs = np.linspace(0, rcut, num=numr)
    r2 = rs ** 2
    qmesh = np.linspace(0, qmax, num=numq)
    values = []
    for q in qmesh:
        qrs = q * rs
        #qrs = 2 * np.pi * q * rs
        ys = spherical_jn(l, qrs) * r2
        intg = simps(ys, x=rs)
        values.append(intg)

    return UnivariateSpline(qmesh, values, s=0)
Example #6
0
 def test_spherical_jn_inf_complex(self):
     # https://dlmf.nist.gov/10.52.E3
     n = 7
     x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
     with suppress_warnings() as sup:
         sup.filter(RuntimeWarning, "invalid value encountered in multiply")
         assert_allclose(spherical_jn(n, x), np.array([0, 0, inf*(1+1j)]))
 def test_spherical_jn_exact(self):
     # http://dlmf.nist.gov/10.49.E3
     # Note: exact expression is numerically stable only for small
     # n or z >> n.
     x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
     assert_allclose(spherical_jn(2, x),
                     (-1/x + 3/x**3)*sin(x) - 3/x**2*cos(x))
Example #8
0
def spbessel(n, kr):
    """Spherical Bessel function (first kind) of order n at kr

    Parameters
    ----------
    n : array_like
       Order
    kr: array_like
       Argument

    Returns
    -------
    J : complex float
       Spherical Bessel
    """
    n, kr = scalar_broadcast_match(n, kr)

    if _np.any(n < 0) | _np.any(kr < 0) | _np.any(_np.mod(n, 1) != 0):
        J = _np.zeros(kr.shape, dtype=_np.complex_)

        kr_non_zero = kr != 0
        J[kr_non_zero] = _np.lib.scimath.sqrt(_np.pi / 2 / kr[kr_non_zero]) * besselj(n[kr_non_zero] + 0.5,
                                                                                      kr[kr_non_zero])
        J[_np.logical_and(kr == 0, n == 0)] = 1
    else:
        J = scy.spherical_jn(n.astype(_np.int), kr)
    return _np.squeeze(J)
Example #9
0
def scattering_amplitude_energy(Evec, U, R, theta, lmax=30):
    costheta = cos(theta)
    P = lpmv(0, arange(lmax), costheta) # Legendre polynomial
    f = zeros(len(Evec), dtype=complex)
    for ll in range(lmax):
        kR = sqrt(2*Evec)*R
        qR = sqrt(2*(Evec+U))*R

        ## Spherical bessels/hankels, and their derivatives
        jl  = spherical_jn(ll, qR)
        jlp = spherical_jn(ll, qR, derivative=True)
        hl  = spherical_jn(ll, kR) + 1j*spherical_yn(ll, kR)
        hlp = spherical_jn(ll, kR, True) + 1j*spherical_yn(ll, kR, True)

        delt = 0.5*pi - angle((kR*hlp*jl - qR*hl*jlp)/R)
        f += (-0.5j*R/kR) * (exp(2j*delt)-1) * (2*ll+1) * P[ll]
    return f
Example #10
0
def scattering_amplitude_theta(E, U, R, thetavec, lmax=30):
    lvec = arange(lmax)

    P = zeros((len(lvec), len(thetavec))) # Legendre polynomials
    for jj in range(len(lvec)):
        P[jj,:] = lpmv(0, lvec[jj], cos(thetavec))

    kR = sqrt(2*E)*R
    qR = sqrt(2*(E+U))*R

    ## Spherical bessels/hankels, and their derivatives
    jl  = spherical_jn(lvec, qR)
    jlp = spherical_jn(lvec, qR, derivative=True)
    hl  = spherical_jn(lvec, kR) + 1j*spherical_yn(lvec, kR)
    hlp = spherical_jn(lvec, kR, True) + 1j*spherical_yn(lvec, kR, True)

    ## Phase shifts for each l component
    delt = 0.5*pi - angle((kR*hlp*jl - qR*hl*jlp)/R)
    coef = (exp(2j*delt)-1) * (2*lvec+1)
    return (-0.5j*R/kR) * dot(coef, P)
Example #11
0
def spherical_hn2(n, z):
    r"""Spherical Hankel function of 2nd kind.

    Defined as http://dlmf.nist.gov/10.47.E6,

    .. math::

        \hankel{2}{n}{z} = \sqrt{\frac{\pi}{2z}}
        \Hankel{2}{n + \frac{1}{2}}{z},

    where :math:`\Hankel{2}{n}{\cdot}` is the Hankel function of the
    second kind and n-th order, and :math:`z` its complex argument.

    Parameters
    ----------
    n : array_like
        Order of the spherical Hankel function (n >= 0).
    z : array_like
        Argument of the spherical Hankel function.

    """
    return spherical_jn(n, z) - 1j * spherical_yn(n, z)
    def test_sph_jn(self):
        s1 = np.empty((2, 3))
        x = 0.2

        s1[0][0] = spherical_jn(0, x)
        s1[0][1] = spherical_jn(1, x)
        s1[0][2] = spherical_jn(2, x)
        s1[1][0] = spherical_jn(0, x, derivative=True)
        s1[1][1] = spherical_jn(1, x, derivative=True)
        s1[1][2] = spherical_jn(2, x, derivative=True)

        s10 = -s1[0][1]
        s11 = s1[0][0] - 2.0 / 0.2 * s1[0][1]
        s12 = s1[0][1] - 3.0 / 0.2 * s1[0][2]
        assert_array_almost_equal(
            s1[0], [0.99334665397530607731, 0.066400380670322230863, 0.0026590560795273856680], 12
        )
        assert_array_almost_equal(s1[1], [s10, s11, s12], 12)
Example #13
0
def jn_zeros(n, k, method="sympy", dps=15):
    """
    Zeros of the spherical Bessel function of the first kind.

    This returns an array of zeros of jn up to the k-th zero.

    * method = "sympy": uses :func:`mpmath.besseljzero`
    * method = "scipy": uses the
      `SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_
      and
      `newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_
      to find all
      roots, which is faster than computing the zeros using a general
      numerical solver, but it requires SciPy and only works with low
      precision floating point numbers.  [The function used with
      method="sympy" is a recent addition to mpmath, before that a general
      solver was used.]

    Examples
    ========

    >>> from sympy import jn_zeros
    >>> jn_zeros(2, 4, dps=5)
    [5.7635, 9.095, 12.323, 15.515]

    See Also
    ========

    jn, yn, besselj, besselk, bessely
    """
    from math import pi

    if method == "sympy":
        from mpmath import besseljzero
        from mpmath.libmp.libmpf import dps_to_prec
        from sympy import Expr
        prec = dps_to_prec(dps)
        return [Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec),
                                              int(l)), prec)
                for l in range(1, k + 1)]
    elif method == "scipy":
        from scipy.optimize import newton
        try:
            from scipy.special import spherical_jn
            f = lambda x: spherical_jn(n, x)
        except ImportError:
            from scipy.special import sph_jn
            f = lambda x: sph_jn(n, x)[0][-1]
    else:
        raise NotImplementedError("Unknown method.")

    def solver(f, x):
        if method == "scipy":
            root = newton(f, x)
        else:
            raise NotImplementedError("Unknown method.")
        return root

    # we need to approximate the position of the first root:
    root = n + pi
    # determine the first root exactly:
    root = solver(f, root)
    roots = [root]
    for i in range(k - 1):
        # estimate the position of the next root using the last root + pi:
        root = solver(f, root + pi)
        roots.append(root)
    return roots
Example #14
0
 def f(self, n, z):
     return spherical_jn(n, z)
Example #15
0
 def test_spherical_jn_recurrence_complex(self):
     # https://dlmf.nist.gov/10.51.E1
     n = np.array([1, 2, 3, 7, 12])
     x = 1.1 + 1.5j
     assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x),
                     (2*n + 1)/x*spherical_jn(n, x))
Example #16
0
 def test_spherical_jn_inf_real(self):
     # http://dlmf.nist.gov/10.52.E3
     n = 6
     x = np.array([-inf, inf])
     assert_allclose(spherical_jn(n, x), np.array([0, 0]))
Example #17
0
 def f(x):
     return spherical_jn(n, x)
Example #18
0
 def test_spherical_jn_large_arg_2(self):
     # https://github.com/scipy/scipy/issues/1641
     # Reference value computed using mpmath, via
     # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
     assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05)
Example #19
0
def xi(n, z):
    # Riccati-Bessel function of third kind
    return z * (spherical_jn(n, z) + 1j * spherical_yn(n, z))
Example #20
0
def spherical_jn_(n, x):
    return spherical_jn(n.astype('l'), x)
Example #21
0
def Jn(r, n):
    """
    numerical spherical bessel functions of order n
    """
    return sp.spherical_jn(n, r)
Example #22
0
 def sphj(n, z):
     return spherical_jn(range(n), z)
def jprimel(kchi, l):
    return spherical_jn(n=l, z=kchi, derivative=True)
Example #24
0
def fluid_sphere(f, Radius, Range, Rho_w, Rho_b, Theta, c_w, c_b):
    #compute wavelength and wave number in the external fluid
    K_ext = k(c_w, f)  # wave number

    #compute wavenumber inside the scattering body
    K_int = k(c_b, f)

    #set convergence parameters
    ConvLim = 1e-10
    MaxCount = 200

    #wavenumbers
    kr = K_ext * Range  #wavenumber at range
    ka = K_ext * Radius  #wvenumber radius
    kdasha = K_int * Radius  #wavenumber radius inside

    #density and soundspeed contrasts
    g = Rho_b / Rho_w  #density contrast
    h = c_b / c_w  #sound velocity contrast
    rho_c = Rho_w * c_w

    #check for convergence and set starting parameters
    Done = False
    Count = 0
    m = 0
    while Done == False:
        # build vector of theta angles and ranges inside/outside of sphere
        #Theta = np.arange(0.0,np.pi,np.pi/180)
        CosTheta = np.cos(Theta)
        #Ext_Range = np.arange(1.5 * Radius, Radius, -0.5 * Radius / 20)
        #Int_Range = np.arange(Radius,0,-Radius/40)

        ###compute spherical bessel fucntions with ka, k'a, kr, k'r
        ###use functions from scipy.special

        #Bessel functions first degree
        Jm_kr = ss.spherical_jn(m, kr)
        Jm_ka = ss.spherical_jn(m, ka)
        Jm_kdasha = ss.spherical_jn(m, kdasha)

        #bessel functions second degree
        Nm_Kr = ss.spherical_yn(m, kr)
        Nm_Ka = ss.spherical_yn(m, ka)

        #First degree derivate bessel functions
        Alpham_kdasha = (2 * m + 1) * ss.spherical_jn(
            m, kdasha, derivative=True)
        Alpham_ka = (2 * m + 1) * ss.spherical_jn(m, ka, derivative=True)
        Alpham_kr = (2 * m + 1) * ss.spherical_jn(m, kr, derivative=True)

        #Second degree derivate bessel functions
        Betam_ka = (2 * m + 1) * ss.spherical_yn(m, ka, derivative=True)
        Betam_kr = (2 * m + 1) * ss.spherical_yn(m, kr, derivative=True)

        # Compute Legendre Polynom, dependent on Theta
        Pm = legendreP(m, CosTheta)

        # Calculate Cm for the current m value - independant of theta
        Cm = (( Alpham_kdasha / Alpham_ka) * (Nm_Ka / Jm_kdasha) - \
              (Betam_ka / Alpham_ka) * g * h) / ((Alpham_kdasha / Alpham_ka) * \
              (Jm_ka / Jm_kdasha) - g * h)

        # Use Cm coefficient to calculate Am explcitely and then Bm from this
        Am = -((-1j)**m) * (2 * m + 1) / (1 + 1j * Cm)

        # Now use Cm to calculate current 'm' value scattered pressure contribution
        ThisPs = -(((-1j)**m) * (2 * m + 1) / (1 + 1j * Cm)) * Pm * \
                   (Jm_kr + 1j * Nm_Kr)
        ThisPi = ((-1j)**m) * (2 * m + 1) * Pm * Jm_kr
        ThisTS = ((-1)**m) * (2 * m + 1) / (1 + 1j * Cm)

        # exterior domain particle velocity
        ThisVel = (-1j / rho_c) * (Am / (2 * m + 1)) * Pm * (Alpham_kr +\
                  1j * Betam_kr)
        ThisVel_Inc = (-1j / rho_c) * ((-1j)**m) * Pm * Alpham_kr
        if m == 0:
            Ps = ThisPs
            Pi = ThisPi
            TS = ThisTS
            Vel = ThisVel
            Vel_Inc = ThisVel_Inc
        else:
            Ps = Ps + ThisPs
            Pi = Pi + ThisPi
            TS = TS + ThisTS
            Vel = Vel + ThisVel
            Vel_Inc = Vel_Inc + ThisVel_Inc
        m += 1
        Count += 1
        if max(abs(ThisPs)) < ConvLim and m > 10:
            Done = True
        elif Count > MaxCount:
            Done = True
            print('Convergence failure in FluidSphereScat')

        IsBad = np.isnan(Ps)
        Ps[IsBad] = 0

    #Calculate final TS after summation is complete
    TS = (2 / ka)**2 * abs(TS)**2 * (np.pi * Radius * Radius)
    TS = 10 * np.log10(TS / (4 * np.pi))

    #print('Backscatter TS of the sphere is %.2f dB re 1m^2'%TS)
    return (TS)
Example #25
0
#         func_k[i] = int_0*int_0*p_nl[i]/(k_nl[i]*k_nl[i])

#     k_min = np.log(k_nl.min())
#     k_max = np.log(k_nl.max())
#     term = integrate.quad(interp1d, k_min, k_max,args=(k_nl,func_k), epsrel = 1e-6)[0]
#     units = l*(l+1)*1e-12*term*omega_m*omega_m/(9.*np.pi*np.pi*chi_Rmax*chi_Rmax)
#     print(l,units)
#     C_l[l-1] = units

C_l1 = np.zeros(2601)  #eq 25 in the paper
func_k1 = np.zeros(nklin_cmb)

for l in range(0, 2601):
    print(l)
    for i, kloop in enumerate(klin_cmb):
        func_k1[i] = kloop*kloop*special.spherical_jn(l,kloop*chi_Rmax)*P_0[i]*\
                    (special.spherical_jn(l,kloop*chi_Rmax)*l - special.spherical_jn(l+1,kloop*chi_Rmax)*kloop*chi_Rmax)\
                    /(8.*np.pi*np.pi*np.pi)
        # func_k1[i] = p_nl_R[i]*kloop*kloop*special.spherical_jn(l,kloop*chi_Rmax)*\
        #             (special.spherical_jn(l,kloop*chi_Rmax)*l - special.spherical_jn(l+1,kloop*chi_Rmax)*kloop*chi_Rmax)\
        #             /(np.power(2.*np.pi,3.))
    k_min = np.log(klin_cmb.min())
    k_max = np.log(klin_cmb.max())
    term = integrate.quad(interp1d,
                          k_min,
                          k_max,
                          args=(klin_cmb, func_k1),
                          epsrel=1e-6)[0]
    C_l1[l] = term

print(chi_Rmax)
Example #26
0
def hankel(n,z,derivative=False):
    return special.spherical_jn(n,z,derivative) + 1j*special.spherical_yn(n,z,derivative)
Example #27
0
def riccati_1_single(n, x):
    """Riccati_1, but only a single n value"""
    jn = special.spherical_jn(n, x)
    jnp = special.spherical_jn(n, x, derivative=True)

    return np.array([x * jn, jn + x * jnp])
Example #28
0
#!/usr/bin/env python3
#
# Plots the power spectra and Fourier-space biases for the HI.
#
import numpy as np
import os, sys
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, HuberRegressor
from scipy.optimize import minimize

from scipy.interpolate import InterpolatedUnivariateSpline as ius
from scipy.integrate import simps
from scipy.special import spherical_jn

j0 = lambda x: spherical_jn(0, x)
#

sys.path.append('../')
from uvbg import mfpathz

from matplotlib import rc, rcParams, font_manager

rcParams['font.family'] = 'serif'
fsize = 12
fontmanage = font_manager.FontProperties(family='serif',
                                         style='normal',
                                         size=fsize,
                                         weight='normal',
                                         stretch='normal')
font = {
    'family': fontmanage.get_family()[0],
def spherical_hn1(n, z):

    return sp.spherical_jn(
        n, z, derivative=False) + 1j * sp.spherical_yn(n, z, derivative=False)
Example #30
0
 def test_spherical_jn_at_zero(self):
     # http://dlmf.nist.gov/10.52.E1
     # But note that n = 0 is a special case: j0 = sin(x)/x -> 1
     n = np.array([0, 1, 2, 5, 10, 100])
     x = 0
     assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0]))
 def f(self, n, z):
     return spherical_jn(n, z)
Example #32
0
 def test_spherical_jn_large_arg_1(self):
     # https://github.com/scipy/scipy/issues/2165
     # Reference value computed using mpmath, via
     # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
     assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747)
 def test_spherical_jn_d_zero(self):
     n = np.array([1, 2, 3, 7, 15])
     assert_allclose(spherical_jn(n, 0, derivative=True), np.zeros(5))
Example #34
0
 def test_spherical_jn_inf_complex(self):
     # http://dlmf.nist.gov/10.52.E3
     n = 7
     x = np.array([-inf + 0j, inf + 0j, inf * (1 + 1j)])
     assert_allclose(spherical_jn(n, x), np.array([0, 0, inf * (1 + 1j)]))
 def test_spherical_jn_inf_complex(self):
     # http://dlmf.nist.gov/10.52.E3
     n = 7
     x = np.array([-inf + 0j, inf + 0j, inf * (1 + 1j)])
     assert_allclose(spherical_jn(n, x), np.array([0, 0, inf * (1 + 1j)]))
Example #36
0
 def test_spherical_jn_d_zero(self):
     n = np.array([1, 2, 3, 7, 15])
     assert_allclose(spherical_jn(n, 0, derivative=True), np.zeros(5))
 def test_spherical_jn_large_arg_2(self):
     # https://github.com/scipy/scipy/issues/1641
     # Reference value computed using mpmath, via
     # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
     assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05)
Example #38
0
 def df(self, n, z):
     return spherical_jn(n, z, derivative=True)
Example #39
0
def spherical_jn_(n, x):
    return spherical_jn(n.astype('l'), x)
Example #40
0
def _create_parameters(package):
    # Start by copying everything in the package
    parameters = {**package}

    # Set up the random seed
    if parameters['seed'] is None:
        parameters['seed'] = random.randrange(2**32 - 1)
    np.random.seed(parameters['seed'])

    #########################
    # Background quantities #
    #########################
    phi0 = parameters['phi0']
    phi0dot = parameters['phi0dot']
    infmodel = parameters['infmodel']
    rho = compute_rho(phi0, phi0dot, infmodel)
    # Estimate Hubble
    H0 = compute_hubble(rho, 0)

    # Construct Rmax and kappa
    parameters['Rmax'] = Rmax = parameters['Rmaxfactor'] / H0
    parameters['kappa'] = kappa = parameters['kappafactor'] * H0

    ####################
    # Wavenumber grids #
    ####################
    k_max_factor = parameters['k_max_factor']
    num_k_modes = int(np.ceil(Rmax * kappa * k_max_factor / np.pi))
    if not parameters['hartree'] or num_k_modes < 2:
        num_k_modes = 2
    parameters['num_k_modes'] = num_k_modes
    k_grids = get_jn_roots(1, num_k_modes)

    # Iterate through all wavenumbers, dividing by Rmax
    # to turn the roots into wavenumbers
    for ell in range(2):
        k_grids[ell] /= Rmax
    parameters['k_grids'] = k_grids

    # Make a tuple storing the number of wavenumbers for each ell
    parameters['total_wavenumbers'] = total_wavenumbers = 2 * num_k_modes - 1

    # Construct wavenumbers squared
    k2_grids = [grid * grid for grid in k_grids]

    # Construct a list of all wavenumbers in order, and their squares
    all_wavenumbers = np.concatenate(k_grids)
    all_wavenumbers2 = all_wavenumbers**2

    # Compute Gaussian suppression for wavenumbers
    factor = 2 * kappa**2
    gaussian_profile = [
        np.exp(-k_grids[0]**2 / factor),
        np.exp(-k_grids[1]**2 / factor)
    ]

    # Compute the normalizations associated with each wavenumber
    normalizations = [None for ell in range(2)]
    factor = np.sqrt(2) / Rmax**1.5
    for ell in range(2):
        normalizations[ell] = factor / np.abs(
            spherical_jn(ell + 1, k_grids[ell] * Rmax))
    parameters['normalizations'] = normalizations

    # Compute 1 / |j_{ell + 1}(k R)|^2, which we'll need for gradient Hartree corrections
    denom_fac = [None for ell in range(2)]
    for ell in range(2):
        denom_fac[ell] = 1 / np.abs(spherical_jn(ell + 1,
                                                 k_grids[ell] * Rmax))**2

    ###############################
    # Construct mode coefficients #
    ###############################
    poscoeffs = [None, [None] * 3]
    velcoeffs = [None, [None] * 3]

    if parameters['perturbBD']:
        # perturb away from Bunch-Davies initial conditions slightly
        # create range for draws of parameters to initialized modes
        delta_min, delta_max = parameters['perturbranges']['delta']
        gamma_min, gamma_max = parameters['perturbranges']['gamma']

        # random coefficients for l = 0 modes
        delta0 = np.random.uniform(delta_min, delta_max, len(k_grids[0]))
        if parameters['perturblogarithmic']:
            gamma0 = np.exp(
                np.random.uniform(np.log(gamma_min), np.log(gamma_max),
                                  len(k_grids[0])))
        else:
            gamma0 = np.random.uniform(gamma_min, gamma_max, len(k_grids[0]))
        alpha0 = 1 / gamma0

        # attach coefficients
        poscoeffs[0] = alpha0 / np.sqrt(2 * k_grids[0])
        velcoeffs[0] = np.sqrt(k_grids[0] / 2) * (-1j * gamma0 + delta0 -
                                                  (H0 * alpha0 / k_grids[0]))

        if parameters['l1modeson']:
            for i in range(3):
                # random coefficients for l = 1 modes
                delta1 = np.random.uniform(delta_min, delta_max,
                                           len(k_grids[1]))
                if parameters['perturblogarithmic']:
                    gamma1 = np.exp(
                        np.random.uniform(np.log(gamma_min), np.log(gamma_max),
                                          len(k_grids[1])))
                else:
                    gamma1 = np.random.uniform(gamma_min, gamma_max,
                                               len(k_grids[1]))
                alpha1 = 1 / gamma1

                poscoeffs[1][i] = alpha1 / np.sqrt(2 * k_grids[1])
                velcoeffs[1][i] = np.sqrt(
                    k_grids[1] / 2) * (-1j * gamma1 + delta1 -
                                       (H0 * alpha1 / k_grids[1]))
        else:
            for i in range(3):
                poscoeffs[1][i] = np.zeros_like(k_grids[1])
                velcoeffs[1][i] = np.zeros_like(k_grids[1])
    else:
        # run standard Bunch-Davies initial conditions
        poscoeffs[0] = 1 / np.sqrt(2 * k_grids[0])
        velcoeffs[0] = np.sqrt(k_grids[0] / 2) * (-1j - H0 / k_grids[0])
        if parameters['l1modeson']:
            for i in range(3):
                poscoeffs[1][i] = 1 / np.sqrt(2 * k_grids[1])
                velcoeffs[1][i] = np.sqrt(
                    k_grids[1] / 2) * (-1j - H0 / k_grids[1])
        else:
            for i in range(3):
                poscoeffs[1][i] = np.zeros_like(k_grids[1])
                velcoeffs[1][i] = np.zeros_like(k_grids[1])

    ###########################
    # Construct EOMParameters #
    ###########################
    parameters['eomparams'] = EOMParameters(
        Rmax, kappa, num_k_modes, parameters['total_wavenumbers'],
        parameters['hartree'], infmodel, k_grids, k2_grids, all_wavenumbers,
        all_wavenumbers2, denom_fac, gaussian_profile, poscoeffs, velcoeffs)

    ################################
    # Construct Initial Conditions #
    ################################
    # The starting value of the scale factor
    a = 1
    # phi0 and phi0dot have been obtained already

    # Initialize the fields phi_{nlm}
    phiA = np.ones(total_wavenumbers)
    phidotA = np.zeros(total_wavenumbers)
    phiB = np.zeros(total_wavenumbers)
    phidotB = np.ones(total_wavenumbers)

    # Compute the Hartree corrections
    if parameters['hartree']:
        phi2pt, phi2ptdt, phi2ptgrad = compute_hartree(phiA, phidotA, phiB,
                                                       phidotB,
                                                       parameters['eomparams'])
        deltarho2 = compute_deltarho2(a, phi0, phi2pt, phi2ptdt, phi2ptgrad,
                                      infmodel)
    else:
        phi2pt, phi2ptdt, phi2ptgrad = (0, 0, 0)
        deltarho2 = 0

    # Compute adot from Hubble
    adot = compute_hubble(rho, deltarho2) * a

    # Compute Hdot
    Hdot = compute_hubbledot(a, phi0dot, phi2ptdt, phi2ptgrad)

    # Make sure that we don't have a denominator blowup in computing the initial psi values
    carefulfactor = 10  # The maximum dimensionless boost that a psi mode can get from the denominator
    badk2 = Hdot + 2 / 3 * phi2ptgrad
    if parameters['rescale']:
        if badk2 < 0 and np.any(
                np.abs(all_wavenumbers**2 + badk2) < H0**2 / carefulfactor):
            # We have a mode that is getting an artificial boost
            # Report an issue so we can try again
            raise BadK()

    # Now compute the initial values for the psi fields
    psiA, psiB = compute_initial_psi(a, adot, phi0, phi0dot, phiA, phidotA,
                                     phiB, phidotB, phi2pt, phi2ptdt,
                                     phi2ptgrad, parameters['eomparams'])

    # Pack all the initial data together
    parameters['initial_data'] = pack(a, phi0, phi0dot, phiA, phidotA, psiA,
                                      phiB, phidotB, psiB)

    # Return everything
    return parameters
Example #41
0
    def j1d(z): return spherical_jn(1, z, derivative=True)
except ImportError:
def scatteringcoefficients(mhu, mhu_p, lamda, lamda_p, rho, rho_p, Flag):
    rho_ratio = rho_p / rho
    R_0 = 200e-6
    Nf = 1000
    f = np.linspace(1.0e5, 3.0e6, Nf)

    #c_L_i = m.sqrt((lamda + 2*mhu)/rho)
    #c_T_i = m.sqrt(mhu/rho)
    T1 = np.zeros((2, Nf), dtype=complex)
    T2 = np.zeros((4, Nf), dtype=complex)
    KKTi = np.zeros((1, Nf), dtype=complex)
    KKLi = np.zeros((1, Nf), dtype=complex)
    resonance = np.zeros((1, Nf), dtype=complex)

    for iterator in range(0, Nf):
        omega = 2 * m.pi * f[iterator]
        lame1 = 3.6e9 + 0.1e9 * (
            (omega * 5000e-9)**2 -
            1j * omega * 5000e-9) / (1 + (omega * 5000e-9)**2) + 0.3e9 * (
                (omega * 500e-9)**2 -
                1j * omega * 500e-9) / (1 + (omega * 500e-9)**2) + 0.25e9 * (
                    (omega * 50e-9)**2 -
                    1j * omega * 50e-9) / (1 + (omega * 50e-9)**2) + 0.3e9 * (
                        (omega * 8e-9)**2 -
                        1j * omega * 8e-9) / (1 + (omega * 8e-9)**2)
        lame2 = 1.05e9 + 0.2e9 * (
            (omega * 5000e-9)**2 -
            1j * omega * 5000e-9) / (1 + (omega * 5000e-9)**2) + 0.15e9 * (
                (omega * 500e-9)**2 -
                1j * omega * 500e-9) / (1 + (omega * 500e-9)**2) - 0.1e9 * (
                    (omega * 14e-9)**2 -
                    1j * omega * 14e-9) / (1 + (omega * 14e-9)**2) + 0.15e9 * (
                        (omega * 50e-9)**2 -
                        1j * omega * 50e-9) / (1 + (omega * 50e-9)**2)
        lamda = lame1
        mhu = lame2
        c_L_i = cm.sqrt((lame1 + 2 * lame2) / rho)
        c_T_i = cm.sqrt(lame2 / rho)

        alphaL_f = 0.1 + 0.25 / 2000000 * f[iterator]
        alphaS_f = 0.05 + 0.1 / 2000000 * f[iterator]

        k_L_i = omega / c_L_i + 1j * alphaL_f
        k_T_i = omega / c_T_i + 1j * alphaS_f
        K_L = k_L_i * R_0
        K_T = k_T_i * R_0
        k_L_p = omega * m.sqrt(rho_p / (lamda_p + 2 * mhu_p))
        k_T_p = omega * m.sqrt(rho_p / mhu_p)
        K_L_p = k_L_p * R_0
        K_T_p = k_T_p * R_0

        KKTi[:, iterator] = K_T
        KKLi[:, iterator] = K_L

        if Flag == "T":
            n = 1
            hnL_n = spherical_hn1(n, K_L)
            hnT_n = spherical_hn1(n, K_T)
            hnL_1n = spherical_hn1(n + 1, K_L)
            hnT_1n = spherical_hn1(n + 1, K_T)

            jnL_n = sp.spherical_jn(n, K_L)
            jnT_n = sp.spherical_jn(n, K_T)
            jnL_np = sp.spherical_jn(n, K_L_p)
            jnT_np = sp.spherical_jn(n, K_T_p)

            jnL_1n = sp.spherical_jn(n + 1, K_L)
            jnT_1n = sp.spherical_jn(n + 1, K_T)
            jnL_1np = sp.spherical_jn(n + 1, K_L_p)
            jnT_1np = sp.spherical_jn(n + 1, K_T_p)

            U_L_p = n * jnL_np - K_L_p * jnL_1np
            U_T_p = n * (n + 1) * jnT_np
            U_L = n * hnL_n - K_L * hnL_1n
            U_T = n * (n + 1) * hnT_n
            U_I = n * (n + 1) * jnT_n

            V_L_p = jnL_np
            V_T_p = (1 + n) * jnT_np - K_T * jnT_1np
            V_L = hnL_n
            V_T = (1 + n) * hnT_n - K_T * hnT_1n
            V_I = (1 + n) * jnT_n - K_T * jnT_1n

            W_S = 1j * (K_T * hnT_n)
            W_S_p = 1j * (K_T_p * jnT_np)
            W_I = 1j * (K_T * jnT_n)

            SS_L_p = (2 * n * (n - 1) * mhu_p - (lamda_p + 2 * mhu_p) *
                      K_L_p**2) * jnL_np + 4 * mhu_p * K_L_p * jnL_1np
            SS_T_p = 2 * n * (n + 1) * mhu_p * (
                (n - 1) * jnT_np - K_T_p * jnT_1np)
            SS_L = (
                2 * n * (n - 1) * mhu -
                (lamda + 2 * mhu) * K_L**2) * hnL_n + 4 * mhu * K_L * hnL_1n
            SS_T = 2 * n * (n + 1) * mhu * ((n - 1) * hnT_n - K_T * hnT_1n)
            SS_I = 2 * n * (n + 1) * mhu * ((n - 1) * jnT_n - K_T * jnT_1n)

            Tau_L_p = 2 * mhu_p * ((n - 1) * jnL_np - K_L_p * jnL_1np)
            Tau_L = 2 * mhu * ((n - 1) * hnL_n - K_L * hnL_1n)
            Tau_T_p = mhu_p * (
                (2 * n**2 - 2 - K_T_p**2) * jnT_np + 2 * K_T_p * jnT_1np)
            Tau_T = mhu * ((2 * n**2 - 2 - K_T**2) * hnT_n + 2 * K_T * hnT_1n)
            Tau_I = mhu * ((2 * n**2 - 2 - K_T**2) * jnT_n + 2 * K_T * jnT_1n)

            Sig_S_p = 1j * mhu_p * K_T_p * ((n - 1) * jnT_np - K_T_p * jnT_1np)
            Sig_S = 1j * mhu * K_T * ((n - 1) * hnT_n - K_T * hnT_1n)
            Sig_I = 1j * mhu * K_T * ((n - 1) * jnT_n - K_T * jnT_1n)

            #Build system of equations
            Designmatrix_LHS = np.array([[U_L, U_T, -U_L_p, -U_T_p],
                                         [V_L, V_T, -V_L_p, -V_T_p],
                                         [SS_L, SS_T, -SS_L_p, -SS_T_p],
                                         [Tau_L, Tau_T, -Tau_L_p, -Tau_T_p]])
            Designmatrix_RHS = np.array([U_I, V_I, SS_I, Tau_I])

            t1 = np.linalg.solve(Designmatrix_LHS, -Designmatrix_RHS)
            T2[:, iterator] = t1

            Designmatrix2_LHS = np.array([[W_S, -W_S_p], [Sig_S, -Sig_S_p]])
            Designmatrix2_RHS = np.array([W_I, Sig_I])
            t2 = np.linalg.solve(Designmatrix2_LHS, -Designmatrix2_RHS)
            T1[:, iterator] = t2

        if Flag == "L":

            f_res = (3 * c_T_i * m.sqrt(8 * rho_ratio)) / (4 * m.pi * R_0 *
                                                           (2 * rho_ratio + 1))
            omega_res = 2 * m.pi * f_res
            K_L_i_res = R_0 * omega_res / c_L_i
            #K_T_i_res = R_0*omega_res/c_T_i
            resonance[:, iterator] = K_L_i_res

            for n in range(0, 2):
                hnL_n = spherical_hn1(n, K_L)
                hnT_n = spherical_hn1(n, K_T)
                hnL_1n = spherical_hn1((n + 1), K_L)
                hnT_1n = spherical_hn1((n + 1), K_T)

                jnL_n = sp.spherical_jn(n, K_L)
                jnT_n = sp.spherical_jn(n, K_T)
                jnL_np = sp.spherical_jn(n, K_L_p)
                jnT_np = sp.spherical_jn(n, K_T_p)

                jnL_1n = sp.spherical_jn((n + 1), K_L)
                jnT_1n = sp.spherical_jn((n + 1), K_T)
                jnL_1np = sp.spherical_jn((n + 1), K_L_p)
                jnT_1np = sp.spherical_jn((n + 1), K_T_p)

                U_L_p = n * jnL_np - K_L_p * jnL_1np
                U_T_p = n * (n + 1) * jnT_np
                U_L = n * hnL_n - K_L * hnL_1n
                U_T = n * (n + 1) * hnT_n
                U_I = n * jnL_n - K_L * jnL_1n

                V_L_p = jnL_np
                V_T_p = (1 + n) * jnT_np - K_T * jnT_1np
                V_L = hnL_n
                V_T = (1 + n) * hnT_n - K_T * hnT_1n
                V_I = jnL_n

                SS_L_p = (2 * n * (n - 1) * mhu_p - (lamda_p + 2 * mhu_p) *
                          K_L_p**2) * jnL_np + 4 * mhu_p * K_L_p * jnL_1np
                SS_T_p = 2 * n * (n + 1) * mhu_p * (
                    (n - 1) * jnT_np - K_T_p * jnT_1np)
                SS_L = (2 * n * (n - 1) * mhu - (lamda + 2 * mhu) *
                        K_L**2) * hnL_n + 4 * mhu * K_L * hnL_1n
                SS_T = 2 * n * (n + 1) * mhu * ((n - 1) * hnT_n - K_T * hnT_1n)
                SS_I = (2 * n * (n - 1) * mhu - (lamda + 2 * mhu) *
                        K_L**2) * jnL_n + 4 * mhu * K_L * jnL_1n

                Tau_L_p = 2 * mhu_p * ((n - 1) * jnL_np - K_L_p * jnL_1np)
                Tau_L = 2 * mhu * ((n - 1) * hnL_n - K_L * hnL_1n)
                Tau_T_p = mhu_p * (
                    (2 * n**2 - 2 - K_T_p**2) * jnT_np + 2 * K_T_p * jnT_1np)
                Tau_T = mhu * (
                    (2 * n**2 - 2 - K_T**2) * hnT_n + 2 * K_T * hnT_1n)
                Tau_I = 2 * mhu * ((n - 1) * jnL_n - K_L * jnL_1n)

                if n == 0:
                    LHS = np.array([[U_L, -U_L_p], [SS_L, -SS_L_p]])
                    RHS = np.array([U_I, SS_I])

                    a0 = np.linalg.solve(LHS, -RHS)
                    T1[:, iterator] = a0
                elif n == 1:
                    LHS1 = np.array([[U_L, U_T, -U_L_p, -U_T_p],
                                     [V_L, V_T, -V_L_p, -V_T_p],
                                     [SS_L, SS_T, -SS_L_p, -SS_T_p],
                                     [Tau_L, Tau_T, -Tau_L_p, -Tau_T_p]])

                    RHS1 = np.array([U_I, V_I, SS_I, Tau_I])

                    a1 = np.linalg.solve(LHS1, -RHS1)

                    T2[:, iterator] = a1

    if Flag == "T":
        coefficients = np.vstack((KKTi[0, :], T1[0, :], T2[0, :], T2[1, :]))
        print(
            "Transverse incident wave, scatteringcoefficients are ordered as [K_T , T1_SS , T1_TL , T1_TT] in np.array"
        )
    if Flag == "L":
        coefficients = np.vstack(
            (KKLi[0, :], T1[0, :], T2[0, :], T2[1, :], resonance[0, :]))
        print(
            "Longitudinal incident wave, scatteringcoefficients are ordered as [K_L , T0_LL , T1_LL , T1_LT, K_Lires] in np.array"
        )

    return coefficients
Example #43
0
def riccati_jn(n, x, derivative=False):
    if derivative == True:
        return spherical_jn(
            n, x, derivative=False) + x * spherical_jn(n, x, derivative=True)
    else:
        return x * spherical_jn(n, x, derivative=False)
 def df(self, n, z):
     return spherical_jn(n, z, derivative=True)
Example #45
0
def ricc1_psi(x):
    return (x * sp.spherical_jn(1, x, 0))
 def test_spherical_jn_recurrence_real(self):
     # http://dlmf.nist.gov/10.51.E1
     n = np.array([1, 2, 3, 7, 12])
     x = 0.12
     assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x), (2 * n + 1) / x * spherical_jn(n, x))
Example #47
0
def ricc1_psi_ch(x):
    return (sp.spherical_jn(1, x, 0) + x * sp.spherical_jn(1, x, 1))
 def test_spherical_jn_inf_real(self):
     # http://dlmf.nist.gov/10.52.E3
     n = 6
     x = np.array([-inf, inf])
     assert_allclose(spherical_jn(n, x), np.array([0, 0]))
Example #49
0
def ricc1_xi(x):
    return (x * (sp.spherical_jn(1, x, 0) + 1j * sp.spherical_yn(1, x, 0)))
 def test_spherical_jn_large_arg_1(self):
     # https://github.com/scipy/scipy/issues/2165
     # Reference value computed using mpmath, via
     # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
     assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747)
Example #51
0
def ricc1_xi_ch(x):
    return ((sp.spherical_jn(1, x, 0) + 1j * sp.spherical_yn(1, x, 0)) + x *
            (sp.spherical_jn(1, x, 1) + 1j * sp.spherical_yn(1, x, 1)))
 def test_spherical_jn_at_zero(self):
     # http://dlmf.nist.gov/10.52.E1
     # But note that n = 0 is a special case: j0 = sin(x)/x -> 1
     n = np.array([0, 1, 2, 5, 10, 100])
     x = 0
     assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0]))
Example #53
0
def jn_zeros(n, k, method="sympy", dps=15):
    """
    Zeros of the spherical Bessel function of the first kind.

    This returns an array of zeros of jn up to the k-th zero.

    * method = "sympy": uses :func:`mpmath.besseljzero`
    * method = "scipy": uses the
      `SciPy's sph_jn <http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.jn_zeros.html>`_
      and
      `newton <http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html>`_
      to find all
      roots, which is faster than computing the zeros using a general
      numerical solver, but it requires SciPy and only works with low
      precision floating point numbers.  [The function used with
      method="sympy" is a recent addition to mpmath, before that a general
      solver was used.]

    Examples
    ========

    >>> from sympy import jn_zeros
    >>> jn_zeros(2, 4, dps=5)
    [5.7635, 9.095, 12.323, 15.515]

    See Also
    ========

    jn, yn, besselj, besselk, bessely
    """
    from math import pi

    if method == "sympy":
        from mpmath import besseljzero
        from mpmath.libmp.libmpf import dps_to_prec
        from sympy import Expr
        prec = dps_to_prec(dps)
        return [
            Expr._from_mpmath(besseljzero(S(n + 0.5)._to_mpmath(prec), int(l)),
                              prec) for l in range(1, k + 1)
        ]
    elif method == "scipy":
        from scipy.optimize import newton
        try:
            from scipy.special import spherical_jn
            f = lambda x: spherical_jn(n, x)
        except ImportError:
            from scipy.special import sph_jn
            f = lambda x: sph_jn(n, x)[0][-1]
    else:
        raise NotImplementedError("Unknown method.")

    def solver(f, x):
        if method == "scipy":
            root = newton(f, x)
        else:
            raise NotImplementedError("Unknown method.")
        return root

    # we need to approximate the position of the first root:
    root = n + pi
    # determine the first root exactly:
    root = solver(f, root)
    roots = [root]
    for i in range(k - 1):
        # estimate the position of the next root using the last root + pi:
        root = solver(f, root + pi)
        roots.append(root)
    return roots
Example #54
0
    def j1(z): return spherical_jn(1, z)

    def j1d(z): return spherical_jn(1, z, derivative=True)
Example #55
0
def psi(n, z):
    # Riccati-Bessel function of first kind
    return z * spherical_jn(n, z)
Example #56
0
def psiDz(n, z):
    # Derivative of Riccati-Bessel function of first kind
    return spherical_jn(n, z) + z * spherical_jn(n, z, 1)
Example #57
0
    c_L_p = m.sqrt((lamda_p + 2 * mhu_p) / rho_p)
    c_T_p = m.sqrt(mhu_p / rho_p)
    k_L_p = omega * m.sqrt(rho_p / (lamda_p + 2 * mhu_p))
    k_T_p = omega * m.sqrt(rho_p / mhu_p)
    K_L_p = k_L_p * R_0
    K_T_p = k_T_p * R_0
    #Loop over two values of n

    for n in range(1, 2):

        hnL_n = spherical_hn1(n, K_L)
        hnT_n = spherical_hn1(n, K_T)
        hnL_1n = spherical_hn1(n + 1, K_L)
        hnT_1n = spherical_hn1(n + 1, K_T)

        jnL_n = sp.spherical_jn(n, K_L)
        jnT_n = sp.spherical_jn(n, K_T)
        jnL_np = sp.spherical_jn(n, K_L_p)
        jnT_np = sp.spherical_jn(n, K_T_p)

        jnL_1n = sp.spherical_jn(n + 1, K_L)
        jnT_1n = sp.spherical_jn(n + 1, K_T)
        jnL_1np = sp.spherical_jn(n + 1, K_L_p)
        jnT_1np = sp.spherical_jn(n + 1, K_T_p)

        U_L_p = n * jnL_np - K_L_p * jnL_1np
        U_T_p = n * (n + 1) * jnT_np
        U_L = n * hnL_n - K_L * hnL_1n
        U_T = n * (n + 1) * hnT_n
        U_I = n * (n + 1) * jnT_n