Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+8
- openflamingo/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/cython_blas.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npzAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/spatial/_ckdtree.cpython-310-x86_64-linux-gnu.soAdded+3
- openflamingo/lib/python3.10/site-packages/scipy/special/_ellip_harm.pyAdded+214
- openflamingo/lib/python3.10/site-packages/scipy/special/_lambertw.pyAdded+149
- openflamingo/lib/python3.10/site-packages/scipy/special/_spfun_stats.pyAdded+106
- openflamingo/lib/python3.10/site-packages/scipy/special/_test_internal.pyiAdded+9
- openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs.pyiAdded+526
- openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyxAdded+181
- openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.hAdded+185
- openflamingo/lib/python3.10/site-packages/scipy/special/cython_special.pyxAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_faddeeva.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_log_softmax.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logit.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logsumexp.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sici.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spfun_stats.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wright_bessel.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wrightomega.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_basic.pyAdded
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.pyAdded+112
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.pyAdded+106
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.pyAdded+527
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.pyAdded+49
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.pyAdded+363
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_data.pyAdded+725
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_dd.pyAdded+46
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_digamma.pyAdded+45
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.pyAdded+278
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.pyAdded+89
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.pyAdded+118
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.pyAdded+85
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_gamma.pyAdded+12
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.pyAdded+136
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.pyAdded+140
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.pyAdded+495
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.pyAdded+109
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.pyAdded+70
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.pyAdded+207
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.pyAdded+2272
- openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.pyAdded+64
785 unmodified lines786787788785 unmodified linesphi4/lib/python3.10/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/io/matlab/_streams.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/io/matlab/_mio5_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text785 unmodified lines786787788789790791792793794795796785 unmodified linesphi4/lib/python3.10/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/io/matlab/_streams.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/io/matlab/_mio5_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textphi4/lib/python3.10/site-packages/numpy/random/bit_generator.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/linalg/cython_blas.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/spatial/_ckdtree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textopenflamingo/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:c39ee117a6cbc87241a50a1b1b7047fa515577945ba129a92c814fc412ee07a0size 1201320123version https://git-lfs.github.com/spec/v1oid sha256:e10940ad4a98bb79181b57eb89e4d5276eed0f3bd2a265cd3ec44cab53574076size 633088123version https://git-lfs.github.com/spec/v1oid sha256:a0e5736df7906bb83eeda658132fa48dc14e5bccb14a75bc36d9fd3e31c80095size 372704123version https://git-lfs.github.com/spec/v1oid sha256:8ec6a3bda2516baea6b3fa92a36206684d7d58385879c6d7173dcd717866c619size 525696123version https://git-lfs.github.com/spec/v1oid sha256:d1a4ff5e2e26f8b33cb6c9b2c4eb9e537b2bef411bd914a024f9751fe33a3063size 300152123version https://git-lfs.github.com/spec/v1oid sha256:ec86a3f8443905debab4b9fc6a858e7b587767473297b3f855a8f3249f0b8cf4size 348849123version https://git-lfs.github.com/spec/v1oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5size 2164123version https://git-lfs.github.com/spec/v1oid sha256:1031461363c3772a9a32030693341b112093ff989eab6e3d04213d6873c235d9size 1027824123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214import numpy as np
from ._ufuncs import _ellip_harmfrom ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
def ellip_harm(h2, k2, n, p, s, signm=1, signn=1): r""" Ellipsoidal harmonic functions E^p_n(l)
These are also known as Lame functions of the first kind, and are solutions to the Lame equation:
.. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not returned) corresponding to the solutions.
Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree s : float Coordinate p : int Order, can range between [1,2n+1] signm : {1, -1}, optional Sign of prefactor of functions. Can be +/-1. See Notes. signn : {1, -1}, optional Sign of prefactor of functions. Can be +/-1. See Notes.
Returns ------- E : float the harmonic :math:`E^p_n(s)`
See Also -------- ellip_harm_2, ellip_normal
Notes ----- The geometric interpretation of the ellipsoidal functions is explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the sign of prefactors for functions according to their type::
K : +1 L : signm M : signn N : signm*signn
.. versionadded:: 0.15.0
References ---------- .. [1] Digital Library of Mathematical Functions 29.12 https://dlmf.nist.gov/29.12 .. [2] Bardhan and Knepley, "Computational science and re-discovery: open-source implementations of ellipsoidal harmonics for problems in potential theory", Comput. Sci. Disc. 5, 014006 (2012) :doi:`10.1088/1749-4699/5/1/014006`. .. [3] David J.and Dechambre P, "Computation of Ellipsoidal Gravity Field Harmonics for small solar system bodies" pp. 30-36, 2000 .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications" pp. 418, 2012
Examples -------- >>> from scipy.special import ellip_harm >>> w = ellip_harm(5,8,1,1,2.5) >>> w 2.5
Check that the functions indeed are solutions to the Lame equation:
>>> import numpy as np >>> from scipy.interpolate import UnivariateSpline >>> def eigenvalue(f, df, ddf): ... r = (((s**2 - h**2) * (s**2 - k**2) * ddf ... + s * (2*s**2 - h**2 - k**2) * df ... - n * (n + 1)*s**2*f) / f) ... return -r.mean(), r.std() >>> s = np.linspace(0.1, 10, 200) >>> k, h, n, p = 8.0, 2.2, 3, 2 >>> E = ellip_harm(h**2, k**2, n, p, s) >>> E_spl = UnivariateSpline(s, E) >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2)) >>> a, a_err (583.44366156701483, 6.4580890640310646e-11)
""" # noqa: E501 return _ellip_harm(h2, k2, n, p, s, signm, signn)
_ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
def ellip_harm_2(h2, k2, n, p, s): r""" Ellipsoidal harmonic functions F^p_n(l)
These are also known as Lame functions of the second kind, and are solutions to the Lame equation:
.. math:: (s^2 - h^2)(s^2 - k^2)F''(s) + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not returned) corresponding to the solutions.
Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree. p : int Order, can range between [1,2n+1]. s : float Coordinate
Returns ------- F : float The harmonic :math:`F^p_n(s)`
See Also -------- ellip_harm, ellip_normal
Notes ----- Lame functions of the second kind are related to the functions of the first kind:
.. math::
F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s} \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
.. versionadded:: 0.15.0
Examples -------- >>> from scipy.special import ellip_harm_2 >>> w = ellip_harm_2(5,8,2,1,10) >>> w 0.00108056853382
""" with np.errstate(all='ignore'): return _ellip_harm_2_vec(h2, k2, n, p, s)
def _ellip_normal_vec(h2, k2, n, p): return _ellipsoid_norm(h2, k2, n, p)
_ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
def ellip_normal(h2, k2, n, p): r""" Ellipsoidal harmonic normalization constants gamma^p_n
The normalization constant is defined as
.. math::
\gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree. p : int Order, can range between [1,2n+1].
Returns ------- gamma : float The normalization constant :math:`\gamma^p_n`
See Also -------- ellip_harm, ellip_harm_2
Notes ----- .. versionadded:: 0.15.0
Examples -------- >>> from scipy.special import ellip_normal >>> w = ellip_normal(5,8,3,7) >>> w 1723.38796997
""" with np.errstate(all='ignore'): return _ellip_normal_vec(h2, k2, n, p)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149from ._ufuncs import _lambertw
import numpy as np
def lambertw(z, k=0, tol=1e-8): r""" lambertw(z, k=0, tol=1e-8)
Lambert W function.
The Lambert W function `W(z)` is defined as the inverse function of ``w * exp(w)``. In other words, the value of ``W(z)`` is such that ``z = W(z) * exp(W(z))`` for any complex number ``z``.
The Lambert W function is a multivalued function with infinitely many branches. Each branch gives a separate solution of the equation ``z = w exp(w)``. Here, the branches are indexed by the integer `k`.
Parameters ---------- z : array_like Input argument. k : int, optional Branch index. tol : float, optional Evaluation tolerance.
Returns ------- w : array `w` will have the same shape as `z`.
See Also -------- wrightomega : the Wright Omega function
Notes ----- All branches are supported by `lambertw`:
* ``lambertw(z)`` gives the principal solution (branch 0) * ``lambertw(z, k)`` gives the solution on branch `k`
The Lambert W function has two partially real branches: the principal branch (`k = 0`) is real for real ``z > -1/e``, and the ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except ``k = 0`` have a logarithmic singularity at ``z = 0``.
**Possible issues**
The evaluation can become inaccurate very close to the branch point at ``-1/e``. In some corner cases, `lambertw` might currently fail to converge, or can end up on the wrong branch.
**Algorithm**
Halley's iteration is used to invert ``w * exp(w)``, using a first-order asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate.
The definition, implementation and choice of branches is based on [2]_.
References ---------- .. [1] https://en.wikipedia.org/wiki/Lambert_W_function .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5 (1996) 329-359. https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
Examples -------- The Lambert W function is the inverse of ``w exp(w)``:
>>> import numpy as np >>> from scipy.special import lambertw >>> w = lambertw(1) >>> w (0.56714329040978384+0j) >>> w * np.exp(w) (1.0+0j)
Any branch gives a valid inverse:
>>> w = lambertw(1, k=3) >>> w (-2.8535817554090377+17.113535539412148j) >>> w*np.exp(w) (1.0000000000000002+1.609823385706477e-15j)
**Applications to equation-solving**
The Lambert W function may be used to solve various kinds of equations. We give two examples here.
First, the function can be used to solve implicit equations of the form
:math:`x = a + b e^{c x}`
for :math:`x`. We assume :math:`c` is not zero. After a little algebra, the equation may be written
:math:`z e^z = -b c e^{a c}`
where :math:`z = c (a - x)`. :math:`z` may then be expressed using the Lambert W function
:math:`z = W(-b c e^{a c})`
giving
:math:`x = a - W(-b c e^{a c})/c`
For example,
>>> a = 3 >>> b = 2 >>> c = -0.5
The solution to :math:`x = a + b e^{c x}` is:
>>> x = a - lambertw(-b*c*np.exp(a*c))/c >>> x (3.3707498368978794+0j)
Verify that it solves the equation:
>>> a + b*np.exp(c*x) (3.37074983689788+0j)
The Lambert W function may also be used find the value of the infinite power tower :math:`z^{z^{z^{\ldots}}}`:
>>> def tower(z, n): ... if n == 0: ... return z ... return z ** tower(z, n-1) ... >>> tower(0.5, 100) 0.641185744504986 >>> -lambertw(-np.log(0.5)) / np.log(0.5) (0.64118574450498589+0j) """ # TODO: special expert should inspect this # interception; better place to do it? k = np.asarray(k, dtype=np.dtype("long")) return _lambertw(z, k, tol)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106# Last Change: Sat Mar 21 02:00 PM 2009 J
# Copyright (c) 2001, 2002 Enthought, Inc.## All rights reserved.## Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions are met:## a. Redistributions of source code must retain the above copyright notice,# this list of conditions and the following disclaimer.# b. Redistributions in binary form must reproduce the above copyright# notice, this list of conditions and the following disclaimer in the# documentation and/or other materials provided with the distribution.# c. Neither the name of the Enthought nor the names of its contributors# may be used to endorse or promote products derived from this software# without specific prior written permission.### THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH# DAMAGE.
"""Some more special functions which may be useful for multivariate statisticalanalysis."""
import numpy as npfrom scipy.special import gammaln as loggam
__all__ = ['multigammaln']
def multigammaln(a, d): r"""Returns the log of multivariate gamma, also sometimes called the generalized gamma.
Parameters ---------- a : ndarray The multivariate gamma is computed for each item of `a`. d : int The dimension of the space of integration.
Returns ------- res : ndarray The values of the log multivariate gamma at the given points `a`.
Notes ----- The formal definition of the multivariate gamma of dimension d for a real `a` is
.. math::
\Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA
with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of all the positive definite matrices of dimension `d`. Note that `a` is a scalar: the integrand only is multivariate, the argument is not (the function is defined over a subset of the real set).
This can be proven to be equal to the much friendlier equation
.. math::
\Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2).
References ---------- R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in probability and mathematical statistics).
Examples -------- >>> import numpy as np >>> from scipy.special import multigammaln, gammaln >>> a = 23.5 >>> d = 10 >>> multigammaln(a, d) 454.1488605074416
Verify that the result agrees with the logarithm of the equation shown above:
>>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum() 454.1488605074416 """ a = np.asarray(a) if not np.isscalar(d) or (np.floor(d) != d): raise ValueError("d should be a positive integer (dimension)") if np.any(a <= 0.5 * (d - 1)): raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met")
res = (d * (d-1) * 0.25) * np.log(np.pi) res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0) return res123456789import numpy as np
def have_fenv() -> bool: ...def random_double(size: int) -> np.float64: ...def test_add_round(size: int, mode: str): ...
def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ...def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ...def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526# This file is automatically generated by _generate_pyx.py.# Do not edit manually!
from typing import Any, Dict
import numpy as np
__all__ = [ 'geterr', 'seterr', 'errstate', 'agm', 'airy', 'airye', 'bdtr', 'bdtrc', 'bdtri', 'bdtrik', 'bdtrin', 'bei', 'beip', 'ber', 'berp', 'besselpoly', 'beta', 'betainc', 'betaincc', 'betainccinv', 'betaincinv', 'betaln', 'binom', 'boxcox', 'boxcox1p', 'btdtr', 'btdtri', 'btdtria', 'btdtrib', 'cbrt', 'chdtr', 'chdtrc', 'chdtri', 'chdtriv', 'chndtr', 'chndtridf', 'chndtrinc', 'chndtrix', 'cosdg', 'cosm1', 'cotdg', 'dawsn', 'ellipe', 'ellipeinc', 'ellipj', 'ellipk', 'ellipkinc', 'ellipkm1', 'elliprc', 'elliprd', 'elliprf', 'elliprg', 'elliprj', 'entr', 'erf', 'erfc', 'erfcinv', 'erfcx', 'erfi', 'erfinv', 'eval_chebyc', 'eval_chebys', 'eval_chebyt', 'eval_chebyu', 'eval_gegenbauer', 'eval_genlaguerre', 'eval_hermite', 'eval_hermitenorm', 'eval_jacobi', 'eval_laguerre', 'eval_legendre', 'eval_sh_chebyt', 'eval_sh_chebyu', 'eval_sh_jacobi', 'eval_sh_legendre', 'exp1', 'exp10', 'exp2', 'expi', 'expit', 'expm1', 'expn', 'exprel', 'fdtr', 'fdtrc', 'fdtri', 'fdtridfd', 'fresnel', 'gamma', 'gammainc', 'gammaincc', 'gammainccinv', 'gammaincinv', 'gammaln', 'gammasgn', 'gdtr', 'gdtrc', 'gdtria', 'gdtrib', 'gdtrix', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e', 'huber', 'hyp0f1', 'hyp1f1', 'hyp2f1', 'hyperu', 'i0', 'i0e', 'i1', 'i1e', 'inv_boxcox', 'inv_boxcox1p', 'it2i0k0', 'it2j0y0', 'it2struve0', 'itairy', 'iti0k0', 'itj0y0', 'itmodstruve0', 'itstruve0', 'iv', 'ive', 'j0', 'j1', 'jn', 'jv', 'jve', 'k0', 'k0e', 'k1', 'k1e', 'kei', 'keip', 'kelvin', 'ker', 'kerp', 'kl_div', 'kn', 'kolmogi', 'kolmogorov', 'kv', 'kve', 'log1p', 'log_expit', 'log_ndtr', 'loggamma', 'logit', 'lpmv', 'mathieu_a', 'mathieu_b', 'mathieu_cem', 'mathieu_modcem1', 'mathieu_modcem2', 'mathieu_modsem1', 'mathieu_modsem2', 'mathieu_sem', 'modfresnelm', 'modfresnelp', 'modstruve', 'nbdtr', 'nbdtrc', 'nbdtri', 'nbdtrik', 'nbdtrin', 'ncfdtr', 'ncfdtri', 'ncfdtridfd', 'ncfdtridfn', 'ncfdtrinc', 'nctdtr', 'nctdtridf', 'nctdtrinc', 'nctdtrit', 'ndtr', 'ndtri', 'ndtri_exp', 'nrdtrimn', 'nrdtrisd', 'obl_ang1', 'obl_ang1_cv', 'obl_cv', 'obl_rad1', 'obl_rad1_cv', 'obl_rad2', 'obl_rad2_cv', 'owens_t', 'pbdv', 'pbvv', 'pbwa', 'pdtr', 'pdtrc', 'pdtri', 'pdtrik', 'poch', 'powm1', 'pro_ang1', 'pro_ang1_cv', 'pro_cv', 'pro_rad1', 'pro_rad1_cv', 'pro_rad2', 'pro_rad2_cv', 'pseudo_huber', 'psi', 'radian', 'rel_entr', 'rgamma', 'round', 'shichi', 'sici', 'sindg', 'smirnov', 'smirnovi', 'spence', 'sph_harm', 'stdtr', 'stdtridf', 'stdtrit', 'struve', 'tandg', 'tklmbda', 'voigt_profile', 'wofz', 'wright_bessel', 'wrightomega', 'xlog1py', 'xlogy', 'y0', 'y1', 'yn', 'yv', 'yve', 'zetac']
def geterr() -> Dict[str, str]: ...def seterr(**kwargs: str) -> Dict[str, str]: ...
class errstate: def __init__(self, **kargs: str) -> None: ... def __enter__(self) -> None: ... def __exit__( self, exc_type: Any, # Unused exc_value: Any, # Unused traceback: Any, # Unused ) -> None: ...
_cosine_cdf: np.ufunc_cosine_invcdf: np.ufunc_cospi: np.ufunc_ellip_harm: np.ufunc_factorial: np.ufunc_igam_fac: np.ufunc_kolmogc: np.ufunc_kolmogci: np.ufunc_kolmogp: np.ufunc_lambertw: np.ufunc_lanczos_sum_expg_scaled: np.ufunc_lgam1p: np.ufunc_log1pmx: np.ufunc_riemann_zeta: np.ufunc_scaled_exp1: np.ufunc_sf_error_test_function: np.ufunc_sinpi: np.ufunc_smirnovc: np.ufunc_smirnovci: np.ufunc_smirnovp: np.ufunc_spherical_in: np.ufunc_spherical_in_d: np.ufunc_spherical_jn: np.ufunc_spherical_jn_d: np.ufunc_spherical_kn: np.ufunc_spherical_kn_d: np.ufunc_spherical_yn: np.ufunc_spherical_yn_d: np.ufunc_stirling2_inexact: np.ufunc_struve_asymp_large_z: np.ufunc_struve_bessel_series: np.ufunc_struve_power_series: np.ufunc_zeta: np.ufuncagm: np.ufuncairy: np.ufuncairye: np.ufuncbdtr: np.ufuncbdtrc: np.ufuncbdtri: np.ufuncbdtrik: np.ufuncbdtrin: np.ufuncbei: np.ufuncbeip: np.ufuncber: np.ufuncberp: np.ufuncbesselpoly: np.ufuncbeta: np.ufuncbetainc: np.ufuncbetaincc: np.ufuncbetainccinv: np.ufuncbetaincinv: np.ufuncbetaln: np.ufuncbinom: np.ufuncboxcox1p: np.ufuncboxcox: np.ufuncbtdtr: np.ufuncbtdtri: np.ufuncbtdtria: np.ufuncbtdtrib: np.ufunccbrt: np.ufuncchdtr: np.ufuncchdtrc: np.ufuncchdtri: np.ufuncchdtriv: np.ufuncchndtr: np.ufuncchndtridf: np.ufuncchndtrinc: np.ufuncchndtrix: np.ufunccosdg: np.ufunccosm1: np.ufunccotdg: np.ufuncdawsn: np.ufuncellipe: np.ufuncellipeinc: np.ufuncellipj: np.ufuncellipk: np.ufuncellipkinc: np.ufuncellipkm1: np.ufuncelliprc: np.ufuncelliprd: np.ufuncelliprf: np.ufuncelliprg: np.ufuncelliprj: np.ufuncentr: np.ufuncerf: np.ufuncerfc: np.ufuncerfcinv: np.ufuncerfcx: np.ufuncerfi: np.ufuncerfinv: np.ufunceval_chebyc: np.ufunceval_chebys: np.ufunceval_chebyt: np.ufunceval_chebyu: np.ufunceval_gegenbauer: np.ufunceval_genlaguerre: np.ufunceval_hermite: np.ufunceval_hermitenorm: np.ufunceval_jacobi: np.ufunceval_laguerre: np.ufunceval_legendre: np.ufunceval_sh_chebyt: np.ufunceval_sh_chebyu: np.ufunceval_sh_jacobi: np.ufunceval_sh_legendre: np.ufuncexp10: np.ufuncexp1: np.ufuncexp2: np.ufuncexpi: np.ufuncexpit: np.ufuncexpm1: np.ufuncexpn: np.ufuncexprel: np.ufuncfdtr: np.ufuncfdtrc: np.ufuncfdtri: np.ufuncfdtridfd: np.ufuncfresnel: np.ufuncgamma: np.ufuncgammainc: np.ufuncgammaincc: np.ufuncgammainccinv: np.ufuncgammaincinv: np.ufuncgammaln: np.ufuncgammasgn: np.ufuncgdtr: np.ufuncgdtrc: np.ufuncgdtria: np.ufuncgdtrib: np.ufuncgdtrix: np.ufunchankel1: np.ufunchankel1e: np.ufunchankel2: np.ufunchankel2e: np.ufunchuber: np.ufunchyp0f1: np.ufunchyp1f1: np.ufunchyp2f1: np.ufunchyperu: np.ufunci0: np.ufunci0e: np.ufunci1: np.ufunci1e: np.ufuncinv_boxcox1p: np.ufuncinv_boxcox: np.ufuncit2i0k0: np.ufuncit2j0y0: np.ufuncit2struve0: np.ufuncitairy: np.ufunciti0k0: np.ufuncitj0y0: np.ufuncitmodstruve0: np.ufuncitstruve0: np.ufunciv: np.ufuncive: np.ufuncj0: np.ufuncj1: np.ufuncjn: np.ufuncjv: np.ufuncjve: np.ufunck0: np.ufunck0e: np.ufunck1: np.ufunck1e: np.ufunckei: np.ufunckeip: np.ufunckelvin: np.ufuncker: np.ufunckerp: np.ufunckl_div: np.ufunckn: np.ufunckolmogi: np.ufunckolmogorov: np.ufunckv: np.ufunckve: np.ufunclog1p: np.ufunclog_expit: np.ufunclog_ndtr: np.ufuncloggamma: np.ufunclogit: np.ufunclpmv: np.ufuncmathieu_a: np.ufuncmathieu_b: np.ufuncmathieu_cem: np.ufuncmathieu_modcem1: np.ufuncmathieu_modcem2: np.ufuncmathieu_modsem1: np.ufuncmathieu_modsem2: np.ufuncmathieu_sem: np.ufuncmodfresnelm: np.ufuncmodfresnelp: np.ufuncmodstruve: np.ufuncnbdtr: np.ufuncnbdtrc: np.ufuncnbdtri: np.ufuncnbdtrik: np.ufuncnbdtrin: np.ufuncncfdtr: np.ufuncncfdtri: np.ufuncncfdtridfd: np.ufuncncfdtridfn: np.ufuncncfdtrinc: np.ufuncnctdtr: np.ufuncnctdtridf: np.ufuncnctdtrinc: np.ufuncnctdtrit: np.ufuncndtr: np.ufuncndtri: np.ufuncndtri_exp: np.ufuncnrdtrimn: np.ufuncnrdtrisd: np.ufuncobl_ang1: np.ufuncobl_ang1_cv: np.ufuncobl_cv: np.ufuncobl_rad1: np.ufuncobl_rad1_cv: np.ufuncobl_rad2: np.ufuncobl_rad2_cv: np.ufuncowens_t: np.ufuncpbdv: np.ufuncpbvv: np.ufuncpbwa: np.ufuncpdtr: np.ufuncpdtrc: np.ufuncpdtri: np.ufuncpdtrik: np.ufuncpoch: np.ufuncpowm1: np.ufuncpro_ang1: np.ufuncpro_ang1_cv: np.ufuncpro_cv: np.ufuncpro_rad1: np.ufuncpro_rad1_cv: np.ufuncpro_rad2: np.ufuncpro_rad2_cv: np.ufuncpseudo_huber: np.ufuncpsi: np.ufuncradian: np.ufuncrel_entr: np.ufuncrgamma: np.ufuncround: np.ufuncshichi: np.ufuncsici: np.ufuncsindg: np.ufuncsmirnov: np.ufuncsmirnovi: np.ufuncspence: np.ufuncsph_harm: np.ufuncstdtr: np.ufuncstdtridf: np.ufuncstdtrit: np.ufuncstruve: np.ufunctandg: np.ufunctklmbda: np.ufuncvoigt_profile: np.ufuncwofz: np.ufuncwright_bessel: np.ufuncwrightomega: np.ufuncxlog1py: np.ufuncxlogy: np.ufuncy0: np.ufuncy1: np.ufuncyn: np.ufuncyv: np.ufuncyve: np.ufunczetac: np.ufunc
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181# This file is automatically generated by _generate_pyx.py.# Do not edit manually!
from libc.math cimport NAN
include "_ufuncs_extra_code_common.pxi"
cdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_ccospi "ccospi"(double complex) noexcept nogilcdef void *_export_ccospi = <void*>_func_ccospicdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_lambertw_scalar "lambertw_scalar"(double complex, long, double) noexcept nogilcdef void *_export_lambertw_scalar = <void*>_func_lambertw_scalarcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_csinpi "csinpi"(double complex) noexcept nogilcdef void *_export_csinpi = <void*>_func_csinpicdef extern from r"_ufuncs_cxx_defs.h": cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogilcdef void *_export__stirling2_inexact = <void*>_func__stirling2_inexactcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogilcdef void *_export_ibeta_float = <void*>_func_ibeta_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogilcdef void *_export_ibeta_double = <void*>_func_ibeta_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogilcdef void *_export_ibetac_float = <void*>_func_ibetac_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogilcdef void *_export_ibetac_double = <void*>_func_ibetac_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogilcdef void *_export_ibetac_inv_float = <void*>_func_ibetac_inv_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogilcdef void *_export_ibetac_inv_double = <void*>_func_ibetac_inv_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogilcdef void *_export_ibeta_inv_float = <void*>_func_ibeta_inv_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogilcdef void *_export_ibeta_inv_double = <void*>_func_ibeta_inv_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_binom "binom"(double, double) noexcept nogilcdef void *_export_binom = <void*>_func_binomcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogilcdef void *_export_faddeeva_dawsn = <void*>_func_faddeeva_dawsncdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogilcdef void *_export_faddeeva_dawsn_complex = <void*>_func_faddeeva_dawsn_complexcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogilcdef void *_export_fellint_RC = <void*>_func_fellint_RCcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogilcdef void *_export_cellint_RC = <void*>_func_cellint_RCcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogilcdef void *_export_fellint_RD = <void*>_func_fellint_RDcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogilcdef void *_export_cellint_RD = <void*>_func_cellint_RDcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogilcdef void *_export_fellint_RF = <void*>_func_fellint_RFcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogilcdef void *_export_cellint_RF = <void*>_func_cellint_RFcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogilcdef void *_export_fellint_RG = <void*>_func_fellint_RGcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogilcdef void *_export_cellint_RG = <void*>_func_cellint_RGcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogilcdef void *_export_fellint_RJ = <void*>_func_fellint_RJcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogilcdef void *_export_cellint_RJ = <void*>_func_cellint_RJcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogilcdef void *_export_faddeeva_erf = <void*>_func_faddeeva_erfcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogilcdef void *_export_faddeeva_erfc_complex = <void*>_func_faddeeva_erfc_complexcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogilcdef void *_export_faddeeva_erfcx = <void*>_func_faddeeva_erfcxcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogilcdef void *_export_faddeeva_erfcx_complex = <void*>_func_faddeeva_erfcx_complexcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogilcdef void *_export_faddeeva_erfi = <void*>_func_faddeeva_erficdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogilcdef void *_export_faddeeva_erfi_complex = <void*>_func_faddeeva_erfi_complexcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogilcdef void *_export_erfinv_float = <void*>_func_erfinv_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogilcdef void *_export_erfinv_double = <void*>_func_erfinv_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_expit "expit"(double) noexcept nogilcdef void *_export_expit = <void*>_func_expitcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_expitf "expitf"(float) noexcept nogilcdef void *_export_expitf = <void*>_func_expitfcdef extern from r"_ufuncs_cxx_defs.h": cdef long double _func_expitl "expitl"(long double) noexcept nogilcdef void *_export_expitl = <void*>_func_expitlcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cgamma "cgamma"(double complex) noexcept nogilcdef void *_export_cgamma = <void*>_func_cgammacdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogilcdef void *_export_hyp1f1_double = <void*>_func_hyp1f1_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_log_expit "log_expit"(double) noexcept nogilcdef void *_export_log_expit = <void*>_func_log_expitcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_log_expitf "log_expitf"(float) noexcept nogilcdef void *_export_log_expitf = <void*>_func_log_expitfcdef extern from r"_ufuncs_cxx_defs.h": cdef long double _func_log_expitl "log_expitl"(long double) noexcept nogilcdef void *_export_log_expitl = <void*>_func_log_expitlcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogilcdef void *_export_faddeeva_log_ndtr = <void*>_func_faddeeva_log_ndtrcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogilcdef void *_export_faddeeva_log_ndtr_complex = <void*>_func_faddeeva_log_ndtr_complexcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_loggamma_real "loggamma_real"(double) noexcept nogilcdef void *_export_loggamma_real = <void*>_func_loggamma_realcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_loggamma "loggamma"(double complex) noexcept nogilcdef void *_export_loggamma = <void*>_func_loggammacdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_logit "logit"(double) noexcept nogilcdef void *_export_logit = <void*>_func_logitcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_logitf "logitf"(float) noexcept nogilcdef void *_export_logitf = <void*>_func_logitfcdef extern from r"_ufuncs_cxx_defs.h": cdef long double _func_logitl "logitl"(long double) noexcept nogilcdef void *_export_logitl = <void*>_func_logitlcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogilcdef void *_export_faddeeva_ndtr = <void*>_func_faddeeva_ndtrcdef extern from r"_ufuncs_cxx_defs.h": cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogilcdef void *_export_powm1_float = <void*>_func_powm1_floatcdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogilcdef void *_export_powm1_double = <void*>_func_powm1_doublecdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_cdigamma "cdigamma"(double complex) noexcept nogilcdef void *_export_cdigamma = <void*>_func_cdigammacdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_digamma "digamma"(double) noexcept nogilcdef void *_export_digamma = <void*>_func_digammacdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_crgamma "crgamma"(double complex) noexcept nogilcdef void *_export_crgamma = <void*>_func_crgammacdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogilcdef void *_export_faddeeva_voigt_profile = <void*>_func_faddeeva_voigt_profilecdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogilcdef void *_export_faddeeva_w = <void*>_func_faddeeva_wcdef extern from r"_ufuncs_cxx_defs.h": cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogilcdef void *_export_wrightomega = <void*>_func_wrightomegacdef extern from r"_ufuncs_cxx_defs.h": cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogilcdef void *_export_wrightomega_real = <void*>_func_wrightomega_real123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185#ifndef UFUNCS_PROTO_H#define UFUNCS_PROTO_H 1#include "_cosine.h"npy_double cosine_cdf(npy_double);npy_double cosine_invcdf(npy_double);#include "cephes.h"npy_double cospi(npy_double);npy_double igam_fac(npy_double, npy_double);npy_double kolmogc(npy_double);npy_double kolmogci(npy_double);npy_double kolmogp(npy_double);npy_double lanczos_sum_expg_scaled(npy_double);npy_double lgam1p(npy_double);npy_double log1pmx(npy_double);npy_double riemann_zeta(npy_double);#include "scaled_exp1.h"npy_double scaled_exp1(npy_double);npy_double sinpi(npy_double);npy_double smirnovc(npy_int, npy_double);npy_double smirnovci(npy_int, npy_double);npy_double smirnovp(npy_int, npy_double);npy_double struve_asymp_large_z(npy_double, npy_double, npy_int, npy_double *);npy_double struve_bessel_series(npy_double, npy_double, npy_int, npy_double *);npy_double struve_power_series(npy_double, npy_double, npy_int, npy_double *);npy_double zeta(npy_double, npy_double);#include "amos_wrappers.h"npy_int airy_wrap(npy_double, npy_double *, npy_double *, npy_double *, npy_double *);npy_int cairy_wrap(npy_cdouble, npy_cdouble *, npy_cdouble *, npy_cdouble *, npy_cdouble *);npy_int cairy_wrap_e(npy_cdouble, npy_cdouble *, npy_cdouble *, npy_cdouble *, npy_cdouble *);npy_int cairy_wrap_e_real(npy_double, npy_double *, npy_double *, npy_double *, npy_double *);npy_double bdtr(npy_double, npy_int, npy_double);npy_double bdtrc(npy_double, npy_int, npy_double);npy_double bdtri(npy_double, npy_int, npy_double);#include "specfun_wrappers.h"npy_double bei_wrap(npy_double);npy_double beip_wrap(npy_double);npy_double ber_wrap(npy_double);npy_double berp_wrap(npy_double);npy_double besselpoly(npy_double, npy_double, npy_double);npy_double beta(npy_double, npy_double);npy_double lbeta(npy_double, npy_double);npy_double btdtr(npy_double, npy_double, npy_double);npy_double incbi(npy_double, npy_double, npy_double);npy_double cbrt(npy_double);npy_double chdtr(npy_double, npy_double);npy_double chdtrc(npy_double, npy_double);npy_double chdtri(npy_double, npy_double);npy_double cosdg(npy_double);npy_double cosm1(npy_double);npy_double cotdg(npy_double);npy_double ellpe(npy_double);npy_double ellie(npy_double, npy_double);npy_int ellpj(npy_double, npy_double, npy_double *, npy_double *, npy_double *, npy_double *);npy_double ellik(npy_double, npy_double);npy_double ellpk(npy_double);npy_double erf(npy_double);npy_double erfc(npy_double);npy_double erfcinv(npy_double);npy_cdouble cexp1_wrap(npy_cdouble);npy_double exp1_wrap(npy_double);npy_double exp10(npy_double);npy_double exp2(npy_double);npy_cdouble cexpi_wrap(npy_cdouble);npy_double expi_wrap(npy_double);npy_double expm1(npy_double);npy_double expn(npy_int, npy_double);npy_double fdtr(npy_double, npy_double, npy_double);npy_double fdtrc(npy_double, npy_double, npy_double);npy_double fdtri(npy_double, npy_double, npy_double);npy_int fresnl(npy_double, npy_double *, npy_double *);npy_int cfresnl_wrap(npy_cdouble, npy_cdouble *, npy_cdouble *);npy_double Gamma(npy_double);npy_double igam(npy_double, npy_double);npy_double igamc(npy_double, npy_double);npy_double igamci(npy_double, npy_double);npy_double igami(npy_double, npy_double);npy_double lgam(npy_double);npy_double gammasgn(npy_double);npy_double gdtr(npy_double, npy_double, npy_double);npy_double gdtrc(npy_double, npy_double, npy_double);npy_cdouble cbesh_wrap1(npy_double, npy_cdouble);npy_cdouble cbesh_wrap1_e(npy_double, npy_cdouble);npy_cdouble cbesh_wrap2(npy_double, npy_cdouble);npy_cdouble cbesh_wrap2_e(npy_double, npy_cdouble);npy_cdouble chyp1f1_wrap(npy_double, npy_double, npy_cdouble);npy_double hyp2f1(npy_double, npy_double, npy_double, npy_double);npy_double i0(npy_double);npy_double i0e(npy_double);npy_double i1(npy_double);npy_double i1e(npy_double);npy_int it2i0k0_wrap(npy_double, npy_double *, npy_double *);npy_int it2j0y0_wrap(npy_double, npy_double *, npy_double *);npy_double it2struve0_wrap(npy_double);npy_int itairy_wrap(npy_double, npy_double *, npy_double *, npy_double *, npy_double *);npy_int it1i0k0_wrap(npy_double, npy_double *, npy_double *);npy_int it1j0y0_wrap(npy_double, npy_double *, npy_double *);npy_double itmodstruve0_wrap(npy_double);npy_double itstruve0_wrap(npy_double);npy_cdouble cbesi_wrap(npy_double, npy_cdouble);npy_double iv(npy_double, npy_double);npy_cdouble cbesi_wrap_e(npy_double, npy_cdouble);npy_double cbesi_wrap_e_real(npy_double, npy_double);npy_double j0(npy_double);npy_double j1(npy_double);npy_cdouble cbesj_wrap(npy_double, npy_cdouble);npy_double cbesj_wrap_real(npy_double, npy_double);npy_cdouble cbesj_wrap_e(npy_double, npy_cdouble);npy_double cbesj_wrap_e_real(npy_double, npy_double);npy_double k0(npy_double);npy_double k0e(npy_double);npy_double k1(npy_double);npy_double k1e(npy_double);npy_double kei_wrap(npy_double);npy_double keip_wrap(npy_double);npy_int kelvin_wrap(npy_double, npy_cdouble *, npy_cdouble *, npy_cdouble *, npy_cdouble *);npy_double ker_wrap(npy_double);npy_double kerp_wrap(npy_double);npy_double cbesk_wrap_real_int(npy_int, npy_double);npy_double kolmogi(npy_double);npy_double kolmogorov(npy_double);npy_cdouble cbesk_wrap(npy_double, npy_cdouble);npy_double cbesk_wrap_real(npy_double, npy_double);npy_cdouble cbesk_wrap_e(npy_double, npy_cdouble);npy_double cbesk_wrap_e_real(npy_double, npy_double);npy_double log1p(npy_double);npy_double pmv_wrap(npy_double, npy_double, npy_double);npy_double cem_cva_wrap(npy_double, npy_double);npy_double sem_cva_wrap(npy_double, npy_double);npy_int cem_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int mcm1_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int mcm2_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int msm1_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int msm2_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int sem_wrap(npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_int modified_fresnel_minus_wrap(npy_double, npy_cdouble *, npy_cdouble *);npy_int modified_fresnel_plus_wrap(npy_double, npy_cdouble *, npy_cdouble *);npy_double struve_l(npy_double, npy_double);npy_double nbdtr(npy_int, npy_int, npy_double);npy_double nbdtrc(npy_int, npy_int, npy_double);npy_double nbdtri(npy_int, npy_int, npy_double);npy_double ndtr(npy_double);npy_double ndtri(npy_double);npy_double oblate_aswfa_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int oblate_aswfa_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double oblate_segv_wrap(npy_double, npy_double, npy_double);npy_double oblate_radial1_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int oblate_radial1_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double oblate_radial2_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int oblate_radial2_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double owens_t(npy_double, npy_double);npy_int pbdv_wrap(npy_double, npy_double, npy_double *, npy_double *);npy_int pbvv_wrap(npy_double, npy_double, npy_double *, npy_double *);npy_int pbwa_wrap(npy_double, npy_double, npy_double *, npy_double *);npy_double pdtr(npy_double, npy_double);npy_double pdtrc(npy_double, npy_double);npy_double pdtri(npy_int, npy_double);npy_double poch(npy_double, npy_double);npy_double prolate_aswfa_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int prolate_aswfa_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double prolate_segv_wrap(npy_double, npy_double, npy_double);npy_double prolate_radial1_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int prolate_radial1_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double prolate_radial2_nocv_wrap(npy_double, npy_double, npy_double, npy_double, npy_double *);npy_int prolate_radial2_wrap(npy_double, npy_double, npy_double, npy_double, npy_double, npy_double *, npy_double *);npy_double radian(npy_double, npy_double, npy_double);npy_double rgamma(npy_double);npy_double round(npy_double);npy_int shichi(npy_double, npy_double *, npy_double *);npy_int sici(npy_double, npy_double *, npy_double *);npy_double sindg(npy_double);npy_double smirnov(npy_int, npy_double);npy_double smirnovi(npy_int, npy_double);npy_double spence(npy_double);npy_double struve_h(npy_double, npy_double);npy_double tandg(npy_double);npy_double tukeylambdacdf(npy_double, npy_double);npy_double y0(npy_double);npy_double y1(npy_double);npy_double yn(npy_int, npy_double);npy_cdouble cbesy_wrap(npy_double, npy_cdouble);npy_double cbesy_wrap_real(npy_double, npy_double);npy_cdouble cbesy_wrap_e(npy_double, npy_cdouble);npy_double cbesy_wrap_e_real(npy_double, npy_double);npy_double zetac(npy_double);#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import numpy as npimport scipy.special as scimport pytestfrom 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])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106import numpy as npfrom numpy.testing import assert_equal, assert_almost_equal, assert_allclosefrom 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527"""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 npfrom numpy.testing import assert_equal, assert_allcloseimport pytest
import scipy.special as spfrom scipy.special._testutils import ( MissingModule, check_version, FuncData)from scipy.special._mptestutils import ( Arg, IntArg, get_args, mpf2float, assert_mpmath_equal)
try: import mpmathexcept 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)))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# gh-14777 regression tests# Test stdtr and stdtrit with infinite df and large values of df
import numpy as npfrom numpy.testing import assert_allclose, assert_equalfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363from __future__ import annotationsfrom typing import Callable
import pytestfrom itertools import productfrom numpy.testing import assert_allclose, suppress_warningsfrom scipy import specialfrom 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}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725import importlib.resources
import numpy as npfrom numpy.testing import suppress_warningsimport 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Tests for a few of the "double-double" C functions defined in cephes/dd_*.
import pytestfrom numpy.testing import assert_allclosefrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445import numpy as npfrom numpy import pi, log, sqrtfrom numpy.testing import assert_, assert_equal
from scipy.special._testutils import FuncDataimport scipy.special as sc
# Euler-Mascheroni constanteuler = 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]))))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278## Tests for the Ellipsoidal Harmonic Function,# Distributed under the same license as SciPy itself.#
import numpy as npfrom numpy.testing import (assert_equal, assert_almost_equal, assert_allclose, assert_, suppress_warnings)from scipy.special._testutils import assert_func_equalfrom scipy.special import ellip_harm, ellip_harm_2, ellip_normalfrom scipy.integrate import IntegrationWarningfrom 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import numpy as npfrom numpy.testing import assert_allclose, assert_equalimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import pytest
import numpy as npfrom numpy.testing import assert_allcloseimport 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)]))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import pytest
import numpy as npfrom numpy.testing import assert_allcloseimport scipy.special as scfrom 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 )123456789101112import numpy as npimport 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import pytest
import numpy as npfrom numpy.testing import assert_allclose, assert_array_equal
import scipy.special as scfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140import pytestimport numpy as npfrom numpy.testing import assert_allclose, assert_equalimport 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.inf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495import itertoolsimport sysimport pytest
import numpy as npfrom numpy.testing import assert_from scipy.special._testutils import FuncData
from scipy.special import kolmogorov, kolmogi, smirnov, smirnovifrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109## 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 pytestimport numpy as npfrom numpy.testing import assert_, assert_equal, assert_array_almost_equalfrom scipy.special import lambertwfrom 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 == z12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import numpy as npfrom numpy.testing import assert_allclose, assert_
from scipy.special._testutils import FuncDatafrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import numpy as npfrom 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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272"""Test SciPy functions versus mpmath, if available.
"""import numpy as npfrom numpy.testing import assert_, assert_allclosefrom numpy import piimport pytestimport itertools
from scipy._lib import _pep440
import scipy.special as scfrom 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 mpmathexcept 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.slowdef 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.slowdef 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.slowdef 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.slowdef 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.slowdef 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 <eps-close to z=0") def test_polygamma(self): assert_mpmath_equal( sc.polygamma, time_limited()(exception_to_nan(mpmath.polygamma)), [IntArg(0, 1000), Arg()], )
def test_rgamma(self): assert_mpmath_equal( sc.rgamma, mpmath.rgamma, [Arg(-8000, np.inf)], n=5000, nan_ok=False, ignore_inf_sign=True, )
def test_rgamma_complex(self): assert_mpmath_equal( sc.rgamma, exception_to_nan(mpmath.rgamma), [ComplexArg()], rtol=5e-13, )
@pytest.mark.xfail(reason=("see gh-3551 for bad points on 32 bit " "systems and gh-8095 for another bad " "point")) def test_rf(self): if _pep440.parse(mpmath.__version__) >= _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, )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Test how the ufuncs in special handle nan inputs.
"""from typing import Callable
import numpy as npfrom numpy.testing import assert_array_equal, assert_, suppress_warningsimport pytestimport 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)).gitattributes+8
openflamingo/lib/python3.10/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/cython_blas.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npzAdded+3
openflamingo/lib/python3.10/site-packages/scipy/spatial/_ckdtree.cpython-310-x86_64-linux-gnu.soAdded+3
openflamingo/lib/python3.10/site-packages/scipy/special/_ellip_harm.pyAdded+214
openflamingo/lib/python3.10/site-packages/scipy/special/_lambertw.pyAdded+149
openflamingo/lib/python3.10/site-packages/scipy/special/_spfun_stats.pyAdded+106
openflamingo/lib/python3.10/site-packages/scipy/special/_test_internal.pyiAdded+9
openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs.pyiAdded+526
openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyxAdded+181
openflamingo/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.hAdded+185
openflamingo/lib/python3.10/site-packages/scipy/special/cython_special.pyxAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_boxcox.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_faddeeva.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_log_softmax.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logit.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_logsumexp.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_sici.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_spfun_stats.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_support_alternative_backends.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wright_bessel.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_wrightomega.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_basic.pyAdded
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.pyAdded+112
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.pyAdded+106
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.pyAdded+527
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.pyAdded+49
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.pyAdded+363
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_data.pyAdded+725
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_dd.pyAdded+46
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_digamma.pyAdded+45
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.pyAdded+278
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.pyAdded+89
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.pyAdded+118
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.pyAdded+85
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_gamma.pyAdded+12
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.pyAdded+136
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.pyAdded+140
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.pyAdded+495
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.pyAdded+109
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.pyAdded+70
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.pyAdded+207
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.pyAdded+2272
openflamingo/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.pyAdded+64