jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def update_branch(self, total_reward):
        """
            Update the whole branch from this node to the root with the total reward of the corresponding trajectory.

        :param total_reward: the total reward obtained through a trajectory passing by this node
        """
        self.update(total_reward)
        if self.parent:
            all_childrens = list(self.parent.children.values())
            all_q_values = np.array([child.value for child in all_childrens])
            all_pre_values = np.array([np.log(child.prior) for child in all_childrens])
            logexpqsum = scipy.special.logsumexp(all_q_values + all_pre_values)

            self.parent.update_branch(logexpqsum)
        elif (self.planner.config["Plot"]==1):
            all_childrens = list(self.children.values())
            all_q_values = np.array([child.value for child in all_childrens])
            all_pre_values = np.array([np.log(child.prior) for child in all_childrens])
            logexpqsum = scipy.special.logsumexp(all_q_values + all_pre_values)
            log_pro = all_q_values + all_pre_values - logexpqsum
            pro = np.exp(log_pro)
//  [python]
def test_riccati_jn(self):
        jnrl = (special.sph_jn(1,.2)[0]*.2,special.sph_jn(1,.2)[0]+special.sph_jn(1,.2)[1]*.2)
        ricjn = special.riccati_jn(1,.2)
        assert_array_almost_equal(ricjn,jnrl,8)
//  [python]
def test_riccati_jn(self):
        jnrl = (special.spherical_jn(1,.2)[0]*.2,special.spherical_jn(1,.2)[0]+special.spherical_jn(1,.2)[1]*.2)
        ricjn = special.riccati_jn(1,.2)
        assert_array_almost_equal(ricjn,jnrl,8)
//  [python]
def test_sph_jnyn(self):
        jnyn = r_[special.sph_jn(1,.2) + special.sph_yn(1,.2)]  # tuple addition
        jnyn1 = r_[special.sph_jnyn(1,.2)]
        assert_array_almost_equal(jnyn1,jnyn,9)
//  [python]
def test_sph_jnyn(self):
        jnyn = r_[special.spherical_jn(1,.2) + special.spherical_yn(1,.2)]  # tuple addition
        jnyn1 = r_[special.spherical_jnyn(1,.2)]
        assert_array_almost_equal(jnyn1,jnyn,9)
//  [python]
def _make_data_logmutrel(mutrel):
  K = len(mutrel.rels)
  valid_models = (Models.A_B, Models.B_A, Models.diff_branches)
  invalid_models = (Models.cocluster, Models.garbage)

  alpha = common._EPSILON
  logrels = np.full(mutrel.rels.shape, np.nan)
  logrels[:,:,invalid_models] = -np.inf
  logrels[:,:,valid_models] = np.log(mutrel.rels[:,:,valid_models] + alpha)

  logrels[range(K),range(K),:] = -np.inf
  logrels[range(K),range(K),Models.cocluster] = 0

  logrels[:,:,valid_models] -= np.log(1 + len(valid_models)*alpha)
  assert np.allclose(0, s.logsumexp(logrels, axis=2))
  assert not np.any(np.isnan(logrels))

  logmutrel = Mutrel(rels=logrels, vids=mutrel.vids)
  return logmutrel
//  [python]
def _make_data_logmutrel(mutrel):
  K = len(mutrel.rels)
  valid_models = (Models.A_B, Models.B_A, Models.diff_branches)
  invalid_models = (Models.cocluster, Models.garbage)

  alpha = common._EPSILON
  logrels = np.full(mutrel.rels.shape, np.nan)
  logrels[:,:,invalid_models] = -np.inf
  logrels[:,:,valid_models] = np.log(mutrel.rels[:,:,valid_models] + alpha)

  logrels[range(K),range(K),:] = -np.inf
  logrels[range(K),range(K),Models.cocluster] = 0

  logrels[:,:,valid_models] -= np.log(1 + len(valid_models)*alpha)
  assert np.allclose(0, scipy.special.logsumexp(logrels, axis=2))
  assert not np.any(np.isnan(logrels))

  logmutrel = Mutrel(rels=logrels, vids=mutrel.vids)
  return logmutrel
//  [python]
def test_sph_jn(self):
        s1 = special.sph_jn(2,.2)
        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)
//  [python]
def test_sph_jn(self):
        s1 = special.spherical_jn(2,.2)
        s10 = -s1[1]
        s11 = s1[0]-2.0/0.2*s1[1]
        s12 = s1[1]-3.0/0.2*s1[2]
        assert_array_almost_equal(s1[:3],[0.99334665397530607731,
                                      0.066400380670322230863,
                                      0.0026590560795273856680],12)
        assert_array_almost_equal([s10,s11,s12], [s10,s11,s12],12)
//  [python]
def test_riccati_jn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            jnrl = (special.sph_jn(1,.2)[0]*.2,special.sph_jn(1,.2)[0]+special.sph_jn(1,.2)[1]*.2)
        ricjn = special.riccati_jn(1,.2)
        assert_array_almost_equal(ricjn,jnrl,8)
//  [python]
def test_riccati_jn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            jnrl = (special.spherical_jn(1,.2)[0]*.2,special.spherical_jn(1,.2)[0]+special.spherical_jn(1,.2)[1]*.2)
        ricjn = special.riccati_jn(1,.2)
        assert_array_almost_equal(ricjn,jnrl,8)
//  [python]
def fit_lp(self):
        n, m, L = self.n_, self.m_, self.L_
        
        # Compute equality constraints
        Q = one_hot(np.repeat(np.arange(n), m), num_classes=n)
        R = one_hot(np.tile(np.arange(m), n), num_classes=m)
        A_eq = np.c_[np.c_[Q, R].T, np.zeros((m+n), dtype=int)][:-1]
        b_eq = np.r_[self.a_, self.b_][:, None][:-1]
        # Last equality contraints has been removed
        # because it is redundant
        
        # Compute inequality constraints
        vecC = np.reshape(self.C_, (L, n*m))
        A_ub = np.c_[vecC, -np.ones((L, 1))]
        b_ub = np.zeros((L, 1))
        
        # Cost
        c = np.zeros(n*m+1)
        c[-1] = 1
        
        # Compute the best solution
        res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq)
        PI = res.x[:-1].reshape((n, m))
        
        # Compute alpha
        phi = np.dot(A_ub[:, :-1], res.x[:-1]) # same as np.einsum("ij,kij->k", PI, self.C_)
        alpha = np.exp(phi/self.eta - np.max(phi/self.eta)) / np.sum(np.exp(phi/self.eta - np.max(phi/self.eta)))
        # The best eta is a hot vector, this one is instead a softmax version
        # It is the same as alpha = np.exp(phi/self.eta); alpha /= alpha.sum()
        # But this is more stable and prevent overflow
        
        return PI, alpha
