jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def phi_eval(self, factors, indeces, phi, lmbda):
        """
        Evaluate the phi_k functions at the points factors[i]*lmbda, for all k in indeces

        Arguments:
            factors: list of factors to multiply lmbda with.
            indeces: list of indeces k for the phi_k functions. Since we use the integral formulation, k=0 is not allowed (not needed neither).
            phi: an instance of mesh with shape (len(factors),len(indeces),*lmbda.shape) (i.e., some space to store the results)
                 it will filled as: phi[i,k][:] = phi_{indeces[k]}(factor[i]*lmbda[:])
            lmbda: dtype_u: the value of lmbda
        """

        assert 0 not in indeces, "phi_0 is not implemented, since the integral definition is not valid for k=0."

        # the quadrature rule used to evaluate the phi functions as integrals. This is not the same as the one used in the ESDC method!!!!
        c = self.phi_coll.nodes
        b = self.phi_coll.weights

        k = np.array(indeces)
        km1_fac = scipy.special.factorial(k - 1)  # (k-1)!

        # Here we use the quadrature rule to approximate the integral
        # phi_{k}(factor[i]*lmbda[:,:])= \int_0^1 e^{(1-s)*factor[i]*lambda[:,:]}*s^{k-1}/(k-1)! ds

        # First, compute e^((1-c[j])*factor[i]*lmbda[:]) for nodes c[j] on the quadrature rule and all factors[i]
        exp_terms = np.exp(((1.0 - c[None, :, None, None]) * factors[:, None, None, None]) * lmbda[None, None, :, :])
        # Then, compute the terms c[j]^{k-1}/(k-1)! for all nodes c[j] and all k and multiply with the weights b[j]
        wgt_tmp = (b[:, None] * c[:, None] ** (k[None, :] - 1)) / km1_fac[None, :]
        # Finally, compute the integral by summing over the quadrature nodes
        phi[:] = np.sum(wgt_tmp[None, :, :, None, None] * exp_terms[:, :, None, :, :], axis=1)
//  [python]
def test_factorialx_scalar_return_type(self, exact):
        assert np.isscalar(s.factorial(1, exact=exact))
        assert np.isscalar(s.factorial2(1, exact=exact))
        assert np.isscalar(s.factorialk(1, 3, exact=True))
//  [python]
def test_factorialx_scalar_return_type(self, exact):
        assert np.isscalar(special.factorial(1, exact=exact))
        assert np.isscalar(special.factorial2(1, exact=exact))
        assert np.isscalar(special.factorialk(1, 3, exact=True))
//  [python]
def test_orthonormality_probabilists_hermite_polynomial(self):
        rho = 0.
        degree = 2
        probability_measure = True
        ab = hermite_recurrence(
            degree+1, rho, probability=probability_measure)

        x, w = np.polynomial.hermite.hermgauss(degree+1)
        # transform rule to probablity weight
        # function w=1/sqrt(2*PI)exp(-x^2/2)
        x *= np.sqrt(2.0)
        w /= np.sqrt(np.pi)
        p = evaluate_orthonormal_polynomial_1d(x, degree, ab)

        # Note if using pecos the following is done (i.e. ptFactpr=sqrt(2)),
        # but if I switch to using orthonormal recursion, used here, in Pecos
        # then I will need to set ptFactor=1.0 as done implicitly above
        p_exact = np.asarray(
            [1+0.*x, x, x**2-1]).T/np.sqrt(s.factorial(np.arange(degree+1)))
        assert np.allclose(p, p_exact)

        # test orthogonality
        exact_moments = np.zeros((degree+1))
        exact_moments[0] = 1.0
        assert np.allclose(np.dot(p.T, w), exact_moments)
        # test orthonormality
        print(np.allclose(np.dot(p.T*w, p), np.eye(degree+1)))
        assert np.allclose(np.dot(p.T*w, p), np.eye(degree+1))
//  [python]
def test_orthonormality_probabilists_hermite_polynomial(self):
        rho = 0.
        degree = 2
        probability_measure = True
        ab = hermite_recurrence(
            degree+1, rho, probability=probability_measure)

        x, w = np.polynomial.hermite.hermgauss(degree+1)
        # transform rule to probablity weight
        # function w=1/sqrt(2*PI)exp(-x^2/2)
        x *= np.sqrt(2.0)
        w /= np.sqrt(np.pi)
        p = evaluate_orthonormal_polynomial_1d(x, degree, ab)

        # Note if using pecos the following is done (i.e. ptFactpr=sqrt(2)),
        # but if I switch to using orthonormal recursion, used here, in Pecos
        # then I will need to set ptFactor=1.0 as done implicitly above
        p_exact = np.asarray(
            [1+0.*x, x, x**2-1]).T/np.sqrt(sp.factorial(np.arange(degree+1)))
        assert np.allclose(p, p_exact)

        # test orthogonality
        exact_moments = np.zeros((degree+1))
        exact_moments[0] = 1.0
        assert np.allclose(np.dot(p.T, w), exact_moments)
        # test orthonormality
        print(np.allclose(np.dot(p.T*w, p), np.eye(degree+1)))
        assert np.allclose(np.dot(p.T*w, p), np.eye(degree+1))
//  [python]
def test_factorialx_negative(self, exact, n):
        assert_equal(s.factorial(n, exact=exact), 0)
        assert_equal(s.factorial2(n, exact=exact), 0)
        assert_equal(s.factorialk(n, 3, exact=True), 0)
//  [python]
def test_factorialx_negative(self, exact, n):
        assert_equal(special.factorial(n, exact=exact), 0)
        assert_equal(special.factorial2(n, exact=exact), 0)
        assert_equal(special.factorialk(n, 3, exact=True), 0)
//  [python]
def test_orthonormality_laguerre_polynomial(self):
        a = 3
        rho = a-1
        degree = 2
        probability_measure = True
        ab = laguerre_recurrence(
            rho, degree+1, probability=probability_measure)
        print(ab)
        from scipy import stats
        x = stats.gamma(a).rvs(int(1e6))
        w = np.ones(x.shape[0])/x.shape[0]
        p = evaluate_orthonormal_polynomial_1d(x, degree, ab)

        p_exact = np.asarray(
            [1+0.*x, -(-x+rho+1),
             0.5*x**2-x*(rho+2)+(rho+1)*(rho+2)/2]).T[:, :degree+1]
        p_exact /= np.sqrt(sp.gamma(np.arange(degree+1)+rho+1)/sp.factorial(
            np.arange(degree+1))/sp.gamma(rho+1))
        #print(p_exact.T.dot(w), 'p')
        #print(np.dot(p_exact.T*w, p_exact)-np.eye(degree+1))
        assert np.allclose(p, p_exact)

        # test orthogonality
        exact_moments = np.zeros((degree+1))
        exact_moments[0] = 1.0
        #print(np.dot(p.T, w)-exact_moments)
        assert np.allclose(np.dot(p.T, w), exact_moments, atol=2e-3)
        # test orthonormality
        # print(np.dot(p.T*w, p)-np.eye(degree+1))
        assert np.allclose(np.dot(p.T*w, p), np.eye(degree+1), atol=2e-2)
