applied-ai-018 commited on
Commit
d3774b3
·
verified ·
1 Parent(s): 2f1dfc1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step40/zero/7.attention.dense.weight/exp_avg.pt +3 -0
  5. venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py +0 -0
  6. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc +0 -0
  9. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py +17 -0
  20. venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py +54 -0
  21. venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py +116 -0
  22. venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py +124 -0
  23. venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py +68 -0
  24. venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py +43 -0
  25. venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py +131 -0
  26. venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py +38 -0
  27. venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py +342 -0
  28. venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py +152 -0
  29. venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py +41 -0
  30. venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py +27 -0
  31. venv/lib/python3.10/site-packages/scipy/special/special/binom.h +85 -0
  32. venv/lib/python3.10/site-packages/scipy/special/special/cephes/beta.h +255 -0
  33. venv/lib/python3.10/site-packages/scipy/special/special/cephes/gamma.h +343 -0
  34. venv/lib/python3.10/site-packages/scipy/special/special/cephes/psi.h +194 -0
  35. venv/lib/python3.10/site-packages/scipy/special/special/cephes/zeta.h +172 -0
  36. venv/lib/python3.10/site-packages/scipy/special/special/config.h +158 -0
  37. venv/lib/python3.10/site-packages/scipy/special/special/digamma.h +198 -0
  38. venv/lib/python3.10/site-packages/scipy/special/special/error.h +42 -0
  39. venv/lib/python3.10/site-packages/scipy/special/special/evalpoly.h +47 -0
  40. venv/lib/python3.10/site-packages/scipy/special/special/lambertw.h +145 -0
  41. venv/lib/python3.10/site-packages/scipy/special/special/loggamma.h +158 -0
  42. venv/lib/python3.10/site-packages/scipy/special/special/trig.h +99 -0
  43. venv/lib/python3.10/site-packages/scipy/special/special/zlog1.h +35 -0
  44. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdflib.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cython_special.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_dd.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_digamma.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_erfinv.cpython-310.pyc +0 -0
ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28e565deae49903e4e68c02c801899d7ffe7d41431886fac53debb60ac807f55
3
+ size 50332828
ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90240fedb5e43f6f5ff46c735c9021e51a30ea0ae8d308a36dd70cef798d8647
3
+ size 50332843
ckpts/universal/global_step40/zero/17.attention.query_key_value.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8a0d1c3bdba907587a39c1fb157306d2c704c79d4d43508ef00d9b049bdd6e4
3
+ size 50332749
ckpts/universal/global_step40/zero/7.attention.dense.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94e7d0ec7249c6edaaf94ea8683e0c39efee4fd85dc0d6098779076664d9699c
3
+ size 16778396
venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc ADDED
Binary file (722 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc ADDED
Binary file (3.35 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc ADDED
Binary file (3.88 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc ADDED
Binary file (1.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc ADDED
Binary file (3.51 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc ADDED
Binary file (4.42 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mpmath
2
+
3
+
4
+ def f(x):
5
+ return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi)
6
+
7
+
8
+ # Note: 40 digits might be overkill; a few more digits than the default
9
+ # might be sufficient.
10
+ mpmath.mp.dps = 40
11
+ ts = mpmath.taylor(f, -mpmath.pi, 20)
12
+ p, q = mpmath.pade(ts, 9, 10)
13
+
14
+ p = [float(c) for c in p]
15
+ q = [float(c) for c in q]
16
+ print('p =', p)
17
+ print('q =', q)
venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Precompute the polynomials for the asymptotic expansion of the
2
+ generalized exponential integral.
3
+
4
+ Sources
5
+ -------
6
+ [1] NIST, Digital Library of Mathematical Functions,
7
+ https://dlmf.nist.gov/8.20#ii
8
+
9
+ """
10
+ import os
11
+
12
+ try:
13
+ import sympy
14
+ from sympy import Poly
15
+ x = sympy.symbols('x')
16
+ except ImportError:
17
+ pass
18
+
19
+
20
+ def generate_A(K):
21
+ A = [Poly(1, x)]
22
+ for k in range(K):
23
+ A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
24
+ return A
25
+
26
+
27
+ WARNING = """\
28
+ /* This file was automatically generated by _precompute/expn_asy.py.
29
+ * Do not edit it manually!
30
+ */
31
+ """
32
+
33
+
34
+ def main():
35
+ print(__doc__)
36
+ fn = os.path.join('..', 'cephes', 'expn.h')
37
+
38
+ K = 12
39
+ A = generate_A(K)
40
+ with open(fn + '.new', 'w') as f:
41
+ f.write(WARNING)
42
+ f.write(f"#define nA {len(A)}\n")
43
+ for k, Ak in enumerate(A):
44
+ ', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
45
+ f.write(f"static const double A{k}[] = {{tmp}};\n")
46
+ ", ".join([f"A{k}" for k in range(K + 1)])
47
+ f.write("static const double *A[] = {{tmp}};\n")
48
+ ", ".join([str(Ak.degree()) for Ak in A])
49
+ f.write("static const int Adegs[] = {{tmp}};\n")
50
+ os.rename(fn + '.new', fn)
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Precompute coefficients of Temme's asymptotic expansion for gammainc.
3
+
4
+ This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
5
+
6
+ Sources:
7
+ [1] NIST, "Digital Library of Mathematical Functions",
8
+ https://dlmf.nist.gov/
9
+
10
+ """
11
+ import os
12
+ from scipy.special._precompute.utils import lagrange_inversion
13
+
14
+ try:
15
+ import mpmath as mp
16
+ except ImportError:
17
+ pass
18
+
19
+
20
+ def compute_a(n):
21
+ """a_k from DLMF 5.11.6"""
22
+ a = [mp.sqrt(2)/2]
23
+ for k in range(1, n):
24
+ ak = a[-1]/k
25
+ for j in range(1, len(a)):
26
+ ak -= a[j]*a[-j]/(j + 1)
27
+ ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
28
+ a.append(ak)
29
+ return a
30
+
31
+
32
+ def compute_g(n):
33
+ """g_k from DLMF 5.11.3/5.11.5"""
34
+ a = compute_a(2*n)
35
+ g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)]
36
+ return g
37
+
38
+
39
+ def eta(lam):
40
+ """Function from DLMF 8.12.1 shifted to be centered at 0."""
41
+ if lam > 0:
42
+ return mp.sqrt(2*(lam - mp.log(lam + 1)))
43
+ elif lam < 0:
44
+ return -mp.sqrt(2*(lam - mp.log(lam + 1)))
45
+ else:
46
+ return 0
47
+
48
+
49
+ def compute_alpha(n):
50
+ """alpha_n from DLMF 8.12.13"""
51
+ coeffs = mp.taylor(eta, 0, n - 1)
52
+ return lagrange_inversion(coeffs)
53
+
54
+
55
+ def compute_d(K, N):
56
+ """d_{k, n} from DLMF 8.12.12"""
57
+ M = N + 2*K
58
+ d0 = [-mp.mpf(1)/3]
59
+ alpha = compute_alpha(M + 2)
60
+ for n in range(1, M):
61
+ d0.append((n + 2)*alpha[n+2])
62
+ d = [d0]
63
+ g = compute_g(K)
64
+ for k in range(1, K):
65
+ dk = []
66
+ for n in range(M - 2*k):
67
+ dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2])
68
+ d.append(dk)
69
+ for k in range(K):
70
+ d[k] = d[k][:N]
71
+ return d
72
+
73
+
74
+ header = \
75
+ r"""/* This file was automatically generated by _precomp/gammainc.py.
76
+ * Do not edit it manually!
77
+ */
78
+
79
+ #ifndef IGAM_H
80
+ #define IGAM_H
81
+
82
+ #define K {}
83
+ #define N {}
84
+
85
+ static const double d[K][N] =
86
+ {{"""
87
+
88
+ footer = \
89
+ r"""
90
+ #endif
91
+ """
92
+
93
+
94
+ def main():
95
+ print(__doc__)
96
+ K = 25
97
+ N = 25
98
+ with mp.workdps(50):
99
+ d = compute_d(K, N)
100
+ fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h')
101
+ with open(fn + '.new', 'w') as f:
102
+ f.write(header.format(K, N))
103
+ for k, row in enumerate(d):
104
+ row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row]
105
+ f.write('{')
106
+ f.write(", ".join(row))
107
+ if k < K - 1:
108
+ f.write('},\n')
109
+ else:
110
+ f.write('}};\n')
111
+ f.write(footer)
112
+ os.rename(fn + '.new', fn)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute gammainc and gammaincc for large arguments and parameters
2
+ and save the values to data files for use in tests. We can't just
3
+ compare to mpmath's gammainc in test_mpmath.TestSystematic because it
4
+ would take too long.
5
+
6
+ Note that mpmath's gammainc is computed using hypercomb, but since it
7
+ doesn't allow the user to increase the maximum number of terms used in
8
+ the series it doesn't converge for many arguments. To get around this
9
+ we copy the mpmath implementation but use more terms.
10
+
11
+ This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB
12
+ ram.
13
+
14
+ Sources:
15
+ [1] Fredrik Johansson and others. mpmath: a Python library for
16
+ arbitrary-precision floating-point arithmetic (version 0.19),
17
+ December 2013. http://mpmath.org/.
18
+
19
+ """
20
+ import os
21
+ from time import time
22
+ import numpy as np
23
+ from numpy import pi
24
+
25
+ from scipy.special._mptestutils import mpf2float
26
+
27
+ try:
28
+ import mpmath as mp
29
+ except ImportError:
30
+ pass
31
+
32
+
33
+ def gammainc(a, x, dps=50, maxterms=10**8):
34
+ """Compute gammainc exactly like mpmath does but allow for more
35
+ summands in hypercomb. See
36
+
37
+ mpmath/functions/expintegrals.py#L134
38
+
39
+ in the mpmath github repository.
40
+
41
+ """
42
+ with mp.workdps(dps):
43
+ z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x)
44
+ G = [z]
45
+ negb = mp.fneg(b, exact=True)
46
+
47
+ def h(z):
48
+ T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b
49
+ return (T1,)
50
+
51
+ res = mp.hypercomb(h, [z], maxterms=maxterms)
52
+ return mpf2float(res)
53
+
54
+
55
+ def gammaincc(a, x, dps=50, maxterms=10**8):
56
+ """Compute gammaincc exactly like mpmath does but allow for more
57
+ terms in hypercomb. See
58
+
59
+ mpmath/functions/expintegrals.py#L187
60
+
61
+ in the mpmath github repository.
62
+
63
+ """
64
+ with mp.workdps(dps):
65
+ z, a = a, x
66
+
67
+ if mp.isint(z):
68
+ try:
69
+ # mpmath has a fast integer path
70
+ return mpf2float(mp.gammainc(z, a=a, regularized=True))
71
+ except mp.libmp.NoConvergence:
72
+ pass
73
+ nega = mp.fneg(a, exact=True)
74
+ G = [z]
75
+ # Use 2F0 series when possible; fall back to lower gamma representation
76
+ try:
77
+ def h(z):
78
+ r = z-1
79
+ return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
80
+ return mpf2float(mp.hypercomb(h, [z], force_series=True))
81
+ except mp.libmp.NoConvergence:
82
+ def h(z):
83
+ T1 = [], [1, z-1], [z], G, [], [], 0
84
+ T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
85
+ return T1, T2
86
+ return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
87
+
88
+
89
+ def main():
90
+ t0 = time()
91
+ # It would be nice to have data for larger values, but either this
92
+ # requires prohibitively large precision (dps > 800) or mpmath has
93
+ # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a
94
+ # value around 0.03, while the true value should be close to 0.5
95
+ # (DLMF 8.12.15).
96
+ print(__doc__)
97
+ pwd = os.path.dirname(__file__)
98
+ r = np.logspace(4, 14, 30)
99
+ ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30)
100
+ utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30)
101
+
102
+ regimes = [(gammainc, ltheta), (gammaincc, utheta)]
103
+ for func, theta in regimes:
104
+ rg, thetag = np.meshgrid(r, theta)
105
+ a, x = rg*np.cos(thetag), rg*np.sin(thetag)
106
+ a, x = a.flatten(), x.flatten()
107
+ dataset = []
108
+ for i, (a0, x0) in enumerate(zip(a, x)):
109
+ if func == gammaincc:
110
+ # Exploit the fast integer path in gammaincc whenever
111
+ # possible so that the computation doesn't take too
112
+ # long
113
+ a0, x0 = np.floor(a0), np.floor(x0)
114
+ dataset.append((a0, x0, func(a0, x0)))
115
+ dataset = np.array(dataset)
116
+ filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
117
+ f'{func.__name__}.txt')
118
+ np.savetxt(filename, dataset)
119
+
120
+ print(f"{(time() - t0)/60} minutes elapsed")
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute a Pade approximation for the principal branch of the
2
+ Lambert W function around 0 and compare it to various other
3
+ approximations.
4
+
5
+ """
6
+ import numpy as np
7
+
8
+ try:
9
+ import mpmath
10
+ import matplotlib.pyplot as plt
11
+ except ImportError:
12
+ pass
13
+
14
+
15
+ def lambertw_pade():
16
+ derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]
17
+ p, q = mpmath.pade(derivs, 3, 2)
18
+ return p, q
19
+
20
+
21
+ def main():
22
+ print(__doc__)
23
+ with mpmath.workdps(50):
24
+ p, q = lambertw_pade()
25
+ p, q = p[::-1], q[::-1]
26
+ print(f"p = {p}")
27
+ print(f"q = {q}")
28
+
29
+ x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
30
+ x, y = np.meshgrid(x, y)
31
+ z = x + 1j*y
32
+ lambertw_std = []
33
+ for z0 in z.flatten():
34
+ lambertw_std.append(complex(mpmath.lambertw(z0)))
35
+ lambertw_std = np.array(lambertw_std).reshape(x.shape)
36
+
37
+ fig, axes = plt.subplots(nrows=3, ncols=1)
38
+ # Compare Pade approximation to true result
39
+ p = np.array([float(p0) for p0 in p])
40
+ q = np.array([float(q0) for q0 in q])
41
+ pade_approx = np.polyval(p, z)/np.polyval(q, z)
42
+ pade_err = abs(pade_approx - lambertw_std)
43
+ axes[0].pcolormesh(x, y, pade_err)
44
+ # Compare two terms of asymptotic series to true result
45
+ asy_approx = np.log(z) - np.log(np.log(z))
46
+ asy_err = abs(asy_approx - lambertw_std)
47
+ axes[1].pcolormesh(x, y, asy_err)
48
+ # Compare two terms of the series around the branch point to the
49
+ # true result
50
+ p = np.sqrt(2*(np.exp(1)*z + 1))
51
+ series_approx = -1 + p - p**2/3
52
+ series_err = abs(series_approx - lambertw_std)
53
+ im = axes[2].pcolormesh(x, y, series_err)
54
+
55
+ fig.colorbar(im, ax=axes.ravel().tolist())
56
+ plt.show()
57
+
58
+ fig, ax = plt.subplots(nrows=1, ncols=1)
59
+ pade_better = pade_err < asy_err
60
+ im = ax.pcolormesh(x, y, pade_better)
61
+ t = np.linspace(-0.3, 0.3)
62
+ ax.plot(-2.5*abs(t) - 0.2, t, 'r')
63
+ fig.colorbar(im, ax=ax)
64
+ plt.show()
65
+
66
+
67
+ if __name__ == '__main__':
68
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Precompute series coefficients for log-Gamma."""
2
+
3
+ try:
4
+ import mpmath
5
+ except ImportError:
6
+ pass
7
+
8
+
9
+ def stirling_series(N):
10
+ with mpmath.workdps(100):
11
+ coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1))
12
+ for n in range(1, N + 1)]
13
+ return coeffs
14
+
15
+
16
+ def taylor_series_at_1(N):
17
+ coeffs = []
18
+ with mpmath.workdps(100):
19
+ coeffs.append(-mpmath.euler)
20
+ for n in range(2, N + 1):
21
+ coeffs.append((-1)**n*mpmath.zeta(n)/n)
22
+ return coeffs
23
+
24
+
25
+ def main():
26
+ print(__doc__)
27
+ print()
28
+ stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
29
+ for x in stirling_series(8)[::-1]]
30
+ taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
31
+ for x in taylor_series_at_1(23)[::-1]]
32
+ print("Stirling series coefficients")
33
+ print("----------------------------")
34
+ print("\n".join(stirling_coeffs))
35
+ print()
36
+ print("Taylor series coefficients")
37
+ print("--------------------------")
38
+ print("\n".join(taylor_coeffs))
39
+ print()
40
+
41
+
42
+ if __name__ == '__main__':
43
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convergence regions of the expansions used in ``struve.c``
3
+
4
+ Note that for v >> z both functions tend rapidly to 0,
5
+ and for v << -z, they tend to infinity.
6
+
7
+ The floating-point functions over/underflow in the lower left and right
8
+ corners of the figure.
9
+
10
+
11
+ Figure legend
12
+ =============
13
+
14
+ Red region
15
+ Power series is close (1e-12) to the mpmath result
16
+
17
+ Blue region
18
+ Asymptotic series is close to the mpmath result
19
+
20
+ Green region
21
+ Bessel series is close to the mpmath result
22
+
23
+ Dotted colored lines
24
+ Boundaries of the regions
25
+
26
+ Solid colored lines
27
+ Boundaries estimated by the routine itself. These will be used
28
+ for determining which of the results to use.
29
+
30
+ Black dashed line
31
+ The line z = 0.7*|v| + 12
32
+
33
+ """
34
+ import numpy as np
35
+ import matplotlib.pyplot as plt
36
+
37
+ import mpmath
38
+
39
+
40
+ def err_metric(a, b, atol=1e-290):
41
+ m = abs(a - b) / (atol + abs(b))
42
+ m[np.isinf(b) & (a == b)] = 0
43
+ return m
44
+
45
+
46
+ def do_plot(is_h=True):
47
+ from scipy.special._ufuncs import (_struve_power_series,
48
+ _struve_asymp_large_z,
49
+ _struve_bessel_series)
50
+
51
+ vs = np.linspace(-1000, 1000, 91)
52
+ zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]])
53
+
54
+ rp = _struve_power_series(vs[:,None], zs[None,:], is_h)
55
+ ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h)
56
+ rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h)
57
+
58
+ mpmath.mp.dps = 50
59
+ if is_h:
60
+ def sh(v, z):
61
+ return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z)))
62
+ else:
63
+ def sh(v, z):
64
+ return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z)))
65
+ ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:])
66
+
67
+ err_a = err_metric(ra[0], ex) + 1e-300
68
+ err_p = err_metric(rp[0], ex) + 1e-300
69
+ err_b = err_metric(rb[0], ex) + 1e-300
70
+
71
+ err_est_a = abs(ra[1]/ra[0])
72
+ err_est_p = abs(rp[1]/rp[0])
73
+ err_est_b = abs(rb[1]/rb[0])
74
+
75
+ z_cutoff = 0.7*abs(vs) + 12
76
+
77
+ levels = [-1000, -12]
78
+
79
+ plt.cla()
80
+
81
+ plt.hold(1)
82
+ plt.contourf(vs, zs, np.log10(err_p).T,
83
+ levels=levels, colors=['r', 'r'], alpha=0.1)
84
+ plt.contourf(vs, zs, np.log10(err_a).T,
85
+ levels=levels, colors=['b', 'b'], alpha=0.1)
86
+ plt.contourf(vs, zs, np.log10(err_b).T,
87
+ levels=levels, colors=['g', 'g'], alpha=0.1)
88
+
89
+ plt.contour(vs, zs, np.log10(err_p).T,
90
+ levels=levels, colors=['r', 'r'], linestyles=[':', ':'])
91
+ plt.contour(vs, zs, np.log10(err_a).T,
92
+ levels=levels, colors=['b', 'b'], linestyles=[':', ':'])
93
+ plt.contour(vs, zs, np.log10(err_b).T,
94
+ levels=levels, colors=['g', 'g'], linestyles=[':', ':'])
95
+
96
+ lp = plt.contour(vs, zs, np.log10(err_est_p).T,
97
+ levels=levels, colors=['r', 'r'], linestyles=['-', '-'])
98
+ la = plt.contour(vs, zs, np.log10(err_est_a).T,
99
+ levels=levels, colors=['b', 'b'], linestyles=['-', '-'])
100
+ lb = plt.contour(vs, zs, np.log10(err_est_b).T,
101
+ levels=levels, colors=['g', 'g'], linestyles=['-', '-'])
102
+
103
+ plt.clabel(lp, fmt={-1000: 'P', -12: 'P'})
104
+ plt.clabel(la, fmt={-1000: 'A', -12: 'A'})
105
+ plt.clabel(lb, fmt={-1000: 'B', -12: 'B'})
106
+
107
+ plt.plot(vs, z_cutoff, 'k--')
108
+
109
+ plt.xlim(vs.min(), vs.max())
110
+ plt.ylim(zs.min(), zs.max())
111
+
112
+ plt.xlabel('v')
113
+ plt.ylabel('z')
114
+
115
+
116
+ def main():
117
+ plt.clf()
118
+ plt.subplot(121)
119
+ do_plot(True)
120
+ plt.title('Struve H')
121
+
122
+ plt.subplot(122)
123
+ do_plot(False)
124
+ plt.title('Struve L')
125
+
126
+ plt.savefig('struve_convergence.png')
127
+ plt.show()
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ import mpmath as mp
3
+ except ImportError:
4
+ pass
5
+
6
+ try:
7
+ from sympy.abc import x
8
+ except ImportError:
9
+ pass
10
+
11
+
12
+ def lagrange_inversion(a):
13
+ """Given a series
14
+
15
+ f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
16
+
17
+ use the Lagrange inversion formula to compute a series
18
+
19
+ g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
20
+
21
+ so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
22
+ necessarily b[0] = 0 too.
23
+
24
+ The algorithm is naive and could be improved, but speed isn't an
25
+ issue here and it's easy to read.
26
+
27
+ """
28
+ n = len(a)
29
+ f = sum(a[i]*x**i for i in range(n))
30
+ h = (x/f).series(x, 0, n).removeO()
31
+ hpower = [h**0]
32
+ for k in range(n):
33
+ hpower.append((hpower[-1]*h).expand())
34
+ b = [mp.mpf(0)]
35
+ for k in range(1, n):
36
+ b.append(hpower[k].coeff(x, k - 1)/k)
37
+ b = [mp.mpf(x) for x in b]
38
+ return b
venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Precompute coefficients of several series expansions
2
+ of Wright's generalized Bessel function Phi(a, b, x).
3
+
4
+ See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x.
5
+ """
6
+ from argparse import ArgumentParser, RawTextHelpFormatter
7
+ import numpy as np
8
+ from scipy.integrate import quad
9
+ from scipy.optimize import minimize_scalar, curve_fit
10
+ from time import time
11
+
12
+ try:
13
+ import sympy
14
+ from sympy import EulerGamma, Rational, S, Sum, \
15
+ factorial, gamma, gammasimp, pi, polygamma, symbols, zeta
16
+ from sympy.polys.polyfuncs import horner
17
+ except ImportError:
18
+ pass
19
+
20
+
21
+ def series_small_a():
22
+ """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.
23
+ """
24
+ order = 5
25
+ a, b, x, k = symbols("a b x k")
26
+ A = [] # terms with a
27
+ X = [] # terms with x
28
+ B = [] # terms with b (polygammas)
29
+ # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i])
30
+ expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
31
+ expression = gamma(b)/sympy.exp(x) * expression
32
+
33
+ # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
34
+ for n in range(0, order+1):
35
+ term = expression.diff(a, n).subs(a, 0).simplify().doit()
36
+ # set the whole bracket involving polygammas to 1
37
+ x_part = (term.subs(polygamma(0, b), 1)
38
+ .replace(polygamma, lambda *args: 0))
39
+ # sign convention: x part always positive
40
+ x_part *= (-1)**n
41
+
42
+ A.append(a**n/factorial(n))
43
+ X.append(horner(x_part))
44
+ B.append(horner((term/x_part).simplify()))
45
+
46
+ s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n"
47
+ s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n"
48
+ for name, c in zip(['A', 'X', 'B'], [A, X, B]):
49
+ for i in range(len(c)):
50
+ s += f"\n{name}[{i}] = " + str(c[i])
51
+ return s
52
+
53
+
54
+ # expansion of digamma
55
+ def dg_series(z, n):
56
+ """Symbolic expansion of digamma(z) in z=0 to order n.
57
+
58
+ See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2
59
+ """
60
+ k = symbols("k")
61
+ return -1/z - EulerGamma + \
62
+ sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1))
63
+
64
+
65
+ def pg_series(k, z, n):
66
+ """Symbolic expansion of polygamma(k, z) in z=0 to order n."""
67
+ return sympy.diff(dg_series(z, n+k), z, k)
68
+
69
+
70
+ def series_small_a_small_b():
71
+ """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5.
72
+
73
+ Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and
74
+ polygamma functions.
75
+
76
+ digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2)
77
+ digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2)
78
+ polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2)
79
+ and so on.
80
+ """
81
+ order = 5
82
+ a, b, x, k = symbols("a b x k")
83
+ M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3")
84
+ c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3}
85
+ A = [] # terms with a
86
+ X = [] # terms with x
87
+ B = [] # terms with b (polygammas expanded)
88
+ C = [] # terms that generate B
89
+ # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i])
90
+ # B[0] = 1
91
+ # B[k] = sum(C[k] * b**k/k!, k=0..)
92
+ # Note: C[k] can be obtained from a series expansion of 1/gamma(b).
93
+ expression = gamma(b)/sympy.exp(x) * \
94
+ Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
95
+
96
+ # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
97
+ for n in range(0, order+1):
98
+ term = expression.diff(a, n).subs(a, 0).simplify().doit()
99
+ # set the whole bracket involving polygammas to 1
100
+ x_part = (term.subs(polygamma(0, b), 1)
101
+ .replace(polygamma, lambda *args: 0))
102
+ # sign convention: x part always positive
103
+ x_part *= (-1)**n
104
+ # expansion of polygamma part with 1/gamma(b)
105
+ pg_part = term/x_part/gamma(b)
106
+ if n >= 1:
107
+ # Note: highest term is digamma^n
108
+ pg_part = pg_part.replace(polygamma,
109
+ lambda k, x: pg_series(k, x, order+1+n))
110
+ pg_part = (pg_part.series(b, 0, n=order+1-n)
111
+ .removeO()
112
+ .subs(polygamma(2, 1), -2*zeta(3))
113
+ .simplify()
114
+ )
115
+
116
+ A.append(a**n/factorial(n))
117
+ X.append(horner(x_part))
118
+ B.append(pg_part)
119
+
120
+ # Calculate C and put in the k!
121
+ C = sympy.Poly(B[1].subs(c_subs), b).coeffs()
122
+ C.reverse()
123
+ for i in range(len(C)):
124
+ C[i] = (C[i] * factorial(i)).simplify()
125
+
126
+ s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5."
127
+ s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n"
128
+ s += "B[0] = 1\n"
129
+ s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n"
130
+ s += "\nM_PI = pi"
131
+ s += "\nM_EG = EulerGamma"
132
+ s += "\nM_Z3 = zeta(3)"
133
+ for name, c in zip(['A', 'X'], [A, X]):
134
+ for i in range(len(c)):
135
+ s += f"\n{name}[{i}] = "
136
+ s += str(c[i])
137
+ # For C, do also compute the values numerically
138
+ for i in range(len(C)):
139
+ s += f"\n# C[{i}] = "
140
+ s += str(C[i])
141
+ s += f"\nC[{i}] = "
142
+ s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)})
143
+ .evalf(17))
144
+
145
+ # Does B have the assumed structure?
146
+ s += "\n\nTest if B[i] does have the assumed structure."
147
+ s += "\nC[i] are derived from B[1] alone."
148
+ s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .."
149
+ test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)])
150
+ test = (test - B[2].subs(c_subs)).simplify()
151
+ s += f"\ntest successful = {test==S(0)}"
152
+ s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .."
153
+ test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)])
154
+ test = (test - B[3].subs(c_subs)).simplify()
155
+ s += f"\ntest successful = {test==S(0)}"
156
+ return s
157
+
158
+
159
+ def asymptotic_series():
160
+ """Asymptotic expansion for large x.
161
+
162
+ Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
163
+ Z = (a*x)^(1/(1+a))
164
+
165
+ Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and
166
+ a_1). With slightly different notation, Paris (2017) lists coefficients
167
+ c_k up to order k=3.
168
+ Paris (2017) uses ZP = (1+a)/a * Z (ZP = Z of Paris) and
169
+ C_k = C_0 * (-a/(1+a))^k * c_k
170
+ """
171
+ order = 8
172
+
173
+ class g(sympy.Function):
174
+ """Helper function g according to Wright (1935)
175
+
176
+ g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...)
177
+
178
+ Note: Wright (1935) uses square root of above definition.
179
+ """
180
+ nargs = 3
181
+
182
+ @classmethod
183
+ def eval(cls, n, rho, v):
184
+ if not n >= 0:
185
+ raise ValueError("must have n >= 0")
186
+ elif n == 0:
187
+ return 1
188
+ else:
189
+ return g(n-1, rho, v) \
190
+ + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \
191
+ / gammasimp(gamma(3+n)/gamma(3))*v**n
192
+
193
+ class coef_C(sympy.Function):
194
+ """Calculate coefficients C_m for integer m.
195
+
196
+ C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of
197
+ Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b)
198
+ * g(rho, v)^(-m-1/2)
199
+ """
200
+ nargs = 3
201
+
202
+ @classmethod
203
+ def eval(cls, m, rho, beta):
204
+ if not m >= 0:
205
+ raise ValueError("must have m >= 0")
206
+
207
+ v = symbols("v")
208
+ expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2))
209
+ res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m)
210
+ res = res * (gamma(m + Rational(1, 2)) / (2*pi)
211
+ * (2/(rho+1))**(m + Rational(1, 2)))
212
+ return res
213
+
214
+ # in order to have nice ordering/sorting of expressions, we set a = xa.
215
+ xa, b, xap1 = symbols("xa b xap1")
216
+ C0 = coef_C(0, xa, b)
217
+ # a1 = a(1, rho, beta)
218
+ s = "Asymptotic expansion for large x\n"
219
+ s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n"
220
+ s += " * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n"
221
+ s += "Z = pow(a * x, 1/(1+a))\n"
222
+ s += "A[k] = pow(a, k)\n"
223
+ s += "B[k] = pow(b, k)\n"
224
+ s += "Ap1[k] = pow(1+a, k)\n\n"
225
+ s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n"
226
+ for i in range(1, order+1):
227
+ expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify()
228
+ factor = [x.denominator() for x in sympy.Poly(expr).coeffs()]
229
+ factor = sympy.lcm(factor)
230
+ expr = (expr * factor).simplify().collect(b, sympy.factor)
231
+ expr = expr.xreplace({xa+1: xap1})
232
+ s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n"
233
+ s += f"C[{i}] *= {str(expr)}\n\n"
234
+ import re
235
+ re_a = re.compile(r'xa\*\*(\d+)')
236
+ s = re_a.sub(r'A[\1]', s)
237
+ re_b = re.compile(r'b\*\*(\d+)')
238
+ s = re_b.sub(r'B[\1]', s)
239
+ s = s.replace('xap1', 'Ap1[1]')
240
+ s = s.replace('xa', 'a')
241
+ # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10
242
+ # or more digits.
243
+ re_digits = re.compile(r'(\d{10,})')
244
+ s = re_digits.sub(r'\1.', s)
245
+ return s
246
+
247
+
248
+ def optimal_epsilon_integral():
249
+ """Fit optimal choice of epsilon for integral representation.
250
+
251
+ The integrand of
252
+ int_0^pi P(eps, a, b, x, phi) * dphi
253
+ can exhibit oscillatory behaviour. It stems from the cosine of P and can be
254
+ minimized by minimizing the arc length of the argument
255
+ f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi
256
+ of cos(f(phi)).
257
+ We minimize the arc length in eps for a grid of values (a, b, x) and fit a
258
+ parametric function to it.
259
+ """
260
+ def fp(eps, a, b, x, phi):
261
+ """Derivative of f w.r.t. phi."""
262
+ eps_a = np.power(1. * eps, -a)
263
+ return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b
264
+
265
+ def arclength(eps, a, b, x, epsrel=1e-2, limit=100):
266
+ """Compute Arc length of f.
267
+
268
+ Note that the arc length of a function f from t0 to t1 is given by
269
+ int_t0^t1 sqrt(1 + f'(t)^2) dt
270
+ """
271
+ return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2),
272
+ 0, np.pi,
273
+ epsrel=epsrel, limit=100)[0]
274
+
275
+ # grid of minimal arc length values
276
+ data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8]
277
+ data_b = [0, 1, 4, 7, 10]
278
+ data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4]
279
+ data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x)
280
+ data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(),
281
+ data_x.flatten())
282
+ best_eps = []
283
+ for i in range(data_x.size):
284
+ best_eps.append(
285
+ minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i],
286
+ data_x[i]),
287
+ bounds=(1e-3, 1000),
288
+ method='Bounded', options={'xatol': 1e-3}).x
289
+ )
290
+ best_eps = np.array(best_eps)
291
+ # pandas would be nice, but here a dictionary is enough
292
+ df = {'a': data_a,
293
+ 'b': data_b,
294
+ 'x': data_x,
295
+ 'eps': best_eps,
296
+ }
297
+
298
+ def func(data, A0, A1, A2, A3, A4, A5):
299
+ """Compute parametric function to fit."""
300
+ a = data['a']
301
+ b = data['b']
302
+ x = data['x']
303
+ return (A0 * b * np.exp(-0.5 * a)
304
+ + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a)
305
+ + A4 / (1 + np.exp(A5 * a))))
306
+
307
+ func_params = list(curve_fit(func, df, df['eps'], method='trf')[0])
308
+
309
+ s = "Fit optimal eps for integrand P via minimal arc length\n"
310
+ s += "with parametric function:\n"
311
+ s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n"
312
+ s += " - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n"
313
+ s += "Fitted parameters A0 to A5 are:\n"
314
+ s += ', '.join([f'{x:.5g}' for x in func_params])
315
+ return s
316
+
317
+
318
+ def main():
319
+ t0 = time()
320
+ parser = ArgumentParser(description=__doc__,
321
+ formatter_class=RawTextHelpFormatter)
322
+ parser.add_argument('action', type=int, choices=[1, 2, 3, 4],
323
+ help='chose what expansion to precompute\n'
324
+ '1 : Series for small a\n'
325
+ '2 : Series for small a and small b\n'
326
+ '3 : Asymptotic series for large x\n'
327
+ ' This may take some time (>4h).\n'
328
+ '4 : Fit optimal eps for integral representation.'
329
+ )
330
+ args = parser.parse_args()
331
+
332
+ switch = {1: lambda: print(series_small_a()),
333
+ 2: lambda: print(series_small_a_small_b()),
334
+ 3: lambda: print(asymptotic_series()),
335
+ 4: lambda: print(optimal_epsilon_integral())
336
+ }
337
+ switch.get(args.action, lambda: print("Invalid input."))()
338
+ print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n")
339
+
340
+
341
+ if __name__ == '__main__':
342
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute a grid of values for Wright's generalized Bessel function
2
+ and save the values to data files for use in tests. Using mpmath directly in
3
+ tests would take too long.
4
+
5
+ This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro.
6
+ """
7
+ from functools import lru_cache
8
+ import os
9
+ from time import time
10
+
11
+ import numpy as np
12
+ from scipy.special._mptestutils import mpf2float
13
+
14
+ try:
15
+ import mpmath as mp
16
+ except ImportError:
17
+ pass
18
+
19
+ # exp_inf: smallest value x for which exp(x) == inf
20
+ exp_inf = 709.78271289338403
21
+
22
+
23
+ # 64 Byte per value
24
+ @lru_cache(maxsize=100_000)
25
+ def rgamma_cached(x, dps):
26
+ with mp.workdps(dps):
27
+ return mp.rgamma(x)
28
+
29
+
30
+ def mp_wright_bessel(a, b, x, dps=50, maxterms=2000):
31
+ """Compute Wright's generalized Bessel function as Series with mpmath.
32
+ """
33
+ with mp.workdps(dps):
34
+ a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
35
+ res = mp.nsum(lambda k: x**k / mp.fac(k)
36
+ * rgamma_cached(a * k + b, dps=dps),
37
+ [0, mp.inf],
38
+ tol=dps, method='s', steps=[maxterms]
39
+ )
40
+ return mpf2float(res)
41
+
42
+
43
+ def main():
44
+ t0 = time()
45
+ print(__doc__)
46
+ pwd = os.path.dirname(__file__)
47
+ eps = np.finfo(float).eps * 100
48
+
49
+ a_range = np.array([eps,
50
+ 1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps),
51
+ 1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps),
52
+ 0.1, 0.5,
53
+ 1 * (1 - eps), 1, 1 * (1 + eps),
54
+ 1.5, 2, 4.999, 5, 10])
55
+ b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100])
56
+ x_range = np.array([0, eps, 1 - eps, 1, 1 + eps,
57
+ 1.5,
58
+ 2 - eps, 2, 2 + eps,
59
+ 9 - eps, 9, 9 + eps,
60
+ 10 * (1 - eps), 10, 10 * (1 + eps),
61
+ 100 * (1 - eps), 100, 100 * (1 + eps),
62
+ 500, exp_inf, 1e3, 1e5, 1e10, 1e20])
63
+
64
+ a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range,
65
+ indexing='ij')
66
+ a_range = a_range.flatten()
67
+ b_range = b_range.flatten()
68
+ x_range = x_range.flatten()
69
+
70
+ # filter out some values, especially too large x
71
+ bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf))
72
+ bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf))
73
+ bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3))
74
+ bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3))
75
+ bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4))
76
+ bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5))
77
+ bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6))
78
+ bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7))
79
+ bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8))
80
+ bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9))
81
+ bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10))
82
+ bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11))
83
+ bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12))
84
+ bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13))
85
+ bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14))
86
+ bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15))
87
+ bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16))
88
+ bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17))
89
+ bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
90
+ bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
91
+ bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19))
92
+ bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20))
93
+
94
+ # filter out known values that do not meet the required numerical accuracy
95
+ # see test test_wright_data_grid_failures
96
+ failing = np.array([
97
+ [0.1, 100, 709.7827128933841],
98
+ [0.5, 10, 709.7827128933841],
99
+ [0.5, 10, 1000],
100
+ [0.5, 100, 1000],
101
+ [1, 20, 100000],
102
+ [1, 100, 100000],
103
+ [1.0000000000000222, 20, 100000],
104
+ [1.0000000000000222, 100, 100000],
105
+ [1.5, 0, 500],
106
+ [1.5, 2.220446049250313e-14, 500],
107
+ [1.5, 1.e-10, 500],
108
+ [1.5, 1.e-05, 500],
109
+ [1.5, 0.1, 500],
110
+ [1.5, 20, 100000],
111
+ [1.5, 100, 100000],
112
+ ]).tolist()
113
+
114
+ does_fail = np.full_like(a_range, False, dtype=bool)
115
+ for i in range(x_range.size):
116
+ if [a_range[i], b_range[i], x_range[i]] in failing:
117
+ does_fail[i] = True
118
+
119
+ # filter and flatten
120
+ a_range = a_range[bool_filter]
121
+ b_range = b_range[bool_filter]
122
+ x_range = x_range[bool_filter]
123
+ does_fail = does_fail[bool_filter]
124
+
125
+ dataset = []
126
+ print(f"Computing {x_range.size} single points.")
127
+ print("Tests will fail for the following data points:")
128
+ for i in range(x_range.size):
129
+ a = a_range[i]
130
+ b = b_range[i]
131
+ x = x_range[i]
132
+ # take care of difficult corner cases
133
+ maxterms = 1000
134
+ if a < 1e-6 and x >= exp_inf/10:
135
+ maxterms = 2000
136
+ f = mp_wright_bessel(a, b, x, maxterms=maxterms)
137
+ if does_fail[i]:
138
+ print("failing data point a, b, x, value = "
139
+ f"[{a}, {b}, {x}, {f}]")
140
+ else:
141
+ dataset.append((a, b, x, f))
142
+ dataset = np.array(dataset)
143
+
144
+ filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
145
+ 'wright_bessel.txt')
146
+ np.savetxt(filename, dataset)
147
+
148
+ print(f"{(time() - t0)/60:.1f} minutes elapsed")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ try:
4
+ import mpmath
5
+ except ImportError:
6
+ pass
7
+
8
+
9
+ def mpmath_wrightomega(x):
10
+ return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
11
+
12
+
13
+ def wrightomega_series_error(x):
14
+ series = x
15
+ desired = mpmath_wrightomega(x)
16
+ return abs(series - desired) / desired
17
+
18
+
19
+ def wrightomega_exp_error(x):
20
+ exponential_approx = mpmath.exp(x)
21
+ desired = mpmath_wrightomega(x)
22
+ return abs(exponential_approx - desired) / desired
23
+
24
+
25
+ def main():
26
+ desired_error = 2 * np.finfo(float).eps
27
+ print('Series Error')
28
+ for x in [1e5, 1e10, 1e15, 1e20]:
29
+ with mpmath.workdps(100):
30
+ error = wrightomega_series_error(x)
31
+ print(x, error, error < desired_error)
32
+
33
+ print('Exp error')
34
+ for x in [-10, -25, -50, -100, -200, -400, -700, -740]:
35
+ with mpmath.workdps(100):
36
+ error = wrightomega_exp_error(x)
37
+ print(x, error, error < desired_error)
38
+
39
+
40
+ if __name__ == '__main__':
41
+ main()
venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute the Taylor series for zeta(x) - 1 around x = 0."""
2
+ try:
3
+ import mpmath
4
+ except ImportError:
5
+ pass
6
+
7
+
8
+ def zetac_series(N):
9
+ coeffs = []
10
+ with mpmath.workdps(100):
11
+ coeffs.append(-1.5)
12
+ for n in range(1, N):
13
+ coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n)
14
+ coeffs.append(coeff)
15
+ return coeffs
16
+
17
+
18
+ def main():
19
+ print(__doc__)
20
+ coeffs = zetac_series(10)
21
+ coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
22
+ for x in coeffs]
23
+ print("\n".join(coeffs[::-1]))
24
+
25
+
26
+ if __name__ == '__main__':
27
+ main()
venv/lib/python3.10/site-packages/scipy/special/special/binom.h ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2024.
2
+ *
3
+ * Original authors: Pauli Virtanen, Eric Moore
4
+ */
5
+
6
+ // Binomial coefficient
7
+
8
+ #pragma once
9
+
10
+ #include "config.h"
11
+
12
+ #include "cephes/beta.h"
13
+ #include "cephes/gamma.h"
14
+
15
+ namespace special {
16
+
17
+ SPECFUN_HOST_DEVICE inline double binom(double n, double k) {
18
+ double kx, nx, num, den, dk, sgn;
19
+
20
+ if (n < 0) {
21
+ nx = std::floor(n);
22
+ if (n == nx) {
23
+ // Undefined
24
+ return std::numeric_limits<double>::quiet_NaN();
25
+ }
26
+ }
27
+
28
+ kx = std::floor(k);
29
+ if (k == kx && (std::abs(n) > 1E-8 || n == 0)) {
30
+ /* Integer case: use multiplication formula for less rounding
31
+ * error for cases where the result is an integer.
32
+ *
33
+ * This cannot be used for small nonzero n due to loss of
34
+ * precision. */
35
+ nx = std::floor(n);
36
+ if (nx == n && kx > nx / 2 && nx > 0) {
37
+ // Reduce kx by symmetry
38
+ kx = nx - kx;
39
+ }
40
+
41
+ if (kx >= 0 && kx < 20) {
42
+ num = 1.0;
43
+ den = 1.0;
44
+ for (int i = 1; i < 1 + static_cast<int>(kx); i++) {
45
+ num *= i + n - kx;
46
+ den *= i;
47
+ if (std::abs(num) > 1E50) {
48
+ num /= den;
49
+ den = 1.0;
50
+ }
51
+ }
52
+ return num / den;
53
+ }
54
+ }
55
+
56
+ // general case
57
+ if (n >= 1E10 * k and k > 0) {
58
+ // avoid under/overflows intermediate results
59
+ return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1));
60
+ }
61
+ if (k > 1E8 * std::abs(n)) {
62
+ // avoid loss of precision
63
+ num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ...
64
+ num /= M_PI * std::pow(std::abs(k), n);
65
+ if (k > 0) {
66
+ kx = std::floor(k);
67
+ if (static_cast<int>(kx) == kx) {
68
+ dk = k - kx;
69
+ sgn = (static_cast<int>(kx) % 2 == 0) ? 1 : -1;
70
+ } else {
71
+ dk = k;
72
+ sgn = 1;
73
+ }
74
+ return num * std::sin((dk - n) * M_PI) * sgn;
75
+ }
76
+ kx = std::floor(k);
77
+ if (static_cast<int>(kx) == kx) {
78
+ return 0;
79
+ }
80
+ return num * std::sin(k * M_PI);
81
+ }
82
+ return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k);
83
+ }
84
+
85
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/cephes/beta.h ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated into C++ by SciPy developers in 2024.
2
+ * Original header with Copyright information appears below.
3
+ */
4
+
5
+ /* beta.c
6
+ *
7
+ * Beta function
8
+ *
9
+ *
10
+ *
11
+ * SYNOPSIS:
12
+ *
13
+ * double a, b, y, beta();
14
+ *
15
+ * y = beta( a, b );
16
+ *
17
+ *
18
+ *
19
+ * DESCRIPTION:
20
+ *
21
+ * - -
22
+ * | (a) | (b)
23
+ * beta( a, b ) = -----------.
24
+ * -
25
+ * | (a+b)
26
+ *
27
+ * For large arguments the logarithm of the function is
28
+ * evaluated using lgam(), then exponentiated.
29
+ *
30
+ *
31
+ *
32
+ * ACCURACY:
33
+ *
34
+ * Relative error:
35
+ * arithmetic domain # trials peak rms
36
+ * IEEE 0,30 30000 8.1e-14 1.1e-14
37
+ *
38
+ * ERROR MESSAGES:
39
+ *
40
+ * message condition value returned
41
+ * beta overflow log(beta) > MAXLOG 0.0
42
+ * a or b <0 integer 0.0
43
+ *
44
+ */
45
+
46
+ /*
47
+ * Cephes Math Library Release 2.0: April, 1987
48
+ * Copyright 1984, 1987 by Stephen L. Moshier
49
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
50
+ */
51
+ #pragma once
52
+
53
+ #include "../config.h"
54
+ #include "const.h"
55
+ #include "gamma.h"
56
+
57
+ namespace special {
58
+ namespace cephes {
59
+
60
+ SPECFUN_HOST_DEVICE double beta(double, double);
61
+ SPECFUN_HOST_DEVICE double lbeta(double, double);
62
+
63
+ namespace detail {
64
+ constexpr double beta_ASYMP_FACTOR = 1e6;
65
+
66
+ /*
67
+ * Asymptotic expansion for ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1).
68
+ */
69
+ SPECFUN_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) {
70
+ double r = lgam_sgn(b, sgn);
71
+ r -= b * std::log(a);
72
+
73
+ r += b * (1 - b) / (2 * a);
74
+ r += b * (1 - b) * (1 - 2 * b) / (12 * a * a);
75
+ r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a);
76
+
77
+ return r;
78
+ }
79
+
80
+ /*
81
+ * Special case for a negative integer argument
82
+ */
83
+
84
+ SPECFUN_HOST_DEVICE inline double beta_negint(int a, double b) {
85
+ int sgn;
86
+ if (b == static_cast<int>(b) && 1 - a - b > 0) {
87
+ sgn = (static_cast<int>(b) % 2 == 0) ? 1 : -1;
88
+ return sgn * special::cephes::beta(1 - a - b, b);
89
+ } else {
90
+ set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
91
+ return std::numeric_limits<double>::infinity();
92
+ }
93
+ }
94
+
95
+ SPECFUN_HOST_DEVICE inline double lbeta_negint(int a, double b) {
96
+ double r;
97
+ if (b == static_cast<int>(b) && 1 - a - b > 0) {
98
+ r = special::cephes::lbeta(1 - a - b, b);
99
+ return r;
100
+ } else {
101
+ set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
102
+ return std::numeric_limits<double>::infinity();
103
+ }
104
+ }
105
+ } // namespace detail
106
+
107
+ SPECFUN_HOST_DEVICE inline double beta(double a, double b) {
108
+ double y;
109
+ int sign = 1;
110
+
111
+ if (a <= 0.0) {
112
+ if (a == std::floor(a)) {
113
+ if (a == static_cast<int>(a)) {
114
+ return detail::beta_negint(static_cast<int>(a), b);
115
+ } else {
116
+ goto overflow;
117
+ }
118
+ }
119
+ }
120
+
121
+ if (b <= 0.0) {
122
+ if (b == std::floor(b)) {
123
+ if (b == static_cast<int>(b)) {
124
+ return detail::beta_negint(static_cast<int>(b), a);
125
+ } else {
126
+ goto overflow;
127
+ }
128
+ }
129
+ }
130
+
131
+ if (std::abs(a) < std::abs(b)) {
132
+ y = a;
133
+ a = b;
134
+ b = y;
135
+ }
136
+
137
+ if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
138
+ /* Avoid loss of precision in lgam(a + b) - lgam(a) */
139
+ y = detail::lbeta_asymp(a, b, &sign);
140
+ return sign * std::exp(y);
141
+ }
142
+
143
+ y = a + b;
144
+ if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
145
+ int sgngam;
146
+ y = detail::lgam_sgn(y, &sgngam);
147
+ sign *= sgngam; /* keep track of the sign */
148
+ y = detail::lgam_sgn(b, &sgngam) - y;
149
+ sign *= sgngam;
150
+ y = detail::lgam_sgn(a, &sgngam) + y;
151
+ sign *= sgngam;
152
+ if (y > detail::MAXLOG) {
153
+ goto overflow;
154
+ }
155
+ return (sign * std::exp(y));
156
+ }
157
+
158
+ y = Gamma(y);
159
+ a = Gamma(a);
160
+ b = Gamma(b);
161
+ if (y == 0.0)
162
+ goto overflow;
163
+
164
+ if (std::abs(std::abs(a) - std::abs(y)) > std::abs(std::abs(b) - std::abs(y))) {
165
+ y = b / y;
166
+ y *= a;
167
+ } else {
168
+ y = a / y;
169
+ y *= b;
170
+ }
171
+
172
+ return (y);
173
+
174
+ overflow:
175
+ set_error("beta", SF_ERROR_OVERFLOW, NULL);
176
+ return (sign * std::numeric_limits<double>::infinity());
177
+ }
178
+
179
+ /* Natural log of |beta|. */
180
+
181
+ SPECFUN_HOST_DEVICE inline double lbeta(double a, double b) {
182
+ double y;
183
+ int sign;
184
+
185
+ sign = 1;
186
+
187
+ if (a <= 0.0) {
188
+ if (a == std::floor(a)) {
189
+ if (a == static_cast<int>(a)) {
190
+ return detail::lbeta_negint(static_cast<int>(a), b);
191
+ } else {
192
+ goto over;
193
+ }
194
+ }
195
+ }
196
+
197
+ if (b <= 0.0) {
198
+ if (b == std::floor(b)) {
199
+ if (b == static_cast<int>(b)) {
200
+ return detail::lbeta_negint(static_cast<int>(b), a);
201
+ } else {
202
+ goto over;
203
+ }
204
+ }
205
+ }
206
+
207
+ if (std::abs(a) < std::abs(b)) {
208
+ y = a;
209
+ a = b;
210
+ b = y;
211
+ }
212
+
213
+ if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
214
+ /* Avoid loss of precision in lgam(a + b) - lgam(a) */
215
+ y = detail::lbeta_asymp(a, b, &sign);
216
+ return y;
217
+ }
218
+
219
+ y = a + b;
220
+ if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
221
+ int sgngam;
222
+ y = detail::lgam_sgn(y, &sgngam);
223
+ sign *= sgngam; /* keep track of the sign */
224
+ y = detail::lgam_sgn(b, &sgngam) - y;
225
+ sign *= sgngam;
226
+ y = detail::lgam_sgn(a, &sgngam) + y;
227
+ sign *= sgngam;
228
+ return (y);
229
+ }
230
+
231
+ y = Gamma(y);
232
+ a = Gamma(a);
233
+ b = Gamma(b);
234
+ if (y == 0.0) {
235
+ over:
236
+ set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
237
+ return (sign * std::numeric_limits<double>::infinity());
238
+ }
239
+
240
+ if (std::abs(std::abs(a) - std::abs(y)) > std::abs(std::abs(b) - std::abs(y))) {
241
+ y = b / y;
242
+ y *= a;
243
+ } else {
244
+ y = a / y;
245
+ y *= b;
246
+ }
247
+
248
+ if (y < 0) {
249
+ y = -y;
250
+ }
251
+
252
+ return (std::log(y));
253
+ }
254
+ } // namespace cephes
255
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/cephes/gamma.h ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated into C++ by SciPy developers in 2024.
2
+ * Original header with Copyright information appears below.
3
+ */
4
+
5
+ /*
6
+ * Gamma function
7
+ *
8
+ *
9
+ *
10
+ * SYNOPSIS:
11
+ *
12
+ * double x, y, Gamma();
13
+ *
14
+ * y = Gamma( x );
15
+ *
16
+ *
17
+ *
18
+ * DESCRIPTION:
19
+ *
20
+ * Returns Gamma function of the argument. The result is
21
+ * correctly signed.
22
+ *
23
+ * Arguments |x| <= 34 are reduced by recurrence and the function
24
+ * approximated by a rational function of degree 6/7 in the
25
+ * interval (2,3). Large arguments are handled by Stirling's
26
+ * formula. Large negative arguments are made positive using
27
+ * a reflection formula.
28
+ *
29
+ *
30
+ * ACCURACY:
31
+ *
32
+ * Relative error:
33
+ * arithmetic domain # trials peak rms
34
+ * IEEE -170,-33 20000 2.3e-15 3.3e-16
35
+ * IEEE -33, 33 20000 9.4e-16 2.2e-16
36
+ * IEEE 33, 171.6 20000 2.3e-15 3.2e-16
37
+ *
38
+ * Error for arguments outside the test range will be larger
39
+ * owing to error amplification by the exponential function.
40
+ *
41
+ */
42
+
43
+ /* lgam()
44
+ *
45
+ * Natural logarithm of Gamma function
46
+ *
47
+ *
48
+ *
49
+ * SYNOPSIS:
50
+ *
51
+ * double x, y, lgam();
52
+ *
53
+ * y = lgam( x );
54
+ *
55
+ *
56
+ *
57
+ * DESCRIPTION:
58
+ *
59
+ * Returns the base e (2.718...) logarithm of the absolute
60
+ * value of the Gamma function of the argument.
61
+ *
62
+ * For arguments greater than 13, the logarithm of the Gamma
63
+ * function is approximated by the logarithmic version of
64
+ * Stirling's formula using a polynomial approximation of
65
+ * degree 4. Arguments between -33 and +33 are reduced by
66
+ * recurrence to the interval [2,3] of a rational approximation.
67
+ * The cosecant reflection formula is employed for arguments
68
+ * less than -33.
69
+ *
70
+ * Arguments greater than MAXLGM return INFINITY and an error
71
+ * message. MAXLGM = 2.556348e305 for IEEE arithmetic.
72
+ *
73
+ *
74
+ *
75
+ * ACCURACY:
76
+ *
77
+ *
78
+ * arithmetic domain # trials peak rms
79
+ * IEEE 0, 3 28000 5.4e-16 1.1e-16
80
+ * IEEE 2.718, 2.556e305 40000 3.5e-16 8.3e-17
81
+ * The error criterion was relative when the function magnitude
82
+ * was greater than one but absolute when it was less than one.
83
+ *
84
+ * The following test used the relative error criterion, though
85
+ * at certain points the relative error could be much higher than
86
+ * indicated.
87
+ * IEEE -200, -4 10000 4.8e-16 1.3e-16
88
+ *
89
+ */
90
+
91
+ /*
92
+ * Cephes Math Library Release 2.2: July, 1992
93
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
94
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
95
+ */
96
+ #pragma once
97
+
98
+ #include "../config.h"
99
+ #include "../error.h"
100
+ #include "polevl.h"
101
+
102
+ namespace special {
103
+ namespace cephes {
104
+ namespace detail {
105
+ constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2,
106
+ 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1,
107
+ 9.99999999999999996796E-1};
108
+
109
+ constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3,
110
+ 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1,
111
+ 7.14304917030273074085E-2, 1.00000000000000000320E0};
112
+
113
+ constexpr double MAXGAM = 171.624376956302725;
114
+ constexpr double LOGPI = 1.14472988584940017414;
115
+
116
+ /* Stirling's formula for the Gamma function */
117
+ constexpr double gamma_STIR[5] = {
118
+ 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3,
119
+ 3.47222221605458667310E-3, 8.33333333333482257126E-2,
120
+ };
121
+
122
+ constexpr double MAXSTIR = 143.01608;
123
+ constexpr double SQTPI = 2.50662827463100050242E0;
124
+
125
+ /* Gamma function computed by Stirling's formula.
126
+ * The polynomial STIR is valid for 33 <= x <= 172.
127
+ */
128
+ SPECFUN_HOST_DEVICE inline double stirf(double x) {
129
+ double y, w, v;
130
+
131
+ if (x >= MAXGAM) {
132
+ return (std::numeric_limits<double>::infinity());
133
+ }
134
+ w = 1.0 / x;
135
+ w = 1.0 + w * special::cephes::polevl(w, gamma_STIR, 4);
136
+ y = std::exp(x);
137
+ if (x > MAXSTIR) { /* Avoid overflow in pow() */
138
+ v = std::pow(x, 0.5 * x - 0.25);
139
+ y = v * (v / y);
140
+ } else {
141
+ y = std::pow(x, x - 0.5) / y;
142
+ }
143
+ y = SQTPI * y * w;
144
+ return (y);
145
+ }
146
+ } // namespace detail
147
+
148
+ SPECFUN_HOST_DEVICE inline double Gamma(double x) {
149
+ double p, q, z;
150
+ int i;
151
+ int sgngam = 1;
152
+
153
+ if (!std::isfinite(x)) {
154
+ return x;
155
+ }
156
+ q = std::abs(x);
157
+
158
+ if (q > 33.0) {
159
+ if (x < 0.0) {
160
+ p = floor(q);
161
+ if (p == q) {
162
+ gamnan:
163
+ set_error("Gamma", SF_ERROR_OVERFLOW, NULL);
164
+ return (std::numeric_limits<double>::infinity());
165
+ }
166
+ i = p;
167
+ if ((i & 1) == 0) {
168
+ sgngam = -1;
169
+ }
170
+ z = q - p;
171
+ if (z > 0.5) {
172
+ p += 1.0;
173
+ z = q - p;
174
+ }
175
+ z = q * std::sin(M_PI * z);
176
+ if (z == 0.0) {
177
+ return (sgngam * std::numeric_limits<double>::infinity());
178
+ }
179
+ z = std::abs(z);
180
+ z = M_PI / (z * detail::stirf(q));
181
+ } else {
182
+ z = detail::stirf(x);
183
+ }
184
+ return (sgngam * z);
185
+ }
186
+
187
+ z = 1.0;
188
+ while (x >= 3.0) {
189
+ x -= 1.0;
190
+ z *= x;
191
+ }
192
+
193
+ while (x < 0.0) {
194
+ if (x > -1.E-9) {
195
+ goto small;
196
+ }
197
+ z /= x;
198
+ x += 1.0;
199
+ }
200
+
201
+ while (x < 2.0) {
202
+ if (x < 1.e-9) {
203
+ goto small;
204
+ }
205
+ z /= x;
206
+ x += 1.0;
207
+ }
208
+
209
+ if (x == 2.0) {
210
+ return (z);
211
+ }
212
+
213
+ x -= 2.0;
214
+ p = polevl(x, detail::gamma_P, 6);
215
+ q = polevl(x, detail::gamma_Q, 7);
216
+ return (z * p / q);
217
+
218
+ small:
219
+ if (x == 0.0) {
220
+ goto gamnan;
221
+ } else
222
+ return (z / ((1.0 + 0.5772156649015329 * x) * x));
223
+ }
224
+
225
+ namespace detail {
226
+ /* A[]: Stirling's formula expansion of log Gamma
227
+ * B[], C[]: log Gamma function between 2 and 3
228
+ */
229
+ constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4,
230
+ -2.77777777730099687205E-3, 8.33333333333331927722E-2};
231
+
232
+ constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5,
233
+ -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5};
234
+
235
+ constexpr double gamma_C[] = {
236
+ /* 1.00000000000000000000E0, */
237
+ -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5,
238
+ -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6};
239
+
240
+ /* log( sqrt( 2*pi ) ) */
241
+ constexpr double LS2PI = 0.91893853320467274178;
242
+
243
+ constexpr double MAXLGM = 2.556348e305;
244
+
245
+ SPECFUN_HOST_DEVICE double lgam_sgn(double x, int *sign) {
246
+ double p, q, u, w, z;
247
+ int i;
248
+
249
+ *sign = 1;
250
+
251
+ if (!std::isfinite(x)) {
252
+ return x;
253
+ }
254
+
255
+ if (x < -34.0) {
256
+ q = -x;
257
+ w = lgam_sgn(q, sign);
258
+ p = floor(q);
259
+ if (p == q) {
260
+ lgsing:
261
+ set_error("lgam", SF_ERROR_SINGULAR, NULL);
262
+ return (std::numeric_limits<double>::infinity());
263
+ }
264
+ i = p;
265
+ if ((i & 1) == 0) {
266
+ *sign = -1;
267
+ } else {
268
+ *sign = 1;
269
+ }
270
+ z = q - p;
271
+ if (z > 0.5) {
272
+ p += 1.0;
273
+ z = p - q;
274
+ }
275
+ z = q * std::sin(M_PI * z);
276
+ if (z == 0.0) {
277
+ goto lgsing;
278
+ }
279
+ /* z = log(M_PI) - log( z ) - w; */
280
+ z = LOGPI - std::log(z) - w;
281
+ return (z);
282
+ }
283
+
284
+ if (x < 13.0) {
285
+ z = 1.0;
286
+ p = 0.0;
287
+ u = x;
288
+ while (u >= 3.0) {
289
+ p -= 1.0;
290
+ u = x + p;
291
+ z *= u;
292
+ }
293
+ while (u < 2.0) {
294
+ if (u == 0.0) {
295
+ goto lgsing;
296
+ }
297
+ z /= u;
298
+ p += 1.0;
299
+ u = x + p;
300
+ }
301
+ if (z < 0.0) {
302
+ *sign = -1;
303
+ z = -z;
304
+ } else {
305
+ *sign = 1;
306
+ }
307
+ if (u == 2.0) {
308
+ return (std::log(z));
309
+ }
310
+ p -= 2.0;
311
+ x = x + p;
312
+ p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6);
313
+ return (std::log(z) + p);
314
+ }
315
+
316
+ if (x > MAXLGM) {
317
+ return (*sign * std::numeric_limits<double>::infinity());
318
+ }
319
+
320
+ q = (x - 0.5) * std::log(x) - x + LS2PI;
321
+ if (x > 1.0e8) {
322
+ return (q);
323
+ }
324
+
325
+ p = 1.0 / (x * x);
326
+ if (x >= 1000.0) {
327
+ q += ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) /
328
+ x;
329
+ } else {
330
+ q += polevl(p, gamma_A, 4) / x;
331
+ }
332
+ return (q);
333
+ }
334
+ } // namespace detail
335
+
336
+ /* Logarithm of Gamma function */
337
+ SPECFUN_HOST_DEVICE double lgam(double x) {
338
+ int sign;
339
+ return detail::lgam_sgn(x, &sign);
340
+ }
341
+
342
+ } // namespace cephes
343
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/cephes/psi.h ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated into C++ by SciPy developers in 2024.
2
+ * Original header with Copyright information appears below.
3
+ */
4
+
5
+ /* psi.c
6
+ *
7
+ * Psi (digamma) function
8
+ *
9
+ *
10
+ * SYNOPSIS:
11
+ *
12
+ * double x, y, psi();
13
+ *
14
+ * y = psi( x );
15
+ *
16
+ *
17
+ * DESCRIPTION:
18
+ *
19
+ * d -
20
+ * psi(x) = -- ln | (x)
21
+ * dx
22
+ *
23
+ * is the logarithmic derivative of the gamma function.
24
+ * For integer x,
25
+ * n-1
26
+ * -
27
+ * psi(n) = -EUL + > 1/k.
28
+ * -
29
+ * k=1
30
+ *
31
+ * This formula is used for 0 < n <= 10. If x is negative, it
32
+ * is transformed to a positive argument by the reflection
33
+ * formula psi(1-x) = psi(x) + pi cot(pi x).
34
+ * For general positive x, the argument is made greater than 10
35
+ * using the recurrence psi(x+1) = psi(x) + 1/x.
36
+ * Then the following asymptotic expansion is applied:
37
+ *
38
+ * inf. B
39
+ * - 2k
40
+ * psi(x) = log(x) - 1/2x - > -------
41
+ * - 2k
42
+ * k=1 2k x
43
+ *
44
+ * where the B2k are Bernoulli numbers.
45
+ *
46
+ * ACCURACY:
47
+ * Relative error (except absolute when |psi| < 1):
48
+ * arithmetic domain # trials peak rms
49
+ * IEEE 0,30 30000 1.3e-15 1.4e-16
50
+ * IEEE -30,0 40000 1.5e-15 2.2e-16
51
+ *
52
+ * ERROR MESSAGES:
53
+ * message condition value returned
54
+ * psi singularity x integer <=0 INFINITY
55
+ */
56
+
57
+ /*
58
+ * Cephes Math Library Release 2.8: June, 2000
59
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
60
+ */
61
+
62
+ /*
63
+ * Code for the rational approximation on [1, 2] is:
64
+ *
65
+ * (C) Copyright John Maddock 2006.
66
+ * Use, modification and distribution are subject to the
67
+ * Boost Software License, Version 1.0. (See accompanying file
68
+ * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
69
+ */
70
+ #pragma once
71
+
72
+ #include "../config.h"
73
+ #include "../error.h"
74
+ #include "const.h"
75
+ #include "polevl.h"
76
+
77
+ namespace special {
78
+ namespace cephes {
79
+ namespace detail {
80
+ constexpr double psi_A[] = {8.33333333333333333333E-2, -2.10927960927960927961E-2, 7.57575757575757575758E-3,
81
+ -4.16666666666666666667E-3, 3.96825396825396825397E-3, -8.33333333333333333333E-3,
82
+ 8.33333333333333333333E-2};
83
+
84
+ constexpr float psi_Y = 0.99558162689208984f;
85
+
86
+ constexpr double psi_root1 = 1569415565.0 / 1073741824.0;
87
+ constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0;
88
+ constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19;
89
+
90
+ constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784,
91
+ -0.65031853770896507, -0.32555031186804491, 0.25479851061131551};
92
+ constexpr double psi_Q[] = {-0.55789841321675513e-6,
93
+ 0.0021284987017821144,
94
+ 0.054151797245674225,
95
+ 0.43593529692665969,
96
+ 1.4606242909763515,
97
+ 2.0767117023730469,
98
+ 1.0};
99
+
100
+ SPECFUN_HOST_DEVICE double digamma_imp_1_2(double x) {
101
+ /*
102
+ * Rational approximation on [1, 2] taken from Boost.
103
+ *
104
+ * Now for the approximation, we use the form:
105
+ *
106
+ * digamma(x) = (x - root) * (Y + R(x-1))
107
+ *
108
+ * Where root is the location of the positive root of digamma,
109
+ * Y is a constant, and R is optimised for low absolute error
110
+ * compared to Y.
111
+ *
112
+ * Maximum Deviation Found: 1.466e-18
113
+ * At double precision, max error found: 2.452e-17
114
+ */
115
+ double r, g;
116
+
117
+ g = x - psi_root1;
118
+ g -= psi_root2;
119
+ g -= psi_root3;
120
+ r = special::cephes::polevl(x - 1.0, psi_P, 5) / special::cephes::polevl(x - 1.0, psi_Q, 6);
121
+
122
+ return g * psi_Y + g * r;
123
+ }
124
+
125
+ SPECFUN_HOST_DEVICE double psi_asy(double x) {
126
+ double y, z;
127
+
128
+ if (x < 1.0e17) {
129
+ z = 1.0 / (x * x);
130
+ y = z * special::cephes::polevl(z, psi_A, 6);
131
+ } else {
132
+ y = 0.0;
133
+ }
134
+
135
+ return std::log(x) - (0.5 / x) - y;
136
+ }
137
+ } // namespace detail
138
+
139
+ SPECFUN_HOST_DEVICE double psi(double x) {
140
+ double y = 0.0;
141
+ double q, r;
142
+ int i, n;
143
+
144
+ if (std::isnan(x)) {
145
+ return x;
146
+ } else if (x == std::numeric_limits<double>::infinity()) {
147
+ return x;
148
+ } else if (x == -std::numeric_limits<double>::infinity()) {
149
+ return std::numeric_limits<double>::quiet_NaN();
150
+ } else if (x == 0) {
151
+ set_error("psi", SF_ERROR_SINGULAR, NULL);
152
+ return std::copysign(std::numeric_limits<double>::infinity(), -x);
153
+ } else if (x < 0.0) {
154
+ /* argument reduction before evaluating tan(pi * x) */
155
+ r = std::modf(x, &q);
156
+ if (r == 0.0) {
157
+ set_error("psi", SF_ERROR_SINGULAR, NULL);
158
+ return std::numeric_limits<double>::quiet_NaN();
159
+ }
160
+ y = -M_PI / std::tan(M_PI * r);
161
+ x = 1.0 - x;
162
+ }
163
+
164
+ /* check for positive integer up to 10 */
165
+ if ((x <= 10.0) && (x == std::floor(x))) {
166
+ n = static_cast<int>(x);
167
+ for (i = 1; i < n; i++) {
168
+ y += 1.0 / i;
169
+ }
170
+ y -= detail::SCIPY_EULER;
171
+ return y;
172
+ }
173
+
174
+ /* use the recurrence relation to move x into [1, 2] */
175
+ if (x < 1.0) {
176
+ y -= 1.0 / x;
177
+ x += 1.0;
178
+ } else if (x < 10.0) {
179
+ while (x > 2.0) {
180
+ x -= 1.0;
181
+ y += 1.0 / x;
182
+ }
183
+ }
184
+ if ((1.0 <= x) && (x <= 2.0)) {
185
+ y += detail::digamma_imp_1_2(x);
186
+ return y;
187
+ }
188
+
189
+ /* x is large, use the asymptotic series */
190
+ y += detail::psi_asy(x);
191
+ return y;
192
+ }
193
+ } // namespace cephes
194
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/cephes/zeta.h ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated into C++ by SciPy developers in 2024.
2
+ * Original header with Copyright information appears below.
3
+ */
4
+
5
+ /* zeta.c
6
+ *
7
+ * Riemann zeta function of two arguments
8
+ *
9
+ *
10
+ *
11
+ * SYNOPSIS:
12
+ *
13
+ * double x, q, y, zeta();
14
+ *
15
+ * y = zeta( x, q );
16
+ *
17
+ *
18
+ *
19
+ * DESCRIPTION:
20
+ *
21
+ *
22
+ *
23
+ * inf.
24
+ * - -x
25
+ * zeta(x,q) = > (k+q)
26
+ * -
27
+ * k=0
28
+ *
29
+ * where x > 1 and q is not a negative integer or zero.
30
+ * The Euler-Maclaurin summation formula is used to obtain
31
+ * the expansion
32
+ *
33
+ * n
34
+ * - -x
35
+ * zeta(x,q) = > (k+q)
36
+ * -
37
+ * k=1
38
+ *
39
+ * 1-x inf. B x(x+1)...(x+2j)
40
+ * (n+q) 1 - 2j
41
+ * + --------- - ------- + > --------------------
42
+ * x-1 x - x+2j+1
43
+ * 2(n+q) j=1 (2j)! (n+q)
44
+ *
45
+ * where the B2j are Bernoulli numbers. Note that (see zetac.c)
46
+ * zeta(x,1) = zetac(x) + 1.
47
+ *
48
+ *
49
+ *
50
+ * ACCURACY:
51
+ *
52
+ *
53
+ *
54
+ * REFERENCE:
55
+ *
56
+ * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals,
57
+ * Series, and Products, p. 1073; Academic Press, 1980.
58
+ *
59
+ */
60
+
61
+ /*
62
+ * Cephes Math Library Release 2.0: April, 1987
63
+ * Copyright 1984, 1987 by Stephen L. Moshier
64
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
65
+ */
66
+ #pragma once
67
+
68
+ #include "../config.h"
69
+ #include "../error.h"
70
+ #include "const.h"
71
+
72
+ namespace special {
73
+ namespace cephes {
74
+
75
+ namespace detail {
76
+ /* Expansion coefficients
77
+ * for Euler-Maclaurin summation formula
78
+ * (2k)! / B2k
79
+ * where B2k are Bernoulli numbers
80
+ */
81
+ constexpr double zeta_A[] = {
82
+ 12.0,
83
+ -720.0,
84
+ 30240.0,
85
+ -1209600.0,
86
+ 47900160.0,
87
+ -1.8924375803183791606e9, /*1.307674368e12/691 */
88
+ 7.47242496e10,
89
+ -2.950130727918164224e12, /*1.067062284288e16/3617 */
90
+ 1.1646782814350067249e14, /*5.109094217170944e18/43867 */
91
+ -4.5979787224074726105e15, /*8.028576626982912e20/174611 */
92
+ 1.8152105401943546773e17, /*1.5511210043330985984e23/854513 */
93
+ -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091 */
94
+ };
95
+
96
+ /* 30 Nov 86 -- error in third coefficient fixed */
97
+ } // namespace detail
98
+
99
+ SPECFUN_HOST_DEVICE double zeta(double x, double q) {
100
+ int i;
101
+ double a, b, k, s, t, w;
102
+
103
+ if (x == 1.0)
104
+ goto retinf;
105
+
106
+ if (x < 1.0) {
107
+ domerr:
108
+ set_error("zeta", SF_ERROR_DOMAIN, NULL);
109
+ return (std::numeric_limits<double>::quiet_NaN());
110
+ }
111
+
112
+ if (q <= 0.0) {
113
+ if (q == floor(q)) {
114
+ set_error("zeta", SF_ERROR_SINGULAR, NULL);
115
+ retinf:
116
+ return (std::numeric_limits<double>::infinity());
117
+ }
118
+ if (x != std::floor(x))
119
+ goto domerr; /* because q^-x not defined */
120
+ }
121
+
122
+ /* Asymptotic expansion
123
+ * https://dlmf.nist.gov/25.11#E43
124
+ */
125
+ if (q > 1e8) {
126
+ return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x);
127
+ }
128
+
129
+ /* Euler-Maclaurin summation formula */
130
+
131
+ /* Permit negative q but continue sum until n+q > +9 .
132
+ * This case should be handled by a reflection formula.
133
+ * If q<0 and x is an integer, there is a relation to
134
+ * the polyGamma function.
135
+ */
136
+ s = std::pow(q, -x);
137
+ a = q;
138
+ i = 0;
139
+ b = 0.0;
140
+ while ((i < 9) || (a <= 9.0)) {
141
+ i += 1;
142
+ a += 1.0;
143
+ b = std::pow(a, -x);
144
+ s += b;
145
+ if (std::abs(b / s) < detail::MACHEP)
146
+ goto done;
147
+ }
148
+
149
+ w = a;
150
+ s += b * w / (x - 1.0);
151
+ s -= 0.5 * b;
152
+ a = 1.0;
153
+ k = 0.0;
154
+ for (i = 0; i < 12; i++) {
155
+ a *= x + k;
156
+ b /= w;
157
+ t = a * b / detail::zeta_A[i];
158
+ s = s + t;
159
+ t = std::abs(t / s);
160
+ if (t < detail::MACHEP)
161
+ goto done;
162
+ k += 1.0;
163
+ a *= x + k;
164
+ b /= w;
165
+ k += 1.0;
166
+ }
167
+ done:
168
+ return (s);
169
+ }
170
+
171
+ } // namespace cephes
172
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/config.h ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // Define math constants if they are not available
4
+ #ifndef M_E
5
+ #define M_E 2.71828182845904523536
6
+ #endif
7
+
8
+ #ifndef M_LOG2E
9
+ #define M_LOG2E 1.44269504088896340736
10
+ #endif
11
+
12
+ #ifndef M_LOG10E
13
+ #define M_LOG10E 0.434294481903251827651
14
+ #endif
15
+
16
+ #ifndef M_LN2
17
+ #define M_LN2 0.693147180559945309417
18
+ #endif
19
+
20
+ #ifndef M_LN10
21
+ #define M_LN10 2.30258509299404568402
22
+ #endif
23
+
24
+ #ifndef M_PI
25
+ #define M_PI 3.14159265358979323846
26
+ #endif
27
+
28
+ #ifndef M_PI_2
29
+ #define M_PI_2 1.57079632679489661923
30
+ #endif
31
+
32
+ #ifndef M_PI_4
33
+ #define M_PI_4 0.785398163397448309616
34
+ #endif
35
+
36
+ #ifndef M_1_PI
37
+ #define M_1_PI 0.318309886183790671538
38
+ #endif
39
+
40
+ #ifndef M_2_PI
41
+ #define M_2_PI 0.636619772367581343076
42
+ #endif
43
+
44
+ #ifndef M_2_SQRTPI
45
+ #define M_2_SQRTPI 1.12837916709551257390
46
+ #endif
47
+
48
+ #ifndef M_SQRT2
49
+ #define M_SQRT2 1.41421356237309504880
50
+ #endif
51
+
52
+ #ifndef M_SQRT1_2
53
+ #define M_SQRT1_2 0.707106781186547524401
54
+ #endif
55
+
56
+ #ifdef __CUDACC__
57
+ #define SPECFUN_HOST_DEVICE __host__ __device__
58
+
59
+ #include <cuda/std/cmath>
60
+ #include <cuda/std/limits>
61
+
62
+ // Fallback to global namespace for functions unsupported on NVRTC Jit
63
+ #ifdef _LIBCUDACXX_COMPILER_NVRTC
64
+ #include <cuda_runtime.h>
65
+ #endif
66
+
67
+ namespace std {
68
+
69
+ SPECFUN_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); }
70
+
71
+ SPECFUN_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); }
72
+
73
+ SPECFUN_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); }
74
+
75
+ SPECFUN_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); }
76
+
77
+ SPECFUN_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); }
78
+
79
+ SPECFUN_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); }
80
+
81
+ SPECFUN_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); }
82
+
83
+ SPECFUN_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); }
84
+
85
+ SPECFUN_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); }
86
+
87
+ SPECFUN_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); }
88
+
89
+ SPECFUN_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); }
90
+
91
+ SPECFUN_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); }
92
+
93
+ // Fallback to global namespace for functions unsupported on NVRTC
94
+ #ifndef _LIBCUDACXX_COMPILER_NVRTC
95
+ SPECFUN_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); }
96
+ SPECFUN_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); }
97
+ SPECFUN_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); }
98
+ SPECFUN_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); }
99
+ SPECFUN_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); }
100
+ SPECFUN_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); }
101
+
102
+ #else
103
+ SPECFUN_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); }
104
+ SPECFUN_HOST_DEVICE inline double floor(double x) { return ::floor(x); }
105
+ SPECFUN_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); }
106
+ SPECFUN_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); }
107
+ SPECFUN_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); }
108
+ SPECFUN_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); }
109
+ #endif
110
+
111
+ template <typename T>
112
+ using numeric_limits = cuda::std::numeric_limits<T>;
113
+
114
+ // Must use thrust for complex types in order to support CuPy
115
+ template <typename T>
116
+ using complex = thrust::complex<T>;
117
+
118
+ template <typename T>
119
+ SPECFUN_HOST_DEVICE T abs(const complex<T> &z) {
120
+ return thrust::abs(z);
121
+ }
122
+
123
+ template <typename T>
124
+ SPECFUN_HOST_DEVICE complex<T> exp(const complex<T> &z) {
125
+ return thrust::exp(z);
126
+ }
127
+
128
+ template <typename T>
129
+ SPECFUN_HOST_DEVICE complex<T> log(const complex<T> &z) {
130
+ return thrust::log(z);
131
+ }
132
+
133
+ template <typename T>
134
+ SPECFUN_HOST_DEVICE T norm(const complex<T> &z) {
135
+ return thrust::norm(z);
136
+ }
137
+
138
+ template <typename T>
139
+ SPECFUN_HOST_DEVICE complex<T> sqrt(const complex<T> &z) {
140
+ return thrust::sqrt(z);
141
+ }
142
+
143
+ template <typename T>
144
+ SPECFUN_HOST_DEVICE complex<T> conj(const complex<T> &z) {
145
+ return thrust::conj(z);
146
+ }
147
+
148
+ } // namespace std
149
+
150
+ #else
151
+ #define SPECFUN_HOST_DEVICE
152
+
153
+ #include <cmath>
154
+ #include <complex>
155
+ #include <limits>
156
+ #include <math.h>
157
+
158
+ #endif
venv/lib/python3.10/site-packages/scipy/special/special/digamma.h ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2024.
2
+ * Original header comment appears below.
3
+ */
4
+
5
+ /* An implementation of the digamma function for complex arguments.
6
+ *
7
+ * Author: Josh Wilson
8
+ *
9
+ * Distributed under the same license as Scipy.
10
+ *
11
+ * Sources:
12
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
13
+ *
14
+ * [2] mpmath (version 0.19), http://mpmath.org
15
+ */
16
+
17
+ #pragma once
18
+
19
+ #include "cephes/psi.h"
20
+ #include "cephes/zeta.h"
21
+ #include "config.h"
22
+ #include "error.h"
23
+ #include "trig.h"
24
+
25
+ namespace special {
26
+ namespace detail {
27
+ // All of the following were computed with mpmath
28
+ // Location of the positive root
29
+ constexpr double digamma_posroot = 1.4616321449683623;
30
+ // Value of the positive root
31
+ constexpr double digamma_posrootval = -9.2412655217294275e-17;
32
+ // Location of the negative root
33
+ constexpr double digamma_negroot = -0.504083008264455409;
34
+ // Value of the negative root
35
+ constexpr double digamma_negrootval = 7.2897639029768949e-17;
36
+
37
+ template <typename T>
38
+ SPECFUN_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) {
39
+ T res = rootval;
40
+ T coeff = -1.0;
41
+
42
+ z = z - root;
43
+ T term;
44
+ for (int n = 1; n < 100; n++) {
45
+ coeff *= -z;
46
+ term = coeff * cephes::zeta(n + 1, root);
47
+ res += term;
48
+ if (std::abs(term) < std::numeric_limits<double>::epsilon() * std::abs(res)) {
49
+ break;
50
+ }
51
+ }
52
+ return res;
53
+ }
54
+
55
+ SPECFUN_HOST_DEVICE inline std::complex<double> digamma_forward_recurrence(std::complex<double> z,
56
+ std::complex<double> psiz, int n) {
57
+ /* Compute digamma(z + n) using digamma(z) using the recurrence
58
+ * relation
59
+ *
60
+ * digamma(z + 1) = digamma(z) + 1/z.
61
+ *
62
+ * See https://dlmf.nist.gov/5.5#E2 */
63
+ std::complex<double> res = psiz;
64
+
65
+ for (int k = 0; k < n; k++) {
66
+ res += 1.0 / (z + static_cast<double>(k));
67
+ }
68
+ return res;
69
+ }
70
+
71
+ SPECFUN_HOST_DEVICE inline std::complex<double> digamma_backward_recurrence(std::complex<double> z,
72
+ std::complex<double> psiz, int n) {
73
+ /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */
74
+ std::complex<double> res = psiz;
75
+
76
+ for (int k = 1; k < n + 1; k++) {
77
+ res -= 1.0 / (z - static_cast<double>(k));
78
+ }
79
+ return res;
80
+ }
81
+
82
+ SPECFUN_HOST_DEVICE inline std::complex<double> digamma_asymptotic_series(std::complex<double> z) {
83
+ /* Evaluate digamma using an asymptotic series. See
84
+ *
85
+ * https://dlmf.nist.gov/5.11#E2 */
86
+ double bernoulli2k[] = {
87
+ 0.166666666666666667, -0.0333333333333333333, 0.0238095238095238095, -0.0333333333333333333,
88
+ 0.0757575757575757576, -0.253113553113553114, 1.16666666666666667, -7.09215686274509804,
89
+ 54.9711779448621554, -529.124242424242424, 6192.12318840579710, -86580.2531135531136,
90
+ 1425517.16666666667, -27298231.0678160920, 601580873.900642368, -15116315767.0921569};
91
+ std::complex<double> rzz = 1.0 / z / z;
92
+ std::complex<double> zfac = 1.0;
93
+ std::complex<double> term;
94
+ std::complex<double> res;
95
+
96
+ if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) {
97
+ /* Check for infinity (or nan) and return early.
98
+ * Result of division by complex infinity is implementation dependent.
99
+ * and has been observed to vary between C++ stdlib and CUDA stdlib.
100
+ */
101
+ return std::log(z);
102
+ }
103
+
104
+ res = std::log(z) - 0.5 / z;
105
+
106
+ for (int k = 1; k < 17; k++) {
107
+ zfac *= rzz;
108
+ term = -bernoulli2k[k - 1] * zfac / (2 * static_cast<double>(k));
109
+ res += term;
110
+ if (std::abs(term) < std::numeric_limits<double>::epsilon() * std::abs(res)) {
111
+ break;
112
+ }
113
+ }
114
+ return res;
115
+ }
116
+
117
+ } // namespace detail
118
+
119
+ SPECFUN_HOST_DEVICE inline double digamma(double z) {
120
+ /* Wrap Cephes' psi to take advantage of the series expansion around
121
+ * the smallest negative zero.
122
+ */
123
+ if (std::abs(z - detail::digamma_negroot) < 0.3) {
124
+ return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
125
+ }
126
+ return cephes::psi(z);
127
+ }
128
+
129
+ SPECFUN_HOST_DEVICE inline std::complex<double> digamma(std::complex<double> z) {
130
+ /*
131
+ * Compute the digamma function for complex arguments. The strategy
132
+ * is:
133
+ *
134
+ * - Around the two zeros closest to the origin (posroot and negroot)
135
+ * use a Taylor series with precomputed zero order coefficient.
136
+ * - If close to the origin, use a recurrence relation to step away
137
+ * from the origin.
138
+ * - If close to the negative real axis, use the reflection formula
139
+ * to move to the right halfplane.
140
+ * - If |z| is large (> 16), use the asymptotic series.
141
+ * - If |z| is small, use a recurrence relation to make |z| large
142
+ * enough to use the asymptotic series.
143
+ */
144
+ double absz = std::abs(z);
145
+ std::complex<double> res = 0;
146
+ /* Use the asymptotic series for z away from the negative real axis
147
+ * with abs(z) > smallabsz. */
148
+ int smallabsz = 16;
149
+ /* Use the reflection principle for z with z.real < 0 that are within
150
+ * smallimag of the negative real axis.
151
+ * int smallimag = 6 # unused below except in a comment */
152
+
153
+ if (z.real() <= 0.0 && std::ceil(z.real()) == z) {
154
+ // Poles
155
+ set_error("digamma", SF_ERROR_SINGULAR, NULL);
156
+ return {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()};
157
+ }
158
+ if (std::abs(z - detail::digamma_negroot) < 0.3) {
159
+ // First negative root.
160
+ return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
161
+ }
162
+
163
+ if (z.real() < 0 and std::abs(z.imag()) < smallabsz) {
164
+ /* Reflection formula for digamma. See
165
+ *
166
+ *https://dlmf.nist.gov/5.5#E4
167
+ */
168
+ res = -M_PI * cospi(z) / sinpi(z);
169
+ z = 1.0 - z;
170
+ absz = std::abs(z);
171
+ }
172
+
173
+ if (absz < 0.5) {
174
+ /* Use one step of the recurrence relation to step away from
175
+ * the pole. */
176
+ res = -1.0 / z;
177
+ z += 1.0;
178
+ absz = std::abs(z);
179
+ }
180
+
181
+ if (std::abs(z - detail::digamma_posroot) < 0.5) {
182
+ res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval);
183
+ } else if (absz > smallabsz) {
184
+ res += detail::digamma_asymptotic_series(z);
185
+ } else if (z.real() >= 0.0) {
186
+ double n = std::trunc(smallabsz - absz) + 1;
187
+ std::complex<double> init = detail::digamma_asymptotic_series(z + n);
188
+ res += detail::digamma_backward_recurrence(z + n, init, n);
189
+ } else {
190
+ // z.real() < 0, absz < smallabsz, and z.imag() > smallimag
191
+ double n = std::trunc(smallabsz - absz) - 1;
192
+ std::complex<double> init = detail::digamma_asymptotic_series(z - n);
193
+ res += detail::digamma_forward_recurrence(z - n, init, n);
194
+ }
195
+ return res;
196
+ }
197
+
198
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/error.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // should be included from config.h, but that won't work until we've cleanly separated out the C and C++ parts of the
4
+ // code
5
+ #ifdef __CUDACC__
6
+ #define SPECFUN_HOST_DEVICE __host__ __device__
7
+ #else
8
+ #define SPECFUN_HOST_DEVICE
9
+ #endif
10
+
11
+ #ifdef __cplusplus
12
+ extern "C" {
13
+ #endif
14
+
15
+ typedef enum {
16
+ SF_ERROR_OK = 0, /* no error */
17
+ SF_ERROR_SINGULAR, /* singularity encountered */
18
+ SF_ERROR_UNDERFLOW, /* floating point underflow */
19
+ SF_ERROR_OVERFLOW, /* floating point overflow */
20
+ SF_ERROR_SLOW, /* too many iterations required */
21
+ SF_ERROR_LOSS, /* loss of precision */
22
+ SF_ERROR_NO_RESULT, /* no result obtained */
23
+ SF_ERROR_DOMAIN, /* out of domain */
24
+ SF_ERROR_ARG, /* invalid input parameter */
25
+ SF_ERROR_OTHER, /* unclassified error */
26
+ SF_ERROR__LAST
27
+ } sf_error_t;
28
+
29
+ #ifdef __cplusplus
30
+ namespace special {
31
+
32
+ #ifndef SP_SPECFUN_ERROR
33
+ SPECFUN_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) {
34
+ // nothing
35
+ }
36
+ #else
37
+ void set_error(const char *func_name, sf_error_t code, const char *fmt, ...);
38
+ #endif
39
+ } // namespace special
40
+
41
+ } // closes extern "C"
42
+ #endif
venv/lib/python3.10/site-packages/scipy/special/special/evalpoly.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2024.
2
+ *
3
+ * Original author: Josh Wilson, 2016.
4
+ */
5
+
6
+ /* Evaluate polynomials.
7
+ *
8
+ * All of the coefficients are stored in reverse order, i.e. if the
9
+ * polynomial is
10
+ *
11
+ * u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0,
12
+ *
13
+ * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0.
14
+ *
15
+ * References
16
+ * ----------
17
+ * [1] Knuth, "The Art of Computer Programming, Volume II"
18
+ */
19
+
20
+ #pragma once
21
+
22
+ #include "config.h"
23
+
24
+ namespace special {
25
+
26
+ SPECFUN_HOST_DEVICE inline std::complex<double> cevalpoly(const double *coeffs, int degree, std::complex<double> z) {
27
+ /* Evaluate a polynomial with real coefficients at a complex point.
28
+ *
29
+ * Uses equation (3) in section 4.6.4 of [1]. Note that it is more
30
+ * efficient than Horner's method.
31
+ */
32
+ double a = coeffs[0];
33
+ double b = coeffs[1];
34
+ double r = 2 * z.real();
35
+ double s = std::norm(z);
36
+ double tmp;
37
+
38
+ for (int j = 2; j < degree + 1; j++) {
39
+ tmp = b;
40
+ b = std::fma(-s, a, coeffs[j]);
41
+ a = std::fma(r, a, tmp);
42
+ }
43
+
44
+ return z * a + b;
45
+ }
46
+
47
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/lambertw.h ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2023.
2
+ * Original header with Copyright information appears below.
3
+ */
4
+
5
+ /* Implementation of the Lambert W function [1]. Based on MPMath
6
+ * Implementation [2], and documentation [3].
7
+ *
8
+ * Copyright: Yosef Meller, 2009
9
+ * Author email: [email protected]
10
+ *
11
+ * Distributed under the same license as SciPy
12
+ *
13
+ *
14
+ * References:
15
+ * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359,
16
+ * available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
17
+ * [2] mpmath source code,
18
+ https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461
19
+ * [3]
20
+ https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function
21
+ *
22
+
23
+ * TODO: use a series expansion when extremely close to the branch point
24
+ * at `-1/e` and make sure that the proper branch is chosen there.
25
+ */
26
+
27
+ #pragma once
28
+
29
+ #include "config.h"
30
+ #include "error.h"
31
+ #include "evalpoly.h"
32
+
33
+ namespace special {
34
+ constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1)
35
+ constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0)
36
+
37
+ namespace detail {
38
+ SPECFUN_HOST_DEVICE inline std::complex<double> lambertw_branchpt(std::complex<double> z) {
39
+ // Series for W(z, 0) around the branch point; see 4.22 in [1].
40
+ double coeffs[] = {-1.0 / 3.0, 1.0, -1.0};
41
+ std::complex<double> p = std::sqrt(2.0 * (M_E * z + 1.0));
42
+
43
+ return cevalpoly(coeffs, 2, p);
44
+ }
45
+
46
+ SPECFUN_HOST_DEVICE inline std::complex<double> lambertw_pade0(std::complex<double> z) {
47
+ // (3, 2) Pade approximation for W(z, 0) around 0.
48
+ double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0};
49
+ double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0};
50
+
51
+ /* This only gets evaluated close to 0, so we don't need a more
52
+ * careful algorithm that avoids overflow in the numerator for
53
+ * large z. */
54
+ return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z);
55
+ }
56
+
57
+ SPECFUN_HOST_DEVICE inline std::complex<double> lambertw_asy(std::complex<double> z, long k) {
58
+ /* Compute the W function using the first two terms of the
59
+ * asymptotic series. See 4.20 in [1].
60
+ */
61
+ std::complex<double> w = std::log(z) + 2.0 * M_PI * k * std::complex<double>(0, 1);
62
+ return w - std::log(w);
63
+ }
64
+
65
+ } // namespace detail
66
+
67
+ SPECFUN_HOST_DEVICE inline std::complex<double> lambertw(std::complex<double> z, long k, double tol) {
68
+ double absz;
69
+ std::complex<double> w;
70
+ std::complex<double> ew, wew, wewz, wn;
71
+
72
+ if (std::isnan(z.real()) || std::isnan(z.imag())) {
73
+ return z;
74
+ }
75
+ if (z.real() == std::numeric_limits<double>::infinity()) {
76
+ return z + 2.0 * M_PI * k * std::complex<double>(0, 1);
77
+ }
78
+ if (z.real() == -std::numeric_limits<double>::infinity()) {
79
+ return -z + (2.0 * M_PI * k + M_PI) * std::complex<double>(0, 1);
80
+ }
81
+ if (z == 0.0) {
82
+ if (k == 0) {
83
+ return z;
84
+ }
85
+ set_error("lambertw", SF_ERROR_SINGULAR, NULL);
86
+ return -std::numeric_limits<double>::infinity();
87
+ }
88
+ if (z == 1.0 && k == 0) {
89
+ // Split out this case because the asymptotic series blows up
90
+ return OMEGA;
91
+ }
92
+
93
+ absz = std::abs(z);
94
+ // Get an initial guess for Halley's method
95
+ if (k == 0) {
96
+ if (std::abs(z + EXPN1) < 0.3) {
97
+ w = detail::lambertw_branchpt(z);
98
+ } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 &&
99
+ -2.5 * std::abs(z.imag()) - 0.2 < z.real()) {
100
+ /* Empirically determined decision boundary where the Pade
101
+ * approximation is more accurate. */
102
+ w = detail::lambertw_pade0(z);
103
+ } else {
104
+ w = detail::lambertw_asy(z, k);
105
+ }
106
+ } else if (k == -1) {
107
+ if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) {
108
+ w = std::log(-z.real());
109
+ } else {
110
+ w = detail::lambertw_asy(z, k);
111
+ }
112
+ } else {
113
+ w = detail::lambertw_asy(z, k);
114
+ }
115
+
116
+ // Halley's method; see 5.9 in [1]
117
+ if (w.real() >= 0) {
118
+ // Rearrange the formula to avoid overflow in exp
119
+ for (int i = 0; i < 100; i++) {
120
+ ew = std::exp(-w);
121
+ wewz = w - z * ew;
122
+ wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0));
123
+ if (std::abs(wn - w) <= tol * std::abs(wn)) {
124
+ return wn;
125
+ }
126
+ w = wn;
127
+ }
128
+ } else {
129
+ for (int i = 0; i < 100; i++) {
130
+ ew = std::exp(w);
131
+ wew = w * ew;
132
+ wewz = wew - z;
133
+ wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0));
134
+ if (std::abs(wn - w) <= tol * std::abs(wn)) {
135
+ return wn;
136
+ }
137
+ w = wn;
138
+ }
139
+ }
140
+
141
+ set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag());
142
+ return {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()};
143
+ }
144
+
145
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/loggamma.h ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2024.
2
+ * Original header comment appears below.
3
+ */
4
+
5
+ /* An implementation of the principal branch of the logarithm of
6
+ * Gamma. Also contains implementations of Gamma and 1/Gamma which are
7
+ * easily computed from log-Gamma.
8
+ *
9
+ * Author: Josh Wilson
10
+ *
11
+ * Distributed under the same license as Scipy.
12
+ *
13
+ * References
14
+ * ----------
15
+ * [1] Hare, "Computing the Principal Branch of log-Gamma",
16
+ * Journal of Algorithms, 1997.
17
+ *
18
+ * [2] Julia,
19
+ * https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl
20
+ */
21
+
22
+ #pragma once
23
+
24
+ #include "cephes/gamma.h"
25
+ #include "config.h"
26
+ #include "error.h"
27
+ #include "evalpoly.h"
28
+ #include "trig.h"
29
+ #include "zlog1.h"
30
+
31
+ namespace special {
32
+
33
+ namespace detail {
34
+ constexpr double loggamma_SMALLX = 7;
35
+ constexpr double loggamma_SMALLY = 7;
36
+ constexpr double loggamma_HLOG2PI = 0.918938533204672742; // log(2*pi)/2
37
+ constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi)
38
+ constexpr double loggamma_TAYLOR_RADIUS = 0.2;
39
+
40
+ SPECFUN_HOST_DEVICE std::complex<double> loggamma_stirling(std::complex<double> z) {
41
+ /* Stirling series for log-Gamma
42
+ *
43
+ * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the
44
+ * (2*n)th Bernoulli number. See (1.1) in [1].
45
+ */
46
+ double coeffs[] = {-2.955065359477124183E-2, 6.4102564102564102564E-3, -1.9175269175269175269E-3,
47
+ 8.4175084175084175084E-4, -5.952380952380952381E-4, 7.9365079365079365079E-4,
48
+ -2.7777777777777777778E-3, 8.3333333333333333333E-2};
49
+ std::complex<double> rz = 1.0 / z;
50
+ std::complex<double> rzz = rz / z;
51
+
52
+ return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz);
53
+ }
54
+
55
+ SPECFUN_HOST_DEVICE std::complex<double> loggamma_recurrence(std::complex<double> z) {
56
+ /* Backward recurrence relation.
57
+ *
58
+ * See Proposition 2.2 in [1] and the Julia implementation [2].
59
+ *
60
+ */
61
+ int signflips = 0;
62
+ int sb = 0;
63
+ std::complex<double> shiftprod = z;
64
+
65
+ z += 1.0;
66
+ int nsb;
67
+ while (z.real() <= loggamma_SMALLX) {
68
+ shiftprod *= z;
69
+ nsb = std::signbit(shiftprod.imag());
70
+ signflips += nsb != 0 && sb == 0 ? 1 : 0;
71
+ sb = nsb;
72
+ z += 1.0;
73
+ }
74
+ return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex<double>(0, 1);
75
+ }
76
+
77
+ SPECFUN_HOST_DEVICE std::complex<double> loggamma_taylor(std::complex<double> z) {
78
+ /* Taylor series for log-Gamma around z = 1.
79
+ *
80
+ * It is
81
+ *
82
+ * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ...
83
+ *
84
+ * where gamma is the Euler-Mascheroni constant.
85
+ */
86
+
87
+ double coeffs[] = {
88
+ -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2,
89
+ -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2,
90
+ -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2,
91
+ -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1,
92
+ -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1,
93
+ -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1};
94
+
95
+ z -= 1.0;
96
+ return z * cevalpoly(coeffs, 22, z);
97
+ }
98
+ } // namespace detail
99
+
100
+ SPECFUN_HOST_DEVICE inline double loggamma(double x) {
101
+ if (x < 0.0) {
102
+ return std::numeric_limits<double>::quiet_NaN();
103
+ }
104
+ return cephes::lgam(x);
105
+ }
106
+
107
+ SPECFUN_HOST_DEVICE inline std::complex<double> loggamma(std::complex<double> z) {
108
+ // Compute the principal branch of log-Gamma
109
+
110
+ if (std::isnan(z.real()) || std::isnan(z.imag())) {
111
+ return {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()};
112
+ }
113
+ if (z.real() <= 0 and z == std::floor(z.real())) {
114
+ set_error("loggamma", SF_ERROR_SINGULAR, NULL);
115
+ return {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()};
116
+ }
117
+ if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) {
118
+ return detail::loggamma_stirling(z);
119
+ }
120
+ if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) {
121
+ return detail::loggamma_taylor(z);
122
+ }
123
+ if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) {
124
+ // Recurrence relation and the Taylor series around 1.
125
+ return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0);
126
+ }
127
+ if (z.real() < 0.1) {
128
+ // Reflection formula; see Proposition 3.1 in [1]
129
+ double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25);
130
+ return std::complex<double>(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z);
131
+ }
132
+ if (std::signbit(z.imag()) == 0) {
133
+ // z.imag() >= 0 but is not -0.0
134
+ return detail::loggamma_recurrence(z);
135
+ }
136
+ return std::conj(detail::loggamma_recurrence(std::conj(z)));
137
+ }
138
+
139
+ SPECFUN_HOST_DEVICE inline std::complex<double> gamma(std::complex<double> z) {
140
+ // Compute Gamma(z) using loggamma.
141
+ if (z.real() <= 0 && z == std::floor(z.real())) {
142
+ // Poles
143
+ set_error("gamma", SF_ERROR_SINGULAR, NULL);
144
+ return {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN()};
145
+ }
146
+ return std::exp(loggamma(z));
147
+ }
148
+
149
+ SPECFUN_HOST_DEVICE inline std::complex<double> rgamma(std::complex<double> z) {
150
+ // Compute 1/Gamma(z) using loggamma.
151
+ if (z.real() <= 0 && z == std::floor(z.real())) {
152
+ // Zeros at 0, -1, -2, ...
153
+ return 0.0;
154
+ }
155
+ return std::exp(-loggamma(z));
156
+ }
157
+
158
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/trig.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2023.
2
+ *
3
+ * Original author: Josh Wilson, 2016.
4
+ */
5
+
6
+ /* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods
7
+ * of these functions are integral (and thus better representable in
8
+ * floating point), it's possible to compute them with greater accuracy
9
+ * than sin(z), cos(z).
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include "cephes/trig.h"
15
+ #include "config.h"
16
+ #include "evalpoly.h"
17
+
18
+ namespace special {
19
+
20
+ SPECFUN_HOST_DEVICE inline std::complex<double> sinpi(std::complex<double> z) {
21
+ double x = z.real();
22
+ double piy = M_PI * z.imag();
23
+ double abspiy = std::abs(piy);
24
+ double sinpix = cephes::sinpi(x);
25
+ double cospix = cephes::cospi(x);
26
+
27
+ if (abspiy < 700) {
28
+ return {sinpix * std::cosh(piy), cospix * std::sinh(piy)};
29
+ }
30
+
31
+ /* Have to be careful--sinh/cosh could overflow while cos/sin are small.
32
+ * At this large of values
33
+ *
34
+ * cosh(y) ~ exp(y)/2
35
+ * sinh(y) ~ sgn(y)*exp(y)/2
36
+ *
37
+ * so we can compute exp(y/2), scale by the right factor of sin/cos
38
+ * and then multiply by exp(y/2) to avoid overflow. */
39
+ double exphpiy = std::exp(abspiy / 2);
40
+ double coshfac;
41
+ double sinhfac;
42
+ if (exphpiy == std::numeric_limits<double>::infinity()) {
43
+ if (sinpix == 0.0) {
44
+ // Preserve the sign of zero.
45
+ coshfac = std::copysign(0.0, sinpix);
46
+ } else {
47
+ coshfac = std::copysign(std::numeric_limits<double>::infinity(), sinpix);
48
+ }
49
+ if (cospix == 0.0) {
50
+ // Preserve the sign of zero.
51
+ sinhfac = std::copysign(0.0, cospix);
52
+ } else {
53
+ sinhfac = std::copysign(std::numeric_limits<double>::infinity(), cospix);
54
+ }
55
+ return {coshfac, sinhfac};
56
+ }
57
+
58
+ coshfac = 0.5 * sinpix * exphpiy;
59
+ sinhfac = 0.5 * cospix * exphpiy;
60
+ return {coshfac * exphpiy, sinhfac * exphpiy};
61
+ }
62
+
63
+ SPECFUN_HOST_DEVICE inline std::complex<double> cospi(std::complex<double> z) {
64
+ double x = z.real();
65
+ double piy = M_PI * z.imag();
66
+ double abspiy = std::abs(piy);
67
+ double sinpix = cephes::sinpi(x);
68
+ double cospix = cephes::cospi(x);
69
+
70
+ if (abspiy < 700) {
71
+ return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)};
72
+ }
73
+
74
+ // See csinpi(z) for an idea of what's going on here.
75
+ double exphpiy = std::exp(abspiy / 2);
76
+ double coshfac;
77
+ double sinhfac;
78
+ if (exphpiy == std::numeric_limits<double>::infinity()) {
79
+ if (sinpix == 0.0) {
80
+ // Preserve the sign of zero.
81
+ coshfac = std::copysign(0.0, cospix);
82
+ } else {
83
+ coshfac = std::copysign(std::numeric_limits<double>::infinity(), cospix);
84
+ }
85
+ if (cospix == 0.0) {
86
+ // Preserve the sign of zero.
87
+ sinhfac = std::copysign(0.0, sinpix);
88
+ } else {
89
+ sinhfac = std::copysign(std::numeric_limits<double>::infinity(), sinpix);
90
+ }
91
+ return {coshfac, sinhfac};
92
+ }
93
+
94
+ coshfac = 0.5 * cospix * exphpiy;
95
+ sinhfac = 0.5 * sinpix * exphpiy;
96
+ return {coshfac * exphpiy, sinhfac * exphpiy};
97
+ }
98
+
99
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/special/zlog1.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Translated from Cython into C++ by SciPy developers in 2023.
2
+ *
3
+ * Original author: Josh Wilson, 2016.
4
+ */
5
+
6
+ #pragma once
7
+
8
+ #include "config.h"
9
+
10
+ namespace special {
11
+ namespace detail {
12
+
13
+ SPECFUN_HOST_DEVICE inline std::complex<double> zlog1(std::complex<double> z) {
14
+ /* Compute log, paying special attention to accuracy around 1. We
15
+ * implement this ourselves because some systems (most notably the
16
+ * Travis CI machines) are weak in this regime. */
17
+ std::complex<double> coeff = -1.0;
18
+ std::complex<double> res = 0.0;
19
+
20
+ if (std::abs(z - 1.0) > 0.1) {
21
+ return std::log(z);
22
+ }
23
+
24
+ z -= 1.0;
25
+ for (int n = 1; n < 17; n++) {
26
+ coeff *= -z;
27
+ res += coeff / static_cast<double>(n);
28
+ if (std::abs(res / coeff) < std::numeric_limits<double>::epsilon()) {
29
+ break;
30
+ }
31
+ }
32
+ return res;
33
+ }
34
+ } // namespace detail
35
+ } // namespace special
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdflib.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cdft_asymptotic.cpython-310.pyc ADDED
Binary file (1.34 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_cython_special.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_dd.cpython-310.pyc ADDED
Binary file (1.3 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_digamma.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
venv/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_erfinv.cpython-310.pyc ADDED
Binary file (2.41 kB). View file