//  [python]
def fit_lp(self):
        n, m, L = self.n_, self.m_, self.L_
        
        # Compute equality constraints
        Q = one_hot(np.repeat(np.arange(n), m), num_classes=n)
        R = one_hot(np.tile(np.arange(m), n), num_classes=m)
        A_eq = np.c_[np.c_[Q, R].T, np.zeros((m+n), dtype=int)][:-1]
        b_eq = np.r_[self.a_, self.b_][:, None][:-1]
        # Last equality contraints has been removed
        # because it is redundant
        
        # Compute inequality constraints
        vecC = np.reshape(self.C_, (L, n*m))
        A_ub = np.c_[vecC, -np.ones((L, 1))]
        b_ub = np.zeros((L, 1))
        
        # Cost
        c = np.zeros(n*m+1)
        c[-1] = 1
        
        # Compute the best solution
        res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq)
        PI = res.x[:-1].reshape((n, m))
        
        # Compute alpha
        phi = np.dot(A_ub[:, :-1], res.x[:-1]) # same as np.einsum("ij,kij->k", PI, self.C_)
        alpha = np.exp(phi/self.eta - logsumexp(phi/self.eta))
        # The best eta is a hot vector, this one is instead a softmax version
        # It is the same as alpha = np.exp(phi/self.eta); alpha /= alpha.sum()
        # But this is more stable and prevent overflow
        
        return PI, alpha
//  [python]
def fit_mog(x, n_components, w=None, tol=1.0e-9, maxiter=float('inf'),
            verbose=False):
    """Fits a mixture of Gaussians to (possibly weighted) data using
    expectation maximization."""
    x = x[:, np.newaxis] if x.ndim == 1 else x
    n_data, n_dim = x.shape
    #
    # Initialize.
    a = np.ones(n_components) / n_components
    ms = rng.randn(n_components, n_dim)
    Ss = [np.eye(n_dim) for _ in range(n_components)]
    iter = 0
    #
    # Calculate log p(x,z), log p(x) and total log likelihood.
    logPxz = np.array([scipy.stats.multivariate_normal.logpdf(
        x, ms[k], Ss[k]) for k in range(n_components)])
    logPxz += np.log(a)[:, np.newaxis]
    logPx = np.log(np.sum(np.exp(logPxz), axis=0))
    loglik_prev = np.mean(logPx) if w is None else np.dot(w, logPx)

    while True:
        #
        # E step
        z = np.exp(logPxz - logPx)
        #
        # M step
        if w is None:
            Nk = np.sum(z, axis=1)
            a = Nk / n_data
            ms = np.dot(z, x) / Nk[:, np.newaxis]
            for k in range(n_components):
                xm = x - ms[k]
                Ss[k] = np.dot(xm.T * z[k], xm) / Nk[k]
        else:
            zw = z * w
            a = np.sum(zw, axis=1)
            ms = np.dot(zw, x) / a[:, np.newaxis]
            for k in range(n_components):
                xm = x - ms[k]
                Ss[k] = np.dot(xm.T * zw[k], xm) / a[k]
        #
        # Calculate log p(x,z), log p(x) and total log likelihood.
        logPxz = np.array([scipy.stats.multivariate_normal.logpdf(
            x, ms[k], Ss[k], allow_singular=True) for k in range(n_components)])
        logPxz += np.log(a)[:, np.newaxis]
        logPx = np.log(np.sum(np.exp(logPxz), axis=0))
        loglik = np.mean(logPx) if w is None else np.dot(w, logPx)
        #
        # Check progress.
        iter += 1
        diff = loglik - loglik_prev
        # assert diff >= 0.0, 'Log likelihood decreased! There is a bug!'
        if verbose:
            print('Iteration = {0}, log likelihood = {1}, diff = {2}'.format(
                iter, loglik, diff))
        if diff < tol or iter > maxiter: break
        loglik_prev = loglik

    return MoG(a=a, ms=ms, Ss=Ss)
//  [python]
def fit_mog(x, n_components, w=None, tol=1.0e-9, maxiter=float('inf'),
            verbose=False):
    """Fits a mixture of Gaussians to (possibly weighted) data using
    expectation maximization."""
    x = x[:, np.newaxis] if x.ndim == 1 else x
    n_data, n_dim = x.shape
    #
    # Initialize.
    a = np.ones(n_components) / n_components
    ms = rng.randn(n_components, n_dim)
    Ss = [np.eye(n_dim) for _ in range(n_components)]
    iter = 0
    #
    # Calculate log p(x,z), log p(x) and total log likelihood.
    logPxz = np.array([scipy.stats.multivariate_normal.logpdf(
        x, ms[k], Ss[k]) for k in range(n_components)])
    logPxz += np.log(a)[:, np.newaxis]
    logPx = logsumexp(logPxz, axis=0)
    loglik_prev = np.mean(logPx) if w is None else np.dot(w, logPx)

    while True:
        #
        # E step
        z = np.exp(logPxz - logPx)
        #
        # M step
        if w is None:
            Nk = np.sum(z, axis=1)
            a = Nk / n_data
            ms = np.dot(z, x) / Nk[:, np.newaxis]
            for k in range(n_components):
                xm = x - ms[k]
                Ss[k] = np.dot(xm.T * z[k], xm) / Nk[k]
        else:
            zw = z * w
            a = np.sum(zw, axis=1)
            ms = np.dot(zw, x) / a[:, np.newaxis]
            for k in range(n_components):
                xm = x - ms[k]
                Ss[k] = np.dot(xm.T * zw[k], xm) / a[k]
        #
        # Calculate log p(x,z), log p(x) and total log likelihood.
        logPxz = np.array([scipy.stats.multivariate_normal.logpdf(
            x, ms[k], Ss[k], allow_singular=True) for k in range(n_components)])
        logPxz += np.log(a)[:, np.newaxis]
        logPx = logsumexp(logPxz, axis=0)
        loglik = np.mean(logPx) if w is None else np.dot(w, logPx)
        #
        # Check progress.
        iter += 1
        diff = loglik - loglik_prev
        # assert diff >= 0.0, 'Log likelihood decreased! There is a bug!'
        if verbose:
            print('Iteration = {0}, log likelihood = {1}, diff = {2}'.format(
                iter, loglik, diff))
        if diff < tol or iter > maxiter: break
        loglik_prev = loglik

    return MoG(a=a, ms=ms, Ss=Ss)
