diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ae8a7507579b456a231737addc8d9917323fe18 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31cbf351bad1b0c19114515783721c3355711816 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7fdbe5371817a8c0d67a7fc2450ee9341e61799 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78766e7cf4e44675503f62590651118d3ff9f7c1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc26550ceaadc94571413974df7bbc4506aeb218 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83cb7ff6ff0625e9c43bd64f998ff42a954749e9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e3307be478bcb056171ca70d21531088031c590 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ec9eb946718903a83c062f517057b7f600eb31e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11079064d85a0605859359db0ba32808a7a99c95 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_bdtr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87bd13a90a3487953866092bee410ed1a5355da1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac4a79658294a0ccae786267e537bae258727e2e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cosine_distr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f4500f80f357412e9fbcdc074fd79c7c737b992 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_data.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a74f8071683796be794e58f1bd47096d2dd999fd Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_ellip_harm.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2bd83682450c8d9cf252c4eec869178ecb50dfe Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_hypergeometric.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13a60443641a4bf4167a30120e6facc906e5ec4d Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_kolmogorov.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0fde1890b912f2d2b36509d7d1baaa4ce08469 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dbca4cc0b7fd3a28ec1e0eeabf3880e9081f267 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal_eval.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3248107cf6b2fe120a94222924699ee73059961e Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pcf.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..068ffd1b89da263a011408744a88ecd4b635a962 Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_pdtr.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c0acbd5ccdab9f5c04116fd022ebfdb9f7f9dad Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_round.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfc19bc8b2794c7956c5950521b25572e07d8cbf Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_specfun.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a4e18182b5c934c6e6b5df73f6eb974afa5def Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spence.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a90b95dc48f7900e48b1939d9f46498e7333550c Binary files /dev/null and b/venv/lib/python3.10/site-packages/scipy/special/tests/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..19aa763ca55fe73a303b1e9f30392e39683c2fb0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py @@ -0,0 +1,4320 @@ +# this program corresponds to special.py + +### Means test is not done yet +# E Means test is giving error (E) +# F Means test is failing (F) +# EF Means test is giving error and Failing +#! Means test is segfaulting +# 8 Means test runs forever + +### test_besselpoly +### test_mathieu_a +### test_mathieu_even_coef +### test_mathieu_odd_coef +### test_modfresnelp +### test_modfresnelm +# test_pbdv_seq +### test_pbvv_seq +### test_sph_harm + +import functools +import itertools +import operator +import platform +import sys + +import numpy as np +from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, + log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, double, + array_equal) + +import pytest +from pytest import raises as assert_raises +from numpy.testing import (assert_equal, assert_almost_equal, + assert_array_equal, assert_array_almost_equal, assert_approx_equal, + assert_, assert_allclose, assert_array_almost_equal_nulp, + suppress_warnings) + +from scipy import special +import scipy.special._ufuncs as cephes +from scipy.special import ellipe, ellipk, ellipkm1 +from scipy.special import elliprc, elliprd, elliprf, elliprg, elliprj +from scipy.special import mathieu_odd_coef, mathieu_even_coef, stirling2 +from scipy._lib.deprecation import _NoValue +from scipy._lib._util import np_long, np_ulong + +from scipy.special._basic import _FACTORIALK_LIMITS_64BITS, \ + _FACTORIALK_LIMITS_32BITS +from scipy.special._testutils import with_special_errors, \ + assert_func_equal, FuncData + +import math + + +class TestCephes: + def test_airy(self): + cephes.airy(0) + + def test_airye(self): + cephes.airye(0) + + def test_binom(self): + n = np.array([0.264, 4, 5.2, 17]) + k = np.array([2, 0.4, 7, 3.3]) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389, + -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846], + [10.92, 2.22993515861399, -0.00585728, 10.468891352063146], + [136, 3.5252179590758828, 19448, 1024.5526916174495]]) + assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13) + + # Test branches in implementation + np.random.seed(1234) + n = np.r_[np.arange(-7, 30), 1000*np.random.rand(30) - 500] + k = np.arange(0, 102) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + + assert_func_equal(cephes.binom, + cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), + nk, + atol=1e-10, rtol=1e-10) + + def test_binom_2(self): + # Test branches in implementation + np.random.seed(1234) + n = np.r_[np.logspace(1, 300, 20)] + k = np.arange(0, 102) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + + assert_func_equal(cephes.binom, + cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)), + nk, + atol=1e-10, rtol=1e-10) + + def test_binom_exact(self): + @np.vectorize + def binom_int(n, k): + n = int(n) + k = int(k) + num = 1 + den = 1 + for i in range(1, k+1): + num *= i + n - k + den *= i + return float(num/den) + + np.random.seed(1234) + n = np.arange(1, 15) + k = np.arange(0, 15) + nk = np.array(np.broadcast_arrays(n[:,None], k[None,:]) + ).reshape(2, -1).T + nk = nk[nk[:,0] >= nk[:,1]] + assert_func_equal(cephes.binom, + binom_int(nk[:,0], nk[:,1]), + nk, + atol=0, rtol=0) + + def test_binom_nooverflow_8346(self): + # Test (binom(n, k) doesn't overflow prematurely */ + dataset = [ + (1000, 500, 2.70288240945436551e+299), + (1002, 501, 1.08007396880791225e+300), + (1004, 502, 4.31599279169058121e+300), + (1006, 503, 1.72468101616263781e+301), + (1008, 504, 6.89188009236419153e+301), + (1010, 505, 2.75402257948335448e+302), + (1012, 506, 1.10052048531923757e+303), + (1014, 507, 4.39774063758732849e+303), + (1016, 508, 1.75736486108312519e+304), + (1018, 509, 7.02255427788423734e+304), + (1020, 510, 2.80626776829962255e+305), + (1022, 511, 1.12140876377061240e+306), + (1024, 512, 4.48125455209897109e+306), + (1026, 513, 1.79075474304149900e+307), + (1028, 514, 7.15605105487789676e+307) + ] + dataset = np.asarray(dataset) + FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check() + + def test_bdtr(self): + assert_equal(cephes.bdtr(1,1,0.5),1.0) + + def test_bdtri(self): + assert_equal(cephes.bdtri(1,3,0.5),0.5) + + def test_bdtrc(self): + assert_equal(cephes.bdtrc(1,3,0.5),0.5) + + def test_bdtrin(self): + assert_equal(cephes.bdtrin(1,0,1),5.0) + + def test_bdtrik(self): + cephes.bdtrik(1,3,0.5) + + def test_bei(self): + assert_equal(cephes.bei(0),0.0) + + def test_beip(self): + assert_equal(cephes.beip(0),0.0) + + def test_ber(self): + assert_equal(cephes.ber(0),1.0) + + def test_berp(self): + assert_equal(cephes.berp(0),0.0) + + def test_besselpoly(self): + assert_equal(cephes.besselpoly(0,0,0),1.0) + + def test_btdtr(self): + with pytest.deprecated_call(match='deprecated in SciPy 1.12.0'): + y = special.btdtr(1, 1, 1) + assert_equal(y, 1.0) + + def test_btdtri(self): + with pytest.deprecated_call(match='deprecated in SciPy 1.12.0'): + y = special.btdtri(1, 1, 1) + assert_equal(y, 1.0) + + def test_btdtria(self): + assert_equal(cephes.btdtria(1,1,1),5.0) + + def test_btdtrib(self): + assert_equal(cephes.btdtrib(1,1,1),5.0) + + def test_cbrt(self): + assert_approx_equal(cephes.cbrt(1),1.0) + + def test_chdtr(self): + assert_equal(cephes.chdtr(1,0),0.0) + + def test_chdtrc(self): + assert_equal(cephes.chdtrc(1,0),1.0) + + def test_chdtri(self): + assert_equal(cephes.chdtri(1,1),0.0) + + def test_chdtriv(self): + assert_equal(cephes.chdtriv(0,0),5.0) + + def test_chndtr(self): + assert_equal(cephes.chndtr(0,1,0),0.0) + + # Each row holds (x, nu, lam, expected_value) + # These values were computed using Wolfram Alpha with + # CDF[NoncentralChiSquareDistribution[nu, lam], x] + values = np.array([ + [25.00, 20.0, 400, 4.1210655112396197139e-57], + [25.00, 8.00, 250, 2.3988026526832425878e-29], + [0.001, 8.00, 40., 5.3761806201366039084e-24], + [0.010, 8.00, 40., 5.45396231055999457039e-20], + [20.00, 2.00, 107, 1.39390743555819597802e-9], + [22.50, 2.00, 107, 7.11803307138105870671e-9], + [25.00, 2.00, 107, 3.11041244829864897313e-8], + [3.000, 2.00, 1.0, 0.62064365321954362734], + [350.0, 300., 10., 0.93880128006276407710], + [100.0, 13.5, 10., 0.99999999650104210949], + [700.0, 20.0, 400, 0.99999999925680650105], + [150.0, 13.5, 10., 0.99999999999999983046], + [160.0, 13.5, 10., 0.99999999999999999518], # 1.0 + ]) + cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2]) + assert_allclose(cdf, values[:, 3], rtol=1e-12) + + assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0) + assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0) + assert_(np.isnan(cephes.chndtr(np.nan, 1, 2))) + assert_(np.isnan(cephes.chndtr(5, np.nan, 2))) + assert_(np.isnan(cephes.chndtr(5, 1, np.nan))) + + def test_chndtridf(self): + assert_equal(cephes.chndtridf(0,0,1),5.0) + + def test_chndtrinc(self): + assert_equal(cephes.chndtrinc(0,1,0),5.0) + + def test_chndtrix(self): + assert_equal(cephes.chndtrix(0,1,0),0.0) + + def test_cosdg(self): + assert_equal(cephes.cosdg(0),1.0) + + def test_cosm1(self): + assert_equal(cephes.cosm1(0),0.0) + + def test_cotdg(self): + assert_almost_equal(cephes.cotdg(45),1.0) + + def test_dawsn(self): + assert_equal(cephes.dawsn(0),0.0) + assert_allclose(cephes.dawsn(1.23), 0.50053727749081767) + + def test_diric(self): + # Test behavior near multiples of 2pi. Regression test for issue + # described in gh-4001. + n_odd = [1, 5, 25] + x = np.array(2*np.pi + 5e-5).astype(np.float32) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7) + x = np.array(2*np.pi + 1e-9).astype(np.float64) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) + x = np.array(2*np.pi + 1e-15).astype(np.float64) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15) + if hasattr(np, 'float128'): + # No float128 available in 32-bit numpy + x = np.array(2*np.pi + 1e-12).astype(np.float128) + assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19) + + n_even = [2, 4, 24] + x = np.array(2*np.pi + 1e-9).astype(np.float64) + assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15) + + # Test at some values not near a multiple of pi + x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi) + octave_result = [0.872677996249965, 0.539344662916632, + 0.127322003750035, -0.206011329583298] + assert_almost_equal(special.diric(x, 3), octave_result, decimal=15) + + def test_diric_broadcasting(self): + x = np.arange(5) + n = np.array([1, 3, 7]) + assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size)) + + def test_ellipe(self): + assert_equal(cephes.ellipe(1),1.0) + + def test_ellipeinc(self): + assert_equal(cephes.ellipeinc(0,1),0.0) + + def test_ellipj(self): + cephes.ellipj(0,1) + + def test_ellipk(self): + assert_allclose(ellipk(0), pi/2) + + def test_ellipkinc(self): + assert_equal(cephes.ellipkinc(0,0),0.0) + + def test_erf(self): + assert_equal(cephes.erf(0), 0.0) + + def test_erf_symmetry(self): + x = 5.905732037710919 + assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0) + + def test_erfc(self): + assert_equal(cephes.erfc(0), 1.0) + + def test_exp10(self): + assert_approx_equal(cephes.exp10(2),100.0) + + def test_exp2(self): + assert_equal(cephes.exp2(2),4.0) + + def test_expm1(self): + assert_equal(cephes.expm1(0),0.0) + assert_equal(cephes.expm1(np.inf), np.inf) + assert_equal(cephes.expm1(-np.inf), -1) + assert_equal(cephes.expm1(np.nan), np.nan) + + def test_expm1_complex(self): + expm1 = cephes.expm1 + assert_equal(expm1(0 + 0j), 0 + 0j) + assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0)) + assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf)) + assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf)) + assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf)) + assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf)) + assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan)) + assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0)) + assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0)) + assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan)) + assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan)) + assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan)) + + @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points') + def test_expm1_complex_hard(self): + # The real part of this function is difficult to evaluate when + # z.real = -log(cos(z.imag)). + y = np.array([0.1, 0.2, 0.3, 5, 11, 20]) + x = -np.log(np.cos(y)) + z = x + 1j*y + + # evaluate using mpmath.expm1 with dps=1000 + expected = np.array([-5.5507901846769623e-17+0.10033467208545054j, + 2.4289354732893695e-18+0.20271003550867248j, + 4.5235500262585768e-17+0.30933624960962319j, + 7.8234305217489006e-17-3.3805150062465863j, + -1.3685191953697676e-16-225.95084645419513j, + 8.7175620481291045e-17+2.2371609442247422j]) + found = cephes.expm1(z) + # this passes. + assert_array_almost_equal_nulp(found.imag, expected.imag, 3) + # this fails. + assert_array_almost_equal_nulp(found.real, expected.real, 20) + + def test_fdtr(self): + assert_equal(cephes.fdtr(1, 1, 0), 0.0) + # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10] + assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488, + rtol=1e-12) + + def test_fdtrc(self): + assert_equal(cephes.fdtrc(1, 1, 0), 1.0) + # Computed using Wolfram Alpha: + # 1 - CDF[FRatioDistribution[2, 1/10], 1e10] + assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512, + rtol=1e-12) + + def test_fdtri(self): + assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]), + array([0.9937365, 1.00630298]), rtol=1e-6) + # From Wolfram Alpha: + # CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874... + p = 0.8756751669632105666874 + assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12) + + @pytest.mark.xfail(reason='Returns nan on i686.') + def test_fdtri_mysterious_failure(self): + assert_allclose(cephes.fdtri(1, 1, 0.5), 1) + + def test_fdtridfd(self): + assert_equal(cephes.fdtridfd(1,0,0),5.0) + + def test_fresnel(self): + assert_equal(cephes.fresnel(0),(0.0,0.0)) + + def test_gamma(self): + assert_equal(cephes.gamma(5),24.0) + + def test_gammainccinv(self): + assert_equal(cephes.gammainccinv(5,1),0.0) + + def test_gammaln(self): + cephes.gammaln(10) + + def test_gammasgn(self): + vals = np.array([-4, -3.5, -2.3, 1, 4.2], np.float64) + assert_array_equal(cephes.gammasgn(vals), np.sign(cephes.rgamma(vals))) + + def test_gdtr(self): + assert_equal(cephes.gdtr(1,1,0),0.0) + + def test_gdtr_inf(self): + assert_equal(cephes.gdtr(1,1,np.inf),1.0) + + def test_gdtrc(self): + assert_equal(cephes.gdtrc(1,1,0),1.0) + + def test_gdtria(self): + assert_equal(cephes.gdtria(0,1,1),0.0) + + def test_gdtrib(self): + cephes.gdtrib(1,0,1) + # assert_equal(cephes.gdtrib(1,0,1),5.0) + + def test_gdtrix(self): + cephes.gdtrix(1,1,.1) + + def test_hankel1(self): + cephes.hankel1(1,1) + + def test_hankel1e(self): + cephes.hankel1e(1,1) + + def test_hankel2(self): + cephes.hankel2(1,1) + + def test_hankel2e(self): + cephes.hankel2e(1,1) + + def test_hyp1f1(self): + assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0)) + assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095) + cephes.hyp1f1(1,1,1) + + def test_hyp2f1(self): + assert_equal(cephes.hyp2f1(1,1,1,0),1.0) + + def test_i0(self): + assert_equal(cephes.i0(0),1.0) + + def test_i0e(self): + assert_equal(cephes.i0e(0),1.0) + + def test_i1(self): + assert_equal(cephes.i1(0),0.0) + + def test_i1e(self): + assert_equal(cephes.i1e(0),0.0) + + def test_it2i0k0(self): + cephes.it2i0k0(1) + + def test_it2j0y0(self): + cephes.it2j0y0(1) + + def test_it2struve0(self): + cephes.it2struve0(1) + + def test_itairy(self): + cephes.itairy(1) + + def test_iti0k0(self): + assert_equal(cephes.iti0k0(0),(0.0,0.0)) + + def test_itj0y0(self): + assert_equal(cephes.itj0y0(0),(0.0,0.0)) + + def test_itmodstruve0(self): + assert_equal(cephes.itmodstruve0(0),0.0) + + def test_itstruve0(self): + assert_equal(cephes.itstruve0(0),0.0) + + def test_iv(self): + assert_equal(cephes.iv(1,0),0.0) + + def test_ive(self): + assert_equal(cephes.ive(1,0),0.0) + + def test_j0(self): + assert_equal(cephes.j0(0),1.0) + + def test_j1(self): + assert_equal(cephes.j1(0),0.0) + + def test_jn(self): + assert_equal(cephes.jn(0,0),1.0) + + def test_jv(self): + assert_equal(cephes.jv(0,0),1.0) + + def test_jve(self): + assert_equal(cephes.jve(0,0),1.0) + + def test_k0(self): + cephes.k0(2) + + def test_k0e(self): + cephes.k0e(2) + + def test_k1(self): + cephes.k1(2) + + def test_k1e(self): + cephes.k1e(2) + + def test_kei(self): + cephes.kei(2) + + def test_keip(self): + assert_equal(cephes.keip(0),0.0) + + def test_ker(self): + cephes.ker(2) + + def test_kerp(self): + cephes.kerp(2) + + def test_kelvin(self): + cephes.kelvin(2) + + def test_kn(self): + cephes.kn(1,1) + + def test_kolmogi(self): + assert_equal(cephes.kolmogi(1),0.0) + assert_(np.isnan(cephes.kolmogi(np.nan))) + + def test_kolmogorov(self): + assert_equal(cephes.kolmogorov(0), 1.0) + + def test_kolmogp(self): + assert_equal(cephes._kolmogp(0), -0.0) + + def test_kolmogc(self): + assert_equal(cephes._kolmogc(0), 0.0) + + def test_kolmogci(self): + assert_equal(cephes._kolmogci(0), 0.0) + assert_(np.isnan(cephes._kolmogci(np.nan))) + + def test_kv(self): + cephes.kv(1,1) + + def test_kve(self): + cephes.kve(1,1) + + def test_log1p(self): + log1p = cephes.log1p + assert_equal(log1p(0), 0.0) + assert_equal(log1p(-1), -np.inf) + assert_equal(log1p(-2), np.nan) + assert_equal(log1p(np.inf), np.inf) + + def test_log1p_complex(self): + log1p = cephes.log1p + c = complex + assert_equal(log1p(0 + 0j), 0 + 0j) + assert_equal(log1p(c(-1, 0)), c(-np.inf, 0)) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2)) + assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan)) + assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi)) + assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0)) + assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4)) + assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4)) + assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan)) + assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan)) + assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan)) + assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan)) + assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan)) + + def test_lpmv(self): + assert_equal(cephes.lpmv(0,0,1),1.0) + + def test_mathieu_a(self): + assert_equal(cephes.mathieu_a(1,0),1.0) + + def test_mathieu_b(self): + assert_equal(cephes.mathieu_b(1,0),1.0) + + def test_mathieu_cem(self): + assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0)) + + # Test AMS 20.2.27 + @np.vectorize + def ce_smallq(m, q, z): + z *= np.pi/180 + if m == 0: + # + O(q^2) + return 2**(-0.5) * (1 - .5*q*cos(2*z)) + elif m == 1: + # + O(q^2) + return cos(z) - q/8 * cos(3*z) + elif m == 2: + # + O(q^2) + return cos(2*z) - q*(cos(4*z)/12 - 1/4) + else: + # + O(q^2) + return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1))) + m = np.arange(0, 100) + q = np.r_[0, np.logspace(-30, -9, 10)] + assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0], + ce_smallq(m[:,None], q[None,:], 0.123), + rtol=1e-14, atol=0) + + def test_mathieu_sem(self): + assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0)) + + # Test AMS 20.2.27 + @np.vectorize + def se_smallq(m, q, z): + z *= np.pi/180 + if m == 1: + # + O(q^2) + return sin(z) - q/8 * sin(3*z) + elif m == 2: + # + O(q^2) + return sin(2*z) - q*sin(4*z)/12 + else: + # + O(q^2) + return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1))) + m = np.arange(1, 100) + q = np.r_[0, np.logspace(-30, -9, 10)] + assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0], + se_smallq(m[:,None], q[None,:], 0.123), + rtol=1e-14, atol=0) + + def test_mathieu_modcem1(self): + assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0)) + + def test_mathieu_modcem2(self): + cephes.mathieu_modcem2(1,1,1) + + # Test reflection relation AMS 20.6.19 + m = np.arange(0, 4)[:,None,None] + q = np.r_[np.logspace(-2, 2, 10)][None,:,None] + z = np.linspace(0, 1, 7)[None,None,:] + + y1 = cephes.mathieu_modcem2(m, q, -z)[0] + + fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0] + y2 = (-cephes.mathieu_modcem2(m, q, z)[0] + - 2*fr*cephes.mathieu_modcem1(m, q, z)[0]) + + assert_allclose(y1, y2, rtol=1e-10) + + def test_mathieu_modsem1(self): + assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0)) + + def test_mathieu_modsem2(self): + cephes.mathieu_modsem2(1,1,1) + + # Test reflection relation AMS 20.6.20 + m = np.arange(1, 4)[:,None,None] + q = np.r_[np.logspace(-2, 2, 10)][None,:,None] + z = np.linspace(0, 1, 7)[None,None,:] + + y1 = cephes.mathieu_modsem2(m, q, -z)[0] + fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1] + y2 = (cephes.mathieu_modsem2(m, q, z)[0] + - 2*fr*cephes.mathieu_modsem1(m, q, z)[0]) + assert_allclose(y1, y2, rtol=1e-10) + + def test_mathieu_overflow(self): + # Check that these return NaNs instead of causing a SEGV + assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan)) + assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan)) + + def test_mathieu_ticket_1847(self): + # Regression test --- this call had some out-of-bounds access + # and could return nan occasionally + for k in range(60): + v = cephes.mathieu_modsem2(2, 100, -1) + # Values from ACM TOMS 804 (derivate by numerical differentiation) + assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10) + assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4) + + def test_modfresnelm(self): + cephes.modfresnelm(0) + + def test_modfresnelp(self): + cephes.modfresnelp(0) + + def test_modstruve(self): + assert_equal(cephes.modstruve(1,0),0.0) + + def test_nbdtr(self): + assert_equal(cephes.nbdtr(1,1,1),1.0) + + def test_nbdtrc(self): + assert_equal(cephes.nbdtrc(1,1,1),0.0) + + def test_nbdtri(self): + assert_equal(cephes.nbdtri(1,1,1),1.0) + + def test_nbdtrik(self): + cephes.nbdtrik(1,.4,.5) + + def test_nbdtrin(self): + assert_equal(cephes.nbdtrin(1,0,0),5.0) + + def test_ncfdtr(self): + assert_equal(cephes.ncfdtr(1,1,1,0),0.0) + + def test_ncfdtri(self): + assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0) + f = [0.5, 1, 1.5] + p = cephes.ncfdtr(2, 3, 1.5, f) + assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f) + + def test_ncfdtridfd(self): + dfd = [1, 2, 3] + p = cephes.ncfdtr(2, dfd, 0.25, 15) + assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd) + + def test_ncfdtridfn(self): + dfn = [0.1, 1, 2, 3, 1e4] + p = cephes.ncfdtr(dfn, 2, 0.25, 15) + assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5) + + def test_ncfdtrinc(self): + nc = [0.5, 1.5, 2.0] + p = cephes.ncfdtr(2, 3, nc, 15) + assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc) + + def test_nctdtr(self): + assert_equal(cephes.nctdtr(1,0,0),0.5) + assert_equal(cephes.nctdtr(9, 65536, 45), 0.0) + + assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5) + assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.))) + assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.) + + assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.))) + assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.))) + assert_(np.isnan(cephes.nctdtr(2., 1., np.nan))) + + def test_nctdtridf(self): + cephes.nctdtridf(1,0.5,0) + + def test_nctdtrinc(self): + cephes.nctdtrinc(1,0,0) + + def test_nctdtrit(self): + cephes.nctdtrit(.1,0.2,.5) + + def test_nrdtrimn(self): + assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0) + + def test_nrdtrisd(self): + assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0, + atol=0, rtol=0) + + def test_obl_ang1(self): + cephes.obl_ang1(1,1,1,0) + + def test_obl_ang1_cv(self): + result = cephes.obl_ang1_cv(1,1,1,1,0) + assert_almost_equal(result[0],1.0) + assert_almost_equal(result[1],0.0) + + def test_obl_cv(self): + assert_equal(cephes.obl_cv(1,1,0),2.0) + + def test_obl_rad1(self): + cephes.obl_rad1(1,1,1,0) + + def test_obl_rad1_cv(self): + cephes.obl_rad1_cv(1,1,1,1,0) + + def test_obl_rad2(self): + cephes.obl_rad2(1,1,1,0) + + def test_obl_rad2_cv(self): + cephes.obl_rad2_cv(1,1,1,1,0) + + def test_pbdv(self): + assert_equal(cephes.pbdv(1,0),(0.0,1.0)) + + def test_pbvv(self): + cephes.pbvv(1,0) + + def test_pbwa(self): + cephes.pbwa(1,0) + + def test_pdtr(self): + val = cephes.pdtr(0, 1) + assert_almost_equal(val, np.exp(-1)) + # Edge case: m = 0. + val = cephes.pdtr([0, 1, 2], 0) + assert_array_equal(val, [1, 1, 1]) + + def test_pdtrc(self): + val = cephes.pdtrc(0, 1) + assert_almost_equal(val, 1 - np.exp(-1)) + # Edge case: m = 0. + val = cephes.pdtrc([0, 1, 2], 0.0) + assert_array_equal(val, [0, 0, 0]) + + def test_pdtri(self): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "floating point number truncated to an integer") + cephes.pdtri(0.5,0.5) + + def test_pdtrik(self): + k = cephes.pdtrik(0.5, 1) + assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5) + # Edge case: m = 0 or very small. + k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6]) + assert_array_equal(k, np.zeros((3, 3))) + + def test_pro_ang1(self): + cephes.pro_ang1(1,1,1,0) + + def test_pro_ang1_cv(self): + assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0), + array((1.0,0.0))) + + def test_pro_cv(self): + assert_equal(cephes.pro_cv(1,1,0),2.0) + + def test_pro_rad1(self): + cephes.pro_rad1(1,1,1,0.1) + + def test_pro_rad1_cv(self): + cephes.pro_rad1_cv(1,1,1,1,0) + + def test_pro_rad2(self): + cephes.pro_rad2(1,1,1,0) + + def test_pro_rad2_cv(self): + cephes.pro_rad2_cv(1,1,1,1,0) + + def test_psi(self): + cephes.psi(1) + + def test_radian(self): + assert_equal(cephes.radian(0,0,0),0) + + def test_rgamma(self): + assert_equal(cephes.rgamma(1),1.0) + + def test_round(self): + assert_equal(cephes.round(3.4),3.0) + assert_equal(cephes.round(-3.4),-3.0) + assert_equal(cephes.round(3.6),4.0) + assert_equal(cephes.round(-3.6),-4.0) + assert_equal(cephes.round(3.5),4.0) + assert_equal(cephes.round(-3.5),-4.0) + + def test_shichi(self): + cephes.shichi(1) + + def test_sici(self): + cephes.sici(1) + + s, c = cephes.sici(np.inf) + assert_almost_equal(s, np.pi * 0.5) + assert_almost_equal(c, 0) + + s, c = cephes.sici(-np.inf) + assert_almost_equal(s, -np.pi * 0.5) + assert_(np.isnan(c), "cosine integral(-inf) is not nan") + + def test_sindg(self): + assert_equal(cephes.sindg(90),1.0) + + def test_smirnov(self): + assert_equal(cephes.smirnov(1,.1),0.9) + assert_(np.isnan(cephes.smirnov(1,np.nan))) + + def test_smirnovp(self): + assert_equal(cephes._smirnovp(1, .1), -1) + assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1)) + assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1)) + assert_(np.isnan(cephes._smirnovp(1, np.nan))) + + def test_smirnovc(self): + assert_equal(cephes._smirnovc(1,.1),0.1) + assert_(np.isnan(cephes._smirnovc(1,np.nan))) + x10 = np.linspace(0, 1, 11, endpoint=True) + assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10)) + x4 = np.linspace(0, 1, 5, endpoint=True) + assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4)) + + def test_smirnovi(self): + assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4) + assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6) + assert_(np.isnan(cephes.smirnovi(1,np.nan))) + + def test_smirnovci(self): + assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4) + assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6) + assert_(np.isnan(cephes._smirnovci(1,np.nan))) + + def test_spence(self): + assert_equal(cephes.spence(1),0.0) + + def test_stdtr(self): + assert_equal(cephes.stdtr(1,0),0.5) + assert_almost_equal(cephes.stdtr(1,1), 0.75) + assert_almost_equal(cephes.stdtr(1,2), 0.852416382349) + + def test_stdtridf(self): + cephes.stdtridf(0.7,1) + + def test_stdtrit(self): + cephes.stdtrit(1,0.7) + + def test_struve(self): + assert_equal(cephes.struve(0,0),0.0) + + def test_tandg(self): + assert_equal(cephes.tandg(45),1.0) + + def test_tklmbda(self): + assert_almost_equal(cephes.tklmbda(1,1),1.0) + + def test_y0(self): + cephes.y0(1) + + def test_y1(self): + cephes.y1(1) + + def test_yn(self): + cephes.yn(1,1) + + def test_yv(self): + cephes.yv(1,1) + + def test_yve(self): + cephes.yve(1,1) + + def test_wofz(self): + z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.), + complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.), + complex(-0.0000000234545,1.1234), complex(-3.,5.1), + complex(-53,30.1), complex(0.0,0.12345), + complex(11,1), complex(-22,-2), complex(9,-28), + complex(21,-33), complex(1e5,1e5), complex(1e14,1e14) + ] + w = [ + complex(-3.78270245518980507452677445620103199303131110e-7, + 0.000903861276433172057331093754199933411710053155), + complex(0.1764906227004816847297495349730234591778719532788, + -0.02146550539468457616788719893991501311573031095617), + complex(0.2410250715772692146133539023007113781272362309451, + 0.06087579663428089745895459735240964093522265589350), + complex(0.30474420525691259245713884106959496013413834051768, + -0.20821893820283162728743734725471561394145872072738), + complex(7.317131068972378096865595229600561710140617977e34, + 8.321873499714402777186848353320412813066170427e34), + complex(0.0615698507236323685519612934241429530190806818395, + -0.00676005783716575013073036218018565206070072304635), + complex(0.3960793007699874918961319170187598400134746631, + -5.593152259116644920546186222529802777409274656e-9), + complex(0.08217199226739447943295069917990417630675021771804, + -0.04701291087643609891018366143118110965272615832184), + complex(0.00457246000350281640952328010227885008541748668738, + -0.00804900791411691821818731763401840373998654987934), + complex(0.8746342859608052666092782112565360755791467973338452, + 0.), + complex(0.00468190164965444174367477874864366058339647648741, + 0.0510735563901306197993676329845149741675029197050), + complex(-0.0023193175200187620902125853834909543869428763219, + -0.025460054739731556004902057663500272721780776336), + complex(9.11463368405637174660562096516414499772662584e304, + 3.97101807145263333769664875189354358563218932e305), + complex(-4.4927207857715598976165541011143706155432296e281, + -2.8019591213423077494444700357168707775769028e281), + complex(2.820947917809305132678577516325951485807107151e-6, + 2.820947917668257736791638444590253942253354058e-6), + complex(2.82094791773878143474039725787438662716372268e-15, + 2.82094791773878143474039725773333923127678361e-15) + ] + assert_func_equal(cephes.wofz, w, z, rtol=1e-13) + + +class TestAiry: + def test_airy(self): + # This tests the airy function to ensure 8 place accuracy in computation + + x = special.airy(.99) + assert_array_almost_equal( + x, + array([0.13689066,-0.16050153,1.19815925,0.92046818]), + 8, + ) + x = special.airy(.41) + assert_array_almost_equal( + x, + array([0.25238916,-.23480512,0.80686202,0.51053919]), + 8, + ) + x = special.airy(-.36) + assert_array_almost_equal( + x, + array([0.44508477,-0.23186773,0.44939534,0.48105354]), + 8, + ) + + def test_airye(self): + a = special.airye(0.01) + b = special.airy(0.01) + b1 = [None]*4 + for n in range(2): + b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01)) + for n in range(2,4): + b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01)))) + assert_array_almost_equal(a,b1,6) + + def test_bi_zeros(self): + bi = special.bi_zeros(2) + bia = (array([-1.17371322, -3.2710930]), + array([-2.29443968, -4.07315509]), + array([-0.45494438, 0.39652284]), + array([0.60195789, -0.76031014])) + assert_array_almost_equal(bi,bia,4) + + bi = special.bi_zeros(5) + assert_array_almost_equal(bi[0],array([-1.173713222709127, + -3.271093302836352, + -4.830737841662016, + -6.169852128310251, + -7.376762079367764]),11) + + assert_array_almost_equal(bi[1],array([-2.294439682614122, + -4.073155089071828, + -5.512395729663599, + -6.781294445990305, + -7.940178689168587]),10) + + assert_array_almost_equal(bi[2],array([-0.454944383639657, + 0.396522836094465, + -0.367969161486959, + 0.349499116831805, + -0.336026240133662]),11) + + assert_array_almost_equal(bi[3],array([0.601957887976239, + -0.760310141492801, + 0.836991012619261, + -0.88947990142654, + 0.929983638568022]),10) + + def test_ai_zeros(self): + ai = special.ai_zeros(1) + assert_array_almost_equal(ai,(array([-2.33810741]), + array([-1.01879297]), + array([0.5357]), + array([0.7012])),4) + + def test_ai_zeros_big(self): + z, zp, ai_zpx, aip_zx = special.ai_zeros(50000) + ai_z, aip_z, _, _ = special.airy(z) + ai_zp, aip_zp, _, _ = special.airy(zp) + + ai_envelope = 1/abs(z)**(1./4) + aip_envelope = abs(zp)**(1./4) + + # Check values + assert_allclose(ai_zpx, ai_zp, rtol=1e-10) + assert_allclose(aip_zx, aip_z, rtol=1e-10) + + # Check they are zeros + assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0) + assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0) + + # Check first zeros, DLMF 9.9.1 + assert_allclose(z[:6], + [-2.3381074105, -4.0879494441, -5.5205598281, + -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10) + assert_allclose(zp[:6], + [-1.0187929716, -3.2481975822, -4.8200992112, + -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10) + + def test_bi_zeros_big(self): + z, zp, bi_zpx, bip_zx = special.bi_zeros(50000) + _, _, bi_z, bip_z = special.airy(z) + _, _, bi_zp, bip_zp = special.airy(zp) + + bi_envelope = 1/abs(z)**(1./4) + bip_envelope = abs(zp)**(1./4) + + # Check values + assert_allclose(bi_zpx, bi_zp, rtol=1e-10) + assert_allclose(bip_zx, bip_z, rtol=1e-10) + + # Check they are zeros + assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0) + assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0) + + # Check first zeros, DLMF 9.9.2 + assert_allclose(z[:6], + [-1.1737132227, -3.2710933028, -4.8307378417, + -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10) + assert_allclose(zp[:6], + [-2.2944396826, -4.0731550891, -5.5123957297, + -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10) + + +class TestAssocLaguerre: + def test_assoc_laguerre(self): + a1 = special.genlaguerre(11,1) + a2 = special.assoc_laguerre(.2,11,1) + assert_array_almost_equal(a2,a1(.2),8) + a2 = special.assoc_laguerre(1,11,1) + assert_array_almost_equal(a2,a1(1),8) + + +class TestBesselpoly: + def test_besselpoly(self): + pass + + +class TestKelvin: + def test_bei(self): + mbei = special.bei(2) + assert_almost_equal(mbei, 0.9722916273066613,5) # this may not be exact + + def test_beip(self): + mbeip = special.beip(2) + assert_almost_equal(mbeip,0.91701361338403631,5) # this may not be exact + + def test_ber(self): + mber = special.ber(2) + assert_almost_equal(mber,0.75173418271380821,5) # this may not be exact + + def test_berp(self): + mberp = special.berp(2) + assert_almost_equal(mberp,-0.49306712470943909,5) # this may not be exact + + def test_bei_zeros(self): + # Abramowitz & Stegun, Table 9.12 + bi = special.bei_zeros(5) + assert_array_almost_equal(bi,array([5.02622, + 9.45541, + 13.89349, + 18.33398, + 22.77544]),4) + + def test_beip_zeros(self): + bip = special.beip_zeros(5) + assert_array_almost_equal(bip,array([3.772673304934953, + 8.280987849760042, + 12.742147523633703, + 17.193431752512542, + 21.641143941167325]),8) + + def test_ber_zeros(self): + ber = special.ber_zeros(5) + assert_array_almost_equal(ber,array([2.84892, + 7.23883, + 11.67396, + 16.11356, + 20.55463]),4) + + def test_berp_zeros(self): + brp = special.berp_zeros(5) + assert_array_almost_equal(brp,array([6.03871, + 10.51364, + 14.96844, + 19.41758, + 23.86430]),4) + + def test_kelvin(self): + mkelv = special.kelvin(2) + assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j, + special.ker(2) + special.kei(2)*1j, + special.berp(2) + special.beip(2)*1j, + special.kerp(2) + special.keip(2)*1j),8) + + def test_kei(self): + mkei = special.kei(2) + assert_almost_equal(mkei,-0.20240006776470432,5) + + def test_keip(self): + mkeip = special.keip(2) + assert_almost_equal(mkeip,0.21980790991960536,5) + + def test_ker(self): + mker = special.ker(2) + assert_almost_equal(mker,-0.041664513991509472,5) + + def test_kerp(self): + mkerp = special.kerp(2) + assert_almost_equal(mkerp,-0.10660096588105264,5) + + def test_kei_zeros(self): + kei = special.kei_zeros(5) + assert_array_almost_equal(kei,array([3.91467, + 8.34422, + 12.78256, + 17.22314, + 21.66464]),4) + + def test_keip_zeros(self): + keip = special.keip_zeros(5) + assert_array_almost_equal(keip,array([4.93181, + 9.40405, + 13.85827, + 18.30717, + 22.75379]),4) + + # numbers come from 9.9 of A&S pg. 381 + def test_kelvin_zeros(self): + tmp = special.kelvin_zeros(5) + berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp + assert_array_almost_equal(berz,array([2.84892, + 7.23883, + 11.67396, + 16.11356, + 20.55463]),4) + assert_array_almost_equal(beiz,array([5.02622, + 9.45541, + 13.89349, + 18.33398, + 22.77544]),4) + assert_array_almost_equal(kerz,array([1.71854, + 6.12728, + 10.56294, + 15.00269, + 19.44382]),4) + assert_array_almost_equal(keiz,array([3.91467, + 8.34422, + 12.78256, + 17.22314, + 21.66464]),4) + assert_array_almost_equal(berpz,array([6.03871, + 10.51364, + 14.96844, + 19.41758, + 23.86430]),4) + assert_array_almost_equal(beipz,array([3.77267, + # table from 1927 had 3.77320 + # but this is more accurate + 8.28099, + 12.74215, + 17.19343, + 21.64114]),4) + assert_array_almost_equal(kerpz,array([2.66584, + 7.17212, + 11.63218, + 16.08312, + 20.53068]),4) + assert_array_almost_equal(keipz,array([4.93181, + 9.40405, + 13.85827, + 18.30717, + 22.75379]),4) + + def test_ker_zeros(self): + ker = special.ker_zeros(5) + assert_array_almost_equal(ker,array([1.71854, + 6.12728, + 10.56294, + 15.00269, + 19.44381]),4) + + def test_kerp_zeros(self): + kerp = special.kerp_zeros(5) + assert_array_almost_equal(kerp,array([2.66584, + 7.17212, + 11.63218, + 16.08312, + 20.53068]),4) + + +class TestBernoulli: + def test_bernoulli(self): + brn = special.bernoulli(5) + assert_array_almost_equal(brn,array([1.0000, + -0.5000, + 0.1667, + 0.0000, + -0.0333, + 0.0000]),4) + + +class TestBeta: + """ + Test beta and betaln. + """ + + def test_beta(self): + assert_equal(special.beta(1, 1), 1.0) + assert_allclose(special.beta(-100.3, 1e-200), special.gamma(1e-200)) + assert_allclose(special.beta(0.0342, 171), 24.070498359873497, + rtol=1e-13, atol=0) + + bet = special.beta(2, 4) + betg = (special.gamma(2)*special.gamma(4))/special.gamma(6) + assert_allclose(bet, betg, rtol=1e-13) + + def test_beta_inf(self): + assert_(np.isinf(special.beta(-1, 2))) + + def test_betaln(self): + assert_equal(special.betaln(1, 1), 0.0) + assert_allclose(special.betaln(-100.3, 1e-200), + special.gammaln(1e-200)) + assert_allclose(special.betaln(0.0342, 170), 3.1811881124242447, + rtol=1e-14, atol=0) + + betln = special.betaln(2, 4) + bet = log(abs(special.beta(2, 4))) + assert_allclose(betln, bet, rtol=1e-13) + + +class TestBetaInc: + """ + Tests for betainc, betaincinv, betaincc, betainccinv. + """ + + def test_a1_b1(self): + # betainc(1, 1, x) is x. + x = np.array([0, 0.25, 1]) + assert_equal(special.betainc(1, 1, x), x) + assert_equal(special.betaincinv(1, 1, x), x) + assert_equal(special.betaincc(1, 1, x), 1 - x) + assert_equal(special.betainccinv(1, 1, x), 1 - x) + + # Nontrivial expected values computed with mpmath: + # from mpmath import mp + # mp.dps = 100 + # p = mp.betainc(a, b, 0, x, regularized=True) + # + # or, e.g., + # + # p = 0.25 + # a, b = 0.0342, 171 + # x = mp.findroot( + # lambda t: mp.betainc(a, b, 0, t, regularized=True) - p, + # (8e-21, 9e-21), + # solver='anderson', + # ) + # + @pytest.mark.parametrize( + 'a, b, x, p', + [(2, 4, 0.3138101704556974, 0.5), + (0.0342, 171.0, 1e-10, 0.552699169018070910641), + # gh-3761: + (0.0342, 171, 8.42313169354797e-21, 0.25), + # gh-4244: + (0.0002742794749792665, 289206.03125, 1.639984034231756e-56, + 0.9688708782196045), + # gh-12796: + (4, 99997, 0.0001947841578892121, 0.999995)]) + def test_betainc_betaincinv(self, a, b, x, p): + p1 = special.betainc(a, b, x) + assert_allclose(p1, p, rtol=1e-15) + x1 = special.betaincinv(a, b, p) + assert_allclose(x1, x, rtol=5e-13) + + # Expected values computed with mpmath: + # from mpmath import mp + # mp.dps = 100 + # p = mp.betainc(a, b, x, 1, regularized=True) + @pytest.mark.parametrize('a, b, x, p', + [(2.5, 3.0, 0.25, 0.833251953125), + (7.5, 13.25, 0.375, 0.43298734645560368593), + (0.125, 7.5, 0.425, 0.0006688257851314237), + (0.125, 18.0, 1e-6, 0.72982359145096327654), + (0.125, 18.0, 0.996, 7.2745875538380150586e-46), + (0.125, 24.0, 0.75, 3.70853404816862016966e-17), + (16.0, 0.75, 0.99999999975, + 5.4408759277418629909e-07), + # gh-4677 (numbers from stackoverflow question): + (0.4211959643503401, 16939.046996018118, + 0.000815296167195521, 1e-7)]) + def test_betaincc_betainccinv(self, a, b, x, p): + p1 = special.betaincc(a, b, x) + assert_allclose(p1, p, rtol=5e-15) + x1 = special.betainccinv(a, b, p) + assert_allclose(x1, x, rtol=8e-15) + + @pytest.mark.parametrize( + 'a, b, y, ref', + [(14.208308325339239, 14.208308325339239, 7.703145458496392e-307, + 8.566004561846704e-23), + (14.0, 14.5, 1e-280, 2.9343915006642424e-21), + (3.5, 15.0, 4e-95, 1.3290751429289227e-28), + (10.0, 1.25, 2e-234, 3.982659092143654e-24), + (4.0, 99997.0, 5e-88, 3.309800566862242e-27)] + ) + def test_betaincinv_tiny_y(self, a, b, y, ref): + # Test with extremely small y values. This test includes + # a regression test for an issue in the boost code; + # see https://github.com/boostorg/math/issues/961 + # + # The reference values were computed with mpmath. For example, + # + # from mpmath import mp + # mp.dps = 1000 + # a = 14.208308325339239 + # p = 7.703145458496392e-307 + # x = mp.findroot(lambda t: mp.betainc(a, a, 0, t, + # regularized=True) - p, + # x0=8.566e-23) + # print(float(x)) + # + x = special.betaincinv(a, b, y) + assert_allclose(x, ref, rtol=1e-14) + + @pytest.mark.parametrize('func', [special.betainc, special.betaincinv, + special.betaincc, special.betainccinv]) + @pytest.mark.parametrize('args', [(-1.0, 2, 0.5), (0, 2, 0.5), + (1.5, -2.0, 0.5), (1.5, 0, 0.5), + (1.5, 2.0, -0.3), (1.5, 2.0, 1.1)]) + def test_betainc_domain_errors(self, func, args): + with special.errstate(domain='raise'): + with pytest.raises(special.SpecialFunctionError, match='domain'): + special.betainc(*args) + + +class TestCombinatorics: + def test_comb(self): + assert_array_almost_equal(special.comb([10, 10], [3, 4]), [120., 210.]) + assert_almost_equal(special.comb(10, 3), 120.) + assert_equal(special.comb(10, 3, exact=True), 120) + assert_equal(special.comb(10, 3, exact=True, repetition=True), 220) + + assert_allclose([special.comb(20, k, exact=True) for k in range(21)], + special.comb(20, list(range(21))), atol=1e-15) + + ii = np.iinfo(int).max + 1 + assert_equal(special.comb(ii, ii-1, exact=True), ii) + + expected = 100891344545564193334812497256 + assert special.comb(100, 50, exact=True) == expected + + @pytest.mark.parametrize("repetition", [True, False]) + @pytest.mark.parametrize("legacy", [True, False, _NoValue]) + @pytest.mark.parametrize("k", [3.5, 3]) + @pytest.mark.parametrize("N", [4.5, 4]) + def test_comb_legacy(self, N, k, legacy, repetition): + # test is only relevant for exact=True + if legacy is not _NoValue: + with pytest.warns( + DeprecationWarning, + match=r"Using 'legacy' keyword is deprecated" + ): + result = special.comb(N, k, exact=True, legacy=legacy, + repetition=repetition) + else: + result = special.comb(N, k, exact=True, legacy=legacy, + repetition=repetition) + if legacy: + # for exact=True and legacy=True, cast input arguments, else don't + if repetition: + # the casting in legacy mode happens AFTER transforming N & k, + # so rounding can change (e.g. both floats, but sum to int); + # hence we need to emulate the repetition-transformation here + N, k = int(N + k - 1), int(k) + repetition = False + else: + N, k = int(N), int(k) + # expected result is the same as with exact=False + with suppress_warnings() as sup: + if legacy is not _NoValue: + sup.filter(DeprecationWarning) + expected = special.comb(N, k, legacy=legacy, repetition=repetition) + assert_equal(result, expected) + + def test_comb_with_np_int64(self): + n = 70 + k = 30 + np_n = np.int64(n) + np_k = np.int64(k) + res_np = special.comb(np_n, np_k, exact=True) + res_py = special.comb(n, k, exact=True) + assert res_np == res_py + + def test_comb_zeros(self): + assert_equal(special.comb(2, 3, exact=True), 0) + assert_equal(special.comb(-1, 3, exact=True), 0) + assert_equal(special.comb(2, -1, exact=True), 0) + assert_equal(special.comb(2, -1, exact=False), 0) + assert_array_almost_equal(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), + [0., 0., 0., 120.]) + + def test_perm(self): + assert_array_almost_equal(special.perm([10, 10], [3, 4]), [720., 5040.]) + assert_almost_equal(special.perm(10, 3), 720.) + assert_equal(special.perm(10, 3, exact=True), 720) + + def test_perm_zeros(self): + assert_equal(special.perm(2, 3, exact=True), 0) + assert_equal(special.perm(-1, 3, exact=True), 0) + assert_equal(special.perm(2, -1, exact=True), 0) + assert_equal(special.perm(2, -1, exact=False), 0) + assert_array_almost_equal(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), + [0., 0., 0., 720.]) + + def test_positional_deprecation(self): + with pytest.deprecated_call(match="use keyword arguments"): + # from test_comb + special.comb([10, 10], [3, 4], False, False) + + +class TestTrigonometric: + def test_cbrt(self): + cb = special.cbrt(27) + cbrl = 27**(1.0/3.0) + assert_approx_equal(cb,cbrl) + + def test_cbrtmore(self): + cb1 = special.cbrt(27.9) + cbrl1 = 27.9**(1.0/3.0) + assert_almost_equal(cb1,cbrl1,8) + + def test_cosdg(self): + cdg = special.cosdg(90) + cdgrl = cos(pi/2.0) + assert_almost_equal(cdg,cdgrl,8) + + def test_cosdgmore(self): + cdgm = special.cosdg(30) + cdgmrl = cos(pi/6.0) + assert_almost_equal(cdgm,cdgmrl,8) + + def test_cosm1(self): + cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10)) + csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1) + assert_array_almost_equal(cs,csrl,8) + + def test_cotdg(self): + ct = special.cotdg(30) + ctrl = tan(pi/6.0)**(-1) + assert_almost_equal(ct,ctrl,8) + + def test_cotdgmore(self): + ct1 = special.cotdg(45) + ctrl1 = tan(pi/4.0)**(-1) + assert_almost_equal(ct1,ctrl1,8) + + def test_specialpoints(self): + assert_almost_equal(special.cotdg(45), 1.0, 14) + assert_almost_equal(special.cotdg(-45), -1.0, 14) + assert_almost_equal(special.cotdg(90), 0.0, 14) + assert_almost_equal(special.cotdg(-90), 0.0, 14) + assert_almost_equal(special.cotdg(135), -1.0, 14) + assert_almost_equal(special.cotdg(-135), 1.0, 14) + assert_almost_equal(special.cotdg(225), 1.0, 14) + assert_almost_equal(special.cotdg(-225), -1.0, 14) + assert_almost_equal(special.cotdg(270), 0.0, 14) + assert_almost_equal(special.cotdg(-270), 0.0, 14) + assert_almost_equal(special.cotdg(315), -1.0, 14) + assert_almost_equal(special.cotdg(-315), 1.0, 14) + assert_almost_equal(special.cotdg(765), 1.0, 14) + + def test_sinc(self): + # the sinc implementation and more extensive sinc tests are in numpy + assert_array_equal(special.sinc([0]), 1) + assert_equal(special.sinc(0.0), 1.0) + + def test_sindg(self): + sn = special.sindg(90) + assert_equal(sn,1.0) + + def test_sindgmore(self): + snm = special.sindg(30) + snmrl = sin(pi/6.0) + assert_almost_equal(snm,snmrl,8) + snm1 = special.sindg(45) + snmrl1 = sin(pi/4.0) + assert_almost_equal(snm1,snmrl1,8) + + +class TestTandg: + + def test_tandg(self): + tn = special.tandg(30) + tnrl = tan(pi/6.0) + assert_almost_equal(tn,tnrl,8) + + def test_tandgmore(self): + tnm = special.tandg(45) + tnmrl = tan(pi/4.0) + assert_almost_equal(tnm,tnmrl,8) + tnm1 = special.tandg(60) + tnmrl1 = tan(pi/3.0) + assert_almost_equal(tnm1,tnmrl1,8) + + def test_specialpoints(self): + assert_almost_equal(special.tandg(0), 0.0, 14) + assert_almost_equal(special.tandg(45), 1.0, 14) + assert_almost_equal(special.tandg(-45), -1.0, 14) + assert_almost_equal(special.tandg(135), -1.0, 14) + assert_almost_equal(special.tandg(-135), 1.0, 14) + assert_almost_equal(special.tandg(180), 0.0, 14) + assert_almost_equal(special.tandg(-180), 0.0, 14) + assert_almost_equal(special.tandg(225), 1.0, 14) + assert_almost_equal(special.tandg(-225), -1.0, 14) + assert_almost_equal(special.tandg(315), -1.0, 14) + assert_almost_equal(special.tandg(-315), 1.0, 14) + + +class TestEllip: + def test_ellipj_nan(self): + """Regression test for #912.""" + special.ellipj(0.5, np.nan) + + def test_ellipj(self): + el = special.ellipj(0.2,0) + rel = [sin(0.2),cos(0.2),1.0,0.20] + assert_array_almost_equal(el,rel,13) + + def test_ellipk(self): + elk = special.ellipk(.2) + assert_almost_equal(elk,1.659623598610528,11) + + assert_equal(special.ellipkm1(0.0), np.inf) + assert_equal(special.ellipkm1(1.0), pi/2) + assert_equal(special.ellipkm1(np.inf), 0.0) + assert_equal(special.ellipkm1(np.nan), np.nan) + assert_equal(special.ellipkm1(-1), np.nan) + assert_allclose(special.ellipk(-10), 0.7908718902387385) + + def test_ellipkinc(self): + elkinc = special.ellipkinc(pi/2,.2) + elk = special.ellipk(0.2) + assert_almost_equal(elkinc,elk,15) + alpha = 20*pi/180 + phi = 45*pi/180 + m = sin(alpha)**2 + elkinc = special.ellipkinc(phi,m) + assert_almost_equal(elkinc,0.79398143,8) + # From pg. 614 of A & S + + assert_equal(special.ellipkinc(pi/2, 0.0), pi/2) + assert_equal(special.ellipkinc(pi/2, 1.0), np.inf) + assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0) + assert_equal(special.ellipkinc(pi/2, np.nan), np.nan) + assert_equal(special.ellipkinc(pi/2, 2), np.nan) + assert_equal(special.ellipkinc(0, 0.5), 0.0) + assert_equal(special.ellipkinc(np.inf, 0.5), np.inf) + assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf) + assert_equal(special.ellipkinc(np.inf, np.inf), np.nan) + assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan) + assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan) + assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan) + assert_equal(special.ellipkinc(np.nan, 0.5), np.nan) + assert_equal(special.ellipkinc(np.nan, np.nan), np.nan) + + assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14) + assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946) + + def test_ellipkinc_2(self): + # Regression test for gh-3550 + # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value + mbad = 0.68359375000000011 + phi = 0.9272952180016123 + m = np.nextafter(mbad, 0) + mvals = [] + for j in range(10): + mvals.append(m) + m = np.nextafter(m, 1) + f = special.ellipkinc(phi, mvals) + assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1) + # this bug also appears at phi + n * pi for at least small n + f1 = special.ellipkinc(phi + pi, mvals) + assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2) + + def test_ellipkinc_singular(self): + # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2) + xlog = np.logspace(-300, -17, 25) + xlin = np.linspace(1e-17, 0.1, 25) + xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False) + + assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)), + rtol=1e14) + assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)), + rtol=1e14) + assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)), + rtol=1e14) + assert_equal(special.ellipkinc(np.pi/2, 1), np.inf) + assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)), + rtol=1e14) + assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)), + rtol=1e14) + assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)), + rtol=1e14) + assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf) + + def test_ellipe(self): + ele = special.ellipe(.2) + assert_almost_equal(ele,1.4890350580958529,8) + + assert_equal(special.ellipe(0.0), pi/2) + assert_equal(special.ellipe(1.0), 1.0) + assert_equal(special.ellipe(-np.inf), np.inf) + assert_equal(special.ellipe(np.nan), np.nan) + assert_equal(special.ellipe(2), np.nan) + assert_allclose(special.ellipe(-10), 3.6391380384177689) + + def test_ellipeinc(self): + eleinc = special.ellipeinc(pi/2,.2) + ele = special.ellipe(0.2) + assert_almost_equal(eleinc,ele,14) + # pg 617 of A & S + alpha, phi = 52*pi/180,35*pi/180 + m = sin(alpha)**2 + eleinc = special.ellipeinc(phi,m) + assert_almost_equal(eleinc, 0.58823065, 8) + + assert_equal(special.ellipeinc(pi/2, 0.0), pi/2) + assert_equal(special.ellipeinc(pi/2, 1.0), 1.0) + assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf) + assert_equal(special.ellipeinc(pi/2, np.nan), np.nan) + assert_equal(special.ellipeinc(pi/2, 2), np.nan) + assert_equal(special.ellipeinc(0, 0.5), 0.0) + assert_equal(special.ellipeinc(np.inf, 0.5), np.inf) + assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf) + assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf) + assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf) + assert_equal(special.ellipeinc(np.inf, np.inf), np.nan) + assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan) + assert_equal(special.ellipeinc(np.nan, 0.5), np.nan) + assert_equal(special.ellipeinc(np.nan, np.nan), np.nan) + assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876) + + def test_ellipeinc_2(self): + # Regression test for gh-3550 + # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value + mbad = 0.68359375000000011 + phi = 0.9272952180016123 + m = np.nextafter(mbad, 0) + mvals = [] + for j in range(10): + mvals.append(m) + m = np.nextafter(m, 1) + f = special.ellipeinc(phi, mvals) + assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2) + # this bug also appears at phi + n * pi for at least small n + f1 = special.ellipeinc(phi + pi, mvals) + assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4) + + +class TestEllipCarlson: + """Test for Carlson elliptic integrals ellipr[cdfgj]. + The special values used in these tests can be found in Sec. 3 of Carlson + (1994), https://arxiv.org/abs/math/9409227 + """ + def test_elliprc(self): + assert_allclose(elliprc(1, 1), 1) + assert elliprc(1, inf) == 0.0 + assert isnan(elliprc(1, 0)) + assert elliprc(1, complex(1, inf)) == 0.0 + args = array([[0.0, 0.25], + [2.25, 2.0], + [0.0, 1.0j], + [-1.0j, 1.0j], + [0.25, -2.0], + [1.0j, -1.0]]) + expected_results = array([np.pi, + np.log(2.0), + 1.1107207345396 * (1.0-1.0j), + 1.2260849569072-0.34471136988768j, + np.log(2.0) / 3.0, + 0.77778596920447+0.19832484993429j]) + for i, arr in enumerate(args): + assert_allclose(elliprc(*arr), expected_results[i]) + + def test_elliprd(self): + assert_allclose(elliprd(1, 1, 1), 1) + assert_allclose(elliprd(0, 2, 1) / 3.0, 0.59907011736779610371) + assert elliprd(1, 1, inf) == 0.0 + assert np.isinf(elliprd(1, 1, 0)) + assert np.isinf(elliprd(1, 1, complex(0, 0))) + assert np.isinf(elliprd(0, 1, complex(0, 0))) + assert isnan(elliprd(1, 1, -np.finfo(np.float64).tiny / 2.0)) + assert isnan(elliprd(1, 1, complex(-1, 0))) + args = array([[0.0, 2.0, 1.0], + [2.0, 3.0, 4.0], + [1.0j, -1.0j, 2.0], + [0.0, 1.0j, -1.0j], + [0.0, -1.0+1.0j, 1.0j], + [-2.0-1.0j, -1.0j, -1.0+1.0j]]) + expected_results = array([1.7972103521034, + 0.16510527294261, + 0.65933854154220, + 1.2708196271910+2.7811120159521j, + -1.8577235439239-0.96193450888839j, + 1.8249027393704-1.2218475784827j]) + for i, arr in enumerate(args): + assert_allclose(elliprd(*arr), expected_results[i]) + + def test_elliprf(self): + assert_allclose(elliprf(1, 1, 1), 1) + assert_allclose(elliprf(0, 1, 2), 1.31102877714605990523) + assert elliprf(1, inf, 1) == 0.0 + assert np.isinf(elliprf(0, 1, 0)) + assert isnan(elliprf(1, 1, -1)) + assert elliprf(complex(inf), 0, 1) == 0.0 + assert isnan(elliprf(1, 1, complex(-inf, 1))) + args = array([[1.0, 2.0, 0.0], + [1.0j, -1.0j, 0.0], + [0.5, 1.0, 0.0], + [-1.0+1.0j, 1.0j, 0.0], + [2.0, 3.0, 4.0], + [1.0j, -1.0j, 2.0], + [-1.0+1.0j, 1.0j, 1.0-1.0j]]) + expected_results = array([1.3110287771461, + 1.8540746773014, + 1.8540746773014, + 0.79612586584234-1.2138566698365j, + 0.58408284167715, + 1.0441445654064, + 0.93912050218619-0.53296252018635j]) + for i, arr in enumerate(args): + assert_allclose(elliprf(*arr), expected_results[i]) + + def test_elliprg(self): + assert_allclose(elliprg(1, 1, 1), 1) + assert_allclose(elliprg(0, 0, 1), 0.5) + assert_allclose(elliprg(0, 0, 0), 0) + assert np.isinf(elliprg(1, inf, 1)) + assert np.isinf(elliprg(complex(inf), 1, 1)) + args = array([[0.0, 16.0, 16.0], + [2.0, 3.0, 4.0], + [0.0, 1.0j, -1.0j], + [-1.0+1.0j, 1.0j, 0.0], + [-1.0j, -1.0+1.0j, 1.0j], + [0.0, 0.0796, 4.0]]) + expected_results = array([np.pi, + 1.7255030280692, + 0.42360654239699, + 0.44660591677018+0.70768352357515j, + 0.36023392184473+0.40348623401722j, + 1.0284758090288]) + for i, arr in enumerate(args): + assert_allclose(elliprg(*arr), expected_results[i]) + + def test_elliprj(self): + assert_allclose(elliprj(1, 1, 1, 1), 1) + assert elliprj(1, 1, inf, 1) == 0.0 + assert isnan(elliprj(1, 0, 0, 0)) + assert isnan(elliprj(-1, 1, 1, 1)) + assert elliprj(1, 1, 1, inf) == 0.0 + args = array([[0.0, 1.0, 2.0, 3.0], + [2.0, 3.0, 4.0, 5.0], + [2.0, 3.0, 4.0, -1.0+1.0j], + [1.0j, -1.0j, 0.0, 2.0], + [-1.0+1.0j, -1.0-1.0j, 1.0, 2.0], + [1.0j, -1.0j, 0.0, 1.0-1.0j], + [-1.0+1.0j, -1.0-1.0j, 1.0, -3.0+1.0j], + [2.0, 3.0, 4.0, -0.5], # Cauchy principal value + [2.0, 3.0, 4.0, -5.0]]) # Cauchy principal value + expected_results = array([0.77688623778582, + 0.14297579667157, + 0.13613945827771-0.38207561624427j, + 1.6490011662711, + 0.94148358841220, + 1.8260115229009+1.2290661908643j, + -0.61127970812028-1.0684038390007j, + 0.24723819703052, # Cauchy principal value + -0.12711230042964]) # Caucny principal value + for i, arr in enumerate(args): + assert_allclose(elliprj(*arr), expected_results[i]) + + @pytest.mark.xfail(reason="Insufficient accuracy on 32-bit") + def test_elliprj_hard(self): + assert_allclose(elliprj(6.483625725195452e-08, + 1.1649136528196886e-27, + 3.6767340167168e+13, + 0.493704617023468), + 8.63426920644241857617477551054e-6, + rtol=5e-15, atol=1e-20) + assert_allclose(elliprj(14.375105857849121, + 9.993988969725365e-11, + 1.72844262269944e-26, + 5.898871222598245e-06), + 829774.1424801627252574054378691828, + rtol=5e-15, atol=1e-20) + + +class TestEllipLegendreCarlsonIdentities: + """Test identities expressing the Legendre elliptic integrals in terms + of Carlson's symmetric integrals. These identities can be found + in the DLMF https://dlmf.nist.gov/19.25#i . + """ + + def setup_class(self): + self.m_n1_1 = np.arange(-1., 1., 0.01) + # For double, this is -(2**1024) + self.max_neg = finfo(double).min + # Lots of very negative numbers + self.very_neg_m = -1. * 2.**arange(-1 + + np.log2(-self.max_neg), 0., + -1.) + self.ms_up_to_1 = np.concatenate(([self.max_neg], + self.very_neg_m, + self.m_n1_1)) + + def test_k(self): + """Test identity: + K(m) = R_F(0, 1-m, 1) + """ + m = self.ms_up_to_1 + assert_allclose(ellipk(m), elliprf(0., 1.-m, 1.)) + + def test_km1(self): + """Test identity: + K(m) = R_F(0, 1-m, 1) + But with the ellipkm1 function + """ + # For double, this is 2**-1022 + tiny = finfo(double).tiny + # All these small powers of 2, up to 2**-1 + m1 = tiny * 2.**arange(0., -np.log2(tiny)) + assert_allclose(ellipkm1(m1), elliprf(0., m1, 1.)) + + def test_e(self): + """Test identity: + E(m) = 2*R_G(0, 1-k^2, 1) + """ + m = self.ms_up_to_1 + assert_allclose(ellipe(m), 2.*elliprg(0., 1.-m, 1.)) + + +class TestErf: + + def test_erf(self): + er = special.erf(.25) + assert_almost_equal(er,0.2763263902,8) + + def test_erf_zeros(self): + erz = special.erf_zeros(5) + erzr = array([1.45061616+1.88094300j, + 2.24465928+2.61657514j, + 2.83974105+3.17562810j, + 3.33546074+3.64617438j, + 3.76900557+4.06069723j]) + assert_array_almost_equal(erz,erzr,4) + + def _check_variant_func(self, func, other_func, rtol, atol=0): + np.random.seed(1234) + n = 10000 + x = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) + y = np.random.pareto(0.02, n) * (2*np.random.randint(0, 2, n) - 1) + z = x + 1j*y + + with np.errstate(all='ignore'): + w = other_func(z) + w_real = other_func(x).real + + mask = np.isfinite(w) + w = w[mask] + z = z[mask] + + mask = np.isfinite(w_real) + w_real = w_real[mask] + x = x[mask] + + # test both real and complex variants + assert_func_equal(func, w, z, rtol=rtol, atol=atol) + assert_func_equal(func, w_real, x, rtol=rtol, atol=atol) + + def test_erfc_consistent(self): + self._check_variant_func( + cephes.erfc, + lambda z: 1 - cephes.erf(z), + rtol=1e-12, + atol=1e-14 # <- the test function loses precision + ) + + def test_erfcx_consistent(self): + self._check_variant_func( + cephes.erfcx, + lambda z: np.exp(z*z) * cephes.erfc(z), + rtol=1e-12 + ) + + def test_erfi_consistent(self): + self._check_variant_func( + cephes.erfi, + lambda z: -1j * cephes.erf(1j*z), + rtol=1e-12 + ) + + def test_dawsn_consistent(self): + self._check_variant_func( + cephes.dawsn, + lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z), + rtol=1e-12 + ) + + def test_erf_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -1, 1] + assert_allclose(special.erf(vals), expected, rtol=1e-15) + + def test_erfc_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, 2, 0] + assert_allclose(special.erfc(vals), expected, rtol=1e-15) + + def test_erfcx_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, np.inf, 0] + assert_allclose(special.erfcx(vals), expected, rtol=1e-15) + + def test_erfi_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -np.inf, np.inf] + assert_allclose(special.erfi(vals), expected, rtol=1e-15) + + def test_dawsn_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan, -0.0, 0.0] + assert_allclose(special.dawsn(vals), expected, rtol=1e-15) + + def test_wofz_nan_inf(self): + vals = [np.nan, -np.inf, np.inf] + expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j] + assert_allclose(special.wofz(vals), expected, rtol=1e-15) + + +class TestEuler: + def test_euler(self): + eu0 = special.euler(0) + eu1 = special.euler(1) + eu2 = special.euler(2) # just checking segfaults + assert_allclose(eu0, [1], rtol=1e-15) + assert_allclose(eu1, [1, 0], rtol=1e-15) + assert_allclose(eu2, [1, 0, -1], rtol=1e-15) + eu24 = special.euler(24) + mathworld = [1,1,5,61,1385,50521,2702765,199360981, + 19391512145,2404879675441, + 370371188237525,69348874393137901, + 15514534163557086905] + correct = zeros((25,),'d') + for k in range(0,13): + if (k % 2): + correct[2*k] = -float(mathworld[k]) + else: + correct[2*k] = float(mathworld[k]) + with np.errstate(all='ignore'): + err = nan_to_num((eu24-correct)/correct) + errmax = max(err) + assert_almost_equal(errmax, 0.0, 14) + + +class TestExp: + def test_exp2(self): + ex = special.exp2(2) + exrl = 2**2 + assert_equal(ex,exrl) + + def test_exp2more(self): + exm = special.exp2(2.5) + exmrl = 2**(2.5) + assert_almost_equal(exm,exmrl,8) + + def test_exp10(self): + ex = special.exp10(2) + exrl = 10**2 + assert_approx_equal(ex,exrl) + + def test_exp10more(self): + exm = special.exp10(2.5) + exmrl = 10**(2.5) + assert_almost_equal(exm,exmrl,8) + + def test_expm1(self): + ex = (special.expm1(2),special.expm1(3),special.expm1(4)) + exrl = (exp(2)-1,exp(3)-1,exp(4)-1) + assert_array_almost_equal(ex,exrl,8) + + def test_expm1more(self): + ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2)) + exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1) + assert_array_almost_equal(ex1,exrl1,8) + + +class TestFactorialFunctions: + @pytest.mark.parametrize("exact", [True, False]) + 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=exact)) + + @pytest.mark.parametrize("n", [-1, -2, -3]) + @pytest.mark.parametrize("exact", [True, False]) + 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=exact), 0) + + @pytest.mark.parametrize("exact", [True, False]) + 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=exact), + [0, 0, 1, 1]) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("content", [np.nan, None, np.datetime64('nat')], + ids=["NaN", "None", "NaT"]) + 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=exact) 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: + with pytest.raises(ValueError, match="factorial with `exact=Tr.*"): + special.factorial([content], exact=exact) + 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=exact) + # array-case also tested in test_factorial{,2,k}_corner_cases + + @pytest.mark.parametrize("levels", range(1, 5)) + @pytest.mark.parametrize("exact", [True, False]) + 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]) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + 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=exact), + np.array(exp[3], ndmin=dim)) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("level", range(1, 5)) + 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=exact), + np.array(exp_nucleus[3], ndmin=level)) + + # note that n=170 is the last integer such that factorial(n) fits float64 + @pytest.mark.parametrize('n', range(30, 180, 10)) + 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) + + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(30, 180, 10))) + 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) + + 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) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize("content", + [[], [1], [1.1], [np.nan], [np.nan, 1]], + ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN, 1]"]) + 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): + 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: + # keep 0-dim.; otherwise n.ravel().ndim==1, even if n.ndim==0 + n_flat = n.ravel() if n.ndim else n + ref = special.factorial(n_flat, exact=exact) if n.size else [] + # expected result is empty if and only if n is empty, + # and has the same dtype & dimension as n + expected = np.array(ref, ndmin=dim, dtype=dtype) + assert_really_equal(result, expected) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, None], + ids=["1", "1.1", "2+2j", "NaN", "None"]) + 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) + + # use odd increment to make sure both odd & even numbers are tested! + @pytest.mark.parametrize('n', range(30, 180, 11)) + def test_factorial2_accuracy(self, n): + # Compare exact=True vs False, i.e. that the accuracy of the + # approximation is better than the specified tolerance. + + rtol = 2e-14 if sys.platform == 'win32' else 1e-15 + # need to cast exact result to float due to numpy/numpy#21220 + assert_allclose(float(special.factorial2(n, exact=True)), + special.factorial2(n, exact=False), rtol=rtol) + assert_allclose(special.factorial2([n], exact=True).astype(float), + special.factorial2([n], exact=False), rtol=rtol) + + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(30, 180, 11))) + def test_factorial2_int_reference(self, n): + # Compare all with correct value + + # Cannot use np.product due to overflow + correct = functools.reduce(operator.mul, list(range(n, 0, -2)), 1) + + assert_array_equal(correct, special.factorial2(n, True)) + assert_array_equal(correct, special.factorial2([n], True)[0]) + + assert_allclose(float(correct), special.factorial2(n, False)) + assert_allclose(float(correct), special.factorial2([n], False)[0]) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize("content", [[], [1], [np.nan], [np.nan, 1]], + ids=["[]", "[1]", "[NaN]", "[NaN, 1]"]) + def test_factorial2_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) + if np.issubdtype(n.dtype, np.integer) or (not content): + # no error + result = special.factorial2(n, exact=exact) + # expected result is identical to n for exact=True resp. empty + # arrays (assert_allclose chokes on object), otherwise up to tol + func = assert_equal if exact or (not content) else assert_allclose + func(result, n) + else: + with pytest.raises(ValueError, match="factorial2 does not*"): + special.factorial2(n, 3) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, None], + ids=["1", "1.1", "2+2j", "NaN", "None"]) + def test_factorial2_scalar_corner_cases(self, n, exact): + if n is None or n is np.nan or np.issubdtype(type(n), np.integer): + # no error + result = special.factorial2(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="factorial2 does not*"): + special.factorial2(n, exact=exact) + + @pytest.mark.parametrize("k", range(1, 5)) + # note that n=170 is the last integer such that factorial(n) fits float64; + # use odd increment to make sure both odd & even numbers are tested + @pytest.mark.parametrize('n', range(170, 20, -29)) + def test_factorialk_accuracy(self, n, k): + # Compare exact=True vs False, i.e. that the accuracy of the + # approximation is better than the specified tolerance. + + # need to cast exact result to float due to numpy/numpy#21220 + assert_allclose(float(special.factorialk(n, k=k, exact=True)), + special.factorialk(n, k=k, exact=False)) + assert_allclose(special.factorialk([n], k=k, exact=True).astype(float), + special.factorialk([n], k=k, exact=False)) + + @pytest.mark.parametrize('k', list(range(1, 5)) + [10, 20]) + @pytest.mark.parametrize('n', + list(range(0, 22)) + list(range(22, 100, 11))) + def test_factorialk_int_reference(self, n, k): + # Compare all with correct value + + # Would be nice to use np.product here, but that's + # broken on windows, see numpy/numpy#21219 + correct = functools.reduce(operator.mul, list(range(n, 0, -k)), 1) + + assert_array_equal(correct, special.factorialk(n, k, True)) + assert_array_equal(correct, special.factorialk([n], k, True)[0]) + + assert_allclose(float(correct), special.factorialk(n, k, False)) + assert_allclose(float(correct), special.factorialk([n], k, False)[0]) + + @pytest.mark.parametrize("dtype", [np.int64, np.float64, + np.complex128, object]) + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("dim", range(0, 5)) + # test empty & non-empty arrays, with nans and mixed + @pytest.mark.parametrize("content", [[], [1], [np.nan], [np.nan, 1]], + ids=["[]", "[1]", "[NaN]", "[NaN, 1]"]) + def test_factorialk_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 if exact else np.float64) + if np.issubdtype(n.dtype, np.integer) or (not content): + # no error; expected result is identical to n + assert_equal(special.factorialk(n, 3, exact=exact), n) + else: + with pytest.raises(ValueError, match="factorialk does not*"): + special.factorialk(n, 3, exact=exact) + + @pytest.mark.parametrize("exact", [True, False, None]) + @pytest.mark.parametrize("k", range(1, 5)) + @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, None], + ids=["1", "1.1", "2+2j", "NaN", "None"]) + def test_factorialk_scalar_corner_cases(self, n, k, exact): + if n is None or n is np.nan or np.issubdtype(type(n), np.integer): + if exact is None: + with pytest.deprecated_call(match="factorialk will default.*"): + result = special.factorialk(n, k=k, exact=exact) + else: + # no error + result = special.factorialk(n, k=k, exact=exact) + + nan_cond = n is np.nan or n is None + # factorialk(1, k) == 1 for all k + expected = np.nan if nan_cond else 1 + assert_equal(result, expected) + else: + with pytest.raises(ValueError, match="factorialk does not*"): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning, "factorialk will default") + special.factorialk(n, k=k, exact=exact) + + @pytest.mark.parametrize("k", [0, 1.1, np.nan, "1"]) + def test_factorialk_raises_k(self, k): + with pytest.raises(ValueError, match="k must be a positive integer*"): + special.factorialk(1, k) + + @pytest.mark.parametrize("exact", [True, False]) + @pytest.mark.parametrize("k", range(1, 12)) + def test_factorialk_dtype(self, k, exact): + kw = {"k": k, "exact": exact} + if exact and k in _FACTORIALK_LIMITS_64BITS.keys(): + n = np.array([_FACTORIALK_LIMITS_32BITS[k]]) + assert_equal(special.factorialk(n, **kw).dtype, np_long) + assert_equal(special.factorialk(n + 1, **kw).dtype, np.int64) + # assert maximality of limits for given dtype + assert special.factorialk(n + 1, **kw) > np.iinfo(np.int32).max + + n = np.array([_FACTORIALK_LIMITS_64BITS[k]]) + assert_equal(special.factorialk(n, **kw).dtype, np.int64) + assert_equal(special.factorialk(n + 1, **kw).dtype, object) + assert special.factorialk(n + 1, **kw) > np.iinfo(np.int64).max + else: + n = np.array([_FACTORIALK_LIMITS_64BITS.get(k, 1)]) + # for exact=True and k >= 10, we always return object; + # for exact=False it's always float + dtype = object if exact else np.float64 + assert_equal(special.factorialk(n, **kw).dtype, dtype) + + 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.raises(ValueError, match="factorial with `exact=True.*"): + special.factorial(x, exact=True) + + +class TestFresnel: + @pytest.mark.parametrize("z, s, c", [ + # some positive value + (.5, 0.064732432859999287, 0.49234422587144644), + (.5 + .0j, 0.064732432859999287, 0.49234422587144644), + # negative half annulus + # https://github.com/scipy/scipy/issues/12309 + # Reference values can be reproduced with + # https://www.wolframalpha.com/input/?i=FresnelS%5B-2.0+%2B+0.1i%5D + # https://www.wolframalpha.com/input/?i=FresnelC%5B-2.0+%2B+0.1i%5D + ( + -2.0 + 0.1j, + -0.3109538687728942-0.0005870728836383176j, + -0.4879956866358554+0.10670801832903172j + ), + ( + -0.1 - 1.5j, + -0.03918309471866977+0.7197508454568574j, + 0.09605692502968956-0.43625191013617465j + ), + # a different algorithm kicks in for "large" values, i.e., |z| >= 4.5, + # make sure to test both float and complex values; a different + # algorithm is used + (6.0, 0.44696076, 0.49953147), + (6.0 + 0.0j, 0.44696076, 0.49953147), + (6.0j, -0.44696076j, 0.49953147j), + (-6.0 + 0.0j, -0.44696076, -0.49953147), + (-6.0j, 0.44696076j, -0.49953147j), + # inf + (np.inf, 0.5, 0.5), + (-np.inf, -0.5, -0.5), + ]) + def test_fresnel_values(self, z, s, c): + frs = array(special.fresnel(z)) + assert_array_almost_equal(frs, array([s, c]), 8) + + # values from pg 329 Table 7.11 of A & S + # slightly corrected in 4th decimal place + def test_fresnel_zeros(self): + szo, czo = special.fresnel_zeros(5) + assert_array_almost_equal(szo, + array([2.0093+0.2885j, + 2.8335+0.2443j, + 3.4675+0.2185j, + 4.0026+0.2009j, + 4.4742+0.1877j]),3) + assert_array_almost_equal(czo, + array([1.7437+0.3057j, + 2.6515+0.2529j, + 3.3204+0.2240j, + 3.8757+0.2047j, + 4.3611+0.1907j]),3) + vals1 = special.fresnel(szo)[0] + vals2 = special.fresnel(czo)[1] + assert_array_almost_equal(vals1,0,14) + assert_array_almost_equal(vals2,0,14) + + def test_fresnelc_zeros(self): + szo, czo = special.fresnel_zeros(6) + frc = special.fresnelc_zeros(6) + assert_array_almost_equal(frc,czo,12) + + def test_fresnels_zeros(self): + szo, czo = special.fresnel_zeros(5) + frs = special.fresnels_zeros(5) + assert_array_almost_equal(frs,szo,12) + + +class TestGamma: + def test_gamma(self): + gam = special.gamma(5) + assert_equal(gam,24.0) + + def test_gammaln(self): + gamln = special.gammaln(3) + lngam = log(special.gamma(3)) + assert_almost_equal(gamln,lngam,8) + + def test_gammainccinv(self): + gccinv = special.gammainccinv(.5,.5) + gcinv = special.gammaincinv(.5,.5) + assert_almost_equal(gccinv,gcinv,8) + + @with_special_errors + def test_gammaincinv(self): + y = special.gammaincinv(.4,.4) + x = special.gammainc(.4,y) + assert_almost_equal(x,0.4,1) + y = special.gammainc(10, 0.05) + x = special.gammaincinv(10, 2.5715803516000736e-20) + assert_almost_equal(0.05, x, decimal=10) + assert_almost_equal(y, 2.5715803516000736e-20, decimal=10) + x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18) + assert_almost_equal(11.0, x, decimal=10) + + @with_special_errors + def test_975(self): + # Regression test for ticket #975 -- switch point in algorithm + # check that things work OK at the point, immediately next floats + # around it, and a bit further away + pts = [0.25, + np.nextafter(0.25, 0), 0.25 - 1e-12, + np.nextafter(0.25, 1), 0.25 + 1e-12] + for xp in pts: + y = special.gammaincinv(.4, xp) + x = special.gammainc(0.4, y) + assert_allclose(x, xp, rtol=1e-12) + + def test_rgamma(self): + rgam = special.rgamma(8) + rlgam = 1/special.gamma(8) + assert_almost_equal(rgam,rlgam,8) + + def test_infinity(self): + assert_(np.isinf(special.gamma(-1))) + assert_equal(special.rgamma(-1), 0) + + +class TestHankel: + + def test_negv1(self): + assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14) + + def test_hankel1(self): + hank1 = special.hankel1(1,.1) + hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j) + assert_almost_equal(hank1,hankrl,8) + + def test_negv1e(self): + assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14) + + def test_hankel1e(self): + hank1e = special.hankel1e(1,.1) + hankrle = special.hankel1(1,.1)*exp(-.1j) + assert_almost_equal(hank1e,hankrle,8) + + def test_negv2(self): + assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14) + + def test_hankel2(self): + hank2 = special.hankel2(1,.1) + hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j) + assert_almost_equal(hank2,hankrl2,8) + + def test_neg2e(self): + assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14) + + def test_hankl2e(self): + hank2e = special.hankel2e(1,.1) + hankrl2e = special.hankel2e(1,.1) + assert_almost_equal(hank2e,hankrl2e,8) + + +class TestHyper: + def test_h1vp(self): + h1 = special.h1vp(1,.1) + h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j) + assert_almost_equal(h1,h1real,8) + + def test_h2vp(self): + h2 = special.h2vp(1,.1) + h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j) + assert_almost_equal(h2,h2real,8) + + def test_hyp0f1(self): + # scalar input + assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12) + assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15) + + # float input, expected values match mpmath + x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5]) + expected = np.array([0.58493659229143, 0.70566805723127, 1.0, + 1.37789689539747, 1.60373685288480]) + assert_allclose(x, expected, rtol=1e-12) + + # complex input + x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j) + assert_allclose(x, expected.astype(complex), rtol=1e-12) + + # test broadcasting + x1 = [0.5, 1.5, 2.5] + x2 = [0, 1, 0.5] + x = special.hyp0f1(x1, x2) + expected = [1.0, 1.8134302039235093, 1.21482702689997] + assert_allclose(x, expected, rtol=1e-12) + x = special.hyp0f1(np.vstack([x1] * 2), x2) + assert_allclose(x, np.vstack([expected] * 2), rtol=1e-12) + assert_raises(ValueError, special.hyp0f1, + np.vstack([x1] * 3), [0, 1]) + + def test_hyp0f1_gh5764(self): + # Just checks the point that failed; there's a more systematic + # test in test_mpmath + res = special.hyp0f1(0.8, 0.5 + 0.5*1J) + # The expected value was generated using mpmath + assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665) + + def test_hyp1f1(self): + hyp1 = special.hyp1f1(.1,.1,.3) + assert_almost_equal(hyp1, 1.3498588075760032,7) + + # test contributed by Moritz Deger (2008-05-29) + # https://github.com/scipy/scipy/issues/1186 (Trac #659) + + # reference data obtained from mathematica [ a, b, x, m(a,b,x)]: + # produced with test_hyp1f1.nb + ref_data = array([ + [-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04], + [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00], + [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05], + [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08], + [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24], + [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21], + [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13], + [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13], + [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02], + [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10], + [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01], + [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21], + [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20], + [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07], + [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03], + [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02], + [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11], + [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03], + [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17], + [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01], + [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00], + [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00], + [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23], + [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01], + [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04], + [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08], + [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01], + [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07], + [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03], + [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09], + [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06], + [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00], + [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01], + [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02], + [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02], + [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02], + [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00], + [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09], + [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01], + [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00], + [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02], + [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05], + [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05], + [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02], + [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02], + [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13], + [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05], + [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12], + [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01], + [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16], + [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37], + [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06], + [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02], + [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12], + [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27], + [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04], + [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06], + [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07], + [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03], + [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07], + [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27], + [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12], + [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32], + [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04], + [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01], + [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02], + [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19], + [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09], + [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31], + [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01], + [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02], + [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08], + [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09], + [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33], + [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01], + [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29], + [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01], + [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29], + [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02], + [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00], + [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08], + [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01], + [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01], + [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01], + [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13], + [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11], + [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02], + [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02], + [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01], + [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31], + [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04], + [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25], + [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01], + [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00], + [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02], + [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05], + [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02], + [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01], + [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01], + [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00] + ]) + + for a,b,c,expected in ref_data: + result = special.hyp1f1(a,b,c) + assert_(abs(expected - result)/expected < 1e-4) + + def test_hyp1f1_gh2957(self): + hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933) + hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934) + assert_almost_equal(hyp1, hyp2, 12) + + def test_hyp1f1_gh2282(self): + hyp = special.hyp1f1(0.5, 1.5, -1000) + assert_almost_equal(hyp, 0.028024956081989643, 12) + + def test_hyp2f1(self): + # a collection of special cases taken from AMS 55 + values = [ + [0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], + [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], + [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], + [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], + [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], + [3, 4, 8, 1, + special.gamma(8) * special.gamma(8-4-3) + / special.gamma(8-3) / special.gamma(8-4)], + [3, 2, 3-2+1, -1, + 1./2**3*sqrt(pi) * special.gamma(1+3-2) + / special.gamma(1+0.5*3-2) / special.gamma(0.5+0.5*3)], + [5, 2, 5-2+1, -1, + 1./2**5*sqrt(pi) * special.gamma(1+5-2) + / special.gamma(1+0.5*5-2) / special.gamma(0.5+0.5*5)], + [4, 0.5+4, 1.5-2*4, -1./3, + (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4) + / special.gamma(3./2) / special.gamma(4./3-2*4)], + # and some others + # ticket #424 + [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484], + # negative integer a or b, with c-a-b integer and x > 0.9 + [-2,3,1,0.95,0.715], + [2,-3,1,0.95,-0.007], + [-6,3,1,0.95,0.0000810625], + [2,-5,1,0.95,-0.000029375], + # huge negative integers + (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24), + (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18), + ] + for i, (a, b, c, x, v) in enumerate(values): + cv = special.hyp2f1(a, b, c, x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_hyperu(self): + val1 = special.hyperu(1,0.1,100) + assert_almost_equal(val1,0.0098153,7) + a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2] + a,b = asarray(a), asarray(b) + z = 0.5 + hypu = special.hyperu(a,b,z) + hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) / + (special.gamma(1+a-b)*special.gamma(b)) - + z**(1-b)*special.hyp1f1(1+a-b,2-b,z) + / (special.gamma(a)*special.gamma(2-b))) + assert_array_almost_equal(hypu,hprl,12) + + def test_hyperu_gh2287(self): + assert_almost_equal(special.hyperu(1, 1.5, 20.2), + 0.048360918656699191, 12) + + +class TestBessel: + def test_itj0y0(self): + it0 = array(special.itj0y0(.2)) + assert_array_almost_equal( + it0, + array([0.19933433254006822, -0.34570883800412566]), + 8, + ) + + def test_it2j0y0(self): + it2 = array(special.it2j0y0(.2)) + assert_array_almost_equal( + it2, + array([0.0049937546274601858, -0.43423067011231614]), + 8, + ) + + def test_negv_iv(self): + assert_equal(special.iv(3,2), special.iv(-3,2)) + + def test_j0(self): + oz = special.j0(.1) + ozr = special.jn(0,.1) + assert_almost_equal(oz,ozr,8) + + def test_j1(self): + o1 = special.j1(.1) + o1r = special.jn(1,.1) + assert_almost_equal(o1,o1r,8) + + def test_jn(self): + jnnr = special.jn(1,.2) + assert_almost_equal(jnnr,0.099500832639235995,8) + + def test_negv_jv(self): + assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14) + + def test_jv(self): + values = [[0, 0.1, 0.99750156206604002], + [2./3, 1e-8, 0.3239028506761532e-5], + [2./3, 1e-10, 0.1503423854873779e-6], + [3.1, 1e-10, 0.1711956265409013e-32], + [2./3, 4.0, -0.2325440850267039], + ] + for i, (v, x, y) in enumerate(values): + yc = special.jv(v, x) + assert_almost_equal(yc, y, 8, err_msg='test #%d' % i) + + def test_negv_jve(self): + assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14) + + def test_jve(self): + jvexp = special.jve(1,.2) + assert_almost_equal(jvexp,0.099500832639235995,8) + jvexp1 = special.jve(1,.2+1j) + z = .2+1j + jvexpr = special.jv(1,z)*exp(-abs(z.imag)) + assert_almost_equal(jvexp1,jvexpr,8) + + def test_jn_zeros(self): + jn0 = special.jn_zeros(0,5) + jn1 = special.jn_zeros(1,5) + assert_array_almost_equal(jn0,array([2.4048255577, + 5.5200781103, + 8.6537279129, + 11.7915344391, + 14.9309177086]),4) + assert_array_almost_equal(jn1,array([3.83171, + 7.01559, + 10.17347, + 13.32369, + 16.47063]),4) + + jn102 = special.jn_zeros(102,5) + assert_allclose(jn102, array([110.89174935992040343, + 117.83464175788308398, + 123.70194191713507279, + 129.02417238949092824, + 134.00114761868422559]), rtol=1e-13) + + jn301 = special.jn_zeros(301,5) + assert_allclose(jn301, array([313.59097866698830153, + 323.21549776096288280, + 331.22338738656748796, + 338.39676338872084500, + 345.03284233056064157]), rtol=1e-13) + + def test_jn_zeros_slow(self): + jn0 = special.jn_zeros(0, 300) + assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13) + assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13) + assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13) + + jn10 = special.jn_zeros(10, 300) + assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13) + assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13) + assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13) + + jn3010 = special.jn_zeros(3010,5) + assert_allclose(jn3010, array([3036.86590780927, + 3057.06598526482, + 3073.66360690272, + 3088.37736494778, + 3101.86438139042]), rtol=1e-8) + + def test_jnjnp_zeros(self): + jn = special.jn + + def jnp(n, x): + return (jn(n-1,x) - jn(n+1,x))/2 + for nt in range(1, 30): + z, n, m, t = special.jnjnp_zeros(nt) + for zz, nn, tt in zip(z, n, t): + if tt == 0: + assert_allclose(jn(nn, zz), 0, atol=1e-6) + elif tt == 1: + assert_allclose(jnp(nn, zz), 0, atol=1e-6) + else: + raise AssertionError("Invalid t return for nt=%d" % nt) + + def test_jnp_zeros(self): + jnp = special.jnp_zeros(1,5) + assert_array_almost_equal(jnp, array([1.84118, + 5.33144, + 8.53632, + 11.70600, + 14.86359]),4) + jnp = special.jnp_zeros(443,5) + assert_allclose(special.jvp(443, jnp), 0, atol=1e-15) + + def test_jnyn_zeros(self): + jnz = special.jnyn_zeros(1,5) + assert_array_almost_equal(jnz,(array([3.83171, + 7.01559, + 10.17347, + 13.32369, + 16.47063]), + array([1.84118, + 5.33144, + 8.53632, + 11.70600, + 14.86359]), + array([2.19714, + 5.42968, + 8.59601, + 11.74915, + 14.89744]), + array([3.68302, + 6.94150, + 10.12340, + 13.28576, + 16.44006])),5) + + def test_jvp(self): + jvprim = special.jvp(2,2) + jv0 = (special.jv(1,2)-special.jv(3,2))/2 + assert_almost_equal(jvprim,jv0,10) + + def test_k0(self): + ozk = special.k0(.1) + ozkr = special.kv(0,.1) + assert_almost_equal(ozk,ozkr,8) + + def test_k0e(self): + ozke = special.k0e(.1) + ozker = special.kve(0,.1) + assert_almost_equal(ozke,ozker,8) + + def test_k1(self): + o1k = special.k1(.1) + o1kr = special.kv(1,.1) + assert_almost_equal(o1k,o1kr,8) + + def test_k1e(self): + o1ke = special.k1e(.1) + o1ker = special.kve(1,.1) + assert_almost_equal(o1ke,o1ker,8) + + def test_jacobi(self): + a = 5*np.random.random() - 1 + b = 5*np.random.random() - 1 + P0 = special.jacobi(0,a,b) + P1 = special.jacobi(1,a,b) + P2 = special.jacobi(2,a,b) + P3 = special.jacobi(3,a,b) + + assert_array_almost_equal(P0.c,[1],13) + assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13) + cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)] + p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]] + assert_array_almost_equal(P2.c,array(p2c)/8.0,13) + cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3), + 12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)] + p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]] + assert_array_almost_equal(P3.c,array(p3c)/48.0,13) + + def test_kn(self): + kn1 = special.kn(0,.2) + assert_almost_equal(kn1,1.7527038555281462,8) + + def test_negv_kv(self): + assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2)) + + def test_kv0(self): + kv0 = special.kv(0,.2) + assert_almost_equal(kv0, 1.7527038555281462, 10) + + def test_kv1(self): + kv1 = special.kv(1,0.2) + assert_almost_equal(kv1, 4.775972543220472, 10) + + def test_kv2(self): + kv2 = special.kv(2,0.2) + assert_almost_equal(kv2, 49.51242928773287, 10) + + def test_kn_largeorder(self): + assert_allclose(special.kn(32, 1), 1.7516596664574289e+43) + + def test_kv_largearg(self): + assert_equal(special.kv(0, 1e19), 0) + + def test_negv_kve(self): + assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2)) + + def test_kve(self): + kve1 = special.kve(0,.2) + kv1 = special.kv(0,.2)*exp(.2) + assert_almost_equal(kve1,kv1,8) + z = .2+1j + kve2 = special.kve(0,z) + kv2 = special.kv(0,z)*exp(z) + assert_almost_equal(kve2,kv2,8) + + def test_kvp_v0n1(self): + z = 2.2 + assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10) + + def test_kvp_n1(self): + v = 3. + z = 2.2 + xc = -special.kv(v+1,z) + v/z*special.kv(v,z) + x = special.kvp(v,z, n=1) + assert_almost_equal(xc, x, 10) # this function (kvp) is broken + + def test_kvp_n2(self): + v = 3. + z = 2.2 + xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z + x = special.kvp(v, z, n=2) + assert_almost_equal(xc, x, 10) + + def test_y0(self): + oz = special.y0(.1) + ozr = special.yn(0,.1) + assert_almost_equal(oz,ozr,8) + + def test_y1(self): + o1 = special.y1(.1) + o1r = special.yn(1,.1) + assert_almost_equal(o1,o1r,8) + + def test_y0_zeros(self): + yo,ypo = special.y0_zeros(2) + zo,zpo = special.y0_zeros(2,complex=1) + all = r_[yo,zo] + allval = r_[ypo,zpo] + assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11) + assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11) + + def test_y1_zeros(self): + y1 = special.y1_zeros(1) + assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5) + + def test_y1p_zeros(self): + y1p = special.y1p_zeros(1,complex=1) + assert_array_almost_equal( + y1p, + (array([0.5768+0.904j]), array([-0.7635+0.5892j])), + 3, + ) + + def test_yn_zeros(self): + an = special.yn_zeros(4,2) + assert_array_almost_equal(an,array([5.64515, 9.36162]),5) + an = special.yn_zeros(443,5) + assert_allclose(an, [450.13573091578090314, + 463.05692376675001542, + 472.80651546418663566, + 481.27353184725625838, + 488.98055964441374646], + rtol=1e-15,) + + def test_ynp_zeros(self): + ao = special.ynp_zeros(0,2) + assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6) + ao = special.ynp_zeros(43,5) + assert_allclose(special.yvp(43, ao), 0, atol=1e-15) + ao = special.ynp_zeros(443,5) + assert_allclose(special.yvp(443, ao), 0, atol=1e-9) + + def test_ynp_zeros_large_order(self): + ao = special.ynp_zeros(443,5) + assert_allclose(special.yvp(443, ao), 0, atol=1e-14) + + def test_yn(self): + yn2n = special.yn(1,.2) + assert_almost_equal(yn2n,-3.3238249881118471,8) + + def test_negv_yv(self): + assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14) + + def test_yv(self): + yv2 = special.yv(1,.2) + assert_almost_equal(yv2,-3.3238249881118471,8) + + def test_negv_yve(self): + assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14) + + def test_yve(self): + yve2 = special.yve(1,.2) + assert_almost_equal(yve2,-3.3238249881118471,8) + yve2r = special.yv(1,.2+1j)*exp(-1) + yve22 = special.yve(1,.2+1j) + assert_almost_equal(yve22,yve2r,8) + + def test_yvp(self): + yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0 + yvp1 = special.yvp(2,.2) + assert_array_almost_equal(yvp1,yvpr,10) + + def _cephes_vs_amos_points(self): + """Yield points at which to compare Cephes implementation to AMOS""" + # check several points, including large-amplitude ones + v = [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301] + z = [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300, + 10003] + yield from itertools.product(v, z) + + # check half-integers; these are problematic points at least + # for cephes/iv + yield from itertools.product(0.5 + arange(-60, 60), [3.5]) + + def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None): + for v, z in self._cephes_vs_amos_points(): + if skip is not None and skip(v, z): + continue + c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z) + if np.isinf(c1): + assert_(np.abs(c2) >= 1e300, (v, z)) + elif np.isnan(c1): + assert_(c2.imag != 0, (v, z)) + else: + assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol) + if v == int(v): + assert_allclose(c3, c2, err_msg=(v, z), + rtol=rtol, atol=atol) + + @pytest.mark.xfail(platform.machine() == 'ppc64le', + reason="fails on ppc64le") + def test_jv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305) + + @pytest.mark.xfail(platform.machine() == 'ppc64le', + reason="fails on ppc64le") + def test_yv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305) + + def test_yv_cephes_vs_amos_only_small_orders(self): + def skipper(v, z): + return abs(v) > 50 + self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305, + skip=skipper) + + def test_iv_cephes_vs_amos(self): + with np.errstate(all='ignore'): + self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305) + + @pytest.mark.slow + def test_iv_cephes_vs_amos_mass_test(self): + N = 1000000 + np.random.seed(1) + v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N) + x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N) + + imsk = (np.random.randint(8, size=N) == 0) + v[imsk] = v[imsk].astype(np.int64) + + with np.errstate(all='ignore'): + c1 = special.iv(v, x) + c2 = special.iv(v, x+0j) + + # deal with differences in the inf and zero cutoffs + c1[abs(c1) > 1e300] = np.inf + c2[abs(c2) > 1e300] = np.inf + c1[abs(c1) < 1e-300] = 0 + c2[abs(c2) < 1e-300] = 0 + + dc = abs(c1/c2 - 1) + dc[np.isnan(dc)] = 0 + + k = np.argmax(dc) + + # Most error apparently comes from AMOS and not our implementation; + # there are some problems near integer orders there + assert_( + dc[k] < 2e-7, + (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j)) + ) + + def test_kv_cephes_vs_amos(self): + self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305) + self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305) + + def test_ticket_623(self): + assert_allclose(special.jv(3, 4), 0.43017147387562193) + assert_allclose(special.jv(301, 1300), 0.0183487151115275) + assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048) + + def test_ticket_853(self): + """Negative-order Bessels""" + # cephes + assert_allclose(special.jv(-1, 1), -0.4400505857449335) + assert_allclose(special.jv(-2, 1), 0.1149034849319005) + assert_allclose(special.yv(-1, 1), 0.7812128213002887) + assert_allclose(special.yv(-2, 1), -1.650682606816255) + assert_allclose(special.iv(-1, 1), 0.5651591039924851) + assert_allclose(special.iv(-2, 1), 0.1357476697670383) + assert_allclose(special.kv(-1, 1), 0.6019072301972347) + assert_allclose(special.kv(-2, 1), 1.624838898635178) + assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952) + assert_allclose(special.yv(-0.5, 1), 0.6713967071418031) + assert_allclose(special.iv(-0.5, 1), 1.231200214592967) + assert_allclose(special.kv(-0.5, 1), 0.4610685044478945) + # amos + assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335) + assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005) + assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887) + assert_allclose(special.yv(-2, 1+0j), -1.650682606816255) + + assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851) + assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383) + assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347) + assert_allclose(special.kv(-2, 1+0j), 1.624838898635178) + + assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952) + assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j) + assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031) + assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j) + + assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967) + assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j) + assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945) + assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j) + + assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3)) + assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3)) + assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3)) + assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j)) + + assert_allclose( + special.hankel1(-0.5, 1+1j), + special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j) + ) + assert_allclose( + special.hankel2(-0.5, 1+1j), + special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j) + ) + + def test_ticket_854(self): + """Real-valued Bessel domains""" + assert_(isnan(special.jv(0.5, -1))) + assert_(isnan(special.iv(0.5, -1))) + assert_(isnan(special.yv(0.5, -1))) + assert_(isnan(special.yv(1, -1))) + assert_(isnan(special.kv(0.5, -1))) + assert_(isnan(special.kv(1, -1))) + assert_(isnan(special.jve(0.5, -1))) + assert_(isnan(special.ive(0.5, -1))) + assert_(isnan(special.yve(0.5, -1))) + assert_(isnan(special.yve(1, -1))) + assert_(isnan(special.kve(0.5, -1))) + assert_(isnan(special.kve(1, -1))) + assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1)) + assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1)) + + def test_gh_7909(self): + assert_(special.kv(1.5, 0) == np.inf) + assert_(special.kve(1.5, 0) == np.inf) + + def test_ticket_503(self): + """Real-valued Bessel I overflow""" + assert_allclose(special.iv(1, 700), 1.528500390233901e302) + assert_allclose(special.iv(1000, 1120), 1.301564549405821e301) + + def test_iv_hyperg_poles(self): + assert_allclose(special.iv(-0.5, 1), 1.231200214592967) + + def iv_series(self, v, z, n=200): + k = arange(0, n).astype(double) + r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1) + r[isnan(r)] = inf + r = exp(r) + err = abs(r).max() * finfo(double).eps * n + abs(r[-1])*10 + return r.sum(), err + + def test_i0_series(self): + for z in [1., 10., 200.5]: + value, err = self.iv_series(0, z) + assert_allclose(special.i0(z), value, atol=err, err_msg=z) + + def test_i1_series(self): + for z in [1., 10., 200.5]: + value, err = self.iv_series(1, z) + assert_allclose(special.i1(z), value, atol=err, err_msg=z) + + def test_iv_series(self): + for v in [-20., -10., -1., 0., 1., 12.49, 120.]: + for z in [1., 10., 200.5, -1+2j]: + value, err = self.iv_series(v, z) + assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z)) + + def test_i0(self): + values = [[0.0, 1.0], + [1e-10, 1.0], + [0.1, 0.9071009258], + [0.5, 0.6450352706], + [1.0, 0.4657596077], + [2.5, 0.2700464416], + [5.0, 0.1835408126], + [20.0, 0.0897803119], + ] + for i, (x, v) in enumerate(values): + cv = special.i0(x) * exp(-x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_i0e(self): + oize = special.i0e(.1) + oizer = special.ive(0,.1) + assert_almost_equal(oize,oizer,8) + + def test_i1(self): + values = [[0.0, 0.0], + [1e-10, 0.4999999999500000e-10], + [0.1, 0.0452984468], + [0.5, 0.1564208032], + [1.0, 0.2079104154], + [5.0, 0.1639722669], + [20.0, 0.0875062222], + ] + for i, (x, v) in enumerate(values): + cv = special.i1(x) * exp(-x) + assert_almost_equal(cv, v, 8, err_msg='test #%d' % i) + + def test_i1e(self): + oi1e = special.i1e(.1) + oi1er = special.ive(1,.1) + assert_almost_equal(oi1e,oi1er,8) + + def test_iti0k0(self): + iti0 = array(special.iti0k0(5)) + assert_array_almost_equal( + iti0, + array([31.848667776169801, 1.5673873907283657]), + 5, + ) + + def test_it2i0k0(self): + it2k = special.it2i0k0(.1) + assert_array_almost_equal( + it2k, + array([0.0012503906973464409, 3.3309450354686687]), + 6, + ) + + def test_iv(self): + iv1 = special.iv(0,.1)*exp(-.1) + assert_almost_equal(iv1,0.90710092578230106,10) + + def test_negv_ive(self): + assert_equal(special.ive(3,2), special.ive(-3,2)) + + def test_ive(self): + ive1 = special.ive(0,.1) + iv1 = special.iv(0,.1)*exp(-.1) + assert_almost_equal(ive1,iv1,10) + + def test_ivp0(self): + assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10) + + def test_ivp(self): + y = (special.iv(0,2) + special.iv(2,2))/2 + x = special.ivp(1,2) + assert_almost_equal(x,y,10) + + +class TestLaguerre: + def test_laguerre(self): + lag0 = special.laguerre(0) + lag1 = special.laguerre(1) + lag2 = special.laguerre(2) + lag3 = special.laguerre(3) + lag4 = special.laguerre(4) + lag5 = special.laguerre(5) + assert_array_almost_equal(lag0.c,[1],13) + assert_array_almost_equal(lag1.c,[-1,1],13) + assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13) + assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13) + assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13) + assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13) + + def test_genlaguerre(self): + k = 5*np.random.random() - 0.9 + lag0 = special.genlaguerre(0,k) + lag1 = special.genlaguerre(1,k) + lag2 = special.genlaguerre(2,k) + lag3 = special.genlaguerre(3,k) + assert_equal(lag0.c, [1]) + assert_equal(lag1.c, [-1, k + 1]) + assert_almost_equal( + lag2.c, + array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0 + ) + assert_almost_equal( + lag3.c, + array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0 + ) + + +# Base polynomials come from Abrahmowitz and Stegan +class TestLegendre: + def test_legendre(self): + leg0 = special.legendre(0) + leg1 = special.legendre(1) + leg2 = special.legendre(2) + leg3 = special.legendre(3) + leg4 = special.legendre(4) + leg5 = special.legendre(5) + assert_equal(leg0.c, [1]) + assert_equal(leg1.c, [1,0]) + assert_almost_equal(leg2.c, array([3,0,-1])/2.0, decimal=13) + assert_almost_equal(leg3.c, array([5,0,-3,0])/2.0) + assert_almost_equal(leg4.c, array([35,0,-30,0,3])/8.0) + assert_almost_equal(leg5.c, array([63,0,-70,0,15,0])/8.0) + + @pytest.mark.parametrize('n', [1, 2, 3, 4, 5]) + @pytest.mark.parametrize('zr', [0.5241717, 12.80232, -9.699001, + 0.5122437, 0.1714377]) + @pytest.mark.parametrize('zi', [9.766818, 0.2999083, 8.24726, -22.84843, + -0.8792666]) + def test_lpn_against_clpmn(self, n, zr, zi): + reslpn = special.lpn(n, zr + zi*1j) + resclpmn = special.clpmn(0, n, zr+zi*1j) + assert_allclose(reslpn[0], resclpmn[0][0]) + assert_allclose(reslpn[1], resclpmn[1][0]) + + +class TestLambda: + def test_lmbda(self): + lam = special.lmbda(1,.1) + lamr = ( + array([special.jn(0,.1), 2*special.jn(1,.1)/.1]), + array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1]) + ) + assert_array_almost_equal(lam,lamr,8) + + +class TestLog1p: + def test_log1p(self): + l1p = (special.log1p(10), special.log1p(11), special.log1p(12)) + l1prl = (log(11), log(12), log(13)) + assert_array_almost_equal(l1p,l1prl,8) + + def test_log1pmore(self): + l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2)) + l1pmrl = (log(2),log(2.1),log(2.2)) + assert_array_almost_equal(l1pm,l1pmrl,8) + + +class TestLegendreFunctions: + def test_clpmn(self): + z = 0.5+0.3j + clp = special.clpmn(2, 2, z, 3) + assert_array_almost_equal(clp, + (array([[1.0000, z, 0.5*(3*z*z-1)], + [0.0000, sqrt(z*z-1), 3*z*sqrt(z*z-1)], + [0.0000, 0.0000, 3*(z*z-1)]]), + array([[0.0000, 1.0000, 3*z], + [0.0000, z/sqrt(z*z-1), 3*(2*z*z-1)/sqrt(z*z-1)], + [0.0000, 0.0000, 6*z]])), + 7) + + def test_clpmn_close_to_real_2(self): + eps = 1e-10 + m = 1 + n = 3 + x = 0.5 + clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n] + clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n] + assert_array_almost_equal(array([clp_plus, clp_minus]), + array([special.lpmv(m, n, x), + special.lpmv(m, n, x)]), + 7) + + def test_clpmn_close_to_real_3(self): + eps = 1e-10 + m = 1 + n = 3 + x = 0.5 + clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n] + clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n] + assert_array_almost_equal(array([clp_plus, clp_minus]), + array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi), + special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]), + 7) + + def test_clpmn_across_unit_circle(self): + eps = 1e-7 + m = 1 + n = 1 + x = 1j + for type in [2, 3]: + assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n], + special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6) + + def test_inf(self): + for z in (1, -1): + for n in range(4): + for m in range(1, n): + lp = special.clpmn(m, n, z) + assert_(np.isinf(lp[1][1,1:]).all()) + lp = special.lpmn(m, n, z) + assert_(np.isinf(lp[1][1,1:]).all()) + + def test_deriv_clpmn(self): + # data inside and outside of the unit circle + zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j, + 1+1j, -1+1j, -1-1j, 1-1j] + m = 2 + n = 3 + for type in [2, 3]: + for z in zvals: + for h in [1e-3, 1e-3j]: + approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0] + - special.clpmn(m, n, z-0.5*h, type)[0])/h + assert_allclose(special.clpmn(m, n, z, type)[1], + approx_derivative, + rtol=1e-4) + + def test_lpmn(self): + lp = special.lpmn(0,2,.5) + assert_array_almost_equal(lp,(array([[1.00000, + 0.50000, + -0.12500]]), + array([[0.00000, + 1.00000, + 1.50000]])),4) + + def test_lpn(self): + lpnf = special.lpn(2,.5) + assert_array_almost_equal(lpnf,(array([1.00000, + 0.50000, + -0.12500]), + array([0.00000, + 1.00000, + 1.50000])),4) + + def test_lpmv(self): + lp = special.lpmv(0,2,.5) + assert_almost_equal(lp,-0.125,7) + lp = special.lpmv(0,40,.001) + assert_almost_equal(lp,0.1252678976534484,7) + + # XXX: this is outside the domain of the current implementation, + # so ensure it returns a NaN rather than a wrong answer. + with np.errstate(all='ignore'): + lp = special.lpmv(-1,-1,.001) + assert_(lp != 0 or np.isnan(lp)) + + def test_lqmn(self): + lqmnf = special.lqmn(0,2,.5) + lqf = special.lqn(2,.5) + assert_array_almost_equal(lqmnf[0][0],lqf[0],4) + assert_array_almost_equal(lqmnf[1][0],lqf[1],4) + + def test_lqmn_gt1(self): + """algorithm for real arguments changes at 1.0001 + test against analytical result for m=2, n=1 + """ + x0 = 1.0001 + delta = 0.00002 + for x in (x0-delta, x0+delta): + lq = special.lqmn(2, 1, x)[0][-1, -1] + expected = 2/(x*x-1) + assert_almost_equal(lq, expected) + + def test_lqmn_shape(self): + a, b = special.lqmn(4, 4, 1.1) + assert_equal(a.shape, (5, 5)) + assert_equal(b.shape, (5, 5)) + + a, b = special.lqmn(4, 0, 1.1) + assert_equal(a.shape, (5, 1)) + assert_equal(b.shape, (5, 1)) + + def test_lqn(self): + lqf = special.lqn(2,.5) + assert_array_almost_equal(lqf,(array([0.5493, -0.7253, -0.8187]), + array([1.3333, 1.216, -0.8427])),4) + + +class TestMathieu: + + def test_mathieu_a(self): + pass + + def test_mathieu_even_coef(self): + special.mathieu_even_coef(2,5) + # Q not defined broken and cannot figure out proper reporting order + + def test_mathieu_odd_coef(self): + # same problem as above + pass + + +class TestFresnelIntegral: + + def test_modfresnelp(self): + pass + + def test_modfresnelm(self): + pass + + +class TestOblCvSeq: + def test_obl_cv_seq(self): + obl = special.obl_cv_seq(0,3,1) + assert_array_almost_equal(obl,array([-0.348602, + 1.393206, + 5.486800, + 11.492120]),5) + + +class TestParabolicCylinder: + def test_pbdn_seq(self): + pb = special.pbdn_seq(1,.1) + assert_array_almost_equal(pb,(array([0.9975, + 0.0998]), + array([-0.0499, + 0.9925])),4) + + def test_pbdv(self): + special.pbdv(1,.2) + 1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0] + + def test_pbdv_seq(self): + pbn = special.pbdn_seq(1,.1) + pbv = special.pbdv_seq(1,.1) + assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4) + + def test_pbdv_points(self): + # simple case + eta = np.linspace(-10, 10, 5) + z = 2**(eta/2)*np.sqrt(np.pi)/special.gamma(.5-.5*eta) + assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14) + + # some points + assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12) + assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12) + + def test_pbdv_gradient(self): + x = np.linspace(-4, 4, 8)[:,None] + eta = np.linspace(-10, 10, 5)[None,:] + + p = special.pbdv(eta, x) + eps = 1e-7 + 1e-7*abs(x) + dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2. + assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) + + def test_pbvv_gradient(self): + x = np.linspace(-4, 4, 8)[:,None] + eta = np.linspace(-10, 10, 5)[None,:] + + p = special.pbvv(eta, x) + eps = 1e-7 + 1e-7*abs(x) + dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2. + assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6) + + def test_pbvv_seq(self): + res1, res2 = special.pbvv_seq(2, 3) + assert_allclose(res1, np.array([2.976319645712036, + 1.358840996329579, + 0.5501016716383508])) + assert_allclose(res2, np.array([3.105638472238475, + 0.9380581512176672, + 0.533688488872053])) + + +class TestPolygamma: + # from Table 6.2 (pg. 271) of A&S + def test_polygamma(self): + poly2 = special.polygamma(2,1) + poly3 = special.polygamma(3,1) + assert_almost_equal(poly2,-2.4041138063,10) + assert_almost_equal(poly3,6.4939394023,10) + + # Test polygamma(0, x) == psi(x) + x = [2, 3, 1.1e14] + assert_almost_equal(special.polygamma(0, x), special.psi(x)) + + # Test broadcasting + n = [0, 1, 2] + x = [0.5, 1.5, 2.5] + expected = [-1.9635100260214238, 0.93480220054467933, + -0.23620405164172739] + assert_almost_equal(special.polygamma(n, x), expected) + expected = np.vstack([expected]*2) + assert_almost_equal(special.polygamma(n, np.vstack([x]*2)), + expected) + assert_almost_equal(special.polygamma(np.vstack([n]*2), x), + expected) + + +class TestProCvSeq: + def test_pro_cv_seq(self): + prol = special.pro_cv_seq(0,3,1) + assert_array_almost_equal(prol,array([0.319000, + 2.593084, + 6.533471, + 12.514462]),5) + + +class TestPsi: + def test_psi(self): + ps = special.psi(1) + assert_almost_equal(ps,-0.57721566490153287,8) + + +class TestRadian: + def test_radian(self): + rad = special.radian(90,0,0) + assert_almost_equal(rad,pi/2.0,5) + + def test_radianmore(self): + rad1 = special.radian(90,1,60) + assert_almost_equal(rad1,pi/2+0.0005816135199345904,5) + + +class TestRiccati: + 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) + + def test_riccati_yn(self): + N, x = 2, 0.2 + C = np.empty((N, N)) + for n in range(N): + y = special.spherical_yn(n, x) + yp = special.spherical_yn(n, x, derivative=True) + C[0,n] = x*y + C[1,n] = x*yp + y + assert_array_almost_equal(C, special.riccati_yn(n, x), 8) + + +class TestRound: + def test_round(self): + rnd = list(map(int, (special.round(10.1), + special.round(10.4), + special.round(10.5), + special.round(10.6)))) + + # Note: According to the documentation, scipy.special.round is + # supposed to round to the nearest even number if the fractional + # part is exactly 0.5. On some platforms, this does not appear + # to work and thus this test may fail. However, this unit test is + # correctly written. + rndrl = (10,10,10,11) + assert_array_equal(rnd,rndrl) + + +def test_sph_harm(): + # Tests derived from tables in + # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics + sh = special.sph_harm + pi = np.pi + exp = np.exp + sqrt = np.sqrt + sin = np.sin + cos = np.cos + assert_array_almost_equal(sh(0,0,0,0), + 0.5/sqrt(pi)) + assert_array_almost_equal(sh(-2,2,0.,pi/4), + 0.25*sqrt(15./(2.*pi)) * + (sin(pi/4))**2.) + assert_array_almost_equal(sh(-2,2,0.,pi/2), + 0.25*sqrt(15./(2.*pi))) + assert_array_almost_equal(sh(2,2,pi,pi/2), + 0.25*sqrt(15/(2.*pi)) * + exp(0+2.*pi*1j)*sin(pi/2.)**2.) + assert_array_almost_equal(sh(2,4,pi/4.,pi/3.), + (3./8.)*sqrt(5./(2.*pi)) * + exp(0+2.*pi/4.*1j) * + sin(pi/3.)**2. * + (7.*cos(pi/3.)**2.-1)) + assert_array_almost_equal(sh(4,4,pi/8.,pi/6.), + (3./16.)*sqrt(35./(2.*pi)) * + exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.) + + +def test_sph_harm_ufunc_loop_selection(): + # see https://github.com/scipy/scipy/issues/4895 + dt = np.dtype(np.complex128) + assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt) + assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt) + assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt) + assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt) + assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt) + assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt) + + +class TestStruve: + def _series(self, v, z, n=100): + """Compute Struve function & error estimate from its power series.""" + k = arange(0, n) + r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5) + err = abs(r).max() * finfo(double).eps * n + return r.sum(), err + + def test_vs_series(self): + """Check Struve function versus its power series""" + for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]: + for z in [1, 10, 19, 21, 30]: + value, err = self._series(v, z) + assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z) + + def test_some_values(self): + assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7) + assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8) + assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12) + assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11) + assert_equal(special.struve(-12, -41), -special.struve(-12, 41)) + assert_equal(special.struve(+12, -41), -special.struve(+12, 41)) + assert_equal(special.struve(-11, -41), +special.struve(-11, 41)) + assert_equal(special.struve(+11, -41), +special.struve(+11, 41)) + + assert_(isnan(special.struve(-7.1, -1))) + assert_(isnan(special.struve(-10.1, -1))) + + def test_regression_679(self): + """Regression test for #679""" + assert_allclose(special.struve(-1.0, 20 - 1e-8), + special.struve(-1.0, 20 + 1e-8)) + assert_allclose(special.struve(-2.0, 20 - 1e-8), + special.struve(-2.0, 20 + 1e-8)) + assert_allclose(special.struve(-4.3, 20 - 1e-8), + special.struve(-4.3, 20 + 1e-8)) + + +def test_chi2_smalldf(): + assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110) + + +def test_ch2_inf(): + assert_equal(special.chdtr(0.7,np.inf), 1.0) + + +def test_chi2c_smalldf(): + assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110) + + +def test_chi2_inv_smalldf(): + assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3) + + +def test_agm_simple(): + rtol = 1e-13 + + # Gauss's constant + assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186, + rtol=rtol) + + # These values were computed using Wolfram Alpha, with the + # function ArithmeticGeometricMean[a, b]. + agm13 = 1.863616783244897 + agm15 = 2.604008190530940 + agm35 = 3.936235503649555 + assert_allclose(special.agm([[1], [3]], [1, 3, 5]), + [[1, agm13, agm15], + [agm13, 3, agm35]], rtol=rtol) + + # Computed by the iteration formula using mpmath, + # with mpmath.mp.prec = 1000: + agm12 = 1.4567910310469068 + assert_allclose(special.agm(1, 2), agm12, rtol=rtol) + assert_allclose(special.agm(2, 1), agm12, rtol=rtol) + assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol) + assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol) + assert_allclose(special.agm(13, 123456789.5), 11111458.498599306, + rtol=rtol) + assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol) + assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol) + assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178, + rtol=rtol) + assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177, + rtol=rtol) + assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152, + rtol=rtol) + fi = np.finfo(1.0) + assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305, + rtol=rtol) + assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308, + rtol=rtol) + assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308, + rtol=rtol) + + # zero, nan and inf cases. + assert_equal(special.agm(0, 0), 0) + assert_equal(special.agm(99, 0), 0) + + assert_equal(special.agm(-1, 10), np.nan) + assert_equal(special.agm(0, np.inf), np.nan) + assert_equal(special.agm(np.inf, 0), np.nan) + assert_equal(special.agm(0, -np.inf), np.nan) + assert_equal(special.agm(-np.inf, 0), np.nan) + assert_equal(special.agm(np.inf, -np.inf), np.nan) + assert_equal(special.agm(-np.inf, np.inf), np.nan) + assert_equal(special.agm(1, np.nan), np.nan) + assert_equal(special.agm(np.nan, -1), np.nan) + + assert_equal(special.agm(1, np.inf), np.inf) + assert_equal(special.agm(np.inf, 1), np.inf) + assert_equal(special.agm(-1, -np.inf), -np.inf) + assert_equal(special.agm(-np.inf, -1), -np.inf) + + +def test_legacy(): + # Legacy behavior: truncating arguments to integers + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "floating point number truncated to an integer") + assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3)) + assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3)) + assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3)) + assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3)) + assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3)) + assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3)) + assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3)) + assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3)) + assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3)) + + +@with_special_errors +def test_error_raising(): + assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j) + + +def test_xlogy(): + def xfunc(x, y): + with np.errstate(invalid='ignore'): + if x == 0 and not np.isnan(y): + return x + else: + return x*np.log(y) + + z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float) + z2 = np.r_[z1, [(0, 1j), (1, 1j)]] + + w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) + assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13) + w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1]) + assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13) + + +def test_xlog1py(): + def xfunc(x, y): + with np.errstate(invalid='ignore'): + if x == 0 and not np.isnan(y): + return x + else: + return x * np.log1p(y) + + z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0), + (1, 1e-30)], dtype=float) + w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1]) + assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13) + + +def test_entr(): + def xfunc(x): + if x < 0: + return -np.inf + else: + return -special.xlogy(x, x) + values = (0, 0.5, 1.0, np.inf) + signs = [-1, 1] + arr = [] + for sgn, v in itertools.product(signs, values): + arr.append(sgn * v) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z) + assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13) + + +def test_kl_div(): + def xfunc(x, y): + if x < 0 or y < 0 or (y == 0 and x != 0): + # extension of natural domain to preserve convexity + return np.inf + elif np.isposinf(x) or np.isposinf(y): + # limits within the natural domain + return np.inf + elif x == 0: + return y + else: + return special.xlogy(x, x/y) - x + y + values = (0, 0.5, 1.0) + signs = [-1, 1] + arr = [] + for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): + arr.append((sgna*va, sgnb*vb)) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13) + + +def test_rel_entr(): + def xfunc(x, y): + if x > 0 and y > 0: + return special.xlogy(x, x/y) + elif x == 0 and y >= 0: + return 0 + else: + return np.inf + values = (0, 0.5, 1.0) + signs = [-1, 1] + arr = [] + for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values): + arr.append((sgna*va, sgnb*vb)) + z = np.array(arr, dtype=float) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13) + + +def test_huber(): + assert_equal(special.huber(-1, 1.5), np.inf) + assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5)) + assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2)) + + def xfunc(delta, r): + if delta < 0: + return np.inf + elif np.abs(r) < delta: + return 0.5 * np.square(r) + else: + return delta * (np.abs(r) - 0.5 * delta) + + z = np.random.randn(10, 2) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13) + + +def test_pseudo_huber(): + def xfunc(delta, r): + if delta < 0: + return np.inf + elif (not delta) or (not r): + return 0 + else: + return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1) + + z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]]) + w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1]) + assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13) + + +def test_pseudo_huber_small_r(): + delta = 1.0 + r = 1e-18 + y = special.pseudo_huber(delta, r) + # expected computed with mpmath: + # import mpmath + # mpmath.mp.dps = 200 + # r = mpmath.mpf(1e-18) + # expected = float(mpmath.sqrt(1 + r**2) - 1) + expected = 5.0000000000000005e-37 + assert_allclose(y, expected, rtol=1e-13) + + +def test_runtime_warning(): + with pytest.warns(RuntimeWarning, + match=r'Too many predicted coefficients'): + mathieu_odd_coef(1000, 1000) + with pytest.warns(RuntimeWarning, + match=r'Too many predicted coefficients'): + mathieu_even_coef(1000, 1000) + + +class TestStirling2: + table = [ + [1], + [0, 1], + [0, 1, 1], + [0, 1, 3, 1], + [0, 1, 7, 6, 1], + [0, 1, 15, 25, 10, 1], + [0, 1, 31, 90, 65, 15, 1], + [0, 1, 63, 301, 350, 140, 21, 1], + [0, 1, 127, 966, 1701, 1050, 266, 28, 1], + [0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1], + [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1], + ] + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_table_cases(self, is_exact, comp, kwargs): + for n in range(1, len(self.table)): + k_values = list(range(n+1)) + row = self.table[n] + comp(row, stirling2([n], k_values, exact=is_exact), **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_valid_single_integer(self, is_exact, comp, kwargs): + comp(stirling2(0, 0, exact=is_exact), self.table[0][0], **kwargs) + comp(stirling2(4, 2, exact=is_exact), self.table[4][2], **kwargs) + # a single 2-tuple of integers as arguments must return an int and not + # an array whereas arrays of single values should return array + comp(stirling2(5, 3, exact=is_exact), 25, **kwargs) + comp(stirling2([5], [3], exact=is_exact), [25], **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_negative_integer(self, is_exact, comp, kwargs): + # negative integers for n or k arguments return 0 + comp(stirling2(-1, -1, exact=is_exact), 0, **kwargs) + comp(stirling2(-1, 2, exact=is_exact), 0, **kwargs) + comp(stirling2(2, -1, exact=is_exact), 0, **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-12}) + ]) + def test_array_inputs(self, is_exact, comp, kwargs): + ans = [self.table[10][3], self.table[10][4]] + comp(stirling2(asarray([10, 10]), + asarray([3, 4]), + exact=is_exact), + ans) + comp(stirling2([10, 10], + asarray([3, 4]), + exact=is_exact), + ans) + comp(stirling2(asarray([10, 10]), + [3, 4], + exact=is_exact), + ans) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_mixed_values(self, is_exact, comp, kwargs): + # negative values-of either n or k-should return 0 for the entry + ans = [0, 1, 3, 25, 1050, 5880, 9330] + n = [-1, 0, 3, 5, 8, 10, 10] + k = [-2, 0, 2, 3, 5, 7, 3] + comp(stirling2(n, k, exact=is_exact), ans, **kwargs) + + def test_correct_parity(self): + """Test parity follows well known identity. + + en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Parity + """ + n, K = 100, np.arange(101) + assert_equal( + stirling2(n, K, exact=True) % 2, + [math.comb(n - (k // 2) - 1, n - k) % 2 for k in K], + ) + + def test_big_numbers(self): + # via mpmath (bigger than 32bit) + ans = asarray([48063331393110, 48004081105038305]) + n = [25, 30] + k = [17, 4] + assert array_equal(stirling2(n, k, exact=True), ans) + # bigger than 64 bit + ans = asarray([2801934359500572414253157841233849412, + 14245032222277144547280648984426251]) + n = [42, 43] + k = [17, 23] + assert array_equal(stirling2(n, k, exact=True), ans) + + @pytest.mark.parametrize("N", [4.5, 3., 4+1j, "12", np.nan]) + @pytest.mark.parametrize("K", [3.5, 3, "2", None]) + @pytest.mark.parametrize("is_exact", [True, False]) + def test_unsupported_input_types(self, N, K, is_exact): + # object, float, string, complex are not supported and raise TypeError + with pytest.raises(TypeError): + stirling2(N, K, exact=is_exact) + + @pytest.mark.parametrize("is_exact", [True, False]) + def test_numpy_array_int_object_dtype(self, is_exact): + # python integers with arbitrary precision are *not* allowed as + # object type in numpy arrays are inconsistent from api perspective + ans = asarray(self.table[4][1:]) + n = asarray([4, 4, 4, 4], dtype=object) + k = asarray([1, 2, 3, 4], dtype=object) + with pytest.raises(TypeError): + array_equal(stirling2(n, k, exact=is_exact), ans) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_numpy_array_unsigned_int_dtype(self, is_exact, comp, kwargs): + # numpy unsigned integers are allowed as dtype in numpy arrays + ans = asarray(self.table[4][1:]) + n = asarray([4, 4, 4, 4], dtype=np_ulong) + k = asarray([1, 2, 3, 4], dtype=np_ulong) + comp(stirling2(n, k, exact=False), ans, **kwargs) + + @pytest.mark.parametrize("is_exact, comp, kwargs", [ + (True, assert_equal, {}), + (False, assert_allclose, {'rtol': 1e-13}) + ]) + def test_broadcasting_arrays_correctly(self, is_exact, comp, kwargs): + # broadcasting is handled by stirling2 + # test leading 1s are replicated + ans = asarray([[1, 15, 25, 10], [1, 7, 6, 1]]) # shape (2,4) + n = asarray([[5, 5, 5, 5], [4, 4, 4, 4]]) # shape (2,4) + k = asarray([1, 2, 3, 4]) # shape (4,) + comp(stirling2(n, k, exact=is_exact), ans, **kwargs) + # test that dims both mismatch broadcast correctly (5,1) & (6,) + n = asarray([[4], [4], [4], [4], [4]]) + k = asarray([0, 1, 2, 3, 4, 5]) + ans = asarray([[0, 1, 7, 6, 1, 0] for _ in range(5)]) + comp(stirling2(n, k, exact=False), ans, **kwargs) + + def test_temme_rel_max_error(self): + # python integers with arbitrary precision are *not* allowed as + # object type in numpy arrays are inconsistent from api perspective + x = list(range(51, 101, 5)) + for n in x: + k_entries = list(range(1, n+1)) + denom = stirling2([n], k_entries, exact=True) + num = denom - stirling2([n], k_entries, exact=False) + assert np.max(np.abs(num / denom)) < 2e-5 diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py new file mode 100644 index 0000000000000000000000000000000000000000..57694becc49b2028f17eac819b80a225ac010795 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py @@ -0,0 +1,112 @@ +import numpy as np +import scipy.special as sc +import pytest +from numpy.testing import assert_allclose, assert_array_equal, suppress_warnings + + +class TestBdtr: + def test(self): + val = sc.bdtr(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtr([0, 1, 2], 2, 0.5) + assert_array_equal(val, [0.25, 0.75, 1.0]) + + def test_rounding(self): + double_val = sc.bdtr([0.1, 1.1, 2.1], 2, 0.5) + int_val = sc.bdtr([0, 1, 2], 2, 0.5) + assert_array_equal(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtr(k, n, p) + assert np.isnan(val) + + def test_domain(self): + val = sc.bdtr(-1.1, 1, 0.5) + assert np.isnan(val) + + +class TestBdtrc: + def test_value(self): + val = sc.bdtrc(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtrc([0, 1, 2], 2, 0.5) + assert_array_equal(val, [0.75, 0.25, 0.0]) + + def test_rounding(self): + double_val = sc.bdtrc([0.1, 1.1, 2.1], 2, 0.5) + int_val = sc.bdtrc([0, 1, 2], 2, 0.5) + assert_array_equal(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtrc(k, n, p) + assert np.isnan(val) + + def test_domain(self): + val = sc.bdtrc(-1.1, 1, 0.5) + val2 = sc.bdtrc(2.1, 1, 0.5) + assert np.isnan(val2) + assert_allclose(val, 1.0) + + def test_bdtr_bdtrc_sum_to_one(self): + bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5) + bdtrc_vals = sc.bdtrc([0, 1, 2], 2, 0.5) + vals = bdtr_vals + bdtrc_vals + assert_allclose(vals, [1.0, 1.0, 1.0]) + + +class TestBdtri: + def test_value(self): + val = sc.bdtri(0, 1, 0.5) + assert_allclose(val, 0.5) + + def test_sum_is_one(self): + val = sc.bdtri([0, 1], 2, 0.5) + actual = np.asarray([1 - 1/np.sqrt(2), 1/np.sqrt(2)]) + assert_allclose(val, actual) + + def test_rounding(self): + double_val = sc.bdtri([0.1, 1.1], 2, 0.5) + int_val = sc.bdtri([0, 1], 2, 0.5) + assert_allclose(double_val, int_val) + + @pytest.mark.parametrize('k, n, p', [ + (np.inf, 2, 0.5), + (1.0, np.inf, 0.5), + (1.0, 2, np.inf) + ]) + def test_inf(self, k, n, p): + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + val = sc.bdtri(k, n, p) + assert np.isnan(val) + + @pytest.mark.parametrize('k, n, p', [ + (-1.1, 1, 0.5), + (2.1, 1, 0.5) + ]) + def test_domain(self, k, n, p): + val = sc.bdtri(k, n, p) + assert np.isnan(val) + + def test_bdtr_bdtri_roundtrip(self): + bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5) + roundtrip_vals = sc.bdtri([0, 1, 2], 2, bdtr_vals) + assert_allclose(roundtrip_vals, [0.5, 0.5, np.nan]) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a0d4305c191d8f157ef152567dc511463285bd --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py @@ -0,0 +1,106 @@ +import numpy as np +from numpy.testing import assert_equal, assert_almost_equal, assert_allclose +from scipy.special import boxcox, boxcox1p, inv_boxcox, inv_boxcox1p + + +# There are more tests of boxcox and boxcox1p in test_mpmath.py. + +def test_boxcox_basic(): + x = np.array([0.5, 1, 2, 4]) + + # lambda = 0 => y = log(x) + y = boxcox(x, 0) + assert_almost_equal(y, np.log(x)) + + # lambda = 1 => y = x - 1 + y = boxcox(x, 1) + assert_almost_equal(y, x - 1) + + # lambda = 2 => y = 0.5*(x**2 - 1) + y = boxcox(x, 2) + assert_almost_equal(y, 0.5*(x**2 - 1)) + + # x = 0 and lambda > 0 => y = -1 / lambda + lam = np.array([0.5, 1, 2]) + y = boxcox(0, lam) + assert_almost_equal(y, -1.0 / lam) + +def test_boxcox_underflow(): + x = 1 + 1e-15 + lmbda = 1e-306 + y = boxcox(x, lmbda) + assert_allclose(y, np.log(x), rtol=1e-14) + + +def test_boxcox_nonfinite(): + # x < 0 => y = nan + x = np.array([-1, -1, -0.5]) + y = boxcox(x, [0.5, 2.0, -1.5]) + assert_equal(y, np.array([np.nan, np.nan, np.nan])) + + # x = 0 and lambda <= 0 => y = -inf + x = 0 + y = boxcox(x, [-2.5, 0]) + assert_equal(y, np.array([-np.inf, -np.inf])) + + +def test_boxcox1p_basic(): + x = np.array([-0.25, -1e-20, 0, 1e-20, 0.25, 1, 3]) + + # lambda = 0 => y = log(1+x) + y = boxcox1p(x, 0) + assert_almost_equal(y, np.log1p(x)) + + # lambda = 1 => y = x + y = boxcox1p(x, 1) + assert_almost_equal(y, x) + + # lambda = 2 => y = 0.5*((1+x)**2 - 1) = 0.5*x*(2 + x) + y = boxcox1p(x, 2) + assert_almost_equal(y, 0.5*x*(2 + x)) + + # x = -1 and lambda > 0 => y = -1 / lambda + lam = np.array([0.5, 1, 2]) + y = boxcox1p(-1, lam) + assert_almost_equal(y, -1.0 / lam) + + +def test_boxcox1p_underflow(): + x = np.array([1e-15, 1e-306]) + lmbda = np.array([1e-306, 1e-18]) + y = boxcox1p(x, lmbda) + assert_allclose(y, np.log1p(x), rtol=1e-14) + + +def test_boxcox1p_nonfinite(): + # x < -1 => y = nan + x = np.array([-2, -2, -1.5]) + y = boxcox1p(x, [0.5, 2.0, -1.5]) + assert_equal(y, np.array([np.nan, np.nan, np.nan])) + + # x = -1 and lambda <= 0 => y = -inf + x = -1 + y = boxcox1p(x, [-2.5, 0]) + assert_equal(y, np.array([-np.inf, -np.inf])) + + +def test_inv_boxcox(): + x = np.array([0., 1., 2.]) + lam = np.array([0., 1., 2.]) + y = boxcox(x, lam) + x2 = inv_boxcox(y, lam) + assert_almost_equal(x, x2) + + x = np.array([0., 1., 2.]) + lam = np.array([0., 1., 2.]) + y = boxcox1p(x, lam) + x2 = inv_boxcox1p(y, lam) + assert_almost_equal(x, x2) + + +def test_inv_boxcox1p_underflow(): + x = 1e-15 + lam = 1e-306 + y = inv_boxcox1p(x, lam) + assert_allclose(y, x, rtol=1e-14) + diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3e82299824b1b349ef46f0266230fc3ad2fa7e --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py @@ -0,0 +1,527 @@ +""" +Test cdflib functions versus mpmath, if available. + +The following functions still need tests: + +- ncfdtr +- ncfdtri +- ncfdtridfn +- ncfdtridfd +- ncfdtrinc +- nbdtrik +- nbdtrin +- pdtrik +- nctdtr +- nctdtrit +- nctdtridf +- nctdtrinc + +""" +import itertools + +import numpy as np +from numpy.testing import assert_equal, assert_allclose +import pytest + +import scipy.special as sp +from scipy.special._testutils import ( + MissingModule, check_version, FuncData) +from scipy.special._mptestutils import ( + Arg, IntArg, get_args, mpf2float, assert_mpmath_equal) + +try: + import mpmath +except ImportError: + mpmath = MissingModule('mpmath') + + +class ProbArg: + """Generate a set of probabilities on [0, 1].""" + + def __init__(self): + # Include the endpoints for compatibility with Arg et. al. + self.a = 0 + self.b = 1 + + def values(self, n): + """Return an array containing approximately n numbers.""" + m = max(1, n//3) + v1 = np.logspace(-30, np.log10(0.3), m) + v2 = np.linspace(0.3, 0.7, m + 1, endpoint=False)[1:] + v3 = 1 - np.logspace(np.log10(0.3), -15, m) + v = np.r_[v1, v2, v3] + return np.unique(v) + + +class EndpointFilter: + def __init__(self, a, b, rtol, atol): + self.a = a + self.b = b + self.rtol = rtol + self.atol = atol + + def __call__(self, x): + mask1 = np.abs(x - self.a) < self.rtol*np.abs(self.a) + self.atol + mask2 = np.abs(x - self.b) < self.rtol*np.abs(self.b) + self.atol + return np.where(mask1 | mask2, False, True) + + +class _CDFData: + def __init__(self, spfunc, mpfunc, index, argspec, spfunc_first=True, + dps=20, n=5000, rtol=None, atol=None, + endpt_rtol=None, endpt_atol=None): + self.spfunc = spfunc + self.mpfunc = mpfunc + self.index = index + self.argspec = argspec + self.spfunc_first = spfunc_first + self.dps = dps + self.n = n + self.rtol = rtol + self.atol = atol + + if not isinstance(argspec, list): + self.endpt_rtol = None + self.endpt_atol = None + elif endpt_rtol is not None or endpt_atol is not None: + if isinstance(endpt_rtol, list): + self.endpt_rtol = endpt_rtol + else: + self.endpt_rtol = [endpt_rtol]*len(self.argspec) + if isinstance(endpt_atol, list): + self.endpt_atol = endpt_atol + else: + self.endpt_atol = [endpt_atol]*len(self.argspec) + else: + self.endpt_rtol = None + self.endpt_atol = None + + def idmap(self, *args): + if self.spfunc_first: + res = self.spfunc(*args) + if np.isnan(res): + return np.nan + args = list(args) + args[self.index] = res + with mpmath.workdps(self.dps): + res = self.mpfunc(*tuple(args)) + # Imaginary parts are spurious + res = mpf2float(res.real) + else: + with mpmath.workdps(self.dps): + res = self.mpfunc(*args) + res = mpf2float(res.real) + args = list(args) + args[self.index] = res + res = self.spfunc(*tuple(args)) + return res + + def get_param_filter(self): + if self.endpt_rtol is None and self.endpt_atol is None: + return None + + filters = [] + for rtol, atol, spec in zip(self.endpt_rtol, self.endpt_atol, self.argspec): + if rtol is None and atol is None: + filters.append(None) + continue + elif rtol is None: + rtol = 0.0 + elif atol is None: + atol = 0.0 + + filters.append(EndpointFilter(spec.a, spec.b, rtol, atol)) + return filters + + def check(self): + # Generate values for the arguments + args = get_args(self.argspec, self.n) + param_filter = self.get_param_filter() + param_columns = tuple(range(args.shape[1])) + result_columns = args.shape[1] + args = np.hstack((args, args[:, self.index].reshape(args.shape[0], 1))) + FuncData(self.idmap, args, + param_columns=param_columns, result_columns=result_columns, + rtol=self.rtol, atol=self.atol, vectorized=False, + param_filter=param_filter).check() + + +def _assert_inverts(*a, **kw): + d = _CDFData(*a, **kw) + d.check() + + +def _binomial_cdf(k, n, p): + k, n, p = mpmath.mpf(k), mpmath.mpf(n), mpmath.mpf(p) + if k <= 0: + return mpmath.mpf(0) + elif k >= n: + return mpmath.mpf(1) + + onemp = mpmath.fsub(1, p, exact=True) + return mpmath.betainc(n - k, k + 1, x2=onemp, regularized=True) + + +def _f_cdf(dfn, dfd, x): + if x < 0: + return mpmath.mpf(0) + dfn, dfd, x = mpmath.mpf(dfn), mpmath.mpf(dfd), mpmath.mpf(x) + ub = dfn*x/(dfn*x + dfd) + res = mpmath.betainc(dfn/2, dfd/2, x2=ub, regularized=True) + return res + + +def _student_t_cdf(df, t, dps=None): + if dps is None: + dps = mpmath.mp.dps + with mpmath.workdps(dps): + df, t = mpmath.mpf(df), mpmath.mpf(t) + fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df) + fac *= t*mpmath.gamma(0.5*(df + 1)) + fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df) + return 0.5 + fac + + +def _noncentral_chi_pdf(t, df, nc): + res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t)) + res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2 + return res + + +def _noncentral_chi_cdf(x, df, nc, dps=None): + if dps is None: + dps = mpmath.mp.dps + x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc) + with mpmath.workdps(dps): + res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x]) + return res + + +def _tukey_lmbda_quantile(p, lmbda): + # For lmbda != 0 + return (p**lmbda - (1 - p)**lmbda)/lmbda + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +class TestCDFlib: + + @pytest.mark.xfail(run=False) + def test_bdtrik(self): + _assert_inverts( + sp.bdtrik, + _binomial_cdf, + 0, [ProbArg(), IntArg(1, 1000), ProbArg()], + rtol=1e-4) + + def test_bdtrin(self): + _assert_inverts( + sp.bdtrin, + _binomial_cdf, + 1, [IntArg(1, 1000), ProbArg(), ProbArg()], + rtol=1e-4, endpt_atol=[None, None, 1e-6]) + + def test_btdtria(self): + _assert_inverts( + sp.btdtria, + lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True), + 0, [ProbArg(), Arg(0, 1e2, inclusive_a=False), + Arg(0, 1, inclusive_a=False, inclusive_b=False)], + rtol=1e-6) + + def test_btdtrib(self): + # Use small values of a or mpmath doesn't converge + _assert_inverts( + sp.btdtrib, + lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True), + 1, + [Arg(0, 1e2, inclusive_a=False), ProbArg(), + Arg(0, 1, inclusive_a=False, inclusive_b=False)], + rtol=1e-7, + endpt_atol=[None, 1e-18, 1e-15]) + + @pytest.mark.xfail(run=False) + def test_fdtridfd(self): + _assert_inverts( + sp.fdtridfd, + _f_cdf, + 1, + [IntArg(1, 100), ProbArg(), Arg(0, 100, inclusive_a=False)], + rtol=1e-7) + + def test_gdtria(self): + _assert_inverts( + sp.gdtria, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 0, + [ProbArg(), Arg(0, 1e3, inclusive_a=False), + Arg(0, 1e4, inclusive_a=False)], + rtol=1e-7, + endpt_atol=[None, 1e-7, 1e-10]) + + def test_gdtrib(self): + # Use small values of a and x or mpmath doesn't converge + _assert_inverts( + sp.gdtrib, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 1, + [Arg(0, 1e2, inclusive_a=False), ProbArg(), + Arg(0, 1e3, inclusive_a=False)], + rtol=1e-5) + + def test_gdtrix(self): + _assert_inverts( + sp.gdtrix, + lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True), + 2, + [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False), + ProbArg()], + rtol=1e-7, + endpt_atol=[None, 1e-7, 1e-10]) + + # Overall nrdtrimn and nrdtrisd are not performing well with infeasible/edge + # combinations of sigma and x, hence restricted the domains to still use the + # testing machinery, also see gh-20069 + + # nrdtrimn signature: p, sd, x + # nrdtrisd signature: mn, p, x + def test_nrdtrimn(self): + _assert_inverts( + sp.nrdtrimn, + lambda x, y, z: mpmath.ncdf(z, x, y), + 0, + [ProbArg(), # CDF value p + Arg(0.1, np.inf, inclusive_a=False, inclusive_b=False), # sigma + Arg(-1e10, 1e10)], # x + rtol=1e-5) + + def test_nrdtrisd(self): + _assert_inverts( + sp.nrdtrisd, + lambda x, y, z: mpmath.ncdf(z, x, y), + 1, + [Arg(-np.inf, 10, inclusive_a=False, inclusive_b=False), # mn + ProbArg(), # CDF value p + Arg(10, 1e100)], # x + rtol=1e-5) + + def test_stdtr(self): + # Ideally the left endpoint for Arg() should be 0. + assert_mpmath_equal( + sp.stdtr, + _student_t_cdf, + [IntArg(1, 100), Arg(1e-10, np.inf)], rtol=1e-7) + + @pytest.mark.xfail(run=False) + def test_stdtridf(self): + _assert_inverts( + sp.stdtridf, + _student_t_cdf, + 0, [ProbArg(), Arg()], rtol=1e-7) + + def test_stdtrit(self): + _assert_inverts( + sp.stdtrit, + _student_t_cdf, + 1, [IntArg(1, 100), ProbArg()], rtol=1e-7, + endpt_atol=[None, 1e-10]) + + def test_chdtriv(self): + _assert_inverts( + sp.chdtriv, + lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True), + 0, [ProbArg(), IntArg(1, 100)], rtol=1e-4) + + @pytest.mark.xfail(run=False) + def test_chndtridf(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtridf, + _noncentral_chi_cdf, + 1, [Arg(0, 100, inclusive_a=False), ProbArg(), + Arg(0, 100, inclusive_a=False)], + n=1000, rtol=1e-4, atol=1e-15) + + @pytest.mark.xfail(run=False) + def test_chndtrinc(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtrinc, + _noncentral_chi_cdf, + 2, [Arg(0, 100, inclusive_a=False), IntArg(1, 100), ProbArg()], + n=1000, rtol=1e-4, atol=1e-15) + + def test_chndtrix(self): + # Use a larger atol since mpmath is doing numerical integration + _assert_inverts( + sp.chndtrix, + _noncentral_chi_cdf, + 0, [ProbArg(), IntArg(1, 100), Arg(0, 100, inclusive_a=False)], + n=1000, rtol=1e-4, atol=1e-15, + endpt_atol=[1e-6, None, None]) + + def test_tklmbda_zero_shape(self): + # When lmbda = 0 the CDF has a simple closed form + one = mpmath.mpf(1) + assert_mpmath_equal( + lambda x: sp.tklmbda(x, 0), + lambda x: one/(mpmath.exp(-x) + one), + [Arg()], rtol=1e-7) + + def test_tklmbda_neg_shape(self): + _assert_inverts( + sp.tklmbda, + _tukey_lmbda_quantile, + 0, [ProbArg(), Arg(-25, 0, inclusive_b=False)], + spfunc_first=False, rtol=1e-5, + endpt_atol=[1e-9, 1e-5]) + + @pytest.mark.xfail(run=False) + def test_tklmbda_pos_shape(self): + _assert_inverts( + sp.tklmbda, + _tukey_lmbda_quantile, + 0, [ProbArg(), Arg(0, 100, inclusive_a=False)], + spfunc_first=False, rtol=1e-5) + + # The values of lmdba are chosen so that 1/lmbda is exact. + @pytest.mark.parametrize('lmbda', [0.5, 1.0, 8.0]) + def test_tklmbda_lmbda1(self, lmbda): + bound = 1/lmbda + assert_equal(sp.tklmbda([-bound, bound], lmbda), [0.0, 1.0]) + + +funcs = [ + ("btdtria", 3), + ("btdtrib", 3), + ("bdtrik", 3), + ("bdtrin", 3), + ("chdtriv", 2), + ("chndtr", 3), + ("chndtrix", 3), + ("chndtridf", 3), + ("chndtrinc", 3), + ("fdtridfd", 3), + ("ncfdtr", 4), + ("ncfdtri", 4), + ("ncfdtridfn", 4), + ("ncfdtridfd", 4), + ("ncfdtrinc", 4), + ("gdtrix", 3), + ("gdtrib", 3), + ("gdtria", 3), + ("nbdtrik", 3), + ("nbdtrin", 3), + ("nrdtrimn", 3), + ("nrdtrisd", 3), + ("pdtrik", 2), + ("stdtr", 2), + ("stdtrit", 2), + ("stdtridf", 2), + ("nctdtr", 3), + ("nctdtrit", 3), + ("nctdtridf", 3), + ("nctdtrinc", 3), + ("tklmbda", 2), +] + + +@pytest.mark.parametrize('func,numargs', funcs, ids=[x[0] for x in funcs]) +def test_nonfinite(func, numargs): + + rng = np.random.default_rng(1701299355559735) + func = getattr(sp, func) + args_choices = [(float(x), np.nan, np.inf, -np.inf) for x in rng.random(numargs)] + + for args in itertools.product(*args_choices): + res = func(*args) + + if any(np.isnan(x) for x in args): + # Nan inputs should result to nan output + assert_equal(res, np.nan) + else: + # All other inputs should return something (but not + # raise exceptions or cause hangs) + pass + + +def test_chndtrix_gh2158(): + # test that gh-2158 is resolved; previously this blew up + res = sp.chndtrix(0.999999, 2, np.arange(20.)+1e-6) + + # Generated in R + # options(digits=16) + # ncp <- seq(0, 19) + 1e-6 + # print(qchisq(0.999999, df = 2, ncp = ncp)) + res_exp = [27.63103493142305, 35.25728589950540, 39.97396073236288, + 43.88033702110538, 47.35206403482798, 50.54112500166103, + 53.52720257322766, 56.35830042867810, 59.06600769498512, + 61.67243118946381, 64.19376191277179, 66.64228141346548, + 69.02756927200180, 71.35726934749408, 73.63759723904816, + 75.87368842650227, 78.06984431185720, 80.22971052389806, + 82.35640899964173, 84.45263768373256] + assert_allclose(res, res_exp) + +@pytest.mark.xfail_on_32bit("32bit fails due to algorithm threshold") +def test_nctdtr_gh19896(): + # test that gh-19896 is resolved. + # Compared to SciPy 1.11 results from Fortran code. + dfarr = [0.98, 9.8, 98, 980] + pnoncarr = [-3.8, 0.38, 3.8, 38] + tarr = [0.0015, 0.15, 1.5, 15] + resarr = [0.9999276519560749, 0.9999276519560749, 0.9999908831755221, + 0.9999990265452424, 0.3524153312279712, 0.39749697267251416, + 0.7168629634895805, 0.9656246449259646, 7.234804392512006e-05, + 7.234804392512006e-05, 0.03538804607509127, 0.795482701508521, + 0.0, 0.0, 0.0, + 0.011927908523093889, 0.9999276519560749, 0.9999276519560749, + 0.9999997441133123, 1.0, 0.3525155979118013, + 0.4076312014048369, 0.8476794017035086, 0.9999999297116268, + 7.234804392512006e-05, 7.234804392512006e-05, 0.013477443099785824, + 0.9998501512331494, 0.0, 0.0, + 0.0, 6.561112613212572e-07, 0.9999276519560749, + 0.9999276519560749, 0.9999999313496014, 1.0, + 0.3525281784865706, 0.40890253001898014, 0.8664672830017024, + 1.0, 7.234804392512006e-05, 7.234804392512006e-05, + 0.010990889489704836, 1.0, 0.0, + 0.0, 0.0, 0.0, + 0.9999276519560749, 0.9999276519560749, 0.9999999418789304, + 1.0, 0.35252945487817355, 0.40903153246690993, + 0.8684247068528264, 1.0, 7.234804392512006e-05, + 7.234804392512006e-05, 0.01075068918582911, 1.0, + 0.0, 0.0, 0.0, 0.0] + actarr = [] + for df, p, t in itertools.product(dfarr, pnoncarr, tarr): + actarr += [sp.nctdtr(df, p, t)] + # The rtol is kept high on purpose to make it pass on 32bit systems + assert_allclose(actarr, resarr, rtol=1e-6, atol=0.0) + + +def test_nctdtrinc_gh19896(): + # test that gh-19896 is resolved. + # Compared to SciPy 1.11 results from Fortran code. + dfarr = [0.001, 0.98, 9.8, 98, 980, 10000, 98, 9.8, 0.98, 0.001] + parr = [0.001, 0.1, 0.3, 0.8, 0.999, 0.001, 0.1, 0.3, 0.8, 0.999] + tarr = [0.0015, 0.15, 1.5, 15, 300, 0.0015, 0.15, 1.5, 15, 300] + desired = [3.090232306168629, 1.406141304556198, 2.014225177124157, + 13.727067118283456, 278.9765683871208, 3.090232306168629, + 1.4312427877936222, 2.014225177124157, 3.712743137978295, + -3.086951096691082] + actual = sp.nctdtrinc(dfarr, parr, tarr) + assert_allclose(actual, desired, rtol=5e-12, atol=0.0) + + +def test_stdtr_stdtrit_neg_inf(): + # -inf was treated as +inf and values from the normal were returned + assert np.all(np.isnan(sp.stdtr(-np.inf, [-np.inf, -1.0, 0.0, 1.0, np.inf]))) + assert np.all(np.isnan(sp.stdtrit(-np.inf, [0.0, 0.25, 0.5, 0.75, 1.0]))) + + +def test_bdtrik_nbdtrik_inf(): + y = np.array( + [np.nan,-np.inf,-10.0, -1.0, 0.0, .00001, .5, 0.9999, 1.0, 10.0, np.inf]) + y = y[:,None] + p = np.atleast_2d( + [np.nan, -np.inf, -10.0, -1.0, 0.0, .00001, .5, 1.0, np.inf]) + assert np.all(np.isnan(sp.bdtrik(y, np.inf, p))) + assert np.all(np.isnan(sp.nbdtrik(y, np.inf, p))) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1ad41243f0865c205963d938ab61a346ee8e88 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py @@ -0,0 +1,49 @@ +# gh-14777 regression tests +# Test stdtr and stdtrit with infinite df and large values of df + +import numpy as np +from numpy.testing import assert_allclose, assert_equal +from scipy.special import stdtr, stdtrit, ndtr, ndtri + + +def test_stdtr_vs_R_large_df(): + df = [1e10, 1e12, 1e120, np.inf] + t = 1. + res = stdtr(df, t) + # R Code: + # options(digits=20) + # pt(1., c(1e10, 1e12, 1e120, Inf)) + res_R = [0.84134474605644460343, + 0.84134474606842180044, + 0.84134474606854281475, + 0.84134474606854292578] + assert_allclose(res, res_R, rtol=2e-15) + # last value should also agree with ndtr + assert_equal(res[3], ndtr(1.)) + + +def test_stdtrit_vs_R_large_df(): + df = [1e10, 1e12, 1e120, np.inf] + p = 0.1 + res = stdtrit(df, p) + # R Code: + # options(digits=20) + # qt(0.1, c(1e10, 1e12, 1e120, Inf)) + res_R = [-1.2815515656292593150, + -1.2815515655454472466, + -1.2815515655446008125, + -1.2815515655446008125] + assert_allclose(res, res_R, rtol=1e-14, atol=1e-15) + # last value should also agree with ndtri + assert_equal(res[3], ndtri(0.1)) + + +def test_stdtr_stdtri_invalid(): + # a mix of large and inf df with t/p equal to nan + df = [1e10, 1e12, 1e120, np.inf] + x = np.nan + res1 = stdtr(df, x) + res2 = stdtrit(df, x) + res_ex = 4*[np.nan] + assert_equal(res1, res_ex) + assert_equal(res2, res_ex) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py new file mode 100644 index 0000000000000000000000000000000000000000..27e3ca2699d0d1d0b58665f125d99c166095696d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py @@ -0,0 +1,83 @@ +import numpy as np +from numpy.testing import assert_allclose +import pytest +from scipy.special._ufuncs import _cosine_cdf, _cosine_invcdf + + +# These values are (x, p) where p is the expected exact value of +# _cosine_cdf(x). These values will be tested for exact agreement. +_coscdf_exact = [ + (-4.0, 0.0), + (0, 0.5), + (np.pi, 1.0), + (4.0, 1.0), +] + +@pytest.mark.parametrize("x, expected", _coscdf_exact) +def test_cosine_cdf_exact(x, expected): + assert _cosine_cdf(x) == expected + + +# These values are (x, p), where p is the expected value of +# _cosine_cdf(x). The expected values were computed with mpmath using +# 50 digits of precision. These values will be tested for agreement +# with the computed values using a very small relative tolerance. +# The value at -np.pi is not 0, because -np.pi does not equal -π. +_coscdf_close = [ + (3.1409, 0.999999999991185), + (2.25, 0.9819328173287907), + # -1.6 is the threshold below which the Pade approximant is used. + (-1.599, 0.08641959838382553), + (-1.601, 0.086110582992713), + (-2.0, 0.0369709335961611), + (-3.0, 7.522387241801384e-05), + (-3.1415, 2.109869685443648e-14), + (-3.14159, 4.956444476505336e-19), + (-np.pi, 4.871934450264861e-50), +] + +@pytest.mark.parametrize("x, expected", _coscdf_close) +def test_cosine_cdf(x, expected): + assert_allclose(_cosine_cdf(x), expected, rtol=5e-15) + + +# These values are (p, x) where x is the expected exact value of +# _cosine_invcdf(p). These values will be tested for exact agreement. +_cosinvcdf_exact = [ + (0.0, -np.pi), + (0.5, 0.0), + (1.0, np.pi), +] + +@pytest.mark.parametrize("p, expected", _cosinvcdf_exact) +def test_cosine_invcdf_exact(p, expected): + assert _cosine_invcdf(p) == expected + + +def test_cosine_invcdf_invalid_p(): + # Check that p values outside of [0, 1] return nan. + assert np.isnan(_cosine_invcdf([-0.1, 1.1])).all() + + +# These values are (p, x), where x is the expected value of _cosine_invcdf(p). +# The expected values were computed with mpmath using 50 digits of precision. +_cosinvcdf_close = [ + (1e-50, -np.pi), + (1e-14, -3.1415204137058454), + (1e-08, -3.1343686589124524), + (0.0018001, -2.732563923138336), + (0.010, -2.41276589008678), + (0.060, -1.7881244975330157), + (0.125, -1.3752523669869274), + (0.250, -0.831711193579736), + (0.400, -0.3167954512395289), + (0.419, -0.25586025626919906), + (0.421, -0.24947570750445663), + (0.750, 0.831711193579736), + (0.940, 1.7881244975330153), + (0.9999999996, 3.1391220839917167), +] + +@pytest.mark.parametrize("p, expected", _cosinvcdf_close) +def test_cosine_invcdf(p, expected): + assert_allclose(_cosine_invcdf(p), expected, rtol=1e-14) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py new file mode 100644 index 0000000000000000000000000000000000000000..058b5a76c54833f127ccc2da3af10c058c00d38f --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py @@ -0,0 +1,363 @@ +from __future__ import annotations +from typing import Callable + +import pytest +from itertools import product +from numpy.testing import assert_allclose, suppress_warnings +from scipy import special +from scipy.special import cython_special + + +bint_points = [True, False] +int_points = [-10, -1, 1, 10] +real_points = [-10.0, -1.0, 1.0, 10.0] +complex_points = [complex(*tup) for tup in product(real_points, repeat=2)] + + +CYTHON_SIGNATURE_MAP = { + 'b': 'bint', + 'f': 'float', + 'd': 'double', + 'g': 'long double', + 'F': 'float complex', + 'D': 'double complex', + 'G': 'long double complex', + 'i': 'int', + 'l': 'long' +} + + +TEST_POINTS = { + 'b': bint_points, + 'f': real_points, + 'd': real_points, + 'g': real_points, + 'F': complex_points, + 'D': complex_points, + 'G': complex_points, + 'i': int_points, + 'l': int_points, +} + + +PARAMS: list[tuple[Callable, Callable, tuple[str, ...], str | None]] = [ + (special.agm, cython_special.agm, ('dd',), None), + (special.airy, cython_special._airy_pywrap, ('d', 'D'), None), + (special.airye, cython_special._airye_pywrap, ('d', 'D'), None), + (special.bdtr, cython_special.bdtr, ('dld', 'ddd'), None), + (special.bdtrc, cython_special.bdtrc, ('dld', 'ddd'), None), + (special.bdtri, cython_special.bdtri, ('dld', 'ddd'), None), + (special.bdtrik, cython_special.bdtrik, ('ddd',), None), + (special.bdtrin, cython_special.bdtrin, ('ddd',), None), + (special.bei, cython_special.bei, ('d',), None), + (special.beip, cython_special.beip, ('d',), None), + (special.ber, cython_special.ber, ('d',), None), + (special.berp, cython_special.berp, ('d',), None), + (special.besselpoly, cython_special.besselpoly, ('ddd',), None), + (special.beta, cython_special.beta, ('dd',), None), + (special.betainc, cython_special.betainc, ('ddd',), None), + (special.betaincc, cython_special.betaincc, ('ddd',), None), + (special.betaincinv, cython_special.betaincinv, ('ddd',), None), + (special.betainccinv, cython_special.betainccinv, ('ddd',), None), + (special.betaln, cython_special.betaln, ('dd',), None), + (special.binom, cython_special.binom, ('dd',), None), + (special.boxcox, cython_special.boxcox, ('dd',), None), + (special.boxcox1p, cython_special.boxcox1p, ('dd',), None), + (special.btdtr, cython_special.btdtr, ('ddd',), None), + (special.btdtri, cython_special.btdtri, ('ddd',), None), + (special.btdtria, cython_special.btdtria, ('ddd',), None), + (special.btdtrib, cython_special.btdtrib, ('ddd',), None), + (special.cbrt, cython_special.cbrt, ('d',), None), + (special.chdtr, cython_special.chdtr, ('dd',), None), + (special.chdtrc, cython_special.chdtrc, ('dd',), None), + (special.chdtri, cython_special.chdtri, ('dd',), None), + (special.chdtriv, cython_special.chdtriv, ('dd',), None), + (special.chndtr, cython_special.chndtr, ('ddd',), None), + (special.chndtridf, cython_special.chndtridf, ('ddd',), None), + (special.chndtrinc, cython_special.chndtrinc, ('ddd',), None), + (special.chndtrix, cython_special.chndtrix, ('ddd',), None), + (special.cosdg, cython_special.cosdg, ('d',), None), + (special.cosm1, cython_special.cosm1, ('d',), None), + (special.cotdg, cython_special.cotdg, ('d',), None), + (special.dawsn, cython_special.dawsn, ('d', 'D'), None), + (special.ellipe, cython_special.ellipe, ('d',), None), + (special.ellipeinc, cython_special.ellipeinc, ('dd',), None), + (special.ellipj, cython_special._ellipj_pywrap, ('dd',), None), + (special.ellipkinc, cython_special.ellipkinc, ('dd',), None), + (special.ellipkm1, cython_special.ellipkm1, ('d',), None), + (special.ellipk, cython_special.ellipk, ('d',), None), + (special.elliprc, cython_special.elliprc, ('dd', 'DD'), None), + (special.elliprd, cython_special.elliprd, ('ddd', 'DDD'), None), + (special.elliprf, cython_special.elliprf, ('ddd', 'DDD'), None), + (special.elliprg, cython_special.elliprg, ('ddd', 'DDD'), None), + (special.elliprj, cython_special.elliprj, ('dddd', 'DDDD'), None), + (special.entr, cython_special.entr, ('d',), None), + (special.erf, cython_special.erf, ('d', 'D'), None), + (special.erfc, cython_special.erfc, ('d', 'D'), None), + (special.erfcx, cython_special.erfcx, ('d', 'D'), None), + (special.erfi, cython_special.erfi, ('d', 'D'), None), + (special.erfinv, cython_special.erfinv, ('d',), None), + (special.erfcinv, cython_special.erfcinv, ('d',), None), + (special.eval_chebyc, cython_special.eval_chebyc, ('dd', 'dD', 'ld'), None), + (special.eval_chebys, cython_special.eval_chebys, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_chebyt, cython_special.eval_chebyt, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_chebyu, cython_special.eval_chebyu, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_gegenbauer, cython_special.eval_gegenbauer, ('ddd', 'ddD', 'ldd'), + 'd and l differ for negative int'), + (special.eval_genlaguerre, cython_special.eval_genlaguerre, ('ddd', 'ddD', 'ldd'), + 'd and l differ for negative int'), + (special.eval_hermite, cython_special.eval_hermite, ('ld',), None), + (special.eval_hermitenorm, cython_special.eval_hermitenorm, ('ld',), None), + (special.eval_jacobi, cython_special.eval_jacobi, ('dddd', 'dddD', 'lddd'), + 'd and l differ for negative int'), + (special.eval_laguerre, cython_special.eval_laguerre, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_legendre, cython_special.eval_legendre, ('dd', 'dD', 'ld'), None), + (special.eval_sh_chebyt, cython_special.eval_sh_chebyt, ('dd', 'dD', 'ld'), None), + (special.eval_sh_chebyu, cython_special.eval_sh_chebyu, ('dd', 'dD', 'ld'), + 'd and l differ for negative int'), + (special.eval_sh_jacobi, cython_special.eval_sh_jacobi, ('dddd', 'dddD', 'lddd'), + 'd and l differ for negative int'), + (special.eval_sh_legendre, cython_special.eval_sh_legendre, ('dd', 'dD', 'ld'), + None), + (special.exp1, cython_special.exp1, ('d', 'D'), None), + (special.exp10, cython_special.exp10, ('d',), None), + (special.exp2, cython_special.exp2, ('d',), None), + (special.expi, cython_special.expi, ('d', 'D'), None), + (special.expit, cython_special.expit, ('f', 'd', 'g'), None), + (special.expm1, cython_special.expm1, ('d', 'D'), None), + (special.expn, cython_special.expn, ('ld', 'dd'), None), + (special.exprel, cython_special.exprel, ('d',), None), + (special.fdtr, cython_special.fdtr, ('ddd',), None), + (special.fdtrc, cython_special.fdtrc, ('ddd',), None), + (special.fdtri, cython_special.fdtri, ('ddd',), None), + (special.fdtridfd, cython_special.fdtridfd, ('ddd',), None), + (special.fresnel, cython_special._fresnel_pywrap, ('d', 'D'), None), + (special.gamma, cython_special.gamma, ('d', 'D'), None), + (special.gammainc, cython_special.gammainc, ('dd',), None), + (special.gammaincc, cython_special.gammaincc, ('dd',), None), + (special.gammainccinv, cython_special.gammainccinv, ('dd',), None), + (special.gammaincinv, cython_special.gammaincinv, ('dd',), None), + (special.gammaln, cython_special.gammaln, ('d',), None), + (special.gammasgn, cython_special.gammasgn, ('d',), None), + (special.gdtr, cython_special.gdtr, ('ddd',), None), + (special.gdtrc, cython_special.gdtrc, ('ddd',), None), + (special.gdtria, cython_special.gdtria, ('ddd',), None), + (special.gdtrib, cython_special.gdtrib, ('ddd',), None), + (special.gdtrix, cython_special.gdtrix, ('ddd',), None), + (special.hankel1, cython_special.hankel1, ('dD',), None), + (special.hankel1e, cython_special.hankel1e, ('dD',), None), + (special.hankel2, cython_special.hankel2, ('dD',), None), + (special.hankel2e, cython_special.hankel2e, ('dD',), None), + (special.huber, cython_special.huber, ('dd',), None), + (special.hyp0f1, cython_special.hyp0f1, ('dd', 'dD'), None), + (special.hyp1f1, cython_special.hyp1f1, ('ddd', 'ddD'), None), + (special.hyp2f1, cython_special.hyp2f1, ('dddd', 'dddD'), None), + (special.hyperu, cython_special.hyperu, ('ddd',), None), + (special.i0, cython_special.i0, ('d',), None), + (special.i0e, cython_special.i0e, ('d',), None), + (special.i1, cython_special.i1, ('d',), None), + (special.i1e, cython_special.i1e, ('d',), None), + (special.inv_boxcox, cython_special.inv_boxcox, ('dd',), None), + (special.inv_boxcox1p, cython_special.inv_boxcox1p, ('dd',), None), + (special.it2i0k0, cython_special._it2i0k0_pywrap, ('d',), None), + (special.it2j0y0, cython_special._it2j0y0_pywrap, ('d',), None), + (special.it2struve0, cython_special.it2struve0, ('d',), None), + (special.itairy, cython_special._itairy_pywrap, ('d',), None), + (special.iti0k0, cython_special._iti0k0_pywrap, ('d',), None), + (special.itj0y0, cython_special._itj0y0_pywrap, ('d',), None), + (special.itmodstruve0, cython_special.itmodstruve0, ('d',), None), + (special.itstruve0, cython_special.itstruve0, ('d',), None), + (special.iv, cython_special.iv, ('dd', 'dD'), None), + (special.ive, cython_special.ive, ('dd', 'dD'), None), + (special.j0, cython_special.j0, ('d',), None), + (special.j1, cython_special.j1, ('d',), None), + (special.jv, cython_special.jv, ('dd', 'dD'), None), + (special.jve, cython_special.jve, ('dd', 'dD'), None), + (special.k0, cython_special.k0, ('d',), None), + (special.k0e, cython_special.k0e, ('d',), None), + (special.k1, cython_special.k1, ('d',), None), + (special.k1e, cython_special.k1e, ('d',), None), + (special.kei, cython_special.kei, ('d',), None), + (special.keip, cython_special.keip, ('d',), None), + (special.kelvin, cython_special._kelvin_pywrap, ('d',), None), + (special.ker, cython_special.ker, ('d',), None), + (special.kerp, cython_special.kerp, ('d',), None), + (special.kl_div, cython_special.kl_div, ('dd',), None), + (special.kn, cython_special.kn, ('ld', 'dd'), None), + (special.kolmogi, cython_special.kolmogi, ('d',), None), + (special.kolmogorov, cython_special.kolmogorov, ('d',), None), + (special.kv, cython_special.kv, ('dd', 'dD'), None), + (special.kve, cython_special.kve, ('dd', 'dD'), None), + (special.log1p, cython_special.log1p, ('d', 'D'), None), + (special.log_expit, cython_special.log_expit, ('f', 'd', 'g'), None), + (special.log_ndtr, cython_special.log_ndtr, ('d', 'D'), None), + (special.ndtri_exp, cython_special.ndtri_exp, ('d',), None), + (special.loggamma, cython_special.loggamma, ('D',), None), + (special.logit, cython_special.logit, ('f', 'd', 'g'), None), + (special.lpmv, cython_special.lpmv, ('ddd',), None), + (special.mathieu_a, cython_special.mathieu_a, ('dd',), None), + (special.mathieu_b, cython_special.mathieu_b, ('dd',), None), + (special.mathieu_cem, cython_special._mathieu_cem_pywrap, ('ddd',), None), + (special.mathieu_modcem1, cython_special._mathieu_modcem1_pywrap, ('ddd',), None), + (special.mathieu_modcem2, cython_special._mathieu_modcem2_pywrap, ('ddd',), None), + (special.mathieu_modsem1, cython_special._mathieu_modsem1_pywrap, ('ddd',), None), + (special.mathieu_modsem2, cython_special._mathieu_modsem2_pywrap, ('ddd',), None), + (special.mathieu_sem, cython_special._mathieu_sem_pywrap, ('ddd',), None), + (special.modfresnelm, cython_special._modfresnelm_pywrap, ('d',), None), + (special.modfresnelp, cython_special._modfresnelp_pywrap, ('d',), None), + (special.modstruve, cython_special.modstruve, ('dd',), None), + (special.nbdtr, cython_special.nbdtr, ('lld', 'ddd'), None), + (special.nbdtrc, cython_special.nbdtrc, ('lld', 'ddd'), None), + (special.nbdtri, cython_special.nbdtri, ('lld', 'ddd'), None), + (special.nbdtrik, cython_special.nbdtrik, ('ddd',), None), + (special.nbdtrin, cython_special.nbdtrin, ('ddd',), None), + (special.ncfdtr, cython_special.ncfdtr, ('dddd',), None), + (special.ncfdtri, cython_special.ncfdtri, ('dddd',), None), + (special.ncfdtridfd, cython_special.ncfdtridfd, ('dddd',), None), + (special.ncfdtridfn, cython_special.ncfdtridfn, ('dddd',), None), + (special.ncfdtrinc, cython_special.ncfdtrinc, ('dddd',), None), + (special.nctdtr, cython_special.nctdtr, ('ddd',), None), + (special.nctdtridf, cython_special.nctdtridf, ('ddd',), None), + (special.nctdtrinc, cython_special.nctdtrinc, ('ddd',), None), + (special.nctdtrit, cython_special.nctdtrit, ('ddd',), None), + (special.ndtr, cython_special.ndtr, ('d', 'D'), None), + (special.ndtri, cython_special.ndtri, ('d',), None), + (special.nrdtrimn, cython_special.nrdtrimn, ('ddd',), None), + (special.nrdtrisd, cython_special.nrdtrisd, ('ddd',), None), + (special.obl_ang1, cython_special._obl_ang1_pywrap, ('dddd',), None), + (special.obl_ang1_cv, cython_special._obl_ang1_cv_pywrap, ('ddddd',), None), + (special.obl_cv, cython_special.obl_cv, ('ddd',), None), + (special.obl_rad1, cython_special._obl_rad1_pywrap, ('dddd',), "see gh-6211"), + (special.obl_rad1_cv, cython_special._obl_rad1_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.obl_rad2, cython_special._obl_rad2_pywrap, ('dddd',), "see gh-6211"), + (special.obl_rad2_cv, cython_special._obl_rad2_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pbdv, cython_special._pbdv_pywrap, ('dd',), None), + (special.pbvv, cython_special._pbvv_pywrap, ('dd',), None), + (special.pbwa, cython_special._pbwa_pywrap, ('dd',), None), + (special.pdtr, cython_special.pdtr, ('dd', 'dd'), None), + (special.pdtrc, cython_special.pdtrc, ('dd', 'dd'), None), + (special.pdtri, cython_special.pdtri, ('ld', 'dd'), None), + (special.pdtrik, cython_special.pdtrik, ('dd',), None), + (special.poch, cython_special.poch, ('dd',), None), + (special.powm1, cython_special.powm1, ('dd',), None), + (special.pro_ang1, cython_special._pro_ang1_pywrap, ('dddd',), None), + (special.pro_ang1_cv, cython_special._pro_ang1_cv_pywrap, ('ddddd',), None), + (special.pro_cv, cython_special.pro_cv, ('ddd',), None), + (special.pro_rad1, cython_special._pro_rad1_pywrap, ('dddd',), "see gh-6211"), + (special.pro_rad1_cv, cython_special._pro_rad1_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pro_rad2, cython_special._pro_rad2_pywrap, ('dddd',), "see gh-6211"), + (special.pro_rad2_cv, cython_special._pro_rad2_cv_pywrap, ('ddddd',), + "see gh-6211"), + (special.pseudo_huber, cython_special.pseudo_huber, ('dd',), None), + (special.psi, cython_special.psi, ('d', 'D'), None), + (special.radian, cython_special.radian, ('ddd',), None), + (special.rel_entr, cython_special.rel_entr, ('dd',), None), + (special.rgamma, cython_special.rgamma, ('d', 'D'), None), + (special.round, cython_special.round, ('d',), None), + (special.spherical_jn, cython_special.spherical_jn, ('ld', 'ldb', 'lD', 'lDb'), + None), + (special.spherical_yn, cython_special.spherical_yn, ('ld', 'ldb', 'lD', 'lDb'), + None), + (special.spherical_in, cython_special.spherical_in, ('ld', 'ldb', 'lD', 'lDb'), + None), + (special.spherical_kn, cython_special.spherical_kn, ('ld', 'ldb', 'lD', 'lDb'), + None), + (special.shichi, cython_special._shichi_pywrap, ('d', 'D'), None), + (special.sici, cython_special._sici_pywrap, ('d', 'D'), None), + (special.sindg, cython_special.sindg, ('d',), None), + (special.smirnov, cython_special.smirnov, ('ld', 'dd'), None), + (special.smirnovi, cython_special.smirnovi, ('ld', 'dd'), None), + (special.spence, cython_special.spence, ('d', 'D'), None), + (special.sph_harm, cython_special.sph_harm, ('lldd', 'dddd'), None), + (special.stdtr, cython_special.stdtr, ('dd',), None), + (special.stdtridf, cython_special.stdtridf, ('dd',), None), + (special.stdtrit, cython_special.stdtrit, ('dd',), None), + (special.struve, cython_special.struve, ('dd',), None), + (special.tandg, cython_special.tandg, ('d',), None), + (special.tklmbda, cython_special.tklmbda, ('dd',), None), + (special.voigt_profile, cython_special.voigt_profile, ('ddd',), None), + (special.wofz, cython_special.wofz, ('D',), None), + (special.wright_bessel, cython_special.wright_bessel, ('ddd',), None), + (special.wrightomega, cython_special.wrightomega, ('D',), None), + (special.xlog1py, cython_special.xlog1py, ('dd', 'DD'), None), + (special.xlogy, cython_special.xlogy, ('dd', 'DD'), None), + (special.y0, cython_special.y0, ('d',), None), + (special.y1, cython_special.y1, ('d',), None), + (special.yn, cython_special.yn, ('ld', 'dd'), None), + (special.yv, cython_special.yv, ('dd', 'dD'), None), + (special.yve, cython_special.yve, ('dd', 'dD'), None), + (special.zetac, cython_special.zetac, ('d',), None), + (special.owens_t, cython_special.owens_t, ('dd',), None) +] + + +IDS = [x[0].__name__ for x in PARAMS] + + +def _generate_test_points(typecodes): + axes = tuple(TEST_POINTS[x] for x in typecodes) + pts = list(product(*axes)) + return pts + + +def test_cython_api_completeness(): + # Check that everything is tested + for name in dir(cython_special): + func = getattr(cython_special, name) + if callable(func) and not name.startswith('_'): + for _, cyfun, _, _ in PARAMS: + if cyfun is func: + break + else: + raise RuntimeError(f"{name} missing from tests!") + + +@pytest.mark.parametrize("param", PARAMS, ids=IDS) +def test_cython_api(param): + pyfunc, cyfunc, specializations, knownfailure = param + if knownfailure: + pytest.xfail(reason=knownfailure) + + # Check which parameters are expected to be fused types + max_params = max(len(spec) for spec in specializations) + values = [set() for _ in range(max_params)] + for typecodes in specializations: + for j, v in enumerate(typecodes): + values[j].add(v) + seen = set() + is_fused_code = [False] * len(values) + for j, v in enumerate(values): + vv = tuple(sorted(v)) + if vv in seen: + continue + is_fused_code[j] = (len(v) > 1) + seen.add(vv) + + # Check results + for typecodes in specializations: + # Pick the correct specialized function + signature = [CYTHON_SIGNATURE_MAP[code] + for j, code in enumerate(typecodes) + if is_fused_code[j]] + + if signature: + cy_spec_func = cyfunc[tuple(signature)] + else: + signature = None + cy_spec_func = cyfunc + + # Test it + pts = _generate_test_points(typecodes) + for pt in pts: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + pyval = pyfunc(*pt) + cyval = cy_spec_func(*pt) + assert_allclose(cyval, pyval, err_msg=f"{pt} {typecodes} {signature}") diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py new file mode 100644 index 0000000000000000000000000000000000000000..40e3eed18ca6816c1c541bb61ecab660447b38f9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py @@ -0,0 +1,725 @@ +import importlib.resources + +import numpy as np +from numpy.testing import suppress_warnings +import pytest + +from scipy.special import ( + lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite, + eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta, + jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp, + gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma, + beta, betainc, betaincinv, poch, + ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc, + elliprc, elliprd, elliprf, elliprg, elliprj, + erf, erfc, erfinv, erfcinv, exp1, expi, expn, + bdtrik, btdtr, btdtri, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib, + nbdtrik, pdtrik, owens_t, + mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1, + mathieu_modsem1, mathieu_modcem2, mathieu_modsem2, + ellip_harm, ellip_harm_2, spherical_jn, spherical_yn, wright_bessel +) +from scipy.integrate import IntegrationWarning + +from scipy.special._testutils import FuncData + + +# The npz files are generated, and hence may live in the build dir. We can only +# access them through `importlib.resources`, not an explicit path from `__file__` +_datadir = importlib.resources.files('scipy.special.tests.data') + +_boost_npz = _datadir.joinpath('boost.npz') +with importlib.resources.as_file(_boost_npz) as f: + DATASETS_BOOST = np.load(f) + +_gsl_npz = _datadir.joinpath('gsl.npz') +with importlib.resources.as_file(_gsl_npz) as f: + DATASETS_GSL = np.load(f) + +_local_npz = _datadir.joinpath('local.npz') +with importlib.resources.as_file(_local_npz) as f: + DATASETS_LOCAL = np.load(f) + + +def data(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_BOOST[dataname], *a, **kw) + + +def data_gsl(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_GSL[dataname], *a, **kw) + + +def data_local(func, dataname, *a, **kw): + kw.setdefault('dataname', dataname) + return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw) + + +def ellipk_(k): + return ellipk(k*k) + + +def ellipkinc_(f, k): + return ellipkinc(f, k*k) + + +def ellipe_(k): + return ellipe(k*k) + + +def ellipeinc_(f, k): + return ellipeinc(f, k*k) + + +def zeta_(x): + return zeta(x, 1.) + + +def assoc_legendre_p_boost_(nu, mu, x): + # the boost test data is for integer orders only + return lpmv(mu, nu.astype(int), x) + +def legendre_p_via_assoc_(nu, x): + return lpmv(0, nu, x) + +def lpn_(n, x): + return lpn(n.astype('l'), x)[0][-1] + +def lqn_(n, x): + return lqn(n.astype('l'), x)[0][-1] + +def legendre_p_via_lpmn(n, x): + return lpmn(0, n, x)[0][0,-1] + +def legendre_q_via_lqmn(n, x): + return lqmn(0, n, x)[0][0,-1] + +def mathieu_ce_rad(m, q, x): + return mathieu_cem(m, q, x*180/np.pi)[0] + + +def mathieu_se_rad(m, q, x): + return mathieu_sem(m, q, x*180/np.pi)[0] + + +def mathieu_mc1_scaled(m, q, x): + # GSL follows a different normalization. + # We follow Abramowitz & Stegun, they apparently something else. + return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_ms1_scaled(m, q, x): + return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_mc2_scaled(m, q, x): + return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2) + + +def mathieu_ms2_scaled(m, q, x): + return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2) + +def eval_legendre_ld(n, x): + return eval_legendre(n.astype('l'), x) + +def eval_legendre_dd(n, x): + return eval_legendre(n.astype('d'), x) + +def eval_hermite_ld(n, x): + return eval_hermite(n.astype('l'), x) + +def eval_laguerre_ld(n, x): + return eval_laguerre(n.astype('l'), x) + +def eval_laguerre_dd(n, x): + return eval_laguerre(n.astype('d'), x) + +def eval_genlaguerre_ldd(n, a, x): + return eval_genlaguerre(n.astype('l'), a, x) + +def eval_genlaguerre_ddd(n, a, x): + return eval_genlaguerre(n.astype('d'), a, x) + +def bdtrik_comp(y, n, p): + return bdtrik(1-y, n, p) + +def btdtri_comp(a, b, p): + return btdtri(a, b, 1-p) + +def btdtria_comp(p, b, x): + return btdtria(1-p, b, x) + +def btdtrib_comp(a, p, x): + return btdtrib(a, 1-p, x) + +def gdtr_(p, x): + return gdtr(1.0, p, x) + +def gdtrc_(p, x): + return gdtrc(1.0, p, x) + +def gdtrix_(b, p): + return gdtrix(1.0, b, p) + +def gdtrix_comp(b, p): + return gdtrix(1.0, b, 1-p) + +def gdtrib_(p, x): + return gdtrib(1.0, p, x) + +def gdtrib_comp(p, x): + return gdtrib(1.0, 1-p, x) + +def nbdtrik_comp(y, n, p): + return nbdtrik(1-y, n, p) + +def pdtrik_comp(p, m): + return pdtrik(1-p, m) + +def poch_(z, m): + return 1.0 / poch(z, m) + +def poch_minus(z, m): + return 1.0 / poch(z, -m) + +def spherical_jn_(n, x): + return spherical_jn(n.astype('l'), x) + +def spherical_yn_(n, x): + return spherical_yn(n.astype('l'), x) + +def sph_harm_(m, n, theta, phi): + y = sph_harm(m, n, theta, phi) + return (y.real, y.imag) + +def cexpm1(x, y): + z = expm1(x + 1j*y) + return z.real, z.imag + +def clog1p(x, y): + z = log1p(x + 1j*y) + return z.real, z.imag + + +BOOST_TESTS = [ + data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p', + (0,1,2), 3, rtol=1e-11), + + data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=1e-11), + data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=9.6e-14), + data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=5e-14, vectorized=False), + data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=9.6e-14, vectorized=False), + data(lpn_, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=5e-14, vectorized=False), + data(lpn_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=3e-13, vectorized=False), + data(eval_legendre_ld, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=6e-14), + data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=2e-13), + data(eval_legendre_dd, 'legendre_p_ipp-legendre_p', + (0,1), 2, rtol=2e-14), + data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 2, rtol=2e-13), + + data(lqn_, 'legendre_p_ipp-legendre_p', + (0,1), 3, rtol=2e-14, vectorized=False), + data(lqn_, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 3, rtol=2e-12, vectorized=False), + data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p', + (0,1), 3, rtol=2e-14, vectorized=False), + data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large', + (0,1), 3, rtol=2e-12, vectorized=False), + + data(beta, 'beta_exp_data_ipp-beta_exp_data', + (0,1), 2, rtol=1e-13), + data(beta, 'beta_exp_data_ipp-beta_exp_data', + (0,1), 2, rtol=1e-13), + data(beta, 'beta_med_data_ipp-beta_med_data', + (0,1), 2, rtol=5e-13), + + data(betainc, 'ibeta_small_data_ipp-ibeta_small_data', + (0,1,2), 5, rtol=6e-15), + data(betainc, 'ibeta_data_ipp-ibeta_data', + (0,1,2), 5, rtol=5e-13), + data(betainc, 'ibeta_int_data_ipp-ibeta_int_data', + (0,1,2), 5, rtol=2e-14), + data(betainc, 'ibeta_large_data_ipp-ibeta_large_data', + (0,1,2), 5, rtol=4e-10), + + data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data', + (0,1,2), 3, rtol=1e-5), + + data(btdtr, 'ibeta_small_data_ipp-ibeta_small_data', + (0,1,2), 5, rtol=6e-15), + data(btdtr, 'ibeta_data_ipp-ibeta_data', + (0,1,2), 5, rtol=4e-13), + data(btdtr, 'ibeta_int_data_ipp-ibeta_int_data', + (0,1,2), 5, rtol=2e-14), + data(btdtr, 'ibeta_large_data_ipp-ibeta_large_data', + (0,1,2), 5, rtol=4e-10), + + data(btdtri, 'ibeta_inv_data_ipp-ibeta_inv_data', + (0,1,2), 3, rtol=1e-5), + data(btdtri_comp, 'ibeta_inv_data_ipp-ibeta_inv_data', + (0,1,2), 4, rtol=8e-7), + + data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data', + (2,0,1), 3, rtol=5e-9), + data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', + (2,0,1), 4, rtol=5e-9), + + data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data', + (0,2,1), 5, rtol=5e-9), + data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data', + (0,2,1), 6, rtol=5e-9), + + data(binom, 'binomial_data_ipp-binomial_data', + (0,1), 2, rtol=1e-13), + data(binom, 'binomial_large_data_ipp-binomial_large_data', + (0,1), 2, rtol=5e-13), + + data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data', + (2,0,1), 3, rtol=5e-9), + data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data', + (2,0,1), 4, rtol=5e-9), + + data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', + (2,0,1), 3, rtol=4e-9), + data(nbdtrik_comp, + 'negative_binomial_quantile_ipp-negative_binomial_quantile_data', + (2,0,1), 4, rtol=4e-9), + + data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data', + (1,0), 2, rtol=3e-9), + data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data', + (1,0), 3, rtol=4e-9), + + data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0), + + data(digamma, 'digamma_data_ipp-digamma_data', 0, 1), + data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1), + data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13), + data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13), + data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15), + data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15), + data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15), + data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14), + + data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1), + data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14), + data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1), + data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14), + + data(erf, 'erf_data_ipp-erf_data', 0, 1), + data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13), + data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15), + data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1), + data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1), + data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14), + data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1), + data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13), + data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2), + + data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1), + data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1), + data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1, + param_filter=(lambda s: s > 0)), + + data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13), + data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9), + data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13), + data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13), + data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1), + + data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2), + data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14), + + data(gamma, 'test_gamma_data_ipp-near_0', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_1', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_2', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1), + data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12), + data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14), + data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9), + data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13), + data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10), + data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11), + data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2), + + data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15), + data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13), + data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13), + data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12), + + data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13), + data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13), + data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13), + data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9), + + data(gammaincc, 'igamma_small_data_ipp-igamma_small_data', + (0,1), 3, rtol=1e-13), + data(gammaincc, 'igamma_med_data_ipp-igamma_med_data', + (0,1), 3, rtol=2e-13), + data(gammaincc, 'igamma_int_data_ipp-igamma_int_data', + (0,1), 3, rtol=4e-14), + data(gammaincc, 'igamma_big_data_ipp-igamma_big_data', + (0,1), 3, rtol=1e-11), + + data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13), + data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13), + data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14), + data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11), + + data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9), + data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9), + + data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', + (0,1), 2, rtol=2e-13), + data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', + (0,1), 2,), + data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', + (0,1), 2,), + data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data', + (0,1), 3, rtol=2e-13), + data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int', + (0,1), 3), + data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2', + (0,1), 3), + + data(eval_hermite_ld, 'hermite_ipp-hermite', + (0,1), 2, rtol=2e-14), + + data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2', + (0,1), 2, rtol=7e-12), + data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2', + (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'), + data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3', + (0,1,2), 3, rtol=2e-13), + data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3', + (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'), + + data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1), + data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2), + + data(iv, 'bessel_i_data_ipp-bessel_i_data', + (0,1), 2, rtol=1e-12), + data(iv, 'bessel_i_data_ipp-bessel_i_data', + (0,1j), 2, rtol=2e-10, atol=1e-306), + data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', + (0,1), 2, rtol=1e-9), + data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data', + (0,1j), 2, rtol=2e-10), + + data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', + (0,1), 2, rtol=1.2e-13), + data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data', + (0,1j), 2, rtol=1.2e-13, atol=1e-300), + + data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12), + data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12), + data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11), + data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11), + + data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12), + data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12), + data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12), + data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12), + + data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', + (0,1), 2, rtol=1e-13), + data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data', + (0,1j), 2, rtol=1e-13), + data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', + (0,1), 2, rtol=1e-11), + data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data', + (0,1j), 2, rtol=2e-11), + + data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12), + + data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12), + data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12), + data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12), + data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12), + + data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', + (0,1), 2, rtol=3e-14), + data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data', + (0,1j), 2, rtol=3e-14), + data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14), + data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14), + + data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12), + data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12), + + data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12), + data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12), + data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10), + data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10), + + data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', + (0, 1), 2, rtol=4e-9), + data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data', + (0, 1j), 2, rtol=4e-9), + + data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1, + param_filter=(lambda s: s > 1)), + data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1, + param_filter=(lambda s: s > 1)), + + data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, rtol=1e-11), + data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 2, rtol=1e-14), + data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 2, rtol=1e-11), + + data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 3, rtol=1e-12), + data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 3, rtol=1e-14), + data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 3, rtol=1e-14), + + data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'), + data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 2, rtol=3e-15), + data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 2), + data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data', + (0,1), 2, knownfailure='gdtrix bad some points'), + data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data', + (0,1), 3, rtol=6e-15), + data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data', + (0,1), 3), + + data(chndtr, 'nccs_ipp-nccs', + (2,0,1), 3, rtol=3e-5), + data(chndtr, 'nccs_big_ipp-nccs_big', + (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'), + + data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic', + (1,0,3,2), (4,5), rtol=5e-11, + param_filter=(lambda p: np.ones(p.shape, '?'), + lambda p: np.ones(p.shape, '?'), + lambda p: np.logical_and(p < 2*np.pi, p >= 0), + lambda p: np.logical_and(p < np.pi, p >= 0))), + + data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data', + (0,1), 2, rtol=1e-13), + data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data', + (0,1), 2, rtol=8e-15), + + data(owens_t, 'owens_t_ipp-owens_t', + (0, 1), 2, rtol=5e-14), + data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data', + (0, 1), 2, rtol=8e-12), + + # -- test data exists in boost but is not used in scipy -- + + # ibeta_derivative_data_ipp/ibeta_derivative_data.txt + # ibeta_derivative_int_data_ipp/ibeta_derivative_int_data.txt + # ibeta_derivative_large_data_ipp/ibeta_derivative_large_data.txt + # ibeta_derivative_small_data_ipp/ibeta_derivative_small_data.txt + + # bessel_y01_prime_data_ipp/bessel_y01_prime_data.txt + # bessel_yn_prime_data_ipp/bessel_yn_prime_data.txt + # sph_bessel_prime_data_ipp/sph_bessel_prime_data.txt + # sph_neumann_prime_data_ipp/sph_neumann_prime_data.txt + + # ellint_d2_data_ipp/ellint_d2_data.txt + # ellint_d_data_ipp/ellint_d_data.txt + # ellint_pi2_data_ipp/ellint_pi2_data.txt + # ellint_pi3_data_ipp/ellint_pi3_data.txt + # ellint_pi3_large_data_ipp/ellint_pi3_large_data.txt + data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2, + rtol=5e-16), + data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3, + rtol=5e-16), + # Some of the following rtol for elliprd may be larger than 5e-16 to + # work around some hard cases in the Boost test where we get slightly + # larger error than the ideal bound when the x (==y) input is close to + # zero. + # Also the accuracy on 32-bit builds with g++ may suffer from excess + # loss of precision; see GCC bugzilla 323 + # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 + data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3, + rtol=6.5e-16), + data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3, + rtol=6e-16), + data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3, + rtol=5e-16), + data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3, + rtol=5e-16), + # The accuracy of R_G is primarily limited by R_D that is used + # internally. It is generally worse than R_D. Notice that we increased + # the rtol for R_G here. The cases with duplicate arguments are + # slightly less likely to be unbalanced (at least two arguments are + # already balanced) so the error bound is slightly better. Again, + # precision with g++ 32-bit is even worse. + data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3, + rtol=8.0e-16), + data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3, + rtol=6e-16), + data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3, + rtol=7.5e-16), + data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3, + rtol=5e-16), + data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3, + rtol=5e-16), + data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4, + rtol=5e-16, atol=1e-25, + param_filter=(lambda s: s <= 5e-26,)), + # ellint_rc_data_ipp/ellint_rc_data.txt + # ellint_rd_0xy_ipp/ellint_rd_0xy.txt + # ellint_rd_0yy_ipp/ellint_rd_0yy.txt + # ellint_rd_data_ipp/ellint_rd_data.txt + # ellint_rd_xxx_ipp/ellint_rd_xxx.txt + # ellint_rd_xxz_ipp/ellint_rd_xxz.txt + # ellint_rd_xyy_ipp/ellint_rd_xyy.txt + # ellint_rf_0yy_ipp/ellint_rf_0yy.txt + # ellint_rf_data_ipp/ellint_rf_data.txt + # ellint_rf_xxx_ipp/ellint_rf_xxx.txt + # ellint_rf_xy0_ipp/ellint_rf_xy0.txt + # ellint_rf_xyy_ipp/ellint_rf_xyy.txt + # ellint_rg_00x_ipp/ellint_rg_00x.txt + # ellint_rg_ipp/ellint_rg.txt + # ellint_rg_xxx_ipp/ellint_rg_xxx.txt + # ellint_rg_xy0_ipp/ellint_rg_xy0.txt + # ellint_rg_xyy_ipp/ellint_rg_xyy.txt + # ellint_rj_data_ipp/ellint_rj_data.txt + # ellint_rj_e2_ipp/ellint_rj_e2.txt + # ellint_rj_e3_ipp/ellint_rj_e3.txt + # ellint_rj_e4_ipp/ellint_rj_e4.txt + # ellint_rj_zp_ipp/ellint_rj_zp.txt + + # jacobi_elliptic_ipp/jacobi_elliptic.txt + # jacobi_elliptic_small_ipp/jacobi_elliptic_small.txt + # jacobi_large_phi_ipp/jacobi_large_phi.txt + # jacobi_near_1_ipp/jacobi_near_1.txt + # jacobi_zeta_big_phi_ipp/jacobi_zeta_big_phi.txt + # jacobi_zeta_data_ipp/jacobi_zeta_data.txt + + # heuman_lambda_data_ipp/heuman_lambda_data.txt + + # hypergeometric_0F2_ipp/hypergeometric_0F2.txt + # hypergeometric_1F1_big_ipp/hypergeometric_1F1_big.txt + # hypergeometric_1F1_ipp/hypergeometric_1F1.txt + # hypergeometric_1F1_small_random_ipp/hypergeometric_1F1_small_random.txt + # hypergeometric_1F2_ipp/hypergeometric_1F2.txt + # hypergeometric_1f1_large_regularized_ipp/hypergeometric_1f1_large_regularized.txt # noqa: E501 + # hypergeometric_1f1_log_large_unsolved_ipp/hypergeometric_1f1_log_large_unsolved.txt # noqa: E501 + # hypergeometric_2F0_half_ipp/hypergeometric_2F0_half.txt + # hypergeometric_2F0_integer_a2_ipp/hypergeometric_2F0_integer_a2.txt + # hypergeometric_2F0_ipp/hypergeometric_2F0.txt + # hypergeometric_2F0_large_z_ipp/hypergeometric_2F0_large_z.txt + # hypergeometric_2F1_ipp/hypergeometric_2F1.txt + # hypergeometric_2F2_ipp/hypergeometric_2F2.txt + + # ncbeta_big_ipp/ncbeta_big.txt + # nct_small_delta_ipp/nct_small_delta.txt + # nct_asym_ipp/nct_asym.txt + # ncbeta_ipp/ncbeta.txt + + # powm1_data_ipp/powm1_big_data.txt + # powm1_sqrtp1m1_test_hpp/sqrtp1m1_data.txt + + # sinc_data_ipp/sinc_data.txt + + # test_gamma_data_ipp/gammap1m1_data.txt + # tgamma_ratio_data_ipp/tgamma_ratio_data.txt + + # trig_data_ipp/trig_data.txt + # trig_data2_ipp/trig_data2.txt +] + + +@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr) +def test_boost(test): + # Filter deprecation warnings of any deprecated functions. + if test.func in [btdtr, btdtri, btdtri_comp]: + with pytest.deprecated_call(): + _test_factory(test) + else: + _test_factory(test) + + +GSL_TESTS = [ + data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13), + data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13), + + # Also the GSL output has limited accuracy... + data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13), + + data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms', + (0, 1, 2), 3, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms', + (0, 1, 2), 4, rtol=1e-7, atol=1e-13), + + data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms', + (0, 1, 2), 5, rtol=1e-7, atol=1e-13), + data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms', + (0, 1, 2), 6, rtol=1e-7, atol=1e-13), +] + + +@pytest.mark.parametrize('test', GSL_TESTS, ids=repr) +def test_gsl(test): + _test_factory(test) + + +LOCAL_TESTS = [ + data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2), + data_local(ellipkm1, 'ellipkm1', 0, 1), + data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2), + data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14), + data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14), + data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12), + data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11), + data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13), + data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13), + data_local(wright_bessel, 'wright_bessel', (0, 1, 2), 3, rtol=1e-11), +] + + +@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr) +def test_local(test): + _test_factory(test) + + +def _test_factory(test, dtype=np.float64): + """Boost test""" + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected") + with np.errstate(all='ignore'): + test.check(dtype=dtype) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py new file mode 100644 index 0000000000000000000000000000000000000000..45c8c88a5e9b297871fa0812c099fbee213c007d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py @@ -0,0 +1,46 @@ +# Tests for a few of the "double-double" C functions defined in cephes/dd_*. + +import pytest +from numpy.testing import assert_allclose +from scipy.special._test_internal import _dd_exp, _dd_log, _dd_expm1 + + +# Each tuple in test_data contains: +# (dd_func, xhi, xlo, expected_yhi, expected_ylo) +# The expected values were computed with mpmath, e.g. +# +# import mpmath +# mpmath.mp.dps = 100 +# xhi = 10.0 +# xlo = 0.0 +# x = mpmath.mpf(xhi) + mpmath.mpf(xlo) +# y = mpmath.log(x) +# expected_yhi = float(y) +# expected_ylo = float(y - expected_yhi) +# +test_data = [ + (_dd_exp, -0.3333333333333333, -1.850371707708594e-17, + 0.7165313105737893, -2.0286948382455594e-17), + (_dd_exp, 0.0, 0.0, 1.0, 0.0), + (_dd_exp, 10.0, 0.0, 22026.465794806718, -1.3780134700517372e-12), + (_dd_log, 0.03125, 0.0, -3.4657359027997265, -4.930038229799327e-18), + (_dd_log, 10.0, 0.0, 2.302585092994046, -2.1707562233822494e-16), + (_dd_expm1, -1.25, 0.0, -0.7134952031398099, -4.7031321153650186e-17), + (_dd_expm1, -0.484375, 0.0, -0.3839178722093218, 7.609376052156984e-18), + (_dd_expm1, -0.25, 0.0, -0.22119921692859512, -1.0231869534531498e-17), + (_dd_expm1, -0.0625, 0.0, -0.06058693718652421, -7.077887227488846e-19), + (_dd_expm1, 0.0, 0.0, 0.0, 0.0), + (_dd_expm1, 0.0625, 3.5e-18, 0.06449445891785943, 1.4323095758164254e-18), + (_dd_expm1, 0.25, 0.0, 0.2840254166877415, -2.133257464457841e-17), + (_dd_expm1, 0.498046875, 0.0, 0.645504254608231, -9.198435524984236e-18), + (_dd_expm1, 1.25, 0.0, 2.4903429574618414, -4.604261945372796e-17) +] + + +@pytest.mark.parametrize('dd_func, xhi, xlo, expected_yhi, expected_ylo', + test_data) +def test_dd(dd_func, xhi, xlo, expected_yhi, expected_ylo): + yhi, ylo = dd_func(xhi, xlo) + assert yhi == expected_yhi, (f"high double ({yhi}) does not equal the " + f"expected value {expected_yhi}") + assert_allclose(ylo, expected_ylo, rtol=5e-15) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f27dc7b71c1ae928b4bdd8bd987df9ca420bab --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py @@ -0,0 +1,45 @@ +import numpy as np +from numpy import pi, log, sqrt +from numpy.testing import assert_, assert_equal + +from scipy.special._testutils import FuncData +import scipy.special as sc + +# Euler-Mascheroni constant +euler = 0.57721566490153286 + + +def test_consistency(): + # Make sure the implementation of digamma for real arguments + # agrees with the implementation of digamma for complex arguments. + + # It's all poles after -1e16 + x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)] + dataset = np.vstack((x + 0j, sc.digamma(x))).T + FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check() + + +def test_special_values(): + # Test special values from Gauss's digamma theorem. See + # + # https://en.wikipedia.org/wiki/Digamma_function + + dataset = [ + (1, -euler), + (0.5, -2*log(2) - euler), + (1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler), + (1/4, -pi/2 - 3*log(2) - euler), + (1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler), + (1/8, + -pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler) + ] + + dataset = np.asarray(dataset) + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() + + +def test_nonfinite(): + pts = [0.0, -0.0, np.inf] + std = [-np.inf, np.inf, np.inf] + assert_equal(sc.digamma(pts), std) + assert_(all(np.isnan(sc.digamma([-np.inf, -1])))) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..a97c2468633062fbb4d858c9b22d60fff9bc9e24 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py @@ -0,0 +1,278 @@ +# +# Tests for the Ellipsoidal Harmonic Function, +# Distributed under the same license as SciPy itself. +# + +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, assert_allclose, + assert_, suppress_warnings) +from scipy.special._testutils import assert_func_equal +from scipy.special import ellip_harm, ellip_harm_2, ellip_normal +from scipy.integrate import IntegrationWarning +from numpy import sqrt, pi + + +def test_ellip_potential(): + def change_coefficient(lambda1, mu, nu, h2, k2): + x = sqrt(lambda1**2*mu**2*nu**2/(h2*k2)) + y = sqrt((lambda1**2 - h2)*(mu**2 - h2)*(h2 - nu**2)/(h2*(k2 - h2))) + z = sqrt((lambda1**2 - k2)*(k2 - mu**2)*(k2 - nu**2)/(k2*(k2 - h2))) + return x, y, z + + def solid_int_ellip(lambda1, mu, nu, n, p, h2, k2): + return (ellip_harm(h2, k2, n, p, lambda1)*ellip_harm(h2, k2, n, p, mu) + * ellip_harm(h2, k2, n, p, nu)) + + def solid_int_ellip2(lambda1, mu, nu, n, p, h2, k2): + return (ellip_harm_2(h2, k2, n, p, lambda1) + * ellip_harm(h2, k2, n, p, mu)*ellip_harm(h2, k2, n, p, nu)) + + def summation(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2): + tol = 1e-8 + sum1 = 0 + for n in range(20): + xsum = 0 + for p in range(1, 2*n+2): + xsum += (4*pi*(solid_int_ellip(lambda2, mu2, nu2, n, p, h2, k2) + * solid_int_ellip2(lambda1, mu1, nu1, n, p, h2, k2)) / + (ellip_normal(h2, k2, n, p)*(2*n + 1))) + if abs(xsum) < 0.1*tol*abs(sum1): + break + sum1 += xsum + return sum1, xsum + + def potential(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2): + x1, y1, z1 = change_coefficient(lambda1, mu1, nu1, h2, k2) + x2, y2, z2 = change_coefficient(lambda2, mu2, nu2, h2, k2) + res = sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2) + return 1/res + + pts = [ + (120, sqrt(19), 2, 41, sqrt(17), 2, 15, 25), + (120, sqrt(16), 3.2, 21, sqrt(11), 2.9, 11, 20), + ] + + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + sup.filter(IntegrationWarning, "The maximum number of subdivisions") + + for p in pts: + err_msg = repr(p) + exact = potential(*p) + result, last_term = summation(*p) + assert_allclose(exact, result, atol=0, rtol=1e-8, err_msg=err_msg) + assert_(abs(result - exact) < 10*abs(last_term), err_msg) + + +def test_ellip_norm(): + + def G01(h2, k2): + return 4*pi + + def G11(h2, k2): + return 4*pi*h2*k2/3 + + def G12(h2, k2): + return 4*pi*h2*(k2 - h2)/3 + + def G13(h2, k2): + return 4*pi*k2*(k2 - h2)/3 + + def G22(h2, k2): + res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 + + sqrt(h2**2 + k2**2 - h2*k2)*(-2*(h2**3 + k2**3) + 3*h2*k2*(h2 + k2))) + return 16*pi/405*res + + def G21(h2, k2): + res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 + + sqrt(h2**2 + k2**2 - h2*k2)*(2*(h2**3 + k2**3) - 3*h2*k2*(h2 + k2))) + return 16*pi/405*res + + def G23(h2, k2): + return 4*pi*h2**2*k2*(k2 - h2)/15 + + def G24(h2, k2): + return 4*pi*h2*k2**2*(k2 - h2)/15 + + def G25(h2, k2): + return 4*pi*h2*k2*(k2 - h2)**2/15 + + def G32(h2, k2): + res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2 + + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(-8*(h2**3 + k2**3) + + 11*h2*k2*(h2 + k2))) + return 16*pi/13125*k2*h2*res + + def G31(h2, k2): + res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2 + + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(8*(h2**3 + k2**3) - + 11*h2*k2*(h2 + k2))) + return 16*pi/13125*h2*k2*res + + def G34(h2, k2): + res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(h2**2 + 4*k2**2 - h2*k2)*(-6*h2**3 - 8*k2**3 + 9*h2**2*k2 + + 13*h2*k2**2)) + return 16*pi/13125*h2*(k2 - h2)*res + + def G33(h2, k2): + res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(h2**2 + 4*k2**2 - h2*k2)*(6*h2**3 + 8*k2**3 - 9*h2**2*k2 - + 13*h2*k2**2)) + return 16*pi/13125*h2*(k2 - h2)*res + + def G36(h2, k2): + res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(4*h2**2 + k2**2 - h2*k2)*(-8*h2**3 - 6*k2**3 + 13*h2**2*k2 + + 9*h2*k2**2)) + return 16*pi/13125*k2*(k2 - h2)*res + + def G35(h2, k2): + res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2 + + sqrt(4*h2**2 + k2**2 - h2*k2)*(8*h2**3 + 6*k2**3 - 13*h2**2*k2 - + 9*h2*k2**2)) + return 16*pi/13125*k2*(k2 - h2)*res + + def G37(h2, k2): + return 4*pi*h2**2*k2**2*(k2 - h2)**2/105 + + known_funcs = {(0, 1): G01, (1, 1): G11, (1, 2): G12, (1, 3): G13, + (2, 1): G21, (2, 2): G22, (2, 3): G23, (2, 4): G24, + (2, 5): G25, (3, 1): G31, (3, 2): G32, (3, 3): G33, + (3, 4): G34, (3, 5): G35, (3, 6): G36, (3, 7): G37} + + def _ellip_norm(n, p, h2, k2): + func = known_funcs[n, p] + return func(h2, k2) + _ellip_norm = np.vectorize(_ellip_norm) + + def ellip_normal_known(h2, k2, n, p): + return _ellip_norm(n, p, h2, k2) + + # generate both large and small h2 < k2 pairs + np.random.seed(1234) + h2 = np.random.pareto(0.5, size=1) + k2 = h2 * (1 + np.random.pareto(0.5, size=h2.size)) + + points = [] + for n in range(4): + for p in range(1, 2*n+2): + points.append((h2, k2, np.full(h2.size, n), np.full(h2.size, p))) + points = np.array(points) + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + assert_func_equal(ellip_normal, ellip_normal_known, points, rtol=1e-12) + + +def test_ellip_harm_2(): + + def I1(h2, k2, s): + res = (ellip_harm_2(h2, k2, 1, 1, s)/(3 * ellip_harm(h2, k2, 1, 1, s)) + + ellip_harm_2(h2, k2, 1, 2, s)/(3 * ellip_harm(h2, k2, 1, 2, s)) + + ellip_harm_2(h2, k2, 1, 3, s)/(3 * ellip_harm(h2, k2, 1, 3, s))) + return res + + with suppress_warnings() as sup: + sup.filter(IntegrationWarning, "The occurrence of roundoff error") + assert_almost_equal(I1(5, 8, 10), 1/(10*sqrt((100-5)*(100-8)))) + + # Values produced by code from arXiv:1204.0267 + assert_almost_equal(ellip_harm_2(5, 8, 2, 1, 10), 0.00108056853382) + assert_almost_equal(ellip_harm_2(5, 8, 2, 2, 10), 0.00105820513809) + assert_almost_equal(ellip_harm_2(5, 8, 2, 3, 10), 0.00106058384743) + assert_almost_equal(ellip_harm_2(5, 8, 2, 4, 10), 0.00106774492306) + assert_almost_equal(ellip_harm_2(5, 8, 2, 5, 10), 0.00107976356454) + + +def test_ellip_harm(): + + def E01(h2, k2, s): + return 1 + + def E11(h2, k2, s): + return s + + def E12(h2, k2, s): + return sqrt(abs(s*s - h2)) + + def E13(h2, k2, s): + return sqrt(abs(s*s - k2)) + + def E21(h2, k2, s): + return s*s - 1/3*((h2 + k2) + sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2))) + + def E22(h2, k2, s): + return s*s - 1/3*((h2 + k2) - sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2))) + + def E23(h2, k2, s): + return s * sqrt(abs(s*s - h2)) + + def E24(h2, k2, s): + return s * sqrt(abs(s*s - k2)) + + def E25(h2, k2, s): + return sqrt(abs((s*s - h2)*(s*s - k2))) + + def E31(h2, k2, s): + return s*s*s - (s/5)*(2*(h2 + k2) + sqrt(4*(h2 + k2)*(h2 + k2) - + 15*h2*k2)) + + def E32(h2, k2, s): + return s*s*s - (s/5)*(2*(h2 + k2) - sqrt(4*(h2 + k2)*(h2 + k2) - + 15*h2*k2)) + + def E33(h2, k2, s): + return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) + sqrt(abs((h2 + + 2*k2)*(h2 + 2*k2) - 5*h2*k2)))) + + def E34(h2, k2, s): + return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) - sqrt(abs((h2 + + 2*k2)*(h2 + 2*k2) - 5*h2*k2)))) + + def E35(h2, k2, s): + return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) + sqrt(abs((2*h2 + + k2)*(2*h2 + k2) - 5*h2*k2)))) + + def E36(h2, k2, s): + return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) - sqrt(abs((2*h2 + + k2)*(2*h2 + k2) - 5*h2*k2)))) + + def E37(h2, k2, s): + return s * sqrt(abs((s*s - h2)*(s*s - k2))) + + assert_equal(ellip_harm(5, 8, 1, 2, 2.5, 1, 1), + ellip_harm(5, 8, 1, 2, 2.5)) + + known_funcs = {(0, 1): E01, (1, 1): E11, (1, 2): E12, (1, 3): E13, + (2, 1): E21, (2, 2): E22, (2, 3): E23, (2, 4): E24, + (2, 5): E25, (3, 1): E31, (3, 2): E32, (3, 3): E33, + (3, 4): E34, (3, 5): E35, (3, 6): E36, (3, 7): E37} + + point_ref = [] + + def ellip_harm_known(h2, k2, n, p, s): + for i in range(h2.size): + func = known_funcs[(int(n[i]), int(p[i]))] + point_ref.append(func(h2[i], k2[i], s[i])) + return point_ref + + np.random.seed(1234) + h2 = np.random.pareto(0.5, size=30) + k2 = h2*(1 + np.random.pareto(0.5, size=h2.size)) + s = np.random.pareto(0.5, size=h2.size) + points = [] + for i in range(h2.size): + for n in range(4): + for p in range(1, 2*n+2): + points.append((h2[i], k2[i], n, p, s[i])) + points = np.array(points) + assert_func_equal(ellip_harm, ellip_harm_known, points, rtol=1e-12) + + +def test_ellip_harm_invalid_p(): + # Regression test. This should return nan. + n = 4 + # Make p > 2*n + 1. + p = 2*n + 2 + result = ellip_harm(0.5, 2.0, n, p, 0.2) + assert np.isnan(result) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py new file mode 100644 index 0000000000000000000000000000000000000000..98739b93fc6ad75a41a7b80107ee696453b12a09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py @@ -0,0 +1,89 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import pytest + +import scipy.special as sc + + +class TestInverseErrorFunction: + def test_compliment(self): + # Test erfcinv(1 - x) == erfinv(x) + x = np.linspace(-1, 1, 101) + assert_allclose(sc.erfcinv(1 - x), sc.erfinv(x), rtol=0, atol=1e-15) + + def test_literal_values(self): + # The expected values were calculated with mpmath: + # + # import mpmath + # mpmath.mp.dps = 200 + # for y in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]: + # x = mpmath.erfinv(y) + # print(x) + # + y = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) + actual = sc.erfinv(y) + expected = [ + 0.0, + 0.08885599049425769, + 0.1791434546212917, + 0.2724627147267543, + 0.37080715859355795, + 0.4769362762044699, + 0.5951160814499948, + 0.7328690779592167, + 0.9061938024368233, + 1.1630871536766743, + ] + assert_allclose(actual, expected, rtol=0, atol=1e-15) + + @pytest.mark.parametrize( + 'f, x, y', + [ + (sc.erfinv, -1, -np.inf), + (sc.erfinv, 0, 0), + (sc.erfinv, 1, np.inf), + (sc.erfinv, -100, np.nan), + (sc.erfinv, 100, np.nan), + (sc.erfcinv, 0, np.inf), + (sc.erfcinv, 1, -0.0), + (sc.erfcinv, 2, -np.inf), + (sc.erfcinv, -100, np.nan), + (sc.erfcinv, 100, np.nan), + ], + ids=[ + 'erfinv at lower bound', + 'erfinv at midpoint', + 'erfinv at upper bound', + 'erfinv below lower bound', + 'erfinv above upper bound', + 'erfcinv at lower bound', + 'erfcinv at midpoint', + 'erfcinv at upper bound', + 'erfcinv below lower bound', + 'erfcinv above upper bound', + ] + ) + def test_domain_bounds(self, f, x, y): + assert_equal(f(x), y) + + def test_erfinv_asympt(self): + # regression test for gh-12758: erfinv(x) loses precision at small x + # expected values precomputed with mpmath: + # >>> mpmath.mp.dps = 100 + # >>> expected = [float(mpmath.erfinv(t)) for t in x] + x = np.array([1e-20, 1e-15, 1e-14, 1e-10, 1e-8, 0.9e-7, 1.1e-7, 1e-6]) + expected = np.array([8.86226925452758e-21, + 8.862269254527581e-16, + 8.86226925452758e-15, + 8.862269254527581e-11, + 8.86226925452758e-09, + 7.97604232907484e-08, + 9.74849617998037e-08, + 8.8622692545299e-07]) + assert_allclose(sc.erfinv(x), expected, + rtol=1e-15) + + # also test the roundtrip consistency + assert_allclose(sc.erf(sc.erfinv(x)), + x, + rtol=5e-15) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py new file mode 100644 index 0000000000000000000000000000000000000000..8332a83267e2f75dded04e80443c150c832676c8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py @@ -0,0 +1,118 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose +import scipy.special as sc + + +class TestExp1: + + def test_branch_cut(self): + assert np.isnan(sc.exp1(-1)) + assert sc.exp1(complex(-1, 0)).imag == ( + -sc.exp1(complex(-1, -0.0)).imag + ) + + assert_allclose( + sc.exp1(complex(-1, 0)), + sc.exp1(-1 + 1e-20j), + atol=0, + rtol=1e-15 + ) + assert_allclose( + sc.exp1(complex(-1, -0.0)), + sc.exp1(-1 - 1e-20j), + atol=0, + rtol=1e-15 + ) + + def test_834(self): + # Regression test for #834 + a = sc.exp1(-complex(19.9999990)) + b = sc.exp1(-complex(19.9999991)) + assert_allclose(a.imag, b.imag, atol=0, rtol=1e-15) + + +class TestScaledExp1: + + @pytest.mark.parametrize('x, expected', [(0, 0), (np.inf, 1)]) + def test_limits(self, x, expected): + y = sc._ufuncs._scaled_exp1(x) + assert y == expected + + # The expected values were computed with mpmath, e.g.: + # + # from mpmath import mp + # mp.dps = 80 + # x = 1e-25 + # print(float(x*mp.exp(x)*np.expint(1, x))) + # + # prints 5.698741165994961e-24 + # + # The method used to compute _scaled_exp1 changes at x=1 + # and x=1250, so values at those inputs, and values just + # above and below them, are included in the test data. + @pytest.mark.parametrize('x, expected', + [(1e-25, 5.698741165994961e-24), + (0.1, 0.20146425447084518), + (0.9995, 0.5962509885831002), + (1.0, 0.5963473623231941), + (1.0005, 0.5964436833238044), + (2.5, 0.7588145912149602), + (10.0, 0.9156333393978808), + (100.0, 0.9901942286733019), + (500.0, 0.9980079523802055), + (1000.0, 0.9990019940238807), + (1249.5, 0.9992009578306811), + (1250.0, 0.9992012769377913), + (1250.25, 0.9992014363957858), + (2000.0, 0.9995004992514963), + (1e4, 0.9999000199940024), + (1e10, 0.9999999999), + (1e15, 0.999999999999999), + ]) + def test_scaled_exp1(self, x, expected): + y = sc._ufuncs._scaled_exp1(x) + assert_allclose(y, expected, rtol=2e-15) + + +class TestExpi: + + @pytest.mark.parametrize('result', [ + sc.expi(complex(-1, 0)), + sc.expi(complex(-1, -0.0)), + sc.expi(-1) + ]) + def test_branch_cut(self, result): + desired = -0.21938393439552027368 # Computed using Mpmath + assert_allclose(result, desired, atol=0, rtol=1e-14) + + def test_near_branch_cut(self): + lim_from_above = sc.expi(-1 + 1e-20j) + lim_from_below = sc.expi(-1 - 1e-20j) + assert_allclose( + lim_from_above.real, + lim_from_below.real, + atol=0, + rtol=1e-15 + ) + assert_allclose( + lim_from_above.imag, + -lim_from_below.imag, + atol=0, + rtol=1e-15 + ) + + def test_continuity_on_positive_real_axis(self): + assert_allclose( + sc.expi(complex(1, 0)), + sc.expi(complex(1, -0.0)), + atol=0, + rtol=1e-15 + ) + + +class TestExpn: + + def test_out_of_domain(self): + assert all(np.isnan([sc.expn(-1, 1.0), sc.expn(1, -1.0)])) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py new file mode 100644 index 0000000000000000000000000000000000000000..8868f66c47ce0d4bbb21c78435a6c89d44065252 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py @@ -0,0 +1,85 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose +import scipy.special as sc +from scipy.special._testutils import FuncData + + +class TestVoigtProfile: + + @pytest.mark.parametrize('x, sigma, gamma', [ + (np.nan, 1, 1), + (0, np.nan, 1), + (0, 1, np.nan), + (1, np.nan, 0), + (np.nan, 1, 0), + (1, 0, np.nan), + (np.nan, 0, 1), + (np.nan, 0, 0) + ]) + def test_nan(self, x, sigma, gamma): + assert np.isnan(sc.voigt_profile(x, sigma, gamma)) + + @pytest.mark.parametrize('x, desired', [ + (-np.inf, 0), + (np.inf, 0) + ]) + def test_inf(self, x, desired): + assert sc.voigt_profile(x, 1, 1) == desired + + def test_against_mathematica(self): + # Results obtained from Mathematica by computing + # + # PDF[VoigtDistribution[gamma, sigma], x] + # + points = np.array([ + [-7.89, 45.06, 6.66, 0.0077921073660388806401], + [-0.05, 7.98, 24.13, 0.012068223646769913478], + [-13.98, 16.83, 42.37, 0.0062442236362132357833], + [-12.66, 0.21, 6.32, 0.010052516161087379402], + [11.34, 4.25, 21.96, 0.0113698923627278917805], + [-11.56, 20.40, 30.53, 0.0076332760432097464987], + [-9.17, 25.61, 8.32, 0.011646345779083005429], + [16.59, 18.05, 2.50, 0.013637768837526809181], + [9.11, 2.12, 39.33, 0.0076644040807277677585], + [-43.33, 0.30, 45.68, 0.0036680463875330150996] + ]) + FuncData( + sc.voigt_profile, + points, + (0, 1, 2), + 3, + atol=0, + rtol=1e-15 + ).check() + + def test_symmetry(self): + x = np.linspace(0, 10, 20) + assert_allclose( + sc.voigt_profile(x, 1, 1), + sc.voigt_profile(-x, 1, 1), + rtol=1e-15, + atol=0 + ) + + @pytest.mark.parametrize('x, sigma, gamma, desired', [ + (0, 0, 0, np.inf), + (1, 0, 0, 0) + ]) + def test_corner_cases(self, x, sigma, gamma, desired): + assert sc.voigt_profile(x, sigma, gamma) == desired + + @pytest.mark.parametrize('sigma1, gamma1, sigma2, gamma2', [ + (0, 1, 1e-16, 1), + (1, 0, 1, 1e-16), + (0, 0, 1e-16, 1e-16) + ]) + def test_continuity(self, sigma1, gamma1, sigma2, gamma2): + x = np.linspace(1, 10, 20) + assert_allclose( + sc.voigt_profile(x, sigma1, gamma1), + sc.voigt_profile(x, sigma2, gamma2), + rtol=1e-16, + atol=1e-16 + ) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..2e3fbd17dddeed73d311566a930f52899e3b9db6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py @@ -0,0 +1,12 @@ +import numpy as np +import scipy.special as sc + + +class TestRgamma: + + def test_gh_11315(self): + assert sc.rgamma(-35) == 0 + + def test_rgamma_zeros(self): + x = np.array([0, -10, -100, -1000, -10000]) + assert np.all(sc.rgamma(x) == 0) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..aae34e5c23f2d293f362abd825f1dad454371ae0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py @@ -0,0 +1,136 @@ +import pytest + +import numpy as np +from numpy.testing import assert_allclose, assert_array_equal + +import scipy.special as sc +from scipy.special._testutils import FuncData + + +INVALID_POINTS = [ + (1, -1), + (0, 0), + (-1, 1), + (np.nan, 1), + (1, np.nan) +] + + +class TestGammainc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammainc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammainc(0, 1) == 1 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 0), + (np.inf, 0, 0), + (np.inf, np.inf, np.nan), + (1, np.inf, 1) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammainc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert_allclose( + sc.gammainc(1000, 100), + sc.gammainc(np.inf, 100), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + assert sc.gammainc(100, 1000) == sc.gammainc(100, np.inf) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammainc(a, 0), 0) + + def test_limit_check(self): + result = sc.gammainc(1e-10, 1) + limit = sc.gammainc(0, 1) + assert np.isclose(result, limit) + + def gammainc_line(self, x): + # The line a = x where a simpler asymptotic expansion (analog + # of DLMF 8.12.15) is available. + c = np.array([-1/3, -1/540, 25/6048, 101/155520, + -3184811/3695155200, -2745493/8151736420]) + res = 0 + xfac = 1 + for ck in c: + res -= ck*xfac + xfac /= x + res /= np.sqrt(2*np.pi*x) + res += 0.5 + return res + + def test_line(self): + x = np.logspace(np.log10(25), 300, 500) + a = x + dataset = np.vstack((a, x, self.gammainc_line(x))).T + FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-11).check() + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammaincinv(a, sc.gammainc(a, x)) + assert_allclose(x, y, rtol=1e-10) + + +class TestGammaincc: + + @pytest.mark.parametrize('a, x', INVALID_POINTS) + def test_domain(self, a, x): + assert np.isnan(sc.gammaincc(a, x)) + + def test_a_eq_0_x_gt_0(self): + assert sc.gammaincc(0, 1) == 0 + + @pytest.mark.parametrize('a, x, desired', [ + (np.inf, 1, 1), + (np.inf, 0, 1), + (np.inf, np.inf, np.nan), + (1, np.inf, 0) + ]) + def test_infinite_arguments(self, a, x, desired): + result = sc.gammaincc(a, x) + if np.isnan(desired): + assert np.isnan(result) + else: + assert result == desired + + def test_infinite_limits(self): + # Test that large arguments converge to the hard-coded limits + # at infinity. + assert sc.gammaincc(1000, 100) == sc.gammaincc(np.inf, 100) + assert_allclose( + sc.gammaincc(100, 1000), + sc.gammaincc(100, np.inf), + atol=1e-200, # Use `atol` since the function converges to 0. + rtol=0 + ) + + def test_limit_check(self): + result = sc.gammaincc(1e-10,1) + limit = sc.gammaincc(0,1) + assert np.isclose(result, limit) + + def test_x_zero(self): + a = np.arange(1, 10) + assert_array_equal(sc.gammaincc(a, 0), 1) + + def test_roundtrip(self): + a = np.logspace(-5, 10, 100) + x = np.logspace(-5, 10, 100) + + y = sc.gammainccinv(a, sc.gammaincc(a, x)) + assert_allclose(x, y, rtol=1e-14) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py new file mode 100644 index 0000000000000000000000000000000000000000..200d4bbedef42997fa45034e69932feb7f5b3b06 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py @@ -0,0 +1,2180 @@ +"""Tests for hyp2f1 for complex values. + +Author: Albert Steppi, with credit to Adam Kullberg (FormerPhycisist) for +the implementation of mp_hyp2f1 below, which modifies mpmath's hyp2f1 to +return the same branch as scipy's on the standard branch cut. +""" + +import sys +import pytest +import numpy as np +from typing import NamedTuple +from numpy.testing import assert_allclose + +from scipy.special import hyp2f1 +from scipy.special._testutils import check_version, MissingModule + + +try: + import mpmath +except ImportError: + mpmath = MissingModule("mpmath") + + +def mp_hyp2f1(a, b, c, z): + """Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1. + + For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the + branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch. + Thus, to generate the right comparison values on the branch cut, we + evaluate mpmath.hyp2f1 at x + 1e-15*j. + + The exception to this occurs when c-a=-m in which case both mpmath and + scipy calculate the x + 0j branch on the branch cut. When this happens + mpmath.hyp2f1 will be evaluated at the original z point. + """ + on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15 + cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0 + cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0 + # Make sure imaginary part is *exactly* zero + if on_branch_cut: + z = z.real + 0.0j + if on_branch_cut and not (cond1 or cond2): + z_mpmath = z.real + 1.0e-15j + else: + z_mpmath = z + return complex(mpmath.hyp2f1(a, b, c, z_mpmath)) + + +class Hyp2f1TestCase(NamedTuple): + a: float + b: float + c: float + z: complex + expected: complex + rtol: float + + +class TestHyp2f1: + """Tests for hyp2f1 for complex values. + + Expected values for test cases were computed using mpmath. See + `scipy.special._precompute.hyp2f1_data`. The verbose style of specifying + test cases is used for readability and to make it easier to mark individual + cases as expected to fail. Expected failures are used to highlight cases + where improvements are needed. See + `scipy.special._precompute.hyp2f1_data.make_hyp2f1_test_cases` for a + function to generate the boilerplate for the test cases. + + Assertions have been added to each test to ensure that the test cases match + the situations that are intended. A final test `test_test_hyp2f1` checks + that the expected values in the test cases actually match what is computed + by mpmath. This test is marked slow even though it isn't particularly slow + so that it won't run by default on continuous integration builds. + """ + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=-10, + z=0.2 + 0.2j, + expected=np.inf + 0j, + rtol=0 + ) + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=-10, + z=0 + 0j, + expected=1 + 0j, + rtol=0 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0, + c=-10, + z=0.2 + 0.2j, + expected=1 + 0j, + rtol=0 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0, + c=0, + z=0.2 + 0.2j, + expected=1 + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=0, + z=0.2 + 0.2j, + expected=np.inf + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=0, + z=0 + 0j, + expected=np.nan + 0j, + rtol=0, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=-5, + c=-10, + z=0.2 + 0.2j, + expected=(1.0495404166666666+0.05708208333333334j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=-10, + c=-10, + z=0.2 + 0.2j, + expected=(1.092966013125+0.13455014673750001j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-10, + b=-20, + c=-10, + z=0.2 + 0.2j, + expected=(-0.07712512000000005+0.12752814080000005j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1, + b=3.2, + c=-1, + z=0.2 + 0.2j, + expected=(1.6400000000000001+0.6400000000000001j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-2, + b=1.2, + c=-4, + z=1 + 0j, + expected=1.8200000000000001 + 0j, + rtol=1e-15, + ), + ), + ] + ) + def test_c_non_positive_int(self, hyp2f1_test_case): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=1.5, + z=1 + 0j, + expected=1.1496439092239847 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=12.3, + b=8.0, + c=20.31, + z=1 + 0j, + expected=69280986.75273195 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=290.2, + b=321.5, + c=700.1, + z=1 + 0j, + expected=1.3396562400934e117 + 0j, + rtol=1e-12, + ), + ), + # Note that here even mpmath produces different results for + # results that should be equivalent. + pytest.param( + Hyp2f1TestCase( + a=9.2, + b=621.5, + c=700.1, + z=(1+0j), + expected=(952726652.4158565+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=621.5, + b=9.2, + c=700.1, + z=(1+0j), + expected=(952726652.4160284+0j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-101.2, + b=-400.4, + c=-172.1, + z=(1+0j), + expected=(2.2253618341394838e+37+0j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-400.4, + b=-101.2, + c=-172.1, + z=(1+0j), + expected=(2.2253618341394838e+37+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=172.5, + b=-201.3, + c=151.2, + z=(1+0j), + expected=(7.072266653650905e-135+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-201.3, + b=172.5, + c=151.2, + z=(1+0j), + expected=(7.072266653650905e-135+0j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-102.1, + b=-20.3, + c=1.3, + z=1 + 0j, + expected=2.7899070752746906e22 + 0j, + rtol=3e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-202.6, + b=60.3, + c=1.5, + z=1 + 0j, + expected=-1.3113641413099326e-56 + 0j, + rtol=1e-12, + ), + ), + ], + ) + def test_unital_argument(self, hyp2f1_test_case): + """Tests for case z = 1, c - a - b > 0. + + Expected answers computed using mpmath. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert z == 1 and c - a - b > 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=0.5, + b=0.2, + c=1.3, + z=-1 + 0j, + expected=0.9428846409614143 + 0j, + rtol=1e-15), + ), + pytest.param( + Hyp2f1TestCase( + a=12.3, + b=8.0, + c=5.300000000000001, + z=-1 + 0j, + expected=-4.845809986595704e-06 + 0j, + rtol=1e-15 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=221.5, + b=90.2, + c=132.3, + z=-1 + 0j, + expected=2.0490488728377282e-42 + 0j, + rtol=1e-7, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-102.1, + b=-20.3, + c=-80.8, + z=-1 + 0j, + expected=45143784.46783885 + 0j, + rtol=1e-7, + ), + marks=pytest.mark.xfail( + condition=sys.maxsize < 2**32, + reason="Fails on 32 bit.", + ) + ), + ], + ) + def test_special_case_z_near_minus_1(self, hyp2f1_test_case): + """Tests for case z ~ -1, c ~ 1 + a - b + + Expected answers computed using mpmath. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15 + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-4, + b=2.02764642551431, + c=1.0561196186065624, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.0031961077109535375-0.0011313924606557173j), + rtol=1e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-8, + b=-7.937789122896016, + c=-15.964218273004214, + z=(2-0.10526315789473695j), + expected=(0.005543763196412503-0.0025948879065698306j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-8, + b=8.095813935368371, + c=4.0013768449590685, + z=(0.9473684210526314-0.10526315789473695j), + expected=(-0.0003054674127221263-9.261359291755414e-05j), + rtol=1e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-4, + b=-3.956227226099288, + c=-3.9316537064827854, + z=(1.1578947368421053-0.3157894736842106j), + expected=(-0.0020809502580892937-0.0041877333232365095j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-4, + c=2.050308316530781, + z=(0.9473684210526314-0.10526315789473695j), + expected=(0.0011282435590058734+0.0002027062303465851j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-8, + c=-15.964218273004214, + z=(1.3684210526315788+0.10526315789473673j), + expected=(-9.134907719238265e-05-0.00040219233987390723j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-4, + c=4.0013768449590685, + z=(0.9473684210526314-0.10526315789473695j), + expected=(-0.000519013062087489-0.0005855883076830948j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-10000, + b=2.2, + c=93459345.3, + z=(2+2j), + expected=(0.9995292071559088-0.00047047067522659253j), + rtol=1e-12, + ), + ), + ] + ) + def test_a_b_negative_int(self, hyp2f1_test_case): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert a == int(a) and a < 0 or b == int(b) and b < 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-0.9629749245209605, + c=-15.5, + z=(1.1578947368421053-1.1578947368421053j), + expected=(0.9778506962676361+0.044083801141231616j), + rtol=3e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-3.9316537064827854, + c=1.5, + z=(0.9473684210526314-0.10526315789473695j), + expected=(4.0793167523167675-10.11694246310966j), + rtol=6e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-0.9629749245209605, + c=2.5, + z=(1.1578947368421053-0.10526315789473695j), + expected=(-2.9692999501916915+0.6394599899845594j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-0.9629749245209605, + c=-15.5, + z=(1.5789473684210522-1.1578947368421053j), + expected=(0.9493076367106102-0.04316852977183447j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.5, + c=-15.5, + z=(0.5263157894736841+0.10526315789473673j), + expected=(0.9844377175631795-0.003120587561483841j), + rtol=1e-10, + ), + ), + ], + ) + def test_a_b_neg_int_after_euler_hypergeometric_transformation( + self, hyp2f1_test_case + ): + a, b, c, z, expected, rtol = hyp2f1_test_case + assert ( # Tests the test + (abs(c - a - int(c - a)) < 1e-15 and c - a < 0) or + (abs(c - b - int(c - b)) < 1e-15 and c - b < 0) + ) + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.10526315789473673-0.3157894736842106j), + expected=(0.9941449585778349+0.01756335047931358j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.5263157894736841+0.5263157894736841j), + expected=(1.0388722293372104-0.09549450380041416j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.0561196186065624, + c=-7.93846038215665, + z=(0.10526315789473673+0.7368421052631575j), + expected=(2.1948378809826434+24.934157235172222j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=16.088264119063613, + c=8.031683612216888, + z=(0.3157894736842106-0.736842105263158j), + expected=(-0.4075277891264672-0.06819344579666956j), + rtol=2e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=2.050308316530781, + c=8.031683612216888, + z=(0.7368421052631575-0.10526315789473695j), + expected=(2.833535530740603-0.6925373701408158j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=4.078873014294075, + z=(0.10526315789473673-0.3157894736842106j), + expected=(1.005347176329683-0.3580736009337313j), + rtol=5e-16, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-15.963511401609862, + z=(0.3157894736842106-0.5263157894736843j), + expected=(0.9824353641135369+0.029271018868990268j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-0.9629749245209605, + c=-159.63511401609862, + z=(0.3157894736842106-0.5263157894736843j), + expected=(0.9982436200365834+0.002927268199671111j), + rtol=1e-7, + ), + marks=pytest.mark.xfail(reason="Poor convergence.") + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=16.088264119063613, + c=8.031683612216888, + z=(0.5263157894736841-0.5263157894736843j), + expected=(-0.6906825165778091+0.8176575137504892j), + rtol=5e-13, + ), + ), + ] + ) + def test_region1(self, hyp2f1_test_case): + """|z| < 0.9 and real(z) >= 0.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(z) < 0.9 and z.real >= 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.0561196186065624, + c=4.078873014294075, + z=(-0.3157894736842106+0.7368421052631575j), + expected=(0.7751915029081136+0.24068493258607315j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=16.088264119063613, + c=2.0397202577726152, + z=(-0.9473684210526316-0.3157894736842106j), + expected=(6.564549348474962e-07+1.6761570598334562e-06j), + rtol=5e-09, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=2.050308316530781, + c=16.056809865262608, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(0.9862043298997204-0.013293151372712681j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=8.077282662161238, + c=16.056809865262608, + z=(-0.3157894736842106-0.736842105263158j), + expected=(0.16163826638754716-0.41378530376373734j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=-0.906685989801748, + z=(-0.5263157894736843+0.3157894736842106j), + expected=(-6.256871535165936+0.13824973858225484j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=8.077282662161238, + c=-3.9924618758357022, + z=(-0.9473684210526316-0.3157894736842106j), + expected=(75.54672526086316+50.56157041797548j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=8.077282662161238, + c=-1.9631175993998025, + z=(-0.5263157894736843+0.5263157894736841j), + expected=(282.0602536306534-82.31597306936214j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-3.9316537064827854, + c=8.031683612216888, + z=(-0.5263157894736843-0.10526315789473695j), + expected=(5.179603735575851+1.4445374002099813j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-7.949900487447654, + c=1.0651378143226575, + z=(-0.3157894736842106-0.9473684210526316j), + expected=(2317.623517606141-269.51476321010324j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-1.92872979730171, + c=2.0397202577726152, + z=(-0.736842105263158-0.3157894736842106j), + expected=(29.179154096175836+22.126690357535043j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-3.9316537064827854, + c=-15.963511401609862, + z=(-0.736842105263158-0.10526315789473695j), + expected=(0.20820247892032057-0.04763956711248794j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.3157894736842106-0.5263157894736843j), + expected=(-157471.63920142158+991294.0587828817j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-7.949900487447654, + c=-7.93846038215665, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(0.30765349653210194-0.2979706363594157j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=1.0561196186065624, + c=8.031683612216888, + z=(-0.9473684210526316-0.10526315789473695j), + expected=(1.6787607400597109+0.10056620134616838j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.088264119063613, + c=4.078873014294075, + z=(-0.5263157894736843-0.736842105263158j), + expected=(7062.07842506049-12768.77955655703j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.088264119063613, + c=2.0397202577726152, + z=(-0.3157894736842106+0.7368421052631575j), + expected=(54749.216391029935-23078.144720887536j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=1.0561196186065624, + c=-0.906685989801748, + z=(-0.10526315789473695-0.10526315789473695j), + expected=(1.21521766411428-4.449385173946672j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=4.0013768449590685, + c=-1.9631175993998025, + z=(-0.736842105263158+0.5263157894736841j), + expected=(19234693144.196907+1617913967.7294445j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=1.0561196186065624, + c=-15.963511401609862, + z=(-0.5263157894736843+0.3157894736842106j), + expected=(0.9345201094534371+0.03745712558992195j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(-0.10526315789473695+0.10526315789473673j), + expected=(0.605732446296829+0.398171533680972j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-15.964218273004214, + c=2.0397202577726152, + z=(-0.10526315789473695-0.5263157894736843j), + expected=(-9.753761888305416-4.590126012666959j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-1.92872979730171, + c=2.0397202577726152, + z=(-0.10526315789473695+0.3157894736842106j), + expected=(0.45587226291120714+1.0694545265819797j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=-0.906685989801748, + z=(-0.736842105263158+0.3157894736842106j), + expected=(12.334808243233418-76.26089051819054j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=-15.963511401609862, + z=(-0.5263157894736843+0.10526315789473673j), + expected=(1.2396019687632678-0.047507973161146286j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-0.9629749245209605, + c=-0.906685989801748, + z=(-0.3157894736842106-0.5263157894736843j), + expected=(97.7889554372208-18.999754543400016j), + rtol=5e-13, + ), + ), + ] + ) + def test_region2(self, hyp2f1_test_case): + """|z| < 1 and real(z) < 0.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert abs(z) < 1 and z.real < 0 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=4.25, + c=2.5, + z=(0.4931034482758623-0.7965517241379311j), + expected=(38.41207903409937-30.510151276075792j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.0, + b=16.087593263474208, + c=16.088264119063613, + z=(0.5689655172413794-0.7965517241379311j), + expected=(-0.6667857912761286-1.0206224321443573j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.0, + b=1.0272592605282642, + c=-7.949900487447654, + z=(0.4931034482758623-0.7965517241379311j), + expected=(1679024.1647997478-2748129.775857212j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=16.0, + c=-7.949900487447654, + z=(0.4931034482758623-0.7965517241379311j), + expected=(424747226301.16986-1245539049327.2856j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-15.964218273004214, + c=4.0, + z=(0.4931034482758623-0.7965517241379311j), + expected=(-0.0057826199201757595+0.026359861999025885j), + rtol=5e-06, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.5689655172413794-0.7965517241379311j), + expected=(0.4671901063492606+0.7769632229834897j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.0, + b=-3.956227226099288, + c=-7.949900487447654, + z=(0.4931034482758623+0.7965517241379312j), + expected=(0.9422283708145973+1.3476905754773343j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0, + b=-15.980848054962111, + c=-15.964218273004214, + z=(0.4931034482758623-0.7965517241379311j), + expected=(0.4168719497319604-0.9770953555235625j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=16.088264119063613, + c=2.5, + z=(0.5689655172413794+0.7965517241379312j), + expected=(1.279096377550619-2.173827694297929j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=4.0013768449590685, + c=2.0397202577726152, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-2.071520656161738-0.7846098268395909j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=8.0, + c=-0.9629749245209605, + z=(0.5689655172413794-0.7965517241379311j), + expected=(-7.740015495862889+3.386766435696699j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.088264119063613, + c=-7.93846038215665, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-6318.553685853241-7133.416085202879j), + rtol=1e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-3.9316537064827854, + c=16.056809865262608, + z=(0.5689655172413794+0.7965517241379312j), + expected=(-0.8854577905547399+8.135089099967278j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-0.9629749245209605, + c=4.078873014294075, + z=(0.4931034482758623+0.7965517241379312j), + expected=(1.224291301521487+0.36014711766402485j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-0.75, + c=-1.5, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-1.5765685855028473-3.9399766961046323j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=-1.92872979730171, + c=-7.93846038215665, + z=(0.5689655172413794-0.7965517241379311j), + expected=(56.794588688231194+4.556286783533971j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=4.5, + c=2.050308316530781, + z=(0.5689655172413794+0.7965517241379312j), + expected=(-4.251456563455306+6.737837111569671j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=8.5, + c=-1.92872979730171, + z=(0.4931034482758623-0.7965517241379311j), + expected=(2177143.9156599627-3313617.2748088865j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-1.5, + c=4.0013768449590685, + z=(0.4931034482758623-0.7965517241379311j), + expected=(0.45563554481603946+0.6212000158060831j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.5, + c=-15.964218273004214, + z=(0.4931034482758623+0.7965517241379312j), + expected=(61.03201617828073-37.185626416756214j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=16.5, + c=4.0013768449590685, + z=(0.4931034482758623+0.7965517241379312j), + expected=(-33143.425963520735+20790.608514722644j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=4.5, + c=-0.9629749245209605, + z=(0.5689655172413794+0.7965517241379312j), + expected=(30.778600270824423-26.65160354466787j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-3.5, + c=16.088264119063613, + z=(0.5689655172413794-0.7965517241379311j), + expected=(1.0629792615560487-0.08308454486044772j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=-7.5, + c=-0.9629749245209605, + z=(0.4931034482758623-0.7965517241379311j), + expected=(17431.571802591767+3553.7129767034507j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.25, + b=8.25, + c=16.5, + z=(0.11379310344827598+0.9482758620689657j), + expected=(0.4468600750211926+0.7313214934036885j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=16.25, + c=4.5, + z=(0.3413793103448277+0.8724137931034486j), + expected=(-3.905704438293991+3.693347860329299j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=4.25, + c=-0.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-40.31777941834244-89.89852492432011j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=8.0, + c=-15.964218273004214, + z=(0.11379310344827598-0.9482758620689655j), + expected=(52584.347773055284-109197.86244309516j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-15.964218273004214, + c=16.056809865262608, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-1.187733570412592-1.5147865053584582j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.9316537064827854, + c=1.0651378143226575, + z=(0.26551724137931054+0.9482758620689657j), + expected=(13.077494677898947+35.071599628224966j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.5, + c=-3.5, + z=(0.26551724137931054+0.8724137931034486j), + expected=(-0.5359656237994614-0.2344483936591811j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.25, + b=-3.75, + c=-1.5, + z=(0.26551724137931054+0.9482758620689657j), + expected=(1204.8114871663133+64.41022826840198j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.0, + c=4.0013768449590685, + z=(0.03793103448275881-0.9482758620689655j), + expected=(-9.85268872413994+7.011107558429154j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=16.0, + c=4.0013768449590685, + z=(0.3413793103448277-0.8724137931034484j), + expected=(528.5522951158454-1412.21630264791j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=1.0561196186065624, + c=-7.5, + z=(0.4172413793103451+0.8724137931034486j), + expected=(133306.45260685298+256510.7045225382j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=8.077282662161238, + c=-15.963511401609862, + z=(0.3413793103448277-0.8724137931034484j), + expected=(-0.998555715276967+2.774198742229889j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.75, + b=-0.75, + c=1.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(2.072445019723025-2.9793504811373515j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.92872979730171, + c=1.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-41.87581944176649-32.52980303527139j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-15.75, + c=-0.5, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-3729.6214864209774-30627.510509112635j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-0.906685989801748, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-131615.07820609974+145596.13384245415j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=16.5, + c=16.088264119063613, + z=(0.26551724137931054+0.8724137931034486j), + expected=(0.18981844071070744+0.7855036242583742j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.5, + b=8.5, + c=-3.9316537064827854, + z=(0.11379310344827598-0.9482758620689655j), + expected=(110224529.2376068+128287212.04290268j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-7.5, + c=4.0013768449590685, + z=(0.3413793103448277-0.8724137931034484j), + expected=(0.2722302180888523-0.21790187837266162j), + rtol=1e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.5, + c=-15.964218273004214, + z=(0.11379310344827598-0.9482758620689655j), + expected=(-2.8252338010989035+2.430661949756161j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=16.5, + c=4.0013768449590685, + z=(0.03793103448275881+0.9482758620689657j), + expected=(-20.604894257647945+74.5109432558078j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=8.5, + c=-0.9629749245209605, + z=(0.3413793103448277+0.8724137931034486j), + expected=(-2764422.521269463-3965966.9965808876j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.5, + b=-0.5, + c=1.0561196186065624, + z=(0.26551724137931054+0.9482758620689657j), + expected=(1.2262338560994905+0.6545051266925549j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.5, + b=-15.5, + c=-7.949900487447654, + z=(0.4172413793103451-0.8724137931034484j), + expected=(-2258.1590330318213+8860.193389158803j), + rtol=1.4e-10, + ), + ), + ] + ) + def test_region4(self, hyp2f1_test_case): + """0.9 <= |z| <= 1 and |1 - z| >= 1. + + This region is unhandled by of the standard transformations and + needs special care. + """ + a, b, c, z, expected, rtol = hyp2f1_test_case + assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9 # Tests the test + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=16.088264119063613, + c=8.5, + z=(0.6448275862068968+0.8724137931034486j), + expected=(0.018601324701770394-0.07618420586062377j), + rtol=5e-08, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.25, + b=4.25, + c=4.5, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-1.391549471425551-0.118036604903893j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=2.050308316530781, + c=-1.9631175993998025, + z=(0.6448275862068968+0.8724137931034486j), + expected=(-2309.178768155151-1932.7247727595172j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=1.0, + c=-15.964218273004214, + z=(0.6448275862068968+0.8724137931034486j), + expected=(85592537010.05054-8061416766688.324j), + rtol=2e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-0.5, + c=1.5, + z=(0.6448275862068968+0.8724137931034486j), + expected=(1.2334498208515172-2.1639498536219732j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-15.964218273004214, + c=4.0, + z=(0.6448275862068968+0.8724137931034486j), + expected=(102266.35398605966-44976.97828737755j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=4.0, + b=-3.956227226099288, + c=-15.964218273004214, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-2.9590030930007236-4.190770764773225j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-15.5, + c=-7.5, + z=(0.5689655172413794-0.8724137931034484j), + expected=(-112554838.92074208+174941462.9202412j), + rtol=5e-05, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=2.050308316530781, + c=1.0, + z=(0.6448275862068968-0.8724137931034484j), + expected=(3.7519882374080145+7.360753798667486j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=2.050308316530781, + c=4.0, + z=(0.6448275862068968-0.8724137931034484j), + expected=(0.000181132943964693+0.07742903103815582j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=4.0013768449590685, + c=-1.9631175993998025, + z=(0.5689655172413794+0.8724137931034486j), + expected=(386338.760913596-386166.51762171905j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.980848054962111, + b=8.0, + c=-1.92872979730171, + z=(0.6448275862068968+0.8724137931034486j), + expected=(1348667126.3444858-2375132427.158893j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=-0.9629749245209605, + c=4.5, + z=(0.5689655172413794+0.8724137931034486j), + expected=(1.428353429538678+0.6472718120804372j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.5689655172413794-0.8724137931034484j), + expected=(3.1439267526119643-3.145305240375117j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=-15.964218273004214, + c=-7.93846038215665, + z=(0.6448275862068968-0.8724137931034484j), + expected=(75.27467675681773+144.0946946292215j), + rtol=1e-07, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.75, + b=-7.75, + c=-7.5, + z=(0.5689655172413794+0.8724137931034486j), + expected=(-0.3699450626264222+0.8732812475910993j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=16.5, + c=1.0561196186065624, + z=(0.5689655172413794-0.8724137931034484j), + expected=(5.5361025821300665-2.4709693474656285j), + rtol=5e-09, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=8.5, + c=-3.9316537064827854, + z=(0.6448275862068968-0.8724137931034484j), + expected=(-782805.6699207705-537192.581278909j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=-15.5, + c=1.0561196186065624, + z=(0.6448275862068968+0.8724137931034486j), + expected=(12.345113400639693-14.993248992902007j), + rtol=0.0005, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=-0.5, + c=-15.964218273004214, + z=(0.6448275862068968+0.8724137931034486j), + expected=(23.698109392667842+97.15002033534108j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=16.5, + c=4.0013768449590685, + z=(0.6448275862068968-0.8724137931034484j), + expected=(1115.2978631811834+915.9212658718577j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=16.5, + c=-0.9629749245209605, + z=(0.6448275862068968+0.8724137931034486j), + expected=(642077722221.6489+535274495398.21027j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=-3.5, + c=4.0013768449590685, + z=(0.5689655172413794+0.8724137931034486j), + expected=(-5.689219222945697+16.877463062787143j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.5, + c=-0.9629749245209605, + z=(0.5689655172413794-0.8724137931034484j), + expected=(-44.32070290703576+1026.9127058617403j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=2.25, + c=4.5, + z=(0.11379310344827598-1.024137931034483j), + expected=(-0.021965227124574663+0.009908300237809064j), + rtol=1e-3, + ), + marks=pytest.mark.xfail( + reason="Unhandled parameters." + ) + ), + pytest.param( + Hyp2f1TestCase( + a=2.02764642551431, + b=1.5, + c=16.5, + z=(0.26551724137931054+1.024137931034483j), + expected=(1.0046072901244183+0.19945500134119992j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=1.0, + c=-3.9316537064827854, + z=(0.3413793103448277+0.9482758620689657j), + expected=(21022.30133421465+49175.98317370489j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=16.088264119063613, + c=-1.9631175993998025, + z=(0.4172413793103451-0.9482758620689655j), + expected=(-7024239.358547302+2481375.02681063j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-15.75, + c=1.5, + z=(0.18965517241379315+1.024137931034483j), + expected=(92371704.94848-403546832.548352j), + rtol=5e-06, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.5, + b=-7.949900487447654, + c=8.5, + z=(0.26551724137931054-1.024137931034483j), + expected=(1.9335109845308265+5.986542524829654j), + rtol=5e-10, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-1.92872979730171, + c=-7.93846038215665, + z=(0.4931034482758623+0.8724137931034486j), + expected=(-122.52639696039328-59.72428067512221j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.25, + b=-1.75, + c=-1.5, + z=(0.4931034482758623+0.9482758620689657j), + expected=(-90.40642053579428+50.50649180047921j), + rtol=5e-08, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.5, + b=8.077282662161238, + c=16.5, + z=(0.4931034482758623+0.9482758620689657j), + expected=(-0.2155745818150323-0.564628986876639j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=1.0561196186065624, + c=8.031683612216888, + z=(0.4172413793103451-0.9482758620689655j), + expected=(0.9503140488280465+0.11574960074292677j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.75, + b=2.25, + c=-15.5, + z=(0.4172413793103451+0.9482758620689657j), + expected=(0.9285862488442175+0.8203699266719692j), + rtol=5e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.75, + b=4.25, + c=-15.5, + z=(0.3413793103448277-0.9482758620689655j), + expected=(-1.0509834850116921-1.1145522325486075j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-0.9629749245209605, + c=2.0397202577726152, + z=(0.4931034482758623-0.9482758620689655j), + expected=(2.88119116536769-3.4249933450696806j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-15.964218273004214, + c=16.5, + z=(0.18965517241379315+1.024137931034483j), + expected=(199.65868451496038+347.79384207302877j), + rtol=1e-13, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.75, + b=-15.75, + c=-3.5, + z=(0.4931034482758623-0.8724137931034484j), + expected=(-208138312553.07013+58631611809.026955j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-15.5, + c=-7.5, + z=(0.3413793103448277+0.9482758620689657j), + expected=(-23032.90519856288-18256.94050457296j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=1.5, + c=1.0561196186065624, + z=(0.4931034482758623-0.8724137931034484j), + expected=(1.507342459587056+1.2332023580148403j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=2.5, + b=4.5, + c=-3.9316537064827854, + z=(0.4172413793103451+0.9482758620689657j), + expected=(7044.766127108853-40210.365567285575j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.5, + b=-1.5, + c=1.0561196186065624, + z=(0.03793103448275881+1.024137931034483j), + expected=(0.2725347741628333-2.247314875514784j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.5, + b=-1.5, + c=-7.949900487447654, + z=(0.26551724137931054+1.024137931034483j), + expected=(-11.250200011017546+12.597393659160472j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=8.5, + c=16.088264119063613, + z=(0.26551724137931054+1.024137931034483j), + expected=(-0.18515160890991517+0.7959014164484782j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.5, + b=16.5, + c=-3.9316537064827854, + z=(0.3413793103448277-1.024137931034483j), + expected=(998246378.8556538+1112032928.103645j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.5, + b=-3.5, + c=2.050308316530781, + z=(0.03793103448275881+1.024137931034483j), + expected=(0.5527670397711952+2.697662715303637j), + rtol=1.2e-15, # rtol bumped from 1e-15 in gh18414 + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-15.5, + b=-1.5, + c=-0.9629749245209605, + z=(0.4931034482758623-0.8724137931034484j), + expected=(55.396931662136886+968.467463806326j), + rtol=5e-14, + ), + ), + ] + ) + def test_region5(self, hyp2f1_test_case): + """1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0 + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.parametrize( + "hyp2f1_test_case", + [ + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=4.0013768449590685, + c=4.078873014294075, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(-0.0018093573941378783+0.003481887377423739j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=2.050308316530781, + c=1.0651378143226575, + z=(-0.736842105263158-0.736842105263158j), + expected=(-0.00023401243818780545-1.7983496305603562e-05j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=8.077282662161238, + c=4.078873014294075, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(0.22359773002226846-0.24092487123993353j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=2.050308316530781, + c=-15.963511401609862, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(1.191573745740011+0.14347394589721466j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=4.0013768449590685, + c=-15.963511401609862, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(31.822620756901784-66.09094396747611j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=8.077282662161238, + c=-7.93846038215665, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(207.16750179245952+34.80478274924269j), + rtol=5e-12, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=8.095813935368371, + b=-7.949900487447654, + c=8.031683612216888, + z=(-0.736842105263158+0.7368421052631575j), + expected=(-159.62429364277145+9.154224290644898j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-1.92872979730171, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1.121122351247184-0.07170260470126685j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=16.087593263474208, + b=-0.9629749245209605, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1.9040596681316053-0.4951799449960107j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-1.92872979730171, + c=-0.906685989801748, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-14.496623497780739-21.897524523299875j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=4.080187217753502, + b=-3.9316537064827854, + c=-3.9924618758357022, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(36.33473466026878+253.88728442029577j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=1.0272592605282642, + b=-15.964218273004214, + c=-0.906685989801748, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(1505052.5653144997-50820766.81043443j), + rtol=1e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=4.0013768449590685, + c=1.0651378143226575, + z=(-0.5263157894736843+0.9473684210526314j), + expected=(-127.79407519260877-28.69899444941112j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=8.077282662161238, + c=16.056809865262608, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(2.0623331933754976+0.741234463565458j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=8.077282662161238, + c=2.0397202577726152, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(30.729193458862525-292.5700835046965j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=1.0561196186065624, + c=-1.9631175993998025, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(1.1285917906203495-0.735264575450189j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=1.0561196186065624, + c=-3.9924618758357022, + z=(-0.736842105263158+0.7368421052631575j), + expected=(0.6356474446678052-0.02429663008952248j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-1.9214641416286231, + b=16.088264119063613, + c=-7.93846038215665, + z=(-0.736842105263158+0.7368421052631575j), + expected=(0.4718880510273174+0.655083067736377j), + rtol=1e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-7.937789122896016, + b=-3.9316537064827854, + c=16.056809865262608, + z=(-0.9473684210526316+0.5263157894736841j), + expected=(-0.14681550942352714+0.16092206364265146j), + rtol=5e-11, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-15.964218273004214, + c=1.0651378143226575, + z=(-0.5263157894736843+0.9473684210526314j), + expected=(-6.436835190526225+22.883156700606182j), + rtol=5e-14, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-0.9220024191881196, + b=-7.949900487447654, + c=4.078873014294075, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-0.7505682955068583-1.1026583264249945j), + rtol=1e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-3.9316537064827854, + c=-7.93846038215665, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(3.6247814989198166+2.596041360148318j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.5263157894736843-0.9473684210526316j), + expected=(-59537.65287927933-669074.4342539902j), + rtol=5e-15, + ), + ), + pytest.param( + Hyp2f1TestCase( + a=-3.956227226099288, + b=-15.964218273004214, + c=-1.9631175993998025, + z=(-0.9473684210526316-0.5263157894736843j), + expected=(-433084.9970266166+431088.393918521j), + rtol=5e-14, + ), + ), + ] + ) + def test_region6(self, hyp2f1_test_case): + """|z| > 1 but not in region 5.""" + a, b, c, z, expected, rtol = hyp2f1_test_case + assert ( + abs(z) > 1 and + not (1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0) + ) + assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol) + + @pytest.mark.slow + @check_version(mpmath, "1.0.0") + def test_test_hyp2f1(self): + """Test that expected values match what is computed by mpmath. + + This gathers the parameters for the test cases out of the pytest marks. + The parameters are a, b, c, z, expected, rtol, where expected should + be the value of hyp2f1(a, b, c, z) computed with mpmath. The test + recomputes hyp2f1(a, b, c, z) using mpmath and verifies that expected + actually is the correct value. This allows the data for the tests to + live within the test code instead of an external datafile, while + avoiding having to compute the results with mpmath during the test, + except for when slow tests are being run. + """ + test_methods = [ + test_method for test_method in dir(self) + if test_method.startswith('test') and + # Filter properties and attributes (futureproofing). + callable(getattr(self, test_method)) and + # Filter out this test + test_method != 'test_test_hyp2f1' + ] + for test_method in test_methods: + params = self._get_test_parameters(getattr(self, test_method)) + for a, b, c, z, expected, _ in params: + assert_allclose(mp_hyp2f1(a, b, c, z), expected, rtol=2.25e-16) + + def _get_test_parameters(self, test_method): + """Get pytest.mark parameters for a test in this class.""" + return [ + case.values[0] for mark in test_method.pytestmark + if mark.name == 'parametrize' + for case in mark.args[1] + ] diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py new file mode 100644 index 0000000000000000000000000000000000000000..749a7e357417667d72d4295678d70830f6b93eb1 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py @@ -0,0 +1,140 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import scipy.special as sc + + +class TestHyperu: + + def test_negative_x(self): + a, b, x = np.meshgrid( + [-1, -0.5, 0, 0.5, 1], + [-1, -0.5, 0, 0.5, 1], + np.linspace(-100, -1, 10), + ) + assert np.all(np.isnan(sc.hyperu(a, b, x))) + + def test_special_cases(self): + assert sc.hyperu(0, 1, 1) == 1.0 + + @pytest.mark.parametrize('a', [0.5, 1, np.nan]) + @pytest.mark.parametrize('b', [1, 2, np.nan]) + @pytest.mark.parametrize('x', [0.25, 3, np.nan]) + def test_nan_inputs(self, a, b, x): + assert np.isnan(sc.hyperu(a, b, x)) == np.any(np.isnan([a, b, x])) + + +class TestHyp1f1: + + @pytest.mark.parametrize('a, b, x', [ + (np.nan, 1, 1), + (1, np.nan, 1), + (1, 1, np.nan) + ]) + def test_nan_inputs(self, a, b, x): + assert np.isnan(sc.hyp1f1(a, b, x)) + + def test_poles(self): + assert_equal(sc.hyp1f1(1, [0, -1, -2, -3, -4], 0.5), np.inf) + + @pytest.mark.parametrize('a, b, x, result', [ + (-1, 1, 0.5, 0.5), + (1, 1, 0.5, 1.6487212707001281468), + (2, 1, 0.5, 2.4730819060501922203), + (1, 2, 0.5, 1.2974425414002562937), + (-10, 1, 0.5, -0.38937441413785204475) + ]) + def test_special_cases(self, a, b, x, result): + # Hit all the special case branches at the beginning of the + # function. Desired answers computed using Mpmath. + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15) + + @pytest.mark.parametrize('a, b, x, result', [ + (1, 1, 0.44, 1.5527072185113360455), + (-1, 1, 0.44, 0.55999999999999999778), + (100, 100, 0.89, 2.4351296512898745592), + (-100, 100, 0.89, 0.40739062490768104667), + (1.5, 100, 59.99, 3.8073513625965598107), + (-1.5, 100, 59.99, 0.25099240047125826943) + ]) + def test_geometric_convergence(self, a, b, x, result): + # Test the region where we are relying on the ratio of + # + # (|a| + 1) * |x| / |b| + # + # being small. Desired answers computed using Mpmath + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15) + + @pytest.mark.parametrize('a, b, x, result', [ + (-1, 1, 1.5, -0.5), + (-10, 1, 1.5, 0.41801777430943080357), + (-25, 1, 1.5, 0.25114491646037839809), + (-50, 1, 1.5, -0.25683643975194756115), + (-80, 1, 1.5, -0.24554329325751503601), + (-150, 1, 1.5, -0.173364795515420454496), + ]) + def test_a_negative_integer(self, a, b, x, result): + # Desired answers computed using Mpmath. + assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=2e-14) + + @pytest.mark.parametrize('a, b, x, expected', [ + (0.01, 150, -4, 0.99973683897677527773), # gh-3492 + (1, 5, 0.01, 1.0020033381011970966), # gh-3593 + (50, 100, 0.01, 1.0050126452421463411), # gh-3593 + (1, 0.3, -1e3, -7.011932249442947651455e-04), # gh-14149 + (1, 0.3, -1e4, -7.001190321418937164734e-05), # gh-14149 + (9, 8.5, -350, -5.224090831922378361082e-20), # gh-17120 + (9, 8.5, -355, -4.595407159813368193322e-20), # gh-17120 + (75, -123.5, 15, 3.425753920814889017493e+06), + ]) + def test_assorted_cases(self, a, b, x, expected): + # Expected values were computed with mpmath.hyp1f1(a, b, x). + assert_allclose(sc.hyp1f1(a, b, x), expected, atol=0, rtol=1e-14) + + def test_a_neg_int_and_b_equal_x(self): + # This is a case where the Boost wrapper will call hypergeometric_pFq + # instead of hypergeometric_1F1. When we use a version of Boost in + # which https://github.com/boostorg/math/issues/833 is fixed, this + # test case can probably be moved into test_assorted_cases. + # The expected value was computed with mpmath.hyp1f1(a, b, x). + a = -10.0 + b = 2.5 + x = 2.5 + expected = 0.0365323664364104338721 + computed = sc.hyp1f1(a, b, x) + assert_allclose(computed, expected, atol=0, rtol=1e-13) + + @pytest.mark.parametrize('a, b, x, desired', [ + (-1, -2, 2, 2), + (-1, -4, 10, 3.5), + (-2, -2, 1, 2.5) + ]) + def test_gh_11099(self, a, b, x, desired): + # All desired results computed using Mpmath + assert sc.hyp1f1(a, b, x) == desired + + @pytest.mark.parametrize('a', [-3, -2]) + def test_x_zero_a_and_b_neg_ints_and_a_ge_b(self, a): + assert sc.hyp1f1(a, -3, 0) == 1 + + # The "legacy edge cases" mentioned in the comments in the following + # tests refers to the behavior of hyp1f1(a, b, x) when b is a nonpositive + # integer. In some subcases, the behavior of SciPy does not match that + # of Boost (1.81+), mpmath and Mathematica (via Wolfram Alpha online). + # If the handling of these edges cases is changed to agree with those + # libraries, these test will have to be updated. + + @pytest.mark.parametrize('b', [0, -1, -5]) + def test_legacy_case1(self, b): + # Test results of hyp1f1(0, n, x) for n <= 0. + # This is a legacy edge case. + # Boost (versions greater than 1.80), Mathematica (via Wolfram Alpha + # online) and mpmath all return 1 in this case, but SciPy's hyp1f1 + # returns inf. + assert_equal(sc.hyp1f1(0, b, [-1.5, 0, 1.5]), [np.inf, np.inf, np.inf]) + + def test_legacy_case2(self): + # This is a legacy edge case. + # In software such as boost (1.81+), mpmath and Mathematica, + # the value is 1. + assert sc.hyp1f1(-4, -3, 0) == np.inf diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py new file mode 100644 index 0000000000000000000000000000000000000000..bc427b0584ab87307c50ffb120fb8bc66a26df5a --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py @@ -0,0 +1,495 @@ +import itertools +import sys +import pytest + +import numpy as np +from numpy.testing import assert_ +from scipy.special._testutils import FuncData + +from scipy.special import kolmogorov, kolmogi, smirnov, smirnovi +from scipy.special._ufuncs import (_kolmogc, _kolmogci, _kolmogp, + _smirnovc, _smirnovci, _smirnovp) + +_rtol = 1e-10 + +class TestSmirnov: + def test_nan(self): + assert_(np.isnan(smirnov(1, np.nan))) + + def test_basic(self): + dataset = [(1, 0.1, 0.9), + (1, 0.875, 0.125), + (2, 0.875, 0.125 * 0.125), + (3, 0.875, 0.125 * 0.125 * 0.125)] + + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0(self): + dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_1(self): + dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0point5(self): + dataset = [(1, 0.5, 0.5), + (2, 0.5, 0.25), + (3, 0.5, 0.166666666667), + (4, 0.5, 0.09375), + (5, 0.5, 0.056), + (6, 0.5, 0.0327932098765), + (7, 0.5, 0.0191958707681), + (8, 0.5, 0.0112953186035), + (9, 0.5, 0.00661933257355), + (10, 0.5, 0.003888705)] + + dataset = np.asarray(dataset) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_1(self): + x = np.linspace(0, 1, 101, endpoint=True) + dataset = np.column_stack([[1]*len(x), x, 1-x]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_2(self): + x = np.linspace(0.5, 1, 101, endpoint=True) + p = np.power(1-x, 2) + n = np.array([2] * len(x)) + dataset = np.column_stack([n, x, p]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_3(self): + x = np.linspace(0.7, 1, 31, endpoint=True) + p = np.power(1-x, 3) + n = np.array([3] * len(x)) + dataset = np.column_stack([n, x, p]) + FuncData( + smirnov, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, -1] = 1 - dataset[:, -1] + FuncData( + _smirnovc, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_large(self): + # test for large values of n + # Probabilities should go down as n goes up + x = 0.4 + pvals = np.array([smirnov(n, x) for n in range(400, 1100, 20)]) + dfs = np.diff(pvals) + assert_(np.all(dfs <= 0), msg='Not all diffs negative %s' % dfs) + + +class TestSmirnovi: + def test_nan(self): + assert_(np.isnan(smirnovi(1, np.nan))) + + def test_basic(self): + dataset = [(1, 0.4, 0.6), + (1, 0.6, 0.4), + (1, 0.99, 0.01), + (1, 0.01, 0.99), + (2, 0.125 * 0.125, 0.875), + (3, 0.125 * 0.125 * 0.125, 0.875), + (10, 1.0 / 16 ** 10, 1 - 1.0 / 16)] + + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0(self): + dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_1(self): + dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))] + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_1(self): + pp = np.linspace(0, 1, 101, endpoint=True) + # dataset = np.array([(1, p, 1-p) for p in pp]) + dataset = np.column_stack([[1]*len(pp), pp, 1-pp]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_2(self): + x = np.linspace(0.5, 1, 101, endpoint=True) + p = np.power(1-x, 2) + n = np.array([2] * len(x)) + dataset = np.column_stack([n, p, x]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_n_equals_3(self): + x = np.linspace(0.7, 1, 31, endpoint=True) + p = np.power(1-x, 3) + n = np.array([3] * len(x)) + dataset = np.column_stack([n, p, x]) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_round_trip(self): + def _sm_smi(n, p): + return smirnov(n, smirnovi(n, p)) + + def _smc_smci(n, p): + return _smirnovc(n, _smirnovci(n, p)) + + dataset = [(1, 0.4, 0.4), + (1, 0.6, 0.6), + (2, 0.875, 0.875), + (3, 0.875, 0.875), + (3, 0.125, 0.125), + (10, 0.999, 0.999), + (10, 0.0001, 0.0001)] + + dataset = np.asarray(dataset) + FuncData( + _sm_smi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + FuncData( + _smc_smci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_x_equals_0point5(self): + dataset = [(1, 0.5, 0.5), + (2, 0.5, 0.366025403784), + (2, 0.25, 0.5), + (3, 0.5, 0.297156508177), + (4, 0.5, 0.255520481121), + (5, 0.5, 0.234559536069), + (6, 0.5, 0.21715965898), + (7, 0.5, 0.202722580034), + (8, 0.5, 0.190621765256), + (9, 0.5, 0.180363501362), + (10, 0.5, 0.17157867006)] + + dataset = np.asarray(dataset) + FuncData( + smirnovi, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + dataset[:, 1] = 1 - dataset[:, 1] + FuncData( + _smirnovci, dataset, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + +class TestSmirnovp: + def test_nan(self): + assert_(np.isnan(_smirnovp(1, np.nan))) + + def test_basic(self): + # Check derivative at endpoints + n1_10 = np.arange(1, 10) + dataset0 = np.column_stack([n1_10, + np.full_like(n1_10, 0), + np.full_like(n1_10, -1)]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + n2_10 = np.arange(2, 10) + dataset1 = np.column_stack([n2_10, + np.full_like(n2_10, 1.0), + np.full_like(n2_10, 0)]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneminusoneovern(self): + # Check derivative at x=1-1/n + n = np.arange(1, 20) + x = 1.0/n + xm1 = 1-1.0/n + pp1 = -n * x**(n-1) + pp1 -= (1-np.sign(n-2)**2) * 0.5 # n=2, x=0.5, 1-1/n = 0.5, need to adjust + dataset1 = np.column_stack([n, xm1, pp1]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneovertwon(self): + # Check derivative at x=1/2n (Discontinuous at x=1/n, so check at x=1/2n) + n = np.arange(1, 20) + x = 1.0/2/n + pp = -(n*x+1) * (1+x)**(n-2) + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + def test_oneovern(self): + # Check derivative at x=1/n + # (Discontinuous at x=1/n, hard to tell if x==1/n, only use n=power of 2) + n = 2**np.arange(1, 10) + x = 1.0/n + pp = -(n*x+1) * (1+x)**(n-2) + 0.5 + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + @pytest.mark.xfail(sys.maxsize <= 2**32, + reason="requires 64-bit platform") + def test_oneovernclose(self): + # Check derivative at x=1/n + # (Discontinuous at x=1/n, test on either side: x=1/n +/- 2epsilon) + n = np.arange(3, 20) + + x = 1.0/n - 2*np.finfo(float).eps + pp = -(n*x+1) * (1+x)**(n-2) + dataset0 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset0, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + x = 1.0/n + 2*np.finfo(float).eps + pp = -(n*x+1) * (1+x)**(n-2) + 1 + dataset1 = np.column_stack([n, x, pp]) + FuncData( + _smirnovp, dataset1, (0, 1), 2, rtol=_rtol + ).check(dtypes=[int, float, float]) + + +class TestKolmogorov: + def test_nan(self): + assert_(np.isnan(kolmogorov(np.nan))) + + def test_basic(self): + dataset = [(0, 1.0), + (0.5, 0.96394524366487511), + (0.8275735551899077, 0.5000000000000000), + (1, 0.26999967167735456), + (2, 0.00067092525577969533)] + + dataset = np.asarray(dataset) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + + def test_linspace(self): + x = np.linspace(0, 2.0, 21) + dataset = [1.0000000000000000, 1.0000000000000000, 0.9999999999994950, + 0.9999906941986655, 0.9971923267772983, 0.9639452436648751, + 0.8642827790506042, 0.7112351950296890, 0.5441424115741981, + 0.3927307079406543, 0.2699996716773546, 0.1777181926064012, + 0.1122496666707249, 0.0680922218447664, 0.0396818795381144, + 0.0222179626165251, 0.0119520432391966, 0.0061774306344441, + 0.0030676213475797, 0.0014636048371873, 0.0006709252557797] + + dataset_c = [0.0000000000000000, 6.609305242245699e-53, 5.050407338670114e-13, + 9.305801334566668e-06, 0.0028076732227017, 0.0360547563351249, + 0.1357172209493958, 0.2887648049703110, 0.4558575884258019, + 0.6072692920593457, 0.7300003283226455, 0.8222818073935988, + 0.8877503333292751, 0.9319077781552336, 0.9603181204618857, + 0.9777820373834749, 0.9880479567608034, 0.9938225693655559, + 0.9969323786524203, 0.9985363951628127, 0.9993290747442203] + + dataset = np.column_stack([x, dataset]) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + dataset_c = np.column_stack([x, dataset_c]) + FuncData(_kolmogc, dataset_c, (0,), 1, rtol=_rtol).check() + + def test_linspacei(self): + p = np.linspace(0, 1.0, 21, endpoint=True) + dataset = [np.inf, 1.3580986393225507, 1.2238478702170823, + 1.1379465424937751, 1.0727491749396481, 1.0191847202536859, + 0.9730633753323726, 0.9320695842357622, 0.8947644549851197, + 0.8601710725555463, 0.8275735551899077, 0.7964065373291559, + 0.7661855555617682, 0.7364542888171910, 0.7067326523068980, + 0.6764476915028201, 0.6448126061663567, 0.6105590999244391, + 0.5711732651063401, 0.5196103791686224, 0.0000000000000000] + + dataset_c = [0.0000000000000000, 0.5196103791686225, 0.5711732651063401, + 0.6105590999244391, 0.6448126061663567, 0.6764476915028201, + 0.7067326523068980, 0.7364542888171910, 0.7661855555617682, + 0.7964065373291559, 0.8275735551899077, 0.8601710725555463, + 0.8947644549851196, 0.9320695842357622, 0.9730633753323727, + 1.0191847202536859, 1.0727491749396481, 1.1379465424937754, + 1.2238478702170825, 1.3580986393225509, np.inf] + + dataset = np.column_stack([p[1:], dataset[1:]]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + dataset_c = np.column_stack([p[:-1], dataset_c[:-1]]) + FuncData(_kolmogci, dataset_c, (0,), 1, rtol=_rtol).check() + + def test_smallx(self): + epsilon = 0.1 ** np.arange(1, 14) + x = np.array([0.571173265106, 0.441027698518, 0.374219690278, 0.331392659217, + 0.300820537459, 0.277539353999, 0.259023494805, 0.243829561254, + 0.231063086389, 0.220135543236, 0.210641372041, 0.202290283658, + 0.19487060742]) + + dataset = np.column_stack([x, 1-epsilon]) + FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check() + + def test_round_trip(self): + def _ki_k(_x): + return kolmogi(kolmogorov(_x)) + + def _kci_kc(_x): + return _kolmogci(_kolmogc(_x)) + + x = np.linspace(0.0, 2.0, 21, endpoint=True) + # Exclude 0.1, 0.2. 0.2 almost makes succeeds, but 0.1 has no chance. + x02 = x[(x == 0) | (x > 0.21)] + dataset02 = np.column_stack([x02, x02]) + FuncData(_ki_k, dataset02, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([x, x]) + FuncData(_kci_kc, dataset, (0,), 1, rtol=_rtol).check() + + +class TestKolmogi: + def test_nan(self): + assert_(np.isnan(kolmogi(np.nan))) + + def test_basic(self): + dataset = [(1.0, 0), + (0.96394524366487511, 0.5), + (0.9, 0.571173265106), + (0.5000000000000000, 0.8275735551899077), + (0.26999967167735456, 1), + (0.00067092525577969533, 2)] + + dataset = np.asarray(dataset) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + def test_smallpcdf(self): + epsilon = 0.5 ** np.arange(1, 55, 3) + # kolmogi(1-p) == _kolmogci(p) if 1-(1-p) == p, but not necessarily otherwise + # Use epsilon s.t. 1-(1-epsilon)) == epsilon, + # so can use same x-array for both results + + x = np.array([0.8275735551899077, 0.5345255069097583, 0.4320114038786941, + 0.3736868442620478, 0.3345161714909591, 0.3057833329315859, + 0.2835052890528936, 0.2655578150208676, 0.2506869966107999, + 0.2380971058736669, 0.2272549289962079, 0.2177876361600040, + 0.2094254686862041, 0.2019676748836232, 0.1952612948137504, + 0.1891874239646641, 0.1836520225050326, 0.1785795904846466]) + + dataset = np.column_stack([1-epsilon, x]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([epsilon, x]) + FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check() + + def test_smallpsf(self): + epsilon = 0.5 ** np.arange(1, 55, 3) + # kolmogi(p) == _kolmogci(1-p) if 1-(1-p) == p, but not necessarily otherwise + # Use epsilon s.t. 1-(1-epsilon)) == epsilon, + # so can use same x-array for both results + + x = np.array([0.8275735551899077, 1.3163786275161036, 1.6651092133663343, + 1.9525136345289607, 2.2027324540033235, 2.4272929437460848, + 2.6327688477341593, 2.8233300509220260, 3.0018183401530627, + 3.1702735084088891, 3.3302184446307912, 3.4828258153113318, + 3.6290214150152051, 3.7695513262825959, 3.9050272690877326, + 4.0359582187082550, 4.1627730557884890, 4.2858371743264527]) + + dataset = np.column_stack([epsilon, x]) + FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check() + + dataset = np.column_stack([1-epsilon, x]) + FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check() + + def test_round_trip(self): + def _k_ki(_p): + return kolmogorov(kolmogi(_p)) + + p = np.linspace(0.1, 1.0, 10, endpoint=True) + dataset = np.column_stack([p, p]) + FuncData(_k_ki, dataset, (0,), 1, rtol=_rtol).check() + + +class TestKolmogp: + def test_nan(self): + assert_(np.isnan(_kolmogp(np.nan))) + + def test_basic(self): + dataset = [(0.000000, -0.0), + (0.200000, -1.532420541338916e-10), + (0.400000, -0.1012254419260496), + (0.600000, -1.324123244249925), + (0.800000, -1.627024345636592), + (1.000000, -1.071948558356941), + (1.200000, -0.538512430720529), + (1.400000, -0.2222133182429472), + (1.600000, -0.07649302775520538), + (1.800000, -0.02208687346347873), + (2.000000, -0.005367402045629683)] + + dataset = np.asarray(dataset) + FuncData(_kolmogp, dataset, (0,), 1, rtol=_rtol).check() diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py new file mode 100644 index 0000000000000000000000000000000000000000..c7fde685406661b821bb1dc490ca0da173eb4bd0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py @@ -0,0 +1,109 @@ +# +# Tests for the lambertw function, +# Adapted from the MPMath tests [1] by Yosef Meller, mellerf@netvision.net.il +# Distributed under the same license as SciPy itself. +# +# [1] mpmath source code, Subversion revision 992 +# http://code.google.com/p/mpmath/source/browse/trunk/mpmath/tests/test_functions2.py?spec=svn994&r=992 + +import pytest +import numpy as np +from numpy.testing import assert_, assert_equal, assert_array_almost_equal +from scipy.special import lambertw +from numpy import nan, inf, pi, e, isnan, log, r_, array, complex128 + +from scipy.special._testutils import FuncData + + +def test_values(): + assert_(isnan(lambertw(nan))) + assert_equal(lambertw(inf,1).real, inf) + assert_equal(lambertw(inf,1).imag, 2*pi) + assert_equal(lambertw(-inf,1).real, inf) + assert_equal(lambertw(-inf,1).imag, 3*pi) + + assert_equal(lambertw(1.), lambertw(1., 0)) + + data = [ + (0,0, 0), + (0+0j,0, 0), + (inf,0, inf), + (0,-1, -inf), + (0,1, -inf), + (0,3, -inf), + (e,0, 1), + (1,0, 0.567143290409783873), + (-pi/2,0, 1j*pi/2), + (-log(2)/2,0, -log(2)), + (0.25,0, 0.203888354702240164), + (-0.25,0, -0.357402956181388903), + (-1./10000,0, -0.000100010001500266719), + (-0.25,-1, -2.15329236411034965), + (0.25,-1, -3.00899800997004620-4.07652978899159763j), + (-0.25,-1, -2.15329236411034965), + (0.25,1, -3.00899800997004620+4.07652978899159763j), + (-0.25,1, -3.48973228422959210+7.41405453009603664j), + (-4,0, 0.67881197132094523+1.91195078174339937j), + (-4,1, -0.66743107129800988+7.76827456802783084j), + (-4,-1, 0.67881197132094523-1.91195078174339937j), + (1000,0, 5.24960285240159623), + (1000,1, 4.91492239981054535+5.44652615979447070j), + (1000,-1, 4.91492239981054535-5.44652615979447070j), + (1000,5, 3.5010625305312892+29.9614548941181328j), + (3+4j,0, 1.281561806123775878+0.533095222020971071j), + (-0.4+0.4j,0, -0.10396515323290657+0.61899273315171632j), + (3+4j,1, -0.11691092896595324+5.61888039871282334j), + (3+4j,-1, 0.25856740686699742-3.85211668616143559j), + (-0.5,-1, -0.794023632344689368-0.770111750510379110j), + (-1./10000,1, -11.82350837248724344+6.80546081842002101j), + (-1./10000,-1, -11.6671145325663544), + (-1./10000,-2, -11.82350837248724344-6.80546081842002101j), + (-1./100000,4, -14.9186890769540539+26.1856750178782046j), + (-1./100000,5, -15.0931437726379218666+32.5525721210262290086j), + ((2+1j)/10,0, 0.173704503762911669+0.071781336752835511j), + ((2+1j)/10,1, -3.21746028349820063+4.56175438896292539j), + ((2+1j)/10,-1, -3.03781405002993088-3.53946629633505737j), + ((2+1j)/10,4, -4.6878509692773249+23.8313630697683291j), + (-(2+1j)/10,0, -0.226933772515757933-0.164986470020154580j), + (-(2+1j)/10,1, -2.43569517046110001+0.76974067544756289j), + (-(2+1j)/10,-1, -3.54858738151989450-6.91627921869943589j), + (-(2+1j)/10,4, -4.5500846928118151+20.6672982215434637j), + (pi,0, 1.073658194796149172092178407024821347547745350410314531), + + # Former bug in generated branch, + (-0.5+0.002j,0, -0.78917138132659918344 + 0.76743539379990327749j), + (-0.5-0.002j,0, -0.78917138132659918344 - 0.76743539379990327749j), + (-0.448+0.4j,0, -0.11855133765652382241 + 0.66570534313583423116j), + (-0.448-0.4j,0, -0.11855133765652382241 - 0.66570534313583423116j), + ] + data = array(data, dtype=complex128) + + def w(x, y): + return lambertw(x, y.real.astype(int)) + with np.errstate(all='ignore'): + FuncData(w, data, (0,1), 2, rtol=1e-10, atol=1e-13).check() + + +def test_ufunc(): + assert_array_almost_equal( + lambertw(r_[0., e, 1.]), r_[0., 1., 0.567143290409783873]) + + +def test_lambertw_ufunc_loop_selection(): + # see https://github.com/scipy/scipy/issues/4895 + dt = np.dtype(np.complex128) + assert_equal(lambertw(0, 0, 0).dtype, dt) + assert_equal(lambertw([0], 0, 0).dtype, dt) + assert_equal(lambertw(0, [0], 0).dtype, dt) + assert_equal(lambertw(0, 0, [0]).dtype, dt) + assert_equal(lambertw([0], [0], [0]).dtype, dt) + + +@pytest.mark.parametrize('z', [1e-316, -2e-320j, -5e-318+1e-320j]) +def test_lambertw_subnormal_k0(z): + # Verify that subnormal inputs are handled correctly on + # the branch k=0 (regression test for gh-16291). + w = lambertw(z) + # For values this small, we can be sure that numerically, + # lambertw(z) is z. + assert w == z diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3a5071fc671d8d4a7ef6c7655ca4212ced4f45 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py @@ -0,0 +1,109 @@ +import numpy as np +from numpy.testing import assert_allclose + +import pytest + +import scipy.special as sc + + +@pytest.mark.parametrize('x, expected', [ + (np.array([1000, 1]), np.array([0, -999])), + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + (np.arange(4), np.array([-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533])) +]) +def test_log_softmax(x, expected): + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +@pytest.fixture +def log_softmax_x(): + x = np.arange(4) + return x + + +@pytest.fixture +def log_softmax_expected(): + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + expected = np.array([-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533]) + return expected + + +def test_log_softmax_translation(log_softmax_x, log_softmax_expected): + # Translation property. If all the values are changed by the same amount, + # the softmax result does not change. + x = log_softmax_x + 100 + expected = log_softmax_expected + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +def test_log_softmax_noneaxis(log_softmax_x, log_softmax_expected): + # When axis=None, softmax operates on the entire array, and preserves + # the shape. + x = log_softmax_x.reshape(2, 2) + expected = log_softmax_expected.reshape(2, 2) + assert_allclose(sc.log_softmax(x), expected, rtol=1e-13) + + +@pytest.mark.parametrize('axis_2d, expected_2d', [ + (0, np.log(0.5) * np.ones((2, 2))), + (1, np.array([[0, -999], [0, -999]])) +]) +def test_axes(axis_2d, expected_2d): + assert_allclose( + sc.log_softmax([[1000, 1], [1000, 1]], axis=axis_2d), + expected_2d, + rtol=1e-13, + ) + + +@pytest.fixture +def log_softmax_2d_x(): + x = np.arange(8).reshape(2, 4) + return x + + +@pytest.fixture +def log_softmax_2d_expected(): + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + expected = np.array([[-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533], + [-3.4401896985611953, + -2.4401896985611953, + -1.4401896985611953, + -0.44018969856119533]]) + return expected + + +def test_log_softmax_2d_axis1(log_softmax_2d_x, log_softmax_2d_expected): + x = log_softmax_2d_x + expected = log_softmax_2d_expected + assert_allclose(sc.log_softmax(x, axis=1), expected, rtol=1e-13) + + +def test_log_softmax_2d_axis0(log_softmax_2d_x, log_softmax_2d_expected): + x = log_softmax_2d_x.T + expected = log_softmax_2d_expected.T + assert_allclose(sc.log_softmax(x, axis=0), expected, rtol=1e-13) + + +def test_log_softmax_3d(log_softmax_2d_x, log_softmax_2d_expected): + # 3-d input, with a tuple for the axis. + x_3d = log_softmax_2d_x.reshape(2, 2, 2) + expected_3d = log_softmax_2d_expected.reshape(2, 2, 2) + assert_allclose(sc.log_softmax(x_3d, axis=(1, 2)), expected_3d, rtol=1e-13) + + +def test_log_softmax_scalar(): + assert_allclose(sc.log_softmax(1.0), 0.0, rtol=1e-13) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcb5a20037de46df939895d38fbe5fe6b85c9aa --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py @@ -0,0 +1,70 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_ + +from scipy.special._testutils import FuncData +from scipy.special import gamma, gammaln, loggamma + + +def test_identities1(): + # test the identity exp(loggamma(z)) = gamma(z) + x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]) + y = x.copy() + x, y = np.meshgrid(x, y) + z = (x + 1J*y).flatten() + dataset = np.vstack((z, gamma(z))).T + + def f(z): + return np.exp(loggamma(z)) + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_identities2(): + # test the identity loggamma(z + 1) = log(z) + loggamma(z) + x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]) + y = x.copy() + x, y = np.meshgrid(x, y) + z = (x + 1J*y).flatten() + dataset = np.vstack((z, np.log(z) + loggamma(z))).T + + def f(z): + return loggamma(z + 1) + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_complex_dispatch_realpart(): + # Test that the real parts of loggamma and gammaln agree on the + # real axis. + x = np.r_[-np.logspace(10, -10), np.logspace(-10, 10)] + 0.5 + + dataset = np.vstack((x, gammaln(x))).T + + def f(z): + z = np.array(z, dtype='complex128') + return loggamma(z).real + + FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + + +def test_real_dispatch(): + x = np.logspace(-10, 10) + 0.5 + dataset = np.vstack((x, gammaln(x))).T + + FuncData(loggamma, dataset, 0, 1, rtol=1e-14, atol=1e-14).check() + assert_(loggamma(0) == np.inf) + assert_(np.isnan(loggamma(-1))) + + +def test_gh_6536(): + z = loggamma(complex(-3.4, +0.0)) + zbar = loggamma(complex(-3.4, -0.0)) + assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0) + + +def test_branch_cut(): + # Make sure negative zero is treated correctly + x = -np.logspace(300, -30, 100) + z = np.asarray([complex(x0, 0.0) for x0 in x]) + zbar = np.asarray([complex(x0, -0.0) for x0 in x]) + assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py new file mode 100644 index 0000000000000000000000000000000000000000..24247ac6f5ec43ae438133a0bf222553602ec925 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py @@ -0,0 +1,145 @@ +import numpy as np +from numpy.testing import (assert_equal, assert_almost_equal, + assert_allclose) +from scipy.special import logit, expit, log_expit + + +class TestLogit: + def check_logit_out(self, dtype, expected): + a = np.linspace(0, 1, 10) + a = np.array(a, dtype=dtype) + with np.errstate(divide='ignore'): + actual = logit(a) + + assert_almost_equal(actual, expected) + + assert_equal(actual.dtype, np.dtype(dtype)) + + def test_float32(self): + expected = np.array([-np.inf, -2.07944155, + -1.25276291, -0.69314718, + -0.22314353, 0.22314365, + 0.6931473, 1.25276303, + 2.07944155, np.inf], dtype=np.float32) + self.check_logit_out('f4', expected) + + def test_float64(self): + expected = np.array([-np.inf, -2.07944154, + -1.25276297, -0.69314718, + -0.22314355, 0.22314355, + 0.69314718, 1.25276297, + 2.07944154, np.inf]) + self.check_logit_out('f8', expected) + + def test_nan(self): + expected = np.array([np.nan]*4) + with np.errstate(invalid='ignore'): + actual = logit(np.array([-3., -2., 2., 3.])) + + assert_equal(expected, actual) + + +class TestExpit: + def check_expit_out(self, dtype, expected): + a = np.linspace(-4, 4, 10) + a = np.array(a, dtype=dtype) + actual = expit(a) + assert_almost_equal(actual, expected) + assert_equal(actual.dtype, np.dtype(dtype)) + + def test_float32(self): + expected = np.array([0.01798621, 0.04265125, + 0.09777259, 0.20860852, + 0.39068246, 0.60931754, + 0.79139149, 0.9022274, + 0.95734876, 0.98201376], dtype=np.float32) + self.check_expit_out('f4', expected) + + def test_float64(self): + expected = np.array([0.01798621, 0.04265125, + 0.0977726, 0.20860853, + 0.39068246, 0.60931754, + 0.79139147, 0.9022274, + 0.95734875, 0.98201379]) + self.check_expit_out('f8', expected) + + def test_large(self): + for dtype in (np.float32, np.float64, np.longdouble): + for n in (88, 89, 709, 710, 11356, 11357): + n = np.array(n, dtype=dtype) + assert_allclose(expit(n), 1.0, atol=1e-20) + assert_allclose(expit(-n), 0.0, atol=1e-20) + assert_equal(expit(n).dtype, dtype) + assert_equal(expit(-n).dtype, dtype) + + +class TestLogExpit: + + def test_large_negative(self): + x = np.array([-10000.0, -750.0, -500.0, -35.0]) + y = log_expit(x) + assert_equal(y, x) + + def test_large_positive(self): + x = np.array([750.0, 1000.0, 10000.0]) + y = log_expit(x) + # y will contain -0.0, and -0.0 is used in the expected value, + # but assert_equal does not check the sign of zeros, and I don't + # think the sign is an essential part of the test (i.e. it would + # probably be OK if log_expit(1000) returned 0.0 instead of -0.0). + assert_equal(y, np.array([-0.0, -0.0, -0.0])) + + def test_basic_float64(self): + x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9, + 0, 1e-9, 0.1, 1, 10, 100, 500, 710, 725, 735]) + y = log_expit(x) + # + # Expected values were computed with mpmath: + # + # import mpmath + # + # mpmath.mp.dps = 100 + # + # def mp_log_expit(x): + # return -mpmath.log1p(mpmath.exp(-x)) + # + # expected = [float(mp_log_expit(t)) for t in x] + # + expected = [-32.000000000000014, -20.000000002061153, + -10.000045398899218, -3.048587351573742, + -1.3132616875182228, -0.7443966600735709, + -0.6931471810599453, -0.6931471805599453, + -0.6931471800599454, -0.6443966600735709, + -0.3132616875182228, -4.539889921686465e-05, + -3.720075976020836e-44, -7.124576406741286e-218, + -4.47628622567513e-309, -1.36930634e-315, + -6.217e-320] + + # When tested locally, only one value in y was not exactly equal to + # expected. That was for x=1, and the y value differed from the + # expected by 1 ULP. For this test, however, I'll use rtol=1e-15. + assert_allclose(y, expected, rtol=1e-15) + + def test_basic_float32(self): + x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9, + 0, 1e-9, 0.1, 1, 10, 100], dtype=np.float32) + y = log_expit(x) + # + # Expected values were computed with mpmath: + # + # import mpmath + # + # mpmath.mp.dps = 100 + # + # def mp_log_expit(x): + # return -mpmath.log1p(mpmath.exp(-x)) + # + # expected = [np.float32(mp_log_expit(t)) for t in x] + # + expected = np.array([-32.0, -20.0, -10.000046, -3.0485873, + -1.3132616, -0.7443967, -0.6931472, + -0.6931472, -0.6931472, -0.64439666, + -0.3132617, -4.5398898e-05, -3.8e-44], + dtype=np.float32) + + assert_allclose(y, expected, rtol=5e-7) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py new file mode 100644 index 0000000000000000000000000000000000000000..5d9848062d3f6496dd19be34ceb9abe2858e8d48 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py @@ -0,0 +1,207 @@ +import numpy as np +from numpy.testing import (assert_almost_equal, assert_equal, assert_allclose, + assert_array_almost_equal, assert_) + +from scipy.special import logsumexp, softmax + + +def test_logsumexp(): + # Test whether logsumexp() function correctly handles large inputs. + a = np.arange(200) + desired = np.log(np.sum(np.exp(a))) + assert_almost_equal(logsumexp(a), desired) + + # Now test with large numbers + b = [1000, 1000] + desired = 1000.0 + np.log(2.0) + assert_almost_equal(logsumexp(b), desired) + + n = 1000 + b = np.full(n, 10000, dtype='float64') + desired = 10000.0 + np.log(n) + assert_almost_equal(logsumexp(b), desired) + + x = np.array([1e-40] * 1000000) + logx = np.log(x) + + X = np.vstack([x, x]) + logX = np.vstack([logx, logx]) + assert_array_almost_equal(np.exp(logsumexp(logX)), X.sum()) + assert_array_almost_equal(np.exp(logsumexp(logX, axis=0)), X.sum(axis=0)) + assert_array_almost_equal(np.exp(logsumexp(logX, axis=1)), X.sum(axis=1)) + + # Handling special values properly + assert_equal(logsumexp(np.inf), np.inf) + assert_equal(logsumexp(-np.inf), -np.inf) + assert_equal(logsumexp(np.nan), np.nan) + assert_equal(logsumexp([-np.inf, -np.inf]), -np.inf) + + # Handling an array with different magnitudes on the axes + assert_array_almost_equal(logsumexp([[1e10, 1e-10], + [-1e10, -np.inf]], axis=-1), + [1e10, -1e10]) + + # Test keeping dimensions + assert_array_almost_equal(logsumexp([[1e10, 1e-10], + [-1e10, -np.inf]], + axis=-1, + keepdims=True), + [[1e10], [-1e10]]) + + # Test multiple axes + assert_array_almost_equal(logsumexp([[1e10, 1e-10], + [-1e10, -np.inf]], + axis=(-1,-2)), + 1e10) + + +def test_logsumexp_b(): + a = np.arange(200) + b = np.arange(200, 0, -1) + desired = np.log(np.sum(b*np.exp(a))) + assert_almost_equal(logsumexp(a, b=b), desired) + + a = [1000, 1000] + b = [1.2, 1.2] + desired = 1000 + np.log(2 * 1.2) + assert_almost_equal(logsumexp(a, b=b), desired) + + x = np.array([1e-40] * 100000) + b = np.linspace(1, 1000, 100000) + logx = np.log(x) + + X = np.vstack((x, x)) + logX = np.vstack((logx, logx)) + B = np.vstack((b, b)) + assert_array_almost_equal(np.exp(logsumexp(logX, b=B)), (B * X).sum()) + assert_array_almost_equal(np.exp(logsumexp(logX, b=B, axis=0)), + (B * X).sum(axis=0)) + assert_array_almost_equal(np.exp(logsumexp(logX, b=B, axis=1)), + (B * X).sum(axis=1)) + + +def test_logsumexp_sign(): + a = [1,1,1] + b = [1,-1,-1] + + r, s = logsumexp(a, b=b, return_sign=True) + assert_almost_equal(r,1) + assert_equal(s,-1) + + +def test_logsumexp_sign_zero(): + a = [1,1] + b = [1,-1] + + r, s = logsumexp(a, b=b, return_sign=True) + assert_(not np.isfinite(r)) + assert_(not np.isnan(r)) + assert_(r < 0) + assert_equal(s,0) + + +def test_logsumexp_sign_shape(): + a = np.ones((1,2,3,4)) + b = np.ones_like(a) + + r, s = logsumexp(a, axis=2, b=b, return_sign=True) + + assert_equal(r.shape, s.shape) + assert_equal(r.shape, (1,2,4)) + + r, s = logsumexp(a, axis=(1,3), b=b, return_sign=True) + + assert_equal(r.shape, s.shape) + assert_equal(r.shape, (1,3)) + + +def test_logsumexp_complex_sign(): + a = np.array([1 + 1j, 2 - 1j, -2 + 3j]) + + r, s = logsumexp(a, return_sign=True) + + expected_sumexp = np.exp(a).sum() + # This is the numpy>=2.0 convention for np.sign + expected_sign = expected_sumexp / abs(expected_sumexp) + + assert_allclose(s, expected_sign) + assert_allclose(s * np.exp(r), expected_sumexp) + + +def test_logsumexp_shape(): + a = np.ones((1, 2, 3, 4)) + b = np.ones_like(a) + + r = logsumexp(a, axis=2, b=b) + assert_equal(r.shape, (1, 2, 4)) + + r = logsumexp(a, axis=(1, 3), b=b) + assert_equal(r.shape, (1, 3)) + + +def test_logsumexp_b_zero(): + a = [1,10000] + b = [1,0] + + assert_almost_equal(logsumexp(a, b=b), 1) + + +def test_logsumexp_b_shape(): + a = np.zeros((4,1,2,1)) + b = np.ones((3,1,5)) + + logsumexp(a, b=b) + + +def test_softmax_fixtures(): + assert_allclose(softmax([1000, 0, 0, 0]), np.array([1, 0, 0, 0]), + rtol=1e-13) + assert_allclose(softmax([1, 1]), np.array([.5, .5]), rtol=1e-13) + assert_allclose(softmax([0, 1]), np.array([1, np.e])/(1 + np.e), + rtol=1e-13) + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + x = np.arange(4) + expected = np.array([0.03205860328008499, + 0.08714431874203256, + 0.23688281808991013, + 0.6439142598879722]) + + assert_allclose(softmax(x), expected, rtol=1e-13) + + # Translation property. If all the values are changed by the same amount, + # the softmax result does not change. + assert_allclose(softmax(x + 100), expected, rtol=1e-13) + + # When axis=None, softmax operates on the entire array, and preserves + # the shape. + assert_allclose(softmax(x.reshape(2, 2)), expected.reshape(2, 2), + rtol=1e-13) + + +def test_softmax_multi_axes(): + assert_allclose(softmax([[1000, 0], [1000, 0]], axis=0), + np.array([[.5, .5], [.5, .5]]), rtol=1e-13) + assert_allclose(softmax([[1000, 0], [1000, 0]], axis=1), + np.array([[1, 0], [1, 0]]), rtol=1e-13) + + # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then + # converted to float. + x = np.array([[-25, 0, 25, 50], + [1, 325, 749, 750]]) + expected = np.array([[2.678636961770877e-33, + 1.9287498479371314e-22, + 1.3887943864771144e-11, + 0.999999999986112], + [0.0, + 1.9444526359919372e-185, + 0.2689414213699951, + 0.7310585786300048]]) + assert_allclose(softmax(x, axis=1), expected, rtol=1e-13) + assert_allclose(softmax(x.T, axis=0), expected.T, rtol=1e-13) + + # 3-d input, with a tuple for the axis. + x3d = x.reshape(2, 2, 2) + assert_allclose(softmax(x3d, axis=(1, 2)), expected.reshape(2, 2, 2), + rtol=1e-13) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6cf3b91692d9daa7c01317f484d160d3798c8c --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py @@ -0,0 +1,2272 @@ +""" +Test SciPy functions versus mpmath, if available. + +""" +import numpy as np +from numpy.testing import assert_, assert_allclose +from numpy import pi +import pytest +import itertools + +from scipy._lib import _pep440 + +import scipy.special as sc +from scipy.special._testutils import ( + MissingModule, check_version, FuncData, + assert_func_equal) +from scipy.special._mptestutils import ( + Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal, + nonfunctional_tooslow, trace_args, time_limited, exception_to_nan, + inf_to_nan) +from scipy.special._ufuncs import ( + _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx, + _igam_fac) + +try: + import mpmath +except ImportError: + mpmath = MissingModule('mpmath') + + +# ------------------------------------------------------------------------------ +# expi +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.10') +def test_expi_complex(): + dataset = [] + for r in np.logspace(-99, 2, 10): + for p in np.linspace(0, 2*np.pi, 30): + z = r*np.exp(1j*p) + dataset.append((z, complex(mpmath.ei(z)))) + dataset = np.array(dataset, dtype=np.cdouble) + + FuncData(sc.expi, dataset, 0, 1).check() + + +# ------------------------------------------------------------------------------ +# expn +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_expn_large_n(): + # Test the transition to the asymptotic regime of n. + dataset = [] + for n in [50, 51]: + for x in np.logspace(0, 4, 200): + with mpmath.workdps(100): + dataset.append((n, x, float(mpmath.expint(n, x)))) + dataset = np.asarray(dataset) + + FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check() + +# ------------------------------------------------------------------------------ +# hyp0f1 +# ------------------------------------------------------------------------------ + + +@check_version(mpmath, '0.19') +def test_hyp0f1_gh5764(): + # Do a small and somewhat systematic test that runs quickly + dataset = [] + axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5] + for v in axis: + for x in axis: + for y in axis: + z = x + 1j*y + # mpmath computes the answer correctly at dps ~ 17 but + # fails for 20 < dps < 120 (uses a different method); + # set the dps high enough that this isn't an issue + with mpmath.workdps(120): + res = complex(mpmath.hyp0f1(v, z)) + dataset.append((v, z, res)) + dataset = np.array(dataset) + + FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2, + rtol=1e-13).check() + + +@check_version(mpmath, '0.19') +def test_hyp0f1_gh_1609(): + # this is a regression test for gh-1609 + vv = np.linspace(150, 180, 21) + af = sc.hyp0f1(vv, 0.5) + mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv]) + assert_allclose(af, mf.astype(float), rtol=1e-12) + + +# ------------------------------------------------------------------------------ +# hyperu +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '1.1.0') +def test_hyperu_around_0(): + dataset = [] + # DLMF 13.2.14-15 test points. + for n in np.arange(-5, 5): + for b in np.linspace(-5, 5, 20): + a = -n + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + a = -n + b - 1 + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + # DLMF 13.2.16-22 test points. + for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]: + for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]: + dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0)))) + dataset = np.array(dataset) + + FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check() + + +# ------------------------------------------------------------------------------ +# hyp2f1 +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '1.0.0') +def test_hyp2f1_strange_points(): + pts = [ + (2, -1, -1, 0.7), # expected: 2.4 + (2, -2, -2, 0.7), # expected: 3.87 + ] + pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4)) + pts = [ + (a, b, c, x) for a, b, c, x in pts + if b == c and round(b) == b and b < 0 and b != -1000 + ] + kw = dict(eliminate=True) + dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.13') +def test_hyp2f1_real_some_points(): + pts = [ + (1, 2, 3, 0), + (1./3, 2./3, 5./6, 27./32), + (1./4, 1./2, 3./4, 80./81), + (2,-2, -3, 3), + (2, -3, -2, 3), + (2, -1.5, -1.5, 3), + (1, 2, 3, 0), + (0.7235, -1, -5, 0.3), + (0.25, 1./3, 2, 0.999), + (0.25, 1./3, 2, -1), + (2, 3, 5, 0.99), + (3./2, -0.5, 3, 0.99), + (2, 2.5, -3.25, 0.999), + (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001), + (-10, 900, -10.5, 0.99), + (-10, 900, 10.5, 0.99), + (-1, 2, 1, 1.0), + (-1, 2, 1, -1.0), + (-3, 13, 5, 1.0), + (-3, 13, 5, -1.0), + (0.5, 1 - 270.5, 1.5, 0.999**2), # from issue 1561 + ] + dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + with np.errstate(invalid='ignore'): + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.14') +def test_hyp2f1_some_points_2(): + # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but + # was fixed in their SVN since then + pts = [ + (112, (51,10), (-9,10), -0.99999), + (10,-900,10.5,0.99), + (10,-900,-10.5,0.99), + ] + + def fev(x): + if isinstance(x, tuple): + return float(x[0]) / x[1] + else: + return x + + dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check() + + +@check_version(mpmath, '0.13') +def test_hyp2f1_real_some(): + dataset = [] + for a in [-10, -5, -1.8, 1.8, 5, 10]: + for b in [-2.5, -1, 1, 7.4]: + for c in [-9, -1.8, 5, 20.4]: + for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]: + try: + v = float(mpmath.hyp2f1(a, b, c, z)) + except Exception: + continue + dataset.append((a, b, c, z, v)) + dataset = np.array(dataset, dtype=np.float64) + + with np.errstate(invalid='ignore'): + FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9, + ignore_inf_sign=True).check() + + +@check_version(mpmath, '0.12') +@pytest.mark.slow +def test_hyp2f1_real_random(): + npoints = 500 + dataset = np.zeros((npoints, 5), np.float64) + + np.random.seed(1234) + dataset[:, 0] = np.random.pareto(1.5, npoints) + dataset[:, 1] = np.random.pareto(1.5, npoints) + dataset[:, 2] = np.random.pareto(1.5, npoints) + dataset[:, 3] = 2*np.random.rand(npoints) - 1 + + dataset[:, 0] *= (-1)**np.random.randint(2, npoints) + dataset[:, 1] *= (-1)**np.random.randint(2, npoints) + dataset[:, 2] *= (-1)**np.random.randint(2, npoints) + + for ds in dataset: + if mpmath.__version__ < '0.14': + # mpmath < 0.14 fails for c too much smaller than a, b + if abs(ds[:2]).max() > abs(ds[2]): + ds[2] = abs(ds[:2]).max() + ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4]))) + + FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check() + + +# ------------------------------------------------------------------------------ +# erf (complex) +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.14') +def test_erf_complex(): + # need to increase mpmath precision for this test + old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec + try: + mpmath.mp.dps = 70 + x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11)) + x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11)) + points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()] + + assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points, + vectorized=False, rtol=1e-13) + assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points, + vectorized=False, rtol=1e-13) + finally: + mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec + + +# ------------------------------------------------------------------------------ +# lpmv +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.15') +def test_lpmv(): + pts = [] + for x in [-0.99, -0.557, 1e-6, 0.132, 1]: + pts.extend([ + (1, 1, x), + (1, -1, x), + (-1, 1, x), + (-1, -2, x), + (1, 1.7, x), + (1, -1.7, x), + (-1, 1.7, x), + (-1, -2.7, x), + (1, 10, x), + (1, 11, x), + (3, 8, x), + (5, 11, x), + (-3, 8, x), + (-5, 11, x), + (3, -8, x), + (5, -11, x), + (-3, -8, x), + (-5, -11, x), + (3, 8.3, x), + (5, 11.3, x), + (-3, 8.3, x), + (-5, 11.3, x), + (3, -8.3, x), + (5, -11.3, x), + (-3, -8.3, x), + (-5, -11.3, x), + ]) + + def mplegenp(nu, mu, x): + if mu == int(mu) and x == 1: + # mpmath 0.17 gets this wrong + if mu == 0: + return 1 + else: + return 0 + return mpmath.legenp(nu, mu, x) + + dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts] + dataset = np.array(dataset, dtype=np.float64) + + def evf(mu, nu, x): + return sc.lpmv(mu.astype(int), nu, x) + + with np.errstate(invalid='ignore'): + FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check() + + +# ------------------------------------------------------------------------------ +# beta +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.15') +def test_beta(): + np.random.seed(1234) + + b = np.r_[np.logspace(-200, 200, 4), + np.logspace(-10, 10, 4), + np.logspace(-1, 1, 4), + np.arange(-10, 11, 1), + np.arange(-10, 11, 1) + 0.5, + -1, -2.3, -3, -100.3, -10003.4] + a = b + + ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T + + old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec + try: + mpmath.mp.dps = 400 + + assert_func_equal(sc.beta, + lambda a, b: float(mpmath.beta(a, b)), + ab, + vectorized=False, + rtol=1e-10, + ignore_inf_sign=True) + + assert_func_equal( + sc.betaln, + lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))), + ab, + vectorized=False, + rtol=1e-10) + finally: + mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec + + +# ------------------------------------------------------------------------------ +# loggamma +# ------------------------------------------------------------------------------ + +LOGGAMMA_TAYLOR_RADIUS = 0.2 + + +@check_version(mpmath, '0.19') +def test_loggamma_taylor_transition(): + # Make sure there isn't a big jump in accuracy when we move from + # using the Taylor series to using the recurrence relation. + + r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1]) + theta = np.linspace(0, 2*np.pi, 20) + r, theta = np.meshgrid(r, theta) + dz = r*np.exp(1j*theta) + z = np.r_[1 + dz, 2 + dz].flatten() + + dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z] + dataset = np.array(dataset) + + FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() + + +@check_version(mpmath, '0.19') +def test_loggamma_taylor(): + # Test around the zeros at z = 1, 2. + + r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10) + theta = np.linspace(0, 2*np.pi, 20) + r, theta = np.meshgrid(r, theta) + dz = r*np.exp(1j*theta) + z = np.r_[1 + dz, 2 + dz].flatten() + + dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z] + dataset = np.array(dataset) + + FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check() + + +# ------------------------------------------------------------------------------ +# rgamma +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_rgamma_zeros(): + # Test around the zeros at z = 0, -1, -2, ..., -169. (After -169 we + # get values that are out of floating point range even when we're + # within 0.1 of the zero.) + + # Can't use too many points here or the test takes forever. + dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = np.arange(0, -170, -1).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + with mpmath.workdps(100): + dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z] + + dataset = np.array(dataset) + FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check() + + +# ------------------------------------------------------------------------------ +# digamma +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_digamma_roots(): + # Test the special-cased roots for digamma. + root = mpmath.findroot(mpmath.digamma, 1.5) + roots = [float(root)] + root = mpmath.findroot(mpmath.digamma, -0.5) + roots.append(float(root)) + roots = np.array(roots) + + # If we test beyond a radius of 0.24 mpmath will take forever. + dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + z = (roots + np.dstack((dz,)*roots.size)).flatten() + with mpmath.workdps(30): + dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z] + + dataset = np.array(dataset) + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check() + + +@check_version(mpmath, '0.19') +def test_digamma_negreal(): + # Test digamma around the negative real axis. Don't do this in + # TestSystematic because the points need some jiggering so that + # mpmath doesn't take forever. + + digamma = exception_to_nan(mpmath.digamma) + + x = -np.logspace(300, -30, 100) + y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)] + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + with mpmath.workdps(40): + dataset = [(z0, complex(digamma(z0))) for z0 in z] + dataset = np.asarray(dataset) + + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() + + +@check_version(mpmath, '0.19') +def test_digamma_boundary(): + # Check that there isn't a jump in accuracy when we switch from + # using the asymptotic series to the reflection formula. + + x = -np.logspace(300, -30, 100) + y = np.array([-6.1, -5.9, 5.9, 6.1]) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + with mpmath.workdps(30): + dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z] + dataset = np.asarray(dataset) + + FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check() + + +# ------------------------------------------------------------------------------ +# gammainc +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_gammainc_boundary(): + # Test the transition to the asymptotic series. + small = 20 + a = np.linspace(0.5*small, 2*small, 50) + x = a.copy() + a, x = np.meshgrid(a, x) + a, x = a.flatten(), x.flatten() + with mpmath.workdps(100): + dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True))) + for a0, x0 in zip(a, x)] + dataset = np.array(dataset) + + FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check() + + +# ------------------------------------------------------------------------------ +# spence +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +@pytest.mark.slow +def test_spence_circle(): + # The trickiest region for spence is around the circle |z - 1| = 1, + # so test that region carefully. + + def spence(z): + return complex(mpmath.polylog(2, 1 - z)) + + r = np.linspace(0.5, 1.5) + theta = np.linspace(0, 2*pi) + z = (1 + np.outer(r, np.exp(1j*theta))).flatten() + dataset = np.asarray([(z0, spence(z0)) for z0 in z]) + + FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check() + + +# ------------------------------------------------------------------------------ +# sinpi and cospi +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_sinpi_zeros(): + eps = np.finfo(float).eps + dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = np.arange(-100, 100, 1).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + dataset = np.asarray([(z0, complex(mpmath.sinpi(z0))) + for z0 in z]) + FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check() + + +@check_version(mpmath, '0.19') +def test_cospi_zeros(): + eps = np.finfo(float).eps + dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)] + dy = dx.copy() + dx, dy = np.meshgrid(dx, dy) + dz = dx + 1j*dy + zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1) + z = (zeros + np.dstack((dz,)*zeros.size)).flatten() + dataset = np.asarray([(z0, complex(mpmath.cospi(z0))) + for z0 in z]) + + FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check() + + +# ------------------------------------------------------------------------------ +# ellipj +# ------------------------------------------------------------------------------ + +@check_version(mpmath, '0.19') +def test_dn_quarter_period(): + def dn(u, m): + return sc.ellipj(u, m)[2] + + def mpmath_dn(u, m): + return float(mpmath.ellipfun("dn", u=u, m=m)) + + m = np.linspace(0, 1, 20) + du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)] + dataset = [] + for m0 in m: + u0 = float(mpmath.ellipk(m0)) + for du0 in du: + p = u0 + du0 + dataset.append((p, m0, mpmath_dn(p, m0))) + dataset = np.asarray(dataset) + + FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check() + + +# ------------------------------------------------------------------------------ +# Wright Omega +# ------------------------------------------------------------------------------ + +def _mpmath_wrightomega(z, dps): + with mpmath.workdps(dps): + z = mpmath.mpc(z) + unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi)) + res = mpmath.lambertw(mpmath.exp(z), unwind) + return res + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_branch(): + x = -np.logspace(10, 0, 25) + picut_above = [np.nextafter(np.pi, np.inf)] + picut_below = [np.nextafter(np.pi, -np.inf)] + npicut_above = [np.nextafter(-np.pi, np.inf)] + npicut_below = [np.nextafter(-np.pi, -np.inf)] + for i in range(50): + picut_above.append(np.nextafter(picut_above[-1], np.inf)) + picut_below.append(np.nextafter(picut_below[-1], -np.inf)) + npicut_above.append(np.nextafter(npicut_above[-1], np.inf)) + npicut_below.append(np.nextafter(npicut_below[-1], -np.inf)) + y = np.hstack((picut_above, picut_below, npicut_above, npicut_below)) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check() + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_region1(): + # This region gets less coverage in the TestSystematic test + x = np.linspace(-2, 1) + y = np.linspace(1, 2*np.pi) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() + + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_wrightomega_region2(): + # This region gets less coverage in the TestSystematic test + x = np.linspace(-2, 1) + y = np.linspace(-2*np.pi, -1) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25))) + for z0 in z]) + + FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check() + + +# ------------------------------------------------------------------------------ +# lambertw +# ------------------------------------------------------------------------------ + +@pytest.mark.slow +@check_version(mpmath, '0.19') +def test_lambertw_smallz(): + x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25) + x, y = np.meshgrid(x, y) + z = (x + 1j*y).flatten() + + dataset = np.asarray([(z0, complex(mpmath.lambertw(z0))) + for z0 in z]) + + FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check() + + +# ------------------------------------------------------------------------------ +# Systematic tests +# ------------------------------------------------------------------------------ + +HYPERKW = dict(maxprec=200, maxterms=200) + + +@pytest.mark.slow +@check_version(mpmath, '0.17') +class TestSystematic: + + def test_airyai(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [Arg(-1e3, 1e3)]) + + def test_airyai_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[0], + mpmath.airyai, + [ComplexArg()]) + + def test_airyai_prime(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [Arg(-1e3, 1e3)]) + + def test_airyai_prime_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z: + mpmath.airyai(z, derivative=1), + [ComplexArg()]) + + def test_airybi(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [Arg(-1e3, 1e3)]) + + def test_airybi_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z: + mpmath.airybi(z), + [ComplexArg()]) + + def test_airybi_prime(self): + # oscillating function, limit range + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [Arg(-1e8, 1e8)], + rtol=1e-5) + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [Arg(-1e3, 1e3)]) + + def test_airybi_prime_complex(self): + assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z: + mpmath.airybi(z, derivative=1), + [ComplexArg()]) + + def test_bei(self): + assert_mpmath_equal(sc.bei, + exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)), + [Arg(-1e3, 1e3)]) + + def test_ber(self): + assert_mpmath_equal(sc.ber, + exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)), + [Arg(-1e3, 1e3)]) + + def test_bernoulli(self): + assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)], + lambda n: float(mpmath.bernoulli(int(n))), + [IntArg(0, 13000)], + rtol=1e-9, n=13000) + + def test_besseli(self): + assert_mpmath_equal( + sc.iv, + exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg()], + atol=1e-270, + ) + + def test_besseli_complex(self): + assert_mpmath_equal( + lambda v, z: sc.iv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), ComplexArg()], + ) + + def test_besselj(self): + assert_mpmath_equal( + sc.jv, + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg(-1e3, 1e3)], + ignore_inf_sign=True, + ) + + # loss of precision at large arguments due to oscillation + assert_mpmath_equal( + sc.jv, + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], + ignore_inf_sign=True, + rtol=1e-5, + ) + + def test_besselj_complex(self): + assert_mpmath_equal( + lambda v, z: sc.jv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)), + [Arg(), ComplexArg()] + ) + + def test_besselk(self): + assert_mpmath_equal( + sc.kv, + mpmath.besselk, + [Arg(-200, 200), Arg(0, np.inf)], + nan_ok=False, + rtol=1e-12, + ) + + def test_besselk_int(self): + assert_mpmath_equal( + sc.kn, + mpmath.besselk, + [IntArg(-200, 200), Arg(0, np.inf)], + nan_ok=False, + rtol=1e-12, + ) + + def test_besselk_complex(self): + assert_mpmath_equal( + lambda v, z: sc.kv(v.real, z), + exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)), + [Arg(-1e100, 1e100), ComplexArg()], + ) + + def test_bessely(self): + def mpbessely(v, x): + r = float(mpmath.bessely(v, x, **HYPERKW)) + if abs(r) > 1e305: + # overflowing to inf a bit earlier is OK + r = np.inf * np.sign(r) + if abs(r) == 0 and x == 0: + # invalid result from mpmath, point x=0 is a divergence + return np.nan + return r + assert_mpmath_equal( + sc.yv, + exception_to_nan(mpbessely), + [Arg(-1e100, 1e100), Arg(-1e8, 1e8)], + n=5000, + ) + + def test_bessely_complex(self): + def mpbessely(v, x): + r = complex(mpmath.bessely(v, x, **HYPERKW)) + if abs(r) > 1e305: + # overflowing to inf a bit earlier is OK + with np.errstate(invalid='ignore'): + r = np.inf * np.sign(r) + return r + assert_mpmath_equal( + lambda v, z: sc.yv(v.real, z), + exception_to_nan(mpbessely), + [Arg(), ComplexArg()], + n=15000, + ) + + def test_bessely_int(self): + def mpbessely(v, x): + r = float(mpmath.bessely(v, x)) + if abs(r) == 0 and x == 0: + # invalid result from mpmath, point x=0 is a divergence + return np.nan + return r + assert_mpmath_equal( + lambda v, z: sc.yn(int(v), z), + exception_to_nan(mpbessely), + [IntArg(-1000, 1000), Arg(-1e8, 1e8)], + ) + + def test_beta(self): + bad_points = [] + + def beta(a, b, nonzero=False): + if a < -1e12 or b < -1e12: + # Function is defined here only at integers, but due + # to loss of precision this is numerically + # ill-defined. Don't compare values here. + return np.nan + if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0: + # close to a zero of the function: mpmath and scipy + # will not round here the same, so the test needs to be + # run with an absolute tolerance + if nonzero: + bad_points.append((float(a), float(b))) + return np.nan + return mpmath.beta(a, b) + + assert_mpmath_equal( + sc.beta, + lambda a, b: beta(a, b, nonzero=True), + [Arg(), Arg()], + dps=400, + ignore_inf_sign=True, + ) + + assert_mpmath_equal( + sc.beta, + beta, + np.array(bad_points), + dps=400, + ignore_inf_sign=True, + atol=1e-11, + ) + + def test_betainc(self): + assert_mpmath_equal( + sc.betainc, + time_limited()( + exception_to_nan( + lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True) + ) + ), + [Arg(), Arg(), Arg()], + ) + + def test_betaincc(self): + assert_mpmath_equal( + sc.betaincc, + time_limited()( + exception_to_nan( + lambda a, b, x: mpmath.betainc(a, b, x, 1, regularized=True) + ) + ), + [Arg(), Arg(), Arg()], + dps=400, + ) + + def test_binom(self): + bad_points = [] + + def binomial(n, k, nonzero=False): + if abs(k) > 1e8*(abs(n) + 1): + # The binomial is rapidly oscillating in this region, + # and the function is numerically ill-defined. Don't + # compare values here. + return np.nan + if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15: + # close to a zero of the function: mpmath and scipy + # will not round here the same, so the test needs to be + # run with an absolute tolerance + if nonzero: + bad_points.append((float(n), float(k))) + return np.nan + return mpmath.binomial(n, k) + + assert_mpmath_equal( + sc.binom, + lambda n, k: binomial(n, k, nonzero=True), + [Arg(), Arg()], + dps=400, + ) + + assert_mpmath_equal( + sc.binom, + binomial, + np.array(bad_points), + dps=400, + atol=1e-14, + ) + + def test_chebyt_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_chebyt(int(n), x), + exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)), + [IntArg(), Arg()], + dps=50, + ) + + @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") + def test_chebyt(self): + assert_mpmath_equal( + sc.eval_chebyt, + lambda n, x: time_limited()( + exception_to_nan(mpmath.chebyt) + )(n, x, **HYPERKW), + [Arg(-101, 101), Arg()], + n=10000, + ) + + def test_chebyu_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_chebyu(int(n), x), + exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)), + [IntArg(), Arg()], + dps=50, + ) + + @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate") + def test_chebyu(self): + assert_mpmath_equal( + sc.eval_chebyu, + lambda n, x: time_limited()( + exception_to_nan(mpmath.chebyu) + )(n, x, **HYPERKW), + [Arg(-101, 101), Arg()], + ) + + def test_chi(self): + def chi(x): + return sc.shichi(x)[1] + assert_mpmath_equal(chi, mpmath.chi, [Arg()]) + # check asymptotic series cross-over + assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) + + def test_chi_complex(self): + def chi(z): + return sc.shichi(z)[1] + # chi oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + chi, + mpmath.chi, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-12, + ) + + def test_ci(self): + def ci(x): + return sc.sici(x)[1] + # oscillating function: limit range + assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)]) + + def test_ci_complex(self): + def ci(z): + return sc.sici(z)[1] + # ci oscillates as Re[z] -> +- inf, so limit range + assert_mpmath_equal( + ci, + mpmath.ci, + [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], + rtol=1e-8, + ) + + def test_cospi(self): + eps = np.finfo(float).eps + assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=2*eps) + + def test_cospi_complex(self): + assert_mpmath_equal( + _cospi, + mpmath.cospi, + [ComplexArg()], + nan_ok=False, + rtol=1e-13, + ) + + def test_digamma(self): + assert_mpmath_equal( + sc.digamma, + exception_to_nan(mpmath.digamma), + [Arg()], + rtol=1e-12, + dps=50, + ) + + def test_digamma_complex(self): + # Test on a cut plane because mpmath will hang. See + # test_digamma_negreal for tests on the negative real axis. + def param_filter(z): + return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True) + + assert_mpmath_equal( + sc.digamma, + exception_to_nan(mpmath.digamma), + [ComplexArg()], + rtol=1e-13, + dps=40, + param_filter=param_filter + ) + + def test_e1(self): + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + [Arg()], + rtol=1e-14, + ) + + def test_e1_complex(self): + # E_1 oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-11, + ) + + # Check cross-over region + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + (np.linspace(-50, 50, 171)[:, None] + + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(), + rtol=1e-11, + ) + assert_mpmath_equal( + sc.exp1, + mpmath.e1, + (np.linspace(-50, -35, 10000) + 0j), + rtol=1e-11, + ) + + def test_exprel(self): + assert_mpmath_equal( + sc.exprel, + lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), + [Arg(a=-np.log(np.finfo(np.float64).max), + b=np.log(np.finfo(np.float64).max))], + ) + assert_mpmath_equal( + sc.exprel, + lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'), + np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]), + rtol=1e-11, + ) + assert_(np.isinf(sc.exprel(np.inf))) + assert_(sc.exprel(-np.inf) == 0) + + def test_expm1_complex(self): + # Oscillates as a function of Im[z], so limit range to avoid loss of precision + assert_mpmath_equal( + sc.expm1, + mpmath.expm1, + [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))], + ) + + def test_log1p_complex(self): + assert_mpmath_equal( + sc.log1p, + lambda x: mpmath.log(x+1), + [ComplexArg()], + dps=60, + ) + + def test_log1pmx(self): + assert_mpmath_equal( + _log1pmx, + lambda x: mpmath.log(x + 1) - x, + [Arg()], + dps=60, + rtol=1e-14, + ) + + def test_ei(self): + assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11) + + def test_ei_complex(self): + # Ei oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + sc.expi, + mpmath.ei, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-9, + ) + + def test_ellipe(self): + assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)]) + + def test_ellipeinc(self): + assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)]) + + def test_ellipeinc_largephi(self): + assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()]) + + def test_ellipf(self): + assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()]) + + def test_ellipf_largephi(self): + assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()]) + + def test_ellipk(self): + assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)]) + assert_mpmath_equal( + sc.ellipkm1, + lambda m: mpmath.ellipk(1 - m), + [Arg(a=0.0)], + dps=400, + ) + + def test_ellipkinc(self): + def ellipkinc(phi, m): + return mpmath.ellippi(0, phi, m) + assert_mpmath_equal( + sc.ellipkinc, + ellipkinc, + [Arg(-1e3, 1e3), Arg(b=1.0)], + ignore_inf_sign=True, + ) + + def test_ellipkinc_largephi(self): + def ellipkinc(phi, m): + return mpmath.ellippi(0, phi, m) + assert_mpmath_equal( + sc.ellipkinc, + ellipkinc, + [Arg(), Arg(b=1.0)], + ignore_inf_sign=True, + ) + + def test_ellipfun_sn(self): + def sn(u, m): + # mpmath doesn't get the zero at u = 0--fix that + if u == 0: + return 0 + else: + return mpmath.ellipfun("sn", u=u, m=m) + + # Oscillating function --- limit range of first argument; the + # loss of precision there is an expected numerical feature + # rather than an actual bug + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[0], + sn, + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_ellipfun_cn(self): + # see comment in ellipfun_sn + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[1], + lambda u, m: mpmath.ellipfun("cn", u=u, m=m), + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_ellipfun_dn(self): + # see comment in ellipfun_sn + assert_mpmath_equal( + lambda u, m: sc.ellipj(u, m)[2], + lambda u, m: mpmath.ellipfun("dn", u=u, m=m), + [Arg(-1e6, 1e6), Arg(a=0, b=1)], + rtol=1e-8, + ) + + def test_erf(self): + assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()]) + + def test_erf_complex(self): + assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200) + + def test_erfc(self): + assert_mpmath_equal( + sc.erfc, + exception_to_nan(lambda z: mpmath.erfc(z)), + [Arg()], + rtol=1e-13, + ) + + def test_erfc_complex(self): + assert_mpmath_equal( + sc.erfc, + exception_to_nan(lambda z: mpmath.erfc(z)), + [ComplexArg()], + n=200, + ) + + def test_erfi(self): + assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200) + + def test_erfi_complex(self): + assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200) + + def test_ndtr(self): + assert_mpmath_equal( + sc.ndtr, + exception_to_nan(lambda z: mpmath.ncdf(z)), + [Arg()], + n=200, + ) + + def test_ndtr_complex(self): + assert_mpmath_equal( + sc.ndtr, + lambda z: mpmath.erfc(-z/np.sqrt(2.))/2., + [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))], + n=400, + ) + + def test_log_ndtr(self): + assert_mpmath_equal( + sc.log_ndtr, + exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))), + [Arg()], n=600, dps=300, rtol=1e-13, + ) + + def test_log_ndtr_complex(self): + assert_mpmath_equal( + sc.log_ndtr, + exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)), + [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))], + n=200, dps=300, + ) + + def test_eulernum(self): + assert_mpmath_equal( + lambda n: sc.euler(n)[-1], + mpmath.eulernum, + [IntArg(1, 10000)], + n=10000, + ) + + def test_expint(self): + assert_mpmath_equal( + sc.expn, + mpmath.expint, + [IntArg(0, 200), Arg(0, np.inf)], + rtol=1e-13, + dps=160, + ) + + def test_fresnels(self): + def fresnels(x): + return sc.fresnel(x)[0] + assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()]) + + def test_fresnelc(self): + def fresnelc(x): + return sc.fresnel(x)[1] + assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()]) + + def test_gamma(self): + assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()]) + + def test_gamma_complex(self): + assert_mpmath_equal( + sc.gamma, + exception_to_nan(mpmath.gamma), + [ComplexArg()], + rtol=5e-13, + ) + + def test_gammainc(self): + # Larger arguments are tested in test_data.py:test_local + assert_mpmath_equal( + sc.gammainc, + lambda z, b: mpmath.gammainc(z, b=b, regularized=True), + [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], + nan_ok=False, + rtol=1e-11, + ) + + def test_gammaincc(self): + # Larger arguments are tested in test_data.py:test_local + assert_mpmath_equal( + sc.gammaincc, + lambda z, a: mpmath.gammainc(z, a=a, regularized=True), + [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)], + nan_ok=False, + rtol=1e-11, + ) + + def test_gammaln(self): + # The real part of loggamma is log(|gamma(z)|). + def f(z): + return mpmath.loggamma(z).real + + assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()]) + + @pytest.mark.xfail(run=False) + def test_gegenbauer(self): + assert_mpmath_equal( + sc.eval_gegenbauer, + exception_to_nan(mpmath.gegenbauer), + [Arg(-1e3, 1e3), Arg(), Arg()], + ) + + def test_gegenbauer_int(self): + # Redefine functions to deal with numerical + mpmath issues + def gegenbauer(n, a, x): + # Avoid overflow at large `a` (mpmath would need an even larger + # dps to handle this correctly, so just skip this region) + if abs(a) > 1e100: + return np.nan + + # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these + # always correctly + if n == 0: + r = 1.0 + elif n == 1: + r = 2*a*x + else: + r = mpmath.gegenbauer(n, a, x) + + # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so + # compute the value by perturbing the result + if float(r) == 0 and a < -1 and float(a) == int(float(a)): + r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x) + if abs(r) < mpmath.mpf('1e-50'): + r = mpmath.mpf('0.0') + + # Differing overflow thresholds in scipy vs. mpmath + if abs(r) > 1e270: + return np.inf + return r + + def sc_gegenbauer(n, a, x): + r = sc.eval_gegenbauer(int(n), a, x) + # Differing overflow thresholds in scipy vs. mpmath + if abs(r) > 1e270: + return np.inf + return r + assert_mpmath_equal( + sc_gegenbauer, + exception_to_nan(gegenbauer), + [IntArg(0, 100), Arg(-1e9, 1e9), Arg()], + n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6, + ) + + # Check the small-x expansion + assert_mpmath_equal( + sc_gegenbauer, + exception_to_nan(gegenbauer), + [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))], + dps=100, ignore_inf_sign=True, + ) + + @pytest.mark.xfail(run=False) + def test_gegenbauer_complex(self): + assert_mpmath_equal( + lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x), + exception_to_nan(mpmath.gegenbauer), + [IntArg(0, 100), Arg(), ComplexArg()], + ) + + @nonfunctional_tooslow + def test_gegenbauer_complex_general(self): + assert_mpmath_equal( + lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x), + exception_to_nan(mpmath.gegenbauer), + [Arg(-1e3, 1e3), Arg(), ComplexArg()], + ) + + def test_hankel1(self): + assert_mpmath_equal( + sc.hankel1, + exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)), + [Arg(-1e20, 1e20), Arg()], + ) + + def test_hankel2(self): + assert_mpmath_equal( + sc.hankel2, + exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)), + [Arg(-1e20, 1e20), Arg()], + ) + + @pytest.mark.xfail(run=False, reason="issues at intermediately large orders") + def test_hermite(self): + assert_mpmath_equal( + lambda n, x: sc.eval_hermite(int(n), x), + exception_to_nan(mpmath.hermite), + [IntArg(0, 10000), Arg()], + ) + + # hurwitz: same as zeta + + def test_hyp0f1(self): + # mpmath reports no convergence unless maxterms is large enough + KW = dict(maxprec=400, maxterms=1500) + # n=500 (non-xslow default) fails for one bad point + assert_mpmath_equal( + sc.hyp0f1, + lambda a, x: mpmath.hyp0f1(a, x, **KW), + [Arg(-1e7, 1e7), Arg(0, 1e5)], + n=5000, + ) + # NB: The range of the second parameter ("z") is limited from below + # because of an overflow in the intermediate calculations. The way + # for fix it is to implement an asymptotic expansion for Bessel J + # (similar to what is implemented for Bessel I here). + + def test_hyp0f1_complex(self): + assert_mpmath_equal( + lambda a, z: sc.hyp0f1(a.real, z), + exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)), + [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))], + ) + # NB: The range of the first parameter ("v") are limited by an overflow + # in the intermediate calculations. Can be fixed by implementing an + # asymptotic expansion for Bessel functions for large order. + + def test_hyp1f1(self): + def mpmath_hyp1f1(a, b, x): + try: + return mpmath.hyp1f1(a, b, x) + except ZeroDivisionError: + return np.inf + + assert_mpmath_equal( + sc.hyp1f1, + mpmath_hyp1f1, + [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)], + n=500, + nan_ok=False, + ) + + @pytest.mark.xfail(run=False) + def test_hyp1f1_complex(self): + assert_mpmath_equal( + inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)), + exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)), + [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()], + n=2000, + ) + + @nonfunctional_tooslow + def test_hyp2f1_complex(self): + # SciPy's hyp2f1 seems to have performance and accuracy problems + assert_mpmath_equal( + lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x), + exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)), + [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()], + n=10, + ) + + @pytest.mark.xfail(run=False) + def test_hyperu(self): + assert_mpmath_equal( + sc.hyperu, + exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)), + [Arg(), Arg(), Arg()], + ) + + @pytest.mark.xfail_on_32bit("mpmath issue gh-342: " + "unsupported operand mpz, long for pow") + def test_igam_fac(self): + def mp_igam_fac(a, x): + return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a) + + assert_mpmath_equal( + _igam_fac, + mp_igam_fac, + [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)], + rtol=1e-10, + ) + + def test_j0(self): + # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x) + # and at large arguments the phase of the cosine loses precision. + # + # This is numerically expected behavior, so we compare only up to + # 1e8 = 1e15 * 1e-7 + assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)]) + assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5) + + def test_j1(self): + # See comment in test_j0 + assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)]) + assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5) + + @pytest.mark.xfail(run=False) + def test_jacobi(self): + assert_mpmath_equal( + sc.eval_jacobi, + exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), + [Arg(), Arg(), Arg(), Arg()], + ) + assert_mpmath_equal( + lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x), + exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)), + [IntArg(), Arg(), Arg(), Arg()], + ) + + def test_jacobi_int(self): + # Redefine functions to deal with numerical + mpmath issues + def jacobi(n, a, b, x): + # Mpmath does not handle n=0 case always correctly + if n == 0: + return 1.0 + return mpmath.jacobi(n, a, b, x) + assert_mpmath_equal( + lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x), + lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW), + [IntArg(), Arg(), Arg(), Arg()], + n=20000, + dps=50, + ) + + def test_kei(self): + def kei(x): + if x == 0: + # work around mpmath issue at x=0 + return -pi/4 + return exception_to_nan(mpmath.kei)(0, x, **HYPERKW) + assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000) + + def test_ker(self): + assert_mpmath_equal( + sc.ker, + exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)), + [Arg(-1e30, 1e30)], + n=1000, + ) + + @nonfunctional_tooslow + def test_laguerre(self): + assert_mpmath_equal( + trace_args(sc.eval_laguerre), + lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), + [Arg(), Arg()], + ) + + def test_laguerre_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_laguerre(int(n), x), + lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW), + [IntArg(), Arg()], + n=20000, + ) + + @pytest.mark.xfail_on_32bit("see gh-3551 for bad points") + def test_lambertw_real(self): + assert_mpmath_equal( + lambda x, k: sc.lambertw(x, int(k.real)), + lambda x, k: mpmath.lambertw(x, int(k.real)), + [ComplexArg(-np.inf, np.inf), IntArg(0, 10)], + rtol=1e-13, nan_ok=False, + ) + + def test_lanczos_sum_expg_scaled(self): + maxgamma = 171.624376956302725 + e = np.exp(1) + g = 6.024680040776729583740234375 + + def gamma(x): + with np.errstate(over='ignore'): + fac = ((x + g - 0.5)/e)**(x - 0.5) + if fac != np.inf: + res = fac*_lanczos_sum_expg_scaled(x) + else: + fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5)) + res = fac*_lanczos_sum_expg_scaled(x) + res *= fac + return res + + assert_mpmath_equal( + gamma, + mpmath.gamma, + [Arg(0, maxgamma, inclusive_a=False)], + rtol=1e-13, + ) + + @nonfunctional_tooslow + def test_legendre(self): + assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()]) + + def test_legendre_int(self): + assert_mpmath_equal( + lambda n, x: sc.eval_legendre(int(n), x), + lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), + [IntArg(), Arg()], + n=20000, + ) + + # Check the small-x expansion + assert_mpmath_equal( + lambda n, x: sc.eval_legendre(int(n), x), + lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW), + [IntArg(), FixedArg(np.logspace(-30, -4, 20))], + ) + + def test_legenp(self): + def lpnm(n, m, z): + try: + v = sc.lpmn(m, n, z)[0][-1,-1] + except ValueError: + return np.nan + if abs(v) > 1e306: + # harmonize overflow to inf + v = np.inf * np.sign(v.real) + return v + + def lpnm_2(n, m, z): + v = sc.lpmv(m, n, z) + if abs(v) > 1e306: + # harmonize overflow to inf + v = np.inf * np.sign(v.real) + return v + + def legenp(n, m, z): + if (z == 1 or z == -1) and int(n) == n: + # Special case (mpmath may give inf, we take the limit by + # continuity) + if m == 0: + if n < 0: + n = -n - 1 + return mpmath.power(mpmath.sign(z), n) + else: + return 0 + + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + + typ = 2 if abs(z) < 1 else 3 + v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ) + + if abs(v) > 1e306: + # harmonize overflow to inf + v = mpmath.inf * mpmath.sign(v.real) + + return v + + assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()]) + + assert_mpmath_equal( + lpnm_2, + legenp, + [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)], + atol=1e-10, + ) + + def test_legenp_complex_2(self): + def clpnm(n, m, z): + try: + return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1] + except ValueError: + return np.nan + + def legenp(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2) + + # mpmath is quite slow here + x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) + y = np.array([-1e3, -0.5, 0.5, 1.3]) + z = (x[:,None] + 1j*y[None,:]).ravel() + + assert_mpmath_equal( + clpnm, + legenp, + [FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg(z)], + rtol=1e-6, + n=500, + ) + + def test_legenp_complex_3(self): + def clpnm(n, m, z): + try: + return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1] + except ValueError: + return np.nan + + def legenp(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3) + + # mpmath is quite slow here + x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3]) + y = np.array([-1e3, -0.5, 0.5, 1.3]) + z = (x[:,None] + 1j*y[None,:]).ravel() + + assert_mpmath_equal( + clpnm, + legenp, + [FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg([-2, -1, 0, 1, 2, 10]), + FixedArg(z)], + rtol=1e-6, + n=500, + ) + + @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1") + def test_legenq(self): + def lqnm(n, m, z): + return sc.lqmn(m, n, z)[0][-1,-1] + + def legenq(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenq)(n, m, z, type=2) + + assert_mpmath_equal( + lqnm, + legenq, + [IntArg(0, 100), IntArg(0, 100), Arg()], + ) + + @nonfunctional_tooslow + def test_legenq_complex(self): + def lqnm(n, m, z): + return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1] + + def legenq(n, m, z): + if abs(z) < 1e-15: + # mpmath has bad performance here + return np.nan + return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2) + + assert_mpmath_equal( + lqnm, + legenq, + [IntArg(0, 100), IntArg(0, 100), ComplexArg()], + n=100, + ) + + def test_lgam1p(self): + def param_filter(x): + # Filter the poles + return np.where((np.floor(x) == x) & (x <= 0), False, True) + + def mp_lgam1p(z): + # The real part of loggamma is log(|gamma(z)|) + return mpmath.loggamma(1 + z).real + + assert_mpmath_equal( + _lgam1p, + mp_lgam1p, + [Arg()], + rtol=1e-13, + dps=100, + param_filter=param_filter, + ) + + def test_loggamma(self): + def mpmath_loggamma(z): + try: + res = mpmath.loggamma(z) + except ValueError: + res = complex(np.nan, np.nan) + return res + + assert_mpmath_equal( + sc.loggamma, + mpmath_loggamma, + [ComplexArg()], + nan_ok=False, + distinguish_nan_and_inf=False, + rtol=5e-14, + ) + + @pytest.mark.xfail(run=False) + def test_pcfd(self): + def pcfd(v, x): + return sc.pbdv(v, x)[0] + assert_mpmath_equal( + pcfd, + exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)), + [Arg(), Arg()], + ) + + @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- " + "maybe different definition?") + def test_pcfv(self): + def pcfv(v, x): + return sc.pbvv(v, x)[0] + assert_mpmath_equal( + pcfv, + lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW), + [Arg(), Arg()], + n=1000, + ) + + def test_pcfw(self): + def pcfw(a, x): + return sc.pbwa(a, x)[0] + + def dpcfw(a, x): + return sc.pbwa(a, x)[1] + + def mpmath_dpcfw(a, x): + return mpmath.diff(mpmath.pcfw, (a, x), (0, 1)) + + # The Zhang and Jin implementation only uses Taylor series and + # is thus accurate in only a very small range. + assert_mpmath_equal( + pcfw, + mpmath.pcfw, + [Arg(-5, 5), Arg(-5, 5)], + rtol=2e-8, + n=100, + ) + + assert_mpmath_equal( + dpcfw, + mpmath_dpcfw, + [Arg(-5, 5), Arg(-5, 5)], + rtol=2e-9, + n=100, + ) + + @pytest.mark.xfail(run=False, + reason="issues at large arguments (atol OK, rtol not) " + "and = _pep440.Version("1.0.0"): + # no workarounds needed + mppoch = mpmath.rf + else: + def mppoch(a, m): + # deal with cases where the result in double precision + # hits exactly a non-positive integer, but the + # corresponding extended-precision mpf floats don't + if float(a + m) == int(a + m) and float(a + m) <= 0: + a = mpmath.mpf(a) + m = int(a + m) - a + return mpmath.rf(a, m) + + assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400) + + def test_sinpi(self): + eps = np.finfo(float).eps + assert_mpmath_equal( + _sinpi, + mpmath.sinpi, + [Arg()], + nan_ok=False, + rtol=2*eps, + ) + + def test_sinpi_complex(self): + assert_mpmath_equal( + _sinpi, + mpmath.sinpi, + [ComplexArg()], + nan_ok=False, + rtol=2e-14, + ) + + def test_shi(self): + def shi(x): + return sc.shichi(x)[0] + assert_mpmath_equal(shi, mpmath.shi, [Arg()]) + # check asymptotic series cross-over + assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])]) + + def test_shi_complex(self): + def shi(z): + return sc.shichi(z)[0] + # shi oscillates as Im[z] -> +- inf, so limit range + assert_mpmath_equal( + shi, + mpmath.shi, + [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))], + rtol=1e-12, + ) + + def test_si(self): + def si(x): + return sc.sici(x)[0] + assert_mpmath_equal(si, mpmath.si, [Arg()]) + + def test_si_complex(self): + def si(z): + return sc.sici(z)[0] + # si oscillates as Re[z] -> +- inf, so limit range + assert_mpmath_equal( + si, + mpmath.si, + [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))], + rtol=1e-12, + ) + + def test_spence(self): + # mpmath uses a different convention for the dilogarithm + def dilog(x): + return mpmath.polylog(2, 1 - x) + # Spence has a branch cut on the negative real axis + assert_mpmath_equal( + sc.spence, + exception_to_nan(dilog), + [Arg(0, np.inf)], + rtol=1e-14, + ) + + def test_spence_complex(self): + def dilog(z): + return mpmath.polylog(2, 1 - z) + assert_mpmath_equal( + sc.spence, + exception_to_nan(dilog), + [ComplexArg()], + rtol=1e-14, + ) + + def test_spherharm(self): + def spherharm(l, m, theta, phi): + if m > l: + return np.nan + return sc.sph_harm(m, l, phi, theta) + assert_mpmath_equal( + spherharm, + mpmath.spherharm, + [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)], + atol=1e-8, + n=6000, + dps=150, + ) + + def test_struveh(self): + assert_mpmath_equal( + sc.struve, + exception_to_nan(mpmath.struveh), + [Arg(-1e4, 1e4), Arg(0, 1e4)], + rtol=5e-10, + ) + + def test_struvel(self): + def mp_struvel(v, z): + if v < 0 and z < -v and abs(v) > 1000: + # larger DPS needed for correct results + old_dps = mpmath.mp.dps + try: + mpmath.mp.dps = 300 + return mpmath.struvel(v, z) + finally: + mpmath.mp.dps = old_dps + return mpmath.struvel(v, z) + + assert_mpmath_equal( + sc.modstruve, + exception_to_nan(mp_struvel), + [Arg(-1e4, 1e4), Arg(0, 1e4)], + rtol=5e-10, + ignore_inf_sign=True, + ) + + def test_wrightomega_real(self): + def mpmath_wrightomega_real(x): + return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) + + # For x < -1000 the Wright Omega function is just 0 to double + # precision, and for x > 1e21 it is just x to double + # precision. + assert_mpmath_equal( + sc.wrightomega, + mpmath_wrightomega_real, + [Arg(-1000, 1e21)], + rtol=5e-15, + atol=0, + nan_ok=False, + ) + + def test_wrightomega(self): + assert_mpmath_equal( + sc.wrightomega, + lambda z: _mpmath_wrightomega(z, 25), + [ComplexArg()], + rtol=1e-14, + nan_ok=False, + ) + + def test_hurwitz_zeta(self): + assert_mpmath_equal( + sc.zeta, + exception_to_nan(mpmath.zeta), + [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)], + ) + + def test_riemann_zeta(self): + assert_mpmath_equal( + sc.zeta, + lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf, + [Arg(-100, 100)], + nan_ok=False, + rtol=5e-13, + ) + + def test_zetac(self): + assert_mpmath_equal( + sc.zetac, + lambda x: mpmath.zeta(x) - 1 if x != 1 else mpmath.inf, + [Arg(-100, 100)], + nan_ok=False, + dps=45, + rtol=5e-13, + ) + + def test_boxcox(self): + + def mp_boxcox(x, lmbda): + x = mpmath.mp.mpf(x) + lmbda = mpmath.mp.mpf(lmbda) + if lmbda == 0: + return mpmath.mp.log(x) + else: + return mpmath.mp.powm1(x, lmbda) / lmbda + + assert_mpmath_equal( + sc.boxcox, + exception_to_nan(mp_boxcox), + [Arg(a=0, inclusive_a=False), Arg()], + n=200, + dps=60, + rtol=1e-13, + ) + + def test_boxcox1p(self): + + def mp_boxcox1p(x, lmbda): + x = mpmath.mp.mpf(x) + lmbda = mpmath.mp.mpf(lmbda) + one = mpmath.mp.mpf(1) + if lmbda == 0: + return mpmath.mp.log(one + x) + else: + return mpmath.mp.powm1(one + x, lmbda) / lmbda + + assert_mpmath_equal( + sc.boxcox1p, + exception_to_nan(mp_boxcox1p), + [Arg(a=-1, inclusive_a=False), Arg()], + n=200, + dps=60, + rtol=1e-13, + ) + + 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, + ) + + 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()] + ) + + def test_spherical_yn(self): + def mp_spherical_yn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.bessely(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_yn(int(n), z), + exception_to_nan(mp_spherical_yn), + [IntArg(0, 200), Arg(-1e10, 1e10)], + dps=100, + ) + + def test_spherical_yn_complex(self): + def mp_spherical_yn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.bessely(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_yn(int(n.real), z), + exception_to_nan(mp_spherical_yn), + [IntArg(0, 200), ComplexArg()], + ) + + def test_spherical_in(self): + def mp_spherical_in(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besseli(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_in(int(n), z), + exception_to_nan(mp_spherical_in), + [IntArg(0, 200), Arg()], + dps=200, + atol=10**(-278), + ) + + def test_spherical_in_complex(self): + def mp_spherical_in(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besseli(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_in(int(n.real), z), + exception_to_nan(mp_spherical_in), + [IntArg(0, 200), ComplexArg()], + ) + + def test_spherical_kn(self): + def mp_spherical_kn(n, z): + out = (mpmath.besselk(n + mpmath.mpf(1)/2, z) * + mpmath.sqrt(mpmath.pi/(2*mpmath.mpmathify(z)))) + if mpmath.mpmathify(z).imag == 0: + return out.real + else: + return out + + assert_mpmath_equal( + lambda n, z: sc.spherical_kn(int(n), z), + exception_to_nan(mp_spherical_kn), + [IntArg(0, 150), Arg()], + dps=100, + ) + + @pytest.mark.xfail(run=False, + reason="Accuracy issues near z = -1 inherited from kv.") + def test_spherical_kn_complex(self): + def mp_spherical_kn(n, z): + arg = mpmath.mpmathify(z) + out = (mpmath.besselk(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_kn(int(n.real), z), + exception_to_nan(mp_spherical_kn), + [IntArg(0, 200), ComplexArg()], + dps=200, + ) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..de28fec4e59094354cf98bc93751e11bdefc909d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py @@ -0,0 +1,64 @@ +"""Test how the ufuncs in special handle nan inputs. + +""" +from typing import Callable + +import numpy as np +from numpy.testing import assert_array_equal, assert_, suppress_warnings +import pytest +import scipy.special as sc + + +KNOWNFAILURES: dict[str, Callable] = {} + +POSTPROCESSING: dict[str, Callable] = {} + + +def _get_ufuncs(): + ufuncs = [] + ufunc_names = [] + for name in sorted(sc.__dict__): + obj = sc.__dict__[name] + if not isinstance(obj, np.ufunc): + continue + msg = KNOWNFAILURES.get(obj) + if msg is None: + ufuncs.append(obj) + ufunc_names.append(name) + else: + fail = pytest.mark.xfail(run=False, reason=msg) + ufuncs.append(pytest.param(obj, marks=fail)) + ufunc_names.append(name) + return ufuncs, ufunc_names + + +UFUNCS, UFUNC_NAMES = _get_ufuncs() + + +@pytest.mark.parametrize("func", UFUNCS, ids=UFUNC_NAMES) +def test_nan_inputs(func): + args = (np.nan,)*func.nin + with suppress_warnings() as sup: + # Ignore warnings about unsafe casts from legacy wrappers + sup.filter(RuntimeWarning, + "floating point number truncated to an integer") + try: + with suppress_warnings() as sup: + sup.filter(DeprecationWarning) + res = func(*args) + except TypeError: + # One of the arguments doesn't take real inputs + return + if func in POSTPROCESSING: + res = POSTPROCESSING[func](*res) + + msg = f"got {res} instead of nan" + assert_array_equal(np.isnan(res), True, err_msg=msg) + + +def test_legacy_cast(): + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, + "floating point number truncated to an integer") + res = sc.bdtrc(np.nan, 1, 0.5) + assert_(np.isnan(res)) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9b689b34384585cc65204000febcb99c910d55 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py @@ -0,0 +1,77 @@ +import numpy as np +from numpy.testing import assert_equal, assert_allclose +import scipy.special as sc + + +def test_ndtr(): + assert_equal(sc.ndtr(0), 0.5) + assert_allclose(sc.ndtr(1), 0.8413447460685429) + + +class TestNdtri: + + def test_zero(self): + assert sc.ndtri(0.5) == 0.0 + + def test_asymptotes(self): + assert_equal(sc.ndtri([0.0, 1.0]), [-np.inf, np.inf]) + + def test_outside_of_domain(self): + assert all(np.isnan(sc.ndtri([-1.5, 1.5]))) + + +class TestLogNdtr: + + # The expected values in these tests were computed with mpmath: + # + # def log_ndtr_mp(x): + # return mpmath.log(mpmath.ncdf(x)) + # + + def test_log_ndtr_moderate_le8(self): + x = np.array([-0.75, -0.25, 0, 0.5, 1.5, 2.5, 3, 4, 5, 7, 8]) + expected = np.array([-1.4844482299196562, + -0.9130617648111351, + -0.6931471805599453, + -0.3689464152886564, + -0.06914345561223398, + -0.006229025485860002, + -0.0013508099647481938, + -3.167174337748927e-05, + -2.866516129637636e-07, + -1.279812543886654e-12, + -6.220960574271786e-16]) + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=1e-14) + + def test_log_ndtr_values_8_16(self): + x = np.array([8.001, 8.06, 8.15, 8.5, 10, 12, 14, 16]) + expected = [-6.170639424817055e-16, + -3.814722443652823e-16, + -1.819621363526629e-16, + -9.479534822203318e-18, + -7.619853024160525e-24, + -1.776482112077679e-33, + -7.7935368191928e-45, + -6.388754400538087e-58] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=5e-14) + + def test_log_ndtr_values_16_31(self): + x = np.array([16.15, 20.3, 21.4, 26.2, 30.9]) + expected = [-5.678084565148492e-59, + -6.429244467698346e-92, + -6.680402412553295e-102, + -1.328698078458869e-151, + -5.972288641838264e-210] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=2e-13) + + def test_log_ndtr_values_gt31(self): + x = np.array([31.6, 32.8, 34.9, 37.1]) + expected = [-1.846036234858162e-219, + -2.9440539964066835e-236, + -3.71721649450857e-267, + -1.4047119663106221e-301] + y = sc.log_ndtr(x) + assert_allclose(y, expected, rtol=3e-13) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py new file mode 100644 index 0000000000000000000000000000000000000000..82a9fbd3bcda117770e00018facda3f56630a6bc --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py @@ -0,0 +1,94 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose +from scipy.special import log_ndtr, ndtri_exp +from scipy.special._testutils import assert_func_equal + + +def log_ndtr_ndtri_exp(y): + return log_ndtr(ndtri_exp(y)) + + +@pytest.fixture(scope="class") +def uniform_random_points(): + random_state = np.random.RandomState(1234) + points = random_state.random_sample(1000) + return points + + +class TestNdtriExp: + """Tests that ndtri_exp is sufficiently close to an inverse of log_ndtr. + + We have separate tests for the five intervals (-inf, -10), + [-10, -2), [-2, -0.14542), [-0.14542, -1e-6), and [-1e-6, 0). + ndtri_exp(y) is computed in three different ways depending on if y + is in (-inf, -2), [-2, log(1 - exp(-2))], or [log(1 - exp(-2), 0). + Each of these intervals is given its own test with two additional tests + for handling very small values and values very close to zero. + """ + + @pytest.mark.parametrize( + "test_input", [-1e1, -1e2, -1e10, -1e20, -np.finfo(float).max] + ) + def test_very_small_arg(self, test_input, uniform_random_points): + scale = test_input + points = scale * (0.5 * uniform_random_points + 0.5) + assert_func_equal( + log_ndtr_ndtri_exp, + lambda y: y, points, + rtol=1e-14, + nan_ok=True + ) + + @pytest.mark.parametrize( + "interval,expected_rtol", + [ + ((-10, -2), 1e-14), + ((-2, -0.14542), 1e-12), + ((-0.14542, -1e-6), 1e-10), + ((-1e-6, 0), 1e-6), + ], + ) + def test_in_interval(self, interval, expected_rtol, uniform_random_points): + left, right = interval + points = (right - left) * uniform_random_points + left + assert_func_equal( + log_ndtr_ndtri_exp, + lambda y: y, points, + rtol=expected_rtol, + nan_ok=True + ) + + def test_extreme(self): + # bigneg is not quite the largest negative double precision value. + # Here's why: + # The round-trip calculation + # y = ndtri_exp(bigneg) + # bigneg2 = log_ndtr(y) + # where bigneg is a very large negative value, would--with infinite + # precision--result in bigneg2 == bigneg. When bigneg is large enough, + # y is effectively equal to -sqrt(2)*sqrt(-bigneg), and log_ndtr(y) is + # effectively -(y/sqrt(2))**2. If we use bigneg = np.finfo(float).min, + # then by construction, the theoretical value is the most negative + # finite value that can be represented with 64 bit float point. This + # means tiny changes in how the computation proceeds can result in the + # return value being -inf. (E.g. changing the constant representation + # of 1/sqrt(2) from 0.7071067811865475--which is the value returned by + # 1/np.sqrt(2)--to 0.7071067811865476--which is the most accurate 64 + # bit floating point representation of 1/sqrt(2)--results in the + # round-trip that starts with np.finfo(float).min returning -inf. So + # we'll move the bigneg value a few ULPs towards 0 to avoid this + # sensitivity. + # Use the reduce method to apply nextafter four times. + bigneg = np.nextafter.reduce([np.finfo(float).min, 0, 0, 0, 0]) + # tinyneg is approx. -2.225e-308. + tinyneg = -np.finfo(float).tiny + x = np.array([tinyneg, bigneg]) + result = log_ndtr_ndtri_exp(x) + assert_allclose(result, x, rtol=1e-12) + + def test_asymptotes(self): + assert_equal(ndtri_exp([-np.inf, 0.0]), [-np.inf, np.inf]) + + def test_outside_domain(self): + assert np.isnan(ndtri_exp(1.0)) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py new file mode 100644 index 0000000000000000000000000000000000000000..5b644a62c0b64b022a171da423953f1ff2e9b79d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py @@ -0,0 +1,804 @@ +import numpy as np +from numpy import array, sqrt +from numpy.testing import (assert_array_almost_equal, assert_equal, + assert_almost_equal, assert_allclose) +from pytest import raises as assert_raises + +from scipy import integrate +import scipy.special as sc +from scipy.special import gamma +import scipy.special._orthogonal as orth + + +class TestCheby: + def test_chebyc(self): + C0 = orth.chebyc(0) + C1 = orth.chebyc(1) + with np.errstate(all='ignore'): + C2 = orth.chebyc(2) + C3 = orth.chebyc(3) + C4 = orth.chebyc(4) + C5 = orth.chebyc(5) + + assert_array_almost_equal(C0.c,[2],13) + assert_array_almost_equal(C1.c,[1,0],13) + assert_array_almost_equal(C2.c,[1,0,-2],13) + assert_array_almost_equal(C3.c,[1,0,-3,0],13) + assert_array_almost_equal(C4.c,[1,0,-4,0,2],13) + assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13) + + def test_chebys(self): + S0 = orth.chebys(0) + S1 = orth.chebys(1) + S2 = orth.chebys(2) + S3 = orth.chebys(3) + S4 = orth.chebys(4) + S5 = orth.chebys(5) + assert_array_almost_equal(S0.c,[1],13) + assert_array_almost_equal(S1.c,[1,0],13) + assert_array_almost_equal(S2.c,[1,0,-1],13) + assert_array_almost_equal(S3.c,[1,0,-2,0],13) + assert_array_almost_equal(S4.c,[1,0,-3,0,1],13) + assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13) + + def test_chebyt(self): + T0 = orth.chebyt(0) + T1 = orth.chebyt(1) + T2 = orth.chebyt(2) + T3 = orth.chebyt(3) + T4 = orth.chebyt(4) + T5 = orth.chebyt(5) + assert_array_almost_equal(T0.c,[1],13) + assert_array_almost_equal(T1.c,[1,0],13) + assert_array_almost_equal(T2.c,[2,0,-1],13) + assert_array_almost_equal(T3.c,[4,0,-3,0],13) + assert_array_almost_equal(T4.c,[8,0,-8,0,1],13) + assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13) + + def test_chebyu(self): + U0 = orth.chebyu(0) + U1 = orth.chebyu(1) + U2 = orth.chebyu(2) + U3 = orth.chebyu(3) + U4 = orth.chebyu(4) + U5 = orth.chebyu(5) + assert_array_almost_equal(U0.c,[1],13) + assert_array_almost_equal(U1.c,[2,0],13) + assert_array_almost_equal(U2.c,[4,0,-1],13) + assert_array_almost_equal(U3.c,[8,0,-4,0],13) + assert_array_almost_equal(U4.c,[16,0,-12,0,1],13) + assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13) + + +class TestGegenbauer: + + def test_gegenbauer(self): + a = 5*np.random.random() - 0.5 + if np.any(a == 0): + a = -0.2 + Ca0 = orth.gegenbauer(0,a) + Ca1 = orth.gegenbauer(1,a) + Ca2 = orth.gegenbauer(2,a) + Ca3 = orth.gegenbauer(3,a) + Ca4 = orth.gegenbauer(4,a) + Ca5 = orth.gegenbauer(5,a) + + assert_array_almost_equal(Ca0.c,array([1]),13) + assert_array_almost_equal(Ca1.c,array([2*a,0]),13) + assert_array_almost_equal(Ca2.c,array([2*a*(a+1),0,-a]),13) + assert_array_almost_equal(Ca3.c,array([4*sc.poch(a,3),0,-6*a*(a+1), + 0])/3.0,11) + assert_array_almost_equal(Ca4.c,array([4*sc.poch(a,4),0,-12*sc.poch(a,3), + 0,3*a*(a+1)])/6.0,11) + assert_array_almost_equal(Ca5.c,array([4*sc.poch(a,5),0,-20*sc.poch(a,4), + 0,15*sc.poch(a,3),0])/15.0,11) + + +class TestHermite: + def test_hermite(self): + H0 = orth.hermite(0) + H1 = orth.hermite(1) + H2 = orth.hermite(2) + H3 = orth.hermite(3) + H4 = orth.hermite(4) + H5 = orth.hermite(5) + assert_array_almost_equal(H0.c,[1],13) + assert_array_almost_equal(H1.c,[2,0],13) + assert_array_almost_equal(H2.c,[4,0,-2],13) + assert_array_almost_equal(H3.c,[8,0,-12,0],13) + assert_array_almost_equal(H4.c,[16,0,-48,0,12],12) + assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12) + + def test_hermitenorm(self): + # He_n(x) = 2**(-n/2) H_n(x/sqrt(2)) + psub = np.poly1d([1.0/sqrt(2),0]) + H0 = orth.hermitenorm(0) + H1 = orth.hermitenorm(1) + H2 = orth.hermitenorm(2) + H3 = orth.hermitenorm(3) + H4 = orth.hermitenorm(4) + H5 = orth.hermitenorm(5) + he0 = orth.hermite(0)(psub) + he1 = orth.hermite(1)(psub) / sqrt(2) + he2 = orth.hermite(2)(psub) / 2.0 + he3 = orth.hermite(3)(psub) / (2*sqrt(2)) + he4 = orth.hermite(4)(psub) / 4.0 + he5 = orth.hermite(5)(psub) / (4.0*sqrt(2)) + + assert_array_almost_equal(H0.c,he0.c,13) + assert_array_almost_equal(H1.c,he1.c,13) + assert_array_almost_equal(H2.c,he2.c,13) + assert_array_almost_equal(H3.c,he3.c,13) + assert_array_almost_equal(H4.c,he4.c,13) + assert_array_almost_equal(H5.c,he5.c,13) + + +class TestShLegendre: + def test_sh_legendre(self): + # P*_n(x) = P_n(2x-1) + psub = np.poly1d([2,-1]) + Ps0 = orth.sh_legendre(0) + Ps1 = orth.sh_legendre(1) + Ps2 = orth.sh_legendre(2) + Ps3 = orth.sh_legendre(3) + Ps4 = orth.sh_legendre(4) + Ps5 = orth.sh_legendre(5) + pse0 = orth.legendre(0)(psub) + pse1 = orth.legendre(1)(psub) + pse2 = orth.legendre(2)(psub) + pse3 = orth.legendre(3)(psub) + pse4 = orth.legendre(4)(psub) + pse5 = orth.legendre(5)(psub) + assert_array_almost_equal(Ps0.c,pse0.c,13) + assert_array_almost_equal(Ps1.c,pse1.c,13) + assert_array_almost_equal(Ps2.c,pse2.c,13) + assert_array_almost_equal(Ps3.c,pse3.c,13) + assert_array_almost_equal(Ps4.c,pse4.c,12) + assert_array_almost_equal(Ps5.c,pse5.c,12) + + +class TestShChebyt: + def test_sh_chebyt(self): + # T*_n(x) = T_n(2x-1) + psub = np.poly1d([2,-1]) + Ts0 = orth.sh_chebyt(0) + Ts1 = orth.sh_chebyt(1) + Ts2 = orth.sh_chebyt(2) + Ts3 = orth.sh_chebyt(3) + Ts4 = orth.sh_chebyt(4) + Ts5 = orth.sh_chebyt(5) + tse0 = orth.chebyt(0)(psub) + tse1 = orth.chebyt(1)(psub) + tse2 = orth.chebyt(2)(psub) + tse3 = orth.chebyt(3)(psub) + tse4 = orth.chebyt(4)(psub) + tse5 = orth.chebyt(5)(psub) + assert_array_almost_equal(Ts0.c,tse0.c,13) + assert_array_almost_equal(Ts1.c,tse1.c,13) + assert_array_almost_equal(Ts2.c,tse2.c,13) + assert_array_almost_equal(Ts3.c,tse3.c,13) + assert_array_almost_equal(Ts4.c,tse4.c,12) + assert_array_almost_equal(Ts5.c,tse5.c,12) + + +class TestShChebyu: + def test_sh_chebyu(self): + # U*_n(x) = U_n(2x-1) + psub = np.poly1d([2,-1]) + Us0 = orth.sh_chebyu(0) + Us1 = orth.sh_chebyu(1) + Us2 = orth.sh_chebyu(2) + Us3 = orth.sh_chebyu(3) + Us4 = orth.sh_chebyu(4) + Us5 = orth.sh_chebyu(5) + use0 = orth.chebyu(0)(psub) + use1 = orth.chebyu(1)(psub) + use2 = orth.chebyu(2)(psub) + use3 = orth.chebyu(3)(psub) + use4 = orth.chebyu(4)(psub) + use5 = orth.chebyu(5)(psub) + assert_array_almost_equal(Us0.c,use0.c,13) + assert_array_almost_equal(Us1.c,use1.c,13) + assert_array_almost_equal(Us2.c,use2.c,13) + assert_array_almost_equal(Us3.c,use3.c,13) + assert_array_almost_equal(Us4.c,use4.c,12) + assert_array_almost_equal(Us5.c,use5.c,11) + + +class TestShJacobi: + def test_sh_jacobi(self): + # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1) + def conv(n, p): + return gamma(n + 1) * gamma(n + p) / gamma(2 * n + p) + psub = np.poly1d([2,-1]) + q = 4 * np.random.random() + p = q-1 + 2*np.random.random() + # print("shifted jacobi p,q = ", p, q) + G0 = orth.sh_jacobi(0,p,q) + G1 = orth.sh_jacobi(1,p,q) + G2 = orth.sh_jacobi(2,p,q) + G3 = orth.sh_jacobi(3,p,q) + G4 = orth.sh_jacobi(4,p,q) + G5 = orth.sh_jacobi(5,p,q) + ge0 = orth.jacobi(0,p-q,q-1)(psub) * conv(0,p) + ge1 = orth.jacobi(1,p-q,q-1)(psub) * conv(1,p) + ge2 = orth.jacobi(2,p-q,q-1)(psub) * conv(2,p) + ge3 = orth.jacobi(3,p-q,q-1)(psub) * conv(3,p) + ge4 = orth.jacobi(4,p-q,q-1)(psub) * conv(4,p) + ge5 = orth.jacobi(5,p-q,q-1)(psub) * conv(5,p) + + assert_array_almost_equal(G0.c,ge0.c,13) + assert_array_almost_equal(G1.c,ge1.c,13) + assert_array_almost_equal(G2.c,ge2.c,13) + assert_array_almost_equal(G3.c,ge3.c,13) + assert_array_almost_equal(G4.c,ge4.c,13) + assert_array_almost_equal(G5.c,ge5.c,13) + + +class TestCall: + def test_call(self): + poly = [] + for n in range(5): + poly.extend([x.strip() for x in + (""" + orth.jacobi(%(n)d,0.3,0.9) + orth.sh_jacobi(%(n)d,0.3,0.9) + orth.genlaguerre(%(n)d,0.3) + orth.laguerre(%(n)d) + orth.hermite(%(n)d) + orth.hermitenorm(%(n)d) + orth.gegenbauer(%(n)d,0.3) + orth.chebyt(%(n)d) + orth.chebyu(%(n)d) + orth.chebyc(%(n)d) + orth.chebys(%(n)d) + orth.sh_chebyt(%(n)d) + orth.sh_chebyu(%(n)d) + orth.legendre(%(n)d) + orth.sh_legendre(%(n)d) + """ % dict(n=n)).split() + ]) + with np.errstate(all='ignore'): + for pstr in poly: + p = eval(pstr) + assert_almost_equal(p(0.315), np.poly1d(p.coef)(0.315), + err_msg=pstr) + + +class TestGenlaguerre: + def test_regression(self): + assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.) + assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.) + assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2])) + assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2])) + + +def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N, + rtol=1e-15, atol=5e-14): + # this test is copied from numpy's TestGauss in test_hermite.py + x, w, mu = root_func(N, True) + + n = np.arange(N, dtype=np.dtype("long")) + v = eval_func(n[:,np.newaxis], x) + vv = np.dot(v*w, v.T) + vd = 1 / np.sqrt(vv.diagonal()) + vv = vd[:, np.newaxis] * vv * vd + assert_allclose(vv, np.eye(N), rtol, atol) + + # check that the integral of 1 is correct + assert_allclose(w.sum(), mu, rtol, atol) + + # compare the results of integrating a function with quad. + def f(x): + return x ** 3 - 3 * x ** 2 + x - 2 + resI = integrate.quad(lambda x: f(x)*weight_func(x), a, b) + resG = np.vdot(f(x), w) + rtol = 1e-6 if 1e-6 < resI[1] else resI[1] * 10 + assert_allclose(resI[0], resG, rtol=rtol) + +def test_roots_jacobi(): + def rf(a, b): + return lambda n, mu: sc.roots_jacobi(n, a, b, mu) + def ef(a, b): + return lambda n, x: sc.eval_jacobi(n, a, b, x) + def wf(a, b): + return lambda x: (1 - x) ** a * (1 + x) ** b + + vgq = verify_gauss_quad + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5) + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., + 25, atol=1e-12) + vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., + 100, atol=1e-11) + + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5) + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13) + vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=2e-12) + + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12) + + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5) + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13) + vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=3e-13) + + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5) + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25, + atol=1.1e-14) + vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., + 100, atol=1e-13) + + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13) + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 25, atol=2e-13) + vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., + 100, atol=1e-11) + + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 5, atol=2e-13) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 25, atol=1e-12) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 100, atol=1e-11) + vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 250, atol=1e-11) + + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 5, + atol=1e-12) + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 25, + atol=1e-11) + vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 100, + atol=1e-10) + + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 5, + atol=1e-12) + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 25, + atol=1e-11) + vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 100, + atol=1e-10) + + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 5, + atol=1e-12) + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 25, + atol=1e-11) + vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 100, + atol=1e-10) + + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5) + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 25, + atol=1e-13) + vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 100, + atol=1e-13) + + # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x) + xj, wj = sc.roots_jacobi(6, 0.0, 0.0) + xl, wl = sc.roots_legendre(6) + assert_allclose(xj, xl, 1e-14, 1e-14) + assert_allclose(wj, wl, 1e-14, 1e-14) + + # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x) + xj, wj = sc.roots_jacobi(6, 4.0, 4.0) + xc, wc = sc.roots_gegenbauer(6, 4.5) + assert_allclose(xj, xc, 1e-14, 1e-14) + assert_allclose(wj, wc, 1e-14, 1e-14) + + x, w = sc.roots_jacobi(5, 2, 3, False) + y, v, m = sc.roots_jacobi(5, 2, 3, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(wf(2,3), -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_jacobi, 0, 1, 1) + assert_raises(ValueError, sc.roots_jacobi, 3.3, 1, 1) + assert_raises(ValueError, sc.roots_jacobi, 3, -2, 1) + assert_raises(ValueError, sc.roots_jacobi, 3, 1, -2) + assert_raises(ValueError, sc.roots_jacobi, 3, -2, -2) + +def test_roots_sh_jacobi(): + def rf(a, b): + return lambda n, mu: sc.roots_sh_jacobi(n, a, b, mu) + def ef(a, b): + return lambda n, x: sc.eval_sh_jacobi(n, a, b, x) + def wf(a, b): + return lambda x: (1.0 - x) ** (a - b) * x ** (b - 1.0) + + vgq = verify_gauss_quad + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., 5) + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., + 25, atol=1e-12) + vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., + 100, atol=1e-11) + + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 5) + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 25, atol=1e-13) + vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 100, atol=1e-12) + + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 5) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 25, atol=1.5e-13) + vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 100, atol=2e-12) + + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 5) + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 25, atol=1e-13) + vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 100, atol=1e-12) + + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 5) + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 25) + vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., + 100, atol=1e-13) + + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 5, atol=1e-12) + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 25, atol=1e-11) + vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 100, atol=1e-10) + + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 5, atol=3.5e-14) + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 25, atol=2e-13) + vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., + 100, atol=1e-12) + + x, w = sc.roots_sh_jacobi(5, 3, 2, False) + y, v, m = sc.roots_sh_jacobi(5, 3, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(wf(3,2), 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_jacobi, 0, 1, 1) + assert_raises(ValueError, sc.roots_sh_jacobi, 3.3, 1, 1) + assert_raises(ValueError, sc.roots_sh_jacobi, 3, 1, 2) # p - q <= -1 + assert_raises(ValueError, sc.roots_sh_jacobi, 3, 2, -1) # q <= 0 + assert_raises(ValueError, sc.roots_sh_jacobi, 3, -2, -1) # both + +def test_roots_hermite(): + rootf = sc.roots_hermite + evalf = sc.eval_hermite + weightf = orth.hermite(5).weight_func + + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12) + + # Golub-Welsch branch + x, w = sc.roots_hermite(5, False) + y, v, m = sc.roots_hermite(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -np.inf, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + # Asymptotic branch (switch over at n >= 150) + x, w = sc.roots_hermite(200, False) + y, v, m = sc.roots_hermite(200, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + assert_allclose(sum(v), m, 1e-14, 1e-14) + + assert_raises(ValueError, sc.roots_hermite, 0) + assert_raises(ValueError, sc.roots_hermite, 3.3) + +def test_roots_hermite_asy(): + # Recursion for Hermite functions + def hermite_recursion(n, nodes): + H = np.zeros((n, nodes.size)) + H[0,:] = np.pi**(-0.25) * np.exp(-0.5*nodes**2) + if n > 1: + H[1,:] = sqrt(2.0) * nodes * H[0,:] + for k in range(2, n): + H[k,:] = sqrt(2.0/k) * nodes * H[k-1,:] - sqrt((k-1.0)/k) * H[k-2,:] + return H + + # This tests only the nodes + def test(N, rtol=1e-15, atol=1e-14): + x, w = orth._roots_hermite_asy(N) + H = hermite_recursion(N+1, x) + assert_allclose(H[-1,:], np.zeros(N), rtol, atol) + assert_allclose(sum(w), sqrt(np.pi), rtol, atol) + + test(150, atol=1e-12) + test(151, atol=1e-12) + test(300, atol=1e-12) + test(301, atol=1e-12) + test(500, atol=1e-12) + test(501, atol=1e-12) + test(999, atol=1e-12) + test(1000, atol=1e-12) + test(2000, atol=1e-12) + test(5000, atol=1e-12) + +def test_roots_hermitenorm(): + rootf = sc.roots_hermitenorm + evalf = sc.eval_hermitenorm + weightf = orth.hermitenorm(5).weight_func + + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13) + verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12) + + x, w = sc.roots_hermitenorm(5, False) + y, v, m = sc.roots_hermitenorm(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -np.inf, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_hermitenorm, 0) + assert_raises(ValueError, sc.roots_hermitenorm, 3.3) + +def test_roots_gegenbauer(): + def rootf(a): + return lambda n, mu: sc.roots_gegenbauer(n, a, mu) + def evalf(a): + return lambda n, x: sc.eval_gegenbauer(n, a, x) + def weightf(a): + return lambda x: (1 - x ** 2) ** (a - 0.5) + + vgq = verify_gauss_quad + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 5) + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 25, atol=1e-12) + vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 100, atol=1e-11) + + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 5) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 25, atol=1e-13) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 100, atol=1e-12) + + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 5) + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 25, atol=1e-13) + vgq(rootf(1), evalf(1), weightf(1), -1., 1., 100, atol=1e-12) + + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 5) + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 25, atol=1e-13) + vgq(rootf(10), evalf(10), weightf(10), -1., 1., 100, atol=1e-12) + + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 5, atol=1e-13) + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 25, atol=1e-12) + vgq(rootf(50), evalf(50), weightf(50), -1., 1., 100, atol=1e-11) + + # Alpha=170 is where the approximation used in roots_gegenbauer changes + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 5, atol=1e-13) + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 25, atol=1e-12) + vgq(rootf(170), evalf(170), weightf(170), -1., 1., 100, atol=1e-11) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 5, atol=1.25e-13) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 25, atol=1e-12) + vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 100, atol=1e-11) + + # Test for failures, e.g. overflows, resulting from large alphas + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 5, atol=1e-13) + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 25, atol=1e-12) + vgq(rootf(238), evalf(238), weightf(238), -1., 1., 100, atol=1e-11) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 5, atol=1e-12) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 25, atol=1e-11) + vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 100, atol=1e-10) + + # this is a special case that the old code supported. + # when alpha = 0, the gegenbauer polynomial is uniformly 0. but it goes + # to a scaled down copy of T_n(x) there. + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 5) + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 25) + vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 100, atol=1e-12) + + x, w = sc.roots_gegenbauer(5, 2, False) + y, v, m = sc.roots_gegenbauer(5, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf(2), -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_gegenbauer, 0, 2) + assert_raises(ValueError, sc.roots_gegenbauer, 3.3, 2) + assert_raises(ValueError, sc.roots_gegenbauer, 3, -.75) + +def test_roots_chebyt(): + weightf = orth.chebyt(5).weight_func + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 25) + verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 100, + atol=1e-12) + + x, w = sc.roots_chebyt(5, False) + y, v, m = sc.roots_chebyt(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyt, 0) + assert_raises(ValueError, sc.roots_chebyt, 3.3) + +def test_chebyt_symmetry(): + x, w = sc.roots_chebyt(21) + pos, neg = x[:10], x[11:] + assert_equal(neg, -pos[::-1]) + assert_equal(x[10], 0) + +def test_roots_chebyu(): + weightf = orth.chebyu(5).weight_func + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 25) + verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 100) + + x, w = sc.roots_chebyu(5, False) + y, v, m = sc.roots_chebyu(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyu, 0) + assert_raises(ValueError, sc.roots_chebyu, 3.3) + +def test_roots_chebyc(): + weightf = orth.chebyc(5).weight_func + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 5) + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 25) + verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 100, + atol=1e-12) + + x, w = sc.roots_chebyc(5, False) + y, v, m = sc.roots_chebyc(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -2, 2) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebyc, 0) + assert_raises(ValueError, sc.roots_chebyc, 3.3) + +def test_roots_chebys(): + weightf = orth.chebys(5).weight_func + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 5) + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 25) + verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 100) + + x, w = sc.roots_chebys(5, False) + y, v, m = sc.roots_chebys(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -2, 2) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_chebys, 0) + assert_raises(ValueError, sc.roots_chebys, 3.3) + +def test_roots_sh_chebyt(): + weightf = orth.sh_chebyt(5).weight_func + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 25) + verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., + 100, atol=1e-13) + + x, w = sc.roots_sh_chebyt(5, False) + y, v, m = sc.roots_sh_chebyt(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_chebyt, 0) + assert_raises(ValueError, sc.roots_sh_chebyt, 3.3) + +def test_roots_sh_chebyu(): + weightf = orth.sh_chebyu(5).weight_func + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 25) + verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., + 100, atol=1e-13) + + x, w = sc.roots_sh_chebyu(5, False) + y, v, m = sc.roots_sh_chebyu(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_chebyu, 0) + assert_raises(ValueError, sc.roots_sh_chebyu, 3.3) + +def test_roots_legendre(): + weightf = orth.legendre(5).weight_func + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., 5) + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., + 25, atol=1e-13) + verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., + 100, atol=1e-12) + + x, w = sc.roots_legendre(5, False) + y, v, m = sc.roots_legendre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, -1, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_legendre, 0) + assert_raises(ValueError, sc.roots_legendre, 3.3) + +def test_roots_sh_legendre(): + weightf = orth.sh_legendre(5).weight_func + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., 5) + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., + 25, atol=1e-13) + verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., + 100, atol=1e-12) + + x, w = sc.roots_sh_legendre(5, False) + y, v, m = sc.roots_sh_legendre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, 1) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_sh_legendre, 0) + assert_raises(ValueError, sc.roots_sh_legendre, 3.3) + +def test_roots_laguerre(): + weightf = orth.laguerre(5).weight_func + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, 5) + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, + 25, atol=1e-13) + verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, + 100, atol=1e-12) + + x, w = sc.roots_laguerre(5, False) + y, v, m = sc.roots_laguerre(5, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf, 0, np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_laguerre, 0) + assert_raises(ValueError, sc.roots_laguerre, 3.3) + +def test_roots_genlaguerre(): + def rootf(a): + return lambda n, mu: sc.roots_genlaguerre(n, a, mu) + def evalf(a): + return lambda n, x: sc.eval_genlaguerre(n, a, x) + def weightf(a): + return lambda x: x ** a * np.exp(-x) + + vgq = verify_gauss_quad + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 5) + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 25, atol=1e-13) + vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 100, atol=1e-12) + + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 5) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 25, atol=1e-13) + vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 100, atol=1.6e-13) + + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 5) + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 25, atol=1e-13) + vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 100, atol=1.03e-13) + + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 5) + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 25, atol=1e-13) + vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 100, atol=1e-12) + + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 5) + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 25, atol=1e-13) + vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 100, rtol=1e-14, atol=2e-13) + + x, w = sc.roots_genlaguerre(5, 2, False) + y, v, m = sc.roots_genlaguerre(5, 2, True) + assert_allclose(x, y, 1e-14, 1e-14) + assert_allclose(w, v, 1e-14, 1e-14) + + muI, muI_err = integrate.quad(weightf(2.), 0., np.inf) + assert_allclose(m, muI, rtol=muI_err) + + assert_raises(ValueError, sc.roots_genlaguerre, 0, 2) + assert_raises(ValueError, sc.roots_genlaguerre, 3.3, 2) + assert_raises(ValueError, sc.roots_genlaguerre, 3, -1.1) + + +def test_gh_6721(): + # Regression test for gh_6721. This should not raise. + sc.chebyt(65)(0.2) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..17414d8e0d6773aaca6696169bfe1d9cbb15e379 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py @@ -0,0 +1,272 @@ +import numpy as np +from numpy.testing import assert_, assert_allclose +import pytest + +from scipy.special import _ufuncs +import scipy.special._orthogonal as orth +from scipy.special._testutils import FuncData + + +def test_eval_chebyt(): + n = np.arange(0, 10000, 7, dtype=np.dtype("long")) + x = 2*np.random.rand() - 1 + v1 = np.cos(n*np.arccos(x)) + v2 = _ufuncs.eval_chebyt(n, x) + assert_(np.allclose(v1, v2, rtol=1e-15)) + + +def test_eval_chebyt_gh20129(): + # https://github.com/scipy/scipy/issues/20129 + assert _ufuncs.eval_chebyt(7, 2 + 0j) == 5042.0 + +def test_eval_genlaguerre_restriction(): + # check it returns nan for alpha <= -1 + assert_(np.isnan(_ufuncs.eval_genlaguerre(0, -1, 0))) + assert_(np.isnan(_ufuncs.eval_genlaguerre(0.1, -1, 0))) + + +def test_warnings(): + # ticket 1334 + with np.errstate(all='raise'): + # these should raise no fp warnings + _ufuncs.eval_legendre(1, 0) + _ufuncs.eval_laguerre(1, 1) + _ufuncs.eval_gegenbauer(1, 1, 0) + + +class TestPolys: + """ + Check that the eval_* functions agree with the constructed polynomials + + """ + + def check_poly(self, func, cls, param_ranges=[], x_range=[], nn=10, + nparam=10, nx=10, rtol=1e-8): + np.random.seed(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + poly = np.poly1d(cls(*p).coef) + z = np.c_[np.tile(p, (nx,1)), x, poly(x)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p = (p[0].astype(np.dtype("long")),) + p[1:] + return func(*p) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, orth.jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1], rtol=1e-5) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, orth.sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1], + rtol=1e-5) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, orth.gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1], + rtol=1e-7) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, orth.chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, orth.chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, orth.chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, orth.chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_chebyt, orth.sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, orth.sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, orth.legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + with np.errstate(all='ignore'): + self.check_poly(_ufuncs.eval_sh_legendre, orth.sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, orth.genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, orth.laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + self.check_poly(_ufuncs.eval_hermite, orth.hermite, + param_ranges=[], x_range=[-100, 100]) + + def test_hermitenorm(self): + self.check_poly(_ufuncs.eval_hermitenorm, orth.hermitenorm, + param_ranges=[], x_range=[-100, 100]) + + +class TestRecurrence: + """ + Check that the eval_* functions sig='ld->d' and 'dd->d' agree. + + """ + + def check_poly(self, func, param_ranges=[], x_range=[], nn=10, + nparam=10, nx=10, rtol=1e-8): + np.random.seed(1234) + + dataset = [] + for n in np.arange(nn): + params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges] + params = np.asarray(params).T + if not param_ranges: + params = [0] + for p in params: + if param_ranges: + p = (n,) + tuple(p) + else: + p = (n,) + x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx) + x[0] = x_range[0] # always include domain start point + x[1] = x_range[1] # always include domain end point + kw = dict(sig=(len(p)+1)*'d'+'->d') + z = np.c_[np.tile(p, (nx,1)), x, func(*(p + (x,)), **kw)] + dataset.append(z) + + dataset = np.concatenate(dataset, axis=0) + + def polyfunc(*p): + p = (p[0].astype(int),) + p[1:] + kw = dict(sig='l'+(len(p)-1)*'d'+'->d') + return func(*p, **kw) + + with np.errstate(all='raise'): + ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1, + rtol=rtol) + ds.check() + + def test_jacobi(self): + self.check_poly(_ufuncs.eval_jacobi, + param_ranges=[(-0.99, 10), (-0.99, 10)], + x_range=[-1, 1]) + + def test_sh_jacobi(self): + self.check_poly(_ufuncs.eval_sh_jacobi, + param_ranges=[(1, 10), (0, 1)], x_range=[0, 1]) + + def test_gegenbauer(self): + self.check_poly(_ufuncs.eval_gegenbauer, + param_ranges=[(-0.499, 10)], x_range=[-1, 1]) + + def test_chebyt(self): + self.check_poly(_ufuncs.eval_chebyt, + param_ranges=[], x_range=[-1, 1]) + + def test_chebyu(self): + self.check_poly(_ufuncs.eval_chebyu, + param_ranges=[], x_range=[-1, 1]) + + def test_chebys(self): + self.check_poly(_ufuncs.eval_chebys, + param_ranges=[], x_range=[-2, 2]) + + def test_chebyc(self): + self.check_poly(_ufuncs.eval_chebyc, + param_ranges=[], x_range=[-2, 2]) + + def test_sh_chebyt(self): + self.check_poly(_ufuncs.eval_sh_chebyt, + param_ranges=[], x_range=[0, 1]) + + def test_sh_chebyu(self): + self.check_poly(_ufuncs.eval_sh_chebyu, + param_ranges=[], x_range=[0, 1]) + + def test_legendre(self): + self.check_poly(_ufuncs.eval_legendre, + param_ranges=[], x_range=[-1, 1]) + + def test_sh_legendre(self): + self.check_poly(_ufuncs.eval_sh_legendre, + param_ranges=[], x_range=[0, 1]) + + def test_genlaguerre(self): + self.check_poly(_ufuncs.eval_genlaguerre, + param_ranges=[(-0.99, 10)], x_range=[0, 100]) + + def test_laguerre(self): + self.check_poly(_ufuncs.eval_laguerre, + param_ranges=[], x_range=[0, 100]) + + def test_hermite(self): + v = _ufuncs.eval_hermite(70, 1.0) + a = -1.457076485701412e60 + assert_allclose(v, a) + + +def test_hermite_domain(): + # Regression test for gh-11091. + assert np.isnan(_ufuncs.eval_hermite(-1, 1.0)) + assert np.isnan(_ufuncs.eval_hermitenorm(-1, 1.0)) + + +@pytest.mark.parametrize("n", [0, 1, 2]) +@pytest.mark.parametrize("x", [0, 1, np.nan]) +def test_hermite_nan(n, x): + # Regression test for gh-11369. + assert np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x])) + assert np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x])) + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [1, np.nan]) +@pytest.mark.parametrize('x', [2, np.nan]) +def test_genlaguerre_nan(n, alpha, x): + # Regression test for gh-11361. + nan_laguerre = np.isnan(_ufuncs.eval_genlaguerre(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_laguerre == nan_arg + + +@pytest.mark.parametrize('n', [0, 1, 2, 3.2]) +@pytest.mark.parametrize('alpha', [0.0, 1, np.nan]) +@pytest.mark.parametrize('x', [1e-6, 2, np.nan]) +def test_gegenbauer_nan(n, alpha, x): + # Regression test for gh-11370. + nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x)) + nan_arg = np.any(np.isnan([n, alpha, x])) + assert nan_gegenbauer == nan_arg diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py new file mode 100644 index 0000000000000000000000000000000000000000..8d15aead25302023c5f07d8392c0931995764ced --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py @@ -0,0 +1,53 @@ +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +import scipy.special as sc + + +def test_symmetries(): + np.random.seed(1234) + a, h = np.random.rand(100), np.random.rand(100) + assert_equal(sc.owens_t(h, a), sc.owens_t(-h, a)) + assert_equal(sc.owens_t(h, a), -sc.owens_t(h, -a)) + + +def test_special_cases(): + assert_equal(sc.owens_t(5, 0), 0) + assert_allclose(sc.owens_t(0, 5), 0.5*np.arctan(5)/np.pi, + rtol=5e-14) + # Target value is 0.5*Phi(5)*(1 - Phi(5)) for Phi the CDF of the + # standard normal distribution + assert_allclose(sc.owens_t(5, 1), 1.4332574485503512543e-07, + rtol=5e-14) + + +def test_nans(): + assert_equal(sc.owens_t(20, np.nan), np.nan) + assert_equal(sc.owens_t(np.nan, 20), np.nan) + assert_equal(sc.owens_t(np.nan, np.nan), np.nan) + + +def test_infs(): + h, a = 0, np.inf + # T(0, a) = 1/2π * arctan(a) + res = 1/(2*np.pi) * np.arctan(a) + assert_allclose(sc.owens_t(h, a), res, rtol=5e-14) + assert_allclose(sc.owens_t(h, -a), -res, rtol=5e-14) + + h = 1 + # Refer Owens T function definition in Wikipedia + # https://en.wikipedia.org/wiki/Owen%27s_T_function + # Value approximated through Numerical Integration + # using scipy.integrate.quad + # quad(lambda x: 1/(2*pi)*(exp(-0.5*(1*1)*(1+x*x))/(1+x*x)), 0, inf) + res = 0.07932762696572854 + assert_allclose(sc.owens_t(h, np.inf), res, rtol=5e-14) + assert_allclose(sc.owens_t(h, -np.inf), -res, rtol=5e-14) + + assert_equal(sc.owens_t(np.inf, 1), 0) + assert_equal(sc.owens_t(-np.inf, 1), 0) + + assert_equal(sc.owens_t(np.inf, np.inf), 0) + assert_equal(sc.owens_t(-np.inf, np.inf), 0) + assert_equal(sc.owens_t(np.inf, -np.inf), -0.0) + assert_equal(sc.owens_t(-np.inf, -np.inf), -0.0) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c42aa688081fb58f79ad2c8ea932d03b33523b --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py @@ -0,0 +1,24 @@ +"""Tests for parabolic cylinder functions. + +""" +import numpy as np +from numpy.testing import assert_allclose, assert_equal +import scipy.special as sc + + +def test_pbwa_segfault(): + # Regression test for https://github.com/scipy/scipy/issues/6208. + # + # Data generated by mpmath. + # + w = 1.02276567211316867161 + wp = -0.48887053372346189882 + assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0) + + +def test_pbwa_nan(): + # Check that NaN's are returned outside of the range in which the + # implementation is accurate. + pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)] + for p in pts: + assert_equal(sc.pbwa(*p), (np.nan, np.nan)) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py new file mode 100644 index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py @@ -0,0 +1,48 @@ +import numpy as np +import scipy.special as sc +from numpy.testing import assert_almost_equal, assert_array_equal + + +class TestPdtr: + def test(self): + val = sc.pdtr(0, 1) + assert_almost_equal(val, np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtr([0, 1, 2], 0) + assert_array_equal(val, [1, 1, 1]) + + def test_rounding(self): + double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtr([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtr(np.inf, 1.0) + assert_almost_equal(val, 1.0) + + def test_domain(self): + val = sc.pdtr(-1.1, 1.0) + assert np.isnan(val) + +class TestPdtrc: + def test_value(self): + val = sc.pdtrc(0, 1) + assert_almost_equal(val, 1 - np.exp(-1)) + + def test_m_zero(self): + val = sc.pdtrc([0, 1, 2], 0.0) + assert_array_equal(val, [0, 0, 0]) + + def test_rounding(self): + double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0) + int_val = sc.pdtrc([0, 1, 2], 1.0) + assert_array_equal(double_val, int_val) + + def test_inf(self): + val = sc.pdtrc(np.inf, 1.0) + assert_almost_equal(val, 0.0) + + def test_domain(self): + val = sc.pdtrc(-1.1, 1.0) + assert np.isnan(val) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py new file mode 100644 index 0000000000000000000000000000000000000000..3d809963f64ddaedf6b59de80dcd5f7ca8fa18a9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py @@ -0,0 +1,65 @@ +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy.special import powm1 + + +# Expected values were computed with mpmath, e.g. +# +# >>> import mpmath +# >>> mpmath.np.dps = 200 +# >>> print(float(mpmath.powm1(2.0, 1e-7)) +# 6.931472045825965e-08 +# +powm1_test_cases = [ + (1.25, 0.75, 0.18217701125396976, 1e-15), + (2.0, 1e-7, 6.931472045825965e-08, 1e-15), + (25.0, 5e-11, 1.6094379125636148e-10, 1e-15), + (0.99996, 0.75, -3.0000150002530058e-05, 1e-15), + (0.9999999999990905, 20, -1.81898940353014e-11, 1e-15), + (-1.25, 751.0, -6.017550852453444e+72, 2e-15) +] + + +@pytest.mark.parametrize('x, y, expected, rtol', powm1_test_cases) +def test_powm1(x, y, expected, rtol): + p = powm1(x, y) + assert_allclose(p, expected, rtol=rtol) + + +@pytest.mark.parametrize('x, y, expected', + [(0.0, 0.0, 0.0), + (0.0, -1.5, np.inf), + (0.0, 1.75, -1.0), + (-1.5, 2.0, 1.25), + (-1.5, 3.0, -4.375), + (np.nan, 0.0, 0.0), + (1.0, np.nan, 0.0), + (1.0, np.inf, 0.0), + (1.0, -np.inf, 0.0), + (np.inf, 7.5, np.inf), + (np.inf, -7.5, -1.0), + (3.25, np.inf, np.inf), + (np.inf, np.inf, np.inf), + (np.inf, -np.inf, -1.0), + (np.inf, 0.0, 0.0), + (-np.inf, 0.0, 0.0), + (-np.inf, 2.0, np.inf), + (-np.inf, 3.0, -np.inf), + (-1.0, float(2**53 - 1), -2.0)]) +def test_powm1_exact_cases(x, y, expected): + # Test cases where we have an exact expected value. + p = powm1(x, y) + assert p == expected + + +@pytest.mark.parametrize('x, y', + [(-1.25, 751.03), + (-1.25, np.inf), + (np.nan, np.nan), + (-np.inf, -np.inf), + (-np.inf, 2.5)]) +def test_powm1_return_nan(x, y): + # Test cases where the expected return value is nan. + p = powm1(x, y) + assert np.isnan(p) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..7b6c6cba21d5c1d5fdfab879153ba8f125e98d5f --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py @@ -0,0 +1,24 @@ +from numpy.testing import assert_equal + +from scipy.special._testutils import check_version, MissingModule +from scipy.special._precompute.expn_asy import generate_A + +try: + import sympy + from sympy import Poly +except ImportError: + sympy = MissingModule("sympy") + + +@check_version(sympy, "1.0") +def test_generate_A(): + # Data from DLMF 8.20.5 + x = sympy.symbols('x') + Astd = [Poly(1, x), + Poly(1, x), + Poly(1 - 2*x), + Poly(1 - 8*x + 6*x**2)] + Ares = generate_A(len(Astd)) + + for p, q in zip(Astd, Ares): + assert_equal(p, q) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c46b456d0a1b545b29e0b8b81b39dafb6b0610 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py @@ -0,0 +1,108 @@ +import pytest + +from scipy.special._testutils import MissingModule, check_version +from scipy.special._mptestutils import ( + Arg, IntArg, mp_assert_allclose, assert_mpmath_equal) +from scipy.special._precompute.gammainc_asy import ( + compute_g, compute_alpha, compute_d) +from scipy.special._precompute.gammainc_data import gammainc, gammaincc + +try: + import sympy +except ImportError: + sympy = MissingModule('sympy') + +try: + import mpmath as mp +except ImportError: + mp = MissingModule('mpmath') + + +@check_version(mp, '0.19') +def test_g(): + # Test data for the g_k. See DLMF 5.11.4. + with mp.workdps(30): + g = [mp.mpf(1), mp.mpf(1)/12, mp.mpf(1)/288, + -mp.mpf(139)/51840, -mp.mpf(571)/2488320, + mp.mpf(163879)/209018880, mp.mpf(5246819)/75246796800] + mp_assert_allclose(compute_g(7), g) + + +@pytest.mark.slow +@check_version(mp, '0.19') +@check_version(sympy, '0.7') +@pytest.mark.xfail_on_32bit("rtol only 2e-11, see gh-6938") +def test_alpha(): + # Test data for the alpha_k. See DLMF 8.12.14. + with mp.workdps(30): + alpha = [mp.mpf(0), mp.mpf(1), mp.mpf(1)/3, mp.mpf(1)/36, + -mp.mpf(1)/270, mp.mpf(1)/4320, mp.mpf(1)/17010, + -mp.mpf(139)/5443200, mp.mpf(1)/204120] + mp_assert_allclose(compute_alpha(9), alpha) + + +@pytest.mark.xslow +@check_version(mp, '0.19') +@check_version(sympy, '0.7') +def test_d(): + # Compare the d_{k, n} to the results in appendix F of [1]. + # + # Sources + # ------- + # [1] DiDonato and Morris, Computation of the Incomplete Gamma + # Function Ratios and their Inverse, ACM Transactions on + # Mathematical Software, 1986. + + with mp.workdps(50): + dataset = [(0, 0, -mp.mpf('0.333333333333333333333333333333')), + (0, 12, mp.mpf('0.102618097842403080425739573227e-7')), + (1, 0, -mp.mpf('0.185185185185185185185185185185e-2')), + (1, 12, mp.mpf('0.119516285997781473243076536700e-7')), + (2, 0, mp.mpf('0.413359788359788359788359788360e-2')), + (2, 12, -mp.mpf('0.140925299108675210532930244154e-7')), + (3, 0, mp.mpf('0.649434156378600823045267489712e-3')), + (3, 12, -mp.mpf('0.191111684859736540606728140873e-7')), + (4, 0, -mp.mpf('0.861888290916711698604702719929e-3')), + (4, 12, mp.mpf('0.288658297427087836297341274604e-7')), + (5, 0, -mp.mpf('0.336798553366358150308767592718e-3')), + (5, 12, mp.mpf('0.482409670378941807563762631739e-7')), + (6, 0, mp.mpf('0.531307936463992223165748542978e-3')), + (6, 12, -mp.mpf('0.882860074633048352505085243179e-7')), + (7, 0, mp.mpf('0.344367606892377671254279625109e-3')), + (7, 12, -mp.mpf('0.175629733590604619378669693914e-6')), + (8, 0, -mp.mpf('0.652623918595309418922034919727e-3')), + (8, 12, mp.mpf('0.377358774161109793380344937299e-6')), + (9, 0, -mp.mpf('0.596761290192746250124390067179e-3')), + (9, 12, mp.mpf('0.870823417786464116761231237189e-6'))] + d = compute_d(10, 13) + res = [d[k][n] for k, n, std in dataset] + std = [x[2] for x in dataset] + mp_assert_allclose(res, std) + + +@check_version(mp, '0.19') +def test_gammainc(): + # Quick check that the gammainc in + # special._precompute.gammainc_data agrees with mpmath's + # gammainc. + assert_mpmath_equal(gammainc, + lambda a, x: mp.gammainc(a, b=x, regularized=True), + [Arg(0, 100, inclusive_a=False), Arg(0, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=50) + + +@pytest.mark.xslow +@check_version(mp, '0.19') +def test_gammaincc(): + # Check that the gammaincc in special._precompute.gammainc_data + # agrees with mpmath's gammainc. + assert_mpmath_equal(lambda a, x: gammaincc(a, x, dps=1000), + lambda a, x: mp.gammainc(a, a=x, regularized=True), + [Arg(20, 100), Arg(20, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=1000) + + # Test the fast integer path + assert_mpmath_equal(gammaincc, + lambda a, x: mp.gammainc(a, a=x, regularized=True), + [IntArg(1, 100), Arg(0, 100)], + nan_ok=False, rtol=1e-17, n=50, dps=50) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..89616b92329691ca76039fe11a7e08f7f3db1150 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py @@ -0,0 +1,36 @@ +import pytest + +from scipy.special._testutils import MissingModule, check_version +from scipy.special._mptestutils import mp_assert_allclose +from scipy.special._precompute.utils import lagrange_inversion + +try: + import sympy +except ImportError: + sympy = MissingModule('sympy') + +try: + import mpmath as mp +except ImportError: + mp = MissingModule('mpmath') + + +@pytest.mark.slow +@check_version(sympy, '0.7') +@check_version(mp, '0.19') +class TestInversion: + @pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938") + def test_log(self): + with mp.workdps(30): + logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10) + expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10) + invlogcoeffs = lagrange_inversion(logcoeffs) + mp_assert_allclose(invlogcoeffs, expcoeffs) + + @pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938") + def test_sin(self): + with mp.workdps(30): + sincoeffs = mp.taylor(mp.sin, 0, 10) + asincoeffs = mp.taylor(mp.asin, 0, 10) + invsincoeffs = lagrange_inversion(sincoeffs) + mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py new file mode 100644 index 0000000000000000000000000000000000000000..ec27e7eed2fe5cd425afd93049b9f043d74be011 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py @@ -0,0 +1,16 @@ +import numpy as np +import pytest + +from scipy.special import _test_internal + + +@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()") +def test_add_round_up(): + np.random.seed(1234) + _test_internal.test_add_round(10**5, 'up') + + +@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()") +def test_add_round_down(): + np.random.seed(1234) + _test_internal.test_add_round(10**5, 'down') diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py new file mode 100644 index 0000000000000000000000000000000000000000..e668629d564ffb37d821c1f1af2869ab045ded50 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py @@ -0,0 +1,134 @@ +import sys +import warnings + +import numpy as np +from numpy.testing import assert_, assert_equal, IS_PYPY +import pytest +from pytest import raises as assert_raises + +import scipy.special as sc +from scipy.special._ufuncs import _sf_error_test_function + +_sf_error_code_map = { + # skip 'ok' + 'singular': 1, + 'underflow': 2, + 'overflow': 3, + 'slow': 4, + 'loss': 5, + 'no_result': 6, + 'domain': 7, + 'arg': 8, + 'other': 9 +} + +_sf_error_actions = [ + 'ignore', + 'warn', + 'raise' +] + + +def _check_action(fun, args, action): + # TODO: special expert should correct + # the coercion at the true location? + args = np.asarray(args, dtype=np.dtype("long")) + if action == 'warn': + with pytest.warns(sc.SpecialFunctionWarning): + fun(*args) + elif action == 'raise': + with assert_raises(sc.SpecialFunctionError): + fun(*args) + else: + # action == 'ignore', make sure there are no warnings/exceptions + with warnings.catch_warnings(): + warnings.simplefilter("error") + fun(*args) + + +def test_geterr(): + err = sc.geterr() + for key, value in err.items(): + assert_(key in _sf_error_code_map) + assert_(value in _sf_error_actions) + + +def test_seterr(): + entry_err = sc.geterr() + try: + for category, error_code in _sf_error_code_map.items(): + for action in _sf_error_actions: + geterr_olderr = sc.geterr() + seterr_olderr = sc.seterr(**{category: action}) + assert_(geterr_olderr == seterr_olderr) + newerr = sc.geterr() + assert_(newerr[category] == action) + geterr_olderr.pop(category) + newerr.pop(category) + assert_(geterr_olderr == newerr) + _check_action(_sf_error_test_function, (error_code,), action) + finally: + sc.seterr(**entry_err) + + +@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy") +def test_sf_error_special_refcount(): + # Regression test for gh-16233. + # Check that the reference count of scipy.special is not increased + # when a SpecialFunctionError is raised. + refcount_before = sys.getrefcount(sc) + with sc.errstate(all='raise'): + with pytest.raises(sc.SpecialFunctionError, match='domain error'): + sc.ndtri(2.0) + refcount_after = sys.getrefcount(sc) + assert refcount_after == refcount_before + + +def test_errstate_pyx_basic(): + olderr = sc.geterr() + with sc.errstate(singular='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.loggamma(0) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_c_basic(): + olderr = sc.geterr() + with sc.errstate(domain='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.spence(-1) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_cpp_basic(): + olderr = sc.geterr() + with sc.errstate(underflow='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.wrightomega(-1000) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_cpp_scipy_special(): + olderr = sc.geterr() + with sc.errstate(singular='raise'): + with assert_raises(sc.SpecialFunctionError): + sc.lambertw(0, 1) + assert_equal(olderr, sc.geterr()) + + +def test_errstate(): + for category, error_code in _sf_error_code_map.items(): + for action in _sf_error_actions: + olderr = sc.geterr() + with sc.errstate(**{category: action}): + _check_action(_sf_error_test_function, (error_code,), action) + assert_equal(olderr, sc.geterr()) + + +def test_errstate_all_but_one(): + olderr = sc.geterr() + with sc.errstate(all='raise', singular='ignore'): + sc.gammaln(0) + with assert_raises(sc.SpecialFunctionError): + sc.spence(-1.0) + assert_equal(olderr, sc.geterr()) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py new file mode 100644 index 0000000000000000000000000000000000000000..d33c1795641ba74f777fcfdcffe80d86463477e3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py @@ -0,0 +1,36 @@ +import numpy as np + +import scipy.special as sc +from scipy.special._testutils import FuncData + + +def test_sici_consistency(): + # Make sure the implementation of sici for real arguments agrees + # with the implementation of sici for complex arguments. + + # On the negative real axis Cephes drops the imaginary part in ci + def sici(x): + si, ci = sc.sici(x + 0j) + return si.real, ci.real + + x = np.r_[-np.logspace(8, -30, 200), 0, np.logspace(-30, 8, 200)] + si, ci = sc.sici(x) + dataset = np.column_stack((x, si, ci)) + FuncData(sici, dataset, 0, (1, 2), rtol=1e-12).check() + + +def test_shichi_consistency(): + # Make sure the implementation of shichi for real arguments agrees + # with the implementation of shichi for complex arguments. + + # On the negative real axis Cephes drops the imaginary part in chi + def shichi(x): + shi, chi = sc.shichi(x + 0j) + return shi.real, chi.real + + # Overflow happens quickly, so limit range + x = np.r_[-np.logspace(np.log10(700), -30, 200), 0, + np.logspace(-30, np.log10(700), 200)] + shi, chi = sc.shichi(x) + dataset = np.column_stack((x, shi, chi)) + FuncData(shichi, dataset, 0, (1, 2), rtol=1e-14).check() diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py new file mode 100644 index 0000000000000000000000000000000000000000..891a08d3bce06e1feaddbb760bc7682909781d20 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py @@ -0,0 +1,36 @@ +""" +Various made-up tests to hit different branches of the code in specfun.c +""" + +import numpy as np +from numpy.testing import assert_allclose +from scipy import special + + +def test_cchg_branches(): + res = special.hyp1f1(0.1, 1, 7.0-24.0j) + assert_allclose(res, (-3.7659844658568016+4.970311359851648j)) + + +def test_cva2_cv0_branches(): + res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([-0.3741211, 0.74441928])) + assert_allclose(resp, np.array([-37.02872758, -86.13549877])) + + res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([0.92955551, 0.66771207])) + assert_allclose(resp, np.array([-14.91073448, 96.02954185])) + + +def test_chgm_branches(): + res = special.eval_genlaguerre(-3.2, 3, 2.5) + assert_allclose(res, -0.7077721935779854) + + +def test_hygfz_branches(): + """(z == 1.0) && (c-a-b > 0.0)""" + res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j) + assert_allclose(res, 10.30835089459151+0j) + """(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)""" + res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j) + assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb26ac281dff81ea71b30318731065fe5a78f94 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py @@ -0,0 +1,32 @@ +import numpy as np +from numpy import sqrt, log, pi +from scipy.special._testutils import FuncData +from scipy.special import spence + + +def test_consistency(): + # Make sure the implementation of spence for real arguments + # agrees with the implementation of spence for imaginary arguments. + + x = np.logspace(-30, 300, 200) + dataset = np.vstack((x + 0j, spence(x))).T + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() + + +def test_special_points(): + # Check against known values of Spence's function. + + phi = (1 + sqrt(5))/2 + dataset = [(1, 0), + (2, -pi**2/12), + (0.5, pi**2/12 - log(2)**2/2), + (0, pi**2/6), + (-1, pi**2/4 - 1j*pi*log(2)), + ((-1 + sqrt(5))/2, pi**2/15 - log(phi)**2), + ((3 - sqrt(5))/2, pi**2/10 - log(phi)**2), + (phi, -pi**2/15 + log(phi)**2/2), + # Corrected from Zagier, "The Dilogarithm Function" + ((3 + sqrt(5))/2, -pi**2/10 - log(phi)**2)] + + dataset = np.asarray(dataset) + FuncData(spence, dataset, 0, 1, rtol=1e-14).check() diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a047c78fb8542bd0abbb75a4815d777e1414b0 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py @@ -0,0 +1,61 @@ +import numpy as np +from numpy.testing import (assert_array_equal, + assert_array_almost_equal_nulp, assert_almost_equal) +from pytest import raises as assert_raises + +from scipy.special import gammaln, multigammaln + + +class TestMultiGammaLn: + + def test1(self): + # A test of the identity + # Gamma_1(a) = Gamma(a) + np.random.seed(1234) + a = np.abs(np.random.randn()) + assert_array_equal(multigammaln(a, 1), gammaln(a)) + + def test2(self): + # A test of the identity + # Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5) + a = np.array([2.5, 10.0]) + result = multigammaln(a, 2) + expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5) + assert_almost_equal(result, expected) + + def test_bararg(self): + assert_raises(ValueError, multigammaln, 0.5, 1.2) + + +def _check_multigammaln_array_result(a, d): + # Test that the shape of the array returned by multigammaln + # matches the input shape, and that all the values match + # the value computed when multigammaln is called with a scalar. + result = multigammaln(a, d) + assert_array_equal(a.shape, result.shape) + a1 = a.ravel() + result1 = result.ravel() + for i in range(a.size): + assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d)) + + +def test_multigammaln_array_arg(): + # Check that the array returned by multigammaln has the correct + # shape and contains the correct values. The cases have arrays + # with several different shapes. + # The cases include a regression test for ticket #1849 + # (a = np.array([2.0]), an array with a single element). + np.random.seed(1234) + + cases = [ + # a, d + (np.abs(np.random.randn(3, 2)) + 5, 5), + (np.abs(np.random.randn(1, 2)) + 5, 5), + (np.arange(10.0, 18.0).reshape(2, 2, 2), 3), + (np.array([2.0]), 3), + (np.float64(2.0), 3), + ] + + for a, d in cases: + _check_multigammaln_array_result(a, d) + diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..6539407bc9d8787af9c85d2e9ac3dffccd1ffa50 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py @@ -0,0 +1,37 @@ +import numpy as np +from numpy.testing import assert_allclose +import scipy.special as sc + + +def test_first_harmonics(): + # Test against explicit representations of the first four + # spherical harmonics which use `theta` as the azimuthal angle, + # `phi` as the polar angle, and include the Condon-Shortley + # phase. + + # Notation is Ymn + def Y00(theta, phi): + return 0.5*np.sqrt(1/np.pi) + + def Yn11(theta, phi): + return 0.5*np.sqrt(3/(2*np.pi))*np.exp(-1j*theta)*np.sin(phi) + + def Y01(theta, phi): + return 0.5*np.sqrt(3/np.pi)*np.cos(phi) + + def Y11(theta, phi): + return -0.5*np.sqrt(3/(2*np.pi))*np.exp(1j*theta)*np.sin(phi) + + harms = [Y00, Yn11, Y01, Y11] + m = [0, -1, 0, 1] + n = [0, 1, 1, 1] + + theta = np.linspace(0, 2*np.pi) + phi = np.linspace(0, np.pi) + theta, phi = np.meshgrid(theta, phi) + + for harm, m, n in zip(harms, m, n): + assert_allclose(sc.sph_harm(m, n, theta, phi), + harm(theta, phi), + rtol=1e-15, atol=1e-15, + err_msg=f"Y^{m}_{n} incorrect") diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddfe0083d6dba2c08518d0d634c4a7e17f82476 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py @@ -0,0 +1,384 @@ +# +# Tests of spherical Bessel functions. +# +import numpy as np +from numpy.testing import (assert_almost_equal, assert_allclose, + assert_array_almost_equal, suppress_warnings) +import pytest +from numpy import sin, cos, sinh, cosh, exp, inf, nan, r_, pi + +from scipy.special import spherical_jn, spherical_yn, spherical_in, spherical_kn +from scipy.integrate import quad + + +class TestSphericalJn: + def test_spherical_jn_exact(self): + # https://dlmf.nist.gov/10.49.E3 + # Note: exact expression is numerically stable only for small + # n or z >> n. + x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5]) + assert_allclose(spherical_jn(2, x), + (-1/x + 3/x**3)*sin(x) - 3/x**2*cos(x)) + + def test_spherical_jn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x), + (2*n + 1)/x*spherical_jn(n, x)) + + def test_spherical_jn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1,x), + (2*n + 1)/x*spherical_jn(n, x)) + + def test_spherical_jn_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 6 + x = np.array([-inf, inf]) + assert_allclose(spherical_jn(n, x), np.array([0, 0])) + + def test_spherical_jn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E3 + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(spherical_jn(n, x), np.array([0, 0, inf*(1+1j)])) + + def test_spherical_jn_large_arg_1(self): + # https://github.com/scipy/scipy/issues/2165 + # Reference value computed using mpmath, via + # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z)) + assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747) + + def test_spherical_jn_large_arg_2(self): + # https://github.com/scipy/scipy/issues/1641 + # Reference value computed using mpmath, via + # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z)) + assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05) + + def test_spherical_jn_at_zero(self): + # https://dlmf.nist.gov/10.52.E1 + # But note that n = 0 is a special case: j0 = sin(x)/x -> 1 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0])) + + +class TestSphericalYn: + def test_spherical_yn_exact(self): + # https://dlmf.nist.gov/10.49.E5 + # Note: exact expression is numerically stable only for small + # n or z >> n. + x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5]) + assert_allclose(spherical_yn(2, x), + (1/x - 3/x**3)*cos(x) - 3/x**2*sin(x)) + + def test_spherical_yn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1,x), + (2*n + 1)/x*spherical_yn(n, x)) + + def test_spherical_yn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1, x), + (2*n + 1)/x*spherical_yn(n, x)) + + def test_spherical_yn_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 6 + x = np.array([-inf, inf]) + assert_allclose(spherical_yn(n, x), np.array([0, 0])) + + def test_spherical_yn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E3 + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + assert_allclose(spherical_yn(n, x), np.array([0, 0, inf*(1+1j)])) + + def test_spherical_yn_at_zero(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_yn(n, x), np.full(n.shape, -inf)) + + def test_spherical_yn_at_zero_complex(self): + # Consistently with numpy: + # >>> -np.cos(0)/0 + # -inf + # >>> -np.cos(0+0j)/(0+0j) + # (-inf + nan*j) + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + 0j + assert_allclose(spherical_yn(n, x), np.full(n.shape, nan)) + + +class TestSphericalJnYnCrossProduct: + def test_spherical_jn_yn_cross_product_1(self): + # https://dlmf.nist.gov/10.50.E3 + n = np.array([1, 5, 8]) + x = np.array([0.1, 1, 10]) + left = (spherical_jn(n + 1, x) * spherical_yn(n, x) - + spherical_jn(n, x) * spherical_yn(n + 1, x)) + right = 1/x**2 + assert_allclose(left, right) + + def test_spherical_jn_yn_cross_product_2(self): + # https://dlmf.nist.gov/10.50.E3 + n = np.array([1, 5, 8]) + x = np.array([0.1, 1, 10]) + left = (spherical_jn(n + 2, x) * spherical_yn(n, x) - + spherical_jn(n, x) * spherical_yn(n + 2, x)) + right = (2*n + 3)/x**3 + assert_allclose(left, right) + + +class TestSphericalIn: + def test_spherical_in_exact(self): + # https://dlmf.nist.gov/10.49.E9 + x = np.array([0.12, 1.23, 12.34, 123.45]) + assert_allclose(spherical_in(2, x), + (1/x + 3/x**3)*sinh(x) - 3/x**2*cosh(x)) + + def test_spherical_in_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x), + (2*n + 1)/x*spherical_in(n, x)) + + def test_spherical_in_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E1 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x), + (2*n + 1)/x*spherical_in(n, x)) + + def test_spherical_in_inf_real(self): + # https://dlmf.nist.gov/10.52.E3 + n = 5 + x = np.array([-inf, inf]) + assert_allclose(spherical_in(n, x), np.array([-inf, inf])) + + def test_spherical_in_inf_complex(self): + # https://dlmf.nist.gov/10.52.E5 + # Ideally, i1n(n, 1j*inf) = 0 and i1n(n, (1+1j)*inf) = (1+1j)*inf, but + # this appears impossible to achieve because C99 regards any complex + # value with at least one infinite part as a complex infinity, so + # 1j*inf cannot be distinguished from (1+1j)*inf. Therefore, nan is + # the correct return value. + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + assert_allclose(spherical_in(n, x), np.array([-inf, inf, nan])) + + def test_spherical_in_at_zero(self): + # https://dlmf.nist.gov/10.52.E1 + # But note that n = 0 is a special case: i0 = sinh(x)/x -> 1 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_in(n, x), np.array([1, 0, 0, 0, 0, 0])) + + +class TestSphericalKn: + def test_spherical_kn_exact(self): + # https://dlmf.nist.gov/10.49.E13 + x = np.array([0.12, 1.23, 12.34, 123.45]) + assert_allclose(spherical_kn(2, x), + pi/2*exp(-x)*(1/x + 3/x**2 + 3/x**3)) + + def test_spherical_kn_recurrence_real(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 0.12 + assert_allclose( + (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x), + (-1)**n*(2*n + 1)/x*spherical_kn(n, x) + ) + + def test_spherical_kn_recurrence_complex(self): + # https://dlmf.nist.gov/10.51.E4 + n = np.array([1, 2, 3, 7, 12]) + x = 1.1 + 1.5j + assert_allclose( + (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x), + (-1)**n*(2*n + 1)/x*spherical_kn(n, x) + ) + + def test_spherical_kn_inf_real(self): + # https://dlmf.nist.gov/10.52.E6 + n = 5 + x = np.array([-inf, inf]) + assert_allclose(spherical_kn(n, x), np.array([-inf, 0])) + + def test_spherical_kn_inf_complex(self): + # https://dlmf.nist.gov/10.52.E6 + # The behavior at complex infinity depends on the sign of the real + # part: if Re(z) >= 0, then the limit is 0; if Re(z) < 0, then it's + # z*inf. This distinction cannot be captured, so we return nan. + n = 7 + x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)]) + assert_allclose(spherical_kn(n, x), np.array([-inf, 0, nan])) + + def test_spherical_kn_at_zero(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + assert_allclose(spherical_kn(n, x), np.full(n.shape, inf)) + + def test_spherical_kn_at_zero_complex(self): + # https://dlmf.nist.gov/10.52.E2 + n = np.array([0, 1, 2, 5, 10, 100]) + x = 0 + 0j + assert_allclose(spherical_kn(n, x), np.full(n.shape, nan)) + + +class SphericalDerivativesTestCase: + def fundamental_theorem(self, n, a, b): + integral, tolerance = quad(lambda z: self.df(n, z), a, b) + assert_allclose(integral, + self.f(n, b) - self.f(n, a), + atol=tolerance) + + @pytest.mark.slow + def test_fundamental_theorem_0(self): + self.fundamental_theorem(0, 3.0, 15.0) + + @pytest.mark.slow + def test_fundamental_theorem_7(self): + self.fundamental_theorem(7, 0.5, 1.2) + + +class TestSphericalJnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_jn(n, z) + + def df(self, n, z): + return spherical_jn(n, z, derivative=True) + + def test_spherical_jn_d_zero(self): + n = np.array([0, 1, 2, 3, 7, 15]) + assert_allclose(spherical_jn(n, 0, derivative=True), + np.array([0, 1/3, 0, 0, 0, 0])) + + +class TestSphericalYnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_yn(n, z) + + def df(self, n, z): + return spherical_yn(n, z, derivative=True) + + +class TestSphericalInDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_in(n, z) + + def df(self, n, z): + return spherical_in(n, z, derivative=True) + + def test_spherical_in_d_zero(self): + n = np.array([1, 2, 3, 7, 15]) + assert_allclose(spherical_in(n, 0, derivative=True), + np.zeros(5)) + + +class TestSphericalKnDerivatives(SphericalDerivativesTestCase): + def f(self, n, z): + return spherical_kn(n, z) + + def df(self, n, z): + return spherical_kn(n, z, derivative=True) + + +class TestSphericalOld: + # These are tests from the TestSpherical class of test_basic.py, + # rewritten to use spherical_* instead of sph_* but otherwise unchanged. + + def test_sph_in(self): + # This test reproduces test_basic.TestSpherical.test_sph_in. + i1n = np.empty((2,2)) + x = 0.2 + + i1n[0][0] = spherical_in(0, x) + i1n[0][1] = spherical_in(1, x) + i1n[1][0] = spherical_in(0, x, derivative=True) + i1n[1][1] = spherical_in(1, x, derivative=True) + + inp0 = (i1n[0][1]) + inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) + assert_array_almost_equal(i1n[0],np.array([1.0066800127054699381, + 0.066933714568029540839]),12) + assert_array_almost_equal(i1n[1],[inp0,inp1],12) + + def test_sph_in_kn_order0(self): + x = 1. + sph_i0 = np.empty((2,)) + sph_i0[0] = spherical_in(0, x) + sph_i0[1] = spherical_in(0, x, derivative=True) + sph_i0_expected = np.array([np.sinh(x)/x, + np.cosh(x)/x-np.sinh(x)/x**2]) + assert_array_almost_equal(r_[sph_i0], sph_i0_expected) + + sph_k0 = np.empty((2,)) + sph_k0[0] = spherical_kn(0, x) + sph_k0[1] = spherical_kn(0, x, derivative=True) + sph_k0_expected = np.array([0.5*pi*exp(-x)/x, + -0.5*pi*exp(-x)*(1/x+1/x**2)]) + assert_array_almost_equal(r_[sph_k0], sph_k0_expected) + + def test_sph_jn(self): + s1 = np.empty((2,3)) + x = 0.2 + + s1[0][0] = spherical_jn(0, x) + s1[0][1] = spherical_jn(1, x) + s1[0][2] = spherical_jn(2, x) + s1[1][0] = spherical_jn(0, x, derivative=True) + s1[1][1] = spherical_jn(1, x, derivative=True) + s1[1][2] = spherical_jn(2, x, derivative=True) + + s10 = -s1[0][1] + s11 = s1[0][0]-2.0/0.2*s1[0][1] + s12 = s1[0][1]-3.0/0.2*s1[0][2] + assert_array_almost_equal(s1[0],[0.99334665397530607731, + 0.066400380670322230863, + 0.0026590560795273856680],12) + assert_array_almost_equal(s1[1],[s10,s11,s12],12) + + def test_sph_kn(self): + kn = np.empty((2,3)) + x = 0.2 + + kn[0][0] = spherical_kn(0, x) + kn[0][1] = spherical_kn(1, x) + kn[0][2] = spherical_kn(2, x) + kn[1][0] = spherical_kn(0, x, derivative=True) + kn[1][1] = spherical_kn(1, x, derivative=True) + kn[1][2] = spherical_kn(2, x, derivative=True) + + kn0 = -kn[0][1] + kn1 = -kn[0][0]-2.0/0.2*kn[0][1] + kn2 = -kn[0][1]-3.0/0.2*kn[0][2] + assert_array_almost_equal(kn[0],[6.4302962978445670140, + 38.581777787067402086, + 585.15696310385559829],12) + assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9) + + def test_sph_yn(self): + sy1 = spherical_yn(2, 0.2) + sy2 = spherical_yn(0, 0.2) + assert_almost_equal(sy1,-377.52483,5) # previous values in the system + assert_almost_equal(sy2,-4.9003329,5) + sphpy = (spherical_yn(0, 0.2) - 2*spherical_yn(2, 0.2))/3 + sy3 = spherical_yn(1, 0.2, derivative=True) + # compare correct derivative val. (correct =-system val). + assert_almost_equal(sy3,sphpy,4) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py new file mode 100644 index 0000000000000000000000000000000000000000..9c00ab0c0db1297d50dba69a41208fd1c4f22e31 --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py @@ -0,0 +1,67 @@ +import pytest +from hypothesis import given, strategies, reproduce_failure # noqa: F401 +import hypothesis.extra.numpy as npst + +from scipy.special._support_alternative_backends import (get_array_special_func, + array_special_func_map) +from scipy.conftest import array_api_compatible +from scipy import special +from scipy._lib._array_api import xp_assert_close +from scipy._lib.array_api_compat import numpy as np + +try: + import array_api_strict + HAVE_ARRAY_API_STRICT = True +except ImportError: + HAVE_ARRAY_API_STRICT = False + + +@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT, + reason="`array_api_strict` not installed") +def test_dispatch_to_unrecognize_library(): + xp = array_api_strict + f = get_array_special_func('ndtr', xp=xp, n_array_args=1) + x = [1, 2, 3] + res = f(xp.asarray(x)) + ref = xp.asarray(special.ndtr(np.asarray(x))) + xp_assert_close(res, ref, xp=xp) + + +@array_api_compatible +@given(data=strategies.data()) +@pytest.mark.parametrize('f_name_n_args', array_special_func_map.items()) +def test_support_alternative_backends(xp, data, f_name_n_args): + f_name, n_args = f_name_n_args + f = getattr(special, f_name) + + mbs = npst.mutually_broadcastable_shapes(num_shapes=n_args) + shapes, final_shape = data.draw(mbs) + + dtype = data.draw(strategies.sampled_from(['float32', 'float64'])) + dtype_np = getattr(np, dtype) + dtype_xp = getattr(xp, dtype) + + elements = dict(min_value=dtype_np(-10), max_value=dtype_np(10), + allow_subnormal=False) + args_np = [np.asarray(data.draw(npst.arrays(dtype_np, shape, elements=elements))) + for shape in shapes] + + # `torch.asarray(np.asarray(1.))` produces + # TypeError: can't convert np.ndarray of type numpy.object_. + # So we extract the scalar from 0d arrays. + args_xp = [xp.asarray(arg[()], dtype=dtype_xp) for arg in args_np] + + ref = np.asarray(f(*args_np)) + res = f(*args_xp) + + eps = np.finfo(dtype).eps + # PyTorch seems to struggle with precision near the poles of `gammaln`, + # so the tolerance needs to be quite loose (eps**0.2) - see gh-19935. + # To compensate, we also check that the root-mean-square error is + # less than eps**0.5. + ref = xp.asarray(ref, dtype=dtype_xp) + xp_assert_close(res, ref, rtol=eps**0.2, atol=eps*10, + check_namespace=True, check_shape=True, check_dtype=True,) + xp_assert_close(xp.sqrt(xp.mean(res**2)), xp.sqrt(xp.mean(ref**2)), + rtol=eps**0.5, atol=eps*10, + check_namespace=False, check_shape=False, check_dtype=False,) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py new file mode 100644 index 0000000000000000000000000000000000000000..578dfbd5e95e6c44b1828716a74c93d645efcb1e --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py @@ -0,0 +1,72 @@ +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose, suppress_warnings + +from scipy.special._ufuncs import _sinpi as sinpi +from scipy.special._ufuncs import _cospi as cospi + + +def test_integer_real_part(): + x = np.arange(-100, 101) + y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10))) + x, y = np.meshgrid(x, y) + z = x + 1j*y + # In the following we should be *exactly* right + res = sinpi(z) + assert_equal(res.real, 0.0) + res = cospi(z) + assert_equal(res.imag, 0.0) + + +def test_half_integer_real_part(): + x = np.arange(-100, 101) + 0.5 + y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10))) + x, y = np.meshgrid(x, y) + z = x + 1j*y + # In the following we should be *exactly* right + res = sinpi(z) + assert_equal(res.imag, 0.0) + res = cospi(z) + assert_equal(res.real, 0.0) + + +@pytest.mark.skip("Temporary skip while gh-19526 is being resolved") +def test_intermediate_overlow(): + # Make sure we avoid overflow in situations where cosh/sinh would + # overflow but the product with sin/cos would not + sinpi_pts = [complex(1 + 1e-14, 227), + complex(1e-35, 250), + complex(1e-301, 445)] + # Data generated with mpmath + sinpi_std = [complex(-8.113438309924894e+295, -np.inf), + complex(1.9507801934611995e+306, np.inf), + complex(2.205958493464539e+306, np.inf)] + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + for p, std in zip(sinpi_pts, sinpi_std): + res = sinpi(p) + assert_allclose(res.real, std.real) + assert_allclose(res.imag, std.imag) + + # Test for cosine, less interesting because cos(0) = 1. + p = complex(0.5 + 1e-14, 227) + std = complex(-8.113438309924894e+295, -np.inf) + with suppress_warnings() as sup: + sup.filter(RuntimeWarning, "invalid value encountered in multiply") + res = cospi(p) + assert_allclose(res.real, std.real) + assert_allclose(res.imag, std.imag) + + +def test_zero_sign(): + y = sinpi(-0.0) + assert y == 0.0 + assert np.signbit(y) + + y = sinpi(0.0) + assert y == 0.0 + assert not np.signbit(y) + + y = cospi(0.5) + assert y == 0.0 + assert not np.signbit(y) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..319db817c1ed3d35de1c08cadea002bf0eac3b0d --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py @@ -0,0 +1,115 @@ +# Reference MPMATH implementation: +# +# import mpmath +# from mpmath import nsum +# +# def Wright_Series_MPMATH(a, b, z, dps=50, method='r+s+e', steps=[1000]): +# """Compute Wright' generalized Bessel function as Series. +# +# This uses mpmath for arbitrary precision. +# """ +# with mpmath.workdps(dps): +# res = nsum(lambda k: z**k/mpmath.fac(k) * mpmath.rgamma(a*k+b), +# [0, mpmath.inf], +# tol=dps, method=method, steps=steps +# ) +# +# return res + +import pytest +import numpy as np +from numpy.testing import assert_equal, assert_allclose + +import scipy.special as sc +from scipy.special import rgamma, wright_bessel + + +@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10]) +def test_wright_bessel_zero(a, b): + """Test at x = 0.""" + assert_equal(wright_bessel(a, b, 0.), rgamma(b)) + + +@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1]) +def test_wright_bessel_iv(b, x): + """Test relation of wright_bessel and modified bessel function iv. + + iv(z) = (1/2*z)**v * Phi(1, v+1; 1/4*z**2). + See https://dlmf.nist.gov/10.46.E2 + """ + if x != 0: + v = b - 1 + wb = wright_bessel(1, v + 1, x**2 / 4.) + # Note: iv(v, x) has precision of less than 1e-12 for some cases + # e.g v=1-1e-6 and x=1e-06) + assert_allclose(np.power(x / 2., v) * wb, + sc.iv(v, x), + rtol=1e-11, atol=1e-11) + + +@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10]) +@pytest.mark.parametrize('b', [1, 1 + 1e-3, 2, 5, 10]) +@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1, 5, 10, 100]) +def test_wright_functional(a, b, x): + """Test functional relation of wright_bessel. + + Phi(a, b-1, z) = a*z*Phi(a, b+a, z) + (b-1)*Phi(a, b, z) + + Note that d/dx Phi(a, b, x) = Phi(a, b-1, x) + See Eq. (22) of + B. Stankovic, On the Function of E. M. Wright, + Publ. de l' Institut Mathematique, Beograd, + Nouvelle S`er. 10 (1970), 113-124. + """ + assert_allclose(wright_bessel(a, b - 1, x), + a * x * wright_bessel(a, b + a, x) + + (b - 1) * wright_bessel(a, b, x), + rtol=1e-8, atol=1e-8) + + +# grid of rows [a, b, x, value, accuracy] that do not reach 1e-11 accuracy +# see output of: +# cd scipy/scipy/_precompute +# python wright_bessel_data.py +grid_a_b_x_value_acc = np.array([ + [0.1, 100.0, 709.7827128933841, 8.026353022981087e+34, 2e-8], + [0.5, 10.0, 709.7827128933841, 2.680788404494657e+48, 9e-8], + [0.5, 10.0, 1000.0, 2.005901980702872e+64, 1e-8], + [0.5, 100.0, 1000.0, 3.4112367580445246e-117, 6e-8], + [1.0, 20.0, 100000.0, 1.7717158630699857e+225, 3e-11], + [1.0, 100.0, 100000.0, 1.0269334596230763e+22, np.nan], + [1.0000000000000222, 20.0, 100000.0, 1.7717158630001672e+225, 3e-11], + [1.0000000000000222, 100.0, 100000.0, 1.0269334595866202e+22, np.nan], + [1.5, 0.0, 500.0, 15648961196.432373, 3e-11], + [1.5, 2.220446049250313e-14, 500.0, 15648961196.431465, 3e-11], + [1.5, 1e-10, 500.0, 15648961192.344728, 3e-11], + [1.5, 1e-05, 500.0, 15648552437.334162, 3e-11], + [1.5, 0.1, 500.0, 12049870581.10317, 2e-11], + [1.5, 20.0, 100000.0, 7.81930438331405e+43, 3e-9], + [1.5, 100.0, 100000.0, 9.653370857459075e-130, np.nan], + ]) + + +@pytest.mark.xfail +@pytest.mark.parametrize( + 'a, b, x, phi', + grid_a_b_x_value_acc[:, :4].tolist()) +def test_wright_data_grid_failures(a, b, x, phi): + """Test cases of test_data that do not reach relative accuracy of 1e-11""" + assert_allclose(wright_bessel(a, b, x), phi, rtol=1e-11) + + +@pytest.mark.parametrize( + 'a, b, x, phi, accuracy', + grid_a_b_x_value_acc.tolist()) +def test_wright_data_grid_less_accurate(a, b, x, phi, accuracy): + """Test cases of test_data that do not reach relative accuracy of 1e-11 + + Here we test for reduced accuracy or even nan. + """ + if np.isnan(accuracy): + assert np.isnan(wright_bessel(a, b, x)) + else: + assert_allclose(wright_bessel(a, b, x), phi, rtol=accuracy) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py new file mode 100644 index 0000000000000000000000000000000000000000..c1a93ca007e42fea3a0dec634c51b37f03effa9e --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py @@ -0,0 +1,117 @@ +import pytest +import numpy as np +from numpy.testing import assert_, assert_equal, assert_allclose + +import scipy.special as sc +from scipy.special._testutils import assert_func_equal + + +def test_wrightomega_nan(): + pts = [complex(np.nan, 0), + complex(0, np.nan), + complex(np.nan, np.nan), + complex(np.nan, 1), + complex(1, np.nan)] + for p in pts: + res = sc.wrightomega(p) + assert_(np.isnan(res.real)) + assert_(np.isnan(res.imag)) + + +def test_wrightomega_inf_branch(): + pts = [complex(-np.inf, np.pi/4), + complex(-np.inf, -np.pi/4), + complex(-np.inf, 3*np.pi/4), + complex(-np.inf, -3*np.pi/4)] + expected_results = [complex(0.0, 0.0), + complex(0.0, -0.0), + complex(-0.0, 0.0), + complex(-0.0, -0.0)] + for p, expected in zip(pts, expected_results): + res = sc.wrightomega(p) + # We can't use assert_equal(res, expected) because in older versions of + # numpy, assert_equal doesn't check the sign of the real and imaginary + # parts when comparing complex zeros. It does check the sign when the + # arguments are *real* scalars. + assert_equal(res.real, expected.real) + assert_equal(res.imag, expected.imag) + + +def test_wrightomega_inf(): + pts = [complex(np.inf, 10), + complex(-np.inf, 10), + complex(10, np.inf), + complex(10, -np.inf)] + for p in pts: + assert_equal(sc.wrightomega(p), p) + + +def test_wrightomega_singular(): + pts = [complex(-1.0, np.pi), + complex(-1.0, -np.pi)] + for p in pts: + res = sc.wrightomega(p) + assert_equal(res, -1.0) + assert_(np.signbit(res.imag) == np.bool_(False)) + + +@pytest.mark.parametrize('x, desired', [ + (-np.inf, 0), + (np.inf, np.inf), +]) +def test_wrightomega_real_infinities(x, desired): + assert sc.wrightomega(x) == desired + + +def test_wrightomega_real_nan(): + assert np.isnan(sc.wrightomega(np.nan)) + + +def test_wrightomega_real_series_crossover(): + desired_error = 2 * np.finfo(float).eps + crossover = 1e20 + x_before_crossover = np.nextafter(crossover, -np.inf) + x_after_crossover = np.nextafter(crossover, np.inf) + # Computed using Mpmath + desired_before_crossover = 99999999999999983569.948 + desired_after_crossover = 100000000000000016337.948 + assert_allclose( + sc.wrightomega(x_before_crossover), + desired_before_crossover, + atol=0, + rtol=desired_error, + ) + assert_allclose( + sc.wrightomega(x_after_crossover), + desired_after_crossover, + atol=0, + rtol=desired_error, + ) + + +def test_wrightomega_exp_approximation_crossover(): + desired_error = 2 * np.finfo(float).eps + crossover = -50 + x_before_crossover = np.nextafter(crossover, np.inf) + x_after_crossover = np.nextafter(crossover, -np.inf) + # Computed using Mpmath + desired_before_crossover = 1.9287498479639314876e-22 + desired_after_crossover = 1.9287498479639040784e-22 + assert_allclose( + sc.wrightomega(x_before_crossover), + desired_before_crossover, + atol=0, + rtol=desired_error, + ) + assert_allclose( + sc.wrightomega(x_after_crossover), + desired_after_crossover, + atol=0, + rtol=desired_error, + ) + + +def test_wrightomega_real_versus_complex(): + x = np.linspace(-500, 500, 1001) + results = sc.wrightomega(x + 0j).real + assert_func_equal(sc.wrightomega, results, x, atol=0, rtol=1e-14) diff --git a/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py b/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py new file mode 100644 index 0000000000000000000000000000000000000000..82b3245cac5399e5d6877fe2d8b2ddad585e9c2a --- /dev/null +++ b/venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py @@ -0,0 +1,49 @@ +import scipy.special as sc +import numpy as np +from numpy.testing import assert_equal, assert_allclose + + +def test_zeta(): + assert_allclose(sc.zeta(2,2), np.pi**2/6 - 1, rtol=1e-12) + + +def test_zetac(): + # Expected values in the following were computed using Wolfram + # Alpha's `Zeta[x] - 1` + x = [-2.1, 0.8, 0.9999, 9, 50, 75] + desired = [ + -0.9972705002153750, + -5.437538415895550, + -10000.42279161673, + 0.002008392826082214, + 8.881784210930816e-16, + 2.646977960169853e-23, + ] + assert_allclose(sc.zetac(x), desired, rtol=1e-12) + + +def test_zetac_special_cases(): + assert sc.zetac(np.inf) == 0 + assert np.isnan(sc.zetac(-np.inf)) + assert sc.zetac(0) == -1.5 + assert sc.zetac(1.0) == np.inf + + assert_equal(sc.zetac([-2, -50, -100]), -1) + + +def test_riemann_zeta_special_cases(): + assert np.isnan(sc.zeta(np.nan)) + assert sc.zeta(np.inf) == 1 + assert sc.zeta(0) == -0.5 + + # Riemann zeta is zero add negative even integers. + assert_equal(sc.zeta([-2, -4, -6, -8, -10]), 0) + + assert_allclose(sc.zeta(2), np.pi**2/6, rtol=1e-12) + assert_allclose(sc.zeta(4), np.pi**4/90, rtol=1e-12) + + +def test_riemann_zeta_avoid_overflow(): + s = -260.00000000001 + desired = -5.6966307844402683127e+297 # Computed with Mpmath + assert_allclose(sc.zeta(s), desired, atol=0, rtol=5e-14)