//  [python]
def test_factorialx_negative_array(self, exact):
        assert_func = assert_array_equal if exact else assert_allclose
        # Consistent output for n < 0
        assert_func(s.factorial([-5, -4, 0, 1], exact=exact),
                    [0, 0, 1, 1])
        assert_func(s.factorial2([-5, -4, 0, 1], exact=exact),
                    [0, 0, 1, 1])
        assert_func(s.factorialk([-5, -4, 0, 1], 3, exact=True),
                    [0, 0, 1, 1])
//  [python]
def test_factorialx_negative_array(self, exact):
        assert_func = assert_array_equal if exact else assert_allclose
        # Consistent output for n < 0
        assert_func(special.factorial([-5, -4, 0, 1], exact=exact),
                    [0, 0, 1, 1])
        assert_func(special.factorial2([-5, -4, 0, 1], exact=exact),
                    [0, 0, 1, 1])
        assert_func(special.factorialk([-5, -4, 0, 1], 3, exact=True),
                    [0, 0, 1, 1])
//  [python]
def test_factorialx_array_dimension(self, dim, exact):
        n = np.array(5, ndmin=dim)
        exp = {1: 120, 2: 15, 3: 10}
        assert_allclose(s.factorial(n, exact=exact),
                        np.array(exp[1], ndmin=dim))
        assert_allclose(s.factorial2(n, exact=exact),
                        np.array(exp[2], ndmin=dim))
        assert_allclose(s.factorialk(n, 3, exact=True),
                        np.array(exp[3], ndmin=dim))
//  [python]
def test_factorialx_array_dimension(self, dim, exact):
        n = np.array(5, ndmin=dim)
        exp = {1: 120, 2: 15, 3: 10}
        assert_allclose(special.factorial(n, exact=exact),
                        np.array(exp[1], ndmin=dim))
        assert_allclose(special.factorial2(n, exact=exact),
                        np.array(exp[2], ndmin=dim))
        assert_allclose(special.factorialk(n, 3, exact=True),
                        np.array(exp[3], ndmin=dim))
//  [python]
def test_factorial_accuracy(self, n):
        # Compare exact=True vs False, i.e. that the accuracy of the
        # approximation is better than the specified tolerance.

        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
        # need to cast exact result to float due to numpy/numpy#21220
        assert_allclose(float(s.factorial(n, exact=True)),
                        s.factorial(n, exact=False), rtol=rtol)
        assert_allclose(s.factorial([n], exact=True).astype(float),
                        s.factorial([n], exact=False), rtol=rtol)
//  [python]
def test_factorial_accuracy(self, n):
        # Compare exact=True vs False, i.e. that the accuracy of the
        # approximation is better than the specified tolerance.

        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
        # need to cast exact result to float due to numpy/numpy#21220
        assert_allclose(float(special.factorial(n, exact=True)),
                        special.factorial(n, exact=False), rtol=rtol)
        assert_allclose(special.factorial([n], exact=True).astype(float),
                        special.factorial([n], exact=False), rtol=rtol)
//  [python]
def test_factorialx_nan(self, content, exact):
        # scalar
        assert s.factorial(content, exact=exact) is np.nan
        assert s.factorial2(content, exact=exact) is np.nan
        assert s.factorialk(content, 3, exact=True) is np.nan
        # array-like (initializes np.array with default dtype)
        if content is not np.nan:
            # None causes object dtype, which is not supported; as is datetime
            with pytest.raises(ValueError, match="Unsupported datatype.*"):
                s.factorial([content], exact=exact)
        elif exact:
            # cannot use `is np.nan` see https://stackoverflow.com/a/52124109
            with pytest.warns(DeprecationWarning, match="Non-integer array.*"):
                assert np.isnan(s.factorial([content], exact=exact)[0])
        else:
            assert np.isnan(s.factorial([content], exact=exact)[0])
        # factorial{2,k} don't support array case due to dtype constraints
        with pytest.raises(ValueError, match="factorial2 does not support.*"):
            s.factorial2([content], exact=exact)
        with pytest.raises(ValueError, match="factorialk does not support.*"):
            s.factorialk([content], 3, exact=True)
//  [python]
def test_factorialx_nan(self, content, exact):
        # scalar
        assert special.factorial(content, exact=exact) is np.nan
        assert special.factorial2(content, exact=exact) is np.nan
        assert special.factorialk(content, 3, exact=True) is np.nan
        # array-like (initializes np.array with default dtype)
        if content is not np.nan:
            # None causes object dtype, which is not supported; as is datetime
            with pytest.raises(ValueError, match="Unsupported datatype.*"):
                special.factorial([content], exact=exact)
        elif exact:
            # cannot use `is np.nan` see https://stackoverflow.com/a/52124109
            with pytest.warns(DeprecationWarning, match="Non-integer array.*"):
                assert np.isnan(special.factorial([content], exact=exact)[0])
        else:
            assert np.isnan(special.factorial([content], exact=exact)[0])
        # factorial{2,k} don't support array case due to dtype constraints
        with pytest.raises(ValueError, match="factorial2 does not support.*"):
            special.factorial2([content], exact=exact)
        with pytest.raises(ValueError, match="factorialk does not support.*"):
            special.factorialk([content], 3, exact=True)
//  [python]
def test_factorialx_array_like(self, level, exact):
        def _nest_me(x, k=1):
            if k == 0:
                return x
            else:
                return _nest_me([x], k-1)

        n = _nest_me([5], k=level-1)  # nested list
        exp_nucleus = {1: 120, 2: 15, 3: 10}
        assert_func = assert_array_equal if exact else assert_allclose
        assert_func(s.factorial(n, exact=exact),
                    np.array(exp_nucleus[1], ndmin=level))
        assert_func(s.factorial2(n, exact=exact),
                    np.array(exp_nucleus[2], ndmin=level))
        assert_func(s.factorialk(n, 3, exact=True),
                    np.array(exp_nucleus[3], ndmin=level))