//  [python]
def test_sph_jnyn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            jnyn = r_[special.sph_jn(1,.2) + special.sph_yn(1,.2)]  # tuple addition
            jnyn1 = r_[special.sph_jnyn(1,.2)]
        assert_array_almost_equal(jnyn1,jnyn,9)
//  [python]
def test_sph_jnyn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            jnyn = r_[special.spherical_jn(1,.2) + special.spherical_yn(1,.2)]  # tuple addition
            jnyn1 = r_[special.sph_jnyn(1,.2)]
        assert_array_almost_equal(jnyn1,jnyn,9)
//  [python]
def sph_jn(n, z):
    return scipy.special.sph_jn(n, z)[0][-1]
//  [python]
def sph_jn(n, z):
    return scipy.special.spherical_jn(n, z)[-1]
//  [python]
def sph_jn_(n, x):
    return sph_jn(n.astype('l'), x)[0][-1]
//  [python]
def sph_jn_(n, x):
    return scipy.special.spherical_jn(n.astype('l'), x)[0][-1]
//  [python]
def test_sph_jn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            s1 = special.sph_jn(2,.2)
        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)
//  [python]
def test_sph_jn(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            s1 = special.spherical_jn(2,.2)
        s10 = -s1[1]
        s11 = s1[0]-2.0/0.2*s1[1]
        s12 = s1[1]-3.0/0.2*s1[2]
        assert_array_almost_equal(s1[:3],[0.99334665397530607731,
                                      0.066400380670322230863,
                                      0.0026590560795273856680],12)
        assert_array_almost_equal([s10,s11,s12], [s10,s11,s12],12)
//  [python]
def Gam(n,xx):
    gamma = np.zeros((n),float)
    for nn in range(0,n):
       jn,jpr = scipy.special.sph_jn(nn,xx)  # Spherical Bessel Functions
    gamma = alpha*jpr/jn   # gamma match owavefunctions outside-inside
    return gamma
//  [python]
def Gam(n,xx):
    gamma = np.zeros((n),float)
    for nn in range(0,n):
       jn,jpr = scipy.special.spherical_jn(nn,xx)  # Spherical Bessel Functions
    gamma = alpha*jpr/jn   # gamma match owavefunctions outside-inside
    return gamma
//  [python]
def get_Jn(n, x):
    return array([special.sph_jn(n, xl) for xl in x])
//  [python]
def get_Jn(n, x):
    return array([special.spherical_jn(n, xl) for xl in x])
//  [python]
def phaseshifts(n,alpha,beta):
    gamm = Gam(n,alpha)
    num = np.zeros((n),float); den = np.zeros((n),float)
    jnb,jnpr =   scipy.special.sph_jn(n,beta)
    ynb,yprb =  scipy.special.sph_yn(n,beta)
    for i in range(0,n):
        num1=gamm[i]*jnb[i]
        den1=gamm[i]*ynb[i]
        num[i]=beta*jnpr[i]-num1
        den[i]=beta*yprb[i]-den1  
        td=atan2(num[i],den[i])      
        delta[i]=td
    return delta
//  [python]
def phaseshifts(n,alpha,beta):
    gamm = Gam(n,alpha)
    num = np.zeros((n),float); den = np.zeros((n),float)
    jnb,jnpr =   scipy.special.spherical_jn(n,beta)
    ynb,yprb =  scipy.special.sph_yn(n,beta)
    for i in range(0,n):
        num1=gamm[i]*jnb[i]
        den1=gamm[i]*ynb[i]
        num[i]=beta*jnpr[i]-num1
        den[i]=beta*yprb[i]-den1  
        td=atan2(num[i],den[i])      
        delta[i]=td
    return delta
//  [python]
def Gam(n,xx): # Spherical Bessel ratio
    gamma = np.zeros((n),float)
    for nn in range(0,n): jn,jpr = scipy.special.sph_jn(nn,xx)  
    gamma = alpha*jpr/jn   # gamma match psi outside-inside
    return gamma
//  [python]
def Gam(n,xx): # Spherical Bessel ratio
    gamma = np.zeros((n),float)
    for nn in range(0,n): jn,jpr = scipy.special.spherical_jn(nn,xx)  
    gamma = alpha*jpr/jn   # gamma match psi outside-inside
    return gamma
//  [python]
def Gam(n,xx): # Spherical Bessel ratio
    gamma = np.zeros((n),float)
    for nn in range(0,n):  jn,jpr = scipy.special.sph_jn(nn,xx)  
    gamma = alpha*jpr/jn   # gamma match psi outside-inside
    return gamma
//  [python]
def Gam(n,xx): # Spherical Bessel ratio
    gamma = np.zeros((n),float)
    for nn in range(0,n):  jn,jpr = scipy.special.spherical_jn(nn,xx)  
    gamma = alpha*jpr/jn   # gamma match psi outside-inside
    return gamma
//  [python]
def Woods_SaxonFormFactor(q, A):
    """Calculates Wood-Saxong's nuclcear form factor.

    Ref : SUPERSYMMETRIC DARK MATTER, G. JUNGMAN.
    Ec. 7.31 p. 271.

    @type  q            :      float
    @param q            :      transfer momentum [eV]
    @type  A            :      float
    @param A            :      mass number


    @rtype              :      float
    @return             :      Woods-Saxon's form factor
    """
    s = 1.0 * pc.fermi
    R = 1.2 * A ** (1 / 3) * pc.fermi
    r = np.sqrt(R ** 2 - 5.0 * s ** 2)

    return (3.0 * spe.sph_jn(q * r) / (q * r)) * np.exp(-((q * r) ** 2))
//  [python]
def Woods_SaxonFormFactor(q, A):
    """Calculates Wood-Saxong's nuclcear form factor.

    Ref : SUPERSYMMETRIC DARK MATTER, G. JUNGMAN.
    Ec. 7.31 p. 271.

    @type  q            :      float
    @param q            :      transfer momentum [eV]
    @type  A            :      float
    @param A            :      mass number


    @rtype              :      float
    @return             :      Woods-Saxon's form factor
    """
    s = 1.0 * pc.fermi
    R = 1.2 * A ** (1 / 3) * pc.fermi
    r = np.sqrt(R ** 2 - 5.0 * s ** 2)

    return (3.0 * spe.spherical_jn(0, q * r) / (q * r)) * np.exp(-((q * r) ** 2))
//  [python]
def test_spherical_jn(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(lambda n, z: s.spherical_jn(int(n), z),
                            exception_to_nan(mp_spherical_jn),
                            [IntArg(0, 200), Arg(-1e8, 1e8)],
                            dps=300)
//  [python]
def test_spherical_jn(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n), z),
                            exception_to_nan(mp_spherical_jn),
                            [IntArg(0, 200), Arg(-1e8, 1e8)],
                            dps=300)
