applied-ai-018 commited on
Commit
e96cf4b
·
verified ·
1 Parent(s): 889b579

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. env-llmeval/lib/python3.10/site-packages/scipy/special/__init__.py +863 -0
  2. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/scipy/special/_add_newdocs.py +0 -0
  19. env-llmeval/lib/python3.10/site-packages/scipy/special/_basic.py +0 -0
  20. env-llmeval/lib/python3.10/site-packages/scipy/special/_cdflib.cpython-310-x86_64-linux-gnu.so +0 -0
  21. env-llmeval/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so +0 -0
  22. env-llmeval/lib/python3.10/site-packages/scipy/special/_ellip_harm.py +214 -0
  23. env-llmeval/lib/python3.10/site-packages/scipy/special/_logsumexp.py +307 -0
  24. env-llmeval/lib/python3.10/site-packages/scipy/special/_mptestutils.py +453 -0
  25. env-llmeval/lib/python3.10/site-packages/scipy/special/_orthogonal.py +2605 -0
  26. env-llmeval/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi +331 -0
  27. env-llmeval/lib/python3.10/site-packages/scipy/special/_sf_error.py +15 -0
  28. env-llmeval/lib/python3.10/site-packages/scipy/special/_specfun.cpython-310-x86_64-linux-gnu.so +0 -0
  29. env-llmeval/lib/python3.10/site-packages/scipy/special/_spfun_stats.py +106 -0
  30. env-llmeval/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py +354 -0
  31. env-llmeval/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py +75 -0
  32. env-llmeval/lib/python3.10/site-packages/scipy/special/_test_internal.cpython-310-x86_64-linux-gnu.so +0 -0
  33. env-llmeval/lib/python3.10/site-packages/scipy/special/_testutils.py +321 -0
  34. env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi +526 -0
  35. env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx +0 -0
  36. env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd +60 -0
  37. env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx +181 -0
  38. env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h +68 -0
  39. env-llmeval/lib/python3.10/site-packages/scipy/special/add_newdocs.py +15 -0
  40. env-llmeval/lib/python3.10/site-packages/scipy/special/basic.py +87 -0
  41. env-llmeval/lib/python3.10/site-packages/scipy/special/cython_special.pyi +3 -0
  42. env-llmeval/lib/python3.10/site-packages/scipy/special/cython_special.pyx +0 -0
  43. env-llmeval/lib/python3.10/site-packages/scipy/special/sf_error.py +20 -0
  44. env-llmeval/lib/python3.10/site-packages/scipy/special/specfun.py +43 -0
  45. env-llmeval/lib/python3.10/site-packages/scipy/special/spfun_stats.py +17 -0
  46. env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__init__.py +0 -0
  47. env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_basic.py +0 -0
  48. env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py +106 -0
  49. env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py +527 -0
  50. env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py +363 -0