//  [python]
def test_factorialx_array_like(self, level, exact):
        def _nest_me(x, k=1):
            if k == 0:
                return x
            else:
                return _nest_me([x], k-1)

        n = _nest_me([5], k=level-1)  # nested list
        exp_nucleus = {1: 120, 2: 15, 3: 10}
        assert_func = assert_array_equal if exact else assert_allclose
        assert_func(special.factorial(n, exact=exact),
                    np.array(exp_nucleus[1], ndmin=level))
        assert_func(special.factorial2(n, exact=exact),
                    np.array(exp_nucleus[2], ndmin=level))
        assert_func(special.factorialk(n, 3, exact=True),
                    np.array(exp_nucleus[3], ndmin=level))
//  [python]
def test_factorial_int_reference(self, n):
        # Compare all with math.factorial
        correct = math.factorial(n)
        assert_array_equal(correct, s.factorial(n, True))
        assert_array_equal(correct, s.factorial([n], True)[0])

        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
        assert_allclose(float(correct), s.factorial(n, False),
                        rtol=rtol)
        assert_allclose(float(correct), s.factorial([n], False)[0],
                        rtol=rtol)
//  [python]
def test_factorial_int_reference(self, n):
        # Compare all with math.factorial
        correct = math.factorial(n)
        assert_array_equal(correct, special.factorial(n, True))
        assert_array_equal(correct, special.factorial([n], True)[0])

        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
        assert_allclose(float(correct), special.factorial(n, False),
                        rtol=rtol)
        assert_allclose(float(correct), special.factorial([n], False)[0],
                        rtol=rtol)
//  [python]
def test_factorialx_array_shape(self, levels, exact):
        def _nest_me(x, k=1):
            """
            Double x and nest it k times

            For example:
            >>> _nest_me([3, 4], 2)
            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
            """
            if k == 0:
                return x
            else:
                return _nest_me([x, x], k-1)

        def _check(res, nucleus):
            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
            # test that ndarray shape is maintained
            # need to cast to float due to numpy/numpy#21220
            assert_allclose(res.astype(np.float64), exp.astype(np.float64))

        n = np.array(_nest_me([5, 25], k=levels))
        exp_nucleus = {1: [120, math.factorial(25)],
                       # correctness of factorial2() is tested elsewhere
                       2: [15, special.factorial2(25, exact=True)],
                       3: [10, special.factorialk(25, 3)]}

        _check(s.factorial(n, exact=exact), exp_nucleus[1])
        _check(s.factorial2(n, exact=exact), exp_nucleus[2])
        _check(s.factorialk(n, 3, exact=True), exp_nucleus[3])
//  [python]
def test_factorialx_array_shape(self, levels, exact):
        def _nest_me(x, k=1):
            """
            Double x and nest it k times

            For example:
            >>> _nest_me([3, 4], 2)
            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
            """
            if k == 0:
                return x
            else:
                return _nest_me([x, x], k-1)

        def _check(res, nucleus):
            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
            # test that ndarray shape is maintained
            # need to cast to float due to numpy/numpy#21220
            assert_allclose(res.astype(np.float64), exp.astype(np.float64))

        n = np.array(_nest_me([5, 25], k=levels))
        exp_nucleus = {1: [120, math.factorial(25)],
                       # correctness of factorial2() is tested elsewhere
                       2: [15, special.factorial2(25, exact=True)],
                       3: [10, special.factorialk(25, 3)]}

        _check(special.factorial(n, exact=exact), exp_nucleus[1])
        _check(special.factorial2(n, exact=exact), exp_nucleus[2])
        _check(special.factorialk(n, 3, exact=True), exp_nucleus[3])
//  [python]
def test_factorial_scalar_corner_cases(self, n, exact):
        if (n is None or n is np.nan or np.issubdtype(type(n), np.integer)
                or np.issubdtype(type(n), np.floating)):
            # no error
            result = s.factorial(n, exact=exact)
            exp = np.nan if n is np.nan or n is None else s.factorial(n)
            assert_equal(result, exp)
        else:
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                s.factorial(n, exact=exact)
//  [python]
def test_factorial_scalar_corner_cases(self, n, exact):
        if (n is None or n is np.nan or np.issubdtype(type(n), np.integer)
                or np.issubdtype(type(n), np.floating)):
            # no error
            result = special.factorial(n, exact=exact)
            exp = np.nan if n is np.nan or n is None else special.factorial(n)
            assert_equal(result, exp)
        else:
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                special.factorial(n, exact=exact)
//  [python]
def test_factorial_mixed_nan_inputs(self):
        x = np.array([np.nan, 1, 2, 3, np.nan])
        expected = np.array([np.nan, 1, 2, 6, np.nan])
        assert_equal(s.factorial(x, exact=False), expected)
        with pytest.warns(DeprecationWarning, match=r"Non-integer array.*"):
            assert_equal(s.factorial(x, exact=True), expected)
//  [python]
def test_factorial_mixed_nan_inputs(self):
        x = np.array([np.nan, 1, 2, 3, np.nan])
        expected = np.array([np.nan, 1, 2, 6, np.nan])
        assert_equal(special.factorial(x, exact=False), expected)
        with pytest.warns(DeprecationWarning, match=r"Non-integer array.*"):
            assert_equal(special.factorial(x, exact=True), expected)
//  [python]
def test_factorialx_array_dimension(self, dim, dtype, exact):
        n = np.array(5, dtype=dtype, ndmin=dim)
        exp = {1: 120, 2: 15, 3: 10}
        assert_allclose(s.factorial(n, exact=exact),
                        np.array(exp[1], ndmin=dim))
        assert_allclose(s.factorial2(n, exact=exact),
                        np.array(exp[2], ndmin=dim))
        assert_allclose(s.factorialk(n, 3, exact=exact),
                        np.array(exp[3], ndmin=dim))
//  [python]
def test_factorialx_array_dimension(self, dim, dtype, exact):
        n = np.array(5, dtype=dtype, ndmin=dim)
        exp = {1: 120, 2: 15, 3: 10}
        assert_allclose(special.factorial(n, exact=exact),
                        np.array(exp[1], ndmin=dim))
        assert_allclose(special.factorial2(n, exact=exact),
                        np.array(exp[2], ndmin=dim))
        assert_allclose(special.factorialk(n, 3, exact=exact),
                        np.array(exp[3], ndmin=dim))