//  [python]
def test_riccati_jn(self):
        N, x = 2, 0.2
        S = np.empty((N, N))
        for n in range(N):
            j = s.spherical_jn(n, x)
            jp = s.spherical_jn(n, x, derivative=True)
            S[0,n] = x*j
            S[1,n] = x*jp + j
        assert_array_almost_equal(S, s.riccati_jn(n, x), 8)
//  [python]
def test_riccati_jn(self):
        N, x = 2, 0.2
        S = np.empty((N, N))
        for n in range(N):
            j = special.spherical_jn(n, x)
            jp = special.spherical_jn(n, x, derivative=True)
            S[0,n] = x*j
            S[1,n] = x*jp + j
        assert_array_almost_equal(S, special.riccati_jn(n, x), 8)
//  [python]
def test_spherical_jn_complex(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(lambda n, z: s.spherical_jn(int(n.real), z),
                            exception_to_nan(mp_spherical_jn),
                            [IntArg(0, 200), ComplexArg()])
//  [python]
def test_spherical_jn_complex(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(lambda n, z: sc.spherical_jn(int(n.real), z),
                            exception_to_nan(mp_spherical_jn),
                            [IntArg(0, 200), ComplexArg()])
//  [python]
def spherical_jn_(n, x):
    return s.spherical_jn(n.astype('l'), x)
//  [python]
def spherical_jn_(n, x):
    return spherical_jn(n.astype('l'), x)
//  [python]
def test_spherical_jn(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(
            lambda n, z: s.spherical_jn(int(n), z),
            exception_to_nan(mp_spherical_jn),
            [IntArg(0, 200), Arg(-1e8, 1e8)],
            dps=300,
        )
//  [python]
def test_spherical_jn(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(
            lambda n, z: sc.spherical_jn(int(n), z),
            exception_to_nan(mp_spherical_jn),
            [IntArg(0, 200), Arg(-1e8, 1e8)],
            dps=300,
        )
//  [python]
def wavefunction():  # computes internal r<1 and externalr>1 wavef.
     delta=phaseshifts(n,alpha,beta)
     BL=np.zeros((n),complex)
     Rin=np.zeros((n,ninpts),float) #internal wavefunction r<1 for n partwaves
     Rex=np.zeros((n,nexpts),float)
     for i in range (0,10):     # to find BL for matching
          jnb,jnpr=scipy.special.sph_jn(n,alpha)# SphBessel functions
          jnf,jnfr=scipy.special.sph_jn(n,beta)
          ynb,yprb=r=scipy.special.sph_yn(n,beta)
          cosd=cos(delta[i])
          sind=sin(delta[i])
          zz=complex(cosd,-sind)
          num=jnb[i]*zz
          den=cosd*jnf[i]-sind*ynb[i]
          BL[i]=num/den  # to match internal and external wavefunctions
     intr=1.0/ninpts # 50points inside, increment          
     for i in range(0,n):   # internal wavefunc 
          rin=intr
          for ri in range(0,ninpts): #plot internal func
              alpr=alpha*rin
              jnint,jnintpr=scipy.special.sph_jn(n,alpr)
              Rin[i,ri]=rin*jnint[i]
              rin=rin+intr
     extr=2./nexpts       # from r= 1 to 3   
     for i in range(0,n):   
          rex=1.0
          for rx in range(0,nexpts): #plot internal func
              argu=beta*rex
              jnxt,jnintpr=scipy.special.sph_jn(n,argu)
              nxt,jnintpr=scipy.special.sph_yn(n,argu)
              factr=jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin=sin(delta[i])*factr
              fcos=cos(delta[i])*factr
              Rex[i,rx]=rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              
              rex=rex+extr       
     ai=np.arange(0,1,intr)       
     nwaf=0  #partial wavef to plotCHANGE FOR OTHER WAVES 1 2 3..
     f3=plt.figure()
     ax3=f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])  # only plot s wavefunction
     ae=np.arange(1,3,extr)   
     plt.title("  r * partial wavefunction S ")
     plt.xlabel ("r")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def wavefunction():  # computes internal r<1 and externalr>1 wavef.
     delta=phaseshifts(n,alpha,beta)
     BL=np.zeros((n),complex)
     Rin=np.zeros((n,ninpts),float) #internal wavefunction r<1 for n partwaves
     Rex=np.zeros((n,nexpts),float)
     for i in range (0,10):     # to find BL for matching
          jnb,jnpr=scipy.special.spherical_jn(n,alpha)# SphBessel functions
          jnf,jnfr=scipy.special.spherical_jn(n,beta)
          ynb,yprb=r=scipy.special.spherical_yn(n,beta)
          cosd=cos(delta[i])
          sind=sin(delta[i])
          zz=complex(cosd,-sind)
          num=jnb[i]*zz
          den=cosd*jnf[i]-sind*ynb[i]
          BL[i]=num/den  # to match internal and external wavefunctions
     intr=1.0/ninpts # 50points inside, increment          
     for i in range(0,n):   # internal wavefunc 
          rin=intr
          for ri in range(0,ninpts): #plot internal func
              alpr=alpha*rin
              jnint,jnintpr=scipy.special.spherical_jn(n,alpr)
              Rin[i,ri]=rin*jnint[i]
              rin=rin+intr
     extr=2./nexpts       # from r= 1 to 3   
     for i in range(0,n):   
          rex=1.0
          for rx in range(0,nexpts): #plot internal func
              argu=beta*rex
              jnxt,jnintpr=scipy.special.spherical_jn(n,argu)
              nxt,jnintpr=scipy.special.spherical_yn(n,argu)
              factr=jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin=sin(delta[i])*factr
              fcos=cos(delta[i])*factr
              Rex[i,rx]=rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              
              rex=rex+extr       
     ai=np.arange(0,1,intr)       
     nwaf=0  #partial wavef to plotCHANGE FOR OTHER WAVES 1 2 3..
     f3=plt.figure()
     ax3=f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])  # only plot s wavefunction
     ae=np.arange(1,3,extr)   
     plt.title("  r * partial wavefunction S ")
     plt.xlabel ("r")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def Jn(r, n):
    """
    numerical spherical bessel functions of order n
    """
    return s.spherical_jn(n, r)