env-llmeval/lib/python3.10/site-packages/scipy/special/__init__.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ========================================
3
+ Special functions (:mod:`scipy.special`)
4
+ ========================================
5
+
6
+ .. currentmodule:: scipy.special
7
+
8
+ Almost all of the functions below accept NumPy arrays as input
9
+ arguments as well as single numbers. This means they follow
10
+ broadcasting and automatic array-looping rules. Technically,
11
+ they are `NumPy universal functions
12
+ <https://numpy.org/doc/stable/user/basics.ufuncs.html#ufuncs-basics>`_.
13
+ Functions which do not accept NumPy arrays are marked by a warning
14
+ in the section description.
15
+
16
+ .. seealso::
17
+
18
+ `scipy.special.cython_special` -- Typed Cython versions of special functions
19
+
20
+
21
+ Error handling
22
+ ==============
23
+
24
+ Errors are handled by returning NaNs or other appropriate values.
25
+ Some of the special function routines can emit warnings or raise
26
+ exceptions when an error occurs. By default this is disabled; to
27
+ query and control the current error handling state the following
28
+ functions are provided.
29
+
30
+ .. autosummary::
31
+ :toctree: generated/
32
+
33
+ geterr -- Get the current way of handling special-function errors.
34
+ seterr -- Set how special-function errors are handled.
35
+ errstate -- Context manager for special-function error handling.
36
+ SpecialFunctionWarning -- Warning that can be emitted by special functions.
37
+ SpecialFunctionError -- Exception that can be raised by special functions.
38
+
39
+ Available functions
40
+ ===================
41
+
42
+ Airy functions
43
+ --------------
44
+
45
+ .. autosummary::
46
+ :toctree: generated/
47
+
48
+ airy -- Airy functions and their derivatives.
49
+ airye -- Exponentially scaled Airy functions and their derivatives.
50
+ ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative.
51
+ bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative.
52
+ itairy -- Integrals of Airy functions
53
+
54
+
55
+ Elliptic functions and integrals
56
+ --------------------------------
57
+
58
+ .. autosummary::
59
+ :toctree: generated/
60
+
61
+ ellipj -- Jacobian elliptic functions.
62
+ ellipk -- Complete elliptic integral of the first kind.
63
+ ellipkm1 -- Complete elliptic integral of the first kind around `m` = 1.
64
+ ellipkinc -- Incomplete elliptic integral of the first kind.
65
+ ellipe -- Complete elliptic integral of the second kind.
66
+ ellipeinc -- Incomplete elliptic integral of the second kind.
67
+ elliprc -- Degenerate symmetric integral RC.
68
+ elliprd -- Symmetric elliptic integral of the second kind.
69
+ elliprf -- Completely-symmetric elliptic integral of the first kind.
70
+ elliprg -- Completely-symmetric elliptic integral of the second kind.
71
+ elliprj -- Symmetric elliptic integral of the third kind.
72
+
73
+ Bessel functions
74
+ ----------------
75
+
76
+ .. autosummary::
77
+ :toctree: generated/
78
+
79
+ jv -- Bessel function of the first kind of real order and \
80
+ complex argument.
81
+ jve -- Exponentially scaled Bessel function of order `v`.
82
+ yn -- Bessel function of the second kind of integer order and \
83
+ real argument.
84
+ yv -- Bessel function of the second kind of real order and \
85
+ complex argument.
86
+ yve -- Exponentially scaled Bessel function of the second kind \
87
+ of real order.
88
+ kn -- Modified Bessel function of the second kind of integer \
89
+ order `n`
90
+ kv -- Modified Bessel function of the second kind of real order \
91
+ `v`
92
+ kve -- Exponentially scaled modified Bessel function of the \
93
+ second kind.
94
+ iv -- Modified Bessel function of the first kind of real order.
95
+ ive -- Exponentially scaled modified Bessel function of the \
96
+ first kind.
97
+ hankel1 -- Hankel function of the first kind.
98
+ hankel1e -- Exponentially scaled Hankel function of the first kind.
99
+ hankel2 -- Hankel function of the second kind.
100
+ hankel2e -- Exponentially scaled Hankel function of the second kind.
101
+ wright_bessel -- Wright's generalized Bessel function.
102
+
103
+ The following function does not accept NumPy arrays (it is not a
104
+ universal function):
105
+
106
+ .. autosummary::
107
+ :toctree: generated/
108
+
109
+ lmbda -- Jahnke-Emden Lambda function, Lambdav(x).
110
+
111
+ Zeros of Bessel functions
112
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
113
+
114
+ The following functions do not accept NumPy arrays (they are not
115
+ universal functions):
116
+
117
+ .. autosummary::
118
+ :toctree: generated/
119
+
120
+ jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'.
121
+ jnyn_zeros -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
122
+ jn_zeros -- Compute zeros of integer-order Bessel function Jn(x).
123
+ jnp_zeros -- Compute zeros of integer-order Bessel function derivative Jn'(x).
124
+ yn_zeros -- Compute zeros of integer-order Bessel function Yn(x).
125
+ ynp_zeros -- Compute zeros of integer-order Bessel function derivative Yn'(x).
126
+ y0_zeros -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
127
+ y1_zeros -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
128
+ y1p_zeros -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
129
+
130
+ Faster versions of common Bessel functions
131
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
132
+
133
+ .. autosummary::
134
+ :toctree: generated/
135
+
136
+ j0 -- Bessel function of the first kind of order 0.
137
+ j1 -- Bessel function of the first kind of order 1.
138
+ y0 -- Bessel function of the second kind of order 0.
139
+ y1 -- Bessel function of the second kind of order 1.
140
+ i0 -- Modified Bessel function of order 0.
141
+ i0e -- Exponentially scaled modified Bessel function of order 0.
142
+ i1 -- Modified Bessel function of order 1.
143
+ i1e -- Exponentially scaled modified Bessel function of order 1.
144
+ k0 -- Modified Bessel function of the second kind of order 0, :math:`K_0`.
145
+ k0e -- Exponentially scaled modified Bessel function K of order 0
146
+ k1 -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`.
147
+ k1e -- Exponentially scaled modified Bessel function K of order 1.
148
+
149
+ Integrals of Bessel functions
150
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151
+
152
+ .. autosummary::
153
+ :toctree: generated/
154
+
155
+ itj0y0 -- Integrals of Bessel functions of order 0.
156
+ it2j0y0 -- Integrals related to Bessel functions of order 0.
157
+ iti0k0 -- Integrals of modified Bessel functions of order 0.
158
+ it2i0k0 -- Integrals related to modified Bessel functions of order 0.
159
+ besselpoly -- Weighted integral of a Bessel function.
160
+
161
+ Derivatives of Bessel functions
162
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
163
+
164
+ .. autosummary::
165
+ :toctree: generated/
166
+
167
+ jvp -- Compute nth derivative of Bessel function Jv(z) with respect to `z`.
168
+ yvp -- Compute nth derivative of Bessel function Yv(z) with respect to `z`.
169
+ kvp -- Compute nth derivative of real-order modified Bessel function Kv(z)
170
+ ivp -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`.
171
+ h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`.
172
+ h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`.
173
+
174
+ Spherical Bessel functions
175
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
176
+
177
+ .. autosummary::
178
+ :toctree: generated/
179
+
180
+ spherical_jn -- Spherical Bessel function of the first kind or its derivative.
181
+ spherical_yn -- Spherical Bessel function of the second kind or its derivative.
182
+ spherical_in -- Modified spherical Bessel function of the first kind or its derivative.
183
+ spherical_kn -- Modified spherical Bessel function of the second kind or its derivative.
184
+
185
+ Riccati-Bessel functions
186
+ ^^^^^^^^^^^^^^^^^^^^^^^^
187
+
188
+ The following functions do not accept NumPy arrays (they are not
189
+ universal functions):
190
+
191
+ .. autosummary::
192
+ :toctree: generated/
193
+
194
+ riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative.
195
+ riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative.
196
+
197
+ Struve functions
198
+ ----------------
199
+
200
+ .. autosummary::
201
+ :toctree: generated/
202
+
203
+ struve -- Struve function.
204
+ modstruve -- Modified Struve function.
205
+ itstruve0 -- Integral of the Struve function of order 0.
206
+ it2struve0 -- Integral related to the Struve function of order 0.
207
+ itmodstruve0 -- Integral of the modified Struve function of order 0.
208
+
209
+
210
+ Raw statistical functions
211
+ -------------------------
212
+
213
+ .. seealso:: :mod:`scipy.stats`: Friendly versions of these functions.
214
+
215
+ Binomial distribution
216
+ ^^^^^^^^^^^^^^^^^^^^^
217
+
218
+ .. autosummary::
219
+ :toctree: generated/
220
+
221
+ bdtr -- Binomial distribution cumulative distribution function.
222
+ bdtrc -- Binomial distribution survival function.
223
+ bdtri -- Inverse function to `bdtr` with respect to `p`.
224
+ bdtrik -- Inverse function to `bdtr` with respect to `k`.
225
+ bdtrin -- Inverse function to `bdtr` with respect to `n`.
226
+
227
+ Beta distribution
228
+ ^^^^^^^^^^^^^^^^^
229
+
230
+ .. autosummary::
231
+ :toctree: generated/
232
+
233
+ btdtr -- Cumulative distribution function of the beta distribution.
234
+ btdtri -- The `p`-th quantile of the beta distribution.
235
+ btdtria -- Inverse of `btdtr` with respect to `a`.
236
+ btdtrib -- btdtria(a, p, x).
237
+
238
+ F distribution
239
+ ^^^^^^^^^^^^^^
240
+
241
+ .. autosummary::
242
+ :toctree: generated/
243
+
244
+ fdtr -- F cumulative distribution function.
245
+ fdtrc -- F survival function.
246
+ fdtri -- The `p`-th quantile of the F-distribution.
247
+ fdtridfd -- Inverse to `fdtr` vs dfd.
248
+
249
+ Gamma distribution
250
+ ^^^^^^^^^^^^^^^^^^
251
+
252
+ .. autosummary::
253
+ :toctree: generated/
254
+
255
+ gdtr -- Gamma distribution cumulative distribution function.
256
+ gdtrc -- Gamma distribution survival function.
257
+ gdtria -- Inverse of `gdtr` vs a.
258
+ gdtrib -- Inverse of `gdtr` vs b.
259
+ gdtrix -- Inverse of `gdtr` vs x.
260
+
261
+ Negative binomial distribution
262
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
263
+
264
+ .. autosummary::
265
+ :toctree: generated/
266
+
267
+ nbdtr -- Negative binomial cumulative distribution function.
268
+ nbdtrc -- Negative binomial survival function.
269
+ nbdtri -- Inverse of `nbdtr` vs `p`.
270
+ nbdtrik -- Inverse of `nbdtr` vs `k`.
271
+ nbdtrin -- Inverse of `nbdtr` vs `n`.
272
+
273
+ Noncentral F distribution
274
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
275
+
276
+ .. autosummary::
277
+ :toctree: generated/
278
+
279
+ ncfdtr -- Cumulative distribution function of the non-central F distribution.
280
+ ncfdtridfd -- Calculate degrees of freedom (denominator) for the noncentral F-distribution.
281
+ ncfdtridfn -- Calculate degrees of freedom (numerator) for the noncentral F-distribution.
282
+ ncfdtri -- Inverse cumulative distribution function of the non-central F distribution.
283
+ ncfdtrinc -- Calculate non-centrality parameter for non-central F distribution.
284
+
285
+ Noncentral t distribution
286
+ ^^^^^^^^^^^^^^^^^^^^^^^^^
287
+
288
+ .. autosummary::
289
+ :toctree: generated/
290
+
291
+ nctdtr -- Cumulative distribution function of the non-central `t` distribution.
292
+ nctdtridf -- Calculate degrees of freedom for non-central t distribution.
293
+ nctdtrit -- Inverse cumulative distribution function of the non-central t distribution.
294
+ nctdtrinc -- Calculate non-centrality parameter for non-central t distribution.
295
+
296
+ Normal distribution
297
+ ^^^^^^^^^^^^^^^^^^^
298
+
299
+ .. autosummary::
300
+ :toctree: generated/
301
+
302
+ nrdtrimn -- Calculate mean of normal distribution given other params.
303
+ nrdtrisd -- Calculate standard deviation of normal distribution given other params.
304
+ ndtr -- Normal cumulative distribution function.
305
+ log_ndtr -- Logarithm of normal cumulative distribution function.
306
+ ndtri -- Inverse of `ndtr` vs x.
307
+ ndtri_exp -- Inverse of `log_ndtr` vs x.
308
+
309
+ Poisson distribution
310
+ ^^^^^^^^^^^^^^^^^^^^
311
+
312
+ .. autosummary::
313
+ :toctree: generated/
314
+
315
+ pdtr -- Poisson cumulative distribution function.
316
+ pdtrc -- Poisson survival function.
317
+ pdtri -- Inverse to `pdtr` vs m.
318
+ pdtrik -- Inverse to `pdtr` vs k.
319
+
320
+ Student t distribution
321
+ ^^^^^^^^^^^^^^^^^^^^^^
322
+
323
+ .. autosummary::
324
+ :toctree: generated/
325
+
326
+ stdtr -- Student t distribution cumulative distribution function.
327
+ stdtridf -- Inverse of `stdtr` vs df.
328
+ stdtrit -- Inverse of `stdtr` vs `t`.
329
+
330
+ Chi square distribution
331
+ ^^^^^^^^^^^^^^^^^^^^^^^
332
+
333
+ .. autosummary::
334
+ :toctree: generated/
335
+
336
+ chdtr -- Chi square cumulative distribution function.
337
+ chdtrc -- Chi square survival function.
338
+ chdtri -- Inverse to `chdtrc`.
339
+ chdtriv -- Inverse to `chdtr` vs `v`.
340
+
341
+ Non-central chi square distribution
342
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
343
+
344
+ .. autosummary::
345
+ :toctree: generated/
346
+
347
+ chndtr -- Non-central chi square cumulative distribution function.
348
+ chndtridf -- Inverse to `chndtr` vs `df`.
349
+ chndtrinc -- Inverse to `chndtr` vs `nc`.
350
+ chndtrix -- Inverse to `chndtr` vs `x`.
351
+
352
+ Kolmogorov distribution
353
+ ^^^^^^^^^^^^^^^^^^^^^^^
354
+
355
+ .. autosummary::
356
+ :toctree: generated/
357
+
358
+ smirnov -- Kolmogorov-Smirnov complementary cumulative distribution function.
359
+ smirnovi -- Inverse to `smirnov`.
360
+ kolmogorov -- Complementary cumulative distribution function of Kolmogorov distribution.
361
+ kolmogi -- Inverse function to `kolmogorov`.
362
+
363
+ Box-Cox transformation
364
+ ^^^^^^^^^^^^^^^^^^^^^^
365
+
366
+ .. autosummary::
367
+ :toctree: generated/
368
+
369
+ boxcox -- Compute the Box-Cox transformation.
370
+ boxcox1p -- Compute the Box-Cox transformation of 1 + `x`.
371
+ inv_boxcox -- Compute the inverse of the Box-Cox transformation.
372
+ inv_boxcox1p -- Compute the inverse of the Box-Cox transformation.
373
+
374
+
375
+ Sigmoidal functions
376
+ ^^^^^^^^^^^^^^^^^^^
377
+
378
+ .. autosummary::
379
+ :toctree: generated/
380
+
381
+ logit -- Logit ufunc for ndarrays.
382
+ expit -- Logistic sigmoid function.
383
+ log_expit -- Logarithm of the logistic sigmoid function.
384
+
385
+ Miscellaneous
386
+ ^^^^^^^^^^^^^
387
+
388
+ .. autosummary::
389
+ :toctree: generated/
390
+
391
+ tklmbda -- Tukey-Lambda cumulative distribution function.
392
+ owens_t -- Owen's T Function.
393
+
394
+
395
+ Information Theory functions
396
+ ----------------------------
397
+
398
+ .. autosummary::
399
+ :toctree: generated/
400
+
401
+ entr -- Elementwise function for computing entropy.
402
+ rel_entr -- Elementwise function for computing relative entropy.
403
+ kl_div -- Elementwise function for computing Kullback-Leibler divergence.
404
+ huber -- Huber loss function.
405
+ pseudo_huber -- Pseudo-Huber loss function.
406
+
407
+
408
+ Gamma and related functions
409
+ ---------------------------
410
+
411
+ .. autosummary::
412
+ :toctree: generated/
413
+
414
+ gamma -- Gamma function.
415
+ gammaln -- Logarithm of the absolute value of the Gamma function for real inputs.
416
+ loggamma -- Principal branch of the logarithm of the Gamma function.
417
+ gammasgn -- Sign of the gamma function.
418
+ gammainc -- Regularized lower incomplete gamma function.
419
+ gammaincinv -- Inverse to `gammainc`.
420
+ gammaincc -- Regularized upper incomplete gamma function.
421
+ gammainccinv -- Inverse to `gammaincc`.
422
+ beta -- Beta function.
423
+ betaln -- Natural logarithm of absolute value of beta function.
424
+ betainc -- Incomplete beta integral.
425
+ betaincc -- Complemented incomplete beta integral.
426
+ betaincinv -- Inverse function to beta integral.
427
+ betainccinv -- Inverse of the complemented incomplete beta integral.
428
+ psi -- The digamma function.
429
+ rgamma -- Gamma function inverted.
430
+ polygamma -- Polygamma function n.
431
+ multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma.
432
+ digamma -- psi(x[, out]).
433
+ poch -- Rising factorial (z)_m.
434
+
435
+
436
+ Error function and Fresnel integrals
437
+ ------------------------------------
438
+
439
+ .. autosummary::
440
+ :toctree: generated/
441
+
442
+ erf -- Returns the error function of complex argument.
443
+ erfc -- Complementary error function, ``1 - erf(x)``.
444
+ erfcx -- Scaled complementary error function, ``exp(x**2) * erfc(x)``.
445
+ erfi -- Imaginary error function, ``-i erf(i z)``.
446
+ erfinv -- Inverse function for erf.
447
+ erfcinv -- Inverse function for erfc.
448
+ wofz -- Faddeeva function.
449
+ dawsn -- Dawson's integral.
450
+ fresnel -- Fresnel sin and cos integrals.
451
+ fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
452
+ modfresnelp -- Modified Fresnel positive integrals.
453
+ modfresnelm -- Modified Fresnel negative integrals.
454
+ voigt_profile -- Voigt profile.
455
+
456
+ The following functions do not accept NumPy arrays (they are not
457
+ universal functions):
458
+
459
+ .. autosummary::
460
+ :toctree: generated/
461
+
462
+ erf_zeros -- Compute nt complex zeros of error function erf(z).
463
+ fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z).
464
+ fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z).
465
+
466
+ Legendre functions
467
+ ------------------
468
+
469
+ .. autosummary::
470
+ :toctree: generated/
471
+
472
+ lpmv -- Associated Legendre function of integer order and real degree.
473
+ sph_harm -- Compute spherical harmonics.
474
+
475
+ The following functions do not accept NumPy arrays (they are not
476
+ universal functions):
477
+
478
+ .. autosummary::
479
+ :toctree: generated/
480
+
481
+ clpmn -- Associated Legendre function of the first kind for complex arguments.
482
+ lpn -- Legendre function of the first kind.
483
+ lqn -- Legendre function of the second kind.
484
+ lpmn -- Sequence of associated Legendre functions of the first kind.
485
+ lqmn -- Sequence of associated Legendre functions of the second kind.
486
+
487
+ Ellipsoidal harmonics
488
+ ---------------------
489
+
490
+ .. autosummary::
491
+ :toctree: generated/
492
+
493
+ ellip_harm -- Ellipsoidal harmonic functions E^p_n(l).
494
+ ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l).
495
+ ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n.
496
+
497
+ Orthogonal polynomials
498
+ ----------------------
499
+
500
+ The following functions evaluate values of orthogonal polynomials:
501
+
502
+ .. autosummary::
503
+ :toctree: generated/
504
+
505
+ assoc_laguerre -- Compute the generalized (associated) Laguerre polynomial of degree n and order k.
506
+ eval_legendre -- Evaluate Legendre polynomial at a point.
507
+ eval_chebyt -- Evaluate Chebyshev polynomial of the first kind at a point.
508
+ eval_chebyu -- Evaluate Chebyshev polynomial of the second kind at a point.
509
+ eval_chebyc -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point.
510
+ eval_chebys -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point.
511
+ eval_jacobi -- Evaluate Jacobi polynomial at a point.
512
+ eval_laguerre -- Evaluate Laguerre polynomial at a point.
513
+ eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point.
514
+ eval_hermite -- Evaluate physicist's Hermite polynomial at a point.
515
+ eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point.
516
+ eval_gegenbauer -- Evaluate Gegenbauer polynomial at a point.
517
+ eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point.
518
+ eval_sh_chebyt -- Evaluate shifted Chebyshev polynomial of the first kind at a point.
519
+ eval_sh_chebyu -- Evaluate shifted Chebyshev polynomial of the second kind at a point.
520
+ eval_sh_jacobi -- Evaluate shifted Jacobi polynomial at a point.
521
+
522
+ The following functions compute roots and quadrature weights for
523
+ orthogonal polynomials:
524
+
525
+ .. autosummary::
526
+ :toctree: generated/
527
+
528
+ roots_legendre -- Gauss-Legendre quadrature.
529
+ roots_chebyt -- Gauss-Chebyshev (first kind) quadrature.
530
+ roots_chebyu -- Gauss-Chebyshev (second kind) quadrature.
531
+ roots_chebyc -- Gauss-Chebyshev (first kind) quadrature.
532
+ roots_chebys -- Gauss-Chebyshev (second kind) quadrature.
533
+ roots_jacobi -- Gauss-Jacobi quadrature.
534
+ roots_laguerre -- Gauss-Laguerre quadrature.
535
+ roots_genlaguerre -- Gauss-generalized Laguerre quadrature.
536
+ roots_hermite -- Gauss-Hermite (physicst's) quadrature.
537
+ roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature.
538
+ roots_gegenbauer -- Gauss-Gegenbauer quadrature.
539
+ roots_sh_legendre -- Gauss-Legendre (shifted) quadrature.
540
+ roots_sh_chebyt -- Gauss-Chebyshev (first kind, shifted) quadrature.
541
+ roots_sh_chebyu -- Gauss-Chebyshev (second kind, shifted) quadrature.
542
+ roots_sh_jacobi -- Gauss-Jacobi (shifted) quadrature.
543
+
544
+ The functions below, in turn, return the polynomial coefficients in
545
+ ``orthopoly1d`` objects, which function similarly as `numpy.poly1d`.
546
+ The ``orthopoly1d`` class also has an attribute ``weights``, which returns
547
+ the roots, weights, and total weights for the appropriate form of Gaussian
548
+ quadrature. These are returned in an ``n x 3`` array with roots in the first
549
+ column, weights in the second column, and total weights in the final column.
550
+ Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing
551
+ arithmetic, and lose information of the original orthogonal polynomial.
552
+
553
+ .. autosummary::
554
+ :toctree: generated/
555
+
556
+ legendre -- Legendre polynomial.
557
+ chebyt -- Chebyshev polynomial of the first kind.
558
+ chebyu -- Chebyshev polynomial of the second kind.
559
+ chebyc -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
560
+ chebys -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
561
+ jacobi -- Jacobi polynomial.
562
+ laguerre -- Laguerre polynomial.
563
+ genlaguerre -- Generalized (associated) Laguerre polynomial.
564
+ hermite -- Physicist's Hermite polynomial.
565
+ hermitenorm -- Normalized (probabilist's) Hermite polynomial.
566
+ gegenbauer -- Gegenbauer (ultraspherical) polynomial.
567
+ sh_legendre -- Shifted Legendre polynomial.
568
+ sh_chebyt -- Shifted Chebyshev polynomial of the first kind.
569
+ sh_chebyu -- Shifted Chebyshev polynomial of the second kind.
570
+ sh_jacobi -- Shifted Jacobi polynomial.
571
+
572
+ .. warning::
573
+
574
+ Computing values of high-order polynomials (around ``order > 20``) using
575
+ polynomial coefficients is numerically unstable. To evaluate polynomial
576
+ values, the ``eval_*`` functions should be used instead.
577
+
578
+
579
+ Hypergeometric functions
580
+ ------------------------
581
+
582
+ .. autosummary::
583
+ :toctree: generated/
584
+
585
+ hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z).
586
+ hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x).
587
+ hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind.
588
+ hyp0f1 -- Confluent hypergeometric limit function 0F1.
589
+
590
+
591
+ Parabolic cylinder functions
592
+ ----------------------------
593
+
594
+ .. autosummary::
595
+ :toctree: generated/
596
+
597
+ pbdv -- Parabolic cylinder function D.
598
+ pbvv -- Parabolic cylinder function V.
599
+ pbwa -- Parabolic cylinder function W.
600
+
601
+ The following functions do not accept NumPy arrays (they are not
602
+ universal functions):
603
+
604
+ .. autosummary::
605
+ :toctree: generated/
606
+
607
+ pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives.
608
+ pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives.
609
+ pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives.
610
+
611
+ Mathieu and related functions
612
+ -----------------------------
613
+
614
+ .. autosummary::
615
+ :toctree: generated/
616
+
617
+ mathieu_a -- Characteristic value of even Mathieu functions.
618
+ mathieu_b -- Characteristic value of odd Mathieu functions.
619
+
620
+ The following functions do not accept NumPy arrays (they are not
621
+ universal functions):
622
+
623
+ .. autosummary::
624
+ :toctree: generated/
625
+
626
+ mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
627
+ mathieu_odd_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
628
+
629
+ The following return both function and first derivative:
630
+
631
+ .. autosummary::
632
+ :toctree: generated/
633
+
634
+ mathieu_cem -- Even Mathieu function and its derivative.
635
+ mathieu_sem -- Odd Mathieu function and its derivative.
636
+ mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative.
637
+ mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative.
638
+ mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative.
639
+ mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative.
640
+
641
+ Spheroidal wave functions
642
+ -------------------------
643
+
644
+ .. autosummary::
645
+ :toctree: generated/
646
+
647
+ pro_ang1 -- Prolate spheroidal angular function of the first kind and its derivative.
648
+ pro_rad1 -- Prolate spheroidal radial function of the first kind and its derivative.
649
+ pro_rad2 -- Prolate spheroidal radial function of the second kind and its derivative.
650
+ obl_ang1 -- Oblate spheroidal angular function of the first kind and its derivative.
651
+ obl_rad1 -- Oblate spheroidal radial function of the first kind and its derivative.
652
+ obl_rad2 -- Oblate spheroidal radial function of the second kind and its derivative.
653
+ pro_cv -- Characteristic value of prolate spheroidal function.
654
+ obl_cv -- Characteristic value of oblate spheroidal function.
655
+ pro_cv_seq -- Characteristic values for prolate spheroidal wave functions.
656
+ obl_cv_seq -- Characteristic values for oblate spheroidal wave functions.
657
+
658
+ The following functions require pre-computed characteristic value:
659
+
660
+ .. autosummary::
661
+ :toctree: generated/
662
+
663
+ pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value.
664
+ pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value.
665
+ pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value.
666
+ obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value.
667
+ obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value.
668
+ obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value.
669
+
670
+ Kelvin functions
671
+ ----------------
672
+
673
+ .. autosummary::
674
+ :toctree: generated/
675
+
676
+ kelvin -- Kelvin functions as complex numbers.
677
+ kelvin_zeros -- Compute nt zeros of all Kelvin functions.
678
+ ber -- Kelvin function ber.
679
+ bei -- Kelvin function bei
680
+ berp -- Derivative of the Kelvin function `ber`.
681
+ beip -- Derivative of the Kelvin function `bei`.
682
+ ker -- Kelvin function ker.
683
+ kei -- Kelvin function ker.
684
+ kerp -- Derivative of the Kelvin function ker.
685
+ keip -- Derivative of the Kelvin function kei.
686
+
687
+ The following functions do not accept NumPy arrays (they are not
688
+ universal functions):
689
+
690
+ .. autosummary::
691
+ :toctree: generated/
692
+
693
+ ber_zeros -- Compute nt zeros of the Kelvin function ber(x).
694
+ bei_zeros -- Compute nt zeros of the Kelvin function bei(x).
695
+ berp_zeros -- Compute nt zeros of the Kelvin function ber'(x).
696
+ beip_zeros -- Compute nt zeros of the Kelvin function bei'(x).
697
+ ker_zeros -- Compute nt zeros of the Kelvin function ker(x).
698
+ kei_zeros -- Compute nt zeros of the Kelvin function kei(x).
699
+ kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x).
700
+ keip_zeros -- Compute nt zeros of the Kelvin function kei'(x).
701
+
702
+ Combinatorics
703
+ -------------
704
+
705
+ .. autosummary::
706
+ :toctree: generated/
707
+
708
+ comb -- The number of combinations of N things taken k at a time.
709
+ perm -- Permutations of N things taken k at a time, i.e., k-permutations of N.
710
+ stirling2 -- Stirling numbers of the second kind.
711
+
712
+ Lambert W and related functions
713
+ -------------------------------
714
+
715
+ .. autosummary::
716
+ :toctree: generated/
717
+
718
+ lambertw -- Lambert W function.
719
+ wrightomega -- Wright Omega function.
720
+
721
+ Other special functions
722
+ -----------------------
723
+
724
+ .. autosummary::
725
+ :toctree: generated/
726
+
727
+ agm -- Arithmetic, Geometric Mean.
728
+ bernoulli -- Bernoulli numbers B0..Bn (inclusive).
729
+ binom -- Binomial coefficient
730
+ diric -- Periodic sinc function, also called the Dirichlet function.
731
+ euler -- Euler numbers E0..En (inclusive).
732
+ expn -- Exponential integral E_n.
733
+ exp1 -- Exponential integral E_1 of complex argument z.
734
+ expi -- Exponential integral Ei.
735
+ factorial -- The factorial of a number or array of numbers.
736
+ factorial2 -- Double factorial.
737
+ factorialk -- Multifactorial of n of order k, n(!!...!).
738
+ shichi -- Hyperbolic sine and cosine integrals.
739
+ sici -- Sine and cosine integrals.
740
+ softmax -- Softmax function.
741
+ log_softmax -- Logarithm of softmax function.
742
+ spence -- Spence's function, also known as the dilogarithm.
743
+ zeta -- Riemann zeta function.
744
+ zetac -- Riemann zeta function minus 1.
745
+
746
+ Convenience functions
747
+ ---------------------
748
+
749
+ .. autosummary::
750
+ :toctree: generated/
751
+
752
+ cbrt -- Cube root of `x`.
753
+ exp10 -- 10**x.
754
+ exp2 -- 2**x.
755
+ radian -- Convert from degrees to radians.
756
+ cosdg -- Cosine of the angle `x` given in degrees.
757
+ sindg -- Sine of angle given in degrees.
758
+ tandg -- Tangent of angle x given in degrees.
759
+ cotdg -- Cotangent of the angle `x` given in degrees.
760
+ log1p -- Calculates log(1+x) for use when `x` is near zero.
761
+ expm1 -- ``exp(x) - 1`` for use when `x` is near zero.
762
+ cosm1 -- ``cos(x) - 1`` for use when `x` is near zero.
763
+ powm1 -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1.
764
+ round -- Round to nearest integer.
765
+ xlogy -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
766
+ xlog1py -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
767
+ logsumexp -- Compute the log of the sum of exponentials of input elements.
768
+ exprel -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero.
769
+ sinc -- Return the sinc function.
770
+
771
+ """ # noqa: E501
772
+
773
+ import warnings
774
+
775
+ from ._sf_error import SpecialFunctionWarning, SpecialFunctionError
776
+
777
+ from . import _ufuncs
778
+ from ._ufuncs import *
779
+
780
+ # Replace some function definitions from _ufuncs to add Array API support
781
+ from ._support_alternative_backends import (
782
+ log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e,
783
+ gammaln, gammainc, gammaincc, logit, expit)
784
+
785
+ from . import _basic
786
+ from ._basic import *
787
+
788
+ from ._logsumexp import logsumexp, softmax, log_softmax
789
+
790
+ from . import _orthogonal
791
+ from ._orthogonal import *
792
+
793
+ from ._spfun_stats import multigammaln
794
+ from ._ellip_harm import (
795
+ ellip_harm,
796
+ ellip_harm_2,
797
+ ellip_normal
798
+ )
799
+ from ._lambertw import lambertw
800
+ from ._spherical_bessel import (
801
+ spherical_jn,
802
+ spherical_yn,
803
+ spherical_in,
804
+ spherical_kn
805
+ )
806
+
807
+ # Deprecated namespaces, to be removed in v2.0.0
808
+ from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats
809
+
810
+ # We replace some function definitions from _ufuncs with those from
811
+ # _support_alternative_backends above, but those are all listed in _ufuncs.__all__,
812
+ # so there is no need to consider _support_alternative_backends.__all__ here.
813
+ __all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__
814
+ __all__ += [
815
+ 'SpecialFunctionWarning',
816
+ 'SpecialFunctionError',
817
+ 'logsumexp',
818
+ 'softmax',
819
+ 'log_softmax',
820
+ 'multigammaln',
821
+ 'ellip_harm',
822
+ 'ellip_harm_2',
823
+ 'ellip_normal',
824
+ 'lambertw',
825
+ 'spherical_jn',
826
+ 'spherical_yn',
827
+ 'spherical_in',
828
+ 'spherical_kn',
829
+ ]
830
+
831
+ from scipy._lib._testutils import PytestTester
832
+ test = PytestTester(__name__)
833
+ del PytestTester
834
+
835
+ _depr_msg = ('\nThis function was deprecated in SciPy 1.12.0, and will be '
836
+ 'removed in SciPy 1.14.0. Use scipy.special.{} instead.')
837
+
838
+
839
+ def btdtr(*args, **kwargs): # type: ignore [no-redef]
840
+ warnings.warn(_depr_msg.format('betainc'), category=DeprecationWarning,
841
+ stacklevel=2)
842
+ return _ufuncs.btdtr(*args, **kwargs)
843
+
844
+
845
+ btdtr.__doc__ = _ufuncs.btdtr.__doc__ # type: ignore [misc]
846
+
847
+
848
+ def btdtri(*args, **kwargs): # type: ignore [no-redef]
849
+ warnings.warn(_depr_msg.format('betaincinv'), category=DeprecationWarning,
850
+ stacklevel=2)
851
+ return _ufuncs.btdtri(*args, **kwargs)
852
+
853
+
854
+ btdtri.__doc__ = _ufuncs.btdtri.__doc__ # type: ignore [misc]
855
+
856
+
857
+ def _get_include():
858
+ """This function is for development purposes only.
859
+
860
+ This function could disappear or its behavior could change at any time.
861
+ """
862
+ import os
863
+ return os.path.dirname(__file__)
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (31.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-310.pyc ADDED
Binary file (396 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc ADDED
Binary file (95.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc ADDED
Binary file (8.62 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_mptestutils.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc ADDED
Binary file (74.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc ADDED
Binary file (759 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/_testutils.cpython-310.pyc ADDED
Binary file (8.57 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc ADDED
Binary file (1.25 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc ADDED
Binary file (645 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc ADDED
Binary file (757 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_add_newdocs.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_basic.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_cdflib.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (188 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (63.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_ellip_harm.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ._ufuncs import _ellip_harm
4
+ from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
5
+
6
+
7
+ def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
8
+ r"""
9
+ Ellipsoidal harmonic functions E^p_n(l)
10
+
11
+ These are also known as Lame functions of the first kind, and are
12
+ solutions to the Lame equation:
13
+
14
+ .. math:: (s^2 - h^2)(s^2 - k^2)E''(s)
15
+ + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
16
+
17
+ where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
18
+ returned) corresponding to the solutions.
19
+
20
+ Parameters
21
+ ----------
22
+ h2 : float
23
+ ``h**2``
24
+ k2 : float
25
+ ``k**2``; should be larger than ``h**2``
26
+ n : int
27
+ Degree
28
+ s : float
29
+ Coordinate
30
+ p : int
31
+ Order, can range between [1,2n+1]
32
+ signm : {1, -1}, optional
33
+ Sign of prefactor of functions. Can be +/-1. See Notes.
34
+ signn : {1, -1}, optional
35
+ Sign of prefactor of functions. Can be +/-1. See Notes.
36
+
37
+ Returns
38
+ -------
39
+ E : float
40
+ the harmonic :math:`E^p_n(s)`
41
+
42
+ See Also
43
+ --------
44
+ ellip_harm_2, ellip_normal
45
+
46
+ Notes
47
+ -----
48
+ The geometric interpretation of the ellipsoidal functions is
49
+ explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
50
+ sign of prefactors for functions according to their type::
51
+
52
+ K : +1
53
+ L : signm
54
+ M : signn
55
+ N : signm*signn
56
+
57
+ .. versionadded:: 0.15.0
58
+
59
+ References
60
+ ----------
61
+ .. [1] Digital Library of Mathematical Functions 29.12
62
+ https://dlmf.nist.gov/29.12
63
+ .. [2] Bardhan and Knepley, "Computational science and
64
+ re-discovery: open-source implementations of
65
+ ellipsoidal harmonics for problems in potential theory",
66
+ Comput. Sci. Disc. 5, 014006 (2012)
67
+ :doi:`10.1088/1749-4699/5/1/014006`.
68
+ .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
69
+ Gravity Field Harmonics for small solar system bodies"
70
+ pp. 30-36, 2000
71
+ .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
72
+ pp. 418, 2012
73
+
74
+ Examples
75
+ --------
76
+ >>> from scipy.special import ellip_harm
77
+ >>> w = ellip_harm(5,8,1,1,2.5)
78
+ >>> w
79
+ 2.5
80
+
81
+ Check that the functions indeed are solutions to the Lame equation:
82
+
83
+ >>> import numpy as np
84
+ >>> from scipy.interpolate import UnivariateSpline
85
+ >>> def eigenvalue(f, df, ddf):
86
+ ... r = (((s**2 - h**2) * (s**2 - k**2) * ddf
87
+ ... + s * (2*s**2 - h**2 - k**2) * df
88
+ ... - n * (n + 1)*s**2*f) / f)
89
+ ... return -r.mean(), r.std()
90
+ >>> s = np.linspace(0.1, 10, 200)
91
+ >>> k, h, n, p = 8.0, 2.2, 3, 2
92
+ >>> E = ellip_harm(h**2, k**2, n, p, s)
93
+ >>> E_spl = UnivariateSpline(s, E)
94
+ >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
95
+ >>> a, a_err
96
+ (583.44366156701483, 6.4580890640310646e-11)
97
+
98
+ """ # noqa: E501
99
+ return _ellip_harm(h2, k2, n, p, s, signm, signn)
100
+
101
+
102
+ _ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
103
+
104
+
105
+ def ellip_harm_2(h2, k2, n, p, s):
106
+ r"""
107
+ Ellipsoidal harmonic functions F^p_n(l)
108
+
109
+ These are also known as Lame functions of the second kind, and are
110
+ solutions to the Lame equation:
111
+
112
+ .. math:: (s^2 - h^2)(s^2 - k^2)F''(s)
113
+ + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
114
+
115
+ where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
116
+ returned) corresponding to the solutions.
117
+
118
+ Parameters
119
+ ----------
120
+ h2 : float
121
+ ``h**2``
122
+ k2 : float
123
+ ``k**2``; should be larger than ``h**2``
124
+ n : int
125
+ Degree.
126
+ p : int
127
+ Order, can range between [1,2n+1].
128
+ s : float
129
+ Coordinate
130
+
131
+ Returns
132
+ -------
133
+ F : float
134
+ The harmonic :math:`F^p_n(s)`
135
+
136
+ See Also
137
+ --------
138
+ ellip_harm, ellip_normal
139
+
140
+ Notes
141
+ -----
142
+ Lame functions of the second kind are related to the functions of the first kind:
143
+
144
+ .. math::
145
+
146
+ F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}
147
+ \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
148
+
149
+ .. versionadded:: 0.15.0
150
+
151
+ Examples
152
+ --------
153
+ >>> from scipy.special import ellip_harm_2
154
+ >>> w = ellip_harm_2(5,8,2,1,10)
155
+ >>> w
156
+ 0.00108056853382
157
+
158
+ """
159
+ with np.errstate(all='ignore'):
160
+ return _ellip_harm_2_vec(h2, k2, n, p, s)
161
+
162
+
163
+ def _ellip_normal_vec(h2, k2, n, p):
164
+ return _ellipsoid_norm(h2, k2, n, p)
165
+
166
+
167
+ _ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
168
+
169
+
170
+ def ellip_normal(h2, k2, n, p):
171
+ r"""
172
+ Ellipsoidal harmonic normalization constants gamma^p_n
173
+
174
+ The normalization constant is defined as
175
+
176
+ .. math::
177
+
178
+ \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy
179
+ \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
180
+
181
+ Parameters
182
+ ----------
183
+ h2 : float
184
+ ``h**2``
185
+ k2 : float
186
+ ``k**2``; should be larger than ``h**2``
187
+ n : int
188
+ Degree.
189
+ p : int
190
+ Order, can range between [1,2n+1].
191
+
192
+ Returns
193
+ -------
194
+ gamma : float
195
+ The normalization constant :math:`\gamma^p_n`
196
+
197
+ See Also
198
+ --------
199
+ ellip_harm, ellip_harm_2
200
+
201
+ Notes
202
+ -----
203
+ .. versionadded:: 0.15.0
204
+
205
+ Examples
206
+ --------
207
+ >>> from scipy.special import ellip_normal
208
+ >>> w = ellip_normal(5,8,3,7)
209
+ >>> w
210
+ 1723.38796997
211
+
212
+ """
213
+ with np.errstate(all='ignore'):
214
+ return _ellip_normal_vec(h2, k2, n, p)
env-llmeval/lib/python3.10/site-packages/scipy/special/_logsumexp.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._util import _asarray_validated
3
+
4
+ __all__ = ["logsumexp", "softmax", "log_softmax"]
5
+
6
+
7
+ def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
8
+ """Compute the log of the sum of exponentials of input elements.
9
+
10
+ Parameters
11
+ ----------
12
+ a : array_like
13
+ Input array.
14
+ axis : None or int or tuple of ints, optional
15
+ Axis or axes over which the sum is taken. By default `axis` is None,
16
+ and all elements are summed.
17
+
18
+ .. versionadded:: 0.11.0
19
+ b : array-like, optional
20
+ Scaling factor for exp(`a`) must be of the same shape as `a` or
21
+ broadcastable to `a`. These values may be negative in order to
22
+ implement subtraction.
23
+
24
+ .. versionadded:: 0.12.0
25
+ keepdims : bool, optional
26
+ If this is set to True, the axes which are reduced are left in the
27
+ result as dimensions with size one. With this option, the result
28
+ will broadcast correctly against the original array.
29
+
30
+ .. versionadded:: 0.15.0
31
+ return_sign : bool, optional
32
+ If this is set to True, the result will be a pair containing sign
33
+ information; if False, results that are negative will be returned
34
+ as NaN. Default is False (no sign information).
35
+
36
+ .. versionadded:: 0.16.0
37
+
38
+ Returns
39
+ -------
40
+ res : ndarray
41
+ The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
42
+ more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
43
+ is returned. If ``return_sign`` is True, ``res`` contains the log of
44
+ the absolute value of the argument.
45
+ sgn : ndarray
46
+ If ``return_sign`` is True, this will be an array of floating-point
47
+ numbers matching res containing +1, 0, -1 (for real-valued inputs)
48
+ or a complex phase (for complex inputs). This gives the sign of the
49
+ argument of the logarithm in ``res``.
50
+ If ``return_sign`` is False, only one result is returned.
51
+
52
+ See Also
53
+ --------
54
+ numpy.logaddexp, numpy.logaddexp2
55
+
56
+ Notes
57
+ -----
58
+ NumPy has a logaddexp function which is very similar to `logsumexp`, but
59
+ only handles two arguments. `logaddexp.reduce` is similar to this
60
+ function, but may be less stable.
61
+
62
+ Examples
63
+ --------
64
+ >>> import numpy as np
65
+ >>> from scipy.special import logsumexp
66
+ >>> a = np.arange(10)
67
+ >>> logsumexp(a)
68
+ 9.4586297444267107
69
+ >>> np.log(np.sum(np.exp(a)))
70
+ 9.4586297444267107
71
+
72
+ With weights
73
+
74
+ >>> a = np.arange(10)
75
+ >>> b = np.arange(10, 0, -1)
76
+ >>> logsumexp(a, b=b)
77
+ 9.9170178533034665
78
+ >>> np.log(np.sum(b*np.exp(a)))
79
+ 9.9170178533034647
80
+
81
+ Returning a sign flag
82
+
83
+ >>> logsumexp([1,2],b=[1,-1],return_sign=True)
84
+ (1.5413248546129181, -1.0)
85
+
86
+ Notice that `logsumexp` does not directly support masked arrays. To use it
87
+ on a masked array, convert the mask into zero weights:
88
+
89
+ >>> a = np.ma.array([np.log(2), 2, np.log(3)],
90
+ ... mask=[False, True, False])
91
+ >>> b = (~a.mask).astype(int)
92
+ >>> logsumexp(a.data, b=b), np.log(5)
93
+ 1.6094379124341005, 1.6094379124341005
94
+
95
+ """
96
+ a = _asarray_validated(a, check_finite=False)
97
+ if b is not None:
98
+ a, b = np.broadcast_arrays(a, b)
99
+ if np.any(b == 0):
100
+ a = a + 0. # promote to at least float
101
+ a[b == 0] = -np.inf
102
+
103
+ # Scale by real part for complex inputs, because this affects
104
+ # the magnitude of the exponential.
105
+ a_max = np.amax(a.real, axis=axis, keepdims=True)
106
+
107
+ if a_max.ndim > 0:
108
+ a_max[~np.isfinite(a_max)] = 0
109
+ elif not np.isfinite(a_max):
110
+ a_max = 0
111
+
112
+ if b is not None:
113
+ b = np.asarray(b)
114
+ tmp = b * np.exp(a - a_max)
115
+ else:
116
+ tmp = np.exp(a - a_max)
117
+
118
+ # suppress warnings about log of zero
119
+ with np.errstate(divide='ignore'):
120
+ s = np.sum(tmp, axis=axis, keepdims=keepdims)
121
+ if return_sign:
122
+ # For complex, use the numpy>=2.0 convention for sign.
123
+ if np.issubdtype(s.dtype, np.complexfloating):
124
+ sgn = s / np.where(s == 0, 1, abs(s))
125
+ else:
126
+ sgn = np.sign(s)
127
+ s = abs(s)
128
+ out = np.log(s)
129
+
130
+ if not keepdims:
131
+ a_max = np.squeeze(a_max, axis=axis)
132
+ out += a_max
133
+
134
+ if return_sign:
135
+ return out, sgn
136
+ else:
137
+ return out
138
+
139
+
140
+ def softmax(x, axis=None):
141
+ r"""Compute the softmax function.
142
+
143
+ The softmax function transforms each element of a collection by
144
+ computing the exponential of each element divided by the sum of the
145
+ exponentials of all the elements. That is, if `x` is a one-dimensional
146
+ numpy array::
147
+
148
+ softmax(x) = np.exp(x)/sum(np.exp(x))
149
+
150
+ Parameters
151
+ ----------
152
+ x : array_like
153
+ Input array.
154
+ axis : int or tuple of ints, optional
155
+ Axis to compute values along. Default is None and softmax will be
156
+ computed over the entire array `x`.
157
+
158
+ Returns
159
+ -------
160
+ s : ndarray
161
+ An array the same shape as `x`. The result will sum to 1 along the
162
+ specified axis.
163
+
164
+ Notes
165
+ -----
166
+ The formula for the softmax function :math:`\sigma(x)` for a vector
167
+ :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is
168
+
169
+ .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}
170
+
171
+ The `softmax` function is the gradient of `logsumexp`.
172
+
173
+ The implementation uses shifting to avoid overflow. See [1]_ for more
174
+ details.
175
+
176
+ .. versionadded:: 1.2.0
177
+
178
+ References
179
+ ----------
180
+ .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
181
+ log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
182
+ Vol.41(4), :doi:`10.1093/imanum/draa038`.
183
+
184
+ Examples
185
+ --------
186
+ >>> import numpy as np
187
+ >>> from scipy.special import softmax
188
+ >>> np.set_printoptions(precision=5)
189
+
190
+ >>> x = np.array([[1, 0.5, 0.2, 3],
191
+ ... [1, -1, 7, 3],
192
+ ... [2, 12, 13, 3]])
193
+ ...
194
+
195
+ Compute the softmax transformation over the entire array.
196
+
197
+ >>> m = softmax(x)
198
+ >>> m
199
+ array([[ 4.48309e-06, 2.71913e-06, 2.01438e-06, 3.31258e-05],
200
+ [ 4.48309e-06, 6.06720e-07, 1.80861e-03, 3.31258e-05],
201
+ [ 1.21863e-05, 2.68421e-01, 7.29644e-01, 3.31258e-05]])
202
+
203
+ >>> m.sum()
204
+ 1.0
205
+
206
+ Compute the softmax transformation along the first axis (i.e., the
207
+ columns).
208
+
209
+ >>> m = softmax(x, axis=0)
210
+
211
+ >>> m
212
+ array([[ 2.11942e-01, 1.01300e-05, 2.75394e-06, 3.33333e-01],
213
+ [ 2.11942e-01, 2.26030e-06, 2.47262e-03, 3.33333e-01],
214
+ [ 5.76117e-01, 9.99988e-01, 9.97525e-01, 3.33333e-01]])
215
+
216
+ >>> m.sum(axis=0)
217
+ array([ 1., 1., 1., 1.])
218
+
219
+ Compute the softmax transformation along the second axis (i.e., the rows).
220
+
221
+ >>> m = softmax(x, axis=1)
222
+ >>> m
223
+ array([[ 1.05877e-01, 6.42177e-02, 4.75736e-02, 7.82332e-01],
224
+ [ 2.42746e-03, 3.28521e-04, 9.79307e-01, 1.79366e-02],
225
+ [ 1.22094e-05, 2.68929e-01, 7.31025e-01, 3.31885e-05]])
226
+
227
+ >>> m.sum(axis=1)
228
+ array([ 1., 1., 1.])
229
+
230
+ """
231
+ x = _asarray_validated(x, check_finite=False)
232
+ x_max = np.amax(x, axis=axis, keepdims=True)
233
+ exp_x_shifted = np.exp(x - x_max)
234
+ return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
235
+
236
+
237
+ def log_softmax(x, axis=None):
238
+ r"""Compute the logarithm of the softmax function.
239
+
240
+ In principle::
241
+
242
+ log_softmax(x) = log(softmax(x))
243
+
244
+ but using a more accurate implementation.
245
+
246
+ Parameters
247
+ ----------
248
+ x : array_like
249
+ Input array.
250
+ axis : int or tuple of ints, optional
251
+ Axis to compute values along. Default is None and softmax will be
252
+ computed over the entire array `x`.
253
+
254
+ Returns
255
+ -------
256
+ s : ndarray or scalar
257
+ An array with the same shape as `x`. Exponential of the result will
258
+ sum to 1 along the specified axis. If `x` is a scalar, a scalar is
259
+ returned.
260
+
261
+ Notes
262
+ -----
263
+ `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
264
+ make `softmax` saturate (see examples below).
265
+
266
+ .. versionadded:: 1.5.0
267
+
268
+ Examples
269
+ --------
270
+ >>> import numpy as np
271
+ >>> from scipy.special import log_softmax
272
+ >>> from scipy.special import softmax
273
+ >>> np.set_printoptions(precision=5)
274
+
275
+ >>> x = np.array([1000.0, 1.0])
276
+
277
+ >>> y = log_softmax(x)
278
+ >>> y
279
+ array([ 0., -999.])
280
+
281
+ >>> with np.errstate(divide='ignore'):
282
+ ... y = np.log(softmax(x))
283
+ ...
284
+ >>> y
285
+ array([ 0., -inf])
286
+
287
+ """
288
+
289
+ x = _asarray_validated(x, check_finite=False)
290
+
291
+ x_max = np.amax(x, axis=axis, keepdims=True)
292
+
293
+ if x_max.ndim > 0:
294
+ x_max[~np.isfinite(x_max)] = 0
295
+ elif not np.isfinite(x_max):
296
+ x_max = 0
297
+
298
+ tmp = x - x_max
299
+ exp_tmp = np.exp(tmp)
300
+
301
+ # suppress warnings about log of zero
302
+ with np.errstate(divide='ignore'):
303
+ s = np.sum(exp_tmp, axis=axis, keepdims=True)
304
+ out = np.log(s)
305
+
306
+ out = tmp - out
307
+ return out
env-llmeval/lib/python3.10/site-packages/scipy/special/_mptestutils.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import time
4
+ from itertools import zip_longest
5
+
6
+ import numpy as np
7
+ from numpy.testing import assert_
8
+ import pytest
9
+
10
+ from scipy.special._testutils import assert_func_equal
11
+
12
+ try:
13
+ import mpmath
14
+ except ImportError:
15
+ pass
16
+
17
+
18
+ # ------------------------------------------------------------------------------
19
+ # Machinery for systematic tests with mpmath
20
+ # ------------------------------------------------------------------------------
21
+
22
+ class Arg:
23
+ """Generate a set of numbers on the real axis, concentrating on
24
+ 'interesting' regions and covering all orders of magnitude.
25
+
26
+ """
27
+
28
+ def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True):
29
+ if a > b:
30
+ raise ValueError("a should be less than or equal to b")
31
+ if a == -np.inf:
32
+ a = -0.5*np.finfo(float).max
33
+ if b == np.inf:
34
+ b = 0.5*np.finfo(float).max
35
+ self.a, self.b = a, b
36
+
37
+ self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b
38
+
39
+ def _positive_values(self, a, b, n):
40
+ if a < 0:
41
+ raise ValueError("a should be positive")
42
+
43
+ # Try to put half of the points into a linspace between a and
44
+ # 10 the other half in a logspace.
45
+ if n % 2 == 0:
46
+ nlogpts = n//2
47
+ nlinpts = nlogpts
48
+ else:
49
+ nlogpts = n//2
50
+ nlinpts = nlogpts + 1
51
+
52
+ if a >= 10:
53
+ # Outside of linspace range; just return a logspace.
54
+ pts = np.logspace(np.log10(a), np.log10(b), n)
55
+ elif a > 0 and b < 10:
56
+ # Outside of logspace range; just return a linspace
57
+ pts = np.linspace(a, b, n)
58
+ elif a > 0:
59
+ # Linspace between a and 10 and a logspace between 10 and
60
+ # b.
61
+ linpts = np.linspace(a, 10, nlinpts, endpoint=False)
62
+ logpts = np.logspace(1, np.log10(b), nlogpts)
63
+ pts = np.hstack((linpts, logpts))
64
+ elif a == 0 and b <= 10:
65
+ # Linspace between 0 and b and a logspace between 0 and
66
+ # the smallest positive point of the linspace
67
+ linpts = np.linspace(0, b, nlinpts)
68
+ if linpts.size > 1:
69
+ right = np.log10(linpts[1])
70
+ else:
71
+ right = -30
72
+ logpts = np.logspace(-30, right, nlogpts, endpoint=False)
73
+ pts = np.hstack((logpts, linpts))
74
+ else:
75
+ # Linspace between 0 and 10, logspace between 0 and the
76
+ # smallest positive point of the linspace, and a logspace
77
+ # between 10 and b.
78
+ if nlogpts % 2 == 0:
79
+ nlogpts1 = nlogpts//2
80
+ nlogpts2 = nlogpts1
81
+ else:
82
+ nlogpts1 = nlogpts//2
83
+ nlogpts2 = nlogpts1 + 1
84
+ linpts = np.linspace(0, 10, nlinpts, endpoint=False)
85
+ if linpts.size > 1:
86
+ right = np.log10(linpts[1])
87
+ else:
88
+ right = -30
89
+ logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False)
90
+ logpts2 = np.logspace(1, np.log10(b), nlogpts2)
91
+ pts = np.hstack((logpts1, linpts, logpts2))
92
+
93
+ return np.sort(pts)
94
+
95
+ def values(self, n):
96
+ """Return an array containing n numbers."""
97
+ a, b = self.a, self.b
98
+ if a == b:
99
+ return np.zeros(n)
100
+
101
+ if not self.inclusive_a:
102
+ n += 1
103
+ if not self.inclusive_b:
104
+ n += 1
105
+
106
+ if n % 2 == 0:
107
+ n1 = n//2
108
+ n2 = n1
109
+ else:
110
+ n1 = n//2
111
+ n2 = n1 + 1
112
+
113
+ if a >= 0:
114
+ pospts = self._positive_values(a, b, n)
115
+ negpts = []
116
+ elif b <= 0:
117
+ pospts = []
118
+ negpts = -self._positive_values(-b, -a, n)
119
+ else:
120
+ pospts = self._positive_values(0, b, n1)
121
+ negpts = -self._positive_values(0, -a, n2 + 1)
122
+ # Don't want to get zero twice
123
+ negpts = negpts[1:]
124
+ pts = np.hstack((negpts[::-1], pospts))
125
+
126
+ if not self.inclusive_a:
127
+ pts = pts[1:]
128
+ if not self.inclusive_b:
129
+ pts = pts[:-1]
130
+ return pts
131
+
132
+
133
+ class FixedArg:
134
+ def __init__(self, values):
135
+ self._values = np.asarray(values)
136
+
137
+ def values(self, n):
138
+ return self._values
139
+
140
+
141
+ class ComplexArg:
142
+ def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)):
143
+ self.real = Arg(a.real, b.real)
144
+ self.imag = Arg(a.imag, b.imag)
145
+
146
+ def values(self, n):
147
+ m = int(np.floor(np.sqrt(n)))
148
+ x = self.real.values(m)
149
+ y = self.imag.values(m + 1)
150
+ return (x[:,None] + 1j*y[None,:]).ravel()
151
+
152
+
153
+ class IntArg:
154
+ def __init__(self, a=-1000, b=1000):
155
+ self.a = a
156
+ self.b = b
157
+
158
+ def values(self, n):
159
+ v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int)
160
+ v2 = np.arange(-5, 5)
161
+ v = np.unique(np.r_[v1, v2])
162
+ v = v[(v >= self.a) & (v < self.b)]
163
+ return v
164
+
165
+
166
+ def get_args(argspec, n):
167
+ if isinstance(argspec, np.ndarray):
168
+ args = argspec.copy()
169
+ else:
170
+ nargs = len(argspec)
171
+ ms = np.asarray(
172
+ [1.5 if isinstance(spec, ComplexArg) else 1.0 for spec in argspec]
173
+ )
174
+ ms = (n**(ms/sum(ms))).astype(int) + 1
175
+
176
+ args = [spec.values(m) for spec, m in zip(argspec, ms)]
177
+ args = np.array(np.broadcast_arrays(*np.ix_(*args))).reshape(nargs, -1).T
178
+
179
+ return args
180
+
181
+
182
+ class MpmathData:
183
+ def __init__(self, scipy_func, mpmath_func, arg_spec, name=None,
184
+ dps=None, prec=None, n=None, rtol=1e-7, atol=1e-300,
185
+ ignore_inf_sign=False, distinguish_nan_and_inf=True,
186
+ nan_ok=True, param_filter=None):
187
+
188
+ # mpmath tests are really slow (see gh-6989). Use a small number of
189
+ # points by default, increase back to 5000 (old default) if XSLOW is
190
+ # set
191
+ if n is None:
192
+ try:
193
+ is_xslow = int(os.environ.get('SCIPY_XSLOW', '0'))
194
+ except ValueError:
195
+ is_xslow = False
196
+
197
+ n = 5000 if is_xslow else 500
198
+
199
+ self.scipy_func = scipy_func
200
+ self.mpmath_func = mpmath_func
201
+ self.arg_spec = arg_spec
202
+ self.dps = dps
203
+ self.prec = prec
204
+ self.n = n
205
+ self.rtol = rtol
206
+ self.atol = atol
207
+ self.ignore_inf_sign = ignore_inf_sign
208
+ self.nan_ok = nan_ok
209
+ if isinstance(self.arg_spec, np.ndarray):
210
+ self.is_complex = np.issubdtype(self.arg_spec.dtype, np.complexfloating)
211
+ else:
212
+ self.is_complex = any(
213
+ [isinstance(arg, ComplexArg) for arg in self.arg_spec]
214
+ )
215
+ self.ignore_inf_sign = ignore_inf_sign
216
+ self.distinguish_nan_and_inf = distinguish_nan_and_inf
217
+ if not name or name == '<lambda>':
218
+ name = getattr(scipy_func, '__name__', None)
219
+ if not name or name == '<lambda>':
220
+ name = getattr(mpmath_func, '__name__', None)
221
+ self.name = name
222
+ self.param_filter = param_filter
223
+
224
+ def check(self):
225
+ np.random.seed(1234)
226
+
227
+ # Generate values for the arguments
228
+ argarr = get_args(self.arg_spec, self.n)
229
+
230
+ # Check
231
+ old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
232
+ try:
233
+ if self.dps is not None:
234
+ dps_list = [self.dps]
235
+ else:
236
+ dps_list = [20]
237
+ if self.prec is not None:
238
+ mpmath.mp.prec = self.prec
239
+
240
+ # Proper casting of mpmath input and output types. Using
241
+ # native mpmath types as inputs gives improved precision
242
+ # in some cases.
243
+ if np.issubdtype(argarr.dtype, np.complexfloating):
244
+ pytype = mpc2complex
245
+
246
+ def mptype(x):
247
+ return mpmath.mpc(complex(x))
248
+ else:
249
+ def mptype(x):
250
+ return mpmath.mpf(float(x))
251
+
252
+ def pytype(x):
253
+ if abs(x.imag) > 1e-16*(1 + abs(x.real)):
254
+ return np.nan
255
+ else:
256
+ return mpf2float(x.real)
257
+
258
+ # Try out different dps until one (or none) works
259
+ for j, dps in enumerate(dps_list):
260
+ mpmath.mp.dps = dps
261
+
262
+ try:
263
+ assert_func_equal(
264
+ self.scipy_func,
265
+ lambda *a: pytype(self.mpmath_func(*map(mptype, a))),
266
+ argarr,
267
+ vectorized=False,
268
+ rtol=self.rtol,
269
+ atol=self.atol,
270
+ ignore_inf_sign=self.ignore_inf_sign,
271
+ distinguish_nan_and_inf=self.distinguish_nan_and_inf,
272
+ nan_ok=self.nan_ok,
273
+ param_filter=self.param_filter
274
+ )
275
+ break
276
+ except AssertionError:
277
+ if j >= len(dps_list)-1:
278
+ # reraise the Exception
279
+ tp, value, tb = sys.exc_info()
280
+ if value.__traceback__ is not tb:
281
+ raise value.with_traceback(tb)
282
+ raise value
283
+ finally:
284
+ mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
285
+
286
+ def __repr__(self):
287
+ if self.is_complex:
288
+ return f"<MpmathData: {self.name} (complex)>"
289
+ else:
290
+ return f"<MpmathData: {self.name}>"
291
+
292
+
293
+ def assert_mpmath_equal(*a, **kw):
294
+ d = MpmathData(*a, **kw)
295
+ d.check()
296
+
297
+
298
+ def nonfunctional_tooslow(func):
299
+ return pytest.mark.skip(
300
+ reason=" Test not yet functional (too slow), needs more work."
301
+ )(func)
302
+
303
+
304
+ # ------------------------------------------------------------------------------
305
+ # Tools for dealing with mpmath quirks
306
+ # ------------------------------------------------------------------------------
307
+
308
+ def mpf2float(x):
309
+ """
310
+ Convert an mpf to the nearest floating point number. Just using
311
+ float directly doesn't work because of results like this:
312
+
313
+ with mp.workdps(50):
314
+ float(mpf("0.99999999999999999")) = 0.9999999999999999
315
+
316
+ """
317
+ return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0))
318
+
319
+
320
+ def mpc2complex(x):
321
+ return complex(mpf2float(x.real), mpf2float(x.imag))
322
+
323
+
324
+ def trace_args(func):
325
+ def tofloat(x):
326
+ if isinstance(x, mpmath.mpc):
327
+ return complex(x)
328
+ else:
329
+ return float(x)
330
+
331
+ def wrap(*a, **kw):
332
+ sys.stderr.write(f"{tuple(map(tofloat, a))!r}: ")
333
+ sys.stderr.flush()
334
+ try:
335
+ r = func(*a, **kw)
336
+ sys.stderr.write("-> %r" % r)
337
+ finally:
338
+ sys.stderr.write("\n")
339
+ sys.stderr.flush()
340
+ return r
341
+ return wrap
342
+
343
+
344
+ try:
345
+ import signal
346
+ POSIX = ('setitimer' in dir(signal))
347
+ except ImportError:
348
+ POSIX = False
349
+
350
+
351
+ class TimeoutError(Exception):
352
+ pass
353
+
354
+
355
+ def time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True):
356
+ """
357
+ Decorator for setting a timeout for pure-Python functions.
358
+
359
+ If the function does not return within `timeout` seconds, the
360
+ value `return_val` is returned instead.
361
+
362
+ On POSIX this uses SIGALRM by default. On non-POSIX, settrace is
363
+ used. Do not use this with threads: the SIGALRM implementation
364
+ does probably not work well. The settrace implementation only
365
+ traces the current thread.
366
+
367
+ The settrace implementation slows down execution speed. Slowdown
368
+ by a factor around 10 is probably typical.
369
+ """
370
+ if POSIX and use_sigalrm:
371
+ def sigalrm_handler(signum, frame):
372
+ raise TimeoutError()
373
+
374
+ def deco(func):
375
+ def wrap(*a, **kw):
376
+ old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)
377
+ signal.setitimer(signal.ITIMER_REAL, timeout)
378
+ try:
379
+ return func(*a, **kw)
380
+ except TimeoutError:
381
+ return return_val
382
+ finally:
383
+ signal.setitimer(signal.ITIMER_REAL, 0)
384
+ signal.signal(signal.SIGALRM, old_handler)
385
+ return wrap
386
+ else:
387
+ def deco(func):
388
+ def wrap(*a, **kw):
389
+ start_time = time.time()
390
+
391
+ def trace(frame, event, arg):
392
+ if time.time() - start_time > timeout:
393
+ raise TimeoutError()
394
+ return trace
395
+ sys.settrace(trace)
396
+ try:
397
+ return func(*a, **kw)
398
+ except TimeoutError:
399
+ sys.settrace(None)
400
+ return return_val
401
+ finally:
402
+ sys.settrace(None)
403
+ return wrap
404
+ return deco
405
+
406
+
407
+ def exception_to_nan(func):
408
+ """Decorate function to return nan if it raises an exception"""
409
+ def wrap(*a, **kw):
410
+ try:
411
+ return func(*a, **kw)
412
+ except Exception:
413
+ return np.nan
414
+ return wrap
415
+
416
+
417
+ def inf_to_nan(func):
418
+ """Decorate function to return nan if it returns inf"""
419
+ def wrap(*a, **kw):
420
+ v = func(*a, **kw)
421
+ if not np.isfinite(v):
422
+ return np.nan
423
+ return v
424
+ return wrap
425
+
426
+
427
+ def mp_assert_allclose(res, std, atol=0, rtol=1e-17):
428
+ """
429
+ Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it
430
+ can be done to higher precision than double.
431
+ """
432
+ failures = []
433
+ for k, (resval, stdval) in enumerate(zip_longest(res, std)):
434
+ if resval is None or stdval is None:
435
+ raise ValueError('Lengths of inputs res and std are not equal.')
436
+ if mpmath.fabs(resval - stdval) > atol + rtol*mpmath.fabs(stdval):
437
+ failures.append((k, resval, stdval))
438
+
439
+ nfail = len(failures)
440
+ if nfail > 0:
441
+ ndigits = int(abs(np.log10(rtol)))
442
+ msg = [""]
443
+ msg.append(f"Bad results ({nfail} out of {k + 1}) for the following points:")
444
+ for k, resval, stdval in failures:
445
+ resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0)
446
+ stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0)
447
+ if stdval == 0:
448
+ rdiff = "inf"
449
+ else:
450
+ rdiff = mpmath.fabs((resval - stdval)/stdval)
451
+ rdiff = mpmath.nstr(rdiff, 3)
452
+ msg.append(f"{k}: {resrep} != {stdrep} (rdiff {rdiff})")
453
+ assert_(False, "\n".join(msg))
env-llmeval/lib/python3.10/site-packages/scipy/special/_orthogonal.py ADDED
@@ -0,0 +1,2605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of functions to find the weights and abscissas for
3
+ Gaussian Quadrature.
4
+
5
+ These calculations are done by finding the eigenvalues of a
6
+ tridiagonal matrix whose entries are dependent on the coefficients
7
+ in the recursion formula for the orthogonal polynomials with the
8
+ corresponding weighting function over the interval.
9
+
10
+ Many recursion relations for orthogonal polynomials are given:
11
+
12
+ .. math::
13
+
14
+ a1n f_{n+1} (x) = (a2n + a3n x ) f_n (x) - a4n f_{n-1} (x)
15
+
16
+ The recursion relation of interest is
17
+
18
+ .. math::
19
+
20
+ P_{n+1} (x) = (x - A_n) P_n (x) - B_n P_{n-1} (x)
21
+
22
+ where :math:`P` has a different normalization than :math:`f`.
23
+
24
+ The coefficients can be found as:
25
+
26
+ .. math::
27
+
28
+ A_n = -a2n / a3n
29
+ \\qquad
30
+ B_n = ( a4n / a3n \\sqrt{h_n-1 / h_n})^2
31
+
32
+ where
33
+
34
+ .. math::
35
+
36
+ h_n = \\int_a^b w(x) f_n(x)^2
37
+
38
+ assume:
39
+
40
+ .. math::
41
+
42
+ P_0 (x) = 1
43
+ \\qquad
44
+ P_{-1} (x) == 0
45
+
46
+ For the mathematical background, see [golub.welsch-1969-mathcomp]_ and
47
+ [abramowitz.stegun-1965]_.
48
+
49
+ References
50
+ ----------
51
+ .. [golub.welsch-1969-mathcomp]
52
+ Golub, Gene H, and John H Welsch. 1969. Calculation of Gauss
53
+ Quadrature Rules. *Mathematics of Computation* 23, 221-230+s1--s10.
54
+
55
+ .. [abramowitz.stegun-1965]
56
+ Abramowitz, Milton, and Irene A Stegun. (1965) *Handbook of
57
+ Mathematical Functions: with Formulas, Graphs, and Mathematical
58
+ Tables*. Gaithersburg, MD: National Bureau of Standards.
59
+ http://www.math.sfu.ca/~cbm/aands/
60
+
61
+ .. [townsend.trogdon.olver-2014]
62
+ Townsend, A. and Trogdon, T. and Olver, S. (2014)
63
+ *Fast computation of Gauss quadrature nodes and
64
+ weights on the whole real line*. :arXiv:`1410.5286`.
65
+
66
+ .. [townsend.trogdon.olver-2015]
67
+ Townsend, A. and Trogdon, T. and Olver, S. (2015)
68
+ *Fast computation of Gauss quadrature nodes and
69
+ weights on the whole real line*.
70
+ IMA Journal of Numerical Analysis
71
+ :doi:`10.1093/imanum/drv002`.
72
+ """
73
+ #
74
+ # Author: Travis Oliphant 2000
75
+ # Updated Sep. 2003 (fixed bugs --- tested to be accurate)
76
+
77
+ # SciPy imports.
78
+ import numpy as np
79
+ from numpy import (exp, inf, pi, sqrt, floor, sin, cos, around,
80
+ hstack, arccos, arange)
81
+ from scipy import linalg
82
+ from scipy.special import airy
83
+
84
+ # Local imports.
85
+ # There is no .pyi file for _specfun
86
+ from . import _specfun # type: ignore
87
+ from . import _ufuncs
88
+ _gam = _ufuncs.gamma
89
+
90
+ _polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
91
+ 'jacobi', 'laguerre', 'genlaguerre', 'hermite',
92
+ 'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
93
+ 'sh_chebyu', 'sh_jacobi']
94
+
95
+ # Correspondence between new and old names of root functions
96
+ _rootfuns_map = {'roots_legendre': 'p_roots',
97
+ 'roots_chebyt': 't_roots',
98
+ 'roots_chebyu': 'u_roots',
99
+ 'roots_chebyc': 'c_roots',
100
+ 'roots_chebys': 's_roots',
101
+ 'roots_jacobi': 'j_roots',
102
+ 'roots_laguerre': 'l_roots',
103
+ 'roots_genlaguerre': 'la_roots',
104
+ 'roots_hermite': 'h_roots',
105
+ 'roots_hermitenorm': 'he_roots',
106
+ 'roots_gegenbauer': 'cg_roots',
107
+ 'roots_sh_legendre': 'ps_roots',
108
+ 'roots_sh_chebyt': 'ts_roots',
109
+ 'roots_sh_chebyu': 'us_roots',
110
+ 'roots_sh_jacobi': 'js_roots'}
111
+
112
+ __all__ = _polyfuns + list(_rootfuns_map.keys())
113
+
114
+
115
+ class orthopoly1d(np.poly1d):
116
+
117
+ def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None,
118
+ limits=None, monic=False, eval_func=None):
119
+ equiv_weights = [weights[k] / wfunc(roots[k]) for
120
+ k in range(len(roots))]
121
+ mu = sqrt(hn)
122
+ if monic:
123
+ evf = eval_func
124
+ if evf:
125
+ knn = kn
126
+ def eval_func(x):
127
+ return evf(x) / knn
128
+ mu = mu / abs(kn)
129
+ kn = 1.0
130
+
131
+ # compute coefficients from roots, then scale
132
+ poly = np.poly1d(roots, r=True)
133
+ np.poly1d.__init__(self, poly.coeffs * float(kn))
134
+
135
+ self.weights = np.array(list(zip(roots, weights, equiv_weights)))
136
+ self.weight_func = wfunc
137
+ self.limits = limits
138
+ self.normcoef = mu
139
+
140
+ # Note: eval_func will be discarded on arithmetic
141
+ self._eval_func = eval_func
142
+
143
+ def __call__(self, v):
144
+ if self._eval_func and not isinstance(v, np.poly1d):
145
+ return self._eval_func(v)
146
+ else:
147
+ return np.poly1d.__call__(self, v)
148
+
149
+ def _scale(self, p):
150
+ if p == 1.0:
151
+ return
152
+ self._coeffs *= p
153
+
154
+ evf = self._eval_func
155
+ if evf:
156
+ self._eval_func = lambda x: evf(x) * p
157
+ self.normcoef *= p
158
+
159
+
160
+ def _gen_roots_and_weights(n, mu0, an_func, bn_func, f, df, symmetrize, mu):
161
+ """[x,w] = gen_roots_and_weights(n,an_func,sqrt_bn_func,mu)
162
+
163
+ Returns the roots (x) of an nth order orthogonal polynomial,
164
+ and weights (w) to use in appropriate Gaussian quadrature with that
165
+ orthogonal polynomial.
166
+
167
+ The polynomials have the recurrence relation
168
+ P_n+1(x) = (x - A_n) P_n(x) - B_n P_n-1(x)
169
+
170
+ an_func(n) should return A_n
171
+ sqrt_bn_func(n) should return sqrt(B_n)
172
+ mu ( = h_0 ) is the integral of the weight over the orthogonal
173
+ interval
174
+ """
175
+ k = np.arange(n, dtype='d')
176
+ c = np.zeros((2, n))
177
+ c[0,1:] = bn_func(k[1:])
178
+ c[1,:] = an_func(k)
179
+ x = linalg.eigvals_banded(c, overwrite_a_band=True)
180
+
181
+ # improve roots by one application of Newton's method
182
+ y = f(n, x)
183
+ dy = df(n, x)
184
+ x -= y/dy
185
+
186
+ # fm and dy may contain very large/small values, so we
187
+ # log-normalize them to maintain precision in the product fm*dy
188
+ fm = f(n-1, x)
189
+ log_fm = np.log(np.abs(fm))
190
+ log_dy = np.log(np.abs(dy))
191
+ fm /= np.exp((log_fm.max() + log_fm.min()) / 2.)
192
+ dy /= np.exp((log_dy.max() + log_dy.min()) / 2.)
193
+ w = 1.0 / (fm * dy)
194
+
195
+ if symmetrize:
196
+ w = (w + w[::-1]) / 2
197
+ x = (x - x[::-1]) / 2
198
+
199
+ w *= mu0 / w.sum()
200
+
201
+ if mu:
202
+ return x, w, mu0
203
+ else:
204
+ return x, w
205
+
206
+ # Jacobi Polynomials 1 P^(alpha,beta)_n(x)
207
+
208
+
209
+ def roots_jacobi(n, alpha, beta, mu=False):
210
+ r"""Gauss-Jacobi quadrature.
211
+
212
+ Compute the sample points and weights for Gauss-Jacobi
213
+ quadrature. The sample points are the roots of the nth degree
214
+ Jacobi polynomial, :math:`P^{\alpha, \beta}_n(x)`. These sample
215
+ points and weights correctly integrate polynomials of degree
216
+ :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
217
+ weight function :math:`w(x) = (1 - x)^{\alpha} (1 +
218
+ x)^{\beta}`. See 22.2.1 in [AS]_ for details.
219
+
220
+ Parameters
221
+ ----------
222
+ n : int
223
+ quadrature order
224
+ alpha : float
225
+ alpha must be > -1
226
+ beta : float
227
+ beta must be > -1
228
+ mu : bool, optional
229
+ If True, return the sum of the weights, optional.
230
+
231
+ Returns
232
+ -------
233
+ x : ndarray
234
+ Sample points
235
+ w : ndarray
236
+ Weights
237
+ mu : float
238
+ Sum of the weights
239
+
240
+ See Also
241
+ --------
242
+ scipy.integrate.quadrature
243
+ scipy.integrate.fixed_quad
244
+
245
+ References
246
+ ----------
247
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
248
+ Handbook of Mathematical Functions with Formulas,
249
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
250
+
251
+ """
252
+ m = int(n)
253
+ if n < 1 or n != m:
254
+ raise ValueError("n must be a positive integer.")
255
+ if alpha <= -1 or beta <= -1:
256
+ raise ValueError("alpha and beta must be greater than -1.")
257
+
258
+ if alpha == 0.0 and beta == 0.0:
259
+ return roots_legendre(m, mu)
260
+ if alpha == beta:
261
+ return roots_gegenbauer(m, alpha+0.5, mu)
262
+
263
+ if (alpha + beta) <= 1000:
264
+ mu0 = 2.0**(alpha+beta+1) * _ufuncs.beta(alpha+1, beta+1)
265
+ else:
266
+ # Avoid overflows in pow and beta for very large parameters
267
+ mu0 = np.exp((alpha + beta + 1) * np.log(2.0)
268
+ + _ufuncs.betaln(alpha+1, beta+1))
269
+ a = alpha
270
+ b = beta
271
+ if a + b == 0.0:
272
+ def an_func(k):
273
+ return np.where(k == 0, (b - a) / (2 + a + b), 0.0)
274
+ else:
275
+ def an_func(k):
276
+ return np.where(
277
+ k == 0,
278
+ (b - a) / (2 + a + b),
279
+ (b * b - a * a) / ((2.0 * k + a + b) * (2.0 * k + a + b + 2))
280
+ )
281
+
282
+ def bn_func(k):
283
+ return (
284
+ 2.0 / (2.0 * k + a + b)
285
+ * np.sqrt((k + a) * (k + b) / (2 * k + a + b + 1))
286
+ * np.where(k == 1, 1.0, np.sqrt(k * (k + a + b) / (2.0 * k + a + b - 1)))
287
+ )
288
+
289
+ def f(n, x):
290
+ return _ufuncs.eval_jacobi(n, a, b, x)
291
+ def df(n, x):
292
+ return 0.5 * (n + a + b + 1) * _ufuncs.eval_jacobi(n - 1, a + 1, b + 1, x)
293
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
294
+
295
+
296
+ def jacobi(n, alpha, beta, monic=False):
297
+ r"""Jacobi polynomial.
298
+
299
+ Defined to be the solution of
300
+
301
+ .. math::
302
+ (1 - x^2)\frac{d^2}{dx^2}P_n^{(\alpha, \beta)}
303
+ + (\beta - \alpha - (\alpha + \beta + 2)x)
304
+ \frac{d}{dx}P_n^{(\alpha, \beta)}
305
+ + n(n + \alpha + \beta + 1)P_n^{(\alpha, \beta)} = 0
306
+
307
+ for :math:`\alpha, \beta > -1`; :math:`P_n^{(\alpha, \beta)}` is a
308
+ polynomial of degree :math:`n`.
309
+
310
+ Parameters
311
+ ----------
312
+ n : int
313
+ Degree of the polynomial.
314
+ alpha : float
315
+ Parameter, must be greater than -1.
316
+ beta : float
317
+ Parameter, must be greater than -1.
318
+ monic : bool, optional
319
+ If `True`, scale the leading coefficient to be 1. Default is
320
+ `False`.
321
+
322
+ Returns
323
+ -------
324
+ P : orthopoly1d
325
+ Jacobi polynomial.
326
+
327
+ Notes
328
+ -----
329
+ For fixed :math:`\alpha, \beta`, the polynomials
330
+ :math:`P_n^{(\alpha, \beta)}` are orthogonal over :math:`[-1, 1]`
331
+ with weight function :math:`(1 - x)^\alpha(1 + x)^\beta`.
332
+
333
+ References
334
+ ----------
335
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
336
+ Handbook of Mathematical Functions with Formulas,
337
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
338
+
339
+ Examples
340
+ --------
341
+ The Jacobi polynomials satisfy the recurrence relation:
342
+
343
+ .. math::
344
+ P_n^{(\alpha, \beta-1)}(x) - P_n^{(\alpha-1, \beta)}(x)
345
+ = P_{n-1}^{(\alpha, \beta)}(x)
346
+
347
+ This can be verified, for example, for :math:`\alpha = \beta = 2`
348
+ and :math:`n = 1` over the interval :math:`[-1, 1]`:
349
+
350
+ >>> import numpy as np
351
+ >>> from scipy.special import jacobi
352
+ >>> x = np.arange(-1.0, 1.0, 0.01)
353
+ >>> np.allclose(jacobi(0, 2, 2)(x),
354
+ ... jacobi(1, 2, 1)(x) - jacobi(1, 1, 2)(x))
355
+ True
356
+
357
+ Plot of the Jacobi polynomial :math:`P_5^{(\alpha, -0.5)}` for
358
+ different values of :math:`\alpha`:
359
+
360
+ >>> import matplotlib.pyplot as plt
361
+ >>> x = np.arange(-1.0, 1.0, 0.01)
362
+ >>> fig, ax = plt.subplots()
363
+ >>> ax.set_ylim(-2.0, 2.0)
364
+ >>> ax.set_title(r'Jacobi polynomials $P_5^{(\alpha, -0.5)}$')
365
+ >>> for alpha in np.arange(0, 4, 1):
366
+ ... ax.plot(x, jacobi(5, alpha, -0.5)(x), label=rf'$\alpha={alpha}$')
367
+ >>> plt.legend(loc='best')
368
+ >>> plt.show()
369
+
370
+ """
371
+ if n < 0:
372
+ raise ValueError("n must be nonnegative.")
373
+
374
+ def wfunc(x):
375
+ return (1 - x) ** alpha * (1 + x) ** beta
376
+ if n == 0:
377
+ return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
378
+ eval_func=np.ones_like)
379
+ x, w, mu = roots_jacobi(n, alpha, beta, mu=True)
380
+ ab1 = alpha + beta + 1.0
381
+ hn = 2**ab1 / (2 * n + ab1) * _gam(n + alpha + 1)
382
+ hn *= _gam(n + beta + 1.0) / _gam(n + 1) / _gam(n + ab1)
383
+ kn = _gam(2 * n + ab1) / 2.0**n / _gam(n + 1) / _gam(n + ab1)
384
+ # here kn = coefficient on x^n term
385
+ p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
386
+ lambda x: _ufuncs.eval_jacobi(n, alpha, beta, x))
387
+ return p
388
+
389
+ # Jacobi Polynomials shifted G_n(p,q,x)
390
+
391
+
392
+ def roots_sh_jacobi(n, p1, q1, mu=False):
393
+ """Gauss-Jacobi (shifted) quadrature.
394
+
395
+ Compute the sample points and weights for Gauss-Jacobi (shifted)
396
+ quadrature. The sample points are the roots of the nth degree
397
+ shifted Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample
398
+ points and weights correctly integrate polynomials of degree
399
+ :math:`2n - 1` or less over the interval :math:`[0, 1]` with
400
+ weight function :math:`w(x) = (1 - x)^{p-q} x^{q-1}`. See 22.2.2
401
+ in [AS]_ for details.
402
+
403
+ Parameters
404
+ ----------
405
+ n : int
406
+ quadrature order
407
+ p1 : float
408
+ (p1 - q1) must be > -1
409
+ q1 : float
410
+ q1 must be > 0
411
+ mu : bool, optional
412
+ If True, return the sum of the weights, optional.
413
+
414
+ Returns
415
+ -------
416
+ x : ndarray
417
+ Sample points
418
+ w : ndarray
419
+ Weights
420
+ mu : float
421
+ Sum of the weights
422
+
423
+ See Also
424
+ --------
425
+ scipy.integrate.quadrature
426
+ scipy.integrate.fixed_quad
427
+
428
+ References
429
+ ----------
430
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
431
+ Handbook of Mathematical Functions with Formulas,
432
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
433
+
434
+ """
435
+ if (p1-q1) <= -1 or q1 <= 0:
436
+ message = "(p - q) must be greater than -1, and q must be greater than 0."
437
+ raise ValueError(message)
438
+ x, w, m = roots_jacobi(n, p1-q1, q1-1, True)
439
+ x = (x + 1) / 2
440
+ scale = 2.0**p1
441
+ w /= scale
442
+ m /= scale
443
+ if mu:
444
+ return x, w, m
445
+ else:
446
+ return x, w
447
+
448
+
449
+ def sh_jacobi(n, p, q, monic=False):
450
+ r"""Shifted Jacobi polynomial.
451
+
452
+ Defined by
453
+
454
+ .. math::
455
+
456
+ G_n^{(p, q)}(x)
457
+ = \binom{2n + p - 1}{n}^{-1}P_n^{(p - q, q - 1)}(2x - 1),
458
+
459
+ where :math:`P_n^{(\cdot, \cdot)}` is the nth Jacobi polynomial.
460
+
461
+ Parameters
462
+ ----------
463
+ n : int
464
+ Degree of the polynomial.
465
+ p : float
466
+ Parameter, must have :math:`p > q - 1`.
467
+ q : float
468
+ Parameter, must be greater than 0.
469
+ monic : bool, optional
470
+ If `True`, scale the leading coefficient to be 1. Default is
471
+ `False`.
472
+
473
+ Returns
474
+ -------
475
+ G : orthopoly1d
476
+ Shifted Jacobi polynomial.
477
+
478
+ Notes
479
+ -----
480
+ For fixed :math:`p, q`, the polynomials :math:`G_n^{(p, q)}` are
481
+ orthogonal over :math:`[0, 1]` with weight function :math:`(1 -
482
+ x)^{p - q}x^{q - 1}`.
483
+
484
+ """
485
+ if n < 0:
486
+ raise ValueError("n must be nonnegative.")
487
+
488
+ def wfunc(x):
489
+ return (1.0 - x) ** (p - q) * x ** (q - 1.0)
490
+ if n == 0:
491
+ return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
492
+ eval_func=np.ones_like)
493
+ n1 = n
494
+ x, w = roots_sh_jacobi(n1, p, q)
495
+ hn = _gam(n + 1) * _gam(n + q) * _gam(n + p) * _gam(n + p - q + 1)
496
+ hn /= (2 * n + p) * (_gam(2 * n + p)**2)
497
+ # kn = 1.0 in standard form so monic is redundant. Kept for compatibility.
498
+ kn = 1.0
499
+ pp = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(0, 1), monic=monic,
500
+ eval_func=lambda x: _ufuncs.eval_sh_jacobi(n, p, q, x))
501
+ return pp
502
+
503
+ # Generalized Laguerre L^(alpha)_n(x)
504
+
505
+
506
+ def roots_genlaguerre(n, alpha, mu=False):
507
+ r"""Gauss-generalized Laguerre quadrature.
508
+
509
+ Compute the sample points and weights for Gauss-generalized
510
+ Laguerre quadrature. The sample points are the roots of the nth
511
+ degree generalized Laguerre polynomial, :math:`L^{\alpha}_n(x)`.
512
+ These sample points and weights correctly integrate polynomials of
513
+ degree :math:`2n - 1` or less over the interval :math:`[0,
514
+ \infty]` with weight function :math:`w(x) = x^{\alpha}
515
+ e^{-x}`. See 22.3.9 in [AS]_ for details.
516
+
517
+ Parameters
518
+ ----------
519
+ n : int
520
+ quadrature order
521
+ alpha : float
522
+ alpha must be > -1
523
+ mu : bool, optional
524
+ If True, return the sum of the weights, optional.
525
+
526
+ Returns
527
+ -------
528
+ x : ndarray
529
+ Sample points
530
+ w : ndarray
531
+ Weights
532
+ mu : float
533
+ Sum of the weights
534
+
535
+ See Also
536
+ --------
537
+ scipy.integrate.quadrature
538
+ scipy.integrate.fixed_quad
539
+
540
+ References
541
+ ----------
542
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
543
+ Handbook of Mathematical Functions with Formulas,
544
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
545
+
546
+ """
547
+ m = int(n)
548
+ if n < 1 or n != m:
549
+ raise ValueError("n must be a positive integer.")
550
+ if alpha < -1:
551
+ raise ValueError("alpha must be greater than -1.")
552
+
553
+ mu0 = _ufuncs.gamma(alpha + 1)
554
+
555
+ if m == 1:
556
+ x = np.array([alpha+1.0], 'd')
557
+ w = np.array([mu0], 'd')
558
+ if mu:
559
+ return x, w, mu0
560
+ else:
561
+ return x, w
562
+
563
+ def an_func(k):
564
+ return 2 * k + alpha + 1
565
+ def bn_func(k):
566
+ return -np.sqrt(k * (k + alpha))
567
+ def f(n, x):
568
+ return _ufuncs.eval_genlaguerre(n, alpha, x)
569
+ def df(n, x):
570
+ return (n * _ufuncs.eval_genlaguerre(n, alpha, x)
571
+ - (n + alpha) * _ufuncs.eval_genlaguerre(n - 1, alpha, x)) / x
572
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
573
+
574
+
575
+ def genlaguerre(n, alpha, monic=False):
576
+ r"""Generalized (associated) Laguerre polynomial.
577
+
578
+ Defined to be the solution of
579
+
580
+ .. math::
581
+ x\frac{d^2}{dx^2}L_n^{(\alpha)}
582
+ + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)}
583
+ + nL_n^{(\alpha)} = 0,
584
+
585
+ where :math:`\alpha > -1`; :math:`L_n^{(\alpha)}` is a polynomial
586
+ of degree :math:`n`.
587
+
588
+ Parameters
589
+ ----------
590
+ n : int
591
+ Degree of the polynomial.
592
+ alpha : float
593
+ Parameter, must be greater than -1.
594
+ monic : bool, optional
595
+ If `True`, scale the leading coefficient to be 1. Default is
596
+ `False`.
597
+
598
+ Returns
599
+ -------
600
+ L : orthopoly1d
601
+ Generalized Laguerre polynomial.
602
+
603
+ See Also
604
+ --------
605
+ laguerre : Laguerre polynomial.
606
+ hyp1f1 : confluent hypergeometric function
607
+
608
+ Notes
609
+ -----
610
+ For fixed :math:`\alpha`, the polynomials :math:`L_n^{(\alpha)}`
611
+ are orthogonal over :math:`[0, \infty)` with weight function
612
+ :math:`e^{-x}x^\alpha`.
613
+
614
+ The Laguerre polynomials are the special case where :math:`\alpha
615
+ = 0`.
616
+
617
+ References
618
+ ----------
619
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
620
+ Handbook of Mathematical Functions with Formulas,
621
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
622
+
623
+ Examples
624
+ --------
625
+ The generalized Laguerre polynomials are closely related to the confluent
626
+ hypergeometric function :math:`{}_1F_1`:
627
+
628
+ .. math::
629
+ L_n^{(\alpha)} = \binom{n + \alpha}{n} {}_1F_1(-n, \alpha +1, x)
630
+
631
+ This can be verified, for example, for :math:`n = \alpha = 3` over the
632
+ interval :math:`[-1, 1]`:
633
+
634
+ >>> import numpy as np
635
+ >>> from scipy.special import binom
636
+ >>> from scipy.special import genlaguerre
637
+ >>> from scipy.special import hyp1f1
638
+ >>> x = np.arange(-1.0, 1.0, 0.01)
639
+ >>> np.allclose(genlaguerre(3, 3)(x), binom(6, 3) * hyp1f1(-3, 4, x))
640
+ True
641
+
642
+ This is the plot of the generalized Laguerre polynomials
643
+ :math:`L_3^{(\alpha)}` for some values of :math:`\alpha`:
644
+
645
+ >>> import matplotlib.pyplot as plt
646
+ >>> x = np.arange(-4.0, 12.0, 0.01)
647
+ >>> fig, ax = plt.subplots()
648
+ >>> ax.set_ylim(-5.0, 10.0)
649
+ >>> ax.set_title(r'Generalized Laguerre polynomials $L_3^{\alpha}$')
650
+ >>> for alpha in np.arange(0, 5):
651
+ ... ax.plot(x, genlaguerre(3, alpha)(x), label=rf'$L_3^{(alpha)}$')
652
+ >>> plt.legend(loc='best')
653
+ >>> plt.show()
654
+
655
+ """
656
+ if alpha <= -1:
657
+ raise ValueError("alpha must be > -1")
658
+ if n < 0:
659
+ raise ValueError("n must be nonnegative.")
660
+
661
+ if n == 0:
662
+ n1 = n + 1
663
+ else:
664
+ n1 = n
665
+ x, w = roots_genlaguerre(n1, alpha)
666
+ def wfunc(x):
667
+ return exp(-x) * x ** alpha
668
+ if n == 0:
669
+ x, w = [], []
670
+ hn = _gam(n + alpha + 1) / _gam(n + 1)
671
+ kn = (-1)**n / _gam(n + 1)
672
+ p = orthopoly1d(x, w, hn, kn, wfunc, (0, inf), monic,
673
+ lambda x: _ufuncs.eval_genlaguerre(n, alpha, x))
674
+ return p
675
+
676
+ # Laguerre L_n(x)
677
+
678
+
679
+ def roots_laguerre(n, mu=False):
680
+ r"""Gauss-Laguerre quadrature.
681
+
682
+ Compute the sample points and weights for Gauss-Laguerre
683
+ quadrature. The sample points are the roots of the nth degree
684
+ Laguerre polynomial, :math:`L_n(x)`. These sample points and
685
+ weights correctly integrate polynomials of degree :math:`2n - 1`
686
+ or less over the interval :math:`[0, \infty]` with weight function
687
+ :math:`w(x) = e^{-x}`. See 22.2.13 in [AS]_ for details.
688
+
689
+ Parameters
690
+ ----------
691
+ n : int
692
+ quadrature order
693
+ mu : bool, optional
694
+ If True, return the sum of the weights, optional.
695
+
696
+ Returns
697
+ -------
698
+ x : ndarray
699
+ Sample points
700
+ w : ndarray
701
+ Weights
702
+ mu : float
703
+ Sum of the weights
704
+
705
+ See Also
706
+ --------
707
+ scipy.integrate.quadrature
708
+ scipy.integrate.fixed_quad
709
+ numpy.polynomial.laguerre.laggauss
710
+
711
+ References
712
+ ----------
713
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
714
+ Handbook of Mathematical Functions with Formulas,
715
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
716
+
717
+ """
718
+ return roots_genlaguerre(n, 0.0, mu=mu)
719
+
720
+
721
+ def laguerre(n, monic=False):
722
+ r"""Laguerre polynomial.
723
+
724
+ Defined to be the solution of
725
+
726
+ .. math::
727
+ x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
728
+
729
+ :math:`L_n` is a polynomial of degree :math:`n`.
730
+
731
+ Parameters
732
+ ----------
733
+ n : int
734
+ Degree of the polynomial.
735
+ monic : bool, optional
736
+ If `True`, scale the leading coefficient to be 1. Default is
737
+ `False`.
738
+
739
+ Returns
740
+ -------
741
+ L : orthopoly1d
742
+ Laguerre Polynomial.
743
+
744
+ See Also
745
+ --------
746
+ genlaguerre : Generalized (associated) Laguerre polynomial.
747
+
748
+ Notes
749
+ -----
750
+ The polynomials :math:`L_n` are orthogonal over :math:`[0,
751
+ \infty)` with weight function :math:`e^{-x}`.
752
+
753
+ References
754
+ ----------
755
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
756
+ Handbook of Mathematical Functions with Formulas,
757
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
758
+
759
+ Examples
760
+ --------
761
+ The Laguerre polynomials :math:`L_n` are the special case
762
+ :math:`\alpha = 0` of the generalized Laguerre polynomials
763
+ :math:`L_n^{(\alpha)}`.
764
+ Let's verify it on the interval :math:`[-1, 1]`:
765
+
766
+ >>> import numpy as np
767
+ >>> from scipy.special import genlaguerre
768
+ >>> from scipy.special import laguerre
769
+ >>> x = np.arange(-1.0, 1.0, 0.01)
770
+ >>> np.allclose(genlaguerre(3, 0)(x), laguerre(3)(x))
771
+ True
772
+
773
+ The polynomials :math:`L_n` also satisfy the recurrence relation:
774
+
775
+ .. math::
776
+ (n + 1)L_{n+1}(x) = (2n +1 -x)L_n(x) - nL_{n-1}(x)
777
+
778
+ This can be easily checked on :math:`[0, 1]` for :math:`n = 3`:
779
+
780
+ >>> x = np.arange(0.0, 1.0, 0.01)
781
+ >>> np.allclose(4 * laguerre(4)(x),
782
+ ... (7 - x) * laguerre(3)(x) - 3 * laguerre(2)(x))
783
+ True
784
+
785
+ This is the plot of the first few Laguerre polynomials :math:`L_n`:
786
+
787
+ >>> import matplotlib.pyplot as plt
788
+ >>> x = np.arange(-1.0, 5.0, 0.01)
789
+ >>> fig, ax = plt.subplots()
790
+ >>> ax.set_ylim(-5.0, 5.0)
791
+ >>> ax.set_title(r'Laguerre polynomials $L_n$')
792
+ >>> for n in np.arange(0, 5):
793
+ ... ax.plot(x, laguerre(n)(x), label=rf'$L_{n}$')
794
+ >>> plt.legend(loc='best')
795
+ >>> plt.show()
796
+
797
+ """
798
+ if n < 0:
799
+ raise ValueError("n must be nonnegative.")
800
+
801
+ if n == 0:
802
+ n1 = n + 1
803
+ else:
804
+ n1 = n
805
+ x, w = roots_laguerre(n1)
806
+ if n == 0:
807
+ x, w = [], []
808
+ hn = 1.0
809
+ kn = (-1)**n / _gam(n + 1)
810
+ p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic,
811
+ lambda x: _ufuncs.eval_laguerre(n, x))
812
+ return p
813
+
814
+ # Hermite 1 H_n(x)
815
+
816
+
817
+ def roots_hermite(n, mu=False):
818
+ r"""Gauss-Hermite (physicist's) quadrature.
819
+
820
+ Compute the sample points and weights for Gauss-Hermite
821
+ quadrature. The sample points are the roots of the nth degree
822
+ Hermite polynomial, :math:`H_n(x)`. These sample points and
823
+ weights correctly integrate polynomials of degree :math:`2n - 1`
824
+ or less over the interval :math:`[-\infty, \infty]` with weight
825
+ function :math:`w(x) = e^{-x^2}`. See 22.2.14 in [AS]_ for
826
+ details.
827
+
828
+ Parameters
829
+ ----------
830
+ n : int
831
+ quadrature order
832
+ mu : bool, optional
833
+ If True, return the sum of the weights, optional.
834
+
835
+ Returns
836
+ -------
837
+ x : ndarray
838
+ Sample points
839
+ w : ndarray
840
+ Weights
841
+ mu : float
842
+ Sum of the weights
843
+
844
+ See Also
845
+ --------
846
+ scipy.integrate.quadrature
847
+ scipy.integrate.fixed_quad
848
+ numpy.polynomial.hermite.hermgauss
849
+ roots_hermitenorm
850
+
851
+ Notes
852
+ -----
853
+ For small n up to 150 a modified version of the Golub-Welsch
854
+ algorithm is used. Nodes are computed from the eigenvalue
855
+ problem and improved by one step of a Newton iteration.
856
+ The weights are computed from the well-known analytical formula.
857
+
858
+ For n larger than 150 an optimal asymptotic algorithm is applied
859
+ which computes nodes and weights in a numerically stable manner.
860
+ The algorithm has linear runtime making computation for very
861
+ large n (several thousand or more) feasible.
862
+
863
+ References
864
+ ----------
865
+ .. [townsend.trogdon.olver-2014]
866
+ Townsend, A. and Trogdon, T. and Olver, S. (2014)
867
+ *Fast computation of Gauss quadrature nodes and
868
+ weights on the whole real line*. :arXiv:`1410.5286`.
869
+ .. [townsend.trogdon.olver-2015]
870
+ Townsend, A. and Trogdon, T. and Olver, S. (2015)
871
+ *Fast computation of Gauss quadrature nodes and
872
+ weights on the whole real line*.
873
+ IMA Journal of Numerical Analysis
874
+ :doi:`10.1093/imanum/drv002`.
875
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
876
+ Handbook of Mathematical Functions with Formulas,
877
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
878
+
879
+ """
880
+ m = int(n)
881
+ if n < 1 or n != m:
882
+ raise ValueError("n must be a positive integer.")
883
+
884
+ mu0 = np.sqrt(np.pi)
885
+ if n <= 150:
886
+ def an_func(k):
887
+ return 0.0 * k
888
+ def bn_func(k):
889
+ return np.sqrt(k / 2.0)
890
+ f = _ufuncs.eval_hermite
891
+ def df(n, x):
892
+ return 2.0 * n * _ufuncs.eval_hermite(n - 1, x)
893
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
894
+ else:
895
+ nodes, weights = _roots_hermite_asy(m)
896
+ if mu:
897
+ return nodes, weights, mu0
898
+ else:
899
+ return nodes, weights
900
+
901
+
902
+ def _compute_tauk(n, k, maxit=5):
903
+ """Helper function for Tricomi initial guesses
904
+
905
+ For details, see formula 3.1 in lemma 3.1 in the
906
+ original paper.
907
+
908
+ Parameters
909
+ ----------
910
+ n : int
911
+ Quadrature order
912
+ k : ndarray of type int
913
+ Index of roots :math:`\tau_k` to compute
914
+ maxit : int
915
+ Number of Newton maxit performed, the default
916
+ value of 5 is sufficient.
917
+
918
+ Returns
919
+ -------
920
+ tauk : ndarray
921
+ Roots of equation 3.1
922
+
923
+ See Also
924
+ --------
925
+ initial_nodes_a
926
+ roots_hermite_asy
927
+ """
928
+ a = n % 2 - 0.5
929
+ c = (4.0*floor(n/2.0) - 4.0*k + 3.0)*pi / (4.0*floor(n/2.0) + 2.0*a + 2.0)
930
+ def f(x):
931
+ return x - sin(x) - c
932
+ def df(x):
933
+ return 1.0 - cos(x)
934
+ xi = 0.5*pi
935
+ for i in range(maxit):
936
+ xi = xi - f(xi)/df(xi)
937
+ return xi
938
+
939
+
940
+ def _initial_nodes_a(n, k):
941
+ r"""Tricomi initial guesses
942
+
943
+ Computes an initial approximation to the square of the `k`-th
944
+ (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
945
+ of order :math:`n`. The formula is the one from lemma 3.1 in the
946
+ original paper. The guesses are accurate except in the region
947
+ near :math:`\sqrt{2n + 1}`.
948
+
949
+ Parameters
950
+ ----------
951
+ n : int
952
+ Quadrature order
953
+ k : ndarray of type int
954
+ Index of roots to compute
955
+
956
+ Returns
957
+ -------
958
+ xksq : ndarray
959
+ Square of the approximate roots
960
+
961
+ See Also
962
+ --------
963
+ initial_nodes
964
+ roots_hermite_asy
965
+ """
966
+ tauk = _compute_tauk(n, k)
967
+ sigk = cos(0.5*tauk)**2
968
+ a = n % 2 - 0.5
969
+ nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
970
+ # Initial approximation of Hermite roots (square)
971
+ xksq = nu*sigk - 1.0/(3.0*nu) * (5.0/(4.0*(1.0-sigk)**2) - 1.0/(1.0-sigk) - 0.25)
972
+ return xksq
973
+
974
+
975
+ def _initial_nodes_b(n, k):
976
+ r"""Gatteschi initial guesses
977
+
978
+ Computes an initial approximation to the square of the kth
979
+ (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
980
+ of order :math:`n`. The formula is the one from lemma 3.2 in the
981
+ original paper. The guesses are accurate in the region just
982
+ below :math:`\sqrt{2n + 1}`.
983
+
984
+ Parameters
985
+ ----------
986
+ n : int
987
+ Quadrature order
988
+ k : ndarray of type int
989
+ Index of roots to compute
990
+
991
+ Returns
992
+ -------
993
+ xksq : ndarray
994
+ Square of the approximate root
995
+
996
+ See Also
997
+ --------
998
+ initial_nodes
999
+ roots_hermite_asy
1000
+ """
1001
+ a = n % 2 - 0.5
1002
+ nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
1003
+ # Airy roots by approximation
1004
+ ak = _specfun.airyzo(k.max(), 1)[0][::-1]
1005
+ # Initial approximation of Hermite roots (square)
1006
+ xksq = (nu
1007
+ + 2.0**(2.0/3.0) * ak * nu**(1.0/3.0)
1008
+ + 1.0/5.0 * 2.0**(4.0/3.0) * ak**2 * nu**(-1.0/3.0)
1009
+ + (9.0/140.0 - 12.0/175.0 * ak**3) * nu**(-1.0)
1010
+ + (16.0/1575.0 * ak + 92.0/7875.0 * ak**4) * 2.0**(2.0/3.0) * nu**(-5.0/3.0)
1011
+ - (15152.0/3031875.0 * ak**5 + 1088.0/121275.0 * ak**2)
1012
+ * 2.0**(1.0/3.0) * nu**(-7.0/3.0))
1013
+ return xksq
1014
+
1015
+
1016
+ def _initial_nodes(n):
1017
+ """Initial guesses for the Hermite roots
1018
+
1019
+ Computes an initial approximation to the non-negative
1020
+ roots :math:`x_k` of the Hermite polynomial :math:`H_n`
1021
+ of order :math:`n`. The Tricomi and Gatteschi initial
1022
+ guesses are used in the region where they are accurate.
1023
+
1024
+ Parameters
1025
+ ----------
1026
+ n : int
1027
+ Quadrature order
1028
+
1029
+ Returns
1030
+ -------
1031
+ xk : ndarray
1032
+ Approximate roots
1033
+
1034
+ See Also
1035
+ --------
1036
+ roots_hermite_asy
1037
+ """
1038
+ # Turnover point
1039
+ # linear polynomial fit to error of 10, 25, 40, ..., 1000 point rules
1040
+ fit = 0.49082003*n - 4.37859653
1041
+ turnover = around(fit).astype(int)
1042
+ # Compute all approximations
1043
+ ia = arange(1, int(floor(n*0.5)+1))
1044
+ ib = ia[::-1]
1045
+ xasq = _initial_nodes_a(n, ia[:turnover+1])
1046
+ xbsq = _initial_nodes_b(n, ib[turnover+1:])
1047
+ # Combine
1048
+ iv = sqrt(hstack([xasq, xbsq]))
1049
+ # Central node is always zero
1050
+ if n % 2 == 1:
1051
+ iv = hstack([0.0, iv])
1052
+ return iv
1053
+
1054
+
1055
+ def _pbcf(n, theta):
1056
+ r"""Asymptotic series expansion of parabolic cylinder function
1057
+
1058
+ The implementation is based on sections 3.2 and 3.3 from the
1059
+ original paper. Compared to the published version this code
1060
+ adds one more term to the asymptotic series. The detailed
1061
+ formulas can be found at [parabolic-asymptotics]_. The evaluation
1062
+ is done in a transformed variable :math:`\theta := \arccos(t)`
1063
+ where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ n : int
1068
+ Quadrature order
1069
+ theta : ndarray
1070
+ Transformed position variable
1071
+
1072
+ Returns
1073
+ -------
1074
+ U : ndarray
1075
+ Value of the parabolic cylinder function :math:`U(a, \theta)`.
1076
+ Ud : ndarray
1077
+ Value of the derivative :math:`U^{\prime}(a, \theta)` of
1078
+ the parabolic cylinder function.
1079
+
1080
+ See Also
1081
+ --------
1082
+ roots_hermite_asy
1083
+
1084
+ References
1085
+ ----------
1086
+ .. [parabolic-asymptotics]
1087
+ https://dlmf.nist.gov/12.10#vii
1088
+ """
1089
+ st = sin(theta)
1090
+ ct = cos(theta)
1091
+ # https://dlmf.nist.gov/12.10#vii
1092
+ mu = 2.0*n + 1.0
1093
+ # https://dlmf.nist.gov/12.10#E23
1094
+ eta = 0.5*theta - 0.5*st*ct
1095
+ # https://dlmf.nist.gov/12.10#E39
1096
+ zeta = -(3.0*eta/2.0) ** (2.0/3.0)
1097
+ # https://dlmf.nist.gov/12.10#E40
1098
+ phi = (-zeta / st**2) ** (0.25)
1099
+ # Coefficients
1100
+ # https://dlmf.nist.gov/12.10#E43
1101
+ a0 = 1.0
1102
+ a1 = 0.10416666666666666667
1103
+ a2 = 0.08355034722222222222
1104
+ a3 = 0.12822657455632716049
1105
+ a4 = 0.29184902646414046425
1106
+ a5 = 0.88162726744375765242
1107
+ b0 = 1.0
1108
+ b1 = -0.14583333333333333333
1109
+ b2 = -0.09874131944444444444
1110
+ b3 = -0.14331205391589506173
1111
+ b4 = -0.31722720267841354810
1112
+ b5 = -0.94242914795712024914
1113
+ # Polynomials
1114
+ # https://dlmf.nist.gov/12.10#E9
1115
+ # https://dlmf.nist.gov/12.10#E10
1116
+ ctp = ct ** arange(16).reshape((-1,1))
1117
+ u0 = 1.0
1118
+ u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0
1119
+ u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0
1120
+ u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:]
1121
+ - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0
1122
+ u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:]
1123
+ + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0
1124
+ u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:]
1125
+ - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:]
1126
+ - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0
1127
+ v0 = 1.0
1128
+ v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0
1129
+ v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0
1130
+ v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:]
1131
+ + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0
1132
+ v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:]
1133
+ - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0
1134
+ v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:]
1135
+ - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:]
1136
+ + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0
1137
+ # Airy Evaluation (Bi and Bip unused)
1138
+ Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta)
1139
+ # Prefactor for U
1140
+ P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi
1141
+ # Terms for U
1142
+ # https://dlmf.nist.gov/12.10#E42
1143
+ phip = phi ** arange(6, 31, 6).reshape((-1,1))
1144
+ A0 = b0*u0
1145
+ A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3
1146
+ A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3
1147
+ + phip[3,:]*b0*u4) / zeta**6
1148
+ B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2
1149
+ B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5
1150
+ B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3
1151
+ + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8
1152
+ # U
1153
+ # https://dlmf.nist.gov/12.10#E35
1154
+ U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) +
1155
+ Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0))
1156
+ # Prefactor for derivative of U
1157
+ Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi
1158
+ # Terms for derivative of U
1159
+ # https://dlmf.nist.gov/12.10#E46
1160
+ C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta
1161
+ C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4
1162
+ C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3
1163
+ + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7
1164
+ D0 = a0*v0
1165
+ D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3
1166
+ D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3
1167
+ + phip[3,:]*a0*v4) / zeta**6
1168
+ # Derivative of U
1169
+ # https://dlmf.nist.gov/12.10#E36
1170
+ Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) +
1171
+ Aip * (D0 + D1/mu**2.0 + D2/mu**4.0))
1172
+ return U, Ud
1173
+
1174
+
1175
+ def _newton(n, x_initial, maxit=5):
1176
+ """Newton iteration for polishing the asymptotic approximation
1177
+ to the zeros of the Hermite polynomials.
1178
+
1179
+ Parameters
1180
+ ----------
1181
+ n : int
1182
+ Quadrature order
1183
+ x_initial : ndarray
1184
+ Initial guesses for the roots
1185
+ maxit : int
1186
+ Maximal number of Newton iterations.
1187
+ The default 5 is sufficient, usually
1188
+ only one or two steps are needed.
1189
+
1190
+ Returns
1191
+ -------
1192
+ nodes : ndarray
1193
+ Quadrature nodes
1194
+ weights : ndarray
1195
+ Quadrature weights
1196
+
1197
+ See Also
1198
+ --------
1199
+ roots_hermite_asy
1200
+ """
1201
+ # Variable transformation
1202
+ mu = sqrt(2.0*n + 1.0)
1203
+ t = x_initial / mu
1204
+ theta = arccos(t)
1205
+ # Newton iteration
1206
+ for i in range(maxit):
1207
+ u, ud = _pbcf(n, theta)
1208
+ dtheta = u / (sqrt(2.0) * mu * sin(theta) * ud)
1209
+ theta = theta + dtheta
1210
+ if max(abs(dtheta)) < 1e-14:
1211
+ break
1212
+ # Undo variable transformation
1213
+ x = mu * cos(theta)
1214
+ # Central node is always zero
1215
+ if n % 2 == 1:
1216
+ x[0] = 0.0
1217
+ # Compute weights
1218
+ w = exp(-x**2) / (2.0*ud**2)
1219
+ return x, w
1220
+
1221
+
1222
+ def _roots_hermite_asy(n):
1223
+ r"""Gauss-Hermite (physicist's) quadrature for large n.
1224
+
1225
+ Computes the sample points and weights for Gauss-Hermite quadrature.
1226
+ The sample points are the roots of the nth degree Hermite polynomial,
1227
+ :math:`H_n(x)`. These sample points and weights correctly integrate
1228
+ polynomials of degree :math:`2n - 1` or less over the interval
1229
+ :math:`[-\infty, \infty]` with weight function :math:`f(x) = e^{-x^2}`.
1230
+
1231
+ This method relies on asymptotic expansions which work best for n > 150.
1232
+ The algorithm has linear runtime making computation for very large n
1233
+ feasible.
1234
+
1235
+ Parameters
1236
+ ----------
1237
+ n : int
1238
+ quadrature order
1239
+
1240
+ Returns
1241
+ -------
1242
+ nodes : ndarray
1243
+ Quadrature nodes
1244
+ weights : ndarray
1245
+ Quadrature weights
1246
+
1247
+ See Also
1248
+ --------
1249
+ roots_hermite
1250
+
1251
+ References
1252
+ ----------
1253
+ .. [townsend.trogdon.olver-2014]
1254
+ Townsend, A. and Trogdon, T. and Olver, S. (2014)
1255
+ *Fast computation of Gauss quadrature nodes and
1256
+ weights on the whole real line*. :arXiv:`1410.5286`.
1257
+
1258
+ .. [townsend.trogdon.olver-2015]
1259
+ Townsend, A. and Trogdon, T. and Olver, S. (2015)
1260
+ *Fast computation of Gauss quadrature nodes and
1261
+ weights on the whole real line*.
1262
+ IMA Journal of Numerical Analysis
1263
+ :doi:`10.1093/imanum/drv002`.
1264
+ """
1265
+ iv = _initial_nodes(n)
1266
+ nodes, weights = _newton(n, iv)
1267
+ # Combine with negative parts
1268
+ if n % 2 == 0:
1269
+ nodes = hstack([-nodes[::-1], nodes])
1270
+ weights = hstack([weights[::-1], weights])
1271
+ else:
1272
+ nodes = hstack([-nodes[-1:0:-1], nodes])
1273
+ weights = hstack([weights[-1:0:-1], weights])
1274
+ # Scale weights
1275
+ weights *= sqrt(pi) / sum(weights)
1276
+ return nodes, weights
1277
+
1278
+
1279
+ def hermite(n, monic=False):
1280
+ r"""Physicist's Hermite polynomial.
1281
+
1282
+ Defined by
1283
+
1284
+ .. math::
1285
+
1286
+ H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2};
1287
+
1288
+ :math:`H_n` is a polynomial of degree :math:`n`.
1289
+
1290
+ Parameters
1291
+ ----------
1292
+ n : int
1293
+ Degree of the polynomial.
1294
+ monic : bool, optional
1295
+ If `True`, scale the leading coefficient to be 1. Default is
1296
+ `False`.
1297
+
1298
+ Returns
1299
+ -------
1300
+ H : orthopoly1d
1301
+ Hermite polynomial.
1302
+
1303
+ Notes
1304
+ -----
1305
+ The polynomials :math:`H_n` are orthogonal over :math:`(-\infty,
1306
+ \infty)` with weight function :math:`e^{-x^2}`.
1307
+
1308
+ Examples
1309
+ --------
1310
+ >>> from scipy import special
1311
+ >>> import matplotlib.pyplot as plt
1312
+ >>> import numpy as np
1313
+
1314
+ >>> p_monic = special.hermite(3, monic=True)
1315
+ >>> p_monic
1316
+ poly1d([ 1. , 0. , -1.5, 0. ])
1317
+ >>> p_monic(1)
1318
+ -0.49999999999999983
1319
+ >>> x = np.linspace(-3, 3, 400)
1320
+ >>> y = p_monic(x)
1321
+ >>> plt.plot(x, y)
1322
+ >>> plt.title("Monic Hermite polynomial of degree 3")
1323
+ >>> plt.xlabel("x")
1324
+ >>> plt.ylabel("H_3(x)")
1325
+ >>> plt.show()
1326
+
1327
+ """
1328
+ if n < 0:
1329
+ raise ValueError("n must be nonnegative.")
1330
+
1331
+ if n == 0:
1332
+ n1 = n + 1
1333
+ else:
1334
+ n1 = n
1335
+ x, w = roots_hermite(n1)
1336
+ def wfunc(x):
1337
+ return exp(-x * x)
1338
+ if n == 0:
1339
+ x, w = [], []
1340
+ hn = 2**n * _gam(n + 1) * sqrt(pi)
1341
+ kn = 2**n
1342
+ p = orthopoly1d(x, w, hn, kn, wfunc, (-inf, inf), monic,
1343
+ lambda x: _ufuncs.eval_hermite(n, x))
1344
+ return p
1345
+
1346
+ # Hermite 2 He_n(x)
1347
+
1348
+
1349
+ def roots_hermitenorm(n, mu=False):
1350
+ r"""Gauss-Hermite (statistician's) quadrature.
1351
+
1352
+ Compute the sample points and weights for Gauss-Hermite
1353
+ quadrature. The sample points are the roots of the nth degree
1354
+ Hermite polynomial, :math:`He_n(x)`. These sample points and
1355
+ weights correctly integrate polynomials of degree :math:`2n - 1`
1356
+ or less over the interval :math:`[-\infty, \infty]` with weight
1357
+ function :math:`w(x) = e^{-x^2/2}`. See 22.2.15 in [AS]_ for more
1358
+ details.
1359
+
1360
+ Parameters
1361
+ ----------
1362
+ n : int
1363
+ quadrature order
1364
+ mu : bool, optional
1365
+ If True, return the sum of the weights, optional.
1366
+
1367
+ Returns
1368
+ -------
1369
+ x : ndarray
1370
+ Sample points
1371
+ w : ndarray
1372
+ Weights
1373
+ mu : float
1374
+ Sum of the weights
1375
+
1376
+ See Also
1377
+ --------
1378
+ scipy.integrate.quadrature
1379
+ scipy.integrate.fixed_quad
1380
+ numpy.polynomial.hermite_e.hermegauss
1381
+
1382
+ Notes
1383
+ -----
1384
+ For small n up to 150 a modified version of the Golub-Welsch
1385
+ algorithm is used. Nodes are computed from the eigenvalue
1386
+ problem and improved by one step of a Newton iteration.
1387
+ The weights are computed from the well-known analytical formula.
1388
+
1389
+ For n larger than 150 an optimal asymptotic algorithm is used
1390
+ which computes nodes and weights in a numerical stable manner.
1391
+ The algorithm has linear runtime making computation for very
1392
+ large n (several thousand or more) feasible.
1393
+
1394
+ References
1395
+ ----------
1396
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1397
+ Handbook of Mathematical Functions with Formulas,
1398
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1399
+
1400
+ """
1401
+ m = int(n)
1402
+ if n < 1 or n != m:
1403
+ raise ValueError("n must be a positive integer.")
1404
+
1405
+ mu0 = np.sqrt(2.0*np.pi)
1406
+ if n <= 150:
1407
+ def an_func(k):
1408
+ return 0.0 * k
1409
+ def bn_func(k):
1410
+ return np.sqrt(k)
1411
+ f = _ufuncs.eval_hermitenorm
1412
+ def df(n, x):
1413
+ return n * _ufuncs.eval_hermitenorm(n - 1, x)
1414
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
1415
+ else:
1416
+ nodes, weights = _roots_hermite_asy(m)
1417
+ # Transform
1418
+ nodes *= sqrt(2)
1419
+ weights *= sqrt(2)
1420
+ if mu:
1421
+ return nodes, weights, mu0
1422
+ else:
1423
+ return nodes, weights
1424
+
1425
+
1426
+ def hermitenorm(n, monic=False):
1427
+ r"""Normalized (probabilist's) Hermite polynomial.
1428
+
1429
+ Defined by
1430
+
1431
+ .. math::
1432
+
1433
+ He_n(x) = (-1)^ne^{x^2/2}\frac{d^n}{dx^n}e^{-x^2/2};
1434
+
1435
+ :math:`He_n` is a polynomial of degree :math:`n`.
1436
+
1437
+ Parameters
1438
+ ----------
1439
+ n : int
1440
+ Degree of the polynomial.
1441
+ monic : bool, optional
1442
+ If `True`, scale the leading coefficient to be 1. Default is
1443
+ `False`.
1444
+
1445
+ Returns
1446
+ -------
1447
+ He : orthopoly1d
1448
+ Hermite polynomial.
1449
+
1450
+ Notes
1451
+ -----
1452
+
1453
+ The polynomials :math:`He_n` are orthogonal over :math:`(-\infty,
1454
+ \infty)` with weight function :math:`e^{-x^2/2}`.
1455
+
1456
+ """
1457
+ if n < 0:
1458
+ raise ValueError("n must be nonnegative.")
1459
+
1460
+ if n == 0:
1461
+ n1 = n + 1
1462
+ else:
1463
+ n1 = n
1464
+ x, w = roots_hermitenorm(n1)
1465
+ def wfunc(x):
1466
+ return exp(-x * x / 2.0)
1467
+ if n == 0:
1468
+ x, w = [], []
1469
+ hn = sqrt(2 * pi) * _gam(n + 1)
1470
+ kn = 1.0
1471
+ p = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(-inf, inf), monic=monic,
1472
+ eval_func=lambda x: _ufuncs.eval_hermitenorm(n, x))
1473
+ return p
1474
+
1475
+ # The remainder of the polynomials can be derived from the ones above.
1476
+
1477
+ # Ultraspherical (Gegenbauer) C^(alpha)_n(x)
1478
+
1479
+
1480
+ def roots_gegenbauer(n, alpha, mu=False):
1481
+ r"""Gauss-Gegenbauer quadrature.
1482
+
1483
+ Compute the sample points and weights for Gauss-Gegenbauer
1484
+ quadrature. The sample points are the roots of the nth degree
1485
+ Gegenbauer polynomial, :math:`C^{\alpha}_n(x)`. These sample
1486
+ points and weights correctly integrate polynomials of degree
1487
+ :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
1488
+ weight function :math:`w(x) = (1 - x^2)^{\alpha - 1/2}`. See
1489
+ 22.2.3 in [AS]_ for more details.
1490
+
1491
+ Parameters
1492
+ ----------
1493
+ n : int
1494
+ quadrature order
1495
+ alpha : float
1496
+ alpha must be > -0.5
1497
+ mu : bool, optional
1498
+ If True, return the sum of the weights, optional.
1499
+
1500
+ Returns
1501
+ -------
1502
+ x : ndarray
1503
+ Sample points
1504
+ w : ndarray
1505
+ Weights
1506
+ mu : float
1507
+ Sum of the weights
1508
+
1509
+ See Also
1510
+ --------
1511
+ scipy.integrate.quadrature
1512
+ scipy.integrate.fixed_quad
1513
+
1514
+ References
1515
+ ----------
1516
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1517
+ Handbook of Mathematical Functions with Formulas,
1518
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1519
+
1520
+ """
1521
+ m = int(n)
1522
+ if n < 1 or n != m:
1523
+ raise ValueError("n must be a positive integer.")
1524
+ if alpha < -0.5:
1525
+ raise ValueError("alpha must be greater than -0.5.")
1526
+ elif alpha == 0.0:
1527
+ # C(n,0,x) == 0 uniformly, however, as alpha->0, C(n,alpha,x)->T(n,x)
1528
+ # strictly, we should just error out here, since the roots are not
1529
+ # really defined, but we used to return something useful, so let's
1530
+ # keep doing so.
1531
+ return roots_chebyt(n, mu)
1532
+
1533
+ if alpha <= 170:
1534
+ mu0 = (np.sqrt(np.pi) * _ufuncs.gamma(alpha + 0.5)) \
1535
+ / _ufuncs.gamma(alpha + 1)
1536
+ else:
1537
+ # For large alpha we use a Taylor series expansion around inf,
1538
+ # expressed as a 6th order polynomial of a^-1 and using Horner's
1539
+ # method to minimize computation and maximize precision
1540
+ inv_alpha = 1. / alpha
1541
+ coeffs = np.array([0.000207186, -0.00152206, -0.000640869,
1542
+ 0.00488281, 0.0078125, -0.125, 1.])
1543
+ mu0 = coeffs[0]
1544
+ for term in range(1, len(coeffs)):
1545
+ mu0 = mu0 * inv_alpha + coeffs[term]
1546
+ mu0 = mu0 * np.sqrt(np.pi / alpha)
1547
+ def an_func(k):
1548
+ return 0.0 * k
1549
+ def bn_func(k):
1550
+ return np.sqrt(k * (k + 2 * alpha - 1) / (4 * (k + alpha) * (k + alpha - 1)))
1551
+ def f(n, x):
1552
+ return _ufuncs.eval_gegenbauer(n, alpha, x)
1553
+ def df(n, x):
1554
+ return (
1555
+ -n * x * _ufuncs.eval_gegenbauer(n, alpha, x)
1556
+ + (n + 2 * alpha - 1) * _ufuncs.eval_gegenbauer(n - 1, alpha, x)
1557
+ ) / (1 - x ** 2)
1558
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
1559
+
1560
+
1561
+ def gegenbauer(n, alpha, monic=False):
1562
+ r"""Gegenbauer (ultraspherical) polynomial.
1563
+
1564
+ Defined to be the solution of
1565
+
1566
+ .. math::
1567
+ (1 - x^2)\frac{d^2}{dx^2}C_n^{(\alpha)}
1568
+ - (2\alpha + 1)x\frac{d}{dx}C_n^{(\alpha)}
1569
+ + n(n + 2\alpha)C_n^{(\alpha)} = 0
1570
+
1571
+ for :math:`\alpha > -1/2`; :math:`C_n^{(\alpha)}` is a polynomial
1572
+ of degree :math:`n`.
1573
+
1574
+ Parameters
1575
+ ----------
1576
+ n : int
1577
+ Degree of the polynomial.
1578
+ alpha : float
1579
+ Parameter, must be greater than -0.5.
1580
+ monic : bool, optional
1581
+ If `True`, scale the leading coefficient to be 1. Default is
1582
+ `False`.
1583
+
1584
+ Returns
1585
+ -------
1586
+ C : orthopoly1d
1587
+ Gegenbauer polynomial.
1588
+
1589
+ Notes
1590
+ -----
1591
+ The polynomials :math:`C_n^{(\alpha)}` are orthogonal over
1592
+ :math:`[-1,1]` with weight function :math:`(1 - x^2)^{(\alpha -
1593
+ 1/2)}`.
1594
+
1595
+ Examples
1596
+ --------
1597
+ >>> import numpy as np
1598
+ >>> from scipy import special
1599
+ >>> import matplotlib.pyplot as plt
1600
+
1601
+ We can initialize a variable ``p`` as a Gegenbauer polynomial using the
1602
+ `gegenbauer` function and evaluate at a point ``x = 1``.
1603
+
1604
+ >>> p = special.gegenbauer(3, 0.5, monic=False)
1605
+ >>> p
1606
+ poly1d([ 2.5, 0. , -1.5, 0. ])
1607
+ >>> p(1)
1608
+ 1.0
1609
+
1610
+ To evaluate ``p`` at various points ``x`` in the interval ``(-3, 3)``,
1611
+ simply pass an array ``x`` to ``p`` as follows:
1612
+
1613
+ >>> x = np.linspace(-3, 3, 400)
1614
+ >>> y = p(x)
1615
+
1616
+ We can then visualize ``x, y`` using `matplotlib.pyplot`.
1617
+
1618
+ >>> fig, ax = plt.subplots()
1619
+ >>> ax.plot(x, y)
1620
+ >>> ax.set_title("Gegenbauer (ultraspherical) polynomial of degree 3")
1621
+ >>> ax.set_xlabel("x")
1622
+ >>> ax.set_ylabel("G_3(x)")
1623
+ >>> plt.show()
1624
+
1625
+ """
1626
+ base = jacobi(n, alpha - 0.5, alpha - 0.5, monic=monic)
1627
+ if monic:
1628
+ return base
1629
+ # Abrahmowitz and Stegan 22.5.20
1630
+ factor = (_gam(2*alpha + n) * _gam(alpha + 0.5) /
1631
+ _gam(2*alpha) / _gam(alpha + 0.5 + n))
1632
+ base._scale(factor)
1633
+ base.__dict__['_eval_func'] = lambda x: _ufuncs.eval_gegenbauer(float(n),
1634
+ alpha, x)
1635
+ return base
1636
+
1637
+ # Chebyshev of the first kind: T_n(x) =
1638
+ # n! sqrt(pi) / _gam(n+1./2)* P^(-1/2,-1/2)_n(x)
1639
+ # Computed anew.
1640
+
1641
+
1642
+ def roots_chebyt(n, mu=False):
1643
+ r"""Gauss-Chebyshev (first kind) quadrature.
1644
+
1645
+ Computes the sample points and weights for Gauss-Chebyshev
1646
+ quadrature. The sample points are the roots of the nth degree
1647
+ Chebyshev polynomial of the first kind, :math:`T_n(x)`. These
1648
+ sample points and weights correctly integrate polynomials of
1649
+ degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
1650
+ with weight function :math:`w(x) = 1/\sqrt{1 - x^2}`. See 22.2.4
1651
+ in [AS]_ for more details.
1652
+
1653
+ Parameters
1654
+ ----------
1655
+ n : int
1656
+ quadrature order
1657
+ mu : bool, optional
1658
+ If True, return the sum of the weights, optional.
1659
+
1660
+ Returns
1661
+ -------
1662
+ x : ndarray
1663
+ Sample points
1664
+ w : ndarray
1665
+ Weights
1666
+ mu : float
1667
+ Sum of the weights
1668
+
1669
+ See Also
1670
+ --------
1671
+ scipy.integrate.quadrature
1672
+ scipy.integrate.fixed_quad
1673
+ numpy.polynomial.chebyshev.chebgauss
1674
+
1675
+ References
1676
+ ----------
1677
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1678
+ Handbook of Mathematical Functions with Formulas,
1679
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1680
+
1681
+ """
1682
+ m = int(n)
1683
+ if n < 1 or n != m:
1684
+ raise ValueError('n must be a positive integer.')
1685
+ x = _ufuncs._sinpi(np.arange(-m + 1, m, 2) / (2*m))
1686
+ w = np.full_like(x, pi/m)
1687
+ if mu:
1688
+ return x, w, pi
1689
+ else:
1690
+ return x, w
1691
+
1692
+
1693
+ def chebyt(n, monic=False):
1694
+ r"""Chebyshev polynomial of the first kind.
1695
+
1696
+ Defined to be the solution of
1697
+
1698
+ .. math::
1699
+ (1 - x^2)\frac{d^2}{dx^2}T_n - x\frac{d}{dx}T_n + n^2T_n = 0;
1700
+
1701
+ :math:`T_n` is a polynomial of degree :math:`n`.
1702
+
1703
+ Parameters
1704
+ ----------
1705
+ n : int
1706
+ Degree of the polynomial.
1707
+ monic : bool, optional
1708
+ If `True`, scale the leading coefficient to be 1. Default is
1709
+ `False`.
1710
+
1711
+ Returns
1712
+ -------
1713
+ T : orthopoly1d
1714
+ Chebyshev polynomial of the first kind.
1715
+
1716
+ See Also
1717
+ --------
1718
+ chebyu : Chebyshev polynomial of the second kind.
1719
+
1720
+ Notes
1721
+ -----
1722
+ The polynomials :math:`T_n` are orthogonal over :math:`[-1, 1]`
1723
+ with weight function :math:`(1 - x^2)^{-1/2}`.
1724
+
1725
+ References
1726
+ ----------
1727
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1728
+ Handbook of Mathematical Functions with Formulas,
1729
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1730
+
1731
+ Examples
1732
+ --------
1733
+ Chebyshev polynomials of the first kind of order :math:`n` can
1734
+ be obtained as the determinant of specific :math:`n \times n`
1735
+ matrices. As an example we can check how the points obtained from
1736
+ the determinant of the following :math:`3 \times 3` matrix
1737
+ lay exactly on :math:`T_3`:
1738
+
1739
+ >>> import numpy as np
1740
+ >>> import matplotlib.pyplot as plt
1741
+ >>> from scipy.linalg import det
1742
+ >>> from scipy.special import chebyt
1743
+ >>> x = np.arange(-1.0, 1.0, 0.01)
1744
+ >>> fig, ax = plt.subplots()
1745
+ >>> ax.set_ylim(-2.0, 2.0)
1746
+ >>> ax.set_title(r'Chebyshev polynomial $T_3$')
1747
+ >>> ax.plot(x, chebyt(3)(x), label=rf'$T_3$')
1748
+ >>> for p in np.arange(-1.0, 1.0, 0.1):
1749
+ ... ax.plot(p,
1750
+ ... det(np.array([[p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
1751
+ ... 'rx')
1752
+ >>> plt.legend(loc='best')
1753
+ >>> plt.show()
1754
+
1755
+ They are also related to the Jacobi Polynomials
1756
+ :math:`P_n^{(-0.5, -0.5)}` through the relation:
1757
+
1758
+ .. math::
1759
+ P_n^{(-0.5, -0.5)}(x) = \frac{1}{4^n} \binom{2n}{n} T_n(x)
1760
+
1761
+ Let's verify it for :math:`n = 3`:
1762
+
1763
+ >>> from scipy.special import binom
1764
+ >>> from scipy.special import jacobi
1765
+ >>> x = np.arange(-1.0, 1.0, 0.01)
1766
+ >>> np.allclose(jacobi(3, -0.5, -0.5)(x),
1767
+ ... 1/64 * binom(6, 3) * chebyt(3)(x))
1768
+ True
1769
+
1770
+ We can plot the Chebyshev polynomials :math:`T_n` for some values
1771
+ of :math:`n`:
1772
+
1773
+ >>> x = np.arange(-1.5, 1.5, 0.01)
1774
+ >>> fig, ax = plt.subplots()
1775
+ >>> ax.set_ylim(-4.0, 4.0)
1776
+ >>> ax.set_title(r'Chebyshev polynomials $T_n$')
1777
+ >>> for n in np.arange(2,5):
1778
+ ... ax.plot(x, chebyt(n)(x), label=rf'$T_n={n}$')
1779
+ >>> plt.legend(loc='best')
1780
+ >>> plt.show()
1781
+
1782
+ """
1783
+ if n < 0:
1784
+ raise ValueError("n must be nonnegative.")
1785
+
1786
+ def wfunc(x):
1787
+ return 1.0 / sqrt(1 - x * x)
1788
+ if n == 0:
1789
+ return orthopoly1d([], [], pi, 1.0, wfunc, (-1, 1), monic,
1790
+ lambda x: _ufuncs.eval_chebyt(n, x))
1791
+ n1 = n
1792
+ x, w, mu = roots_chebyt(n1, mu=True)
1793
+ hn = pi / 2
1794
+ kn = 2**(n - 1)
1795
+ p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
1796
+ lambda x: _ufuncs.eval_chebyt(n, x))
1797
+ return p
1798
+
1799
+ # Chebyshev of the second kind
1800
+ # U_n(x) = (n+1)! sqrt(pi) / (2*_gam(n+3./2)) * P^(1/2,1/2)_n(x)
1801
+
1802
+
1803
+ def roots_chebyu(n, mu=False):
1804
+ r"""Gauss-Chebyshev (second kind) quadrature.
1805
+
1806
+ Computes the sample points and weights for Gauss-Chebyshev
1807
+ quadrature. The sample points are the roots of the nth degree
1808
+ Chebyshev polynomial of the second kind, :math:`U_n(x)`. These
1809
+ sample points and weights correctly integrate polynomials of
1810
+ degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
1811
+ with weight function :math:`w(x) = \sqrt{1 - x^2}`. See 22.2.5 in
1812
+ [AS]_ for details.
1813
+
1814
+ Parameters
1815
+ ----------
1816
+ n : int
1817
+ quadrature order
1818
+ mu : bool, optional
1819
+ If True, return the sum of the weights, optional.
1820
+
1821
+ Returns
1822
+ -------
1823
+ x : ndarray
1824
+ Sample points
1825
+ w : ndarray
1826
+ Weights
1827
+ mu : float
1828
+ Sum of the weights
1829
+
1830
+ See Also
1831
+ --------
1832
+ scipy.integrate.quadrature
1833
+ scipy.integrate.fixed_quad
1834
+
1835
+ References
1836
+ ----------
1837
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1838
+ Handbook of Mathematical Functions with Formulas,
1839
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1840
+
1841
+ """
1842
+ m = int(n)
1843
+ if n < 1 or n != m:
1844
+ raise ValueError('n must be a positive integer.')
1845
+ t = np.arange(m, 0, -1) * pi / (m + 1)
1846
+ x = np.cos(t)
1847
+ w = pi * np.sin(t)**2 / (m + 1)
1848
+ if mu:
1849
+ return x, w, pi / 2
1850
+ else:
1851
+ return x, w
1852
+
1853
+
1854
+ def chebyu(n, monic=False):
1855
+ r"""Chebyshev polynomial of the second kind.
1856
+
1857
+ Defined to be the solution of
1858
+
1859
+ .. math::
1860
+ (1 - x^2)\frac{d^2}{dx^2}U_n - 3x\frac{d}{dx}U_n
1861
+ + n(n + 2)U_n = 0;
1862
+
1863
+ :math:`U_n` is a polynomial of degree :math:`n`.
1864
+
1865
+ Parameters
1866
+ ----------
1867
+ n : int
1868
+ Degree of the polynomial.
1869
+ monic : bool, optional
1870
+ If `True`, scale the leading coefficient to be 1. Default is
1871
+ `False`.
1872
+
1873
+ Returns
1874
+ -------
1875
+ U : orthopoly1d
1876
+ Chebyshev polynomial of the second kind.
1877
+
1878
+ See Also
1879
+ --------
1880
+ chebyt : Chebyshev polynomial of the first kind.
1881
+
1882
+ Notes
1883
+ -----
1884
+ The polynomials :math:`U_n` are orthogonal over :math:`[-1, 1]`
1885
+ with weight function :math:`(1 - x^2)^{1/2}`.
1886
+
1887
+ References
1888
+ ----------
1889
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1890
+ Handbook of Mathematical Functions with Formulas,
1891
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1892
+
1893
+ Examples
1894
+ --------
1895
+ Chebyshev polynomials of the second kind of order :math:`n` can
1896
+ be obtained as the determinant of specific :math:`n \times n`
1897
+ matrices. As an example we can check how the points obtained from
1898
+ the determinant of the following :math:`3 \times 3` matrix
1899
+ lay exactly on :math:`U_3`:
1900
+
1901
+ >>> import numpy as np
1902
+ >>> import matplotlib.pyplot as plt
1903
+ >>> from scipy.linalg import det
1904
+ >>> from scipy.special import chebyu
1905
+ >>> x = np.arange(-1.0, 1.0, 0.01)
1906
+ >>> fig, ax = plt.subplots()
1907
+ >>> ax.set_ylim(-2.0, 2.0)
1908
+ >>> ax.set_title(r'Chebyshev polynomial $U_3$')
1909
+ >>> ax.plot(x, chebyu(3)(x), label=rf'$U_3$')
1910
+ >>> for p in np.arange(-1.0, 1.0, 0.1):
1911
+ ... ax.plot(p,
1912
+ ... det(np.array([[2*p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
1913
+ ... 'rx')
1914
+ >>> plt.legend(loc='best')
1915
+ >>> plt.show()
1916
+
1917
+ They satisfy the recurrence relation:
1918
+
1919
+ .. math::
1920
+ U_{2n-1}(x) = 2 T_n(x)U_{n-1}(x)
1921
+
1922
+ where the :math:`T_n` are the Chebyshev polynomial of the first kind.
1923
+ Let's verify it for :math:`n = 2`:
1924
+
1925
+ >>> from scipy.special import chebyt
1926
+ >>> x = np.arange(-1.0, 1.0, 0.01)
1927
+ >>> np.allclose(chebyu(3)(x), 2 * chebyt(2)(x) * chebyu(1)(x))
1928
+ True
1929
+
1930
+ We can plot the Chebyshev polynomials :math:`U_n` for some values
1931
+ of :math:`n`:
1932
+
1933
+ >>> x = np.arange(-1.0, 1.0, 0.01)
1934
+ >>> fig, ax = plt.subplots()
1935
+ >>> ax.set_ylim(-1.5, 1.5)
1936
+ >>> ax.set_title(r'Chebyshev polynomials $U_n$')
1937
+ >>> for n in np.arange(1,5):
1938
+ ... ax.plot(x, chebyu(n)(x), label=rf'$U_n={n}$')
1939
+ >>> plt.legend(loc='best')
1940
+ >>> plt.show()
1941
+
1942
+ """
1943
+ base = jacobi(n, 0.5, 0.5, monic=monic)
1944
+ if monic:
1945
+ return base
1946
+ factor = sqrt(pi) / 2.0 * _gam(n + 2) / _gam(n + 1.5)
1947
+ base._scale(factor)
1948
+ return base
1949
+
1950
+ # Chebyshev of the first kind C_n(x)
1951
+
1952
+
1953
+ def roots_chebyc(n, mu=False):
1954
+ r"""Gauss-Chebyshev (first kind) quadrature.
1955
+
1956
+ Compute the sample points and weights for Gauss-Chebyshev
1957
+ quadrature. The sample points are the roots of the nth degree
1958
+ Chebyshev polynomial of the first kind, :math:`C_n(x)`. These
1959
+ sample points and weights correctly integrate polynomials of
1960
+ degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
1961
+ with weight function :math:`w(x) = 1 / \sqrt{1 - (x/2)^2}`. See
1962
+ 22.2.6 in [AS]_ for more details.
1963
+
1964
+ Parameters
1965
+ ----------
1966
+ n : int
1967
+ quadrature order
1968
+ mu : bool, optional
1969
+ If True, return the sum of the weights, optional.
1970
+
1971
+ Returns
1972
+ -------
1973
+ x : ndarray
1974
+ Sample points
1975
+ w : ndarray
1976
+ Weights
1977
+ mu : float
1978
+ Sum of the weights
1979
+
1980
+ See Also
1981
+ --------
1982
+ scipy.integrate.quadrature
1983
+ scipy.integrate.fixed_quad
1984
+
1985
+ References
1986
+ ----------
1987
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
1988
+ Handbook of Mathematical Functions with Formulas,
1989
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
1990
+
1991
+ """
1992
+ x, w, m = roots_chebyt(n, True)
1993
+ x *= 2
1994
+ w *= 2
1995
+ m *= 2
1996
+ if mu:
1997
+ return x, w, m
1998
+ else:
1999
+ return x, w
2000
+
2001
+
2002
+ def chebyc(n, monic=False):
2003
+ r"""Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
2004
+
2005
+ Defined as :math:`C_n(x) = 2T_n(x/2)`, where :math:`T_n` is the
2006
+ nth Chebychev polynomial of the first kind.
2007
+
2008
+ Parameters
2009
+ ----------
2010
+ n : int
2011
+ Degree of the polynomial.
2012
+ monic : bool, optional
2013
+ If `True`, scale the leading coefficient to be 1. Default is
2014
+ `False`.
2015
+
2016
+ Returns
2017
+ -------
2018
+ C : orthopoly1d
2019
+ Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
2020
+
2021
+ See Also
2022
+ --------
2023
+ chebyt : Chebyshev polynomial of the first kind.
2024
+
2025
+ Notes
2026
+ -----
2027
+ The polynomials :math:`C_n(x)` are orthogonal over :math:`[-2, 2]`
2028
+ with weight function :math:`1/\sqrt{1 - (x/2)^2}`.
2029
+
2030
+ References
2031
+ ----------
2032
+ .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
2033
+ Section 22. National Bureau of Standards, 1972.
2034
+
2035
+ """
2036
+ if n < 0:
2037
+ raise ValueError("n must be nonnegative.")
2038
+
2039
+ if n == 0:
2040
+ n1 = n + 1
2041
+ else:
2042
+ n1 = n
2043
+ x, w = roots_chebyc(n1)
2044
+ if n == 0:
2045
+ x, w = [], []
2046
+ hn = 4 * pi * ((n == 0) + 1)
2047
+ kn = 1.0
2048
+ p = orthopoly1d(x, w, hn, kn,
2049
+ wfunc=lambda x: 1.0 / sqrt(1 - x * x / 4.0),
2050
+ limits=(-2, 2), monic=monic)
2051
+ if not monic:
2052
+ p._scale(2.0 / p(2))
2053
+ p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebyc(n, x)
2054
+ return p
2055
+
2056
+ # Chebyshev of the second kind S_n(x)
2057
+
2058
+
2059
+ def roots_chebys(n, mu=False):
2060
+ r"""Gauss-Chebyshev (second kind) quadrature.
2061
+
2062
+ Compute the sample points and weights for Gauss-Chebyshev
2063
+ quadrature. The sample points are the roots of the nth degree
2064
+ Chebyshev polynomial of the second kind, :math:`S_n(x)`. These
2065
+ sample points and weights correctly integrate polynomials of
2066
+ degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
2067
+ with weight function :math:`w(x) = \sqrt{1 - (x/2)^2}`. See 22.2.7
2068
+ in [AS]_ for more details.
2069
+
2070
+ Parameters
2071
+ ----------
2072
+ n : int
2073
+ quadrature order
2074
+ mu : bool, optional
2075
+ If True, return the sum of the weights, optional.
2076
+
2077
+ Returns
2078
+ -------
2079
+ x : ndarray
2080
+ Sample points
2081
+ w : ndarray
2082
+ Weights
2083
+ mu : float
2084
+ Sum of the weights
2085
+
2086
+ See Also
2087
+ --------
2088
+ scipy.integrate.quadrature
2089
+ scipy.integrate.fixed_quad
2090
+
2091
+ References
2092
+ ----------
2093
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
2094
+ Handbook of Mathematical Functions with Formulas,
2095
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
2096
+
2097
+ """
2098
+ x, w, m = roots_chebyu(n, True)
2099
+ x *= 2
2100
+ w *= 2
2101
+ m *= 2
2102
+ if mu:
2103
+ return x, w, m
2104
+ else:
2105
+ return x, w
2106
+
2107
+
2108
+ def chebys(n, monic=False):
2109
+ r"""Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
2110
+
2111
+ Defined as :math:`S_n(x) = U_n(x/2)` where :math:`U_n` is the
2112
+ nth Chebychev polynomial of the second kind.
2113
+
2114
+ Parameters
2115
+ ----------
2116
+ n : int
2117
+ Degree of the polynomial.
2118
+ monic : bool, optional
2119
+ If `True`, scale the leading coefficient to be 1. Default is
2120
+ `False`.
2121
+
2122
+ Returns
2123
+ -------
2124
+ S : orthopoly1d
2125
+ Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
2126
+
2127
+ See Also
2128
+ --------
2129
+ chebyu : Chebyshev polynomial of the second kind
2130
+
2131
+ Notes
2132
+ -----
2133
+ The polynomials :math:`S_n(x)` are orthogonal over :math:`[-2, 2]`
2134
+ with weight function :math:`\sqrt{1 - (x/2)}^2`.
2135
+
2136
+ References
2137
+ ----------
2138
+ .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
2139
+ Section 22. National Bureau of Standards, 1972.
2140
+
2141
+ """
2142
+ if n < 0:
2143
+ raise ValueError("n must be nonnegative.")
2144
+
2145
+ if n == 0:
2146
+ n1 = n + 1
2147
+ else:
2148
+ n1 = n
2149
+ x, w = roots_chebys(n1)
2150
+ if n == 0:
2151
+ x, w = [], []
2152
+ hn = pi
2153
+ kn = 1.0
2154
+ p = orthopoly1d(x, w, hn, kn,
2155
+ wfunc=lambda x: sqrt(1 - x * x / 4.0),
2156
+ limits=(-2, 2), monic=monic)
2157
+ if not monic:
2158
+ factor = (n + 1.0) / p(2)
2159
+ p._scale(factor)
2160
+ p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebys(n, x)
2161
+ return p
2162
+
2163
+ # Shifted Chebyshev of the first kind T^*_n(x)
2164
+
2165
+
2166
+ def roots_sh_chebyt(n, mu=False):
2167
+ r"""Gauss-Chebyshev (first kind, shifted) quadrature.
2168
+
2169
+ Compute the sample points and weights for Gauss-Chebyshev
2170
+ quadrature. The sample points are the roots of the nth degree
2171
+ shifted Chebyshev polynomial of the first kind, :math:`T_n(x)`.
2172
+ These sample points and weights correctly integrate polynomials of
2173
+ degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
2174
+ with weight function :math:`w(x) = 1/\sqrt{x - x^2}`. See 22.2.8
2175
+ in [AS]_ for more details.
2176
+
2177
+ Parameters
2178
+ ----------
2179
+ n : int
2180
+ quadrature order
2181
+ mu : bool, optional
2182
+ If True, return the sum of the weights, optional.
2183
+
2184
+ Returns
2185
+ -------
2186
+ x : ndarray
2187
+ Sample points
2188
+ w : ndarray
2189
+ Weights
2190
+ mu : float
2191
+ Sum of the weights
2192
+
2193
+ See Also
2194
+ --------
2195
+ scipy.integrate.quadrature
2196
+ scipy.integrate.fixed_quad
2197
+
2198
+ References
2199
+ ----------
2200
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
2201
+ Handbook of Mathematical Functions with Formulas,
2202
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
2203
+
2204
+ """
2205
+ xw = roots_chebyt(n, mu)
2206
+ return ((xw[0] + 1) / 2,) + xw[1:]
2207
+
2208
+
2209
+ def sh_chebyt(n, monic=False):
2210
+ r"""Shifted Chebyshev polynomial of the first kind.
2211
+
2212
+ Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
2213
+ Chebyshev polynomial of the first kind.
2214
+
2215
+ Parameters
2216
+ ----------
2217
+ n : int
2218
+ Degree of the polynomial.
2219
+ monic : bool, optional
2220
+ If `True`, scale the leading coefficient to be 1. Default is
2221
+ `False`.
2222
+
2223
+ Returns
2224
+ -------
2225
+ T : orthopoly1d
2226
+ Shifted Chebyshev polynomial of the first kind.
2227
+
2228
+ Notes
2229
+ -----
2230
+ The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
2231
+ with weight function :math:`(x - x^2)^{-1/2}`.
2232
+
2233
+ """
2234
+ base = sh_jacobi(n, 0.0, 0.5, monic=monic)
2235
+ if monic:
2236
+ return base
2237
+ if n > 0:
2238
+ factor = 4**n / 2.0
2239
+ else:
2240
+ factor = 1.0
2241
+ base._scale(factor)
2242
+ return base
2243
+
2244
+
2245
+ # Shifted Chebyshev of the second kind U^*_n(x)
2246
+ def roots_sh_chebyu(n, mu=False):
2247
+ r"""Gauss-Chebyshev (second kind, shifted) quadrature.
2248
+
2249
+ Computes the sample points and weights for Gauss-Chebyshev
2250
+ quadrature. The sample points are the roots of the nth degree
2251
+ shifted Chebyshev polynomial of the second kind, :math:`U_n(x)`.
2252
+ These sample points and weights correctly integrate polynomials of
2253
+ degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
2254
+ with weight function :math:`w(x) = \sqrt{x - x^2}`. See 22.2.9 in
2255
+ [AS]_ for more details.
2256
+
2257
+ Parameters
2258
+ ----------
2259
+ n : int
2260
+ quadrature order
2261
+ mu : bool, optional
2262
+ If True, return the sum of the weights, optional.
2263
+
2264
+ Returns
2265
+ -------
2266
+ x : ndarray
2267
+ Sample points
2268
+ w : ndarray
2269
+ Weights
2270
+ mu : float
2271
+ Sum of the weights
2272
+
2273
+ See Also
2274
+ --------
2275
+ scipy.integrate.quadrature
2276
+ scipy.integrate.fixed_quad
2277
+
2278
+ References
2279
+ ----------
2280
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
2281
+ Handbook of Mathematical Functions with Formulas,
2282
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
2283
+
2284
+ """
2285
+ x, w, m = roots_chebyu(n, True)
2286
+ x = (x + 1) / 2
2287
+ m_us = _ufuncs.beta(1.5, 1.5)
2288
+ w *= m_us / m
2289
+ if mu:
2290
+ return x, w, m_us
2291
+ else:
2292
+ return x, w
2293
+
2294
+
2295
+ def sh_chebyu(n, monic=False):
2296
+ r"""Shifted Chebyshev polynomial of the second kind.
2297
+
2298
+ Defined as :math:`U^*_n(x) = U_n(2x - 1)` for :math:`U_n` the nth
2299
+ Chebyshev polynomial of the second kind.
2300
+
2301
+ Parameters
2302
+ ----------
2303
+ n : int
2304
+ Degree of the polynomial.
2305
+ monic : bool, optional
2306
+ If `True`, scale the leading coefficient to be 1. Default is
2307
+ `False`.
2308
+
2309
+ Returns
2310
+ -------
2311
+ U : orthopoly1d
2312
+ Shifted Chebyshev polynomial of the second kind.
2313
+
2314
+ Notes
2315
+ -----
2316
+ The polynomials :math:`U^*_n` are orthogonal over :math:`[0, 1]`
2317
+ with weight function :math:`(x - x^2)^{1/2}`.
2318
+
2319
+ """
2320
+ base = sh_jacobi(n, 2.0, 1.5, monic=monic)
2321
+ if monic:
2322
+ return base
2323
+ factor = 4**n
2324
+ base._scale(factor)
2325
+ return base
2326
+
2327
+ # Legendre
2328
+
2329
+
2330
+ def roots_legendre(n, mu=False):
2331
+ r"""Gauss-Legendre quadrature.
2332
+
2333
+ Compute the sample points and weights for Gauss-Legendre
2334
+ quadrature [GL]_. The sample points are the roots of the nth degree
2335
+ Legendre polynomial :math:`P_n(x)`. These sample points and
2336
+ weights correctly integrate polynomials of degree :math:`2n - 1`
2337
+ or less over the interval :math:`[-1, 1]` with weight function
2338
+ :math:`w(x) = 1`. See 2.2.10 in [AS]_ for more details.
2339
+
2340
+ Parameters
2341
+ ----------
2342
+ n : int
2343
+ quadrature order
2344
+ mu : bool, optional
2345
+ If True, return the sum of the weights, optional.
2346
+
2347
+ Returns
2348
+ -------
2349
+ x : ndarray
2350
+ Sample points
2351
+ w : ndarray
2352
+ Weights
2353
+ mu : float
2354
+ Sum of the weights
2355
+
2356
+ See Also
2357
+ --------
2358
+ scipy.integrate.quadrature
2359
+ scipy.integrate.fixed_quad
2360
+ numpy.polynomial.legendre.leggauss
2361
+
2362
+ References
2363
+ ----------
2364
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
2365
+ Handbook of Mathematical Functions with Formulas,
2366
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
2367
+ .. [GL] Gauss-Legendre quadrature, Wikipedia,
2368
+ https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature
2369
+
2370
+ Examples
2371
+ --------
2372
+ >>> import numpy as np
2373
+ >>> from scipy.special import roots_legendre, eval_legendre
2374
+ >>> roots, weights = roots_legendre(9)
2375
+
2376
+ ``roots`` holds the roots, and ``weights`` holds the weights for
2377
+ Gauss-Legendre quadrature.
2378
+
2379
+ >>> roots
2380
+ array([-0.96816024, -0.83603111, -0.61337143, -0.32425342, 0. ,
2381
+ 0.32425342, 0.61337143, 0.83603111, 0.96816024])
2382
+ >>> weights
2383
+ array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936,
2384
+ 0.31234708, 0.2606107 , 0.18064816, 0.08127439])
2385
+
2386
+ Verify that we have the roots by evaluating the degree 9 Legendre
2387
+ polynomial at ``roots``. All the values are approximately zero:
2388
+
2389
+ >>> eval_legendre(9, roots)
2390
+ array([-8.88178420e-16, -2.22044605e-16, 1.11022302e-16, 1.11022302e-16,
2391
+ 0.00000000e+00, -5.55111512e-17, -1.94289029e-16, 1.38777878e-16,
2392
+ -8.32667268e-17])
2393
+
2394
+ Here we'll show how the above values can be used to estimate the
2395
+ integral from 1 to 2 of f(t) = t + 1/t with Gauss-Legendre
2396
+ quadrature [GL]_. First define the function and the integration
2397
+ limits.
2398
+
2399
+ >>> def f(t):
2400
+ ... return t + 1/t
2401
+ ...
2402
+ >>> a = 1
2403
+ >>> b = 2
2404
+
2405
+ We'll use ``integral(f(t), t=a, t=b)`` to denote the definite integral
2406
+ of f from t=a to t=b. The sample points in ``roots`` are from the
2407
+ interval [-1, 1], so we'll rewrite the integral with the simple change
2408
+ of variable::
2409
+
2410
+ x = 2/(b - a) * t - (a + b)/(b - a)
2411
+
2412
+ with inverse::
2413
+
2414
+ t = (b - a)/2 * x + (a + 2)/2
2415
+
2416
+ Then::
2417
+
2418
+ integral(f(t), a, b) =
2419
+ (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1)
2420
+
2421
+ We can approximate the latter integral with the values returned
2422
+ by `roots_legendre`.
2423
+
2424
+ Map the roots computed above from [-1, 1] to [a, b].
2425
+
2426
+ >>> t = (b - a)/2 * roots + (a + b)/2
2427
+
2428
+ Approximate the integral as the weighted sum of the function values.
2429
+
2430
+ >>> (b - a)/2 * f(t).dot(weights)
2431
+ 2.1931471805599276
2432
+
2433
+ Compare that to the exact result, which is 3/2 + log(2):
2434
+
2435
+ >>> 1.5 + np.log(2)
2436
+ 2.1931471805599454
2437
+
2438
+ """
2439
+ m = int(n)
2440
+ if n < 1 or n != m:
2441
+ raise ValueError("n must be a positive integer.")
2442
+
2443
+ mu0 = 2.0
2444
+ def an_func(k):
2445
+ return 0.0 * k
2446
+ def bn_func(k):
2447
+ return k * np.sqrt(1.0 / (4 * k * k - 1))
2448
+ f = _ufuncs.eval_legendre
2449
+ def df(n, x):
2450
+ return (-n * x * _ufuncs.eval_legendre(n, x)
2451
+ + n * _ufuncs.eval_legendre(n - 1, x)) / (1 - x ** 2)
2452
+ return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
2453
+
2454
+
2455
+ def legendre(n, monic=False):
2456
+ r"""Legendre polynomial.
2457
+
2458
+ Defined to be the solution of
2459
+
2460
+ .. math::
2461
+ \frac{d}{dx}\left[(1 - x^2)\frac{d}{dx}P_n(x)\right]
2462
+ + n(n + 1)P_n(x) = 0;
2463
+
2464
+ :math:`P_n(x)` is a polynomial of degree :math:`n`.
2465
+
2466
+ Parameters
2467
+ ----------
2468
+ n : int
2469
+ Degree of the polynomial.
2470
+ monic : bool, optional
2471
+ If `True`, scale the leading coefficient to be 1. Default is
2472
+ `False`.
2473
+
2474
+ Returns
2475
+ -------
2476
+ P : orthopoly1d
2477
+ Legendre polynomial.
2478
+
2479
+ Notes
2480
+ -----
2481
+ The polynomials :math:`P_n` are orthogonal over :math:`[-1, 1]`
2482
+ with weight function 1.
2483
+
2484
+ Examples
2485
+ --------
2486
+ Generate the 3rd-order Legendre polynomial 1/2*(5x^3 + 0x^2 - 3x + 0):
2487
+
2488
+ >>> from scipy.special import legendre
2489
+ >>> legendre(3)
2490
+ poly1d([ 2.5, 0. , -1.5, 0. ])
2491
+
2492
+ """
2493
+ if n < 0:
2494
+ raise ValueError("n must be nonnegative.")
2495
+
2496
+ if n == 0:
2497
+ n1 = n + 1
2498
+ else:
2499
+ n1 = n
2500
+ x, w = roots_legendre(n1)
2501
+ if n == 0:
2502
+ x, w = [], []
2503
+ hn = 2.0 / (2 * n + 1)
2504
+ kn = _gam(2 * n + 1) / _gam(n + 1)**2 / 2.0**n
2505
+ p = orthopoly1d(x, w, hn, kn, wfunc=lambda x: 1.0, limits=(-1, 1),
2506
+ monic=monic,
2507
+ eval_func=lambda x: _ufuncs.eval_legendre(n, x))
2508
+ return p
2509
+
2510
+ # Shifted Legendre P^*_n(x)
2511
+
2512
+
2513
+ def roots_sh_legendre(n, mu=False):
2514
+ r"""Gauss-Legendre (shifted) quadrature.
2515
+
2516
+ Compute the sample points and weights for Gauss-Legendre
2517
+ quadrature. The sample points are the roots of the nth degree
2518
+ shifted Legendre polynomial :math:`P^*_n(x)`. These sample points
2519
+ and weights correctly integrate polynomials of degree :math:`2n -
2520
+ 1` or less over the interval :math:`[0, 1]` with weight function
2521
+ :math:`w(x) = 1.0`. See 2.2.11 in [AS]_ for details.
2522
+
2523
+ Parameters
2524
+ ----------
2525
+ n : int
2526
+ quadrature order
2527
+ mu : bool, optional
2528
+ If True, return the sum of the weights, optional.
2529
+
2530
+ Returns
2531
+ -------
2532
+ x : ndarray
2533
+ Sample points
2534
+ w : ndarray
2535
+ Weights
2536
+ mu : float
2537
+ Sum of the weights
2538
+
2539
+ See Also
2540
+ --------
2541
+ scipy.integrate.quadrature
2542
+ scipy.integrate.fixed_quad
2543
+
2544
+ References
2545
+ ----------
2546
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
2547
+ Handbook of Mathematical Functions with Formulas,
2548
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
2549
+
2550
+ """
2551
+ x, w = roots_legendre(n)
2552
+ x = (x + 1) / 2
2553
+ w /= 2
2554
+ if mu:
2555
+ return x, w, 1.0
2556
+ else:
2557
+ return x, w
2558
+
2559
+
2560
+ def sh_legendre(n, monic=False):
2561
+ r"""Shifted Legendre polynomial.
2562
+
2563
+ Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth
2564
+ Legendre polynomial.
2565
+
2566
+ Parameters
2567
+ ----------
2568
+ n : int
2569
+ Degree of the polynomial.
2570
+ monic : bool, optional
2571
+ If `True`, scale the leading coefficient to be 1. Default is
2572
+ `False`.
2573
+
2574
+ Returns
2575
+ -------
2576
+ P : orthopoly1d
2577
+ Shifted Legendre polynomial.
2578
+
2579
+ Notes
2580
+ -----
2581
+ The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]`
2582
+ with weight function 1.
2583
+
2584
+ """
2585
+ if n < 0:
2586
+ raise ValueError("n must be nonnegative.")
2587
+
2588
+ def wfunc(x):
2589
+ return 0.0 * x + 1.0
2590
+ if n == 0:
2591
+ return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic,
2592
+ lambda x: _ufuncs.eval_sh_legendre(n, x))
2593
+ x, w = roots_sh_legendre(n)
2594
+ hn = 1.0 / (2 * n + 1.0)
2595
+ kn = _gam(2 * n + 1) / _gam(n + 1)**2
2596
+ p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic,
2597
+ eval_func=lambda x: _ufuncs.eval_sh_legendre(n, x))
2598
+ return p
2599
+
2600
+
2601
+ # Make the old root function names an alias for the new ones
2602
+ _modattrs = globals()
2603
+ for newfun, oldfun in _rootfuns_map.items():
2604
+ _modattrs[oldfun] = _modattrs[newfun]
2605
+ __all__.append(oldfun)
env-llmeval/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import (
3
+ Any,
4
+ Callable,
5
+ Literal,
6
+ Optional,
7
+ overload,
8
+ )
9
+
10
+ import numpy
11
+
12
+ _IntegerType = int | numpy.integer
13
+ _FloatingType = float | numpy.floating
14
+ _PointsAndWeights = tuple[numpy.ndarray, numpy.ndarray]
15
+ _PointsAndWeightsAndMu = tuple[numpy.ndarray, numpy.ndarray, float]
16
+
17
+ _ArrayLike0D = bool | int | float | complex | str | bytes | numpy.generic
18
+
19
+ __all__ = [
20
+ 'legendre',
21
+ 'chebyt',
22
+ 'chebyu',
23
+ 'chebyc',
24
+ 'chebys',
25
+ 'jacobi',
26
+ 'laguerre',
27
+ 'genlaguerre',
28
+ 'hermite',
29
+ 'hermitenorm',
30
+ 'gegenbauer',
31
+ 'sh_legendre',
32
+ 'sh_chebyt',
33
+ 'sh_chebyu',
34
+ 'sh_jacobi',
35
+ 'roots_legendre',
36
+ 'roots_chebyt',
37
+ 'roots_chebyu',
38
+ 'roots_chebyc',
39
+ 'roots_chebys',
40
+ 'roots_jacobi',
41
+ 'roots_laguerre',
42
+ 'roots_genlaguerre',
43
+ 'roots_hermite',
44
+ 'roots_hermitenorm',
45
+ 'roots_gegenbauer',
46
+ 'roots_sh_legendre',
47
+ 'roots_sh_chebyt',
48
+ 'roots_sh_chebyu',
49
+ 'roots_sh_jacobi',
50
+ ]
51
+
52
+ @overload
53
+ def roots_jacobi(
54
+ n: _IntegerType,
55
+ alpha: _FloatingType,
56
+ beta: _FloatingType,
57
+ ) -> _PointsAndWeights: ...
58
+ @overload
59
+ def roots_jacobi(
60
+ n: _IntegerType,
61
+ alpha: _FloatingType,
62
+ beta: _FloatingType,
63
+ mu: Literal[False],
64
+ ) -> _PointsAndWeights: ...
65
+ @overload
66
+ def roots_jacobi(
67
+ n: _IntegerType,
68
+ alpha: _FloatingType,
69
+ beta: _FloatingType,
70
+ mu: Literal[True],
71
+ ) -> _PointsAndWeightsAndMu: ...
72
+
73
+ @overload
74
+ def roots_sh_jacobi(
75
+ n: _IntegerType,
76
+ p1: _FloatingType,
77
+ q1: _FloatingType,
78
+ ) -> _PointsAndWeights: ...
79
+ @overload
80
+ def roots_sh_jacobi(
81
+ n: _IntegerType,
82
+ p1: _FloatingType,
83
+ q1: _FloatingType,
84
+ mu: Literal[False],
85
+ ) -> _PointsAndWeights: ...
86
+ @overload
87
+ def roots_sh_jacobi(
88
+ n: _IntegerType,
89
+ p1: _FloatingType,
90
+ q1: _FloatingType,
91
+ mu: Literal[True],
92
+ ) -> _PointsAndWeightsAndMu: ...
93
+
94
+ @overload
95
+ def roots_genlaguerre(
96
+ n: _IntegerType,
97
+ alpha: _FloatingType,
98
+ ) -> _PointsAndWeights: ...
99
+ @overload
100
+ def roots_genlaguerre(
101
+ n: _IntegerType,
102
+ alpha: _FloatingType,
103
+ mu: Literal[False],
104
+ ) -> _PointsAndWeights: ...
105
+ @overload
106
+ def roots_genlaguerre(
107
+ n: _IntegerType,
108
+ alpha: _FloatingType,
109
+ mu: Literal[True],
110
+ ) -> _PointsAndWeightsAndMu: ...
111
+
112
+ @overload
113
+ def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ...
114
+ @overload
115
+ def roots_laguerre(
116
+ n: _IntegerType,
117
+ mu: Literal[False],
118
+ ) -> _PointsAndWeights: ...
119
+ @overload
120
+ def roots_laguerre(
121
+ n: _IntegerType,
122
+ mu: Literal[True],
123
+ ) -> _PointsAndWeightsAndMu: ...
124
+
125
+ @overload
126
+ def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ...
127
+ @overload
128
+ def roots_hermite(
129
+ n: _IntegerType,
130
+ mu: Literal[False],
131
+ ) -> _PointsAndWeights: ...
132
+ @overload
133
+ def roots_hermite(
134
+ n: _IntegerType,
135
+ mu: Literal[True],
136
+ ) -> _PointsAndWeightsAndMu: ...
137
+
138
+ @overload
139
+ def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ...
140
+ @overload
141
+ def roots_hermitenorm(
142
+ n: _IntegerType,
143
+ mu: Literal[False],
144
+ ) -> _PointsAndWeights: ...
145
+ @overload
146
+ def roots_hermitenorm(
147
+ n: _IntegerType,
148
+ mu: Literal[True],
149
+ ) -> _PointsAndWeightsAndMu: ...
150
+
151
+ @overload
152
+ def roots_gegenbauer(
153
+ n: _IntegerType,
154
+ alpha: _FloatingType,
155
+ ) -> _PointsAndWeights: ...
156
+ @overload
157
+ def roots_gegenbauer(
158
+ n: _IntegerType,
159
+ alpha: _FloatingType,
160
+ mu: Literal[False],
161
+ ) -> _PointsAndWeights: ...
162
+ @overload
163
+ def roots_gegenbauer(
164
+ n: _IntegerType,
165
+ alpha: _FloatingType,
166
+ mu: Literal[True],
167
+ ) -> _PointsAndWeightsAndMu: ...
168
+
169
+ @overload
170
+ def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
171
+ @overload
172
+ def roots_chebyt(
173
+ n: _IntegerType,
174
+ mu: Literal[False],
175
+ ) -> _PointsAndWeights: ...
176
+ @overload
177
+ def roots_chebyt(
178
+ n: _IntegerType,
179
+ mu: Literal[True],
180
+ ) -> _PointsAndWeightsAndMu: ...
181
+
182
+ @overload
183
+ def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
184
+ @overload
185
+ def roots_chebyu(
186
+ n: _IntegerType,
187
+ mu: Literal[False],
188
+ ) -> _PointsAndWeights: ...
189
+ @overload
190
+ def roots_chebyu(
191
+ n: _IntegerType,
192
+ mu: Literal[True],
193
+ ) -> _PointsAndWeightsAndMu: ...
194
+
195
+ @overload
196
+ def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ...
197
+ @overload
198
+ def roots_chebyc(
199
+ n: _IntegerType,
200
+ mu: Literal[False],
201
+ ) -> _PointsAndWeights: ...
202
+ @overload
203
+ def roots_chebyc(
204
+ n: _IntegerType,
205
+ mu: Literal[True],
206
+ ) -> _PointsAndWeightsAndMu: ...
207
+
208
+ @overload
209
+ def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ...
210
+ @overload
211
+ def roots_chebys(
212
+ n: _IntegerType,
213
+ mu: Literal[False],
214
+ ) -> _PointsAndWeights: ...
215
+ @overload
216
+ def roots_chebys(
217
+ n: _IntegerType,
218
+ mu: Literal[True],
219
+ ) -> _PointsAndWeightsAndMu: ...
220
+
221
+ @overload
222
+ def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
223
+ @overload
224
+ def roots_sh_chebyt(
225
+ n: _IntegerType,
226
+ mu: Literal[False],
227
+ ) -> _PointsAndWeights: ...
228
+ @overload
229
+ def roots_sh_chebyt(
230
+ n: _IntegerType,
231
+ mu: Literal[True],
232
+ ) -> _PointsAndWeightsAndMu: ...
233
+
234
+ @overload
235
+ def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
236
+ @overload
237
+ def roots_sh_chebyu(
238
+ n: _IntegerType,
239
+ mu: Literal[False],
240
+ ) -> _PointsAndWeights: ...
241
+ @overload
242
+ def roots_sh_chebyu(
243
+ n: _IntegerType,
244
+ mu: Literal[True],
245
+ ) -> _PointsAndWeightsAndMu: ...
246
+
247
+ @overload
248
+ def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ...
249
+ @overload
250
+ def roots_legendre(
251
+ n: _IntegerType,
252
+ mu: Literal[False],
253
+ ) -> _PointsAndWeights: ...
254
+ @overload
255
+ def roots_legendre(
256
+ n: _IntegerType,
257
+ mu: Literal[True],
258
+ ) -> _PointsAndWeightsAndMu: ...
259
+
260
+ @overload
261
+ def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ...
262
+ @overload
263
+ def roots_sh_legendre(
264
+ n: _IntegerType,
265
+ mu: Literal[False],
266
+ ) -> _PointsAndWeights: ...
267
+ @overload
268
+ def roots_sh_legendre(
269
+ n: _IntegerType,
270
+ mu: Literal[True],
271
+ ) -> _PointsAndWeightsAndMu: ...
272
+
273
+ class orthopoly1d(numpy.poly1d):
274
+ def __init__(
275
+ self,
276
+ roots: numpy.typing.ArrayLike,
277
+ weights: numpy.typing.ArrayLike | None,
278
+ hn: float = ...,
279
+ kn: float = ...,
280
+ wfunc = Optional[Callable[[float], float]], # noqa: UP007
281
+ limits = tuple[float, float] | None,
282
+ monic: bool = ...,
283
+ eval_func: numpy.ufunc = ...,
284
+ ) -> None: ...
285
+ @property
286
+ def limits(self) -> tuple[float, float]: ...
287
+ def weight_func(self, x: float) -> float: ...
288
+ @overload
289
+ def __call__(self, x: _ArrayLike0D) -> Any: ...
290
+ @overload
291
+ def __call__(self, x: numpy.poly1d) -> numpy.poly1d: ... # type: ignore[misc]
292
+ @overload
293
+ def __call__(self, x: numpy.typing.ArrayLike) -> numpy.ndarray: ...
294
+
295
+ def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
296
+ def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
297
+ def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
298
+ def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
299
+ def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
300
+ def jacobi(
301
+ n: _IntegerType,
302
+ alpha: _FloatingType,
303
+ beta: _FloatingType,
304
+ monic: bool = ...,
305
+ ) -> orthopoly1d: ...
306
+ def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
307
+ def genlaguerre(
308
+ n: _IntegerType,
309
+ alpha: _FloatingType,
310
+ monic: bool = ...,
311
+ ) -> orthopoly1d: ...
312
+ def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
313
+ def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
314
+ def gegenbauer(
315
+ n: _IntegerType,
316
+ alpha: _FloatingType,
317
+ monic: bool = ...,
318
+ ) -> orthopoly1d: ...
319
+ def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
320
+ def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
321
+ def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
322
+ def sh_jacobi(
323
+ n: _IntegerType,
324
+ p: _FloatingType,
325
+ q: _FloatingType,
326
+ monic: bool = ...,
327
+ ) -> orthopoly1d: ...
328
+
329
+ # These functions are not public, but still need stubs because they
330
+ # get checked in the tests.
331
+ def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ...
env-llmeval/lib/python3.10/site-packages/scipy/special/_sf_error.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Warnings and Exceptions that can be raised by special functions."""
2
+ import warnings
3
+
4
+
5
+ class SpecialFunctionWarning(Warning):
6
+ """Warning that can be emitted by special functions."""
7
+ pass
8
+
9
+
10
+ warnings.simplefilter("always", category=SpecialFunctionWarning)
11
+
12
+
13
+ class SpecialFunctionError(Exception):
14
+ """Exception that can be raised by special functions."""
15
+ pass
env-llmeval/lib/python3.10/site-packages/scipy/special/_specfun.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (302 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_spfun_stats.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Last Change: Sat Mar 21 02:00 PM 2009 J
2
+
3
+ # Copyright (c) 2001, 2002 Enthought, Inc.
4
+ #
5
+ # All rights reserved.
6
+ #
7
+ # Redistribution and use in source and binary forms, with or without
8
+ # modification, are permitted provided that the following conditions are met:
9
+ #
10
+ # a. Redistributions of source code must retain the above copyright notice,
11
+ # this list of conditions and the following disclaimer.
12
+ # b. Redistributions in binary form must reproduce the above copyright
13
+ # notice, this list of conditions and the following disclaimer in the
14
+ # documentation and/or other materials provided with the distribution.
15
+ # c. Neither the name of the Enthought nor the names of its contributors
16
+ # may be used to endorse or promote products derived from this software
17
+ # without specific prior written permission.
18
+ #
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
24
+ # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29
+ # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
30
+ # DAMAGE.
31
+
32
+ """Some more special functions which may be useful for multivariate statistical
33
+ analysis."""
34
+
35
+ import numpy as np
36
+ from scipy.special import gammaln as loggam
37
+
38
+
39
+ __all__ = ['multigammaln']
40
+
41
+
42
+ def multigammaln(a, d):
43
+ r"""Returns the log of multivariate gamma, also sometimes called the
44
+ generalized gamma.
45
+
46
+ Parameters
47
+ ----------
48
+ a : ndarray
49
+ The multivariate gamma is computed for each item of `a`.
50
+ d : int
51
+ The dimension of the space of integration.
52
+
53
+ Returns
54
+ -------
55
+ res : ndarray
56
+ The values of the log multivariate gamma at the given points `a`.
57
+
58
+ Notes
59
+ -----
60
+ The formal definition of the multivariate gamma of dimension d for a real
61
+ `a` is
62
+
63
+ .. math::
64
+
65
+ \Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA
66
+
67
+ with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of
68
+ all the positive definite matrices of dimension `d`. Note that `a` is a
69
+ scalar: the integrand only is multivariate, the argument is not (the
70
+ function is defined over a subset of the real set).
71
+
72
+ This can be proven to be equal to the much friendlier equation
73
+
74
+ .. math::
75
+
76
+ \Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2).
77
+
78
+ References
79
+ ----------
80
+ R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in
81
+ probability and mathematical statistics).
82
+
83
+ Examples
84
+ --------
85
+ >>> import numpy as np
86
+ >>> from scipy.special import multigammaln, gammaln
87
+ >>> a = 23.5
88
+ >>> d = 10
89
+ >>> multigammaln(a, d)
90
+ 454.1488605074416
91
+
92
+ Verify that the result agrees with the logarithm of the equation
93
+ shown above:
94
+
95
+ >>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum()
96
+ 454.1488605074416
97
+ """
98
+ a = np.asarray(a)
99
+ if not np.isscalar(d) or (np.floor(d) != d):
100
+ raise ValueError("d should be a positive integer (dimension)")
101
+ if np.any(a <= 0.5 * (d - 1)):
102
+ raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met")
103
+
104
+ res = (d * (d-1) * 0.25) * np.log(np.pi)
105
+ res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0)
106
+ return res
env-llmeval/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from ._ufuncs import (_spherical_jn, _spherical_yn, _spherical_in,
3
+ _spherical_kn, _spherical_jn_d, _spherical_yn_d,
4
+ _spherical_in_d, _spherical_kn_d)
5
+
6
+ def spherical_jn(n, z, derivative=False):
7
+ r"""Spherical Bessel function of the first kind or its derivative.
8
+
9
+ Defined as [1]_,
10
+
11
+ .. math:: j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n + 1/2}(z),
12
+
13
+ where :math:`J_n` is the Bessel function of the first kind.
14
+
15
+ Parameters
16
+ ----------
17
+ n : int, array_like
18
+ Order of the Bessel function (n >= 0).
19
+ z : complex or float, array_like
20
+ Argument of the Bessel function.
21
+ derivative : bool, optional
22
+ If True, the value of the derivative (rather than the function
23
+ itself) is returned.
24
+
25
+ Returns
26
+ -------
27
+ jn : ndarray
28
+
29
+ Notes
30
+ -----
31
+ For real arguments greater than the order, the function is computed
32
+ using the ascending recurrence [2]_. For small real or complex
33
+ arguments, the definitional relation to the cylindrical Bessel function
34
+ of the first kind is used.
35
+
36
+ The derivative is computed using the relations [3]_,
37
+
38
+ .. math::
39
+ j_n'(z) = j_{n-1}(z) - \frac{n + 1}{z} j_n(z).
40
+
41
+ j_0'(z) = -j_1(z)
42
+
43
+
44
+ .. versionadded:: 0.18.0
45
+
46
+ References
47
+ ----------
48
+ .. [1] https://dlmf.nist.gov/10.47.E3
49
+ .. [2] https://dlmf.nist.gov/10.51.E1
50
+ .. [3] https://dlmf.nist.gov/10.51.E2
51
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
52
+ Handbook of Mathematical Functions with Formulas,
53
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
54
+
55
+ Examples
56
+ --------
57
+ The spherical Bessel functions of the first kind :math:`j_n` accept
58
+ both real and complex second argument. They can return a complex type:
59
+
60
+ >>> from scipy.special import spherical_jn
61
+ >>> spherical_jn(0, 3+5j)
62
+ (-9.878987731663194-8.021894345786002j)
63
+ >>> type(spherical_jn(0, 3+5j))
64
+ <class 'numpy.complex128'>
65
+
66
+ We can verify the relation for the derivative from the Notes
67
+ for :math:`n=3` in the interval :math:`[1, 2]`:
68
+
69
+ >>> import numpy as np
70
+ >>> x = np.arange(1.0, 2.0, 0.01)
71
+ >>> np.allclose(spherical_jn(3, x, True),
72
+ ... spherical_jn(2, x) - 4/x * spherical_jn(3, x))
73
+ True
74
+
75
+ The first few :math:`j_n` with real argument:
76
+
77
+ >>> import matplotlib.pyplot as plt
78
+ >>> x = np.arange(0.0, 10.0, 0.01)
79
+ >>> fig, ax = plt.subplots()
80
+ >>> ax.set_ylim(-0.5, 1.5)
81
+ >>> ax.set_title(r'Spherical Bessel functions $j_n$')
82
+ >>> for n in np.arange(0, 4):
83
+ ... ax.plot(x, spherical_jn(n, x), label=rf'$j_{n}$')
84
+ >>> plt.legend(loc='best')
85
+ >>> plt.show()
86
+
87
+ """
88
+ n = np.asarray(n, dtype=np.dtype("long"))
89
+ if derivative:
90
+ return _spherical_jn_d(n, z)
91
+ else:
92
+ return _spherical_jn(n, z)
93
+
94
+
95
+ def spherical_yn(n, z, derivative=False):
96
+ r"""Spherical Bessel function of the second kind or its derivative.
97
+
98
+ Defined as [1]_,
99
+
100
+ .. math:: y_n(z) = \sqrt{\frac{\pi}{2z}} Y_{n + 1/2}(z),
101
+
102
+ where :math:`Y_n` is the Bessel function of the second kind.
103
+
104
+ Parameters
105
+ ----------
106
+ n : int, array_like
107
+ Order of the Bessel function (n >= 0).
108
+ z : complex or float, array_like
109
+ Argument of the Bessel function.
110
+ derivative : bool, optional
111
+ If True, the value of the derivative (rather than the function
112
+ itself) is returned.
113
+
114
+ Returns
115
+ -------
116
+ yn : ndarray
117
+
118
+ Notes
119
+ -----
120
+ For real arguments, the function is computed using the ascending
121
+ recurrence [2]_. For complex arguments, the definitional relation to
122
+ the cylindrical Bessel function of the second kind is used.
123
+
124
+ The derivative is computed using the relations [3]_,
125
+
126
+ .. math::
127
+ y_n' = y_{n-1} - \frac{n + 1}{z} y_n.
128
+
129
+ y_0' = -y_1
130
+
131
+
132
+ .. versionadded:: 0.18.0
133
+
134
+ References
135
+ ----------
136
+ .. [1] https://dlmf.nist.gov/10.47.E4
137
+ .. [2] https://dlmf.nist.gov/10.51.E1
138
+ .. [3] https://dlmf.nist.gov/10.51.E2
139
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
140
+ Handbook of Mathematical Functions with Formulas,
141
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
142
+
143
+ Examples
144
+ --------
145
+ The spherical Bessel functions of the second kind :math:`y_n` accept
146
+ both real and complex second argument. They can return a complex type:
147
+
148
+ >>> from scipy.special import spherical_yn
149
+ >>> spherical_yn(0, 3+5j)
150
+ (8.022343088587197-9.880052589376795j)
151
+ >>> type(spherical_yn(0, 3+5j))
152
+ <class 'numpy.complex128'>
153
+
154
+ We can verify the relation for the derivative from the Notes
155
+ for :math:`n=3` in the interval :math:`[1, 2]`:
156
+
157
+ >>> import numpy as np
158
+ >>> x = np.arange(1.0, 2.0, 0.01)
159
+ >>> np.allclose(spherical_yn(3, x, True),
160
+ ... spherical_yn(2, x) - 4/x * spherical_yn(3, x))
161
+ True
162
+
163
+ The first few :math:`y_n` with real argument:
164
+
165
+ >>> import matplotlib.pyplot as plt
166
+ >>> x = np.arange(0.0, 10.0, 0.01)
167
+ >>> fig, ax = plt.subplots()
168
+ >>> ax.set_ylim(-2.0, 1.0)
169
+ >>> ax.set_title(r'Spherical Bessel functions $y_n$')
170
+ >>> for n in np.arange(0, 4):
171
+ ... ax.plot(x, spherical_yn(n, x), label=rf'$y_{n}$')
172
+ >>> plt.legend(loc='best')
173
+ >>> plt.show()
174
+
175
+ """
176
+ n = np.asarray(n, dtype=np.dtype("long"))
177
+ if derivative:
178
+ return _spherical_yn_d(n, z)
179
+ else:
180
+ return _spherical_yn(n, z)
181
+
182
+
183
+ def spherical_in(n, z, derivative=False):
184
+ r"""Modified spherical Bessel function of the first kind or its derivative.
185
+
186
+ Defined as [1]_,
187
+
188
+ .. math:: i_n(z) = \sqrt{\frac{\pi}{2z}} I_{n + 1/2}(z),
189
+
190
+ where :math:`I_n` is the modified Bessel function of the first kind.
191
+
192
+ Parameters
193
+ ----------
194
+ n : int, array_like
195
+ Order of the Bessel function (n >= 0).
196
+ z : complex or float, array_like
197
+ Argument of the Bessel function.
198
+ derivative : bool, optional
199
+ If True, the value of the derivative (rather than the function
200
+ itself) is returned.
201
+
202
+ Returns
203
+ -------
204
+ in : ndarray
205
+
206
+ Notes
207
+ -----
208
+ The function is computed using its definitional relation to the
209
+ modified cylindrical Bessel function of the first kind.
210
+
211
+ The derivative is computed using the relations [2]_,
212
+
213
+ .. math::
214
+ i_n' = i_{n-1} - \frac{n + 1}{z} i_n.
215
+
216
+ i_1' = i_0
217
+
218
+
219
+ .. versionadded:: 0.18.0
220
+
221
+ References
222
+ ----------
223
+ .. [1] https://dlmf.nist.gov/10.47.E7
224
+ .. [2] https://dlmf.nist.gov/10.51.E5
225
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
226
+ Handbook of Mathematical Functions with Formulas,
227
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
228
+
229
+ Examples
230
+ --------
231
+ The modified spherical Bessel functions of the first kind :math:`i_n`
232
+ accept both real and complex second argument.
233
+ They can return a complex type:
234
+
235
+ >>> from scipy.special import spherical_in
236
+ >>> spherical_in(0, 3+5j)
237
+ (-1.1689867793369182-1.2697305267234222j)
238
+ >>> type(spherical_in(0, 3+5j))
239
+ <class 'numpy.complex128'>
240
+
241
+ We can verify the relation for the derivative from the Notes
242
+ for :math:`n=3` in the interval :math:`[1, 2]`:
243
+
244
+ >>> import numpy as np
245
+ >>> x = np.arange(1.0, 2.0, 0.01)
246
+ >>> np.allclose(spherical_in(3, x, True),
247
+ ... spherical_in(2, x) - 4/x * spherical_in(3, x))
248
+ True
249
+
250
+ The first few :math:`i_n` with real argument:
251
+
252
+ >>> import matplotlib.pyplot as plt
253
+ >>> x = np.arange(0.0, 6.0, 0.01)
254
+ >>> fig, ax = plt.subplots()
255
+ >>> ax.set_ylim(-0.5, 5.0)
256
+ >>> ax.set_title(r'Modified spherical Bessel functions $i_n$')
257
+ >>> for n in np.arange(0, 4):
258
+ ... ax.plot(x, spherical_in(n, x), label=rf'$i_{n}$')
259
+ >>> plt.legend(loc='best')
260
+ >>> plt.show()
261
+
262
+ """
263
+ n = np.asarray(n, dtype=np.dtype("long"))
264
+ if derivative:
265
+ return _spherical_in_d(n, z)
266
+ else:
267
+ return _spherical_in(n, z)
268
+
269
+
270
+ def spherical_kn(n, z, derivative=False):
271
+ r"""Modified spherical Bessel function of the second kind or its derivative.
272
+
273
+ Defined as [1]_,
274
+
275
+ .. math:: k_n(z) = \sqrt{\frac{\pi}{2z}} K_{n + 1/2}(z),
276
+
277
+ where :math:`K_n` is the modified Bessel function of the second kind.
278
+
279
+ Parameters
280
+ ----------
281
+ n : int, array_like
282
+ Order of the Bessel function (n >= 0).
283
+ z : complex or float, array_like
284
+ Argument of the Bessel function.
285
+ derivative : bool, optional
286
+ If True, the value of the derivative (rather than the function
287
+ itself) is returned.
288
+
289
+ Returns
290
+ -------
291
+ kn : ndarray
292
+
293
+ Notes
294
+ -----
295
+ The function is computed using its definitional relation to the
296
+ modified cylindrical Bessel function of the second kind.
297
+
298
+ The derivative is computed using the relations [2]_,
299
+
300
+ .. math::
301
+ k_n' = -k_{n-1} - \frac{n + 1}{z} k_n.
302
+
303
+ k_0' = -k_1
304
+
305
+
306
+ .. versionadded:: 0.18.0
307
+
308
+ References
309
+ ----------
310
+ .. [1] https://dlmf.nist.gov/10.47.E9
311
+ .. [2] https://dlmf.nist.gov/10.51.E5
312
+ .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
313
+ Handbook of Mathematical Functions with Formulas,
314
+ Graphs, and Mathematical Tables. New York: Dover, 1972.
315
+
316
+ Examples
317
+ --------
318
+ The modified spherical Bessel functions of the second kind :math:`k_n`
319
+ accept both real and complex second argument.
320
+ They can return a complex type:
321
+
322
+ >>> from scipy.special import spherical_kn
323
+ >>> spherical_kn(0, 3+5j)
324
+ (0.012985785614001561+0.003354691603137546j)
325
+ >>> type(spherical_kn(0, 3+5j))
326
+ <class 'numpy.complex128'>
327
+
328
+ We can verify the relation for the derivative from the Notes
329
+ for :math:`n=3` in the interval :math:`[1, 2]`:
330
+
331
+ >>> import numpy as np
332
+ >>> x = np.arange(1.0, 2.0, 0.01)
333
+ >>> np.allclose(spherical_kn(3, x, True),
334
+ ... - 4/x * spherical_kn(3, x) - spherical_kn(2, x))
335
+ True
336
+
337
+ The first few :math:`k_n` with real argument:
338
+
339
+ >>> import matplotlib.pyplot as plt
340
+ >>> x = np.arange(0.0, 4.0, 0.01)
341
+ >>> fig, ax = plt.subplots()
342
+ >>> ax.set_ylim(0.0, 5.0)
343
+ >>> ax.set_title(r'Modified spherical Bessel functions $k_n$')
344
+ >>> for n in np.arange(0, 4):
345
+ ... ax.plot(x, spherical_kn(n, x), label=rf'$k_{n}$')
346
+ >>> plt.legend(loc='best')
347
+ >>> plt.show()
348
+
349
+ """
350
+ n = np.asarray(n, dtype=np.dtype("long"))
351
+ if derivative:
352
+ return _spherical_kn_d(n, z)
353
+ else:
354
+ return _spherical_kn(n, z)
env-llmeval/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import functools
4
+
5
+ import numpy as np
6
+ from scipy._lib._array_api import array_namespace, is_cupy, is_torch, is_numpy
7
+ from . import _ufuncs
8
+ # These don't really need to be imported, but otherwise IDEs might not realize
9
+ # that these are defined in this file / report an error in __init__.py
10
+ from ._ufuncs import (
11
+ log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, # noqa: F401
12
+ gammaln, gammainc, gammaincc, logit, expit) # noqa: F401
13
+
14
+ _SCIPY_ARRAY_API = os.environ.get("SCIPY_ARRAY_API", False)
15
+ array_api_compat_prefix = "scipy._lib.array_api_compat"
16
+
17
+
18
+ def get_array_special_func(f_name, xp, n_array_args):
19
+ if is_numpy(xp):
20
+ f = getattr(_ufuncs, f_name, None)
21
+ elif is_torch(xp):
22
+ f = getattr(xp.special, f_name, None)
23
+ elif is_cupy(xp):
24
+ import cupyx # type: ignore[import]
25
+ f = getattr(cupyx.scipy.special, f_name, None)
26
+ elif xp.__name__ == f"{array_api_compat_prefix}.jax":
27
+ f = getattr(xp.scipy.special, f_name, None)
28
+ else:
29
+ f_scipy = getattr(_ufuncs, f_name, None)
30
+ def f(*args, **kwargs):
31
+ array_args = args[:n_array_args]
32
+ other_args = args[n_array_args:]
33
+ array_args = [np.asarray(arg) for arg in array_args]
34
+ out = f_scipy(*array_args, *other_args, **kwargs)
35
+ return xp.asarray(out)
36
+
37
+ return f
38
+
39
+ # functools.wraps doesn't work because:
40
+ # 'numpy.ufunc' object has no attribute '__module__'
41
+ def support_alternative_backends(f_name, n_array_args):
42
+ func = getattr(_ufuncs, f_name)
43
+
44
+ @functools.wraps(func)
45
+ def wrapped(*args, **kwargs):
46
+ xp = array_namespace(*args[:n_array_args])
47
+ f = get_array_special_func(f_name, xp, n_array_args)
48
+ return f(*args, **kwargs)
49
+
50
+ return wrapped
51
+
52
+
53
+ array_special_func_map = {
54
+ 'log_ndtr': 1,
55
+ 'ndtr': 1,
56
+ 'ndtri': 1,
57
+ 'erf': 1,
58
+ 'erfc': 1,
59
+ 'i0': 1,
60
+ 'i0e': 1,
61
+ 'i1': 1,
62
+ 'i1e': 1,
63
+ 'gammaln': 1,
64
+ 'gammainc': 2,
65
+ 'gammaincc': 2,
66
+ 'logit': 1,
67
+ 'expit': 1,
68
+ }
69
+
70
+ for f_name, n_array_args in array_special_func_map.items():
71
+ f = (support_alternative_backends(f_name, n_array_args) if _SCIPY_ARRAY_API
72
+ else getattr(_ufuncs, f_name))
73
+ sys.modules[__name__].__dict__[f_name] = f
74
+
75
+ __all__ = list(array_special_func_map)
env-llmeval/lib/python3.10/site-packages/scipy/special/_test_internal.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (290 kB). View file
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_testutils.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import functools
3
+ import operator
4
+ from scipy._lib import _pep440
5
+
6
+ import numpy as np
7
+ from numpy.testing import assert_
8
+ import pytest
9
+
10
+ import scipy.special as sc
11
+
12
+ __all__ = ['with_special_errors', 'assert_func_equal', 'FuncData']
13
+
14
+
15
+ #------------------------------------------------------------------------------
16
+ # Check if a module is present to be used in tests
17
+ #------------------------------------------------------------------------------
18
+
19
+ class MissingModule:
20
+ def __init__(self, name):
21
+ self.name = name
22
+
23
+
24
+ def check_version(module, min_ver):
25
+ if type(module) == MissingModule:
26
+ return pytest.mark.skip(reason=f"{module.name} is not installed")
27
+ return pytest.mark.skipif(
28
+ _pep440.parse(module.__version__) < _pep440.Version(min_ver),
29
+ reason=f"{module.__name__} version >= {min_ver} required"
30
+ )
31
+
32
+
33
+ #------------------------------------------------------------------------------
34
+ # Enable convergence and loss of precision warnings -- turn off one by one
35
+ #------------------------------------------------------------------------------
36
+
37
+ def with_special_errors(func):
38
+ """
39
+ Enable special function errors (such as underflow, overflow,
40
+ loss of precision, etc.)
41
+ """
42
+ @functools.wraps(func)
43
+ def wrapper(*a, **kw):
44
+ with sc.errstate(all='raise'):
45
+ res = func(*a, **kw)
46
+ return res
47
+ return wrapper
48
+
49
+
50
+ #------------------------------------------------------------------------------
51
+ # Comparing function values at many data points at once, with helpful
52
+ # error reports
53
+ #------------------------------------------------------------------------------
54
+
55
+ def assert_func_equal(func, results, points, rtol=None, atol=None,
56
+ param_filter=None, knownfailure=None,
57
+ vectorized=True, dtype=None, nan_ok=False,
58
+ ignore_inf_sign=False, distinguish_nan_and_inf=True):
59
+ if hasattr(points, 'next'):
60
+ # it's a generator
61
+ points = list(points)
62
+
63
+ points = np.asarray(points)
64
+ if points.ndim == 1:
65
+ points = points[:,None]
66
+ nparams = points.shape[1]
67
+
68
+ if hasattr(results, '__name__'):
69
+ # function
70
+ data = points
71
+ result_columns = None
72
+ result_func = results
73
+ else:
74
+ # dataset
75
+ data = np.c_[points, results]
76
+ result_columns = list(range(nparams, data.shape[1]))
77
+ result_func = None
78
+
79
+ fdata = FuncData(func, data, list(range(nparams)),
80
+ result_columns=result_columns, result_func=result_func,
81
+ rtol=rtol, atol=atol, param_filter=param_filter,
82
+ knownfailure=knownfailure, nan_ok=nan_ok, vectorized=vectorized,
83
+ ignore_inf_sign=ignore_inf_sign,
84
+ distinguish_nan_and_inf=distinguish_nan_and_inf)
85
+ fdata.check()
86
+
87
+
88
+ class FuncData:
89
+ """
90
+ Data set for checking a special function.
91
+
92
+ Parameters
93
+ ----------
94
+ func : function
95
+ Function to test
96
+ data : numpy array
97
+ columnar data to use for testing
98
+ param_columns : int or tuple of ints
99
+ Columns indices in which the parameters to `func` lie.
100
+ Can be imaginary integers to indicate that the parameter
101
+ should be cast to complex.
102
+ result_columns : int or tuple of ints, optional
103
+ Column indices for expected results from `func`.
104
+ result_func : callable, optional
105
+ Function to call to obtain results.
106
+ rtol : float, optional
107
+ Required relative tolerance. Default is 5*eps.
108
+ atol : float, optional
109
+ Required absolute tolerance. Default is 5*tiny.
110
+ param_filter : function, or tuple of functions/Nones, optional
111
+ Filter functions to exclude some parameter ranges.
112
+ If omitted, no filtering is done.
113
+ knownfailure : str, optional
114
+ Known failure error message to raise when the test is run.
115
+ If omitted, no exception is raised.
116
+ nan_ok : bool, optional
117
+ If nan is always an accepted result.
118
+ vectorized : bool, optional
119
+ Whether all functions passed in are vectorized.
120
+ ignore_inf_sign : bool, optional
121
+ Whether to ignore signs of infinities.
122
+ (Doesn't matter for complex-valued functions.)
123
+ distinguish_nan_and_inf : bool, optional
124
+ If True, treat numbers which contain nans or infs as
125
+ equal. Sets ignore_inf_sign to be True.
126
+
127
+ """
128
+
129
+ def __init__(self, func, data, param_columns, result_columns=None,
130
+ result_func=None, rtol=None, atol=None, param_filter=None,
131
+ knownfailure=None, dataname=None, nan_ok=False, vectorized=True,
132
+ ignore_inf_sign=False, distinguish_nan_and_inf=True):
133
+ self.func = func
134
+ self.data = data
135
+ self.dataname = dataname
136
+ if not hasattr(param_columns, '__len__'):
137
+ param_columns = (param_columns,)
138
+ self.param_columns = tuple(param_columns)
139
+ if result_columns is not None:
140
+ if not hasattr(result_columns, '__len__'):
141
+ result_columns = (result_columns,)
142
+ self.result_columns = tuple(result_columns)
143
+ if result_func is not None:
144
+ message = "Only result_func or result_columns should be provided"
145
+ raise ValueError(message)
146
+ elif result_func is not None:
147
+ self.result_columns = None
148
+ else:
149
+ raise ValueError("Either result_func or result_columns should be provided")
150
+ self.result_func = result_func
151
+ self.rtol = rtol
152
+ self.atol = atol
153
+ if not hasattr(param_filter, '__len__'):
154
+ param_filter = (param_filter,)
155
+ self.param_filter = param_filter
156
+ self.knownfailure = knownfailure
157
+ self.nan_ok = nan_ok
158
+ self.vectorized = vectorized
159
+ self.ignore_inf_sign = ignore_inf_sign
160
+ self.distinguish_nan_and_inf = distinguish_nan_and_inf
161
+ if not self.distinguish_nan_and_inf:
162
+ self.ignore_inf_sign = True
163
+
164
+ def get_tolerances(self, dtype):
165
+ if not np.issubdtype(dtype, np.inexact):
166
+ dtype = np.dtype(float)
167
+ info = np.finfo(dtype)
168
+ rtol, atol = self.rtol, self.atol
169
+ if rtol is None:
170
+ rtol = 5*info.eps
171
+ if atol is None:
172
+ atol = 5*info.tiny
173
+ return rtol, atol
174
+
175
+ def check(self, data=None, dtype=None, dtypes=None):
176
+ """Check the special function against the data."""
177
+ __tracebackhide__ = operator.methodcaller(
178
+ 'errisinstance', AssertionError
179
+ )
180
+
181
+ if self.knownfailure:
182
+ pytest.xfail(reason=self.knownfailure)
183
+
184
+ if data is None:
185
+ data = self.data
186
+
187
+ if dtype is None:
188
+ dtype = data.dtype
189
+ else:
190
+ data = data.astype(dtype)
191
+
192
+ rtol, atol = self.get_tolerances(dtype)
193
+
194
+ # Apply given filter functions
195
+ if self.param_filter:
196
+ param_mask = np.ones((data.shape[0],), np.bool_)
197
+ for j, filter in zip(self.param_columns, self.param_filter):
198
+ if filter:
199
+ param_mask &= list(filter(data[:,j]))
200
+ data = data[param_mask]
201
+
202
+ # Pick parameters from the correct columns
203
+ params = []
204
+ for idx, j in enumerate(self.param_columns):
205
+ if np.iscomplexobj(j):
206
+ j = int(j.imag)
207
+ params.append(data[:,j].astype(complex))
208
+ elif dtypes and idx < len(dtypes):
209
+ params.append(data[:, j].astype(dtypes[idx]))
210
+ else:
211
+ params.append(data[:,j])
212
+
213
+ # Helper for evaluating results
214
+ def eval_func_at_params(func, skip_mask=None):
215
+ if self.vectorized:
216
+ got = func(*params)
217
+ else:
218
+ got = []
219
+ for j in range(len(params[0])):
220
+ if skip_mask is not None and skip_mask[j]:
221
+ got.append(np.nan)
222
+ continue
223
+ got.append(func(*tuple([params[i][j] for i in range(len(params))])))
224
+ got = np.asarray(got)
225
+ if not isinstance(got, tuple):
226
+ got = (got,)
227
+ return got
228
+
229
+ # Evaluate function to be tested
230
+ got = eval_func_at_params(self.func)
231
+
232
+ # Grab the correct results
233
+ if self.result_columns is not None:
234
+ # Correct results passed in with the data
235
+ wanted = tuple([data[:,icol] for icol in self.result_columns])
236
+ else:
237
+ # Function producing correct results passed in
238
+ skip_mask = None
239
+ if self.nan_ok and len(got) == 1:
240
+ # Don't spend time evaluating what doesn't need to be evaluated
241
+ skip_mask = np.isnan(got[0])
242
+ wanted = eval_func_at_params(self.result_func, skip_mask=skip_mask)
243
+
244
+ # Check the validity of each output returned
245
+ assert_(len(got) == len(wanted))
246
+
247
+ for output_num, (x, y) in enumerate(zip(got, wanted)):
248
+ if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign:
249
+ pinf_x = np.isinf(x)
250
+ pinf_y = np.isinf(y)
251
+ minf_x = np.isinf(x)
252
+ minf_y = np.isinf(y)
253
+ else:
254
+ pinf_x = np.isposinf(x)
255
+ pinf_y = np.isposinf(y)
256
+ minf_x = np.isneginf(x)
257
+ minf_y = np.isneginf(y)
258
+ nan_x = np.isnan(x)
259
+ nan_y = np.isnan(y)
260
+
261
+ with np.errstate(all='ignore'):
262
+ abs_y = np.absolute(y)
263
+ abs_y[~np.isfinite(abs_y)] = 0
264
+ diff = np.absolute(x - y)
265
+ diff[~np.isfinite(diff)] = 0
266
+
267
+ rdiff = diff / np.absolute(y)
268
+ rdiff[~np.isfinite(rdiff)] = 0
269
+
270
+ tol_mask = (diff <= atol + rtol*abs_y)
271
+ pinf_mask = (pinf_x == pinf_y)
272
+ minf_mask = (minf_x == minf_y)
273
+
274
+ nan_mask = (nan_x == nan_y)
275
+
276
+ bad_j = ~(tol_mask & pinf_mask & minf_mask & nan_mask)
277
+
278
+ point_count = bad_j.size
279
+ if self.nan_ok:
280
+ bad_j &= ~nan_x
281
+ bad_j &= ~nan_y
282
+ point_count -= (nan_x | nan_y).sum()
283
+
284
+ if not self.distinguish_nan_and_inf and not self.nan_ok:
285
+ # If nan's are okay we've already covered all these cases
286
+ inf_x = np.isinf(x)
287
+ inf_y = np.isinf(y)
288
+ both_nonfinite = (inf_x & nan_y) | (nan_x & inf_y)
289
+ bad_j &= ~both_nonfinite
290
+ point_count -= both_nonfinite.sum()
291
+
292
+ if np.any(bad_j):
293
+ # Some bad results: inform what, where, and how bad
294
+ msg = [""]
295
+ msg.append("Max |adiff|: %g" % diff[bad_j].max())
296
+ msg.append("Max |rdiff|: %g" % rdiff[bad_j].max())
297
+ msg.append("Bad results (%d out of %d) for the following points "
298
+ "(in output %d):"
299
+ % (np.sum(bad_j), point_count, output_num,))
300
+ for j in np.nonzero(bad_j)[0]:
301
+ j = int(j)
302
+ def fmt(x):
303
+ return '%30s' % np.array2string(x[j], precision=18)
304
+ a = " ".join(map(fmt, params))
305
+ b = " ".join(map(fmt, got))
306
+ c = " ".join(map(fmt, wanted))
307
+ d = fmt(rdiff)
308
+ msg.append(f"{a} => {b} != {c} (rdiff {d})")
309
+ assert_(False, "\n".join(msg))
310
+
311
+ def __repr__(self):
312
+ """Pretty-printing, esp. for Nose output"""
313
+ if np.any(list(map(np.iscomplexobj, self.param_columns))):
314
+ is_complex = " (complex)"
315
+ else:
316
+ is_complex = ""
317
+ if self.dataname:
318
+ return "<Data for {}{}: {}>".format(self.func.__name__, is_complex,
319
+ os.path.basename(self.dataname))
320
+ else:
321
+ return f"<Data for {self.func.__name__}{is_complex}>"
env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically generated by _generate_pyx.py.
2
+ # Do not edit manually!
3
+
4
+ from typing import Any, Dict
5
+
6
+ import numpy as np
7
+
8
+ __all__ = [
9
+ 'geterr',
10
+ 'seterr',
11
+ 'errstate',
12
+ 'agm',
13
+ 'airy',
14
+ 'airye',
15
+ 'bdtr',
16
+ 'bdtrc',
17
+ 'bdtri',
18
+ 'bdtrik',
19
+ 'bdtrin',
20
+ 'bei',
21
+ 'beip',
22
+ 'ber',
23
+ 'berp',
24
+ 'besselpoly',
25
+ 'beta',
26
+ 'betainc',
27
+ 'betaincc',
28
+ 'betainccinv',
29
+ 'betaincinv',
30
+ 'betaln',
31
+ 'binom',
32
+ 'boxcox',
33
+ 'boxcox1p',
34
+ 'btdtr',
35
+ 'btdtri',
36
+ 'btdtria',
37
+ 'btdtrib',
38
+ 'cbrt',
39
+ 'chdtr',
40
+ 'chdtrc',
41
+ 'chdtri',
42
+ 'chdtriv',
43
+ 'chndtr',
44
+ 'chndtridf',
45
+ 'chndtrinc',
46
+ 'chndtrix',
47
+ 'cosdg',
48
+ 'cosm1',
49
+ 'cotdg',
50
+ 'dawsn',
51
+ 'ellipe',
52
+ 'ellipeinc',
53
+ 'ellipj',
54
+ 'ellipk',
55
+ 'ellipkinc',
56
+ 'ellipkm1',
57
+ 'elliprc',
58
+ 'elliprd',
59
+ 'elliprf',
60
+ 'elliprg',
61
+ 'elliprj',
62
+ 'entr',
63
+ 'erf',
64
+ 'erfc',
65
+ 'erfcinv',
66
+ 'erfcx',
67
+ 'erfi',
68
+ 'erfinv',
69
+ 'eval_chebyc',
70
+ 'eval_chebys',
71
+ 'eval_chebyt',
72
+ 'eval_chebyu',
73
+ 'eval_gegenbauer',
74
+ 'eval_genlaguerre',
75
+ 'eval_hermite',
76
+ 'eval_hermitenorm',
77
+ 'eval_jacobi',
78
+ 'eval_laguerre',
79
+ 'eval_legendre',
80
+ 'eval_sh_chebyt',
81
+ 'eval_sh_chebyu',
82
+ 'eval_sh_jacobi',
83
+ 'eval_sh_legendre',
84
+ 'exp1',
85
+ 'exp10',
86
+ 'exp2',
87
+ 'expi',
88
+ 'expit',
89
+ 'expm1',
90
+ 'expn',
91
+ 'exprel',
92
+ 'fdtr',
93
+ 'fdtrc',
94
+ 'fdtri',
95
+ 'fdtridfd',
96
+ 'fresnel',
97
+ 'gamma',
98
+ 'gammainc',
99
+ 'gammaincc',
100
+ 'gammainccinv',
101
+ 'gammaincinv',
102
+ 'gammaln',
103
+ 'gammasgn',
104
+ 'gdtr',
105
+ 'gdtrc',
106
+ 'gdtria',
107
+ 'gdtrib',
108
+ 'gdtrix',
109
+ 'hankel1',
110
+ 'hankel1e',
111
+ 'hankel2',
112
+ 'hankel2e',
113
+ 'huber',
114
+ 'hyp0f1',
115
+ 'hyp1f1',
116
+ 'hyp2f1',
117
+ 'hyperu',
118
+ 'i0',
119
+ 'i0e',
120
+ 'i1',
121
+ 'i1e',
122
+ 'inv_boxcox',
123
+ 'inv_boxcox1p',
124
+ 'it2i0k0',
125
+ 'it2j0y0',
126
+ 'it2struve0',
127
+ 'itairy',
128
+ 'iti0k0',
129
+ 'itj0y0',
130
+ 'itmodstruve0',
131
+ 'itstruve0',
132
+ 'iv',
133
+ 'ive',
134
+ 'j0',
135
+ 'j1',
136
+ 'jn',
137
+ 'jv',
138
+ 'jve',
139
+ 'k0',
140
+ 'k0e',
141
+ 'k1',
142
+ 'k1e',
143
+ 'kei',
144
+ 'keip',
145
+ 'kelvin',
146
+ 'ker',
147
+ 'kerp',
148
+ 'kl_div',
149
+ 'kn',
150
+ 'kolmogi',
151
+ 'kolmogorov',
152
+ 'kv',
153
+ 'kve',
154
+ 'log1p',
155
+ 'log_expit',
156
+ 'log_ndtr',
157
+ 'loggamma',
158
+ 'logit',
159
+ 'lpmv',
160
+ 'mathieu_a',
161
+ 'mathieu_b',
162
+ 'mathieu_cem',
163
+ 'mathieu_modcem1',
164
+ 'mathieu_modcem2',
165
+ 'mathieu_modsem1',
166
+ 'mathieu_modsem2',
167
+ 'mathieu_sem',
168
+ 'modfresnelm',
169
+ 'modfresnelp',
170
+ 'modstruve',
171
+ 'nbdtr',
172
+ 'nbdtrc',
173
+ 'nbdtri',
174
+ 'nbdtrik',
175
+ 'nbdtrin',
176
+ 'ncfdtr',
177
+ 'ncfdtri',
178
+ 'ncfdtridfd',
179
+ 'ncfdtridfn',
180
+ 'ncfdtrinc',
181
+ 'nctdtr',
182
+ 'nctdtridf',
183
+ 'nctdtrinc',
184
+ 'nctdtrit',
185
+ 'ndtr',
186
+ 'ndtri',
187
+ 'ndtri_exp',
188
+ 'nrdtrimn',
189
+ 'nrdtrisd',
190
+ 'obl_ang1',
191
+ 'obl_ang1_cv',
192
+ 'obl_cv',
193
+ 'obl_rad1',
194
+ 'obl_rad1_cv',
195
+ 'obl_rad2',
196
+ 'obl_rad2_cv',
197
+ 'owens_t',
198
+ 'pbdv',
199
+ 'pbvv',
200
+ 'pbwa',
201
+ 'pdtr',
202
+ 'pdtrc',
203
+ 'pdtri',
204
+ 'pdtrik',
205
+ 'poch',
206
+ 'powm1',
207
+ 'pro_ang1',
208
+ 'pro_ang1_cv',
209
+ 'pro_cv',
210
+ 'pro_rad1',
211
+ 'pro_rad1_cv',
212
+ 'pro_rad2',
213
+ 'pro_rad2_cv',
214
+ 'pseudo_huber',
215
+ 'psi',
216
+ 'radian',
217
+ 'rel_entr',
218
+ 'rgamma',
219
+ 'round',
220
+ 'shichi',
221
+ 'sici',
222
+ 'sindg',
223
+ 'smirnov',
224
+ 'smirnovi',
225
+ 'spence',
226
+ 'sph_harm',
227
+ 'stdtr',
228
+ 'stdtridf',
229
+ 'stdtrit',
230
+ 'struve',
231
+ 'tandg',
232
+ 'tklmbda',
233
+ 'voigt_profile',
234
+ 'wofz',
235
+ 'wright_bessel',
236
+ 'wrightomega',
237
+ 'xlog1py',
238
+ 'xlogy',
239
+ 'y0',
240
+ 'y1',
241
+ 'yn',
242
+ 'yv',
243
+ 'yve',
244
+ 'zetac'
245
+ ]
246
+
247
+ def geterr() -> Dict[str, str]: ...
248
+ def seterr(**kwargs: str) -> Dict[str, str]: ...
249
+
250
+ class errstate:
251
+ def __init__(self, **kargs: str) -> None: ...
252
+ def __enter__(self) -> None: ...
253
+ def __exit__(
254
+ self,
255
+ exc_type: Any, # Unused
256
+ exc_value: Any, # Unused
257
+ traceback: Any, # Unused
258
+ ) -> None: ...
259
+
260
+ _cosine_cdf: np.ufunc
261
+ _cosine_invcdf: np.ufunc
262
+ _cospi: np.ufunc
263
+ _ellip_harm: np.ufunc
264
+ _factorial: np.ufunc
265
+ _igam_fac: np.ufunc
266
+ _kolmogc: np.ufunc
267
+ _kolmogci: np.ufunc
268
+ _kolmogp: np.ufunc
269
+ _lambertw: np.ufunc
270
+ _lanczos_sum_expg_scaled: np.ufunc
271
+ _lgam1p: np.ufunc
272
+ _log1pmx: np.ufunc
273
+ _riemann_zeta: np.ufunc
274
+ _scaled_exp1: np.ufunc
275
+ _sf_error_test_function: np.ufunc
276
+ _sinpi: np.ufunc
277
+ _smirnovc: np.ufunc
278
+ _smirnovci: np.ufunc
279
+ _smirnovp: np.ufunc
280
+ _spherical_in: np.ufunc
281
+ _spherical_in_d: np.ufunc
282
+ _spherical_jn: np.ufunc
283
+ _spherical_jn_d: np.ufunc
284
+ _spherical_kn: np.ufunc
285
+ _spherical_kn_d: np.ufunc
286
+ _spherical_yn: np.ufunc
287
+ _spherical_yn_d: np.ufunc
288
+ _stirling2_inexact: np.ufunc
289
+ _struve_asymp_large_z: np.ufunc
290
+ _struve_bessel_series: np.ufunc
291
+ _struve_power_series: np.ufunc
292
+ _zeta: np.ufunc
293
+ agm: np.ufunc
294
+ airy: np.ufunc
295
+ airye: np.ufunc
296
+ bdtr: np.ufunc
297
+ bdtrc: np.ufunc
298
+ bdtri: np.ufunc
299
+ bdtrik: np.ufunc
300
+ bdtrin: np.ufunc
301
+ bei: np.ufunc
302
+ beip: np.ufunc
303
+ ber: np.ufunc
304
+ berp: np.ufunc
305
+ besselpoly: np.ufunc
306
+ beta: np.ufunc
307
+ betainc: np.ufunc
308
+ betaincc: np.ufunc
309
+ betainccinv: np.ufunc
310
+ betaincinv: np.ufunc
311
+ betaln: np.ufunc
312
+ binom: np.ufunc
313
+ boxcox1p: np.ufunc
314
+ boxcox: np.ufunc
315
+ btdtr: np.ufunc
316
+ btdtri: np.ufunc
317
+ btdtria: np.ufunc
318
+ btdtrib: np.ufunc
319
+ cbrt: np.ufunc
320
+ chdtr: np.ufunc
321
+ chdtrc: np.ufunc
322
+ chdtri: np.ufunc
323
+ chdtriv: np.ufunc
324
+ chndtr: np.ufunc
325
+ chndtridf: np.ufunc
326
+ chndtrinc: np.ufunc
327
+ chndtrix: np.ufunc
328
+ cosdg: np.ufunc
329
+ cosm1: np.ufunc
330
+ cotdg: np.ufunc
331
+ dawsn: np.ufunc
332
+ ellipe: np.ufunc
333
+ ellipeinc: np.ufunc
334
+ ellipj: np.ufunc
335
+ ellipk: np.ufunc
336
+ ellipkinc: np.ufunc
337
+ ellipkm1: np.ufunc
338
+ elliprc: np.ufunc
339
+ elliprd: np.ufunc
340
+ elliprf: np.ufunc
341
+ elliprg: np.ufunc
342
+ elliprj: np.ufunc
343
+ entr: np.ufunc
344
+ erf: np.ufunc
345
+ erfc: np.ufunc
346
+ erfcinv: np.ufunc
347
+ erfcx: np.ufunc
348
+ erfi: np.ufunc
349
+ erfinv: np.ufunc
350
+ eval_chebyc: np.ufunc
351
+ eval_chebys: np.ufunc
352
+ eval_chebyt: np.ufunc
353
+ eval_chebyu: np.ufunc
354
+ eval_gegenbauer: np.ufunc
355
+ eval_genlaguerre: np.ufunc
356
+ eval_hermite: np.ufunc
357
+ eval_hermitenorm: np.ufunc
358
+ eval_jacobi: np.ufunc
359
+ eval_laguerre: np.ufunc
360
+ eval_legendre: np.ufunc
361
+ eval_sh_chebyt: np.ufunc
362
+ eval_sh_chebyu: np.ufunc
363
+ eval_sh_jacobi: np.ufunc
364
+ eval_sh_legendre: np.ufunc
365
+ exp10: np.ufunc
366
+ exp1: np.ufunc
367
+ exp2: np.ufunc
368
+ expi: np.ufunc
369
+ expit: np.ufunc
370
+ expm1: np.ufunc
371
+ expn: np.ufunc
372
+ exprel: np.ufunc
373
+ fdtr: np.ufunc
374
+ fdtrc: np.ufunc
375
+ fdtri: np.ufunc
376
+ fdtridfd: np.ufunc
377
+ fresnel: np.ufunc
378
+ gamma: np.ufunc
379
+ gammainc: np.ufunc
380
+ gammaincc: np.ufunc
381
+ gammainccinv: np.ufunc
382
+ gammaincinv: np.ufunc
383
+ gammaln: np.ufunc
384
+ gammasgn: np.ufunc
385
+ gdtr: np.ufunc
386
+ gdtrc: np.ufunc
387
+ gdtria: np.ufunc
388
+ gdtrib: np.ufunc
389
+ gdtrix: np.ufunc
390
+ hankel1: np.ufunc
391
+ hankel1e: np.ufunc
392
+ hankel2: np.ufunc
393
+ hankel2e: np.ufunc
394
+ huber: np.ufunc
395
+ hyp0f1: np.ufunc
396
+ hyp1f1: np.ufunc
397
+ hyp2f1: np.ufunc
398
+ hyperu: np.ufunc
399
+ i0: np.ufunc
400
+ i0e: np.ufunc
401
+ i1: np.ufunc
402
+ i1e: np.ufunc
403
+ inv_boxcox1p: np.ufunc
404
+ inv_boxcox: np.ufunc
405
+ it2i0k0: np.ufunc
406
+ it2j0y0: np.ufunc
407
+ it2struve0: np.ufunc
408
+ itairy: np.ufunc
409
+ iti0k0: np.ufunc
410
+ itj0y0: np.ufunc
411
+ itmodstruve0: np.ufunc
412
+ itstruve0: np.ufunc
413
+ iv: np.ufunc
414
+ ive: np.ufunc
415
+ j0: np.ufunc
416
+ j1: np.ufunc
417
+ jn: np.ufunc
418
+ jv: np.ufunc
419
+ jve: np.ufunc
420
+ k0: np.ufunc
421
+ k0e: np.ufunc
422
+ k1: np.ufunc
423
+ k1e: np.ufunc
424
+ kei: np.ufunc
425
+ keip: np.ufunc
426
+ kelvin: np.ufunc
427
+ ker: np.ufunc
428
+ kerp: np.ufunc
429
+ kl_div: np.ufunc
430
+ kn: np.ufunc
431
+ kolmogi: np.ufunc
432
+ kolmogorov: np.ufunc
433
+ kv: np.ufunc
434
+ kve: np.ufunc
435
+ log1p: np.ufunc
436
+ log_expit: np.ufunc
437
+ log_ndtr: np.ufunc
438
+ loggamma: np.ufunc
439
+ logit: np.ufunc
440
+ lpmv: np.ufunc
441
+ mathieu_a: np.ufunc
442
+ mathieu_b: np.ufunc
443
+ mathieu_cem: np.ufunc
444
+ mathieu_modcem1: np.ufunc
445
+ mathieu_modcem2: np.ufunc
446
+ mathieu_modsem1: np.ufunc
447
+ mathieu_modsem2: np.ufunc
448
+ mathieu_sem: np.ufunc
449
+ modfresnelm: np.ufunc
450
+ modfresnelp: np.ufunc
451
+ modstruve: np.ufunc
452
+ nbdtr: np.ufunc
453
+ nbdtrc: np.ufunc
454
+ nbdtri: np.ufunc
455
+ nbdtrik: np.ufunc
456
+ nbdtrin: np.ufunc
457
+ ncfdtr: np.ufunc
458
+ ncfdtri: np.ufunc
459
+ ncfdtridfd: np.ufunc
460
+ ncfdtridfn: np.ufunc
461
+ ncfdtrinc: np.ufunc
462
+ nctdtr: np.ufunc
463
+ nctdtridf: np.ufunc
464
+ nctdtrinc: np.ufunc
465
+ nctdtrit: np.ufunc
466
+ ndtr: np.ufunc
467
+ ndtri: np.ufunc
468
+ ndtri_exp: np.ufunc
469
+ nrdtrimn: np.ufunc
470
+ nrdtrisd: np.ufunc
471
+ obl_ang1: np.ufunc
472
+ obl_ang1_cv: np.ufunc
473
+ obl_cv: np.ufunc
474
+ obl_rad1: np.ufunc
475
+ obl_rad1_cv: np.ufunc
476
+ obl_rad2: np.ufunc
477
+ obl_rad2_cv: np.ufunc
478
+ owens_t: np.ufunc
479
+ pbdv: np.ufunc
480
+ pbvv: np.ufunc
481
+ pbwa: np.ufunc
482
+ pdtr: np.ufunc
483
+ pdtrc: np.ufunc
484
+ pdtri: np.ufunc
485
+ pdtrik: np.ufunc
486
+ poch: np.ufunc
487
+ powm1: np.ufunc
488
+ pro_ang1: np.ufunc
489
+ pro_ang1_cv: np.ufunc
490
+ pro_cv: np.ufunc
491
+ pro_rad1: np.ufunc
492
+ pro_rad1_cv: np.ufunc
493
+ pro_rad2: np.ufunc
494
+ pro_rad2_cv: np.ufunc
495
+ pseudo_huber: np.ufunc
496
+ psi: np.ufunc
497
+ radian: np.ufunc
498
+ rel_entr: np.ufunc
499
+ rgamma: np.ufunc
500
+ round: np.ufunc
501
+ shichi: np.ufunc
502
+ sici: np.ufunc
503
+ sindg: np.ufunc
504
+ smirnov: np.ufunc
505
+ smirnovi: np.ufunc
506
+ spence: np.ufunc
507
+ sph_harm: np.ufunc
508
+ stdtr: np.ufunc
509
+ stdtridf: np.ufunc
510
+ stdtrit: np.ufunc
511
+ struve: np.ufunc
512
+ tandg: np.ufunc
513
+ tklmbda: np.ufunc
514
+ voigt_profile: np.ufunc
515
+ wofz: np.ufunc
516
+ wright_bessel: np.ufunc
517
+ wrightomega: np.ufunc
518
+ xlog1py: np.ufunc
519
+ xlogy: np.ufunc
520
+ y0: np.ufunc
521
+ y1: np.ufunc
522
+ yn: np.ufunc
523
+ yv: np.ufunc
524
+ yve: np.ufunc
525
+ zetac: np.ufunc
526
+
env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . cimport sf_error
2
+ cdef void _set_action(sf_error.sf_error_t, sf_error.sf_action_t) noexcept nogil
3
+ cdef void *_export_ccospi
4
+ cdef void *_export_lambertw_scalar
5
+ cdef void *_export_csinpi
6
+ cdef void *_export__stirling2_inexact
7
+ cdef void *_export_ibeta_float
8
+ cdef void *_export_ibeta_double
9
+ cdef void *_export_ibetac_float
10
+ cdef void *_export_ibetac_double
11
+ cdef void *_export_ibetac_inv_float
12
+ cdef void *_export_ibetac_inv_double
13
+ cdef void *_export_ibeta_inv_float
14
+ cdef void *_export_ibeta_inv_double
15
+ cdef void *_export_binom
16
+ cdef void *_export_faddeeva_dawsn
17
+ cdef void *_export_faddeeva_dawsn_complex
18
+ cdef void *_export_fellint_RC
19
+ cdef void *_export_cellint_RC
20
+ cdef void *_export_fellint_RD
21
+ cdef void *_export_cellint_RD
22
+ cdef void *_export_fellint_RF
23
+ cdef void *_export_cellint_RF
24
+ cdef void *_export_fellint_RG
25
+ cdef void *_export_cellint_RG
26
+ cdef void *_export_fellint_RJ
27
+ cdef void *_export_cellint_RJ
28
+ cdef void *_export_faddeeva_erf
29
+ cdef void *_export_faddeeva_erfc_complex
30
+ cdef void *_export_faddeeva_erfcx
31
+ cdef void *_export_faddeeva_erfcx_complex
32
+ cdef void *_export_faddeeva_erfi
33
+ cdef void *_export_faddeeva_erfi_complex
34
+ cdef void *_export_erfinv_float
35
+ cdef void *_export_erfinv_double
36
+ cdef void *_export_expit
37
+ cdef void *_export_expitf
38
+ cdef void *_export_expitl
39
+ cdef void *_export_cgamma
40
+ cdef void *_export_hyp1f1_double
41
+ cdef void *_export_log_expit
42
+ cdef void *_export_log_expitf
43
+ cdef void *_export_log_expitl
44
+ cdef void *_export_faddeeva_log_ndtr
45
+ cdef void *_export_faddeeva_log_ndtr_complex
46
+ cdef void *_export_loggamma_real
47
+ cdef void *_export_loggamma
48
+ cdef void *_export_logit
49
+ cdef void *_export_logitf
50
+ cdef void *_export_logitl
51
+ cdef void *_export_faddeeva_ndtr
52
+ cdef void *_export_powm1_float
53
+ cdef void *_export_powm1_double
54
+ cdef void *_export_cdigamma
55
+ cdef void *_export_digamma
56
+ cdef void *_export_crgamma
57
+ cdef void *_export_faddeeva_voigt_profile
58
+ cdef void *_export_faddeeva_w
59
+ cdef void *_export_wrightomega
60
+ cdef void *_export_wrightomega_real
env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically generated by _generate_pyx.py.
2
+ # Do not edit manually!
3
+
4
+ from libc.math cimport NAN
5
+
6
+ include "_ufuncs_extra_code_common.pxi"
7
+
8
+ cdef extern from r"_ufuncs_cxx_defs.h":
9
+ cdef double complex _func_ccospi "ccospi"(double complex) noexcept nogil
10
+ cdef void *_export_ccospi = <void*>_func_ccospi
11
+ cdef extern from r"_ufuncs_cxx_defs.h":
12
+ cdef double complex _func_lambertw_scalar "lambertw_scalar"(double complex, long, double) noexcept nogil
13
+ cdef void *_export_lambertw_scalar = <void*>_func_lambertw_scalar
14
+ cdef extern from r"_ufuncs_cxx_defs.h":
15
+ cdef double complex _func_csinpi "csinpi"(double complex) noexcept nogil
16
+ cdef void *_export_csinpi = <void*>_func_csinpi
17
+ cdef extern from r"_ufuncs_cxx_defs.h":
18
+ cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil
19
+ cdef void *_export__stirling2_inexact = <void*>_func__stirling2_inexact
20
+ cdef extern from r"_ufuncs_cxx_defs.h":
21
+ cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil
22
+ cdef void *_export_ibeta_float = <void*>_func_ibeta_float
23
+ cdef extern from r"_ufuncs_cxx_defs.h":
24
+ cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil
25
+ cdef void *_export_ibeta_double = <void*>_func_ibeta_double
26
+ cdef extern from r"_ufuncs_cxx_defs.h":
27
+ cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil
28
+ cdef void *_export_ibetac_float = <void*>_func_ibetac_float
29
+ cdef extern from r"_ufuncs_cxx_defs.h":
30
+ cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil
31
+ cdef void *_export_ibetac_double = <void*>_func_ibetac_double
32
+ cdef extern from r"_ufuncs_cxx_defs.h":
33
+ cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil
34
+ cdef void *_export_ibetac_inv_float = <void*>_func_ibetac_inv_float
35
+ cdef extern from r"_ufuncs_cxx_defs.h":
36
+ cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil
37
+ cdef void *_export_ibetac_inv_double = <void*>_func_ibetac_inv_double
38
+ cdef extern from r"_ufuncs_cxx_defs.h":
39
+ cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil
40
+ cdef void *_export_ibeta_inv_float = <void*>_func_ibeta_inv_float
41
+ cdef extern from r"_ufuncs_cxx_defs.h":
42
+ cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil
43
+ cdef void *_export_ibeta_inv_double = <void*>_func_ibeta_inv_double
44
+ cdef extern from r"_ufuncs_cxx_defs.h":
45
+ cdef double _func_binom "binom"(double, double) noexcept nogil
46
+ cdef void *_export_binom = <void*>_func_binom
47
+ cdef extern from r"_ufuncs_cxx_defs.h":
48
+ cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil
49
+ cdef void *_export_faddeeva_dawsn = <void*>_func_faddeeva_dawsn
50
+ cdef extern from r"_ufuncs_cxx_defs.h":
51
+ cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil
52
+ cdef void *_export_faddeeva_dawsn_complex = <void*>_func_faddeeva_dawsn_complex
53
+ cdef extern from r"_ufuncs_cxx_defs.h":
54
+ cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil
55
+ cdef void *_export_fellint_RC = <void*>_func_fellint_RC
56
+ cdef extern from r"_ufuncs_cxx_defs.h":
57
+ cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil
58
+ cdef void *_export_cellint_RC = <void*>_func_cellint_RC
59
+ cdef extern from r"_ufuncs_cxx_defs.h":
60
+ cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil
61
+ cdef void *_export_fellint_RD = <void*>_func_fellint_RD
62
+ cdef extern from r"_ufuncs_cxx_defs.h":
63
+ cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil
64
+ cdef void *_export_cellint_RD = <void*>_func_cellint_RD
65
+ cdef extern from r"_ufuncs_cxx_defs.h":
66
+ cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil
67
+ cdef void *_export_fellint_RF = <void*>_func_fellint_RF
68
+ cdef extern from r"_ufuncs_cxx_defs.h":
69
+ cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil
70
+ cdef void *_export_cellint_RF = <void*>_func_cellint_RF
71
+ cdef extern from r"_ufuncs_cxx_defs.h":
72
+ cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil
73
+ cdef void *_export_fellint_RG = <void*>_func_fellint_RG
74
+ cdef extern from r"_ufuncs_cxx_defs.h":
75
+ cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil
76
+ cdef void *_export_cellint_RG = <void*>_func_cellint_RG
77
+ cdef extern from r"_ufuncs_cxx_defs.h":
78
+ cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil
79
+ cdef void *_export_fellint_RJ = <void*>_func_fellint_RJ
80
+ cdef extern from r"_ufuncs_cxx_defs.h":
81
+ cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil
82
+ cdef void *_export_cellint_RJ = <void*>_func_cellint_RJ
83
+ cdef extern from r"_ufuncs_cxx_defs.h":
84
+ cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil
85
+ cdef void *_export_faddeeva_erf = <void*>_func_faddeeva_erf
86
+ cdef extern from r"_ufuncs_cxx_defs.h":
87
+ cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil
88
+ cdef void *_export_faddeeva_erfc_complex = <void*>_func_faddeeva_erfc_complex
89
+ cdef extern from r"_ufuncs_cxx_defs.h":
90
+ cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil
91
+ cdef void *_export_faddeeva_erfcx = <void*>_func_faddeeva_erfcx
92
+ cdef extern from r"_ufuncs_cxx_defs.h":
93
+ cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil
94
+ cdef void *_export_faddeeva_erfcx_complex = <void*>_func_faddeeva_erfcx_complex
95
+ cdef extern from r"_ufuncs_cxx_defs.h":
96
+ cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil
97
+ cdef void *_export_faddeeva_erfi = <void*>_func_faddeeva_erfi
98
+ cdef extern from r"_ufuncs_cxx_defs.h":
99
+ cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil
100
+ cdef void *_export_faddeeva_erfi_complex = <void*>_func_faddeeva_erfi_complex
101
+ cdef extern from r"_ufuncs_cxx_defs.h":
102
+ cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil
103
+ cdef void *_export_erfinv_float = <void*>_func_erfinv_float
104
+ cdef extern from r"_ufuncs_cxx_defs.h":
105
+ cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil
106
+ cdef void *_export_erfinv_double = <void*>_func_erfinv_double
107
+ cdef extern from r"_ufuncs_cxx_defs.h":
108
+ cdef double _func_expit "expit"(double) noexcept nogil
109
+ cdef void *_export_expit = <void*>_func_expit
110
+ cdef extern from r"_ufuncs_cxx_defs.h":
111
+ cdef float _func_expitf "expitf"(float) noexcept nogil
112
+ cdef void *_export_expitf = <void*>_func_expitf
113
+ cdef extern from r"_ufuncs_cxx_defs.h":
114
+ cdef long double _func_expitl "expitl"(long double) noexcept nogil
115
+ cdef void *_export_expitl = <void*>_func_expitl
116
+ cdef extern from r"_ufuncs_cxx_defs.h":
117
+ cdef double complex _func_cgamma "cgamma"(double complex) noexcept nogil
118
+ cdef void *_export_cgamma = <void*>_func_cgamma
119
+ cdef extern from r"_ufuncs_cxx_defs.h":
120
+ cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil
121
+ cdef void *_export_hyp1f1_double = <void*>_func_hyp1f1_double
122
+ cdef extern from r"_ufuncs_cxx_defs.h":
123
+ cdef double _func_log_expit "log_expit"(double) noexcept nogil
124
+ cdef void *_export_log_expit = <void*>_func_log_expit
125
+ cdef extern from r"_ufuncs_cxx_defs.h":
126
+ cdef float _func_log_expitf "log_expitf"(float) noexcept nogil
127
+ cdef void *_export_log_expitf = <void*>_func_log_expitf
128
+ cdef extern from r"_ufuncs_cxx_defs.h":
129
+ cdef long double _func_log_expitl "log_expitl"(long double) noexcept nogil
130
+ cdef void *_export_log_expitl = <void*>_func_log_expitl
131
+ cdef extern from r"_ufuncs_cxx_defs.h":
132
+ cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil
133
+ cdef void *_export_faddeeva_log_ndtr = <void*>_func_faddeeva_log_ndtr
134
+ cdef extern from r"_ufuncs_cxx_defs.h":
135
+ cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil
136
+ cdef void *_export_faddeeva_log_ndtr_complex = <void*>_func_faddeeva_log_ndtr_complex
137
+ cdef extern from r"_ufuncs_cxx_defs.h":
138
+ cdef double _func_loggamma_real "loggamma_real"(double) noexcept nogil
139
+ cdef void *_export_loggamma_real = <void*>_func_loggamma_real
140
+ cdef extern from r"_ufuncs_cxx_defs.h":
141
+ cdef double complex _func_loggamma "loggamma"(double complex) noexcept nogil
142
+ cdef void *_export_loggamma = <void*>_func_loggamma
143
+ cdef extern from r"_ufuncs_cxx_defs.h":
144
+ cdef double _func_logit "logit"(double) noexcept nogil
145
+ cdef void *_export_logit = <void*>_func_logit
146
+ cdef extern from r"_ufuncs_cxx_defs.h":
147
+ cdef float _func_logitf "logitf"(float) noexcept nogil
148
+ cdef void *_export_logitf = <void*>_func_logitf
149
+ cdef extern from r"_ufuncs_cxx_defs.h":
150
+ cdef long double _func_logitl "logitl"(long double) noexcept nogil
151
+ cdef void *_export_logitl = <void*>_func_logitl
152
+ cdef extern from r"_ufuncs_cxx_defs.h":
153
+ cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil
154
+ cdef void *_export_faddeeva_ndtr = <void*>_func_faddeeva_ndtr
155
+ cdef extern from r"_ufuncs_cxx_defs.h":
156
+ cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil
157
+ cdef void *_export_powm1_float = <void*>_func_powm1_float
158
+ cdef extern from r"_ufuncs_cxx_defs.h":
159
+ cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil
160
+ cdef void *_export_powm1_double = <void*>_func_powm1_double
161
+ cdef extern from r"_ufuncs_cxx_defs.h":
162
+ cdef double complex _func_cdigamma "cdigamma"(double complex) noexcept nogil
163
+ cdef void *_export_cdigamma = <void*>_func_cdigamma
164
+ cdef extern from r"_ufuncs_cxx_defs.h":
165
+ cdef double _func_digamma "digamma"(double) noexcept nogil
166
+ cdef void *_export_digamma = <void*>_func_digamma
167
+ cdef extern from r"_ufuncs_cxx_defs.h":
168
+ cdef double complex _func_crgamma "crgamma"(double complex) noexcept nogil
169
+ cdef void *_export_crgamma = <void*>_func_crgamma
170
+ cdef extern from r"_ufuncs_cxx_defs.h":
171
+ cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil
172
+ cdef void *_export_faddeeva_voigt_profile = <void*>_func_faddeeva_voigt_profile
173
+ cdef extern from r"_ufuncs_cxx_defs.h":
174
+ cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil
175
+ cdef void *_export_faddeeva_w = <void*>_func_faddeeva_w
176
+ cdef extern from r"_ufuncs_cxx_defs.h":
177
+ cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil
178
+ cdef void *_export_wrightomega = <void*>_func_wrightomega
179
+ cdef extern from r"_ufuncs_cxx_defs.h":
180
+ cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil
181
+ cdef void *_export_wrightomega_real = <void*>_func_wrightomega_real
env-llmeval/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UFUNCS_PROTO_H
2
+ #define UFUNCS_PROTO_H 1
3
+ #include "_special.h"
4
+ npy_cdouble ccospi(npy_cdouble);
5
+ npy_cdouble lambertw_scalar(npy_cdouble, npy_long, npy_double);
6
+ npy_cdouble csinpi(npy_cdouble);
7
+ #include "stirling2.h"
8
+ npy_double _stirling2_inexact(npy_double, npy_double);
9
+ #include "boost_special_functions.h"
10
+ npy_float ibeta_float(npy_float, npy_float, npy_float);
11
+ npy_double ibeta_double(npy_double, npy_double, npy_double);
12
+ npy_float ibetac_float(npy_float, npy_float, npy_float);
13
+ npy_double ibetac_double(npy_double, npy_double, npy_double);
14
+ npy_float ibetac_inv_float(npy_float, npy_float, npy_float);
15
+ npy_double ibetac_inv_double(npy_double, npy_double, npy_double);
16
+ npy_float ibeta_inv_float(npy_float, npy_float, npy_float);
17
+ npy_double ibeta_inv_double(npy_double, npy_double, npy_double);
18
+ npy_double binom(npy_double, npy_double);
19
+ #include "_faddeeva.h"
20
+ npy_double faddeeva_dawsn(npy_double);
21
+ npy_cdouble faddeeva_dawsn_complex(npy_cdouble);
22
+ #include "ellint_carlson_wrap.hh"
23
+ npy_double fellint_RC(npy_double, npy_double);
24
+ npy_cdouble cellint_RC(npy_cdouble, npy_cdouble);
25
+ npy_double fellint_RD(npy_double, npy_double, npy_double);
26
+ npy_cdouble cellint_RD(npy_cdouble, npy_cdouble, npy_cdouble);
27
+ npy_double fellint_RF(npy_double, npy_double, npy_double);
28
+ npy_cdouble cellint_RF(npy_cdouble, npy_cdouble, npy_cdouble);
29
+ npy_double fellint_RG(npy_double, npy_double, npy_double);
30
+ npy_cdouble cellint_RG(npy_cdouble, npy_cdouble, npy_cdouble);
31
+ npy_double fellint_RJ(npy_double, npy_double, npy_double, npy_double);
32
+ npy_cdouble cellint_RJ(npy_cdouble, npy_cdouble, npy_cdouble, npy_cdouble);
33
+ npy_cdouble faddeeva_erf(npy_cdouble);
34
+ npy_cdouble faddeeva_erfc_complex(npy_cdouble);
35
+ npy_double faddeeva_erfcx(npy_double);
36
+ npy_cdouble faddeeva_erfcx_complex(npy_cdouble);
37
+ npy_double faddeeva_erfi(npy_double);
38
+ npy_cdouble faddeeva_erfi_complex(npy_cdouble);
39
+ npy_float erfinv_float(npy_float);
40
+ npy_double erfinv_double(npy_double);
41
+ #include "_logit.h"
42
+ npy_double expit(npy_double);
43
+ npy_float expitf(npy_float);
44
+ npy_longdouble expitl(npy_longdouble);
45
+ npy_cdouble cgamma(npy_cdouble);
46
+ npy_double hyp1f1_double(npy_double, npy_double, npy_double);
47
+ npy_double log_expit(npy_double);
48
+ npy_float log_expitf(npy_float);
49
+ npy_longdouble log_expitl(npy_longdouble);
50
+ npy_double faddeeva_log_ndtr(npy_double);
51
+ npy_cdouble faddeeva_log_ndtr_complex(npy_cdouble);
52
+ npy_double loggamma_real(npy_double);
53
+ npy_cdouble loggamma(npy_cdouble);
54
+ npy_double logit(npy_double);
55
+ npy_float logitf(npy_float);
56
+ npy_longdouble logitl(npy_longdouble);
57
+ npy_cdouble faddeeva_ndtr(npy_cdouble);
58
+ npy_float powm1_float(npy_float, npy_float);
59
+ npy_double powm1_double(npy_double, npy_double);
60
+ npy_cdouble cdigamma(npy_cdouble);
61
+ npy_double digamma(npy_double);
62
+ npy_cdouble crgamma(npy_cdouble);
63
+ npy_double faddeeva_voigt_profile(npy_double, npy_double, npy_double);
64
+ npy_cdouble faddeeva_w(npy_cdouble);
65
+ #include "_wright.h"
66
+ npy_cdouble wrightomega(npy_cdouble);
67
+ npy_double wrightomega_real(npy_double);
68
+ #endif
env-llmeval/lib/python3.10/site-packages/scipy/special/add_newdocs.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+
3
+ from scipy._lib.deprecation import _sub_module_deprecation
4
+
5
+ __all__ = ['get', 'add_newdoc', 'docdict'] # noqa: F822
6
+
7
+
8
+ def __dir__():
9
+ return __all__
10
+
11
+
12
+ def __getattr__(name):
13
+ return _sub_module_deprecation(sub_package="special", module="add_newdocs",
14
+ private_modules=["_add_newdocs"], all=__all__,
15
+ attribute=name)
env-llmeval/lib/python3.10/site-packages/scipy/special/basic.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.special` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'ai_zeros',
10
+ 'assoc_laguerre',
11
+ 'bei_zeros',
12
+ 'beip_zeros',
13
+ 'ber_zeros',
14
+ 'bernoulli',
15
+ 'berp_zeros',
16
+ 'bi_zeros',
17
+ 'clpmn',
18
+ 'comb',
19
+ 'digamma',
20
+ 'diric',
21
+ 'erf_zeros',
22
+ 'euler',
23
+ 'factorial',
24
+ 'factorial2',
25
+ 'factorialk',
26
+ 'fresnel_zeros',
27
+ 'fresnelc_zeros',
28
+ 'fresnels_zeros',
29
+ 'gamma',
30
+ 'h1vp',
31
+ 'h2vp',
32
+ 'hankel1',
33
+ 'hankel2',
34
+ 'iv',
35
+ 'ivp',
36
+ 'jn_zeros',
37
+ 'jnjnp_zeros',
38
+ 'jnp_zeros',
39
+ 'jnyn_zeros',
40
+ 'jv',
41
+ 'jvp',
42
+ 'kei_zeros',
43
+ 'keip_zeros',
44
+ 'kelvin_zeros',
45
+ 'ker_zeros',
46
+ 'kerp_zeros',
47
+ 'kv',
48
+ 'kvp',
49
+ 'lmbda',
50
+ 'lpmn',
51
+ 'lpn',
52
+ 'lqmn',
53
+ 'lqn',
54
+ 'mathieu_a',
55
+ 'mathieu_b',
56
+ 'mathieu_even_coef',
57
+ 'mathieu_odd_coef',
58
+ 'obl_cv_seq',
59
+ 'pbdn_seq',
60
+ 'pbdv_seq',
61
+ 'pbvv_seq',
62
+ 'perm',
63
+ 'polygamma',
64
+ 'pro_cv_seq',
65
+ 'psi',
66
+ 'riccati_jn',
67
+ 'riccati_yn',
68
+ 'sinc',
69
+ 'y0_zeros',
70
+ 'y1_zeros',
71
+ 'y1p_zeros',
72
+ 'yn_zeros',
73
+ 'ynp_zeros',
74
+ 'yv',
75
+ 'yvp',
76
+ 'zeta'
77
+ ]
78
+
79
+
80
+ def __dir__():
81
+ return __all__
82
+
83
+
84
+ def __getattr__(name):
85
+ return _sub_module_deprecation(sub_package="special", module="basic",
86
+ private_modules=["_basic", "_ufuncs"], all=__all__,
87
+ attribute=name)
env-llmeval/lib/python3.10/site-packages/scipy/special/cython_special.pyi ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from typing import Any
2
+
3
+ def __getattr__(name) -> Any: ...
env-llmeval/lib/python3.10/site-packages/scipy/special/cython_special.pyx ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/scipy/special/sf_error.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.special` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'SpecialFunctionWarning',
9
+ 'SpecialFunctionError'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="special", module="sf_error",
19
+ private_modules=["_sf_error"], all=__all__,
20
+ attribute=name)
env-llmeval/lib/python3.10/site-packages/scipy/special/specfun.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.special` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'airyzo',
9
+ 'bernob',
10
+ 'cerzo',
11
+ 'clpmn',
12
+ 'clpn',
13
+ 'clqmn',
14
+ 'clqn',
15
+ 'cpbdn',
16
+ 'cyzo',
17
+ 'eulerb',
18
+ 'fcoef',
19
+ 'fcszo',
20
+ 'jdzo',
21
+ 'jyzo',
22
+ 'klvnzo',
23
+ 'lamn',
24
+ 'lamv',
25
+ 'lpmn',
26
+ 'lpn',
27
+ 'lqmn',
28
+ 'lqnb',
29
+ 'pbdv',
30
+ 'rctj',
31
+ 'rcty',
32
+ 'segv'
33
+ ]
34
+
35
+
36
+ def __dir__():
37
+ return __all__
38
+
39
+
40
+ def __getattr__(name):
41
+ return _sub_module_deprecation(sub_package="special", module="specfun",
42
+ private_modules=["_specfun"], all=__all__,
43
+ attribute=name)
env-llmeval/lib/python3.10/site-packages/scipy/special/spfun_stats.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.special` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = ['multigammaln', 'loggam'] # noqa: F822
8
+
9
+
10
+ def __dir__():
11
+ return __all__
12
+
13
+
14
+ def __getattr__(name):
15
+ return _sub_module_deprecation(sub_package="special", module="spfun_stats",
16
+ private_modules=["_spfun_stats"], all=__all__,
17
+ attribute=name)
env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_basic.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
3
+ from scipy.special import boxcox, boxcox1p, inv_boxcox, inv_boxcox1p
4
+
5
+
6
+ # There are more tests of boxcox and boxcox1p in test_mpmath.py.
7
+
8
+ def test_boxcox_basic():
9
+ x = np.array([0.5, 1, 2, 4])
10
+
11
+ # lambda = 0 => y = log(x)
12
+ y = boxcox(x, 0)
13
+ assert_almost_equal(y, np.log(x))
14
+
15
+ # lambda = 1 => y = x - 1
16
+ y = boxcox(x, 1)
17
+ assert_almost_equal(y, x - 1)
18
+
19
+ # lambda = 2 => y = 0.5*(x**2 - 1)
20
+ y = boxcox(x, 2)
21
+ assert_almost_equal(y, 0.5*(x**2 - 1))
22
+
23
+ # x = 0 and lambda > 0 => y = -1 / lambda
24
+ lam = np.array([0.5, 1, 2])
25
+ y = boxcox(0, lam)
26
+ assert_almost_equal(y, -1.0 / lam)
27
+
28
+ def test_boxcox_underflow():
29
+ x = 1 + 1e-15
30
+ lmbda = 1e-306
31
+ y = boxcox(x, lmbda)
32
+ assert_allclose(y, np.log(x), rtol=1e-14)
33
+
34
+
35
+ def test_boxcox_nonfinite():
36
+ # x < 0 => y = nan
37
+ x = np.array([-1, -1, -0.5])
38
+ y = boxcox(x, [0.5, 2.0, -1.5])
39
+ assert_equal(y, np.array([np.nan, np.nan, np.nan]))
40
+
41
+ # x = 0 and lambda <= 0 => y = -inf
42
+ x = 0
43
+ y = boxcox(x, [-2.5, 0])
44
+ assert_equal(y, np.array([-np.inf, -np.inf]))
45
+
46
+
47
+ def test_boxcox1p_basic():
48
+ x = np.array([-0.25, -1e-20, 0, 1e-20, 0.25, 1, 3])
49
+
50
+ # lambda = 0 => y = log(1+x)
51
+ y = boxcox1p(x, 0)
52
+ assert_almost_equal(y, np.log1p(x))
53
+
54
+ # lambda = 1 => y = x
55
+ y = boxcox1p(x, 1)
56
+ assert_almost_equal(y, x)
57
+
58
+ # lambda = 2 => y = 0.5*((1+x)**2 - 1) = 0.5*x*(2 + x)
59
+ y = boxcox1p(x, 2)
60
+ assert_almost_equal(y, 0.5*x*(2 + x))
61
+
62
+ # x = -1 and lambda > 0 => y = -1 / lambda
63
+ lam = np.array([0.5, 1, 2])
64
+ y = boxcox1p(-1, lam)
65
+ assert_almost_equal(y, -1.0 / lam)
66
+
67
+
68
+ def test_boxcox1p_underflow():
69
+ x = np.array([1e-15, 1e-306])
70
+ lmbda = np.array([1e-306, 1e-18])
71
+ y = boxcox1p(x, lmbda)
72
+ assert_allclose(y, np.log1p(x), rtol=1e-14)
73
+
74
+
75
+ def test_boxcox1p_nonfinite():
76
+ # x < -1 => y = nan
77
+ x = np.array([-2, -2, -1.5])
78
+ y = boxcox1p(x, [0.5, 2.0, -1.5])
79
+ assert_equal(y, np.array([np.nan, np.nan, np.nan]))
80
+
81
+ # x = -1 and lambda <= 0 => y = -inf
82
+ x = -1
83
+ y = boxcox1p(x, [-2.5, 0])
84
+ assert_equal(y, np.array([-np.inf, -np.inf]))
85
+
86
+
87
+ def test_inv_boxcox():
88
+ x = np.array([0., 1., 2.])
89
+ lam = np.array([0., 1., 2.])
90
+ y = boxcox(x, lam)
91
+ x2 = inv_boxcox(y, lam)
92
+ assert_almost_equal(x, x2)
93
+
94
+ x = np.array([0., 1., 2.])
95
+ lam = np.array([0., 1., 2.])
96
+ y = boxcox1p(x, lam)
97
+ x2 = inv_boxcox1p(y, lam)
98
+ assert_almost_equal(x, x2)
99
+
100
+
101
+ def test_inv_boxcox1p_underflow():
102
+ x = 1e-15
103
+ lam = 1e-306
104
+ y = inv_boxcox1p(x, lam)
105
+ assert_allclose(y, x, rtol=1e-14)
106
+
env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test cdflib functions versus mpmath, if available.
3
+
4
+ The following functions still need tests:
5
+
6
+ - ncfdtr
7
+ - ncfdtri
8
+ - ncfdtridfn
9
+ - ncfdtridfd
10
+ - ncfdtrinc
11
+ - nbdtrik
12
+ - nbdtrin
13
+ - pdtrik
14
+ - nctdtr
15
+ - nctdtrit
16
+ - nctdtridf
17
+ - nctdtrinc
18
+
19
+ """
20
+ import itertools
21
+
22
+ import numpy as np
23
+ from numpy.testing import assert_equal, assert_allclose
24
+ import pytest
25
+
26
+ import scipy.special as sp
27
+ from scipy.special._testutils import (
28
+ MissingModule, check_version, FuncData)
29
+ from scipy.special._mptestutils import (
30
+ Arg, IntArg, get_args, mpf2float, assert_mpmath_equal)
31
+
32
+ try:
33
+ import mpmath
34
+ except ImportError:
35
+ mpmath = MissingModule('mpmath')
36
+
37
+
38
+ class ProbArg:
39
+ """Generate a set of probabilities on [0, 1]."""
40
+
41
+ def __init__(self):
42
+ # Include the endpoints for compatibility with Arg et. al.
43
+ self.a = 0
44
+ self.b = 1
45
+
46
+ def values(self, n):
47
+ """Return an array containing approximately n numbers."""
48
+ m = max(1, n//3)
49
+ v1 = np.logspace(-30, np.log10(0.3), m)
50
+ v2 = np.linspace(0.3, 0.7, m + 1, endpoint=False)[1:]
51
+ v3 = 1 - np.logspace(np.log10(0.3), -15, m)
52
+ v = np.r_[v1, v2, v3]
53
+ return np.unique(v)
54
+
55
+
56
+ class EndpointFilter:
57
+ def __init__(self, a, b, rtol, atol):
58
+ self.a = a
59
+ self.b = b
60
+ self.rtol = rtol
61
+ self.atol = atol
62
+
63
+ def __call__(self, x):
64
+ mask1 = np.abs(x - self.a) < self.rtol*np.abs(self.a) + self.atol
65
+ mask2 = np.abs(x - self.b) < self.rtol*np.abs(self.b) + self.atol
66
+ return np.where(mask1 | mask2, False, True)
67
+
68
+
69
+ class _CDFData:
70
+ def __init__(self, spfunc, mpfunc, index, argspec, spfunc_first=True,
71
+ dps=20, n=5000, rtol=None, atol=None,
72
+ endpt_rtol=None, endpt_atol=None):
73
+ self.spfunc = spfunc
74
+ self.mpfunc = mpfunc
75
+ self.index = index
76
+ self.argspec = argspec
77
+ self.spfunc_first = spfunc_first
78
+ self.dps = dps
79
+ self.n = n
80
+ self.rtol = rtol
81
+ self.atol = atol
82
+
83
+ if not isinstance(argspec, list):
84
+ self.endpt_rtol = None
85
+ self.endpt_atol = None
86
+ elif endpt_rtol is not None or endpt_atol is not None:
87
+ if isinstance(endpt_rtol, list):
88
+ self.endpt_rtol = endpt_rtol
89
+ else:
90
+ self.endpt_rtol = [endpt_rtol]*len(self.argspec)
91
+ if isinstance(endpt_atol, list):
92
+ self.endpt_atol = endpt_atol
93
+ else:
94
+ self.endpt_atol = [endpt_atol]*len(self.argspec)
95
+ else:
96
+ self.endpt_rtol = None
97
+ self.endpt_atol = None
98
+
99
+ def idmap(self, *args):
100
+ if self.spfunc_first:
101
+ res = self.spfunc(*args)
102
+ if np.isnan(res):
103
+ return np.nan
104
+ args = list(args)
105
+ args[self.index] = res
106
+ with mpmath.workdps(self.dps):
107
+ res = self.mpfunc(*tuple(args))
108
+ # Imaginary parts are spurious
109
+ res = mpf2float(res.real)
110
+ else:
111
+ with mpmath.workdps(self.dps):
112
+ res = self.mpfunc(*args)
113
+ res = mpf2float(res.real)
114
+ args = list(args)
115
+ args[self.index] = res
116
+ res = self.spfunc(*tuple(args))
117
+ return res
118
+
119
+ def get_param_filter(self):
120
+ if self.endpt_rtol is None and self.endpt_atol is None:
121
+ return None
122
+
123
+ filters = []
124
+ for rtol, atol, spec in zip(self.endpt_rtol, self.endpt_atol, self.argspec):
125
+ if rtol is None and atol is None:
126
+ filters.append(None)
127
+ continue
128
+ elif rtol is None:
129
+ rtol = 0.0
130
+ elif atol is None:
131
+ atol = 0.0
132
+
133
+ filters.append(EndpointFilter(spec.a, spec.b, rtol, atol))
134
+ return filters
135
+
136
+ def check(self):
137
+ # Generate values for the arguments
138
+ args = get_args(self.argspec, self.n)
139
+ param_filter = self.get_param_filter()
140
+ param_columns = tuple(range(args.shape[1]))
141
+ result_columns = args.shape[1]
142
+ args = np.hstack((args, args[:, self.index].reshape(args.shape[0], 1)))
143
+ FuncData(self.idmap, args,
144
+ param_columns=param_columns, result_columns=result_columns,
145
+ rtol=self.rtol, atol=self.atol, vectorized=False,
146
+ param_filter=param_filter).check()
147
+
148
+
149
+ def _assert_inverts(*a, **kw):
150
+ d = _CDFData(*a, **kw)
151
+ d.check()
152
+
153
+
154
+ def _binomial_cdf(k, n, p):
155
+ k, n, p = mpmath.mpf(k), mpmath.mpf(n), mpmath.mpf(p)
156
+ if k <= 0:
157
+ return mpmath.mpf(0)
158
+ elif k >= n:
159
+ return mpmath.mpf(1)
160
+
161
+ onemp = mpmath.fsub(1, p, exact=True)
162
+ return mpmath.betainc(n - k, k + 1, x2=onemp, regularized=True)
163
+
164
+
165
+ def _f_cdf(dfn, dfd, x):
166
+ if x < 0:
167
+ return mpmath.mpf(0)
168
+ dfn, dfd, x = mpmath.mpf(dfn), mpmath.mpf(dfd), mpmath.mpf(x)
169
+ ub = dfn*x/(dfn*x + dfd)
170
+ res = mpmath.betainc(dfn/2, dfd/2, x2=ub, regularized=True)
171
+ return res
172
+
173
+
174
+ def _student_t_cdf(df, t, dps=None):
175
+ if dps is None:
176
+ dps = mpmath.mp.dps
177
+ with mpmath.workdps(dps):
178
+ df, t = mpmath.mpf(df), mpmath.mpf(t)
179
+ fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df)
180
+ fac *= t*mpmath.gamma(0.5*(df + 1))
181
+ fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df)
182
+ return 0.5 + fac
183
+
184
+
185
+ def _noncentral_chi_pdf(t, df, nc):
186
+ res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t))
187
+ res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2
188
+ return res
189
+
190
+
191
+ def _noncentral_chi_cdf(x, df, nc, dps=None):
192
+ if dps is None:
193
+ dps = mpmath.mp.dps
194
+ x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc)
195
+ with mpmath.workdps(dps):
196
+ res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x])
197
+ return res
198
+
199
+
200
+ def _tukey_lmbda_quantile(p, lmbda):
201
+ # For lmbda != 0
202
+ return (p**lmbda - (1 - p)**lmbda)/lmbda
203
+
204
+
205
+ @pytest.mark.slow
206
+ @check_version(mpmath, '0.19')
207
+ class TestCDFlib:
208
+
209
+ @pytest.mark.xfail(run=False)
210
+ def test_bdtrik(self):
211
+ _assert_inverts(
212
+ sp.bdtrik,
213
+ _binomial_cdf,
214
+ 0, [ProbArg(), IntArg(1, 1000), ProbArg()],
215
+ rtol=1e-4)
216
+
217
+ def test_bdtrin(self):
218
+ _assert_inverts(
219
+ sp.bdtrin,
220
+ _binomial_cdf,
221
+ 1, [IntArg(1, 1000), ProbArg(), ProbArg()],
222
+ rtol=1e-4, endpt_atol=[None, None, 1e-6])
223
+
224
+ def test_btdtria(self):
225
+ _assert_inverts(
226
+ sp.btdtria,
227
+ lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
228
+ 0, [ProbArg(), Arg(0, 1e2, inclusive_a=False),
229
+ Arg(0, 1, inclusive_a=False, inclusive_b=False)],
230
+ rtol=1e-6)
231
+
232
+ def test_btdtrib(self):
233
+ # Use small values of a or mpmath doesn't converge
234
+ _assert_inverts(
235
+ sp.btdtrib,
236
+ lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
237
+ 1,
238
+ [Arg(0, 1e2, inclusive_a=False), ProbArg(),
239
+ Arg(0, 1, inclusive_a=False, inclusive_b=False)],
240
+ rtol=1e-7,
241
+ endpt_atol=[None, 1e-18, 1e-15])
242
+
243
+ @pytest.mark.xfail(run=False)
244
+ def test_fdtridfd(self):
245
+ _assert_inverts(
246
+ sp.fdtridfd,
247
+ _f_cdf,
248
+ 1,
249
+ [IntArg(1, 100), ProbArg(), Arg(0, 100, inclusive_a=False)],
250
+ rtol=1e-7)
251
+
252
+ def test_gdtria(self):
253
+ _assert_inverts(
254
+ sp.gdtria,
255
+ lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
256
+ 0,
257
+ [ProbArg(), Arg(0, 1e3, inclusive_a=False),
258
+ Arg(0, 1e4, inclusive_a=False)],
259
+ rtol=1e-7,
260
+ endpt_atol=[None, 1e-7, 1e-10])
261
+
262
+ def test_gdtrib(self):
263
+ # Use small values of a and x or mpmath doesn't converge
264
+ _assert_inverts(
265
+ sp.gdtrib,
266
+ lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
267
+ 1,
268
+ [Arg(0, 1e2, inclusive_a=False), ProbArg(),
269
+ Arg(0, 1e3, inclusive_a=False)],
270
+ rtol=1e-5)
271
+
272
+ def test_gdtrix(self):
273
+ _assert_inverts(
274
+ sp.gdtrix,
275
+ lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
276
+ 2,
277
+ [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False),
278
+ ProbArg()],
279
+ rtol=1e-7,
280
+ endpt_atol=[None, 1e-7, 1e-10])
281
+
282
+ # Overall nrdtrimn and nrdtrisd are not performing well with infeasible/edge
283
+ # combinations of sigma and x, hence restricted the domains to still use the
284
+ # testing machinery, also see gh-20069
285
+
286
+ # nrdtrimn signature: p, sd, x
287
+ # nrdtrisd signature: mn, p, x
288
+ def test_nrdtrimn(self):
289
+ _assert_inverts(
290
+ sp.nrdtrimn,
291
+ lambda x, y, z: mpmath.ncdf(z, x, y),
292
+ 0,
293
+ [ProbArg(), # CDF value p
294
+ Arg(0.1, np.inf, inclusive_a=False, inclusive_b=False), # sigma
295
+ Arg(-1e10, 1e10)], # x
296
+ rtol=1e-5)
297
+
298
+ def test_nrdtrisd(self):
299
+ _assert_inverts(
300
+ sp.nrdtrisd,
301
+ lambda x, y, z: mpmath.ncdf(z, x, y),
302
+ 1,
303
+ [Arg(-np.inf, 10, inclusive_a=False, inclusive_b=False), # mn
304
+ ProbArg(), # CDF value p
305
+ Arg(10, 1e100)], # x
306
+ rtol=1e-5)
307
+
308
+ def test_stdtr(self):
309
+ # Ideally the left endpoint for Arg() should be 0.
310
+ assert_mpmath_equal(
311
+ sp.stdtr,
312
+ _student_t_cdf,
313
+ [IntArg(1, 100), Arg(1e-10, np.inf)], rtol=1e-7)
314
+
315
+ @pytest.mark.xfail(run=False)
316
+ def test_stdtridf(self):
317
+ _assert_inverts(
318
+ sp.stdtridf,
319
+ _student_t_cdf,
320
+ 0, [ProbArg(), Arg()], rtol=1e-7)
321
+
322
+ def test_stdtrit(self):
323
+ _assert_inverts(
324
+ sp.stdtrit,
325
+ _student_t_cdf,
326
+ 1, [IntArg(1, 100), ProbArg()], rtol=1e-7,
327
+ endpt_atol=[None, 1e-10])
328
+
329
+ def test_chdtriv(self):
330
+ _assert_inverts(
331
+ sp.chdtriv,
332
+ lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True),
333
+ 0, [ProbArg(), IntArg(1, 100)], rtol=1e-4)
334
+
335
+ @pytest.mark.xfail(run=False)
336
+ def test_chndtridf(self):
337
+ # Use a larger atol since mpmath is doing numerical integration
338
+ _assert_inverts(
339
+ sp.chndtridf,
340
+ _noncentral_chi_cdf,
341
+ 1, [Arg(0, 100, inclusive_a=False), ProbArg(),
342
+ Arg(0, 100, inclusive_a=False)],
343
+ n=1000, rtol=1e-4, atol=1e-15)
344
+
345
+ @pytest.mark.xfail(run=False)
346
+ def test_chndtrinc(self):
347
+ # Use a larger atol since mpmath is doing numerical integration
348
+ _assert_inverts(
349
+ sp.chndtrinc,
350
+ _noncentral_chi_cdf,
351
+ 2, [Arg(0, 100, inclusive_a=False), IntArg(1, 100), ProbArg()],
352
+ n=1000, rtol=1e-4, atol=1e-15)
353
+
354
+ def test_chndtrix(self):
355
+ # Use a larger atol since mpmath is doing numerical integration
356
+ _assert_inverts(
357
+ sp.chndtrix,
358
+ _noncentral_chi_cdf,
359
+ 0, [ProbArg(), IntArg(1, 100), Arg(0, 100, inclusive_a=False)],
360
+ n=1000, rtol=1e-4, atol=1e-15,
361
+ endpt_atol=[1e-6, None, None])
362
+
363
+ def test_tklmbda_zero_shape(self):
364
+ # When lmbda = 0 the CDF has a simple closed form
365
+ one = mpmath.mpf(1)
366
+ assert_mpmath_equal(
367
+ lambda x: sp.tklmbda(x, 0),
368
+ lambda x: one/(mpmath.exp(-x) + one),
369
+ [Arg()], rtol=1e-7)
370
+
371
+ def test_tklmbda_neg_shape(self):
372
+ _assert_inverts(
373
+ sp.tklmbda,
374
+ _tukey_lmbda_quantile,
375
+ 0, [ProbArg(), Arg(-25, 0, inclusive_b=False)],
376
+ spfunc_first=False, rtol=1e-5,
377
+ endpt_atol=[1e-9, 1e-5])
378
+
379
+ @pytest.mark.xfail(run=False)
380
+ def test_tklmbda_pos_shape(self):
381
+ _assert_inverts(
382
+ sp.tklmbda,
383
+ _tukey_lmbda_quantile,
384
+ 0, [ProbArg(), Arg(0, 100, inclusive_a=False)],
385
+ spfunc_first=False, rtol=1e-5)
386
+
387
+ # The values of lmdba are chosen so that 1/lmbda is exact.
388
+ @pytest.mark.parametrize('lmbda', [0.5, 1.0, 8.0])
389
+ def test_tklmbda_lmbda1(self, lmbda):
390
+ bound = 1/lmbda
391
+ assert_equal(sp.tklmbda([-bound, bound], lmbda), [0.0, 1.0])
392
+
393
+
394
+ funcs = [
395
+ ("btdtria", 3),
396
+ ("btdtrib", 3),
397
+ ("bdtrik", 3),
398
+ ("bdtrin", 3),
399
+ ("chdtriv", 2),
400
+ ("chndtr", 3),
401
+ ("chndtrix", 3),
402
+ ("chndtridf", 3),
403
+ ("chndtrinc", 3),
404
+ ("fdtridfd", 3),
405
+ ("ncfdtr", 4),
406
+ ("ncfdtri", 4),
407
+ ("ncfdtridfn", 4),
408
+ ("ncfdtridfd", 4),
409
+ ("ncfdtrinc", 4),
410
+ ("gdtrix", 3),
411
+ ("gdtrib", 3),
412
+ ("gdtria", 3),
413
+ ("nbdtrik", 3),
414
+ ("nbdtrin", 3),
415
+ ("nrdtrimn", 3),
416
+ ("nrdtrisd", 3),
417
+ ("pdtrik", 2),
418
+ ("stdtr", 2),
419
+ ("stdtrit", 2),
420
+ ("stdtridf", 2),
421
+ ("nctdtr", 3),
422
+ ("nctdtrit", 3),
423
+ ("nctdtridf", 3),
424
+ ("nctdtrinc", 3),
425
+ ("tklmbda", 2),
426
+ ]
427
+
428
+
429
+ @pytest.mark.parametrize('func,numargs', funcs, ids=[x[0] for x in funcs])
430
+ def test_nonfinite(func, numargs):
431
+
432
+ rng = np.random.default_rng(1701299355559735)
433
+ func = getattr(sp, func)
434
+ args_choices = [(float(x), np.nan, np.inf, -np.inf) for x in rng.random(numargs)]
435
+
436
+ for args in itertools.product(*args_choices):
437
+ res = func(*args)
438
+
439
+ if any(np.isnan(x) for x in args):
440
+ # Nan inputs should result to nan output
441
+ assert_equal(res, np.nan)
442
+ else:
443
+ # All other inputs should return something (but not
444
+ # raise exceptions or cause hangs)
445
+ pass
446
+
447
+
448
+ def test_chndtrix_gh2158():
449
+ # test that gh-2158 is resolved; previously this blew up
450
+ res = sp.chndtrix(0.999999, 2, np.arange(20.)+1e-6)
451
+
452
+ # Generated in R
453
+ # options(digits=16)
454
+ # ncp <- seq(0, 19) + 1e-6
455
+ # print(qchisq(0.999999, df = 2, ncp = ncp))
456
+ res_exp = [27.63103493142305, 35.25728589950540, 39.97396073236288,
457
+ 43.88033702110538, 47.35206403482798, 50.54112500166103,
458
+ 53.52720257322766, 56.35830042867810, 59.06600769498512,
459
+ 61.67243118946381, 64.19376191277179, 66.64228141346548,
460
+ 69.02756927200180, 71.35726934749408, 73.63759723904816,
461
+ 75.87368842650227, 78.06984431185720, 80.22971052389806,
462
+ 82.35640899964173, 84.45263768373256]
463
+ assert_allclose(res, res_exp)
464
+
465
+ @pytest.mark.xfail_on_32bit("32bit fails due to algorithm threshold")
466
+ def test_nctdtr_gh19896():
467
+ # test that gh-19896 is resolved.
468
+ # Compared to SciPy 1.11 results from Fortran code.
469
+ dfarr = [0.98, 9.8, 98, 980]
470
+ pnoncarr = [-3.8, 0.38, 3.8, 38]
471
+ tarr = [0.0015, 0.15, 1.5, 15]
472
+ resarr = [0.9999276519560749, 0.9999276519560749, 0.9999908831755221,
473
+ 0.9999990265452424, 0.3524153312279712, 0.39749697267251416,
474
+ 0.7168629634895805, 0.9656246449259646, 7.234804392512006e-05,
475
+ 7.234804392512006e-05, 0.03538804607509127, 0.795482701508521,
476
+ 0.0, 0.0, 0.0,
477
+ 0.011927908523093889, 0.9999276519560749, 0.9999276519560749,
478
+ 0.9999997441133123, 1.0, 0.3525155979118013,
479
+ 0.4076312014048369, 0.8476794017035086, 0.9999999297116268,
480
+ 7.234804392512006e-05, 7.234804392512006e-05, 0.013477443099785824,
481
+ 0.9998501512331494, 0.0, 0.0,
482
+ 0.0, 6.561112613212572e-07, 0.9999276519560749,
483
+ 0.9999276519560749, 0.9999999313496014, 1.0,
484
+ 0.3525281784865706, 0.40890253001898014, 0.8664672830017024,
485
+ 1.0, 7.234804392512006e-05, 7.234804392512006e-05,
486
+ 0.010990889489704836, 1.0, 0.0,
487
+ 0.0, 0.0, 0.0,
488
+ 0.9999276519560749, 0.9999276519560749, 0.9999999418789304,
489
+ 1.0, 0.35252945487817355, 0.40903153246690993,
490
+ 0.8684247068528264, 1.0, 7.234804392512006e-05,
491
+ 7.234804392512006e-05, 0.01075068918582911, 1.0,
492
+ 0.0, 0.0, 0.0, 0.0]
493
+ actarr = []
494
+ for df, p, t in itertools.product(dfarr, pnoncarr, tarr):
495
+ actarr += [sp.nctdtr(df, p, t)]
496
+ # The rtol is kept high on purpose to make it pass on 32bit systems
497
+ assert_allclose(actarr, resarr, rtol=1e-6, atol=0.0)
498
+
499
+
500
+ def test_nctdtrinc_gh19896():
501
+ # test that gh-19896 is resolved.
502
+ # Compared to SciPy 1.11 results from Fortran code.
503
+ dfarr = [0.001, 0.98, 9.8, 98, 980, 10000, 98, 9.8, 0.98, 0.001]
504
+ parr = [0.001, 0.1, 0.3, 0.8, 0.999, 0.001, 0.1, 0.3, 0.8, 0.999]
505
+ tarr = [0.0015, 0.15, 1.5, 15, 300, 0.0015, 0.15, 1.5, 15, 300]
506
+ desired = [3.090232306168629, 1.406141304556198, 2.014225177124157,
507
+ 13.727067118283456, 278.9765683871208, 3.090232306168629,
508
+ 1.4312427877936222, 2.014225177124157, 3.712743137978295,
509
+ -3.086951096691082]
510
+ actual = sp.nctdtrinc(dfarr, parr, tarr)
511
+ assert_allclose(actual, desired, rtol=5e-12, atol=0.0)
512
+
513
+
514
+ def test_stdtr_stdtrit_neg_inf():
515
+ # -inf was treated as +inf and values from the normal were returned
516
+ assert np.all(np.isnan(sp.stdtr(-np.inf, [-np.inf, -1.0, 0.0, 1.0, np.inf])))
517
+ assert np.all(np.isnan(sp.stdtrit(-np.inf, [0.0, 0.25, 0.5, 0.75, 1.0])))
518
+
519
+
520
+ def test_bdtrik_nbdtrik_inf():
521
+ y = np.array(
522
+ [np.nan,-np.inf,-10.0, -1.0, 0.0, .00001, .5, 0.9999, 1.0, 10.0, np.inf])
523
+ y = y[:,None]
524
+ p = np.atleast_2d(
525
+ [np.nan, -np.inf, -10.0, -1.0, 0.0, .00001, .5, 1.0, np.inf])
526
+ assert np.all(np.isnan(sp.bdtrik(y, np.inf, p)))
527
+ assert np.all(np.isnan(sp.nbdtrik(y, np.inf, p)))
env-llmeval/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Callable
3
+
4
+ import pytest
5
+ from itertools import product
6
+ from numpy.testing import assert_allclose, suppress_warnings
7
+ from scipy import special
8
+ from scipy.special import cython_special
9
+
10
+
11
+ bint_points = [True, False]
12
+ int_points = [-10, -1, 1, 10]
13
+ real_points = [-10.0, -1.0, 1.0, 10.0]
14
+ complex_points = [complex(*tup) for tup in product(real_points, repeat=2)]
15
+
16
+
17
+ CYTHON_SIGNATURE_MAP = {
18
+ 'b': 'bint',
19
+ 'f': 'float',
20
+ 'd': 'double',
21
+ 'g': 'long double',
22
+ 'F': 'float complex',
23
+ 'D': 'double complex',
24
+ 'G': 'long double complex',
25
+ 'i': 'int',
26
+ 'l': 'long'
27
+ }
28
+
29
+
30
+ TEST_POINTS = {
31
+ 'b': bint_points,
32
+ 'f': real_points,
33
+ 'd': real_points,
34
+ 'g': real_points,
35
+ 'F': complex_points,
36
+ 'D': complex_points,
37
+ 'G': complex_points,
38
+ 'i': int_points,
39
+ 'l': int_points,
40
+ }
41
+
42
+
43
+ PARAMS: list[tuple[Callable, Callable, tuple[str, ...], str | None]] = [
44
+ (special.agm, cython_special.agm, ('dd',), None),
45
+ (special.airy, cython_special._airy_pywrap, ('d', 'D'), None),
46
+ (special.airye, cython_special._airye_pywrap, ('d', 'D'), None),
47
+ (special.bdtr, cython_special.bdtr, ('dld', 'ddd'), None),
48
+ (special.bdtrc, cython_special.bdtrc, ('dld', 'ddd'), None),
49
+ (special.bdtri, cython_special.bdtri, ('dld', 'ddd'), None),
50
+ (special.bdtrik, cython_special.bdtrik, ('ddd',), None),
51
+ (special.bdtrin, cython_special.bdtrin, ('ddd',), None),
52
+ (special.bei, cython_special.bei, ('d',), None),
53
+ (special.beip, cython_special.beip, ('d',), None),
54
+ (special.ber, cython_special.ber, ('d',), None),
55
+ (special.berp, cython_special.berp, ('d',), None),
56
+ (special.besselpoly, cython_special.besselpoly, ('ddd',), None),
57
+ (special.beta, cython_special.beta, ('dd',), None),
58
+ (special.betainc, cython_special.betainc, ('ddd',), None),
59
+ (special.betaincc, cython_special.betaincc, ('ddd',), None),
60
+ (special.betaincinv, cython_special.betaincinv, ('ddd',), None),
61
+ (special.betainccinv, cython_special.betainccinv, ('ddd',), None),
62
+ (special.betaln, cython_special.betaln, ('dd',), None),
63
+ (special.binom, cython_special.binom, ('dd',), None),
64
+ (special.boxcox, cython_special.boxcox, ('dd',), None),
65
+ (special.boxcox1p, cython_special.boxcox1p, ('dd',), None),
66
+ (special.btdtr, cython_special.btdtr, ('ddd',), None),
67
+ (special.btdtri, cython_special.btdtri, ('ddd',), None),
68
+ (special.btdtria, cython_special.btdtria, ('ddd',), None),
69
+ (special.btdtrib, cython_special.btdtrib, ('ddd',), None),
70
+ (special.cbrt, cython_special.cbrt, ('d',), None),
71
+ (special.chdtr, cython_special.chdtr, ('dd',), None),
72
+ (special.chdtrc, cython_special.chdtrc, ('dd',), None),
73
+ (special.chdtri, cython_special.chdtri, ('dd',), None),
74
+ (special.chdtriv, cython_special.chdtriv, ('dd',), None),
75
+ (special.chndtr, cython_special.chndtr, ('ddd',), None),
76
+ (special.chndtridf, cython_special.chndtridf, ('ddd',), None),
77
+ (special.chndtrinc, cython_special.chndtrinc, ('ddd',), None),
78
+ (special.chndtrix, cython_special.chndtrix, ('ddd',), None),
79
+ (special.cosdg, cython_special.cosdg, ('d',), None),
80
+ (special.cosm1, cython_special.cosm1, ('d',), None),
81
+ (special.cotdg, cython_special.cotdg, ('d',), None),
82
+ (special.dawsn, cython_special.dawsn, ('d', 'D'), None),
83
+ (special.ellipe, cython_special.ellipe, ('d',), None),
84
+ (special.ellipeinc, cython_special.ellipeinc, ('dd',), None),
85
+ (special.ellipj, cython_special._ellipj_pywrap, ('dd',), None),
86
+ (special.ellipkinc, cython_special.ellipkinc, ('dd',), None),
87
+ (special.ellipkm1, cython_special.ellipkm1, ('d',), None),
88
+ (special.ellipk, cython_special.ellipk, ('d',), None),
89
+ (special.elliprc, cython_special.elliprc, ('dd', 'DD'), None),
90
+ (special.elliprd, cython_special.elliprd, ('ddd', 'DDD'), None),
91
+ (special.elliprf, cython_special.elliprf, ('ddd', 'DDD'), None),
92
+ (special.elliprg, cython_special.elliprg, ('ddd', 'DDD'), None),
93
+ (special.elliprj, cython_special.elliprj, ('dddd', 'DDDD'), None),
94
+ (special.entr, cython_special.entr, ('d',), None),
95
+ (special.erf, cython_special.erf, ('d', 'D'), None),
96
+ (special.erfc, cython_special.erfc, ('d', 'D'), None),
97
+ (special.erfcx, cython_special.erfcx, ('d', 'D'), None),
98
+ (special.erfi, cython_special.erfi, ('d', 'D'), None),
99
+ (special.erfinv, cython_special.erfinv, ('d',), None),
100
+ (special.erfcinv, cython_special.erfcinv, ('d',), None),
101
+ (special.eval_chebyc, cython_special.eval_chebyc, ('dd', 'dD', 'ld'), None),
102
+ (special.eval_chebys, cython_special.eval_chebys, ('dd', 'dD', 'ld'),
103
+ 'd and l differ for negative int'),
104
+ (special.eval_chebyt, cython_special.eval_chebyt, ('dd', 'dD', 'ld'),
105
+ 'd and l differ for negative int'),
106
+ (special.eval_chebyu, cython_special.eval_chebyu, ('dd', 'dD', 'ld'),
107
+ 'd and l differ for negative int'),
108
+ (special.eval_gegenbauer, cython_special.eval_gegenbauer, ('ddd', 'ddD', 'ldd'),
109
+ 'd and l differ for negative int'),
110
+ (special.eval_genlaguerre, cython_special.eval_genlaguerre, ('ddd', 'ddD', 'ldd'),
111
+ 'd and l differ for negative int'),
112
+ (special.eval_hermite, cython_special.eval_hermite, ('ld',), None),
113
+ (special.eval_hermitenorm, cython_special.eval_hermitenorm, ('ld',), None),
114
+ (special.eval_jacobi, cython_special.eval_jacobi, ('dddd', 'dddD', 'lddd'),
115
+ 'd and l differ for negative int'),
116
+ (special.eval_laguerre, cython_special.eval_laguerre, ('dd', 'dD', 'ld'),
117
+ 'd and l differ for negative int'),
118
+ (special.eval_legendre, cython_special.eval_legendre, ('dd', 'dD', 'ld'), None),
119
+ (special.eval_sh_chebyt, cython_special.eval_sh_chebyt, ('dd', 'dD', 'ld'), None),
120
+ (special.eval_sh_chebyu, cython_special.eval_sh_chebyu, ('dd', 'dD', 'ld'),
121
+ 'd and l differ for negative int'),
122
+ (special.eval_sh_jacobi, cython_special.eval_sh_jacobi, ('dddd', 'dddD', 'lddd'),
123
+ 'd and l differ for negative int'),
124
+ (special.eval_sh_legendre, cython_special.eval_sh_legendre, ('dd', 'dD', 'ld'),
125
+ None),
126
+ (special.exp1, cython_special.exp1, ('d', 'D'), None),
127
+ (special.exp10, cython_special.exp10, ('d',), None),
128
+ (special.exp2, cython_special.exp2, ('d',), None),
129
+ (special.expi, cython_special.expi, ('d', 'D'), None),
130
+ (special.expit, cython_special.expit, ('f', 'd', 'g'), None),
131
+ (special.expm1, cython_special.expm1, ('d', 'D'), None),
132
+ (special.expn, cython_special.expn, ('ld', 'dd'), None),
133
+ (special.exprel, cython_special.exprel, ('d',), None),
134
+ (special.fdtr, cython_special.fdtr, ('ddd',), None),
135
+ (special.fdtrc, cython_special.fdtrc, ('ddd',), None),
136
+ (special.fdtri, cython_special.fdtri, ('ddd',), None),
137
+ (special.fdtridfd, cython_special.fdtridfd, ('ddd',), None),
138
+ (special.fresnel, cython_special._fresnel_pywrap, ('d', 'D'), None),
139
+ (special.gamma, cython_special.gamma, ('d', 'D'), None),
140
+ (special.gammainc, cython_special.gammainc, ('dd',), None),
141
+ (special.gammaincc, cython_special.gammaincc, ('dd',), None),
142
+ (special.gammainccinv, cython_special.gammainccinv, ('dd',), None),
143
+ (special.gammaincinv, cython_special.gammaincinv, ('dd',), None),
144
+ (special.gammaln, cython_special.gammaln, ('d',), None),
145
+ (special.gammasgn, cython_special.gammasgn, ('d',), None),
146
+ (special.gdtr, cython_special.gdtr, ('ddd',), None),
147
+ (special.gdtrc, cython_special.gdtrc, ('ddd',), None),
148
+ (special.gdtria, cython_special.gdtria, ('ddd',), None),
149
+ (special.gdtrib, cython_special.gdtrib, ('ddd',), None),
150
+ (special.gdtrix, cython_special.gdtrix, ('ddd',), None),
151
+ (special.hankel1, cython_special.hankel1, ('dD',), None),
152
+ (special.hankel1e, cython_special.hankel1e, ('dD',), None),
153
+ (special.hankel2, cython_special.hankel2, ('dD',), None),
154
+ (special.hankel2e, cython_special.hankel2e, ('dD',), None),
155
+ (special.huber, cython_special.huber, ('dd',), None),
156
+ (special.hyp0f1, cython_special.hyp0f1, ('dd', 'dD'), None),
157
+ (special.hyp1f1, cython_special.hyp1f1, ('ddd', 'ddD'), None),
158
+ (special.hyp2f1, cython_special.hyp2f1, ('dddd', 'dddD'), None),
159
+ (special.hyperu, cython_special.hyperu, ('ddd',), None),
160
+ (special.i0, cython_special.i0, ('d',), None),
161
+ (special.i0e, cython_special.i0e, ('d',), None),
162
+ (special.i1, cython_special.i1, ('d',), None),
163
+ (special.i1e, cython_special.i1e, ('d',), None),
164
+ (special.inv_boxcox, cython_special.inv_boxcox, ('dd',), None),
165
+ (special.inv_boxcox1p, cython_special.inv_boxcox1p, ('dd',), None),
166
+ (special.it2i0k0, cython_special._it2i0k0_pywrap, ('d',), None),
167
+ (special.it2j0y0, cython_special._it2j0y0_pywrap, ('d',), None),
168
+ (special.it2struve0, cython_special.it2struve0, ('d',), None),
169
+ (special.itairy, cython_special._itairy_pywrap, ('d',), None),
170
+ (special.iti0k0, cython_special._iti0k0_pywrap, ('d',), None),
171
+ (special.itj0y0, cython_special._itj0y0_pywrap, ('d',), None),
172
+ (special.itmodstruve0, cython_special.itmodstruve0, ('d',), None),
173
+ (special.itstruve0, cython_special.itstruve0, ('d',), None),
174
+ (special.iv, cython_special.iv, ('dd', 'dD'), None),
175
+ (special.ive, cython_special.ive, ('dd', 'dD'), None),
176
+ (special.j0, cython_special.j0, ('d',), None),
177
+ (special.j1, cython_special.j1, ('d',), None),
178
+ (special.jv, cython_special.jv, ('dd', 'dD'), None),
179
+ (special.jve, cython_special.jve, ('dd', 'dD'), None),
180
+ (special.k0, cython_special.k0, ('d',), None),
181
+ (special.k0e, cython_special.k0e, ('d',), None),
182
+ (special.k1, cython_special.k1, ('d',), None),
183
+ (special.k1e, cython_special.k1e, ('d',), None),
184
+ (special.kei, cython_special.kei, ('d',), None),
185
+ (special.keip, cython_special.keip, ('d',), None),
186
+ (special.kelvin, cython_special._kelvin_pywrap, ('d',), None),
187
+ (special.ker, cython_special.ker, ('d',), None),
188
+ (special.kerp, cython_special.kerp, ('d',), None),
189
+ (special.kl_div, cython_special.kl_div, ('dd',), None),
190
+ (special.kn, cython_special.kn, ('ld', 'dd'), None),
191
+ (special.kolmogi, cython_special.kolmogi, ('d',), None),
192
+ (special.kolmogorov, cython_special.kolmogorov, ('d',), None),
193
+ (special.kv, cython_special.kv, ('dd', 'dD'), None),
194
+ (special.kve, cython_special.kve, ('dd', 'dD'), None),
195
+ (special.log1p, cython_special.log1p, ('d', 'D'), None),
196
+ (special.log_expit, cython_special.log_expit, ('f', 'd', 'g'), None),
197
+ (special.log_ndtr, cython_special.log_ndtr, ('d', 'D'), None),
198
+ (special.ndtri_exp, cython_special.ndtri_exp, ('d',), None),
199
+ (special.loggamma, cython_special.loggamma, ('D',), None),
200
+ (special.logit, cython_special.logit, ('f', 'd', 'g'), None),
201
+ (special.lpmv, cython_special.lpmv, ('ddd',), None),
202
+ (special.mathieu_a, cython_special.mathieu_a, ('dd',), None),
203
+ (special.mathieu_b, cython_special.mathieu_b, ('dd',), None),
204
+ (special.mathieu_cem, cython_special._mathieu_cem_pywrap, ('ddd',), None),
205
+ (special.mathieu_modcem1, cython_special._mathieu_modcem1_pywrap, ('ddd',), None),
206
+ (special.mathieu_modcem2, cython_special._mathieu_modcem2_pywrap, ('ddd',), None),
207
+ (special.mathieu_modsem1, cython_special._mathieu_modsem1_pywrap, ('ddd',), None),
208
+ (special.mathieu_modsem2, cython_special._mathieu_modsem2_pywrap, ('ddd',), None),
209
+ (special.mathieu_sem, cython_special._mathieu_sem_pywrap, ('ddd',), None),
210
+ (special.modfresnelm, cython_special._modfresnelm_pywrap, ('d',), None),
211
+ (special.modfresnelp, cython_special._modfresnelp_pywrap, ('d',), None),
212
+ (special.modstruve, cython_special.modstruve, ('dd',), None),
213
+ (special.nbdtr, cython_special.nbdtr, ('lld', 'ddd'), None),
214
+ (special.nbdtrc, cython_special.nbdtrc, ('lld', 'ddd'), None),
215
+ (special.nbdtri, cython_special.nbdtri, ('lld', 'ddd'), None),
216
+ (special.nbdtrik, cython_special.nbdtrik, ('ddd',), None),
217
+ (special.nbdtrin, cython_special.nbdtrin, ('ddd',), None),
218
+ (special.ncfdtr, cython_special.ncfdtr, ('dddd',), None),
219
+ (special.ncfdtri, cython_special.ncfdtri, ('dddd',), None),
220
+ (special.ncfdtridfd, cython_special.ncfdtridfd, ('dddd',), None),
221
+ (special.ncfdtridfn, cython_special.ncfdtridfn, ('dddd',), None),
222
+ (special.ncfdtrinc, cython_special.ncfdtrinc, ('dddd',), None),
223
+ (special.nctdtr, cython_special.nctdtr, ('ddd',), None),
224
+ (special.nctdtridf, cython_special.nctdtridf, ('ddd',), None),
225
+ (special.nctdtrinc, cython_special.nctdtrinc, ('ddd',), None),
226
+ (special.nctdtrit, cython_special.nctdtrit, ('ddd',), None),
227
+ (special.ndtr, cython_special.ndtr, ('d', 'D'), None),
228
+ (special.ndtri, cython_special.ndtri, ('d',), None),
229
+ (special.nrdtrimn, cython_special.nrdtrimn, ('ddd',), None),
230
+ (special.nrdtrisd, cython_special.nrdtrisd, ('ddd',), None),
231
+ (special.obl_ang1, cython_special._obl_ang1_pywrap, ('dddd',), None),
232
+ (special.obl_ang1_cv, cython_special._obl_ang1_cv_pywrap, ('ddddd',), None),
233
+ (special.obl_cv, cython_special.obl_cv, ('ddd',), None),
234
+ (special.obl_rad1, cython_special._obl_rad1_pywrap, ('dddd',), "see gh-6211"),
235
+ (special.obl_rad1_cv, cython_special._obl_rad1_cv_pywrap, ('ddddd',),
236
+ "see gh-6211"),
237
+ (special.obl_rad2, cython_special._obl_rad2_pywrap, ('dddd',), "see gh-6211"),
238
+ (special.obl_rad2_cv, cython_special._obl_rad2_cv_pywrap, ('ddddd',),
239
+ "see gh-6211"),
240
+ (special.pbdv, cython_special._pbdv_pywrap, ('dd',), None),
241
+ (special.pbvv, cython_special._pbvv_pywrap, ('dd',), None),
242
+ (special.pbwa, cython_special._pbwa_pywrap, ('dd',), None),
243
+ (special.pdtr, cython_special.pdtr, ('dd', 'dd'), None),
244
+ (special.pdtrc, cython_special.pdtrc, ('dd', 'dd'), None),
245
+ (special.pdtri, cython_special.pdtri, ('ld', 'dd'), None),
246
+ (special.pdtrik, cython_special.pdtrik, ('dd',), None),
247
+ (special.poch, cython_special.poch, ('dd',), None),
248
+ (special.powm1, cython_special.powm1, ('dd',), None),
249
+ (special.pro_ang1, cython_special._pro_ang1_pywrap, ('dddd',), None),
250
+ (special.pro_ang1_cv, cython_special._pro_ang1_cv_pywrap, ('ddddd',), None),
251
+ (special.pro_cv, cython_special.pro_cv, ('ddd',), None),
252
+ (special.pro_rad1, cython_special._pro_rad1_pywrap, ('dddd',), "see gh-6211"),
253
+ (special.pro_rad1_cv, cython_special._pro_rad1_cv_pywrap, ('ddddd',),
254
+ "see gh-6211"),
255
+ (special.pro_rad2, cython_special._pro_rad2_pywrap, ('dddd',), "see gh-6211"),
256
+ (special.pro_rad2_cv, cython_special._pro_rad2_cv_pywrap, ('ddddd',),
257
+ "see gh-6211"),
258
+ (special.pseudo_huber, cython_special.pseudo_huber, ('dd',), None),
259
+ (special.psi, cython_special.psi, ('d', 'D'), None),
260
+ (special.radian, cython_special.radian, ('ddd',), None),
261
+ (special.rel_entr, cython_special.rel_entr, ('dd',), None),
262
+ (special.rgamma, cython_special.rgamma, ('d', 'D'), None),
263
+ (special.round, cython_special.round, ('d',), None),
264
+ (special.spherical_jn, cython_special.spherical_jn, ('ld', 'ldb', 'lD', 'lDb'),
265
+ None),
266
+ (special.spherical_yn, cython_special.spherical_yn, ('ld', 'ldb', 'lD', 'lDb'),
267
+ None),
268
+ (special.spherical_in, cython_special.spherical_in, ('ld', 'ldb', 'lD', 'lDb'),
269
+ None),
270
+ (special.spherical_kn, cython_special.spherical_kn, ('ld', 'ldb', 'lD', 'lDb'),
271
+ None),
272
+ (special.shichi, cython_special._shichi_pywrap, ('d', 'D'), None),
273
+ (special.sici, cython_special._sici_pywrap, ('d', 'D'), None),
274
+ (special.sindg, cython_special.sindg, ('d',), None),
275
+ (special.smirnov, cython_special.smirnov, ('ld', 'dd'), None),
276
+ (special.smirnovi, cython_special.smirnovi, ('ld', 'dd'), None),
277
+ (special.spence, cython_special.spence, ('d', 'D'), None),
278
+ (special.sph_harm, cython_special.sph_harm, ('lldd', 'dddd'), None),
279
+ (special.stdtr, cython_special.stdtr, ('dd',), None),
280
+ (special.stdtridf, cython_special.stdtridf, ('dd',), None),
281
+ (special.stdtrit, cython_special.stdtrit, ('dd',), None),
282
+ (special.struve, cython_special.struve, ('dd',), None),
283
+ (special.tandg, cython_special.tandg, ('d',), None),
284
+ (special.tklmbda, cython_special.tklmbda, ('dd',), None),
285
+ (special.voigt_profile, cython_special.voigt_profile, ('ddd',), None),
286
+ (special.wofz, cython_special.wofz, ('D',), None),
287
+ (special.wright_bessel, cython_special.wright_bessel, ('ddd',), None),
288
+ (special.wrightomega, cython_special.wrightomega, ('D',), None),
289
+ (special.xlog1py, cython_special.xlog1py, ('dd', 'DD'), None),
290
+ (special.xlogy, cython_special.xlogy, ('dd', 'DD'), None),
291
+ (special.y0, cython_special.y0, ('d',), None),
292
+ (special.y1, cython_special.y1, ('d',), None),
293
+ (special.yn, cython_special.yn, ('ld', 'dd'), None),
294
+ (special.yv, cython_special.yv, ('dd', 'dD'), None),
295
+ (special.yve, cython_special.yve, ('dd', 'dD'), None),
296
+ (special.zetac, cython_special.zetac, ('d',), None),
297
+ (special.owens_t, cython_special.owens_t, ('dd',), None)
298
+ ]
299
+
300
+
301
+ IDS = [x[0].__name__ for x in PARAMS]
302
+
303
+
304
+ def _generate_test_points(typecodes):
305
+ axes = tuple(TEST_POINTS[x] for x in typecodes)
306
+ pts = list(product(*axes))
307
+ return pts
308
+
309
+
310
+ def test_cython_api_completeness():
311
+ # Check that everything is tested
312
+ for name in dir(cython_special):
313
+ func = getattr(cython_special, name)
314
+ if callable(func) and not name.startswith('_'):
315
+ for _, cyfun, _, _ in PARAMS:
316
+ if cyfun is func:
317
+ break
318
+ else:
319
+ raise RuntimeError(f"{name} missing from tests!")
320
+
321
+
322
+ @pytest.mark.parametrize("param", PARAMS, ids=IDS)
323
+ def test_cython_api(param):
324
+ pyfunc, cyfunc, specializations, knownfailure = param
325
+ if knownfailure:
326
+ pytest.xfail(reason=knownfailure)
327
+
328
+ # Check which parameters are expected to be fused types
329
+ max_params = max(len(spec) for spec in specializations)
330
+ values = [set() for _ in range(max_params)]
331
+ for typecodes in specializations:
332
+ for j, v in enumerate(typecodes):
333
+ values[j].add(v)
334
+ seen = set()
335
+ is_fused_code = [False] * len(values)
336
+ for j, v in enumerate(values):
337
+ vv = tuple(sorted(v))
338
+ if vv in seen:
339
+ continue
340
+ is_fused_code[j] = (len(v) > 1)
341
+ seen.add(vv)
342
+
343
+ # Check results
344
+ for typecodes in specializations:
345
+ # Pick the correct specialized function
346
+ signature = [CYTHON_SIGNATURE_MAP[code]
347
+ for j, code in enumerate(typecodes)
348
+ if is_fused_code[j]]
349
+
350
+ if signature:
351
+ cy_spec_func = cyfunc[tuple(signature)]
352
+ else:
353
+ signature = None
354
+ cy_spec_func = cyfunc
355
+
356
+ # Test it
357
+ pts = _generate_test_points(typecodes)
358
+ for pt in pts:
359
+ with suppress_warnings() as sup:
360
+ sup.filter(DeprecationWarning)
361
+ pyval = pyfunc(*pt)
362
+ cyval = cy_spec_func(*pt)
363
+ assert_allclose(cyval, pyval, err_msg=f"{pt} {typecodes} {signature}")