//  [python]
def test_factorial_scalar_corner_cases(self, n, exact):
        if (n is None or n is np.nan or np.issubdtype(type(n), np.integer)
                or np.issubdtype(type(n), np.floating)):
            # no error
            if (np.issubdtype(type(n), np.floating) and exact
                    and n is not np.nan):
                with pytest.deprecated_call(match="Non-integer values.*"):
                    result = s.factorial(n, exact=exact)
            else:
                result = s.factorial(n, exact=exact)
            exp = np.nan if n is np.nan or n is None else s.factorial(n)
            assert_equal(result, exp)
        else:
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                s.factorial(n, exact=exact)
//  [python]
def test_factorial_scalar_corner_cases(self, n, exact):
        if (n is None or n is np.nan or np.issubdtype(type(n), np.integer)
                or np.issubdtype(type(n), np.floating)):
            # no error
            if (np.issubdtype(type(n), np.floating) and exact
                    and n is not np.nan):
                with pytest.deprecated_call(match="Non-integer values.*"):
                    result = special.factorial(n, exact=exact)
            else:
                result = special.factorial(n, exact=exact)
            exp = np.nan if n is np.nan or n is None else special.factorial(n)
            assert_equal(result, exp)
        else:
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                special.factorial(n, exact=exact)
//  [python]
def test_factorial_float_reference(self, exact):
        def _check(n, expected):
            # support for exact=True with scalar floats grandfathered in
            assert_allclose(s.factorial(n, exact=exact), expected)
            # non-integer types in arrays only allowed with exact=False
            assert_allclose(s.factorial([n])[0], expected)

        # Reference values from mpmath for gamma(n+1)
        _check(0.01, 0.994325851191506032181932988)
        _check(1.11, 1.051609009483625091514147465)
        _check(5.55, 314.9503192327208241614959052)
        _check(11.1, 50983227.84411615655137170553)
        _check(33.3, 2.493363339642036352229215273e+37)
        _check(55.5, 9.479934358436729043289162027e+73)
        _check(77.7, 3.060540559059579022358692625e+114)
        _check(99.9, 5.885840419492871504575693337e+157)
        # close to maximum for float64
        _check(170.6243, 1.79698185749571048960082e+308)
//  [python]
def test_factorial_float_reference(self, exact):
        def _check(n, expected):
            # support for exact=True with scalar floats grandfathered in
            assert_allclose(special.factorial(n, exact=exact), expected)
            # non-integer types in arrays only allowed with exact=False
            assert_allclose(special.factorial([n])[0], expected)

        # Reference values from mpmath for gamma(n+1)
        _check(0.01, 0.994325851191506032181932988)
        _check(1.11, 1.051609009483625091514147465)
        _check(5.55, 314.9503192327208241614959052)
        _check(11.1, 50983227.84411615655137170553)
        _check(33.3, 2.493363339642036352229215273e+37)
        _check(55.5, 9.479934358436729043289162027e+73)
        _check(77.7, 3.060540559059579022358692625e+114)
        _check(99.9, 5.885840419492871504575693337e+157)
        # close to maximum for float64
        _check(170.6243, 1.79698185749571048960082e+308)
//  [python]
def test_factorialx_array_shape(self, levels, exact):
        def _nest_me(x, k=1):
            """
            Double x and nest it k times

            For example:
            >>> _nest_me([3, 4], 2)
            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
            """
            if k == 0:
                return x
            else:
                return _nest_me([x, x], k-1)

        def _check(res, nucleus):
            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
            # test that ndarray shape is maintained
            # need to cast to float due to numpy/numpy#21220
            assert_allclose(res.astype(np.float64), exp.astype(np.float64))

        n = np.array(_nest_me([5, 25], k=levels))
        exp_nucleus = {1: [120, math.factorial(25)],
                       # correctness of factorial{2,k}() is tested elsewhere
                       2: [15, special.factorial2(25, exact=True)],
                       3: [10, special.factorialk(25, 3, exact=True)]}

        _check(s.factorial(n, exact=exact), exp_nucleus[1])
        _check(s.factorial2(n, exact=exact), exp_nucleus[2])
        _check(s.factorialk(n, 3, exact=exact), exp_nucleus[3])
//  [python]
def test_factorialx_array_shape(self, levels, exact):
        def _nest_me(x, k=1):
            """
            Double x and nest it k times

            For example:
            >>> _nest_me([3, 4], 2)
            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
            """
            if k == 0:
                return x
            else:
                return _nest_me([x, x], k-1)

        def _check(res, nucleus):
            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
            # test that ndarray shape is maintained
            # need to cast to float due to numpy/numpy#21220
            assert_allclose(res.astype(np.float64), exp.astype(np.float64))

        n = np.array(_nest_me([5, 25], k=levels))
        exp_nucleus = {1: [120, math.factorial(25)],
                       # correctness of factorial{2,k}() is tested elsewhere
                       2: [15, special.factorial2(25, exact=True)],
                       3: [10, special.factorialk(25, 3, exact=True)]}

        _check(special.factorial(n, exact=exact), exp_nucleus[1])
        _check(special.factorial2(n, exact=exact), exp_nucleus[2])
        _check(special.factorialk(n, 3, exact=exact), exp_nucleus[3])
//  [python]
def Dlam(lamb,N):
    '''
    Order lamb (>=1) derivative matrix, size N*N
    '''
    if par.ricb == 0:
        const1 = (1/rcmb)**lamb  # ok when rcmb is not 1
    else:
        const1 = (2./(rcmb-par.ricb))**lamb
    const2 = s.factorial(lamb-1.)*2**(lamb-1.)
    tmp = lamb + np.arange(0,N-lamb)

    return const1*const2*ss.diags(tmp,lamb, format='csr')
//  [python]
def Dlam(lamb,N):
    '''
    Order lamb (>=1) derivative matrix, size N*N
    '''
    if par.ricb == 0:
        const1 = (1/rcmb)**lamb  # ok when rcmb is not 1
    else:
        const1 = (2./(rcmb-par.ricb))**lamb
    const2 = scsp.factorial(lamb-1.)*2**(lamb-1.)
    tmp = lamb + np.arange(0,N-lamb)

    return const1*const2*ss.diags(tmp,lamb, format='csr')