//  [python]
def Jn(r, n):
    """
    numerical spherical bessel functions of order n
    """
    return sp.spherical_jn(n, r)
//  [python]
def test_spherical_jn_complex(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(
            lambda n, z: s.spherical_jn(int(n.real), z),
            exception_to_nan(mp_spherical_jn),
            [IntArg(0, 200), ComplexArg()]
        )
//  [python]
def test_spherical_jn_complex(self):
        def mp_spherical_jn(n, z):
            arg = mpmath.mpmathify(z)
            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
                   mpmath.sqrt(2*arg/mpmath.pi))
            if arg.imag == 0:
                return out.real
            else:
                return out

        assert_mpmath_equal(
            lambda n, z: sc.spherical_jn(int(n.real), z),
            exception_to_nan(mp_spherical_jn),
            [IntArg(0, 200), ComplexArg()]
        )
//  [python]
def wavefunction():  # computes internal r<1 and externalr>1 wavef.
     delta = phaseshifts(n,alpha,beta)
     BL = np.zeros((n),complex)
     Rin = np.zeros((n,Nin),float) #internal wavefunction r<1 for n partwaves
     Rex = np.zeros((n,nexpts),float)
     for i in range (0,10):     # to find BL for matching
          jnb,jnpr = scipy.special.sph_jn(n,alpha)# SphBessel functions
          jnf,jnfr = scipy.special.sph_jn(n,beta)
          ynb,yprb = r = scipy.special.sph_yn(n,beta)
          cosd = cos(delta[i])
          sind = sin(delta[i])
          zz = complex(cosd,-sind)
          num = jnb[i]*zz
          den = cosd*jnf[i]-sind*ynb[i]
          BL[i] = num/den  # to match internal and external wavefunctions
     intr = 1.0/Nin # 50points inside, increment          
     for i in range(0,n):   # internal wavefunc 
          rin = intr
          for ri in range(0,Nin): #plot internal func
              alpr = alpha*rin
              jnint,jnintpr = scipy.special.sph_jn(n,alpr)
              Rin[i,ri] = rin*jnint[i]
              rin = rin+intr
     extr = 2./nexpts       # from r =  1 to 3   
     for i in range(0,n):   
          rex = 1.0
          for rx in range(0,nexpts): #plot internal func
              argu = beta*rex
              jnxt,jnintpr = scipy.special.sph_jn(n,argu)
              nxt,jnintpr = scipy.special.sph_yn(n,argu)
              factr = jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin = sin(delta[i])*factr
              fcos = cos(delta[i])*factr
              Rex[i,rx] = rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              
              rex = rex+extr       
     ai = np.arange(0,1,intr)       
     nwaf = 0  #partial wavef to plotCHANGE FOR OTHER WAVES 1 2 3..
     f3 = plt.figure()
     ax3 = f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])  # only plot s wavefunction
     ae = np.arange(1,3,extr)   
     plt.title("  r * partial wavefunction S ")
     plt.xlabel ("r")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def wavefunction():  # computes internal r<1 and externalr>1 wavef.
     delta = phaseshifts(n,alpha,beta)
     BL = np.zeros((n),complex)
     Rin = np.zeros((n,Nin),float) #internal wavefunction r<1 for n partwaves
     Rex = np.zeros((n,nexpts),float)
     for i in range (0,10):     # to find BL for matching
          jnb,jnpr = scipy.special.spherical_jn(n,alpha)# SphBessel functions
          jnf,jnfr = scipy.special.spherical_jn(n,beta)
          ynb,yprb = r = scipy.special.spherical_yn(n,beta)
          cosd = cos(delta[i])
          sind = sin(delta[i])
          zz = complex(cosd,-sind)
          num = jnb[i]*zz
          den = cosd*jnf[i]-sind*ynb[i]
          BL[i] = num/den  # to match internal and external wavefunctions
     intr = 1.0/Nin # 50points inside, increment          
     for i in range(0,n):   # internal wavefunc 
          rin = intr
          for ri in range(0,Nin): #plot internal func
              alpr = alpha*rin
              jnint,jnintpr = scipy.special.spherical_jn(n,alpr)
              Rin[i,ri] = rin*jnint[i]
              rin = rin+intr
     extr = 2./nexpts       # from r =  1 to 3   
     for i in range(0,n):   
          rex = 1.0
          for rx in range(0,nexpts): #plot internal func
              argu = beta*rex
              jnxt,jnintpr = scipy.special.spherical_jn(n,argu)
              nxt,jnintpr = scipy.special.spherical_yn(n,argu)
              factr = jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin = sin(delta[i])*factr
              fcos = cos(delta[i])*factr
              Rex[i,rx] = rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              
              rex = rex+extr       
     ai = np.arange(0,1,intr)       
     nwaf = 0  #partial wavef to plotCHANGE FOR OTHER WAVES 1 2 3..
     f3 = plt.figure()
     ax3 = f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])  # only plot s wavefunction
     ae = np.arange(1,3,extr)   
     plt.title("  r * partial wavefunction S ")
     plt.xlabel ("r")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def wavefunction():             # Compute Psi(<1) & Psi(>1)
     delta = phaseshifts(n,alpha,beta)
     BL = np.zeros((n),complex)
     Rin = np.zeros((n,Nin),float)       # Psi(r<1), nLs
     Rex = np.zeros((n,nexpts),float)
     for i in range (0,10):            # BL for matching
          jnb,jnpr = scipy.special.sph_jn(n,alpha) # SphBes
          jnf,jnfr = scipy.special.sph_jn(n,beta)
          ynb,yprb = r = scipy.special.sph_yn(n,beta)
          cosd = cos(delta[i])
          sind = sin(delta[i])
          zz = complex(cosd,-sind)
          num = jnb[i]*zz
          den = cosd*jnf[i]-sind*ynb[i]
          BL[i] = num/den      # For wavefunction match
     intr = 1.0/Nin                  # Points increment          
     for i in range(0,n):                # Internal Psi 
          rin = intr
          for ri in range(0,Nin):          # PsiIn plot
              alpr = alpha*rin
              jnint,jnintpr = scipy.special.sph_jn(n,alpr)
              Rin[i,ri] = rin*jnint[i]
              rin = rin+intr
     extr = 2./nexpts             
     for i in range(0,n):   
          rex = 1.0
          for rx in range(0,nexpts):     # PsiIn plot
              argu = beta*rex
              jnxt,jnintpr = scipy.special.sph_jn(n,argu)
              nxt,jnintpr = scipy.special.sph_yn(n,argu)
              factr = jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin = sin(delta[i])*factr
              fcos = cos(delta[i])*factr
              Rex[i,rx] = rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              rex = rex+extr       
     ai = np.arange(0,1,intr)       
     nwaf = 0     # PsiL to plot, CHANGE FOR OTHER WAVES
     f3 = plt.figure()
     ax3 = f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])   
     ae = np.arange(1,3,extr)   
     plt.title("$\Psi(r<1), \ \ \Psi(r>1), \ \ \ell = 0$")
     plt.xlabel ("$r$")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def wavefunction():             # Compute Psi(<1) & Psi(>1)
     delta = phaseshifts(n,alpha,beta)
     BL = np.zeros((n),complex)
     Rin = np.zeros((n,Nin),float)       # Psi(r<1), nLs
     Rex = np.zeros((n,nexpts),float)
     for i in range (0,10):            # BL for matching
          jnb,jnpr = scipy.special.spherical_jn(n,alpha) # SphBes
          jnf,jnfr = scipy.special.spherical_jn(n,beta)
          ynb,yprb = r = scipy.special.spherical_yn(n,beta)
          cosd = cos(delta[i])
          sind = sin(delta[i])
          zz = complex(cosd,-sind)
          num = jnb[i]*zz
          den = cosd*jnf[i]-sind*ynb[i]
          BL[i] = num/den      # For wavefunction match
     intr = 1.0/Nin                  # Points increment          
     for i in range(0,n):                # Internal Psi 
          rin = intr
          for ri in range(0,Nin):          # PsiIn plot
              alpr = alpha*rin
              jnint,jnintpr = scipy.special.spherical_jn(n,alpr)
              Rin[i,ri] = rin*jnint[i]
              rin = rin+intr
     extr = 2./nexpts             
     for i in range(0,n):   
          rex = 1.0
          for rx in range(0,nexpts):     # PsiIn plot
              argu = beta*rex
              jnxt,jnintpr = scipy.special.spherical_jn(n,argu)
              nxt,jnintpr = scipy.special.spherical_yn(n,argu)
              factr = jnxt[i]*cos(delta[i])-nxt[i]*sin(delta[i])
              fsin = sin(delta[i])*factr
              fcos = cos(delta[i])*factr
              Rex[i,rx] = rex*(fcos*BL.real[i]-fsin*BL.imag[i] )
              rex = rex+extr       
     ai = np.arange(0,1,intr)       
     nwaf = 0     # PsiL to plot, CHANGE FOR OTHER WAVES
     f3 = plt.figure()
     ax3 = f3.add_subplot(111)
     plt.plot(ai,Rin[nwaf, :])   
     ae = np.arange(1,3,extr)   
     plt.title("$\Psi(r<1), \ \ \Psi(r>1), \ \ \ell = 0$")
     plt.xlabel ("$r$")
     plt.plot(ae,Rex[nwaf, :])