//  [python]
def inverse_quadratic_expansion(epsilon, mu):
    c = 4.0*np.pi**(3.0/2.0)*scipy.special.gamma(mu+1) / \
        scipy.special.gamma(mu + 3.0/2.0)/(1.0 + 4.0*epsilon**2)**(mu+1) * \
        scipy.special.hyp2f1(mu+1, mu+1, 2.*mu+2, 4.*epsilon**2/(1.+4.*epsilon**2))
    return c
//  [python]
def inverse_quadratic_expansion(epsilon, mu):
    c = 4.0*np.pi**(3.0/2.0)*scipy.special.factorial(mu) / \
        scipy.special.gamma(mu + 3.0/2.0)/(1.0 + 4.0*epsilon**2)**(mu+1) * \
        scipy.special.hyp2f1(mu+1, mu+1, 2.*mu+2, 4.*epsilon**2/(1.+4.*epsilon**2))
    return c
//  [python]
def test_factorial_array_corner_cases(self, content, dim, exact, dtype):
        if dtype == np.int64 and any(np.isnan(x) for x in content):
            pytest.skip("impossible combination")
        # np.array(x, ndim=0) will not be 0-dim. unless x is too
        content = content if (dim > 0 or len(content) != 1) else content[0]
        n = np.array(content, ndmin=dim, dtype=dtype)
        result = None
        if not content:
            result = s.factorial(n, exact=exact)
        elif not (np.issubdtype(n.dtype, np.integer)
                  or np.issubdtype(n.dtype, np.floating)):
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                s.factorial(n, exact=exact)
        elif (exact and not np.issubdtype(n.dtype, np.integer) and n.size and
              np.allclose(n[~np.isnan(n)], n[~np.isnan(n)].astype(np.int64))):
            # using integers but in array with wrong dtype (e.g. due to NaNs)
            with pytest.warns(DeprecationWarning, match="Non-integer array.*"):
                result = s.factorial(n, exact=exact)
                # expected dtype is integer, unless there are NaNs
                dtype = np.float_ if np.any(np.isnan(n)) else np.int_
        elif exact and not np.issubdtype(n.dtype, np.integer):
            with pytest.raises(ValueError, match="factorial with exact=.*"):
                s.factorial(n, exact=exact)
        else:
            # no error
            result = s.factorial(n, exact=exact)

        # assert_equal does not distinguish scalars and 0-dim arrays of the same value, see
        # https://github.com/numpy/numpy/issues/24050
        def assert_really_equal(x, y):
            assert type(x) == type(y), f"types not equal: {type(x)}, {type(y)}"
            assert_equal(x, y)

        if result is not None:
            # expected result is empty if and only if n is empty,
            # and has the same dtype & dimension as n
            with suppress_warnings() as sup:
                sup.filter(DeprecationWarning)
                # keep 0-dim.; otherwise n.ravel().ndim==1, even if n.ndim==0
                n_flat = n.ravel() if n.ndim else n
                r = s.factorial(n_flat, exact=exact) if n.size else []
            expected = np.array(r, ndmin=dim, dtype=dtype)
            assert_really_equal(result, expected)
//  [python]
def test_factorial_array_corner_cases(self, content, dim, exact, dtype):
        if dtype == np.int64 and any(np.isnan(x) for x in content):
            pytest.skip("impossible combination")
        # np.array(x, ndim=0) will not be 0-dim. unless x is too
        content = content if (dim > 0 or len(content) != 1) else content[0]
        n = np.array(content, ndmin=dim, dtype=dtype)
        result = None
        if not content:
            result = special.factorial(n, exact=exact)
        elif not (np.issubdtype(n.dtype, np.integer)
                  or np.issubdtype(n.dtype, np.floating)):
            with pytest.raises(ValueError, match="Unsupported datatype*"):
                special.factorial(n, exact=exact)
        elif (exact and not np.issubdtype(n.dtype, np.integer) and n.size and
              np.allclose(n[~np.isnan(n)], n[~np.isnan(n)].astype(np.int64))):
            # using integers but in array with wrong dtype (e.g. due to NaNs)
            with pytest.warns(DeprecationWarning, match="Non-integer array.*"):
                result = special.factorial(n, exact=exact)
                # expected dtype is integer, unless there are NaNs
                dtype = np.float_ if np.any(np.isnan(n)) else np.int_
        elif exact and not np.issubdtype(n.dtype, np.integer):
            with pytest.raises(ValueError, match="factorial with exact=.*"):
                special.factorial(n, exact=exact)
        else:
            # no error
            result = special.factorial(n, exact=exact)

        # assert_equal does not distinguish scalars and 0-dim arrays of the same value, see
        # https://github.com/numpy/numpy/issues/24050
        def assert_really_equal(x, y):
            assert type(x) == type(y), f"types not equal: {type(x)}, {type(y)}"
            assert_equal(x, y)

        if result is not None:
            # expected result is empty if and only if n is empty,
            # and has the same dtype & dimension as n
            with suppress_warnings() as sup:
                sup.filter(DeprecationWarning)
                # keep 0-dim.; otherwise n.ravel().ndim==1, even if n.ndim==0
                n_flat = n.ravel() if n.ndim else n
                r = special.factorial(n_flat, exact=exact) if n.size else []
            expected = np.array(r, ndmin=dim, dtype=dtype)
            assert_really_equal(result, expected)
//  [python]
def fact(n):
    """Exact factorial function."""
    return s.factorial(n, exact=True).astype(float)
//  [python]
def fact(n):
    """Exact factorial function."""
    return scipy.special.factorial(n, exact=True).astype(float)
//  [python]
def test_factorial_float_reference(self):
        def _check(n, expected):
            assert_allclose(s.factorial(n), expected)
            assert_allclose(s.factorial([n])[0], expected)
            # using floats with exact=True is deprecated for scalars...
            with pytest.deprecated_call(match="Non-integer values.*"):
                assert_allclose(s.factorial(n, exact=True), expected)
            # ... and already an error for arrays
            with pytest.raises(ValueError, match="factorial with `exact=Tr.*"):
                s.factorial([n], exact=True)

        # Reference values from mpmath for gamma(n+1)
        _check(0.01, 0.994325851191506032181932988)
        _check(1.11, 1.051609009483625091514147465)
        _check(5.55, 314.9503192327208241614959052)
        _check(11.1, 50983227.84411615655137170553)
        _check(33.3, 2.493363339642036352229215273e+37)
        _check(55.5, 9.479934358436729043289162027e+73)
        _check(77.7, 3.060540559059579022358692625e+114)
        _check(99.9, 5.885840419492871504575693337e+157)
        # close to maximum for float64
        _check(170.6243, 1.79698185749571048960082e+308)
//  [python]
def test_factorial_float_reference(self):
        def _check(n, expected):
            assert_allclose(special.factorial(n), expected)
            assert_allclose(special.factorial([n])[0], expected)
            # using floats with exact=True is deprecated for scalars...
            with pytest.deprecated_call(match="Non-integer values.*"):
                assert_allclose(special.factorial(n, exact=True), expected)
            # ... and already an error for arrays
            with pytest.raises(ValueError, match="factorial with `exact=Tr.*"):
                special.factorial([n], exact=True)

        # Reference values from mpmath for gamma(n+1)
        _check(0.01, 0.994325851191506032181932988)
        _check(1.11, 1.051609009483625091514147465)
        _check(5.55, 314.9503192327208241614959052)
        _check(11.1, 50983227.84411615655137170553)
        _check(33.3, 2.493363339642036352229215273e+37)
        _check(55.5, 9.479934358436729043289162027e+73)
        _check(77.7, 3.060540559059579022358692625e+114)
        _check(99.9, 5.885840419492871504575693337e+157)
        # close to maximum for float64
        _check(170.6243, 1.79698185749571048960082e+308)
//  [python]
def jl_smx(l,x,d):
    '''
    Spherical Bessel function of the first kind and derivatives,
    small argument (x<<1) only, 0 <= d <= 3
    '''
    c1 =  (2**l)*s.factorial(l)/s.factorial(2*l+1)
    c2 = -(2**l)*s.factorial(l+1)/s.factorial(2*l+3)
    c3 =  (2**l)*s.factorial(l+2)/(2*s.factorial(2*l+5))

    if d == 0:
        out = c1*x**l + c2*x**(l+2) + c3*x**(l+4)

    elif d == 1:
        out = c1*l*x**(l-1) + c2*(l+2)*x**(l+1) + c3*(l+4)*x**(l+3)

    elif d == 2:
        if l>=2:
            out = c1*l*(l-1)*x**(l-2) + c2*(l+2)*(l+1)*x**l + c3*(l+4)*(l+3)*x**(l+2)
        elif l==1:
            out = c2*(l+2)*(l+1)*x**l + c3*(l+4)*(l+3)*x**(l+2)

    elif d == 3:
        if l>=3:
            out = c1*l*(l-1)*(l-2)*x**(l-3) + c2*(l+2)*(l+1)*l*x**(l-1) + c3*(l+4)*(l+3)*(l+2)*x**(l+1)
        else:
            out = c2*(l+2)*(l+1)*l*x**(l-1) + c3*(l+4)*(l+3)*(l+2)*x**(l+1)

    return out
//  [python]
def jl_smx(l,x,d):
    '''
    Spherical Bessel function of the first kind and derivatives,
    small argument (x<<1) only, 0 <= d <= 3
    '''
    c1 =  (2**l)*scsp.factorial(l)/scsp.factorial(2*l+1)
    c2 = -(2**l)*scsp.factorial(l+1)/scsp.factorial(2*l+3)
    c3 =  (2**l)*scsp.factorial(l+2)/(2*scsp.factorial(2*l+5))

    if d == 0:
        out = c1*x**l + c2*x**(l+2) + c3*x**(l+4)

    elif d == 1:
        out = c1*l*x**(l-1) + c2*(l+2)*x**(l+1) + c3*(l+4)*x**(l+3)

    elif d == 2:
        if l>=2:
            out = c1*l*(l-1)*x**(l-2) + c2*(l+2)*(l+1)*x**l + c3*(l+4)*(l+3)*x**(l+2)
        elif l==1:
            out = c2*(l+2)*(l+1)*x**l + c3*(l+4)*(l+3)*x**(l+2)

    elif d == 3:
        if l>=3:
            out = c1*l*(l-1)*(l-2)*x**(l-3) + c2*(l+2)*(l+1)*l*x**(l-1) + c3*(l+4)*(l+3)*(l+2)*x**(l+1)
        else:
            out = c2*(l+2)*(l+1)*l*x**(l-1) + c3*(l+4)*(l+3)*(l+2)*x**(l+1)

    return out
//  [python]
def spherical_harmonic_matrix(l,theta,phi):
    #-- calculate legendre polynomials
    nth = len(theta)
    Pl = legendre(l,np.cos(theta)).transpose()
    #-- calculate degree dependent factors C and F
    m = np.arange(0,l+1)#-- spherical harmonic orders up to degree l
    C = np.sqrt((2.0*l + 1.0)/(4.0*np.pi))
    F=np.sqrt(s.factorial(1+l-m-1)/s.factorial(1+l+m-1))
    F=np.kron(np.ones((nth,1)), F[np.newaxis,:])
    #-- calculate Euler's of spherical harmonic order multiplied by azimuth phi
    mphi = np.exp(1j*np.dot(np.squeeze(phi)[:,np.newaxis],m[np.newaxis,:]))
    #-- calculate spherical harmonics
    Ylms = F*Pl[:,0:l+1]*mphi
    #-- multiply by C and convert to reduced matrix (theta,Slm:Clm)
    SPH = C*np.concatenate((np.imag(Ylms[:,:0:-1]),np.real(Ylms)), axis=1)
    return SPH
//  [python]
def spherical_harmonic_matrix(l,theta,phi):
    #-- calculate legendre polynomials
    nth = len(theta)
    Pl = legendre(l,np.cos(theta)).transpose()
    #-- calculate degree dependent factors C and F
    m = np.arange(0,l+1)#-- spherical harmonic orders up to degree l
    C = np.sqrt((2.0*l + 1.0)/(4.0*np.pi))
    F=np.sqrt(scipy.special.factorial(1+l-m-1)/scipy.special.factorial(1+l+m-1))
    F=np.kron(np.ones((nth,1)), F[np.newaxis,:])
    #-- calculate Euler's of spherical harmonic order multiplied by azimuth phi
    mphi = np.exp(1j*np.dot(np.squeeze(phi)[:,np.newaxis],m[np.newaxis,:]))
    #-- calculate spherical harmonics
    Ylms = F*Pl[:,0:l+1]*mphi
    #-- multiply by C and convert to reduced matrix (theta,Slm:Clm)
    SPH = C*np.concatenate((np.imag(Ylms[:,:0:-1]),np.real(Ylms)), axis=1)
    return SPH