//  [python]
def general_Bnl_integrand(func,kn,lp):
    
    '''
    Standard form of executable integrand in the e.r approximation of the matrix element
    
    *args*:

        - **func**: executable function of position (float), in units of Angstrom
        
        - **kn**: float, norm of the k vector (in inverse Angstrom)
        
        - **lp**: int, final state angular momentum quantum number
    
    *return*:

        - executable function of float (position)
    
    ***
    '''
    
    def lambda_gen():
        return lambda r: (-1.0j)**lp*r**3*s.spherical_jn(lp,r*kn)*func(r)
    
    return lambda_gen()
//  [python]
def general_Bnl_integrand(func,kn,lp):
    
    '''
    Standard form of executable integrand in the e.r approximation of the matrix element
    
    *args*:

        - **func**: executable function of position (float), in units of Angstrom
        
        - **kn**: float, norm of the k vector (in inverse Angstrom)
        
        - **lp**: int, final state angular momentum quantum number
    
    *return*:

        - executable function of float (position)
    
    ***
    '''
    
    def lambda_gen():
        return lambda r: (-1.0j)**lp*r**3*sc.spherical_jn(lp,r*kn)*func(r)
    
    return lambda_gen()
//  [python]
def jl(l,x,d):
    '''
    Spherical Bessel function of the first kind
    d is zero or 1
    '''
    out = np.zeros_like(x)

    k = x<1e-3
    out[k]  = jl_smx(l,x[k],d)
    out[~k] = s.spherical_jn(l,x[~k],derivative=d)

    return out
//  [python]
def jl(l,x,d):
    '''
    Spherical Bessel function of the first kind
    d is zero or 1
    '''
    out = np.zeros_like(x)

    k = x<1e-3
    out[k]  = jl_smx(l,x[k],d)
    out[~k] = scsp.spherical_jn(l,x[~k],derivative=d)

    return out
//  [python]
def radialfft_simpson(r, f, l, qmesh, volume):
  fq = np.zeros_like(qmesh)
  fact = 4.0*np.pi / np.sqrt(volume)
  
  f[r > 10.0] = 0.0
  for iq in range(len(qmesh)):
    q = qmesh[iq]
    bess = scipy.special.spherical_jn(l, r*q)
    aux = f * bess * r
    fq[iq] = scipy.integrate.simps(aux, r)*fact
  return fq