//  [python]
def SphHarmonic(n, theta, phi):
    y = np.zeros(2*n+1, dtype=complex)
    for m in range(-n, n+1):
        temp = np.sqrt((2*n+1)/(4*np.pi) * s.factorial(n-abs(m)) / s.factorial(n+abs(m))) * np.exp(1j*m*phi)
        if m >= 0:
            y[m+n] = temp * lpmv(m, n, np.cos(theta))
        else:
            fm = -m
            y[m+n] = temp * lpmv(fm, n, np.cos(theta)) * (-1)**fm
    return y
//  [python]
def SphHarmonic(n, theta, phi):
    y = np.zeros(2*n+1, dtype=complex)
    for m in range(-n, n+1):
        temp = np.sqrt((2*n+1)/(4*np.pi) * factorial(n-abs(m)) / factorial(n+abs(m))) * np.exp(1j*m*phi)
        if m >= 0:
            y[m+n] = temp * lpmv(m, n, np.cos(theta))
        else:
            fm = -m
            y[m+n] = temp * lpmv(fm, n, np.cos(theta)) * (-1)**fm
    return y
//  [python]
def poisson(self, param, x, standardize=False):
        ll = np.exp(-param) * param**x / s.factorial(x)
        if standardize:
            return ll / np.max(ll)
        else:
            return ll
//  [python]
def poisson(self, param, x, standardize=False):
        ll = np.exp(-param) * param**x / scipy.special.factorial(x)
        if standardize:
            return ll / np.max(ll)
        else:
            return ll
//  [python]
def multinomial(n, k):
    """
    Multinomial coefficient returning an integer.

    Parameters
    ----------
    n : int
    k : list of int

    Returns
    -------
    int
         Multinomial coefficient.
    """

    ret = s.factorial(n)
    for i in k:
        ret //= s.factorial(i)
    return ret
//  [python]
def multinomial(n, k):
    """
    Multinomial coefficient returning an integer.

    Parameters
    ----------
    n : int
    k : list of int

    Returns
    -------
    int
         Multinomial coefficient.
    """

    ret = sc_sp.factorial(n)
    for i in k:
        ret //= sc_sp.factorial(i)
    return ret
//  [python]
def log_poisson(self, param, x, standardize=False):
        with np.errstate(divide="ignore"):
            ll = np.log(np.exp(-param) * param**x / s.factorial(x))
        if standardize:
            return ll - np.max(ll)
        else:
            return ll
//  [python]
def log_poisson(self, param, x, standardize=False):
        with np.errstate(divide="ignore"):
            ll = np.log(np.exp(-param) * param**x / scipy.special.factorial(x))
        if standardize:
            return ll - np.max(ll)
        else:
            return ll
//  [python]
def __init__(self, n: int, l: int, m: int, Z: float, **kwargs):
        self._Z = Z

        Helper = namedtuple("Helper", ["Z", "prefactor"])
        z = 2 * Z / (n * a0("Ang"))
        pref = (z**3 * s.factorial(n - l - 1) / (2 * n * s.factorial(n + l))) ** 0.5
        self._radial_helper = Helper(z, pref)

        super().__init__(n, l, m, **kwargs)
//  [python]
def __init__(self, n: int, l: int, m: int, Z: float, **kwargs):
        self._Z = Z

        Helper = namedtuple("Helper", ["Z", "prefactor"])
        z = 2 * Z / (n * a0("Ang"))
        pref = (z**3 * factorial(n - l - 1) / (2 * n * factorial(n + l))) ** 0.5
        self._radial_helper = Helper(z, pref)

        super().__init__(n, l, m, **kwargs)
//  [python]
def K(dim=4, dfn=7, dfd=np.inf):
    r"""
    Determine the polynomial K in:

        Worsley, K.J. (1994). 'Local maxima and the expected Euler
        characteristic of excursion sets of \chi^2, F and t fields.' Advances in
        Applied Probability, 26:13-42.

    If dfd=inf, return the limiting polynomial.
    """
    def lbinom(n, j):
        return gammaln(n+1) - gammaln(j+1) - gammaln(n-j+1)

    m = dfd
    n = dfn
    D = dim
    k = np.arange(D)
    coef = 0
    for j in range(int(np.floor((D-1)/2.)+1)):
        if np.isfinite(m):
            t = (gammaln((m+n-D)/2.+j) -
                 gammaln(j+1) -
                 gammaln((m+n-D)/2.))
            t += lbinom(m-1, k-j) - k * np.log(m)
        else:
            _t = np.power(2., -j) / (s.factorial(k-j) * s.factorial(j))
            t = np.log(_t)
            t[np.isinf(_t)] = -np.inf
        t += lbinom(n-1, D-1-j-k)
        coef += (-1)**(D-1) * s.factorial(D-1) * np.exp(t) * np.power(-1.*n, k)
    return np.poly1d(coef[::-1])
//  [python]
def K(dim=4, dfn=7, dfd=np.inf):
    r"""
    Determine the polynomial K in:

        Worsley, K.J. (1994). 'Local maxima and the expected Euler
        characteristic of excursion sets of \chi^2, F and t fields.' Advances in
        Applied Probability, 26:13-42.

    If dfd=inf, return the limiting polynomial.
    """
    def lbinom(n, j):
        return gammaln(n+1) - gammaln(j+1) - gammaln(n-j+1)

    m = dfd
    n = dfn
    D = dim
    k = np.arange(D)
    coef = 0
    for j in range(int(np.floor((D-1)/2.)+1)):
        if np.isfinite(m):
            t = (gammaln((m+n-D)/2.+j) -
                 gammaln(j+1) -
                 gammaln((m+n-D)/2.))
            t += lbinom(m-1, k-j) - k * np.log(m)
        else:
            _t = np.power(2., -j) / (factorial(k-j) * factorial(j))
            t = np.log(_t)
            t[np.isinf(_t)] = -np.inf
        t += lbinom(n-1, D-1-j-k)
        coef += (-1)**(D-1) * factorial(D-1) * np.exp(t) * np.power(-1.*n, k)
    return np.poly1d(coef[::-1])
//  [python]
def _psi_R(r,n=1,l=0):
    coeff = np.sqrt((2.0 / n) ** 3 * s.factorial(n-l-1) / (2.0*n*s.factorial(n+l)))
    
    laguerre = spe.assoc_laguerre(2.0*r/n,n-l-1,2*l+1)
    
    return coeff * np.exp(-r / n) * (2.0 * r / n) ** l * laguerre
//  [python]
def _psi_R(r,n=1,l=0):
    coeff = np.sqrt((2.0 / n) ** 3 * spe.factorial(n-l-1) / (2.0*n*spe.factorial(n+l)))
    
    laguerre = spe.assoc_laguerre(2.0*r/n,n-l-1,2*l+1)
    
    return coeff * np.exp(-r / n) * (2.0 * r / n) ** l * laguerre
//  [python]
def __init__(self, p):
        """
        Constructor; initializes a Laguerre basis function
        """

        super(Laguerre, self).__init__(p)

        self.fun_norm = (s.factorial(p["i"]+p["alpha"]) / s.factorial(p["i"])) / \
                        scipy.special.gamma(p["alpha"] + 1)

        # define basis function
        self.fun = scipy.special.genlaguerre(p["i"], alpha=p["alpha"], monic=False) / np.sqrt(self.fun_norm)

        # derivative of polynomial
        self.fun_der = np.polyder(self.fun)

        # integral of fun and fun_der w.r.t. pdf (numerical integration with corresponding weights)
        if self.p["i"] == 0:
            self.fun_int = 1.0
            self.fun_der_int = 0.0
        else:
            knots, weights = get_quadrature_laguerre_1d(n=10 * self.p["i"], alpha=p["alpha"])
            self.fun_int = np.dot(self.fun(knots), weights)
            self.fun_der_int = np.dot(self.fun_der(knots), weights)
//  [python]
def __init__(self, p):
        """
        Constructor; initializes a Laguerre basis function
        """

        super(Laguerre, self).__init__(p)

        self.fun_norm = (scipy.special.factorial(p["i"]+p["alpha"]) / scipy.special.factorial(p["i"])) / \
                        scipy.special.gamma(p["alpha"] + 1)

        # define basis function
        self.fun = scipy.special.genlaguerre(p["i"], alpha=p["alpha"], monic=False) / np.sqrt(self.fun_norm)

        # derivative of polynomial
        self.fun_der = np.polyder(self.fun)

        # integral of fun and fun_der w.r.t. pdf (numerical integration with corresponding weights)
        if self.p["i"] == 0:
            self.fun_int = 1.0
            self.fun_der_int = 0.0
        else:
            knots, weights = get_quadrature_laguerre_1d(n=10 * self.p["i"], alpha=p["alpha"])
            self.fun_int = np.dot(self.fun(knots), weights)
            self.fun_der_int = np.dot(self.fun_der(knots), weights)
//  [python]
def __init__(self, p):
        """
        Constructor; initializes a Hermite basis function
        """

        super(Hermite, self).__init__(p)

        # normalization factor of polynomial (to later normalize basis functions <psi^2> = int(psi^2*p)dx)
        self.fun_norm = np.float64(scipy.misc.factorial(p["i"]))

        # define basis function
        self.fun = scipy.special.hermitenorm(p["i"], monic=False) / np.sqrt(self.fun_norm)

        # derivative of polynomial
        self.fun_der = np.polyder(self.fun)

        # integral of fun and fun_der w.r.t. pdf (numerical integration with corresponding weights)
        if self.p["i"] == 0:
            self.fun_int = 1.0
            self.fun_der_int = 0.0
        else:
            knots, weights = get_quadrature_hermite_1d(n=10 * self.p["i"])
            self.fun_int = np.dot(self.fun(knots), weights)
            self.fun_der_int = np.dot(self.fun_der(knots), weights)
//  [python]
def __init__(self, p):
        """
        Constructor; initializes a Hermite basis function
        """

        super(Hermite, self).__init__(p)

        # normalization factor of polynomial (to later normalize basis functions <psi^2> = int(psi^2*p)dx)
        self.fun_norm = np.float64(scipy.special.factorial(p["i"]))

        # define basis function
        self.fun = scipy.special.hermitenorm(p["i"], monic=False) / np.sqrt(self.fun_norm)

        # derivative of polynomial
        self.fun_der = np.polyder(self.fun)

        # integral of fun and fun_der w.r.t. pdf (numerical integration with corresponding weights)
        if self.p["i"] == 0:
            self.fun_int = 1.0
            self.fun_der_int = 0.0
        else:
            knots, weights = get_quadrature_hermite_1d(n=10 * self.p["i"])
            self.fun_int = np.dot(self.fun(knots), weights)
            self.fun_der_int = np.dot(self.fun_der(knots), weights)
//  [python]
def _pade_delay(p, q, c):
    """Numerically evaluated state-space using Pade approximants.

    This may have numerical issues for large values of p or q.
    """
    i = np.arange(1, p+q+1, dtype=np.float64)
    taylor = np.append([1.0], (-c)**i / s.factorial(i))
    num, den = pade(taylor, q)
    return LinearSystem((num, den), analog=True)
//  [python]
def _pade_delay(p, q, c):
    """Numerically evaluated state-space using Pade approximants.

    This may have numerical issues for large values of p or q.
    """
    i = np.arange(1, p+q+1, dtype=np.float64)
    taylor = np.append([1.0], (-c)**i / factorial(i))
    num, den = pade(taylor, q)
    return LinearSystem((num, den), analog=True)
//  [python]
def testNormalizedLpmnValues(self, l_max, shape, dtype):
    rng = jtu.rand_uniform(self.rng(), low=-0.2, high=0.9)
    args_maker = lambda: [rng(shape, dtype)]

    # Note: we test only the normalized values, not the derivatives.
    lax_fun = partial(lsp_special.lpmn_values, l_max, l_max, is_normalized=True)

    def scipy_fun(z, m=l_max, n=l_max):
      # scipy only supports scalar inputs for z, so we must loop here.
      vals, _ = zip(*(osp_special.lpmn(m, n, zi) for zi in z))
      a = np.dstack(vals)

      # apply the normalization
      num_m, num_l, _ = a.shape
      a_normalized = np.zeros_like(a)
      for m in range(num_m):
        for l in range(num_l):
          c0 = (2.0 * l + 1.0) * osp_special.factorial(l - m)
          c1 = (4.0 * np.pi) * osp_special.factorial(l + m)
          c2 = np.sqrt(c0 / c1)
          a_normalized[m, l] = c2 * a[m, l]
      return a_normalized

    self._CheckAgainstNumpy(scipy_fun, lax_fun, args_maker,
                            rtol=1e-5, atol=1e-5, check_dtypes=False)
    self._CompileAndCheck(lax_fun, args_maker, rtol=1E-6, atol=1E-6)