//  [python]
def HankSph(n, kr):
    """Evaluate the spherical Hankel function for order n and vector kr"""
    return s.spherical_jn(n, kr) - 1j*s.spherical_yn(n, kr)
//  [python]
def HankSph(n, kr):
    """Evaluate the spherical Hankel function for order n and vector kr"""
    return scipy.special.spherical_jn(n, kr) - 1j*scipy.special.spherical_yn(n, kr)
//  [python]
def sphereJ(l, x):
    return s.spherical_jn(l, x)
//  [python]
def sphereJ(l, x):
    return spc.spherical_jn(l, x)
//  [python]
def spherical_besselj(nu,x, derivative = 0):
    '''
        Compute spherical bessel function of the first kind, using formula 
        given in: Abramowitz and Stegun, p. 437, 10.1.1
        Derivative calculated using recurrence relation in 
        (https://dlmf.nist.gov/10.51)

        Inputs:
        nu         order of the riccati Bessel's function. Must be a column vector.   
        x          row vector of size parameters at each frequency
        derivative       1, first order derivative ; 0, none.
    '''
    M = max(np.shape(x))
    N = max(np.shape(nu))
    x = np.reshape(np.array(x), (1, M))
    nu = np.reshape(np.array(nu), (N,1))
 
    j = s.spherical_jn(nu, x, derivative)

    return j
//  [python]
def spherical_besselj(nu,x, derivative = 0):
    '''
        Compute spherical bessel function of the first kind, using formula 
        given in: Abramowitz and Stegun, p. 437, 10.1.1
        Derivative calculated using recurrence relation in 
        (https://dlmf.nist.gov/10.51)

        Inputs:
        nu         order of the riccati Bessel's function. Must be a column vector.   
        x          row vector of size parameters at each frequency
        derivative       1, first order derivative ; 0, none.
    '''
    M = max(np.shape(x))
    N = max(np.shape(nu))
    x = np.reshape(np.array(x), (1, M))
    nu = np.reshape(np.array(nu), (N,1))
 
    j = ss.spherical_jn(nu, x, derivative)

    return j
//  [python]
def dphiJ(l, x):
    return s.spherical_jn(l, x) * 0.5 + x * 0.5 * (s.spherical_jn(l - 1, x) - s.spherical_jn(l + 1, x))
//  [python]
def dphiJ(l, x):
    return spc.spherical_jn(l, x) * 0.5 + x * 0.5 * (spc.spherical_jn(l - 1, x) - spc.spherical_jn(l + 1, x))
//  [python]
def spherical_besselh(nu,x, derivative = 0):
    '''
        Compute spherical hankel function of the first kind, using formula 
        given in: Abramowitz and Stegun, p. 437, 10.1.1
        Derivative calculated using recurrence relation in 
        (https://dlmf.nist.gov/10.51)

        Inputs:
        nu         order of the riccati Bessel's function. Must be a column vector.   
        x          row vector of size parameters at each frequency
        derivative       1, first order derivative ; 0, none.
    '''
    M = max(np.shape(x))
    N = max(np.shape(nu))
    x = np.reshape(np.array(x), (1, M))
    nu = np.reshape(np.array(nu), (N,1))
 
    J = s.spherical_jn(nu, x, derivative)
    Y = s.spherical_yn(nu, x, derivative)
    H = J + (1.0j)*Y
    return H
//  [python]
def spherical_besselh(nu,x, derivative = 0):
    '''
        Compute spherical hankel function of the first kind, using formula 
        given in: Abramowitz and Stegun, p. 437, 10.1.1
        Derivative calculated using recurrence relation in 
        (https://dlmf.nist.gov/10.51)

        Inputs:
        nu         order of the riccati Bessel's function. Must be a column vector.   
        x          row vector of size parameters at each frequency
        derivative       1, first order derivative ; 0, none.
    '''
    M = max(np.shape(x))
    N = max(np.shape(nu))
    x = np.reshape(np.array(x), (1, M))
    nu = np.reshape(np.array(nu), (N,1))
 
    J = ss.spherical_jn(nu, x, derivative)
    Y = ss.spherical_yn(nu, x, derivative)
    H = J + (1.0j)*Y
    return H
//  [python]
def spherical_jn_d(n, z):
    """Derivative of the spherical Bessel function of the first kind.

    This is simply a wrapper for `scipy.special.spherical_jn(n, z, True)`, see
    :py:func:`scipy.special.spherical_jn`. It's here to have a consistent way of
    calling the derivative of a (spherical) Bessel or Hankel function.

    Args:
        n (int, array_like): Order
        z (float or complex, array_like): Argument

    Returns:
        float or complex

    References:
        - `DLMF 10.47 <https://dlmf.nist.gov/10.47>`_
        - `DLMF 10.51 <https://dlmf.nist.gov/10.51>`_
    """
    return s.spherical_jn(n, z, True)
//  [python]
def spherical_jn_d(n, z):
    """Derivative of the spherical Bessel function of the first kind.

    This is simply a wrapper for `scipy.special.spherical_jn(n, z, True)`, see
    :py:func:`scipy.special.spherical_jn`. It's here to have a consistent way of
    calling the derivative of a (spherical) Bessel or Hankel function.

    Args:
        n (int, array_like): Order
        z (float or complex, array_like): Argument

    Returns:
        float or complex

    References:
        - `DLMF 10.47 <https://dlmf.nist.gov/10.47>`_
        - `DLMF 10.51 <https://dlmf.nist.gov/10.51>`_
    """
    return spherical_jn(n, z, True)
//  [python]
def sj(n, q):
    return s.spherical_jn(n, q)
//  [python]
def sj(n, q):
    return sp.spherical_jn(n, q)
//  [python]
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 = s.spherical_jn(n.astype(_np.int_), kr)
    return _np.squeeze(J)
//  [python]
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)
//  [python]
def dsj(n, q):
    return s.spherical_jn(n, q, derivative=True)
//  [python]
def dsj(n, q):
    return sp.spherical_jn(n, q, derivative=True)
//  [python]
def test_real(self):
        assert s.spherical_jn(1, 3) == ssc.spherical_jn(1, 3)
//  [python]
def test_real(self):
        assert sc.spherical_jn(1, 3) == ssc.spherical_jn(1, 3)
//  [python]
def calculate_constants():
	""" Calculate needed constants for the wave function """
	global k_e, k_b, td

	k_e = np.sqrt(E/h2m + 0j)  # + Oj added to allow square root calculation for negative numbers
	k_b = np.sqrt((E - V_barrier) / h2m + 0j)

	x_e = barrier_end
	
	td = (k_e*s.spherical_jn(l,k_b*x_e)*s.spherical_jn(l+1,k_e*x_e)-k_b*s.spherical_jn(l,k_e*x_e)*s.spherical_jn(l+1,k_b*x_e)) \
            /(k_e*s.spherical_jn(l,k_b*x_e)*s.spherical_yn(l+1,k_e*x_e)-k_b*s.spherical_yn(l,k_e*x_e)*s.spherical_jn(l+1,k_b*x_e))
//  [python]
def calculate_constants():
	""" Calculate needed constants for the wave function """
	global k_e, k_b, td

	k_e = np.sqrt(E/h2m + 0j)  # + Oj added to allow square root calculation for negative numbers
	k_b = np.sqrt((E - V_barrier) / h2m + 0j)

	x_e = barrier_end
	
	td = (k_e*sp.spherical_jn(l,k_b*x_e)*sp.spherical_jn(l+1,k_e*x_e)-k_b*sp.spherical_jn(l,k_e*x_e)*sp.spherical_jn(l+1,k_b*x_e)) \
            /(k_e*sp.spherical_jn(l,k_b*x_e)*sp.spherical_yn(l+1,k_e*x_e)-k_b*sp.spherical_yn(l,k_e*x_e)*sp.spherical_jn(l+1,k_b*x_e))
//  [python]
def test_complex(self):
        assert s.spherical_jn(1, 3 + 1j) == ssc.spherical_jn(1, 3 + 1j)
//  [python]
def test_complex(self):
        assert sc.spherical_jn(1, 3 + 1j) == ssc.spherical_jn(1, 3 + 1j)
//  [python]
def test_non_zero(self):
        assert isclose(sc.spherical_jn_d(2, 3 + 4j), s.spherical_jn(2, 3 + 4j, True))
//  [python]
def test_non_zero(self):
        assert isclose(sc.spherical_jn_d(2, 3 + 4j), ssc.spherical_jn(2, 3 + 4j, True))
//  [python]
def test_zero(self):
        assert isclose(sc.spherical_jn_d(0, 3), ssc.spherical_jn(0, 3, 1))
//  [python]
def test_zero(self):
        assert isclose(sc.spherical_jn_d(0, 3), ssc.spherical_jn(0, 3, True))
//  [python]
def wave_function_value(x):
        """ Returns value of wave function in x """
        if x < barrier_end:
#            return np.sin(k_b * x)/k_b #  l=0 only
            return s.spherical_jn(l, k_b * x) * x / k_b**l
        else:  # x > barrier_end
#            return np.sin(k_e * x) / np.sin(k_e * barrier_end) * np.sin(k_b * barrier_end)/k_b  # l=0 only
            return (s.spherical_jn(l, k_e * x) - td * s.spherical_yn(l, k_e * x)) \
                 / (s.spherical_jn(l, k_e * barrier_end) - td * s.spherical_yn(l, k_e * barrier_end)) \
                 *  s.spherical_jn(l, k_b * barrier_end) * x/k_b**l
//  [python]
def wave_function_value(x):
        """ Returns value of wave function in x """
        if x < barrier_end:
#            return np.sin(k_b * x)/k_b #  l=0 only
            return sp.spherical_jn(l, k_b * x) * x / k_b**l
        else:  # x > barrier_end
#            return np.sin(k_e * x) / np.sin(k_e * barrier_end) * np.sin(k_b * barrier_end)/k_b  # l=0 only
            return (sp.spherical_jn(l, k_e * x) - td * sp.spherical_yn(l, k_e * x)) \
                 / (sp.spherical_jn(l, k_e * barrier_end) - td * sp.spherical_yn(l, k_e * barrier_end)) \
                 *  sp.spherical_jn(l, k_b * barrier_end) * x/k_b**l
//  [python]
def test_zero_arg_2(self):
        assert isclose(sc.spherical_jn_d(1, 0), s.spherical_jn(1, 0, True))
//  [python]
def test_zero_arg_2(self):
        assert isclose(sc.spherical_jn_d(1, 0), ssc.spherical_jn(1, 0, True))
//  [python]
def test_zero_arg(self):
        assert isclose(sc.spherical_jn_d(3, 0), s.spherical_jn(3, 0, True))
//  [python]
def test_zero_arg(self):
        assert isclose(sc.spherical_jn_d(3, 0), ssc.spherical_jn(3, 0, True))
//  [python]
def test_0(self):
        expect = (
            -1j
            * (s.spherical_jn(2, 4 + 1j) + 1j * ssc.spherical_yn(2, 4 + 1j))
            * np.sqrt(15 / (2 * 3 * 8 * np.pi))
            * np.exp(1j)
            * np.array([0, 1j * np.cos(2), -np.cos(4)])
        )
        assert np.sum(np.abs(sc.vsw_M(2, 1, 4 + 1j, 2, 1) - expect)) < EPS
//  [python]
def test_0(self):
        expect = (
            -1j
            * (ssc.spherical_jn(2, 4 + 1j) + 1j * ssc.spherical_yn(2, 4 + 1j))
            * np.sqrt(15 / (2 * 3 * 8 * np.pi))
            * np.exp(1j)
            * np.array([0, 1j * np.cos(2), -np.cos(4)])
        )
        assert np.sum(np.abs(sc.vsw_M(2, 1, 4 + 1j, 2, 1) - expect)) < EPS
//  [python]
def test_1(self):
        expect = (
            -1j
            * s.spherical_jn(2, 4 + 1j)
            * np.sqrt(15 / (2 * 3 * 8 * np.pi))
            * np.exp(1j)
            * np.array([0, 1j * np.cos(2), -np.cos(4)])
        )
        assert np.sum(np.abs(sc.vsw_rM(2, 1, 4 + 1j, 2, 1) - expect)) < EPS