ZTWHHH commited on
Commit
98137ab
·
verified ·
1 Parent(s): dc1ff3a

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. llava_video/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llava_video/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc +0 -0
  3. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py +0 -0
  4. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py +217 -0
  5. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py +714 -0
  6. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py +1389 -0
  7. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py +74 -0
  8. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py +680 -0
  9. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py +732 -0
  10. llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py +1153 -0
  11. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_backward.h +26 -0
  12. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cudnn_rnn.h +91 -0
  13. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cummax_helper.h +30 -0
  14. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_ops.h +28 -0
  15. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin_ops.h +50 -0
  16. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tan.h +44 -0
  17. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_fw_primal_copy_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
  18. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_cpu_dispatch.h +25 -0
  19. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_solve_ex_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
  20. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_scale_ops.h +39 -0
  21. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_sum_backward.h +30 -0
  22. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_buffer_ops.h +28 -0
  23. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_pack_padded_sequence_native.h +22 -0
  24. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_cuda_dispatch.h +23 -0
  25. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_cpu_dispatch.h +23 -0
  26. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h +34 -0
  27. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_mm_cuda_dispatch.h +23 -0
  28. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautograd_dispatch.h +24 -0
  29. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h +30 -0
  30. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_ops.h +39 -0
  31. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_unsafe_masked_index.h +30 -0
  32. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/addr_ops.h +50 -0
  33. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/all_cuda_dispatch.h +31 -0
  34. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy.h +39 -0
  35. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cat_cuda_dispatch.h +25 -0
  36. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose1d_native.h +21 -0
  37. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/elu_backward_cpu_dispatch.h +25 -0
  38. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fft_irfft2.h +91 -0
  39. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool2d_backward_meta_dispatch.h +25 -0
  40. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h +25 -0
  41. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/hardtanh_backward_ops.h +39 -0
  42. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/huber_loss_backward_cuda_dispatch.h +24 -0
  43. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_add_compositeimplicitautograd_dispatch.h +23 -0
  44. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_meta.h +50 -0
  45. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_reduce_meta_dispatch.h +26 -0
  46. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/is_pinned_compositeexplicitautograd_dispatch.h +23 -0
  47. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/logaddexp_cuda_dispatch.h +25 -0
  48. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/logical_or_ops.h +50 -0
  49. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/minimum_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
  50. pllava/lib/python3.10/site-packages/torch/include/ATen/ops/nanmedian_compositeexplicitautograd_dispatch.h +25 -0
llava_video/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (540 Bytes). View file
 
llava_video/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc ADDED
Binary file (8.49 kB). View file
 
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py ADDED
File without changes
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_allclose
5
+
6
+ from scipy.integrate import quad_vec
7
+
8
+ from multiprocessing.dummy import Pool
9
+
10
+
11
+ quadrature_params = pytest.mark.parametrize(
12
+ 'quadrature', [None, "gk15", "gk21", "trapezoid"])
13
+
14
+
15
+ @quadrature_params
16
+ def test_quad_vec_simple(quadrature):
17
+ n = np.arange(10)
18
+ def f(x):
19
+ return x ** n
20
+ for epsabs in [0.1, 1e-3, 1e-6]:
21
+ if quadrature == 'trapezoid' and epsabs < 1e-4:
22
+ # slow: skip
23
+ continue
24
+
25
+ kwargs = dict(epsabs=epsabs, quadrature=quadrature)
26
+
27
+ exact = 2**(n+1)/(n + 1)
28
+
29
+ res, err = quad_vec(f, 0, 2, norm='max', **kwargs)
30
+ assert_allclose(res, exact, rtol=0, atol=epsabs)
31
+
32
+ res, err = quad_vec(f, 0, 2, norm='2', **kwargs)
33
+ assert np.linalg.norm(res - exact) < epsabs
34
+
35
+ res, err = quad_vec(f, 0, 2, norm='max', points=(0.5, 1.0), **kwargs)
36
+ assert_allclose(res, exact, rtol=0, atol=epsabs)
37
+
38
+ res, err, *rest = quad_vec(f, 0, 2, norm='max',
39
+ epsrel=1e-8,
40
+ full_output=True,
41
+ limit=10000,
42
+ **kwargs)
43
+ assert_allclose(res, exact, rtol=0, atol=epsabs)
44
+
45
+
46
+ @quadrature_params
47
+ def test_quad_vec_simple_inf(quadrature):
48
+ def f(x):
49
+ return 1 / (1 + np.float64(x) ** 2)
50
+
51
+ for epsabs in [0.1, 1e-3, 1e-6]:
52
+ if quadrature == 'trapezoid' and epsabs < 1e-4:
53
+ # slow: skip
54
+ continue
55
+
56
+ kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature)
57
+
58
+ res, err = quad_vec(f, 0, np.inf, **kwargs)
59
+ assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
60
+
61
+ res, err = quad_vec(f, 0, -np.inf, **kwargs)
62
+ assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
63
+
64
+ res, err = quad_vec(f, -np.inf, 0, **kwargs)
65
+ assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
66
+
67
+ res, err = quad_vec(f, np.inf, 0, **kwargs)
68
+ assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
69
+
70
+ res, err = quad_vec(f, -np.inf, np.inf, **kwargs)
71
+ assert_allclose(res, np.pi, rtol=0, atol=max(epsabs, err))
72
+
73
+ res, err = quad_vec(f, np.inf, -np.inf, **kwargs)
74
+ assert_allclose(res, -np.pi, rtol=0, atol=max(epsabs, err))
75
+
76
+ res, err = quad_vec(f, np.inf, np.inf, **kwargs)
77
+ assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
78
+
79
+ res, err = quad_vec(f, -np.inf, -np.inf, **kwargs)
80
+ assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
81
+
82
+ res, err = quad_vec(f, 0, np.inf, points=(1.0, 2.0), **kwargs)
83
+ assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
84
+
85
+ def f(x):
86
+ return np.sin(x + 2) / (1 + x ** 2)
87
+ exact = np.pi / np.e * np.sin(2)
88
+ epsabs = 1e-5
89
+
90
+ res, err, info = quad_vec(f, -np.inf, np.inf, limit=1000, norm='max', epsabs=epsabs,
91
+ quadrature=quadrature, full_output=True)
92
+ assert info.status == 1
93
+ assert_allclose(res, exact, rtol=0, atol=max(epsabs, 1.5 * err))
94
+
95
+
96
+ def test_quad_vec_args():
97
+ def f(x, a):
98
+ return x * (x + a) * np.arange(3)
99
+ a = 2
100
+ exact = np.array([0, 4/3, 8/3])
101
+
102
+ res, err = quad_vec(f, 0, 1, args=(a,))
103
+ assert_allclose(res, exact, rtol=0, atol=1e-4)
104
+
105
+
106
+ def _lorenzian(x):
107
+ return 1 / (1 + x**2)
108
+
109
+
110
+ @pytest.mark.fail_slow(10)
111
+ def test_quad_vec_pool():
112
+ f = _lorenzian
113
+ res, err = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=4)
114
+ assert_allclose(res, np.pi, rtol=0, atol=1e-4)
115
+
116
+ with Pool(10) as pool:
117
+ def f(x):
118
+ return 1 / (1 + x ** 2)
119
+ res, _ = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=pool.map)
120
+ assert_allclose(res, np.pi, rtol=0, atol=1e-4)
121
+
122
+
123
+ def _func_with_args(x, a):
124
+ return x * (x + a) * np.arange(3)
125
+
126
+
127
+ @pytest.mark.fail_slow(10)
128
+ @pytest.mark.parametrize('extra_args', [2, (2,)])
129
+ @pytest.mark.parametrize('workers', [1, 10])
130
+ def test_quad_vec_pool_args(extra_args, workers):
131
+ f = _func_with_args
132
+ exact = np.array([0, 4/3, 8/3])
133
+
134
+ res, err = quad_vec(f, 0, 1, args=extra_args, workers=workers)
135
+ assert_allclose(res, exact, rtol=0, atol=1e-4)
136
+
137
+ with Pool(workers) as pool:
138
+ res, err = quad_vec(f, 0, 1, args=extra_args, workers=pool.map)
139
+ assert_allclose(res, exact, rtol=0, atol=1e-4)
140
+
141
+
142
+ @quadrature_params
143
+ def test_num_eval(quadrature):
144
+ def f(x):
145
+ count[0] += 1
146
+ return x**5
147
+
148
+ count = [0]
149
+ res = quad_vec(f, 0, 1, norm='max', full_output=True, quadrature=quadrature)
150
+ assert res[2].neval == count[0]
151
+
152
+
153
+ def test_info():
154
+ def f(x):
155
+ return np.ones((3, 2, 1))
156
+
157
+ res, err, info = quad_vec(f, 0, 1, norm='max', full_output=True)
158
+
159
+ assert info.success is True
160
+ assert info.status == 0
161
+ assert info.message == 'Target precision reached.'
162
+ assert info.neval > 0
163
+ assert info.intervals.shape[1] == 2
164
+ assert info.integrals.shape == (info.intervals.shape[0], 3, 2, 1)
165
+ assert info.errors.shape == (info.intervals.shape[0],)
166
+
167
+
168
+ def test_nan_inf():
169
+ def f_nan(x):
170
+ return np.nan
171
+
172
+ def f_inf(x):
173
+ return np.inf if x < 0.1 else 1/x
174
+
175
+ res, err, info = quad_vec(f_nan, 0, 1, full_output=True)
176
+ assert info.status == 3
177
+
178
+ res, err, info = quad_vec(f_inf, 0, 1, full_output=True)
179
+ assert info.status == 3
180
+
181
+
182
+ @pytest.mark.parametrize('a,b', [(0, 1), (0, np.inf), (np.inf, 0),
183
+ (-np.inf, np.inf), (np.inf, -np.inf)])
184
+ def test_points(a, b):
185
+ # Check that initial interval splitting is done according to
186
+ # `points`, by checking that consecutive sets of 15 point (for
187
+ # gk15) function evaluations lie between `points`
188
+
189
+ points = (0, 0.25, 0.5, 0.75, 1.0)
190
+ points += tuple(-x for x in points)
191
+
192
+ quadrature_points = 15
193
+ interval_sets = []
194
+ count = 0
195
+
196
+ def f(x):
197
+ nonlocal count
198
+
199
+ if count % quadrature_points == 0:
200
+ interval_sets.append(set())
201
+
202
+ count += 1
203
+ interval_sets[-1].add(float(x))
204
+ return 0.0
205
+
206
+ quad_vec(f, a, b, points=points, quadrature='gk15', limit=0)
207
+
208
+ # Check that all point sets lie in a single `points` interval
209
+ for p in interval_sets:
210
+ j = np.searchsorted(sorted(points), tuple(p))
211
+ assert np.all(j == j[0])
212
+
213
+
214
+ @pytest.mark.thread_unsafe
215
+ def test_trapz_deprecation():
216
+ with pytest.deprecated_call(match="`quadrature='trapz'`"):
217
+ quad_vec(lambda x: x, 0, 1, quadrature="trapz")
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py ADDED
@@ -0,0 +1,714 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ try:
4
+ from StringIO import StringIO
5
+ except ImportError:
6
+ from io import StringIO
7
+
8
+ import numpy as np
9
+ from numpy.testing import (assert_, assert_array_equal, assert_allclose,
10
+ assert_equal)
11
+ from pytest import raises as assert_raises
12
+
13
+ from scipy.sparse import coo_matrix
14
+ from scipy.special import erf
15
+ from scipy.integrate._bvp import (modify_mesh, estimate_fun_jac,
16
+ estimate_bc_jac, compute_jac_indices,
17
+ construct_global_jac, solve_bvp)
18
+
19
+ import pytest
20
+
21
+
22
+ def exp_fun(x, y):
23
+ return np.vstack((y[1], y[0]))
24
+
25
+
26
+ def exp_fun_jac(x, y):
27
+ df_dy = np.empty((2, 2, x.shape[0]))
28
+ df_dy[0, 0] = 0
29
+ df_dy[0, 1] = 1
30
+ df_dy[1, 0] = 1
31
+ df_dy[1, 1] = 0
32
+ return df_dy
33
+
34
+
35
+ def exp_bc(ya, yb):
36
+ return np.hstack((ya[0] - 1, yb[0]))
37
+
38
+
39
+ def exp_bc_complex(ya, yb):
40
+ return np.hstack((ya[0] - 1 - 1j, yb[0]))
41
+
42
+
43
+ def exp_bc_jac(ya, yb):
44
+ dbc_dya = np.array([
45
+ [1, 0],
46
+ [0, 0]
47
+ ])
48
+ dbc_dyb = np.array([
49
+ [0, 0],
50
+ [1, 0]
51
+ ])
52
+ return dbc_dya, dbc_dyb
53
+
54
+
55
+ def exp_sol(x):
56
+ return (np.exp(-x) - np.exp(x - 2)) / (1 - np.exp(-2))
57
+
58
+
59
+ def sl_fun(x, y, p):
60
+ return np.vstack((y[1], -p[0]**2 * y[0]))
61
+
62
+
63
+ def sl_fun_jac(x, y, p):
64
+ n, m = y.shape
65
+ df_dy = np.empty((n, 2, m))
66
+ df_dy[0, 0] = 0
67
+ df_dy[0, 1] = 1
68
+ df_dy[1, 0] = -p[0]**2
69
+ df_dy[1, 1] = 0
70
+
71
+ df_dp = np.empty((n, 1, m))
72
+ df_dp[0, 0] = 0
73
+ df_dp[1, 0] = -2 * p[0] * y[0]
74
+
75
+ return df_dy, df_dp
76
+
77
+
78
+ def sl_bc(ya, yb, p):
79
+ return np.hstack((ya[0], yb[0], ya[1] - p[0]))
80
+
81
+
82
+ def sl_bc_jac(ya, yb, p):
83
+ dbc_dya = np.zeros((3, 2))
84
+ dbc_dya[0, 0] = 1
85
+ dbc_dya[2, 1] = 1
86
+
87
+ dbc_dyb = np.zeros((3, 2))
88
+ dbc_dyb[1, 0] = 1
89
+
90
+ dbc_dp = np.zeros((3, 1))
91
+ dbc_dp[2, 0] = -1
92
+
93
+ return dbc_dya, dbc_dyb, dbc_dp
94
+
95
+
96
+ def sl_sol(x, p):
97
+ return np.sin(p[0] * x)
98
+
99
+
100
+ def emden_fun(x, y):
101
+ return np.vstack((y[1], -y[0]**5))
102
+
103
+
104
+ def emden_fun_jac(x, y):
105
+ df_dy = np.empty((2, 2, x.shape[0]))
106
+ df_dy[0, 0] = 0
107
+ df_dy[0, 1] = 1
108
+ df_dy[1, 0] = -5 * y[0]**4
109
+ df_dy[1, 1] = 0
110
+ return df_dy
111
+
112
+
113
+ def emden_bc(ya, yb):
114
+ return np.array([ya[1], yb[0] - (3/4)**0.5])
115
+
116
+
117
+ def emden_bc_jac(ya, yb):
118
+ dbc_dya = np.array([
119
+ [0, 1],
120
+ [0, 0]
121
+ ])
122
+ dbc_dyb = np.array([
123
+ [0, 0],
124
+ [1, 0]
125
+ ])
126
+ return dbc_dya, dbc_dyb
127
+
128
+
129
+ def emden_sol(x):
130
+ return (1 + x**2/3)**-0.5
131
+
132
+
133
+ def undefined_fun(x, y):
134
+ return np.zeros_like(y)
135
+
136
+
137
+ def undefined_bc(ya, yb):
138
+ return np.array([ya[0], yb[0] - 1])
139
+
140
+
141
+ def big_fun(x, y):
142
+ f = np.zeros_like(y)
143
+ f[::2] = y[1::2]
144
+ return f
145
+
146
+
147
+ def big_bc(ya, yb):
148
+ return np.hstack((ya[::2], yb[::2] - 1))
149
+
150
+
151
+ def big_sol(x, n):
152
+ y = np.ones((2 * n, x.size))
153
+ y[::2] = x
154
+ return x
155
+
156
+
157
+ def big_fun_with_parameters(x, y, p):
158
+ """ Big version of sl_fun, with two parameters.
159
+
160
+ The two differential equations represented by sl_fun are broadcast to the
161
+ number of rows of y, rotating between the parameters p[0] and p[1].
162
+ Here are the differential equations:
163
+
164
+ dy[0]/dt = y[1]
165
+ dy[1]/dt = -p[0]**2 * y[0]
166
+ dy[2]/dt = y[3]
167
+ dy[3]/dt = -p[1]**2 * y[2]
168
+ dy[4]/dt = y[5]
169
+ dy[5]/dt = -p[0]**2 * y[4]
170
+ dy[6]/dt = y[7]
171
+ dy[7]/dt = -p[1]**2 * y[6]
172
+ .
173
+ .
174
+ .
175
+
176
+ """
177
+ f = np.zeros_like(y)
178
+ f[::2] = y[1::2]
179
+ f[1::4] = -p[0]**2 * y[::4]
180
+ f[3::4] = -p[1]**2 * y[2::4]
181
+ return f
182
+
183
+
184
+ def big_fun_with_parameters_jac(x, y, p):
185
+ # big version of sl_fun_jac, with two parameters
186
+ n, m = y.shape
187
+ df_dy = np.zeros((n, n, m))
188
+ df_dy[range(0, n, 2), range(1, n, 2)] = 1
189
+ df_dy[range(1, n, 4), range(0, n, 4)] = -p[0]**2
190
+ df_dy[range(3, n, 4), range(2, n, 4)] = -p[1]**2
191
+
192
+ df_dp = np.zeros((n, 2, m))
193
+ df_dp[range(1, n, 4), 0] = -2 * p[0] * y[range(0, n, 4)]
194
+ df_dp[range(3, n, 4), 1] = -2 * p[1] * y[range(2, n, 4)]
195
+
196
+ return df_dy, df_dp
197
+
198
+
199
+ def big_bc_with_parameters(ya, yb, p):
200
+ # big version of sl_bc, with two parameters
201
+ return np.hstack((ya[::2], yb[::2], ya[1] - p[0], ya[3] - p[1]))
202
+
203
+
204
+ def big_bc_with_parameters_jac(ya, yb, p):
205
+ # big version of sl_bc_jac, with two parameters
206
+ n = ya.shape[0]
207
+ dbc_dya = np.zeros((n + 2, n))
208
+ dbc_dyb = np.zeros((n + 2, n))
209
+
210
+ dbc_dya[range(n // 2), range(0, n, 2)] = 1
211
+ dbc_dyb[range(n // 2, n), range(0, n, 2)] = 1
212
+
213
+ dbc_dp = np.zeros((n + 2, 2))
214
+ dbc_dp[n, 0] = -1
215
+ dbc_dya[n, 1] = 1
216
+ dbc_dp[n + 1, 1] = -1
217
+ dbc_dya[n + 1, 3] = 1
218
+
219
+ return dbc_dya, dbc_dyb, dbc_dp
220
+
221
+
222
+ def big_sol_with_parameters(x, p):
223
+ # big version of sl_sol, with two parameters
224
+ return np.vstack((np.sin(p[0] * x), np.sin(p[1] * x)))
225
+
226
+
227
+ def shock_fun(x, y):
228
+ eps = 1e-3
229
+ return np.vstack((
230
+ y[1],
231
+ -(x * y[1] + eps * np.pi**2 * np.cos(np.pi * x) +
232
+ np.pi * x * np.sin(np.pi * x)) / eps
233
+ ))
234
+
235
+
236
+ def shock_bc(ya, yb):
237
+ return np.array([ya[0] + 2, yb[0]])
238
+
239
+
240
+ def shock_sol(x):
241
+ eps = 1e-3
242
+ k = np.sqrt(2 * eps)
243
+ return np.cos(np.pi * x) + erf(x / k) / erf(1 / k)
244
+
245
+
246
+ def nonlin_bc_fun(x, y):
247
+ # laplace eq.
248
+ return np.stack([y[1], np.zeros_like(x)])
249
+
250
+
251
+ def nonlin_bc_bc(ya, yb):
252
+ phiA, phipA = ya
253
+ phiC, phipC = yb
254
+
255
+ kappa, ioA, ioC, V, f = 1.64, 0.01, 1.0e-4, 0.5, 38.9
256
+
257
+ # Butler-Volmer Kinetics at Anode
258
+ hA = 0.0-phiA-0.0
259
+ iA = ioA * (np.exp(f*hA) - np.exp(-f*hA))
260
+ res0 = iA + kappa * phipA
261
+
262
+ # Butler-Volmer Kinetics at Cathode
263
+ hC = V - phiC - 1.0
264
+ iC = ioC * (np.exp(f*hC) - np.exp(-f*hC))
265
+ res1 = iC - kappa*phipC
266
+
267
+ return np.array([res0, res1])
268
+
269
+
270
+ def nonlin_bc_sol(x):
271
+ return -0.13426436116763119 - 1.1308709 * x
272
+
273
+
274
+ def test_modify_mesh():
275
+ x = np.array([0, 1, 3, 9], dtype=float)
276
+ x_new = modify_mesh(x, np.array([0]), np.array([2]))
277
+ assert_array_equal(x_new, np.array([0, 0.5, 1, 3, 5, 7, 9]))
278
+
279
+ x = np.array([-6, -3, 0, 3, 6], dtype=float)
280
+ x_new = modify_mesh(x, np.array([1], dtype=int), np.array([0, 2, 3]))
281
+ assert_array_equal(x_new, [-6, -5, -4, -3, -1.5, 0, 1, 2, 3, 4, 5, 6])
282
+
283
+
284
+ def test_compute_fun_jac():
285
+ x = np.linspace(0, 1, 5)
286
+ y = np.empty((2, x.shape[0]))
287
+ y[0] = 0.01
288
+ y[1] = 0.02
289
+ p = np.array([])
290
+ df_dy, df_dp = estimate_fun_jac(lambda x, y, p: exp_fun(x, y), x, y, p)
291
+ df_dy_an = exp_fun_jac(x, y)
292
+ assert_allclose(df_dy, df_dy_an)
293
+ assert_(df_dp is None)
294
+
295
+ x = np.linspace(0, np.pi, 5)
296
+ y = np.empty((2, x.shape[0]))
297
+ y[0] = np.sin(x)
298
+ y[1] = np.cos(x)
299
+ p = np.array([1.0])
300
+ df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
301
+ df_dy_an, df_dp_an = sl_fun_jac(x, y, p)
302
+ assert_allclose(df_dy, df_dy_an)
303
+ assert_allclose(df_dp, df_dp_an)
304
+
305
+ x = np.linspace(0, 1, 10)
306
+ y = np.empty((2, x.shape[0]))
307
+ y[0] = (3/4)**0.5
308
+ y[1] = 1e-4
309
+ p = np.array([])
310
+ df_dy, df_dp = estimate_fun_jac(lambda x, y, p: emden_fun(x, y), x, y, p)
311
+ df_dy_an = emden_fun_jac(x, y)
312
+ assert_allclose(df_dy, df_dy_an)
313
+ assert_(df_dp is None)
314
+
315
+
316
+ def test_compute_bc_jac():
317
+ ya = np.array([-1.0, 2])
318
+ yb = np.array([0.5, 3])
319
+ p = np.array([])
320
+ dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
321
+ lambda ya, yb, p: exp_bc(ya, yb), ya, yb, p)
322
+ dbc_dya_an, dbc_dyb_an = exp_bc_jac(ya, yb)
323
+ assert_allclose(dbc_dya, dbc_dya_an)
324
+ assert_allclose(dbc_dyb, dbc_dyb_an)
325
+ assert_(dbc_dp is None)
326
+
327
+ ya = np.array([0.0, 1])
328
+ yb = np.array([0.0, -1])
329
+ p = np.array([0.5])
330
+ dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, ya, yb, p)
331
+ dbc_dya_an, dbc_dyb_an, dbc_dp_an = sl_bc_jac(ya, yb, p)
332
+ assert_allclose(dbc_dya, dbc_dya_an)
333
+ assert_allclose(dbc_dyb, dbc_dyb_an)
334
+ assert_allclose(dbc_dp, dbc_dp_an)
335
+
336
+ ya = np.array([0.5, 100])
337
+ yb = np.array([-1000, 10.5])
338
+ p = np.array([])
339
+ dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
340
+ lambda ya, yb, p: emden_bc(ya, yb), ya, yb, p)
341
+ dbc_dya_an, dbc_dyb_an = emden_bc_jac(ya, yb)
342
+ assert_allclose(dbc_dya, dbc_dya_an)
343
+ assert_allclose(dbc_dyb, dbc_dyb_an)
344
+ assert_(dbc_dp is None)
345
+
346
+
347
+ def test_compute_jac_indices():
348
+ n = 2
349
+ m = 4
350
+ k = 2
351
+ i, j = compute_jac_indices(n, m, k)
352
+ s = coo_matrix((np.ones_like(i), (i, j))).toarray()
353
+ s_true = np.array([
354
+ [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
355
+ [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
356
+ [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
357
+ [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
358
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
359
+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
360
+ [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
361
+ [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
362
+ [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
363
+ [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
364
+ ])
365
+ assert_array_equal(s, s_true)
366
+
367
+
368
+ def test_compute_global_jac():
369
+ n = 2
370
+ m = 5
371
+ k = 1
372
+ i_jac, j_jac = compute_jac_indices(2, 5, 1)
373
+ x = np.linspace(0, 1, 5)
374
+ h = np.diff(x)
375
+ y = np.vstack((np.sin(np.pi * x), np.pi * np.cos(np.pi * x)))
376
+ p = np.array([3.0])
377
+
378
+ f = sl_fun(x, y, p)
379
+
380
+ x_middle = x[:-1] + 0.5 * h
381
+ y_middle = 0.5 * (y[:, :-1] + y[:, 1:]) - h/8 * (f[:, 1:] - f[:, :-1])
382
+
383
+ df_dy, df_dp = sl_fun_jac(x, y, p)
384
+ df_dy_middle, df_dp_middle = sl_fun_jac(x_middle, y_middle, p)
385
+ dbc_dya, dbc_dyb, dbc_dp = sl_bc_jac(y[:, 0], y[:, -1], p)
386
+
387
+ J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
388
+ df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
389
+ J = J.toarray()
390
+
391
+ def J_block(h, p):
392
+ return np.array([
393
+ [h**2*p**2/12 - 1, -0.5*h, -h**2*p**2/12 + 1, -0.5*h],
394
+ [0.5*h*p**2, h**2*p**2/12 - 1, 0.5*h*p**2, 1 - h**2*p**2/12]
395
+ ])
396
+
397
+ J_true = np.zeros((m * n + k, m * n + k))
398
+ for i in range(m - 1):
399
+ J_true[i * n: (i + 1) * n, i * n: (i + 2) * n] = J_block(h[i], p[0])
400
+
401
+ J_true[:(m - 1) * n:2, -1] = p * h**2/6 * (y[0, :-1] - y[0, 1:])
402
+ J_true[1:(m - 1) * n:2, -1] = p * (h * (y[0, :-1] + y[0, 1:]) +
403
+ h**2/6 * (y[1, :-1] - y[1, 1:]))
404
+
405
+ J_true[8, 0] = 1
406
+ J_true[9, 8] = 1
407
+ J_true[10, 1] = 1
408
+ J_true[10, 10] = -1
409
+
410
+ assert_allclose(J, J_true, rtol=1e-10)
411
+
412
+ df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
413
+ df_dy_middle, df_dp_middle = estimate_fun_jac(sl_fun, x_middle, y_middle, p)
414
+ dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, y[:, 0], y[:, -1], p)
415
+ J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
416
+ df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
417
+ J = J.toarray()
418
+ assert_allclose(J, J_true, rtol=2e-8, atol=2e-8)
419
+
420
+
421
+ def test_parameter_validation():
422
+ x = [0, 1, 0.5]
423
+ y = np.zeros((2, 3))
424
+ assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
425
+
426
+ x = np.linspace(0, 1, 5)
427
+ y = np.zeros((2, 4))
428
+ assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
429
+
430
+ def fun(x, y, p):
431
+ return exp_fun(x, y)
432
+ def bc(ya, yb, p):
433
+ return exp_bc(ya, yb)
434
+
435
+ y = np.zeros((2, x.shape[0]))
436
+ assert_raises(ValueError, solve_bvp, fun, bc, x, y, p=[1])
437
+
438
+ def wrong_shape_fun(x, y):
439
+ return np.zeros(3)
440
+
441
+ assert_raises(ValueError, solve_bvp, wrong_shape_fun, bc, x, y)
442
+
443
+ S = np.array([[0, 0]])
444
+ assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y, S=S)
445
+
446
+
447
+ def test_no_params():
448
+ x = np.linspace(0, 1, 5)
449
+ x_test = np.linspace(0, 1, 100)
450
+ y = np.zeros((2, x.shape[0]))
451
+ for fun_jac in [None, exp_fun_jac]:
452
+ for bc_jac in [None, exp_bc_jac]:
453
+ sol = solve_bvp(exp_fun, exp_bc, x, y, fun_jac=fun_jac,
454
+ bc_jac=bc_jac)
455
+
456
+ assert_equal(sol.status, 0)
457
+ assert_(sol.success)
458
+
459
+ assert_equal(sol.x.size, 5)
460
+
461
+ sol_test = sol.sol(x_test)
462
+
463
+ assert_allclose(sol_test[0], exp_sol(x_test), atol=1e-5)
464
+
465
+ f_test = exp_fun(x_test, sol_test)
466
+ r = sol.sol(x_test, 1) - f_test
467
+ rel_res = r / (1 + np.abs(f_test))
468
+ norm_res = np.sum(rel_res**2, axis=0)**0.5
469
+ assert_(np.all(norm_res < 1e-3))
470
+
471
+ assert_(np.all(sol.rms_residuals < 1e-3))
472
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
473
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
474
+
475
+
476
+ def test_with_params():
477
+ x = np.linspace(0, np.pi, 5)
478
+ x_test = np.linspace(0, np.pi, 100)
479
+ y = np.ones((2, x.shape[0]))
480
+
481
+ for fun_jac in [None, sl_fun_jac]:
482
+ for bc_jac in [None, sl_bc_jac]:
483
+ sol = solve_bvp(sl_fun, sl_bc, x, y, p=[0.5], fun_jac=fun_jac,
484
+ bc_jac=bc_jac)
485
+
486
+ assert_equal(sol.status, 0)
487
+ assert_(sol.success)
488
+
489
+ assert_(sol.x.size < 10)
490
+
491
+ assert_allclose(sol.p, [1], rtol=1e-4)
492
+
493
+ sol_test = sol.sol(x_test)
494
+
495
+ assert_allclose(sol_test[0], sl_sol(x_test, [1]),
496
+ rtol=1e-4, atol=1e-4)
497
+
498
+ f_test = sl_fun(x_test, sol_test, [1])
499
+ r = sol.sol(x_test, 1) - f_test
500
+ rel_res = r / (1 + np.abs(f_test))
501
+ norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
502
+ assert_(np.all(norm_res < 1e-3))
503
+
504
+ assert_(np.all(sol.rms_residuals < 1e-3))
505
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
506
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
507
+
508
+
509
+ def test_singular_term():
510
+ x = np.linspace(0, 1, 10)
511
+ x_test = np.linspace(0.05, 1, 100)
512
+ y = np.empty((2, 10))
513
+ y[0] = (3/4)**0.5
514
+ y[1] = 1e-4
515
+ S = np.array([[0, 0], [0, -2]])
516
+
517
+ for fun_jac in [None, emden_fun_jac]:
518
+ for bc_jac in [None, emden_bc_jac]:
519
+ sol = solve_bvp(emden_fun, emden_bc, x, y, S=S, fun_jac=fun_jac,
520
+ bc_jac=bc_jac)
521
+
522
+ assert_equal(sol.status, 0)
523
+ assert_(sol.success)
524
+
525
+ assert_equal(sol.x.size, 10)
526
+
527
+ sol_test = sol.sol(x_test)
528
+ assert_allclose(sol_test[0], emden_sol(x_test), atol=1e-5)
529
+
530
+ f_test = emden_fun(x_test, sol_test) + S.dot(sol_test) / x_test
531
+ r = sol.sol(x_test, 1) - f_test
532
+ rel_res = r / (1 + np.abs(f_test))
533
+ norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
534
+
535
+ assert_(np.all(norm_res < 1e-3))
536
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
537
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
538
+
539
+
540
+ def test_complex():
541
+ # The test is essentially the same as test_no_params, but boundary
542
+ # conditions are turned into complex.
543
+ x = np.linspace(0, 1, 5)
544
+ x_test = np.linspace(0, 1, 100)
545
+ y = np.zeros((2, x.shape[0]), dtype=complex)
546
+ for fun_jac in [None, exp_fun_jac]:
547
+ for bc_jac in [None, exp_bc_jac]:
548
+ sol = solve_bvp(exp_fun, exp_bc_complex, x, y, fun_jac=fun_jac,
549
+ bc_jac=bc_jac)
550
+
551
+ assert_equal(sol.status, 0)
552
+ assert_(sol.success)
553
+
554
+ sol_test = sol.sol(x_test)
555
+
556
+ assert_allclose(sol_test[0].real, exp_sol(x_test), atol=1e-5)
557
+ assert_allclose(sol_test[0].imag, exp_sol(x_test), atol=1e-5)
558
+
559
+ f_test = exp_fun(x_test, sol_test)
560
+ r = sol.sol(x_test, 1) - f_test
561
+ rel_res = r / (1 + np.abs(f_test))
562
+ norm_res = np.sum(np.real(rel_res * np.conj(rel_res)),
563
+ axis=0) ** 0.5
564
+ assert_(np.all(norm_res < 1e-3))
565
+
566
+ assert_(np.all(sol.rms_residuals < 1e-3))
567
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
568
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
569
+
570
+
571
+ def test_failures():
572
+ x = np.linspace(0, 1, 2)
573
+ y = np.zeros((2, x.size))
574
+ res = solve_bvp(exp_fun, exp_bc, x, y, tol=1e-5, max_nodes=5)
575
+ assert_equal(res.status, 1)
576
+ assert_(not res.success)
577
+
578
+ x = np.linspace(0, 1, 5)
579
+ y = np.zeros((2, x.size))
580
+ res = solve_bvp(undefined_fun, undefined_bc, x, y)
581
+ assert_equal(res.status, 2)
582
+ assert_(not res.success)
583
+
584
+
585
+ def test_big_problem():
586
+ n = 30
587
+ x = np.linspace(0, 1, 5)
588
+ y = np.zeros((2 * n, x.size))
589
+ sol = solve_bvp(big_fun, big_bc, x, y)
590
+
591
+ assert_equal(sol.status, 0)
592
+ assert_(sol.success)
593
+
594
+ sol_test = sol.sol(x)
595
+
596
+ assert_allclose(sol_test[0], big_sol(x, n))
597
+
598
+ f_test = big_fun(x, sol_test)
599
+ r = sol.sol(x, 1) - f_test
600
+ rel_res = r / (1 + np.abs(f_test))
601
+ norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), axis=0) ** 0.5
602
+ assert_(np.all(norm_res < 1e-3))
603
+
604
+ assert_(np.all(sol.rms_residuals < 1e-3))
605
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
606
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
607
+
608
+
609
+ def test_big_problem_with_parameters():
610
+ n = 30
611
+ x = np.linspace(0, np.pi, 5)
612
+ x_test = np.linspace(0, np.pi, 100)
613
+ y = np.ones((2 * n, x.size))
614
+
615
+ for fun_jac in [None, big_fun_with_parameters_jac]:
616
+ for bc_jac in [None, big_bc_with_parameters_jac]:
617
+ sol = solve_bvp(big_fun_with_parameters, big_bc_with_parameters, x,
618
+ y, p=[0.5, 0.5], fun_jac=fun_jac, bc_jac=bc_jac)
619
+
620
+ assert_equal(sol.status, 0)
621
+ assert_(sol.success)
622
+
623
+ assert_allclose(sol.p, [1, 1], rtol=1e-4)
624
+
625
+ sol_test = sol.sol(x_test)
626
+
627
+ for isol in range(0, n, 4):
628
+ assert_allclose(sol_test[isol],
629
+ big_sol_with_parameters(x_test, [1, 1])[0],
630
+ rtol=1e-4, atol=1e-4)
631
+ assert_allclose(sol_test[isol + 2],
632
+ big_sol_with_parameters(x_test, [1, 1])[1],
633
+ rtol=1e-4, atol=1e-4)
634
+
635
+ f_test = big_fun_with_parameters(x_test, sol_test, [1, 1])
636
+ r = sol.sol(x_test, 1) - f_test
637
+ rel_res = r / (1 + np.abs(f_test))
638
+ norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
639
+ assert_(np.all(norm_res < 1e-3))
640
+
641
+ assert_(np.all(sol.rms_residuals < 1e-3))
642
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
643
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
644
+
645
+
646
+ def test_shock_layer():
647
+ x = np.linspace(-1, 1, 5)
648
+ x_test = np.linspace(-1, 1, 100)
649
+ y = np.zeros((2, x.size))
650
+ sol = solve_bvp(shock_fun, shock_bc, x, y)
651
+
652
+ assert_equal(sol.status, 0)
653
+ assert_(sol.success)
654
+
655
+ assert_(sol.x.size < 110)
656
+
657
+ sol_test = sol.sol(x_test)
658
+ assert_allclose(sol_test[0], shock_sol(x_test), rtol=1e-5, atol=1e-5)
659
+
660
+ f_test = shock_fun(x_test, sol_test)
661
+ r = sol.sol(x_test, 1) - f_test
662
+ rel_res = r / (1 + np.abs(f_test))
663
+ norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
664
+
665
+ assert_(np.all(norm_res < 1e-3))
666
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
667
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
668
+
669
+
670
+ def test_nonlin_bc():
671
+ x = np.linspace(0, 0.1, 5)
672
+ x_test = x
673
+ y = np.zeros([2, x.size])
674
+ sol = solve_bvp(nonlin_bc_fun, nonlin_bc_bc, x, y)
675
+
676
+ assert_equal(sol.status, 0)
677
+ assert_(sol.success)
678
+
679
+ assert_(sol.x.size < 8)
680
+
681
+ sol_test = sol.sol(x_test)
682
+ assert_allclose(sol_test[0], nonlin_bc_sol(x_test), rtol=1e-5, atol=1e-5)
683
+
684
+ f_test = nonlin_bc_fun(x_test, sol_test)
685
+ r = sol.sol(x_test, 1) - f_test
686
+ rel_res = r / (1 + np.abs(f_test))
687
+ norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
688
+
689
+ assert_(np.all(norm_res < 1e-3))
690
+ assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
691
+ assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
692
+
693
+
694
+ @pytest.mark.thread_unsafe
695
+ def test_verbose():
696
+ # Smoke test that checks the printing does something and does not crash
697
+ x = np.linspace(0, 1, 5)
698
+ y = np.zeros((2, x.shape[0]))
699
+ for verbose in [0, 1, 2]:
700
+ old_stdout = sys.stdout
701
+ sys.stdout = StringIO()
702
+ try:
703
+ sol = solve_bvp(exp_fun, exp_bc, x, y, verbose=verbose)
704
+ text = sys.stdout.getvalue()
705
+ finally:
706
+ sys.stdout = old_stdout
707
+
708
+ assert_(sol.success)
709
+ if verbose == 0:
710
+ assert_(not text, text)
711
+ if verbose >= 1:
712
+ assert_("Solved in" in text, text)
713
+ if verbose >= 2:
714
+ assert_("Max residual" in text, text)
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py ADDED
@@ -0,0 +1,1389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import scipy
3
+ import itertools
4
+
5
+ import pytest
6
+
7
+ from scipy._lib._array_api import (
8
+ array_namespace,
9
+ xp_assert_close,
10
+ xp_size,
11
+ np_compat,
12
+ is_array_api_strict,
13
+ )
14
+ from scipy.conftest import array_api_compatible
15
+
16
+ from scipy.integrate import cubature
17
+
18
+ from scipy.integrate._rules import (
19
+ Rule, FixedRule,
20
+ NestedFixedRule,
21
+ GaussLegendreQuadrature, GaussKronrodQuadrature,
22
+ GenzMalikCubature,
23
+ )
24
+
25
+ from scipy.integrate._cubature import _InfiniteLimitsTransform
26
+
27
+ pytestmark = [pytest.mark.usefixtures("skip_xp_backends"),]
28
+ skip_xp_backends = pytest.mark.skip_xp_backends
29
+
30
+ # The integrands ``genz_malik_1980_*`` come from the paper:
31
+ # A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
32
+ # numerical integration over an N-dimensional rectangular region, Journal of
33
+ # Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
34
+ # ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
35
+
36
+
37
+ def basic_1d_integrand(x, n, xp):
38
+ x_reshaped = xp.reshape(x, (-1, 1, 1))
39
+ n_reshaped = xp.reshape(n, (1, -1, 1))
40
+
41
+ return x_reshaped**n_reshaped
42
+
43
+
44
+ def basic_1d_integrand_exact(n, xp):
45
+ # Exact only for integration over interval [0, 2].
46
+ return xp.reshape(2**(n+1)/(n+1), (-1, 1))
47
+
48
+
49
+ def basic_nd_integrand(x, n, xp):
50
+ return xp.reshape(xp.sum(x, axis=-1), (-1, 1))**xp.reshape(n, (1, -1))
51
+
52
+
53
+ def basic_nd_integrand_exact(n, xp):
54
+ # Exact only for integration over interval [0, 2].
55
+ return (-2**(3+n) + 4**(2+n))/((1+n)*(2+n))
56
+
57
+
58
+ def genz_malik_1980_f_1(x, r, alphas, xp):
59
+ r"""
60
+ .. math:: f_1(\mathbf x) = \cos\left(2\pi r + \sum^n_{i = 1}\alpha_i x_i\right)
61
+
62
+ .. code-block:: mathematica
63
+
64
+ genzMalik1980f1[x_List, r_, alphas_List] := Cos[2*Pi*r + Total[x*alphas]]
65
+ """
66
+
67
+ npoints, ndim = x.shape[0], x.shape[-1]
68
+
69
+ alphas_reshaped = alphas[None, ...]
70
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
71
+
72
+ return xp.cos(2*math.pi*r + xp.sum(alphas_reshaped * x_reshaped, axis=-1))
73
+
74
+
75
+ def genz_malik_1980_f_1_exact(a, b, r, alphas, xp):
76
+ ndim = xp_size(a)
77
+ a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
78
+ b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
79
+
80
+ return (
81
+ (-2)**ndim
82
+ * 1/xp.prod(alphas, axis=-1)
83
+ * xp.cos(2*math.pi*r + xp.sum(alphas * (a+b) * 0.5, axis=-1))
84
+ * xp.prod(xp.sin(alphas * (a-b)/2), axis=-1)
85
+ )
86
+
87
+
88
+ def genz_malik_1980_f_1_random_args(rng, shape, xp):
89
+ r = xp.asarray(rng.random(shape[:-1]))
90
+ alphas = xp.asarray(rng.random(shape))
91
+
92
+ difficulty = 9
93
+ normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
94
+ alphas = difficulty * alphas / normalisation_factors
95
+
96
+ return (r, alphas)
97
+
98
+
99
+ def genz_malik_1980_f_2(x, alphas, betas, xp):
100
+ r"""
101
+ .. math:: f_2(\mathbf x) = \prod^n_{i = 1} (\alpha_i^2 + (x_i - \beta_i)^2)^{-1}
102
+
103
+ .. code-block:: mathematica
104
+
105
+ genzMalik1980f2[x_List, alphas_List, betas_List] :=
106
+ 1/Times @@ ((alphas^2 + (x - betas)^2))
107
+ """
108
+ npoints, ndim = x.shape[0], x.shape[-1]
109
+
110
+ alphas_reshaped = alphas[None, ...]
111
+ betas_reshaped = betas[None, ...]
112
+
113
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
114
+
115
+ return 1/xp.prod(alphas_reshaped**2 + (x_reshaped-betas_reshaped)**2, axis=-1)
116
+
117
+
118
+ def genz_malik_1980_f_2_exact(a, b, alphas, betas, xp):
119
+ ndim = xp_size(a)
120
+ a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
121
+ b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
122
+
123
+ # `xp` is the unwrapped namespace, so `.atan` won't work for `xp = np` and np<2.
124
+ xp_test = array_namespace(a)
125
+
126
+ return (
127
+ (-1)**ndim * 1/xp.prod(alphas, axis=-1)
128
+ * xp.prod(
129
+ xp_test.atan((a - betas)/alphas) - xp_test.atan((b - betas)/alphas),
130
+ axis=-1,
131
+ )
132
+ )
133
+
134
+
135
+ def genz_malik_1980_f_2_random_args(rng, shape, xp):
136
+ ndim = shape[-1]
137
+ alphas = xp.asarray(rng.random(shape))
138
+ betas = xp.asarray(rng.random(shape))
139
+
140
+ difficulty = 25.0
141
+ products = xp.prod(alphas**xp.asarray(-2.0), axis=-1)
142
+ normalisation_factors = (products**xp.asarray(1 / (2*ndim)))[..., None]
143
+ alphas = alphas * normalisation_factors * math.pow(difficulty, 1 / (2*ndim))
144
+
145
+ # Adjust alphas from distribution used in Genz and Malik 1980 since denominator
146
+ # is very small for high dimensions.
147
+ alphas *= 10
148
+
149
+ return alphas, betas
150
+
151
+
152
+ def genz_malik_1980_f_3(x, alphas, xp):
153
+ r"""
154
+ .. math:: f_3(\mathbf x) = \exp\left(\sum^n_{i = 1} \alpha_i x_i\right)
155
+
156
+ .. code-block:: mathematica
157
+
158
+ genzMalik1980f3[x_List, alphas_List] := Exp[Dot[x, alphas]]
159
+ """
160
+
161
+ npoints, ndim = x.shape[0], x.shape[-1]
162
+
163
+ alphas_reshaped = alphas[None, ...]
164
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
165
+
166
+ return xp.exp(xp.sum(alphas_reshaped * x_reshaped, axis=-1))
167
+
168
+
169
+ def genz_malik_1980_f_3_exact(a, b, alphas, xp):
170
+ ndim = xp_size(a)
171
+ a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
172
+ b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
173
+
174
+ return (
175
+ (-1)**ndim * 1/xp.prod(alphas, axis=-1)
176
+ * xp.prod(xp.exp(alphas * a) - xp.exp(alphas * b), axis=-1)
177
+ )
178
+
179
+
180
+ def genz_malik_1980_f_3_random_args(rng, shape, xp):
181
+ alphas = xp.asarray(rng.random(shape))
182
+ normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
183
+ difficulty = 12.0
184
+ alphas = difficulty * alphas / normalisation_factors
185
+
186
+ return (alphas,)
187
+
188
+
189
+ def genz_malik_1980_f_4(x, alphas, xp):
190
+ r"""
191
+ .. math:: f_4(\mathbf x) = \left(1 + \sum^n_{i = 1} \alpha_i x_i\right)^{-n-1}
192
+
193
+ .. code-block:: mathematica
194
+ genzMalik1980f4[x_List, alphas_List] :=
195
+ (1 + Dot[x, alphas])^(-Length[alphas] - 1)
196
+ """
197
+
198
+ npoints, ndim = x.shape[0], x.shape[-1]
199
+
200
+ alphas_reshaped = alphas[None, ...]
201
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
202
+
203
+ return (1 + xp.sum(alphas_reshaped * x_reshaped, axis=-1))**(-ndim-1)
204
+
205
+
206
+ def genz_malik_1980_f_4_exact(a, b, alphas, xp):
207
+ ndim = xp_size(a)
208
+
209
+ def F(x):
210
+ x_reshaped = xp.reshape(x, (*([1]*(len(alphas.shape) - 1)), ndim))
211
+
212
+ return (
213
+ (-1)**ndim/xp.prod(alphas, axis=-1)
214
+ / math.factorial(ndim)
215
+ / (1 + xp.sum(alphas * x_reshaped, axis=-1))
216
+ )
217
+
218
+ return _eval_indefinite_integral(F, a, b, xp)
219
+
220
+
221
+ def _eval_indefinite_integral(F, a, b, xp):
222
+ """
223
+ Calculates a definite integral from points `a` to `b` by summing up over the corners
224
+ of the corresponding hyperrectangle.
225
+ """
226
+
227
+ ndim = xp_size(a)
228
+ points = xp.stack([a, b], axis=0)
229
+
230
+ out = 0
231
+ for ind in itertools.product(range(2), repeat=ndim):
232
+ selected_points = xp.asarray([points[i, j] for i, j in zip(ind, range(ndim))])
233
+ out += pow(-1, sum(ind) + ndim) * F(selected_points)
234
+
235
+ return out
236
+
237
+
238
+ def genz_malik_1980_f_4_random_args(rng, shape, xp):
239
+ ndim = shape[-1]
240
+
241
+ alphas = xp.asarray(rng.random(shape))
242
+ normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
243
+ difficulty = 14.0
244
+ alphas = (difficulty / ndim) * alphas / normalisation_factors
245
+
246
+ return (alphas,)
247
+
248
+
249
+ def genz_malik_1980_f_5(x, alphas, betas, xp):
250
+ r"""
251
+ .. math::
252
+
253
+ f_5(\mathbf x) = \exp\left(-\sum^n_{i = 1} \alpha^2_i (x_i - \beta_i)^2\right)
254
+
255
+ .. code-block:: mathematica
256
+
257
+ genzMalik1980f5[x_List, alphas_List, betas_List] :=
258
+ Exp[-Total[alphas^2 * (x - betas)^2]]
259
+ """
260
+
261
+ npoints, ndim = x.shape[0], x.shape[-1]
262
+
263
+ alphas_reshaped = alphas[None, ...]
264
+ betas_reshaped = betas[None, ...]
265
+
266
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
267
+
268
+ return xp.exp(
269
+ -xp.sum(alphas_reshaped**2 * (x_reshaped - betas_reshaped)**2, axis=-1)
270
+ )
271
+
272
+
273
+ def genz_malik_1980_f_5_exact(a, b, alphas, betas, xp):
274
+ ndim = xp_size(a)
275
+ a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
276
+ b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
277
+
278
+ return (
279
+ (1/2)**ndim
280
+ * 1/xp.prod(alphas, axis=-1)
281
+ * (math.pi**(ndim/2))
282
+ * xp.prod(
283
+ scipy.special.erf(alphas * (betas - a))
284
+ + scipy.special.erf(alphas * (b - betas)),
285
+ axis=-1,
286
+ )
287
+ )
288
+
289
+
290
+ def genz_malik_1980_f_5_random_args(rng, shape, xp):
291
+ alphas = xp.asarray(rng.random(shape))
292
+ betas = xp.asarray(rng.random(shape))
293
+
294
+ difficulty = 21.0
295
+ normalisation_factors = xp.sqrt(xp.sum(alphas**xp.asarray(2.0), axis=-1))[..., None]
296
+ alphas = alphas / normalisation_factors * math.sqrt(difficulty)
297
+
298
+ return alphas, betas
299
+
300
+
301
+ def f_gaussian(x, alphas, xp):
302
+ r"""
303
+ .. math::
304
+
305
+ f(\mathbf x) = \exp\left(-\sum^n_{i = 1} (\alpha_i x_i)^2 \right)
306
+ """
307
+ npoints, ndim = x.shape[0], x.shape[-1]
308
+ alphas_reshaped = alphas[None, ...]
309
+ x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
310
+
311
+ return xp.exp(-xp.sum((alphas_reshaped * x_reshaped)**2, axis=-1))
312
+
313
+
314
+ def f_gaussian_exact(a, b, alphas, xp):
315
+ # Exact only when `a` and `b` are one of:
316
+ # (-oo, oo), or
317
+ # (0, oo), or
318
+ # (-oo, 0)
319
+ # `alphas` can be arbitrary.
320
+
321
+ ndim = xp_size(a)
322
+ double_infinite_count = 0
323
+ semi_infinite_count = 0
324
+
325
+ for i in range(ndim):
326
+ if xp.isinf(a[i]) and xp.isinf(b[i]): # doubly-infinite
327
+ double_infinite_count += 1
328
+ elif xp.isinf(a[i]) != xp.isinf(b[i]): # exclusive or, so semi-infinite
329
+ semi_infinite_count += 1
330
+
331
+ return (math.sqrt(math.pi) ** ndim) / (
332
+ 2**semi_infinite_count * xp.prod(alphas, axis=-1)
333
+ )
334
+
335
+
336
+ def f_gaussian_random_args(rng, shape, xp):
337
+ alphas = xp.asarray(rng.random(shape))
338
+
339
+ # If alphas are very close to 0 this makes the problem very difficult due to large
340
+ # values of ``f``.
341
+ alphas *= 100
342
+
343
+ return (alphas,)
344
+
345
+
346
+ def f_modified_gaussian(x_arr, n, xp):
347
+ r"""
348
+ .. math::
349
+
350
+ f(x, y, z, w) = x^n \sqrt{y} \exp(-y-z^2-w^2)
351
+ """
352
+ x, y, z, w = x_arr[:, 0], x_arr[:, 1], x_arr[:, 2], x_arr[:, 3]
353
+ res = (x ** n[:, None]) * xp.sqrt(y) * xp.exp(-y-z**2-w**2)
354
+
355
+ return res.T
356
+
357
+
358
+ def f_modified_gaussian_exact(a, b, n, xp):
359
+ # Exact only for the limits
360
+ # a = (0, 0, -oo, -oo)
361
+ # b = (1, oo, oo, oo)
362
+ # but defined here as a function to match the format of the other integrands.
363
+ return 1/(2 + 2*n) * math.pi ** (3/2)
364
+
365
+
366
+ def f_with_problematic_points(x_arr, points, xp):
367
+ """
368
+ This emulates a function with a list of singularities given by `points`.
369
+
370
+ If no `x_arr` are one of the `points`, then this function returns 1.
371
+ """
372
+
373
+ for point in points:
374
+ if xp.any(x_arr == point):
375
+ raise ValueError("called with a problematic point")
376
+
377
+ return xp.ones(x_arr.shape[0])
378
+
379
+
380
+ @array_api_compatible
381
+ class TestCubature:
382
+ """
383
+ Tests related to the interface of `cubature`.
384
+ """
385
+
386
+ @pytest.mark.parametrize("rule_str", [
387
+ "gauss-kronrod",
388
+ "genz-malik",
389
+ "gk21",
390
+ "gk15",
391
+ ])
392
+ def test_pass_str(self, rule_str, xp):
393
+ n = xp.arange(5, dtype=xp.float64)
394
+ a = xp.asarray([0, 0], dtype=xp.float64)
395
+ b = xp.asarray([2, 2], dtype=xp.float64)
396
+
397
+ res = cubature(basic_nd_integrand, a, b, rule=rule_str, args=(n, xp))
398
+
399
+ xp_assert_close(
400
+ res.estimate,
401
+ basic_nd_integrand_exact(n, xp),
402
+ rtol=1e-8,
403
+ atol=0,
404
+ )
405
+
406
+ @skip_xp_backends(np_only=True,
407
+ reason='array-likes only supported for NumPy backend')
408
+ def test_pass_array_like_not_array(self, xp):
409
+ n = np_compat.arange(5, dtype=np_compat.float64)
410
+ a = [0]
411
+ b = [2]
412
+
413
+ res = cubature(
414
+ basic_1d_integrand,
415
+ a,
416
+ b,
417
+ args=(n, xp)
418
+ )
419
+
420
+ xp_assert_close(
421
+ res.estimate,
422
+ basic_1d_integrand_exact(n, xp),
423
+ rtol=1e-8,
424
+ atol=0,
425
+ )
426
+
427
+ def test_stops_after_max_subdivisions(self, xp):
428
+ a = xp.asarray([0])
429
+ b = xp.asarray([1])
430
+ rule = BadErrorRule()
431
+
432
+ res = cubature(
433
+ basic_1d_integrand, # Any function would suffice
434
+ a,
435
+ b,
436
+ rule=rule,
437
+ max_subdivisions=10,
438
+ args=(xp.arange(5, dtype=xp.float64), xp),
439
+ )
440
+
441
+ assert res.subdivisions == 10
442
+ assert res.status == "not_converged"
443
+
444
+ def test_a_and_b_must_be_1d(self, xp):
445
+ a = xp.asarray([[0]], dtype=xp.float64)
446
+ b = xp.asarray([[1]], dtype=xp.float64)
447
+
448
+ with pytest.raises(Exception, match="`a` and `b` must be 1D arrays"):
449
+ cubature(basic_1d_integrand, a, b, args=(xp,))
450
+
451
+ def test_a_and_b_must_be_nonempty(self, xp):
452
+ a = xp.asarray([])
453
+ b = xp.asarray([])
454
+
455
+ with pytest.raises(Exception, match="`a` and `b` must be nonempty"):
456
+ cubature(basic_1d_integrand, a, b, args=(xp,))
457
+
458
+ def test_zero_width_limits(self, xp):
459
+ n = xp.arange(5, dtype=xp.float64)
460
+
461
+ a = xp.asarray([0], dtype=xp.float64)
462
+ b = xp.asarray([0], dtype=xp.float64)
463
+
464
+ res = cubature(
465
+ basic_1d_integrand,
466
+ a,
467
+ b,
468
+ args=(n, xp),
469
+ )
470
+
471
+ xp_assert_close(
472
+ res.estimate,
473
+ xp.asarray([[0], [0], [0], [0], [0]], dtype=xp.float64),
474
+ rtol=1e-8,
475
+ atol=0,
476
+ )
477
+
478
+ def test_limits_other_way_around(self, xp):
479
+ n = xp.arange(5, dtype=xp.float64)
480
+
481
+ a = xp.asarray([2], dtype=xp.float64)
482
+ b = xp.asarray([0], dtype=xp.float64)
483
+
484
+ res = cubature(
485
+ basic_1d_integrand,
486
+ a,
487
+ b,
488
+ args=(n, xp),
489
+ )
490
+
491
+ xp_assert_close(
492
+ res.estimate,
493
+ -basic_1d_integrand_exact(n, xp),
494
+ rtol=1e-8,
495
+ atol=0,
496
+ )
497
+
498
+ def test_result_dtype_promoted_correctly(self, xp):
499
+ result_dtype = cubature(
500
+ basic_1d_integrand,
501
+ xp.asarray([0], dtype=xp.float64),
502
+ xp.asarray([1], dtype=xp.float64),
503
+ points=[],
504
+ args=(xp.asarray([1], dtype=xp.float64), xp),
505
+ ).estimate.dtype
506
+
507
+ assert result_dtype == xp.float64
508
+
509
+ result_dtype = cubature(
510
+ basic_1d_integrand,
511
+ xp.asarray([0], dtype=xp.float32),
512
+ xp.asarray([1], dtype=xp.float32),
513
+ points=[],
514
+ args=(xp.asarray([1], dtype=xp.float32), xp),
515
+ ).estimate.dtype
516
+
517
+ assert result_dtype == xp.float32
518
+
519
+ result_dtype = cubature(
520
+ basic_1d_integrand,
521
+ xp.asarray([0], dtype=xp.float32),
522
+ xp.asarray([1], dtype=xp.float64),
523
+ points=[],
524
+ args=(xp.asarray([1], dtype=xp.float32), xp),
525
+ ).estimate.dtype
526
+
527
+ assert result_dtype == xp.float64
528
+
529
+
530
+ @pytest.mark.parametrize("rtol", [1e-4])
531
+ @pytest.mark.parametrize("atol", [1e-5])
532
+ @pytest.mark.parametrize("rule", [
533
+ "gk15",
534
+ "gk21",
535
+ "genz-malik",
536
+ ])
537
+ @array_api_compatible
538
+ class TestCubatureProblems:
539
+ """
540
+ Tests that `cubature` gives the correct answer.
541
+ """
542
+
543
+ @pytest.mark.parametrize("problem", [
544
+ # -- f1 --
545
+ (
546
+ # Function to integrate, like `f(x, *args)`
547
+ genz_malik_1980_f_1,
548
+
549
+ # Exact solution, like `exact(a, b, *args)`
550
+ genz_malik_1980_f_1_exact,
551
+
552
+ # Coordinates of `a`
553
+ [0],
554
+
555
+ # Coordinates of `b`
556
+ [10],
557
+
558
+ # Arguments to pass to `f` and `exact`
559
+ (
560
+ 1/4,
561
+ [5],
562
+ )
563
+ ),
564
+ (
565
+ genz_malik_1980_f_1,
566
+ genz_malik_1980_f_1_exact,
567
+ [0, 0],
568
+ [1, 1],
569
+ (
570
+ 1/4,
571
+ [2, 4],
572
+ ),
573
+ ),
574
+ (
575
+ genz_malik_1980_f_1,
576
+ genz_malik_1980_f_1_exact,
577
+ [0, 0],
578
+ [5, 5],
579
+ (
580
+ 1/2,
581
+ [2, 4],
582
+ )
583
+ ),
584
+ (
585
+ genz_malik_1980_f_1,
586
+ genz_malik_1980_f_1_exact,
587
+ [0, 0, 0],
588
+ [5, 5, 5],
589
+ (
590
+ 1/2,
591
+ [1, 1, 1],
592
+ )
593
+ ),
594
+
595
+ # -- f2 --
596
+ (
597
+ genz_malik_1980_f_2,
598
+ genz_malik_1980_f_2_exact,
599
+ [-1],
600
+ [1],
601
+ (
602
+ [5],
603
+ [4],
604
+ )
605
+ ),
606
+ (
607
+ genz_malik_1980_f_2,
608
+ genz_malik_1980_f_2_exact,
609
+
610
+ [0, 0],
611
+ [10, 50],
612
+ (
613
+ [-3, 3],
614
+ [-2, 2],
615
+ ),
616
+ ),
617
+ (
618
+ genz_malik_1980_f_2,
619
+ genz_malik_1980_f_2_exact,
620
+ [0, 0, 0],
621
+ [1, 1, 1],
622
+ (
623
+ [1, 1, 1],
624
+ [1, 1, 1],
625
+ )
626
+ ),
627
+ (
628
+ genz_malik_1980_f_2,
629
+ genz_malik_1980_f_2_exact,
630
+ [0, 0, 0],
631
+ [1, 1, 1],
632
+ (
633
+ [2, 3, 4],
634
+ [2, 3, 4],
635
+ )
636
+ ),
637
+ (
638
+ genz_malik_1980_f_2,
639
+ genz_malik_1980_f_2_exact,
640
+ [-1, -1, -1],
641
+ [1, 1, 1],
642
+ (
643
+ [1, 1, 1],
644
+ [2, 2, 2],
645
+ )
646
+ ),
647
+ (
648
+ genz_malik_1980_f_2,
649
+ genz_malik_1980_f_2_exact,
650
+ [-1, -1, -1, -1],
651
+ [1, 1, 1, 1],
652
+ (
653
+ [1, 1, 1, 1],
654
+ [1, 1, 1, 1],
655
+ )
656
+ ),
657
+
658
+ # -- f3 --
659
+ (
660
+ genz_malik_1980_f_3,
661
+ genz_malik_1980_f_3_exact,
662
+ [-1],
663
+ [1],
664
+ (
665
+ [1/2],
666
+ ),
667
+ ),
668
+ (
669
+ genz_malik_1980_f_3,
670
+ genz_malik_1980_f_3_exact,
671
+ [0, -1],
672
+ [1, 1],
673
+ (
674
+ [5, 5],
675
+ ),
676
+ ),
677
+ (
678
+ genz_malik_1980_f_3,
679
+ genz_malik_1980_f_3_exact,
680
+ [-1, -1, -1],
681
+ [1, 1, 1],
682
+ (
683
+ [1, 1, 1],
684
+ ),
685
+ ),
686
+
687
+ # -- f4 --
688
+ (
689
+ genz_malik_1980_f_4,
690
+ genz_malik_1980_f_4_exact,
691
+ [0],
692
+ [2],
693
+ (
694
+ [1],
695
+ ),
696
+ ),
697
+ (
698
+ genz_malik_1980_f_4,
699
+ genz_malik_1980_f_4_exact,
700
+ [0, 0],
701
+ [2, 1],
702
+ ([1, 1],),
703
+ ),
704
+ (
705
+ genz_malik_1980_f_4,
706
+ genz_malik_1980_f_4_exact,
707
+ [0, 0, 0],
708
+ [1, 1, 1],
709
+ ([1, 1, 1],),
710
+ ),
711
+
712
+ # -- f5 --
713
+ (
714
+ genz_malik_1980_f_5,
715
+ genz_malik_1980_f_5_exact,
716
+ [-1],
717
+ [1],
718
+ (
719
+ [-2],
720
+ [2],
721
+ ),
722
+ ),
723
+ (
724
+ genz_malik_1980_f_5,
725
+ genz_malik_1980_f_5_exact,
726
+ [-1, -1],
727
+ [1, 1],
728
+ (
729
+ [2, 3],
730
+ [4, 5],
731
+ ),
732
+ ),
733
+ (
734
+ genz_malik_1980_f_5,
735
+ genz_malik_1980_f_5_exact,
736
+ [-1, -1],
737
+ [1, 1],
738
+ (
739
+ [-1, 1],
740
+ [0, 0],
741
+ ),
742
+ ),
743
+ (
744
+ genz_malik_1980_f_5,
745
+ genz_malik_1980_f_5_exact,
746
+ [-1, -1, -1],
747
+ [1, 1, 1],
748
+ (
749
+ [1, 1, 1],
750
+ [1, 1, 1],
751
+ ),
752
+ ),
753
+ ])
754
+ def test_scalar_output(self, problem, rule, rtol, atol, xp):
755
+ f, exact, a, b, args = problem
756
+
757
+ a = xp.asarray(a, dtype=xp.float64)
758
+ b = xp.asarray(b, dtype=xp.float64)
759
+ args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
760
+
761
+ ndim = xp_size(a)
762
+
763
+ if rule == "genz-malik" and ndim < 2:
764
+ pytest.skip("Genz-Malik cubature does not support 1D integrals")
765
+
766
+ res = cubature(
767
+ f,
768
+ a,
769
+ b,
770
+ rule=rule,
771
+ rtol=rtol,
772
+ atol=atol,
773
+ args=(*args, xp),
774
+ )
775
+
776
+ assert res.status == "converged"
777
+
778
+ est = res.estimate
779
+ exact_sol = exact(a, b, *args, xp)
780
+
781
+ xp_assert_close(
782
+ est,
783
+ exact_sol,
784
+ rtol=rtol,
785
+ atol=atol,
786
+ err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
787
+ )
788
+
789
+ @pytest.mark.parametrize("problem", [
790
+ (
791
+ # Function to integrate, like `f(x, *args)`
792
+ genz_malik_1980_f_1,
793
+
794
+ # Exact solution, like `exact(a, b, *args)`
795
+ genz_malik_1980_f_1_exact,
796
+
797
+ # Function that generates random args of a certain shape.
798
+ genz_malik_1980_f_1_random_args,
799
+ ),
800
+ (
801
+ genz_malik_1980_f_2,
802
+ genz_malik_1980_f_2_exact,
803
+ genz_malik_1980_f_2_random_args,
804
+ ),
805
+ (
806
+ genz_malik_1980_f_3,
807
+ genz_malik_1980_f_3_exact,
808
+ genz_malik_1980_f_3_random_args
809
+ ),
810
+ (
811
+ genz_malik_1980_f_4,
812
+ genz_malik_1980_f_4_exact,
813
+ genz_malik_1980_f_4_random_args
814
+ ),
815
+ (
816
+ genz_malik_1980_f_5,
817
+ genz_malik_1980_f_5_exact,
818
+ genz_malik_1980_f_5_random_args,
819
+ ),
820
+ ])
821
+ @pytest.mark.parametrize("shape", [
822
+ (2,),
823
+ (3,),
824
+ (4,),
825
+ (1, 2),
826
+ (1, 3),
827
+ (1, 4),
828
+ (3, 2),
829
+ (3, 4, 2),
830
+ (2, 1, 3),
831
+ ])
832
+ def test_array_output(self, problem, rule, shape, rtol, atol, xp):
833
+ rng = np_compat.random.default_rng(1)
834
+ ndim = shape[-1]
835
+
836
+ if rule == "genz-malik" and ndim < 2:
837
+ pytest.skip("Genz-Malik cubature does not support 1D integrals")
838
+
839
+ if rule == "genz-malik" and ndim >= 5:
840
+ pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
841
+
842
+ f, exact, random_args = problem
843
+ args = random_args(rng, shape, xp)
844
+
845
+ a = xp.asarray([0] * ndim, dtype=xp.float64)
846
+ b = xp.asarray([1] * ndim, dtype=xp.float64)
847
+
848
+ res = cubature(
849
+ f,
850
+ a,
851
+ b,
852
+ rule=rule,
853
+ rtol=rtol,
854
+ atol=atol,
855
+ args=(*args, xp),
856
+ )
857
+
858
+ est = res.estimate
859
+ exact_sol = exact(a, b, *args, xp)
860
+
861
+ xp_assert_close(
862
+ est,
863
+ exact_sol,
864
+ rtol=rtol,
865
+ atol=atol,
866
+ err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
867
+ )
868
+
869
+ err_msg = (f"estimate_error={res.error}, "
870
+ f"subdivisions= {res.subdivisions}, "
871
+ f"true_error={xp.abs(res.estimate - exact_sol)}")
872
+ assert res.status == "converged", err_msg
873
+
874
+ assert res.estimate.shape == shape[:-1]
875
+
876
+ @pytest.mark.parametrize("problem", [
877
+ (
878
+ # Function to integrate
879
+ lambda x, xp: x,
880
+
881
+ # Exact value
882
+ [50.0],
883
+
884
+ # Coordinates of `a`
885
+ [0],
886
+
887
+ # Coordinates of `b`
888
+ [10],
889
+
890
+ # Points by which to split up the initial region
891
+ None,
892
+ ),
893
+ (
894
+ lambda x, xp: xp.sin(x)/x,
895
+ [2.551496047169878], # si(1) + si(2),
896
+ [-1],
897
+ [2],
898
+ [
899
+ [0.0],
900
+ ],
901
+ ),
902
+ (
903
+ lambda x, xp: xp.ones((x.shape[0], 1)),
904
+ [1.0],
905
+ [0, 0, 0],
906
+ [1, 1, 1],
907
+ [
908
+ [0.5, 0.5, 0.5],
909
+ ],
910
+ ),
911
+ (
912
+ lambda x, xp: xp.ones((x.shape[0], 1)),
913
+ [1.0],
914
+ [0, 0, 0],
915
+ [1, 1, 1],
916
+ [
917
+ [0.25, 0.25, 0.25],
918
+ [0.5, 0.5, 0.5],
919
+ ],
920
+ ),
921
+ (
922
+ lambda x, xp: xp.ones((x.shape[0], 1)),
923
+ [1.0],
924
+ [0, 0, 0],
925
+ [1, 1, 1],
926
+ [
927
+ [0.1, 0.25, 0.5],
928
+ [0.25, 0.25, 0.25],
929
+ [0.5, 0.5, 0.5],
930
+ ],
931
+ )
932
+ ])
933
+ def test_break_points(self, problem, rule, rtol, atol, xp):
934
+ f, exact, a, b, points = problem
935
+
936
+ a = xp.asarray(a, dtype=xp.float64)
937
+ b = xp.asarray(b, dtype=xp.float64)
938
+ exact = xp.asarray(exact, dtype=xp.float64)
939
+
940
+ if points is not None:
941
+ points = [xp.asarray(point, dtype=xp.float64) for point in points]
942
+
943
+ ndim = xp_size(a)
944
+
945
+ if rule == "genz-malik" and ndim < 2:
946
+ pytest.skip("Genz-Malik cubature does not support 1D integrals")
947
+
948
+ if rule == "genz-malik" and ndim >= 5:
949
+ pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
950
+
951
+ res = cubature(
952
+ f,
953
+ a,
954
+ b,
955
+ rule=rule,
956
+ rtol=rtol,
957
+ atol=atol,
958
+ points=points,
959
+ args=(xp,),
960
+ )
961
+
962
+ xp_assert_close(
963
+ res.estimate,
964
+ exact,
965
+ rtol=rtol,
966
+ atol=atol,
967
+ err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
968
+ check_dtype=False,
969
+ )
970
+
971
+ err_msg = (f"estimate_error={res.error}, "
972
+ f"subdivisions= {res.subdivisions}, "
973
+ f"true_error={xp.abs(res.estimate - exact)}")
974
+ assert res.status == "converged", err_msg
975
+
976
+ @skip_xp_backends(
977
+ "jax.numpy",
978
+ reasons=["transforms make use of indexing assignment"],
979
+ )
980
+ @pytest.mark.parametrize("problem", [
981
+ (
982
+ # Function to integrate
983
+ f_gaussian,
984
+
985
+ # Exact solution
986
+ f_gaussian_exact,
987
+
988
+ # Arguments passed to f
989
+ f_gaussian_random_args,
990
+ (1, 1),
991
+
992
+ # Limits, have to match the shape of the arguments
993
+ [-math.inf], # a
994
+ [math.inf], # b
995
+ ),
996
+ (
997
+ f_gaussian,
998
+ f_gaussian_exact,
999
+ f_gaussian_random_args,
1000
+ (2, 2),
1001
+ [-math.inf, -math.inf],
1002
+ [math.inf, math.inf],
1003
+ ),
1004
+ (
1005
+ f_gaussian,
1006
+ f_gaussian_exact,
1007
+ f_gaussian_random_args,
1008
+ (1, 1),
1009
+ [0],
1010
+ [math.inf],
1011
+ ),
1012
+ (
1013
+ f_gaussian,
1014
+ f_gaussian_exact,
1015
+ f_gaussian_random_args,
1016
+ (1, 1),
1017
+ [-math.inf],
1018
+ [0],
1019
+ ),
1020
+ (
1021
+ f_gaussian,
1022
+ f_gaussian_exact,
1023
+ f_gaussian_random_args,
1024
+ (2, 2),
1025
+ [0, 0],
1026
+ [math.inf, math.inf],
1027
+ ),
1028
+ (
1029
+ f_gaussian,
1030
+ f_gaussian_exact,
1031
+ f_gaussian_random_args,
1032
+ (2, 2),
1033
+ [0, -math.inf],
1034
+ [math.inf, math.inf],
1035
+ ),
1036
+ (
1037
+ f_gaussian,
1038
+ f_gaussian_exact,
1039
+ f_gaussian_random_args,
1040
+ (1, 4),
1041
+ [0, 0, -math.inf, -math.inf],
1042
+ [math.inf, math.inf, math.inf, math.inf],
1043
+ ),
1044
+ (
1045
+ f_gaussian,
1046
+ f_gaussian_exact,
1047
+ f_gaussian_random_args,
1048
+ (1, 4),
1049
+ [-math.inf, -math.inf, -math.inf, -math.inf],
1050
+ [0, 0, math.inf, math.inf],
1051
+ ),
1052
+ (
1053
+ lambda x, xp: 1/xp.prod(x, axis=-1)**2,
1054
+
1055
+ # Exact only for the below limits, not for general `a` and `b`.
1056
+ lambda a, b, xp: xp.asarray(1/6, dtype=xp.float64),
1057
+
1058
+ # Arguments
1059
+ lambda rng, shape, xp: tuple(),
1060
+ tuple(),
1061
+
1062
+ [1, -math.inf, 3],
1063
+ [math.inf, -2, math.inf],
1064
+ ),
1065
+
1066
+ # This particular problem can be slow
1067
+ pytest.param(
1068
+ (
1069
+ # f(x, y, z, w) = x^n * sqrt(y) * exp(-y-z**2-w**2) for n in [0,1,2,3]
1070
+ f_modified_gaussian,
1071
+
1072
+ # This exact solution is for the below limits, not in general
1073
+ f_modified_gaussian_exact,
1074
+
1075
+ # Constant arguments
1076
+ lambda rng, shape, xp: (xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64),),
1077
+ tuple(),
1078
+
1079
+ [0, 0, -math.inf, -math.inf],
1080
+ [1, math.inf, math.inf, math.inf]
1081
+ ),
1082
+
1083
+ marks=pytest.mark.xslow,
1084
+ ),
1085
+ ])
1086
+ def test_infinite_limits(self, problem, rule, rtol, atol, xp):
1087
+ rng = np_compat.random.default_rng(1)
1088
+ f, exact, random_args_func, random_args_shape, a, b = problem
1089
+
1090
+ a = xp.asarray(a, dtype=xp.float64)
1091
+ b = xp.asarray(b, dtype=xp.float64)
1092
+ args = random_args_func(rng, random_args_shape, xp)
1093
+
1094
+ ndim = xp_size(a)
1095
+
1096
+ if rule == "genz-malik" and ndim < 2:
1097
+ pytest.skip("Genz-Malik cubature does not support 1D integrals")
1098
+
1099
+ if rule == "genz-malik" and ndim >= 4:
1100
+ pytest.mark.slow("Genz-Malik is slow in >= 5 dim")
1101
+
1102
+ if rule == "genz-malik" and ndim >= 4 and is_array_api_strict(xp):
1103
+ pytest.mark.xslow("Genz-Malik very slow for array_api_strict in >= 4 dim")
1104
+
1105
+ res = cubature(
1106
+ f,
1107
+ a,
1108
+ b,
1109
+ rule=rule,
1110
+ rtol=rtol,
1111
+ atol=atol,
1112
+ args=(*args, xp),
1113
+ )
1114
+
1115
+ assert res.status == "converged"
1116
+
1117
+ xp_assert_close(
1118
+ res.estimate,
1119
+ exact(a, b, *args, xp),
1120
+ rtol=rtol,
1121
+ atol=atol,
1122
+ err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
1123
+ check_0d=False,
1124
+ )
1125
+
1126
+ @skip_xp_backends(
1127
+ "jax.numpy",
1128
+ reasons=["transforms make use of indexing assignment"],
1129
+ )
1130
+ @pytest.mark.parametrize("problem", [
1131
+ (
1132
+ # Function to integrate
1133
+ lambda x, xp: (xp.sin(x) / x)**8,
1134
+
1135
+ # Exact value
1136
+ [151/315 * math.pi],
1137
+
1138
+ # Limits
1139
+ [-math.inf],
1140
+ [math.inf],
1141
+
1142
+ # Breakpoints
1143
+ [[0]],
1144
+
1145
+ ),
1146
+ (
1147
+ # Function to integrate
1148
+ lambda x, xp: (xp.sin(x[:, 0]) / x[:, 0])**8,
1149
+
1150
+ # Exact value
1151
+ 151/315 * math.pi,
1152
+
1153
+ # Limits
1154
+ [-math.inf, 0],
1155
+ [math.inf, 1],
1156
+
1157
+ # Breakpoints
1158
+ [[0, 0.5]],
1159
+
1160
+ )
1161
+ ])
1162
+ def test_infinite_limits_and_break_points(self, problem, rule, rtol, atol, xp):
1163
+ f, exact, a, b, points = problem
1164
+
1165
+ a = xp.asarray(a, dtype=xp.float64)
1166
+ b = xp.asarray(b, dtype=xp.float64)
1167
+ exact = xp.asarray(exact, dtype=xp.float64)
1168
+
1169
+ ndim = xp_size(a)
1170
+
1171
+ if rule == "genz-malik" and ndim < 2:
1172
+ pytest.skip("Genz-Malik cubature does not support 1D integrals")
1173
+
1174
+ if points is not None:
1175
+ points = [xp.asarray(point, dtype=xp.float64) for point in points]
1176
+
1177
+ res = cubature(
1178
+ f,
1179
+ a,
1180
+ b,
1181
+ rule=rule,
1182
+ rtol=rtol,
1183
+ atol=atol,
1184
+ points=points,
1185
+ args=(xp,),
1186
+ )
1187
+
1188
+ assert res.status == "converged"
1189
+
1190
+ xp_assert_close(
1191
+ res.estimate,
1192
+ exact,
1193
+ rtol=rtol,
1194
+ atol=atol,
1195
+ err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
1196
+ check_0d=False,
1197
+ )
1198
+
1199
+
1200
+ @array_api_compatible
1201
+ class TestRules:
1202
+ """
1203
+ Tests related to the general Rule interface (currently private).
1204
+ """
1205
+
1206
+ @pytest.mark.parametrize("problem", [
1207
+ (
1208
+ # 2D problem, 1D rule
1209
+ [0, 0],
1210
+ [1, 1],
1211
+ GaussKronrodQuadrature,
1212
+ (21,),
1213
+ ),
1214
+ (
1215
+ # 1D problem, 2D rule
1216
+ [0],
1217
+ [1],
1218
+ GenzMalikCubature,
1219
+ (2,),
1220
+ )
1221
+ ])
1222
+ def test_incompatible_dimension_raises_error(self, problem, xp):
1223
+ a, b, quadrature, quadrature_args = problem
1224
+ rule = quadrature(*quadrature_args, xp=xp)
1225
+
1226
+ a = xp.asarray(a, dtype=xp.float64)
1227
+ b = xp.asarray(b, dtype=xp.float64)
1228
+
1229
+ with pytest.raises(Exception, match="incompatible dimension"):
1230
+ rule.estimate(basic_1d_integrand, a, b, args=(xp,))
1231
+
1232
+ def test_estimate_with_base_classes_raise_error(self, xp):
1233
+ a = xp.asarray([0])
1234
+ b = xp.asarray([1])
1235
+
1236
+ for base_class in [Rule(), FixedRule()]:
1237
+ with pytest.raises(Exception):
1238
+ base_class.estimate(basic_1d_integrand, a, b, args=(xp,))
1239
+
1240
+
1241
+ @array_api_compatible
1242
+ class TestRulesQuadrature:
1243
+ """
1244
+ Tests underlying quadrature rules (ndim == 1).
1245
+ """
1246
+
1247
+ @pytest.mark.parametrize(("rule", "rule_args"), [
1248
+ (GaussLegendreQuadrature, (3,)),
1249
+ (GaussLegendreQuadrature, (5,)),
1250
+ (GaussLegendreQuadrature, (10,)),
1251
+ (GaussKronrodQuadrature, (15,)),
1252
+ (GaussKronrodQuadrature, (21,)),
1253
+ ])
1254
+ def test_base_1d_quadratures_simple(self, rule, rule_args, xp):
1255
+ quadrature = rule(*rule_args, xp=xp)
1256
+
1257
+ n = xp.arange(5, dtype=xp.float64)
1258
+
1259
+ def f(x):
1260
+ x_reshaped = xp.reshape(x, (-1, 1, 1))
1261
+ n_reshaped = xp.reshape(n, (1, -1, 1))
1262
+
1263
+ return x_reshaped**n_reshaped
1264
+
1265
+ a = xp.asarray([0], dtype=xp.float64)
1266
+ b = xp.asarray([2], dtype=xp.float64)
1267
+
1268
+ exact = xp.reshape(2**(n+1)/(n+1), (-1, 1))
1269
+ estimate = quadrature.estimate(f, a, b)
1270
+
1271
+ xp_assert_close(
1272
+ estimate,
1273
+ exact,
1274
+ rtol=1e-8,
1275
+ atol=0,
1276
+ )
1277
+
1278
+ @pytest.mark.parametrize(("rule_pair", "rule_pair_args"), [
1279
+ ((GaussLegendreQuadrature, GaussLegendreQuadrature), (10, 5)),
1280
+ ])
1281
+ def test_base_1d_quadratures_error_from_difference(self, rule_pair, rule_pair_args,
1282
+ xp):
1283
+ n = xp.arange(5, dtype=xp.float64)
1284
+ a = xp.asarray([0], dtype=xp.float64)
1285
+ b = xp.asarray([2], dtype=xp.float64)
1286
+
1287
+ higher = rule_pair[0](rule_pair_args[0], xp=xp)
1288
+ lower = rule_pair[1](rule_pair_args[1], xp=xp)
1289
+
1290
+ rule = NestedFixedRule(higher, lower)
1291
+ res = cubature(
1292
+ basic_1d_integrand,
1293
+ a, b,
1294
+ rule=rule,
1295
+ rtol=1e-8,
1296
+ args=(n, xp),
1297
+ )
1298
+
1299
+ xp_assert_close(
1300
+ res.estimate,
1301
+ basic_1d_integrand_exact(n, xp),
1302
+ rtol=1e-8,
1303
+ atol=0,
1304
+ )
1305
+
1306
+ @pytest.mark.parametrize("quadrature", [
1307
+ GaussLegendreQuadrature
1308
+ ])
1309
+ def test_one_point_fixed_quad_impossible(self, quadrature, xp):
1310
+ with pytest.raises(Exception):
1311
+ quadrature(1, xp=xp)
1312
+
1313
+
1314
+ @array_api_compatible
1315
+ class TestRulesCubature:
1316
+ """
1317
+ Tests underlying cubature rules (ndim >= 2).
1318
+ """
1319
+
1320
+ @pytest.mark.parametrize("ndim", range(2, 11))
1321
+ def test_genz_malik_func_evaluations(self, ndim, xp):
1322
+ """
1323
+ Tests that the number of function evaluations required for Genz-Malik cubature
1324
+ matches the number in Genz and Malik 1980.
1325
+ """
1326
+
1327
+ nodes, _ = GenzMalikCubature(ndim, xp=xp).nodes_and_weights
1328
+
1329
+ assert nodes.shape[0] == (2**ndim) + 2*ndim**2 + 2*ndim + 1
1330
+
1331
+ def test_genz_malik_1d_raises_error(self, xp):
1332
+ with pytest.raises(Exception, match="only defined for ndim >= 2"):
1333
+ GenzMalikCubature(1, xp=xp)
1334
+
1335
+
1336
+ @array_api_compatible
1337
+ @skip_xp_backends(
1338
+ "jax.numpy",
1339
+ reasons=["transforms make use of indexing assignment"],
1340
+ )
1341
+ class TestTransformations:
1342
+ @pytest.mark.parametrize(("a", "b", "points"), [
1343
+ (
1344
+ [0, 1, -math.inf],
1345
+ [1, math.inf, math.inf],
1346
+ [
1347
+ [1, 1, 1],
1348
+ [0.5, 10, 10],
1349
+ ]
1350
+ )
1351
+ ])
1352
+ def test_infinite_limits_maintains_points(self, a, b, points, xp):
1353
+ """
1354
+ Test that break points are correctly mapped under the _InfiniteLimitsTransform
1355
+ transformation.
1356
+ """
1357
+
1358
+ xp_compat = array_namespace(xp.empty(0))
1359
+ points = [xp.asarray(p, dtype=xp.float64) for p in points]
1360
+
1361
+ f_transformed = _InfiniteLimitsTransform(
1362
+ # Bind `points` and `xp` argument in f
1363
+ lambda x: f_with_problematic_points(x, points, xp_compat),
1364
+ xp.asarray(a, dtype=xp_compat.float64),
1365
+ xp.asarray(b, dtype=xp_compat.float64),
1366
+ xp=xp_compat,
1367
+ )
1368
+
1369
+ for point in points:
1370
+ transformed_point = f_transformed.inv(xp_compat.reshape(point, (1, -1)))
1371
+
1372
+ with pytest.raises(Exception, match="called with a problematic point"):
1373
+ f_transformed(transformed_point)
1374
+
1375
+
1376
+ class BadErrorRule(Rule):
1377
+ """
1378
+ A rule with fake high error so that cubature will keep on subdividing.
1379
+ """
1380
+
1381
+ def estimate(self, f, a, b, args=()):
1382
+ xp = array_namespace(a, b)
1383
+ underlying = GaussLegendreQuadrature(10, xp=xp)
1384
+
1385
+ return underlying.estimate(f, a, b, args)
1386
+
1387
+ def estimate_error(self, f, a, b, args=()):
1388
+ xp = array_namespace(a, b)
1389
+ return xp.asarray(1e6, dtype=xp.float64)
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_equal, assert_allclose
3
+ from scipy.integrate import odeint
4
+ import scipy.integrate._test_odeint_banded as banded5x5
5
+
6
+
7
+ def rhs(y, t):
8
+ dydt = np.zeros_like(y)
9
+ banded5x5.banded5x5(t, y, dydt)
10
+ return dydt
11
+
12
+
13
+ def jac(y, t):
14
+ n = len(y)
15
+ jac = np.zeros((n, n), order='F')
16
+ banded5x5.banded5x5_jac(t, y, 1, 1, jac)
17
+ return jac
18
+
19
+
20
+ def bjac(y, t):
21
+ n = len(y)
22
+ bjac = np.zeros((4, n), order='F')
23
+ banded5x5.banded5x5_bjac(t, y, 1, 1, bjac)
24
+ return bjac
25
+
26
+
27
+ JACTYPE_FULL = 1
28
+ JACTYPE_BANDED = 4
29
+
30
+
31
+ def check_odeint(jactype):
32
+ if jactype == JACTYPE_FULL:
33
+ ml = None
34
+ mu = None
35
+ jacobian = jac
36
+ elif jactype == JACTYPE_BANDED:
37
+ ml = 2
38
+ mu = 1
39
+ jacobian = bjac
40
+ else:
41
+ raise ValueError(f"invalid jactype: {jactype!r}")
42
+
43
+ y0 = np.arange(1.0, 6.0)
44
+ # These tolerances must match the tolerances used in banded5x5.f.
45
+ rtol = 1e-11
46
+ atol = 1e-13
47
+ dt = 0.125
48
+ nsteps = 64
49
+ t = dt * np.arange(nsteps+1)
50
+
51
+ sol, info = odeint(rhs, y0, t,
52
+ Dfun=jacobian, ml=ml, mu=mu,
53
+ atol=atol, rtol=rtol, full_output=True)
54
+ yfinal = sol[-1]
55
+ odeint_nst = info['nst'][-1]
56
+ odeint_nfe = info['nfe'][-1]
57
+ odeint_nje = info['nje'][-1]
58
+
59
+ y1 = y0.copy()
60
+ # Pure Fortran solution. y1 is modified in-place.
61
+ nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype)
62
+
63
+ # It is likely that yfinal and y1 are *exactly* the same, but
64
+ # we'll be cautious and use assert_allclose.
65
+ assert_allclose(yfinal, y1, rtol=1e-12)
66
+ assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje))
67
+
68
+
69
+ def test_odeint_full_jac():
70
+ check_odeint(JACTYPE_FULL)
71
+
72
+
73
+ def test_odeint_banded_jac():
74
+ check_odeint(JACTYPE_BANDED)
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import math
3
+ import numpy as np
4
+ from numpy import sqrt, cos, sin, arctan, exp, log, pi
5
+ from numpy.testing import (assert_,
6
+ assert_allclose, assert_array_less, assert_almost_equal)
7
+ import pytest
8
+
9
+ from scipy.integrate import quad, dblquad, tplquad, nquad
10
+ from scipy.special import erf, erfc
11
+ from scipy._lib._ccallback import LowLevelCallable
12
+
13
+ import ctypes
14
+ import ctypes.util
15
+ from scipy._lib._ccallback_c import sine_ctypes
16
+
17
+ import scipy.integrate._test_multivariate as clib_test
18
+
19
+
20
+ def assert_quad(value_and_err, tabled_value, error_tolerance=1.5e-8):
21
+ value, err = value_and_err
22
+ assert_allclose(value, tabled_value, atol=err, rtol=0)
23
+ if error_tolerance is not None:
24
+ assert_array_less(err, error_tolerance)
25
+
26
+
27
+ def get_clib_test_routine(name, restype, *argtypes):
28
+ ptr = getattr(clib_test, name)
29
+ return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes))
30
+
31
+
32
+ class TestCtypesQuad:
33
+ def setup_method(self):
34
+ if sys.platform == 'win32':
35
+ files = ['api-ms-win-crt-math-l1-1-0.dll']
36
+ elif sys.platform == 'darwin':
37
+ files = ['libm.dylib']
38
+ else:
39
+ files = ['libm.so', 'libm.so.6']
40
+
41
+ for file in files:
42
+ try:
43
+ self.lib = ctypes.CDLL(file)
44
+ break
45
+ except OSError:
46
+ pass
47
+ else:
48
+ # This test doesn't work on some Linux platforms (Fedora for
49
+ # example) that put an ld script in libm.so - see gh-5370
50
+ pytest.skip("Ctypes can't import libm.so")
51
+
52
+ restype = ctypes.c_double
53
+ argtypes = (ctypes.c_double,)
54
+ for name in ['sin', 'cos', 'tan']:
55
+ func = getattr(self.lib, name)
56
+ func.restype = restype
57
+ func.argtypes = argtypes
58
+
59
+ def test_typical(self):
60
+ assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0])
61
+ assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0])
62
+ assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0])
63
+
64
+ def test_ctypes_sine(self):
65
+ quad(LowLevelCallable(sine_ctypes), 0, 1)
66
+
67
+ def test_ctypes_variants(self):
68
+ sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double,
69
+ ctypes.c_double, ctypes.c_void_p)
70
+
71
+ sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double,
72
+ ctypes.c_int, ctypes.POINTER(ctypes.c_double),
73
+ ctypes.c_void_p)
74
+
75
+ sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double,
76
+ ctypes.c_double)
77
+
78
+ sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double,
79
+ ctypes.c_int, ctypes.POINTER(ctypes.c_double))
80
+
81
+ sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double,
82
+ ctypes.c_int, ctypes.c_double)
83
+
84
+ all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4]
85
+ legacy_sigs = [sin_2, sin_4]
86
+ legacy_only_sigs = [sin_4]
87
+
88
+ # LowLevelCallables work for new signatures
89
+ for j, func in enumerate(all_sigs):
90
+ callback = LowLevelCallable(func)
91
+ if func in legacy_only_sigs:
92
+ pytest.raises(ValueError, quad, callback, 0, pi)
93
+ else:
94
+ assert_allclose(quad(callback, 0, pi)[0], 2.0)
95
+
96
+ # Plain ctypes items work only for legacy signatures
97
+ for j, func in enumerate(legacy_sigs):
98
+ if func in legacy_sigs:
99
+ assert_allclose(quad(func, 0, pi)[0], 2.0)
100
+ else:
101
+ pytest.raises(ValueError, quad, func, 0, pi)
102
+
103
+
104
+ class TestMultivariateCtypesQuad:
105
+ def setup_method(self):
106
+ restype = ctypes.c_double
107
+ argtypes = (ctypes.c_int, ctypes.c_double)
108
+ for name in ['_multivariate_typical', '_multivariate_indefinite',
109
+ '_multivariate_sin']:
110
+ func = get_clib_test_routine(name, restype, *argtypes)
111
+ setattr(self, name, func)
112
+
113
+ def test_typical(self):
114
+ # 1) Typical function with two extra arguments:
115
+ assert_quad(quad(self._multivariate_typical, 0, pi, (2, 1.8)),
116
+ 0.30614353532540296487)
117
+
118
+ def test_indefinite(self):
119
+ # 2) Infinite integration limits --- Euler's constant
120
+ assert_quad(quad(self._multivariate_indefinite, 0, np.inf),
121
+ 0.577215664901532860606512)
122
+
123
+ def test_threadsafety(self):
124
+ # Ensure multivariate ctypes are threadsafe
125
+ def threadsafety(y):
126
+ return y + quad(self._multivariate_sin, 0, 1)[0]
127
+ assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602)
128
+
129
+
130
+ class TestQuad:
131
+ def test_typical(self):
132
+ # 1) Typical function with two extra arguments:
133
+ def myfunc(x, n, z): # Bessel function integrand
134
+ return cos(n*x-z*sin(x))/pi
135
+ assert_quad(quad(myfunc, 0, pi, (2, 1.8)), 0.30614353532540296487)
136
+
137
+ def test_indefinite(self):
138
+ # 2) Infinite integration limits --- Euler's constant
139
+ def myfunc(x): # Euler's constant integrand
140
+ return -exp(-x)*log(x)
141
+ assert_quad(quad(myfunc, 0, np.inf), 0.577215664901532860606512)
142
+
143
+ def test_singular(self):
144
+ # 3) Singular points in region of integration.
145
+ def myfunc(x):
146
+ if 0 < x < 2.5:
147
+ return sin(x)
148
+ elif 2.5 <= x <= 5.0:
149
+ return exp(-x)
150
+ else:
151
+ return 0.0
152
+
153
+ assert_quad(quad(myfunc, 0, 10, points=[2.5, 5.0]),
154
+ 1 - cos(2.5) + exp(-2.5) - exp(-5.0))
155
+
156
+ def test_sine_weighted_finite(self):
157
+ # 4) Sine weighted integral (finite limits)
158
+ def myfunc(x, a):
159
+ return exp(a*(x-1))
160
+
161
+ ome = 2.0**3.4
162
+ assert_quad(quad(myfunc, 0, 1, args=20, weight='sin', wvar=ome),
163
+ (20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2))
164
+
165
+ def test_sine_weighted_infinite(self):
166
+ # 5) Sine weighted integral (infinite limits)
167
+ def myfunc(x, a):
168
+ return exp(-x*a)
169
+
170
+ a = 4.0
171
+ ome = 3.0
172
+ assert_quad(quad(myfunc, 0, np.inf, args=a, weight='sin', wvar=ome),
173
+ ome/(a**2 + ome**2))
174
+
175
+ def test_cosine_weighted_infinite(self):
176
+ # 6) Cosine weighted integral (negative infinite limits)
177
+ def myfunc(x, a):
178
+ return exp(x*a)
179
+
180
+ a = 2.5
181
+ ome = 2.3
182
+ assert_quad(quad(myfunc, -np.inf, 0, args=a, weight='cos', wvar=ome),
183
+ a/(a**2 + ome**2))
184
+
185
+ def test_algebraic_log_weight(self):
186
+ # 6) Algebraic-logarithmic weight.
187
+ def myfunc(x, a):
188
+ return 1/(1+x+2**(-a))
189
+
190
+ a = 1.5
191
+ assert_quad(quad(myfunc, -1, 1, args=a, weight='alg',
192
+ wvar=(-0.5, -0.5)),
193
+ pi/sqrt((1+2**(-a))**2 - 1))
194
+
195
+ def test_cauchypv_weight(self):
196
+ # 7) Cauchy prinicpal value weighting w(x) = 1/(x-c)
197
+ def myfunc(x, a):
198
+ return 2.0**(-a)/((x-1)**2+4.0**(-a))
199
+
200
+ a = 0.4
201
+ tabledValue = ((2.0**(-0.4)*log(1.5) -
202
+ 2.0**(-1.4)*log((4.0**(-a)+16) / (4.0**(-a)+1)) -
203
+ arctan(2.0**(a+2)) -
204
+ arctan(2.0**a)) /
205
+ (4.0**(-a) + 1))
206
+ assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0),
207
+ tabledValue, error_tolerance=1.9e-8)
208
+
209
+ def test_b_less_than_a(self):
210
+ def f(x, p, q):
211
+ return p * np.exp(-q*x)
212
+
213
+ val_1, err_1 = quad(f, 0, np.inf, args=(2, 3))
214
+ val_2, err_2 = quad(f, np.inf, 0, args=(2, 3))
215
+ assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
216
+
217
+ def test_b_less_than_a_2(self):
218
+ def f(x, s):
219
+ return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s)
220
+
221
+ val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,))
222
+ val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,))
223
+ assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
224
+
225
+ def test_b_less_than_a_3(self):
226
+ def f(x):
227
+ return 1.0
228
+
229
+ val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0))
230
+ val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0))
231
+ assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
232
+
233
+ def test_b_less_than_a_full_output(self):
234
+ def f(x):
235
+ return 1.0
236
+
237
+ res_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0), full_output=True)
238
+ res_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0), full_output=True)
239
+ err = max(res_1[1], res_2[1])
240
+ assert_allclose(res_1[0], -res_2[0], atol=err)
241
+
242
+ def test_double_integral(self):
243
+ # 8) Double Integral test
244
+ def simpfunc(y, x): # Note order of arguments.
245
+ return x+y
246
+
247
+ a, b = 1.0, 2.0
248
+ assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x),
249
+ 5/6.0 * (b**3.0-a**3.0))
250
+
251
+ def test_double_integral2(self):
252
+ def func(x0, x1, t0, t1):
253
+ return x0 + x1 + t0 + t1
254
+ def g(x):
255
+ return x
256
+ def h(x):
257
+ return 2 * x
258
+ args = 1, 2
259
+ assert_quad(dblquad(func, 1, 2, g, h, args=args),35./6 + 9*.5)
260
+
261
+ def test_double_integral3(self):
262
+ def func(x0, x1):
263
+ return x0 + x1 + 1 + 2
264
+ assert_quad(dblquad(func, 1, 2, 1, 2),6.)
265
+
266
+ @pytest.mark.parametrize(
267
+ "x_lower, x_upper, y_lower, y_upper, expected",
268
+ [
269
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
270
+ # over domain D = [-inf, 0] for all n.
271
+ (-np.inf, 0, -np.inf, 0, np.pi / 4),
272
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
273
+ # over domain D = [-inf, -1] for each n (one at a time).
274
+ (-np.inf, -1, -np.inf, 0, np.pi / 4 * erfc(1)),
275
+ (-np.inf, 0, -np.inf, -1, np.pi / 4 * erfc(1)),
276
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
277
+ # over domain D = [-inf, -1] for all n.
278
+ (-np.inf, -1, -np.inf, -1, np.pi / 4 * (erfc(1) ** 2)),
279
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
280
+ # over domain D = [-inf, 1] for each n (one at a time).
281
+ (-np.inf, 1, -np.inf, 0, np.pi / 4 * (erf(1) + 1)),
282
+ (-np.inf, 0, -np.inf, 1, np.pi / 4 * (erf(1) + 1)),
283
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
284
+ # over domain D = [-inf, 1] for all n.
285
+ (-np.inf, 1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) ** 2)),
286
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
287
+ # over domain Dx = [-inf, -1] and Dy = [-inf, 1].
288
+ (-np.inf, -1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
289
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
290
+ # over domain Dx = [-inf, 1] and Dy = [-inf, -1].
291
+ (-np.inf, 1, -np.inf, -1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
292
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
293
+ # over domain D = [0, inf] for all n.
294
+ (0, np.inf, 0, np.inf, np.pi / 4),
295
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
296
+ # over domain D = [1, inf] for each n (one at a time).
297
+ (1, np.inf, 0, np.inf, np.pi / 4 * erfc(1)),
298
+ (0, np.inf, 1, np.inf, np.pi / 4 * erfc(1)),
299
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
300
+ # over domain D = [1, inf] for all n.
301
+ (1, np.inf, 1, np.inf, np.pi / 4 * (erfc(1) ** 2)),
302
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
303
+ # over domain D = [-1, inf] for each n (one at a time).
304
+ (-1, np.inf, 0, np.inf, np.pi / 4 * (erf(1) + 1)),
305
+ (0, np.inf, -1, np.inf, np.pi / 4 * (erf(1) + 1)),
306
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
307
+ # over domain D = [-1, inf] for all n.
308
+ (-1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) ** 2)),
309
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
310
+ # over domain Dx = [-1, inf] and Dy = [1, inf].
311
+ (-1, np.inf, 1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
312
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
313
+ # over domain Dx = [1, inf] and Dy = [-1, inf].
314
+ (1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
315
+ # Multiple integration of a function in n = 2 variables: f(x, y, z)
316
+ # over domain D = [-inf, inf] for all n.
317
+ (-np.inf, np.inf, -np.inf, np.inf, np.pi)
318
+ ]
319
+ )
320
+ def test_double_integral_improper(
321
+ self, x_lower, x_upper, y_lower, y_upper, expected
322
+ ):
323
+ # The Gaussian Integral.
324
+ def f(x, y):
325
+ return np.exp(-x ** 2 - y ** 2)
326
+
327
+ assert_quad(
328
+ dblquad(f, x_lower, x_upper, y_lower, y_upper),
329
+ expected,
330
+ error_tolerance=3e-8
331
+ )
332
+
333
+ def test_triple_integral(self):
334
+ # 9) Triple Integral test
335
+ def simpfunc(z, y, x, t): # Note order of arguments.
336
+ return (x+y+z)*t
337
+
338
+ a, b = 1.0, 2.0
339
+ assert_quad(tplquad(simpfunc, a, b,
340
+ lambda x: x, lambda x: 2*x,
341
+ lambda x, y: x - y, lambda x, y: x + y,
342
+ (2.,)),
343
+ 2*8/3.0 * (b**4.0 - a**4.0))
344
+
345
+ @pytest.mark.xslow
346
+ @pytest.mark.parametrize(
347
+ "x_lower, x_upper, y_lower, y_upper, z_lower, z_upper, expected",
348
+ [
349
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
350
+ # over domain D = [-inf, 0] for all n.
351
+ (-np.inf, 0, -np.inf, 0, -np.inf, 0, (np.pi ** (3 / 2)) / 8),
352
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
353
+ # over domain D = [-inf, -1] for each n (one at a time).
354
+ (-np.inf, -1, -np.inf, 0, -np.inf, 0,
355
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
356
+ (-np.inf, 0, -np.inf, -1, -np.inf, 0,
357
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
358
+ (-np.inf, 0, -np.inf, 0, -np.inf, -1,
359
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
360
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
361
+ # over domain D = [-inf, -1] for each n (two at a time).
362
+ (-np.inf, -1, -np.inf, -1, -np.inf, 0,
363
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
364
+ (-np.inf, -1, -np.inf, 0, -np.inf, -1,
365
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
366
+ (-np.inf, 0, -np.inf, -1, -np.inf, -1,
367
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
368
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
369
+ # over domain D = [-inf, -1] for all n.
370
+ (-np.inf, -1, -np.inf, -1, -np.inf, -1,
371
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
372
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
373
+ # over domain Dx = [-inf, -1] and Dy = Dz = [-inf, 1].
374
+ (-np.inf, -1, -np.inf, 1, -np.inf, 1,
375
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
376
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
377
+ # over domain Dx = Dy = [-inf, -1] and Dz = [-inf, 1].
378
+ (-np.inf, -1, -np.inf, -1, -np.inf, 1,
379
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
380
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
381
+ # over domain Dx = Dz = [-inf, -1] and Dy = [-inf, 1].
382
+ (-np.inf, -1, -np.inf, 1, -np.inf, -1,
383
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
384
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
385
+ # over domain Dx = [-inf, 1] and Dy = Dz = [-inf, -1].
386
+ (-np.inf, 1, -np.inf, -1, -np.inf, -1,
387
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
388
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
389
+ # over domain Dx = Dy = [-inf, 1] and Dz = [-inf, -1].
390
+ (-np.inf, 1, -np.inf, 1, -np.inf, -1,
391
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
392
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
393
+ # over domain Dx = Dz = [-inf, 1] and Dy = [-inf, -1].
394
+ (-np.inf, 1, -np.inf, -1, -np.inf, 1,
395
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
396
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
397
+ # over domain D = [-inf, 1] for each n (one at a time).
398
+ (-np.inf, 1, -np.inf, 0, -np.inf, 0,
399
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
400
+ (-np.inf, 0, -np.inf, 1, -np.inf, 0,
401
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
402
+ (-np.inf, 0, -np.inf, 0, -np.inf, 1,
403
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
404
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
405
+ # over domain D = [-inf, 1] for each n (two at a time).
406
+ (-np.inf, 1, -np.inf, 1, -np.inf, 0,
407
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
408
+ (-np.inf, 1, -np.inf, 0, -np.inf, 1,
409
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
410
+ (-np.inf, 0, -np.inf, 1, -np.inf, 1,
411
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
412
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
413
+ # over domain D = [-inf, 1] for all n.
414
+ (-np.inf, 1, -np.inf, 1, -np.inf, 1,
415
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
416
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
417
+ # over domain D = [0, inf] for all n.
418
+ (0, np.inf, 0, np.inf, 0, np.inf, (np.pi ** (3 / 2)) / 8),
419
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
420
+ # over domain D = [1, inf] for each n (one at a time).
421
+ (1, np.inf, 0, np.inf, 0, np.inf,
422
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
423
+ (0, np.inf, 1, np.inf, 0, np.inf,
424
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
425
+ (0, np.inf, 0, np.inf, 1, np.inf,
426
+ (np.pi ** (3 / 2)) / 8 * erfc(1)),
427
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
428
+ # over domain D = [1, inf] for each n (two at a time).
429
+ (1, np.inf, 1, np.inf, 0, np.inf,
430
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
431
+ (1, np.inf, 0, np.inf, 1, np.inf,
432
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
433
+ (0, np.inf, 1, np.inf, 1, np.inf,
434
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
435
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
436
+ # over domain D = [1, inf] for all n.
437
+ (1, np.inf, 1, np.inf, 1, np.inf,
438
+ (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
439
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
440
+ # over domain D = [-1, inf] for each n (one at a time).
441
+ (-1, np.inf, 0, np.inf, 0, np.inf,
442
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
443
+ (0, np.inf, -1, np.inf, 0, np.inf,
444
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
445
+ (0, np.inf, 0, np.inf, -1, np.inf,
446
+ (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
447
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
448
+ # over domain D = [-1, inf] for each n (two at a time).
449
+ (-1, np.inf, -1, np.inf, 0, np.inf,
450
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
451
+ (-1, np.inf, 0, np.inf, -1, np.inf,
452
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
453
+ (0, np.inf, -1, np.inf, -1, np.inf,
454
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
455
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
456
+ # over domain D = [-1, inf] for all n.
457
+ (-1, np.inf, -1, np.inf, -1, np.inf,
458
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
459
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
460
+ # over domain Dx = [1, inf] and Dy = Dz = [-1, inf].
461
+ (1, np.inf, -1, np.inf, -1, np.inf,
462
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
463
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
464
+ # over domain Dx = Dy = [1, inf] and Dz = [-1, inf].
465
+ (1, np.inf, 1, np.inf, -1, np.inf,
466
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
467
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
468
+ # over domain Dx = Dz = [1, inf] and Dy = [-1, inf].
469
+ (1, np.inf, -1, np.inf, 1, np.inf,
470
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
471
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
472
+ # over domain Dx = [-1, inf] and Dy = Dz = [1, inf].
473
+ (-1, np.inf, 1, np.inf, 1, np.inf,
474
+ (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
475
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
476
+ # over domain Dx = Dy = [-1, inf] and Dz = [1, inf].
477
+ (-1, np.inf, -1, np.inf, 1, np.inf,
478
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
479
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
480
+ # over domain Dx = Dz = [-1, inf] and Dy = [1, inf].
481
+ (-1, np.inf, 1, np.inf, -1, np.inf,
482
+ (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
483
+ # Multiple integration of a function in n = 3 variables: f(x, y, z)
484
+ # over domain D = [-inf, inf] for all n.
485
+ (-np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf,
486
+ np.pi ** (3 / 2)),
487
+ ],
488
+ )
489
+ def test_triple_integral_improper(
490
+ self,
491
+ x_lower,
492
+ x_upper,
493
+ y_lower,
494
+ y_upper,
495
+ z_lower,
496
+ z_upper,
497
+ expected
498
+ ):
499
+ # The Gaussian Integral.
500
+ def f(x, y, z):
501
+ return np.exp(-x ** 2 - y ** 2 - z ** 2)
502
+
503
+ assert_quad(
504
+ tplquad(f, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper),
505
+ expected,
506
+ error_tolerance=6e-8
507
+ )
508
+
509
+ def test_complex(self):
510
+ def tfunc(x):
511
+ return np.exp(1j*x)
512
+
513
+ assert np.allclose(
514
+ quad(tfunc, 0, np.pi/2, complex_func=True)[0],
515
+ 1+1j)
516
+
517
+ # We consider a divergent case in order to force quadpack
518
+ # to return an error message. The output is compared
519
+ # against what is returned by explicit integration
520
+ # of the parts.
521
+ kwargs = {'a': 0, 'b': np.inf, 'full_output': True,
522
+ 'weight': 'cos', 'wvar': 1}
523
+ res_c = quad(tfunc, complex_func=True, **kwargs)
524
+ res_r = quad(lambda x: np.real(np.exp(1j*x)),
525
+ complex_func=False,
526
+ **kwargs)
527
+ res_i = quad(lambda x: np.imag(np.exp(1j*x)),
528
+ complex_func=False,
529
+ **kwargs)
530
+
531
+ np.testing.assert_equal(res_c[0], res_r[0] + 1j*res_i[0])
532
+ np.testing.assert_equal(res_c[1], res_r[1] + 1j*res_i[1])
533
+
534
+ assert len(res_c[2]['real']) == len(res_r[2:]) == 3
535
+ assert res_c[2]['real'][2] == res_r[4]
536
+ assert res_c[2]['real'][1] == res_r[3]
537
+ assert res_c[2]['real'][0]['lst'] == res_r[2]['lst']
538
+
539
+ assert len(res_c[2]['imag']) == len(res_i[2:]) == 1
540
+ assert res_c[2]['imag'][0]['lst'] == res_i[2]['lst']
541
+
542
+
543
+ class TestNQuad:
544
+ @pytest.mark.fail_slow(5)
545
+ def test_fixed_limits(self):
546
+ def func1(x0, x1, x2, x3):
547
+ val = (x0**2 + x1*x2 - x3**3 + np.sin(x0) +
548
+ (1 if (x0 - 0.2*x3 - 0.5 - 0.25*x1 > 0) else 0))
549
+ return val
550
+
551
+ def opts_basic(*args):
552
+ return {'points': [0.2*args[2] + 0.5 + 0.25*args[0]]}
553
+
554
+ res = nquad(func1, [[0, 1], [-1, 1], [.13, .8], [-.15, 1]],
555
+ opts=[opts_basic, {}, {}, {}], full_output=True)
556
+ assert_quad(res[:-1], 1.5267454070738635)
557
+ assert_(res[-1]['neval'] > 0 and res[-1]['neval'] < 4e5)
558
+
559
+ @pytest.mark.fail_slow(5)
560
+ def test_variable_limits(self):
561
+ scale = .1
562
+
563
+ def func2(x0, x1, x2, x3, t0, t1):
564
+ val = (x0*x1*x3**2 + np.sin(x2) + 1 +
565
+ (1 if x0 + t1*x1 - t0 > 0 else 0))
566
+ return val
567
+
568
+ def lim0(x1, x2, x3, t0, t1):
569
+ return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
570
+ scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
571
+
572
+ def lim1(x2, x3, t0, t1):
573
+ return [scale * (t0*x2 + t1*x3) - 1,
574
+ scale * (t0*x2 + t1*x3) + 1]
575
+
576
+ def lim2(x3, t0, t1):
577
+ return [scale * (x3 + t0**2*t1**3) - 1,
578
+ scale * (x3 + t0**2*t1**3) + 1]
579
+
580
+ def lim3(t0, t1):
581
+ return [scale * (t0 + t1) - 1, scale * (t0 + t1) + 1]
582
+
583
+ def opts0(x1, x2, x3, t0, t1):
584
+ return {'points': [t0 - t1*x1]}
585
+
586
+ def opts1(x2, x3, t0, t1):
587
+ return {}
588
+
589
+ def opts2(x3, t0, t1):
590
+ return {}
591
+
592
+ def opts3(t0, t1):
593
+ return {}
594
+
595
+ res = nquad(func2, [lim0, lim1, lim2, lim3], args=(0, 0),
596
+ opts=[opts0, opts1, opts2, opts3])
597
+ assert_quad(res, 25.066666666666663)
598
+
599
+ def test_square_separate_ranges_and_opts(self):
600
+ def f(y, x):
601
+ return 1.0
602
+
603
+ assert_quad(nquad(f, [[-1, 1], [-1, 1]], opts=[{}, {}]), 4.0)
604
+
605
+ def test_square_aliased_ranges_and_opts(self):
606
+ def f(y, x):
607
+ return 1.0
608
+
609
+ r = [-1, 1]
610
+ opt = {}
611
+ assert_quad(nquad(f, [r, r], opts=[opt, opt]), 4.0)
612
+
613
+ def test_square_separate_fn_ranges_and_opts(self):
614
+ def f(y, x):
615
+ return 1.0
616
+
617
+ def fn_range0(*args):
618
+ return (-1, 1)
619
+
620
+ def fn_range1(*args):
621
+ return (-1, 1)
622
+
623
+ def fn_opt0(*args):
624
+ return {}
625
+
626
+ def fn_opt1(*args):
627
+ return {}
628
+
629
+ ranges = [fn_range0, fn_range1]
630
+ opts = [fn_opt0, fn_opt1]
631
+ assert_quad(nquad(f, ranges, opts=opts), 4.0)
632
+
633
+ def test_square_aliased_fn_ranges_and_opts(self):
634
+ def f(y, x):
635
+ return 1.0
636
+
637
+ def fn_range(*args):
638
+ return (-1, 1)
639
+
640
+ def fn_opt(*args):
641
+ return {}
642
+
643
+ ranges = [fn_range, fn_range]
644
+ opts = [fn_opt, fn_opt]
645
+ assert_quad(nquad(f, ranges, opts=opts), 4.0)
646
+
647
+ def test_matching_quad(self):
648
+ def func(x):
649
+ return x**2 + 1
650
+
651
+ res, reserr = quad(func, 0, 4)
652
+ res2, reserr2 = nquad(func, ranges=[[0, 4]])
653
+ assert_almost_equal(res, res2)
654
+ assert_almost_equal(reserr, reserr2)
655
+
656
+ def test_matching_dblquad(self):
657
+ def func2d(x0, x1):
658
+ return x0**2 + x1**3 - x0 * x1 + 1
659
+
660
+ res, reserr = dblquad(func2d, -2, 2, lambda x: -3, lambda x: 3)
661
+ res2, reserr2 = nquad(func2d, [[-3, 3], (-2, 2)])
662
+ assert_almost_equal(res, res2)
663
+ assert_almost_equal(reserr, reserr2)
664
+
665
+ def test_matching_tplquad(self):
666
+ def func3d(x0, x1, x2, c0, c1):
667
+ return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2)
668
+
669
+ res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2,
670
+ lambda x, y: -np.pi, lambda x, y: np.pi,
671
+ args=(2, 3))
672
+ res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
673
+ assert_almost_equal(res, res2)
674
+
675
+ def test_dict_as_opts(self):
676
+ try:
677
+ nquad(lambda x, y: x * y, [[0, 1], [0, 1]], opts={'epsrel': 0.0001})
678
+ except TypeError:
679
+ assert False
680
+
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable-error-code="attr-defined"
2
+ import pytest
3
+ import numpy as np
4
+ from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
5
+ from hypothesis import given
6
+ import hypothesis.strategies as st
7
+ import hypothesis.extra.numpy as hyp_num
8
+
9
+ from scipy.integrate import (romb, newton_cotes,
10
+ cumulative_trapezoid, trapezoid,
11
+ quad, simpson, fixed_quad,
12
+ qmc_quad, cumulative_simpson)
13
+ from scipy.integrate._quadrature import _cumulative_simpson_unequal_intervals
14
+
15
+ from scipy import stats, special, integrate
16
+ from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
17
+ from scipy._lib._array_api_no_0d import xp_assert_close
18
+
19
+ skip_xp_backends = pytest.mark.skip_xp_backends
20
+
21
+
22
+ class TestFixedQuad:
23
+ def test_scalar(self):
24
+ n = 4
25
+ expected = 1/(2*n)
26
+ got, _ = fixed_quad(lambda x: x**(2*n - 1), 0, 1, n=n)
27
+ # quadrature exact for this input
28
+ assert_allclose(got, expected, rtol=1e-12)
29
+
30
+ def test_vector(self):
31
+ n = 4
32
+ p = np.arange(1, 2*n)
33
+ expected = 1/(p + 1)
34
+ got, _ = fixed_quad(lambda x: x**p[:, None], 0, 1, n=n)
35
+ assert_allclose(got, expected, rtol=1e-12)
36
+
37
+
38
+ class TestQuadrature:
39
+ def quad(self, x, a, b, args):
40
+ raise NotImplementedError
41
+
42
+ def test_romb(self):
43
+ assert_equal(romb(np.arange(17)), 128)
44
+
45
+ def test_romb_gh_3731(self):
46
+ # Check that romb makes maximal use of data points
47
+ x = np.arange(2**4+1)
48
+ y = np.cos(0.2*x)
49
+ val = romb(y)
50
+ val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max())
51
+ assert_allclose(val, val2, rtol=1e-8, atol=0)
52
+
53
+ def test_newton_cotes(self):
54
+ """Test the first few degrees, for evenly spaced points."""
55
+ n = 1
56
+ wts, errcoff = newton_cotes(n, 1)
57
+ assert_equal(wts, n*np.array([0.5, 0.5]))
58
+ assert_almost_equal(errcoff, -n**3/12.0)
59
+
60
+ n = 2
61
+ wts, errcoff = newton_cotes(n, 1)
62
+ assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)
63
+ assert_almost_equal(errcoff, -n**5/2880.0)
64
+
65
+ n = 3
66
+ wts, errcoff = newton_cotes(n, 1)
67
+ assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)
68
+ assert_almost_equal(errcoff, -n**5/6480.0)
69
+
70
+ n = 4
71
+ wts, errcoff = newton_cotes(n, 1)
72
+ assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)
73
+ assert_almost_equal(errcoff, -n**7/1935360.0)
74
+
75
+ def test_newton_cotes2(self):
76
+ """Test newton_cotes with points that are not evenly spaced."""
77
+
78
+ x = np.array([0.0, 1.5, 2.0])
79
+ y = x**2
80
+ wts, errcoff = newton_cotes(x)
81
+ exact_integral = 8.0/3
82
+ numeric_integral = np.dot(wts, y)
83
+ assert_almost_equal(numeric_integral, exact_integral)
84
+
85
+ x = np.array([0.0, 1.4, 2.1, 3.0])
86
+ y = x**2
87
+ wts, errcoff = newton_cotes(x)
88
+ exact_integral = 9.0
89
+ numeric_integral = np.dot(wts, y)
90
+ assert_almost_equal(numeric_integral, exact_integral)
91
+
92
+ def test_simpson(self):
93
+ y = np.arange(17)
94
+ assert_equal(simpson(y), 128)
95
+ assert_equal(simpson(y, dx=0.5), 64)
96
+ assert_equal(simpson(y, x=np.linspace(0, 4, 17)), 32)
97
+
98
+ # integral should be exactly 21
99
+ x = np.linspace(1, 4, 4)
100
+ def f(x):
101
+ return x**2
102
+
103
+ assert_allclose(simpson(f(x), x=x), 21.0)
104
+
105
+ # integral should be exactly 114
106
+ x = np.linspace(1, 7, 4)
107
+ assert_allclose(simpson(f(x), dx=2.0), 114)
108
+
109
+ # test multi-axis behaviour
110
+ a = np.arange(16).reshape(4, 4)
111
+ x = np.arange(64.).reshape(4, 4, 4)
112
+ y = f(x)
113
+ for i in range(3):
114
+ r = simpson(y, x=x, axis=i)
115
+ it = np.nditer(a, flags=['multi_index'])
116
+ for _ in it:
117
+ idx = list(it.multi_index)
118
+ idx.insert(i, slice(None))
119
+ integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
120
+ assert_allclose(r[it.multi_index], integral)
121
+
122
+ # test when integration axis only has two points
123
+ x = np.arange(16).reshape(8, 2)
124
+ y = f(x)
125
+ r = simpson(y, x=x, axis=-1)
126
+
127
+ integral = 0.5 * (y[:, 1] + y[:, 0]) * (x[:, 1] - x[:, 0])
128
+ assert_allclose(r, integral)
129
+
130
+ # odd points, test multi-axis behaviour
131
+ a = np.arange(25).reshape(5, 5)
132
+ x = np.arange(125).reshape(5, 5, 5)
133
+ y = f(x)
134
+ for i in range(3):
135
+ r = simpson(y, x=x, axis=i)
136
+ it = np.nditer(a, flags=['multi_index'])
137
+ for _ in it:
138
+ idx = list(it.multi_index)
139
+ idx.insert(i, slice(None))
140
+ integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
141
+ assert_allclose(r[it.multi_index], integral)
142
+
143
+ # Tests for checking base case
144
+ x = np.array([3])
145
+ y = np.power(x, 2)
146
+ assert_allclose(simpson(y, x=x, axis=0), 0.0)
147
+ assert_allclose(simpson(y, x=x, axis=-1), 0.0)
148
+
149
+ x = np.array([3, 3, 3, 3])
150
+ y = np.power(x, 2)
151
+ assert_allclose(simpson(y, x=x, axis=0), 0.0)
152
+ assert_allclose(simpson(y, x=x, axis=-1), 0.0)
153
+
154
+ x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8]])
155
+ y = np.power(x, 2)
156
+ zero_axis = [0.0, 0.0, 0.0, 0.0]
157
+ default_axis = [170 + 1/3] * 3 # 8**3 / 3 - 1/3
158
+ assert_allclose(simpson(y, x=x, axis=0), zero_axis)
159
+ # the following should be exact
160
+ assert_allclose(simpson(y, x=x, axis=-1), default_axis)
161
+
162
+ x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 8, 16, 32]])
163
+ y = np.power(x, 2)
164
+ zero_axis = [0.0, 136.0, 1088.0, 8704.0]
165
+ default_axis = [170 + 1/3, 170 + 1/3, 32**3 / 3 - 1/3]
166
+ assert_allclose(simpson(y, x=x, axis=0), zero_axis)
167
+ assert_allclose(simpson(y, x=x, axis=-1), default_axis)
168
+
169
+
170
+ @pytest.mark.parametrize('droplast', [False, True])
171
+ def test_simpson_2d_integer_no_x(self, droplast):
172
+ # The inputs are 2d integer arrays. The results should be
173
+ # identical to the results when the inputs are floating point.
174
+ y = np.array([[2, 2, 4, 4, 8, 8, -4, 5],
175
+ [4, 4, 2, -4, 10, 22, -2, 10]])
176
+ if droplast:
177
+ y = y[:, :-1]
178
+ result = simpson(y, axis=-1)
179
+ expected = simpson(np.array(y, dtype=np.float64), axis=-1)
180
+ assert_equal(result, expected)
181
+
182
+
183
+ class TestCumulative_trapezoid:
184
+ def test_1d(self):
185
+ x = np.linspace(-2, 2, num=5)
186
+ y = x
187
+ y_int = cumulative_trapezoid(y, x, initial=0)
188
+ y_expected = [0., -1.5, -2., -1.5, 0.]
189
+ assert_allclose(y_int, y_expected)
190
+
191
+ y_int = cumulative_trapezoid(y, x, initial=None)
192
+ assert_allclose(y_int, y_expected[1:])
193
+
194
+ def test_y_nd_x_nd(self):
195
+ x = np.arange(3 * 2 * 4).reshape(3, 2, 4)
196
+ y = x
197
+ y_int = cumulative_trapezoid(y, x, initial=0)
198
+ y_expected = np.array([[[0., 0.5, 2., 4.5],
199
+ [0., 4.5, 10., 16.5]],
200
+ [[0., 8.5, 18., 28.5],
201
+ [0., 12.5, 26., 40.5]],
202
+ [[0., 16.5, 34., 52.5],
203
+ [0., 20.5, 42., 64.5]]])
204
+
205
+ assert_allclose(y_int, y_expected)
206
+
207
+ # Try with all axes
208
+ shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)]
209
+ for axis, shape in zip([0, 1, 2], shapes):
210
+ y_int = cumulative_trapezoid(y, x, initial=0, axis=axis)
211
+ assert_equal(y_int.shape, (3, 2, 4))
212
+ y_int = cumulative_trapezoid(y, x, initial=None, axis=axis)
213
+ assert_equal(y_int.shape, shape)
214
+
215
+ def test_y_nd_x_1d(self):
216
+ y = np.arange(3 * 2 * 4).reshape(3, 2, 4)
217
+ x = np.arange(4)**2
218
+ # Try with all axes
219
+ ys_expected = (
220
+ np.array([[[4., 5., 6., 7.],
221
+ [8., 9., 10., 11.]],
222
+ [[40., 44., 48., 52.],
223
+ [56., 60., 64., 68.]]]),
224
+ np.array([[[2., 3., 4., 5.]],
225
+ [[10., 11., 12., 13.]],
226
+ [[18., 19., 20., 21.]]]),
227
+ np.array([[[0.5, 5., 17.5],
228
+ [4.5, 21., 53.5]],
229
+ [[8.5, 37., 89.5],
230
+ [12.5, 53., 125.5]],
231
+ [[16.5, 69., 161.5],
232
+ [20.5, 85., 197.5]]]))
233
+
234
+ for axis, y_expected in zip([0, 1, 2], ys_expected):
235
+ y_int = cumulative_trapezoid(y, x=x[:y.shape[axis]], axis=axis,
236
+ initial=None)
237
+ assert_allclose(y_int, y_expected)
238
+
239
+ def test_x_none(self):
240
+ y = np.linspace(-2, 2, num=5)
241
+
242
+ y_int = cumulative_trapezoid(y)
243
+ y_expected = [-1.5, -2., -1.5, 0.]
244
+ assert_allclose(y_int, y_expected)
245
+
246
+ y_int = cumulative_trapezoid(y, initial=0)
247
+ y_expected = [0, -1.5, -2., -1.5, 0.]
248
+ assert_allclose(y_int, y_expected)
249
+
250
+ y_int = cumulative_trapezoid(y, dx=3)
251
+ y_expected = [-4.5, -6., -4.5, 0.]
252
+ assert_allclose(y_int, y_expected)
253
+
254
+ y_int = cumulative_trapezoid(y, dx=3, initial=0)
255
+ y_expected = [0, -4.5, -6., -4.5, 0.]
256
+ assert_allclose(y_int, y_expected)
257
+
258
+ @pytest.mark.parametrize(
259
+ "initial", [1, 0.5]
260
+ )
261
+ def test_initial_error(self, initial):
262
+ """If initial is not None or 0, a ValueError is raised."""
263
+ y = np.linspace(0, 10, num=10)
264
+ with pytest.raises(ValueError, match="`initial`"):
265
+ cumulative_trapezoid(y, initial=initial)
266
+
267
+ def test_zero_len_y(self):
268
+ with pytest.raises(ValueError, match="At least one point is required"):
269
+ cumulative_trapezoid(y=[])
270
+
271
+
272
+ @array_api_compatible
273
+ class TestTrapezoid:
274
+ def test_simple(self, xp):
275
+ x = xp.arange(-10, 10, .1)
276
+ r = trapezoid(xp.exp(-.5 * x ** 2) / xp.sqrt(2 * xp.asarray(xp.pi)), dx=0.1)
277
+ # check integral of normal equals 1
278
+ xp_assert_close(r, xp.asarray(1.0))
279
+
280
+ @skip_xp_backends('jax.numpy',
281
+ reasons=["JAX arrays do not support item assignment"])
282
+ @pytest.mark.usefixtures("skip_xp_backends")
283
+ def test_ndim(self, xp):
284
+ x = xp.linspace(0, 1, 3)
285
+ y = xp.linspace(0, 2, 8)
286
+ z = xp.linspace(0, 3, 13)
287
+
288
+ wx = xp.ones_like(x) * (x[1] - x[0])
289
+ wx[0] /= 2
290
+ wx[-1] /= 2
291
+ wy = xp.ones_like(y) * (y[1] - y[0])
292
+ wy[0] /= 2
293
+ wy[-1] /= 2
294
+ wz = xp.ones_like(z) * (z[1] - z[0])
295
+ wz[0] /= 2
296
+ wz[-1] /= 2
297
+
298
+ q = x[:, None, None] + y[None,:, None] + z[None, None,:]
299
+
300
+ qx = xp.sum(q * wx[:, None, None], axis=0)
301
+ qy = xp.sum(q * wy[None, :, None], axis=1)
302
+ qz = xp.sum(q * wz[None, None, :], axis=2)
303
+
304
+ # n-d `x`
305
+ r = trapezoid(q, x=x[:, None, None], axis=0)
306
+ xp_assert_close(r, qx)
307
+ r = trapezoid(q, x=y[None,:, None], axis=1)
308
+ xp_assert_close(r, qy)
309
+ r = trapezoid(q, x=z[None, None,:], axis=2)
310
+ xp_assert_close(r, qz)
311
+
312
+ # 1-d `x`
313
+ r = trapezoid(q, x=x, axis=0)
314
+ xp_assert_close(r, qx)
315
+ r = trapezoid(q, x=y, axis=1)
316
+ xp_assert_close(r, qy)
317
+ r = trapezoid(q, x=z, axis=2)
318
+ xp_assert_close(r, qz)
319
+
320
+ @skip_xp_backends('jax.numpy',
321
+ reasons=["JAX arrays do not support item assignment"])
322
+ @pytest.mark.usefixtures("skip_xp_backends")
323
+ def test_gh21908(self, xp):
324
+ # extended testing for n-dim arrays
325
+ x = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
326
+ y = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
327
+
328
+ out0 = xp.linspace(200, 380, 10)
329
+ xp_assert_close(trapezoid(y, x=x, axis=0), out0)
330
+ xp_assert_close(trapezoid(y, x=xp.asarray([0, 10., 20.]), axis=0), out0)
331
+ # x needs to be broadcastable against y
332
+ xp_assert_close(
333
+ trapezoid(y, x=xp.asarray([0, 10., 20.])[:, None], axis=0),
334
+ out0
335
+ )
336
+ with pytest.raises(Exception):
337
+ # x is not broadcastable against y
338
+ trapezoid(y, x=xp.asarray([0, 10., 20.])[None, :], axis=0)
339
+
340
+ out1 = xp.asarray([ 40.5, 130.5, 220.5])
341
+ xp_assert_close(trapezoid(y, x=x, axis=1), out1)
342
+ xp_assert_close(
343
+ trapezoid(y, x=xp.linspace(0, 9, 10), axis=1),
344
+ out1
345
+ )
346
+
347
+ @skip_xp_invalid_arg
348
+ def test_masked(self, xp):
349
+ # Testing that masked arrays behave as if the function is 0 where
350
+ # masked
351
+ x = np.arange(5)
352
+ y = x * x
353
+ mask = x == 2
354
+ ym = np.ma.array(y, mask=mask)
355
+ r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
356
+ assert_allclose(trapezoid(ym, x), r)
357
+
358
+ xm = np.ma.array(x, mask=mask)
359
+ assert_allclose(trapezoid(ym, xm), r)
360
+
361
+ xm = np.ma.array(x, mask=mask)
362
+ assert_allclose(trapezoid(y, xm), r)
363
+
364
+ @skip_xp_backends(np_only=True,
365
+ reasons=['array-likes only supported for NumPy backend'])
366
+ @pytest.mark.usefixtures("skip_xp_backends")
367
+ def test_array_like(self, xp):
368
+ x = list(range(5))
369
+ y = [t * t for t in x]
370
+ xarr = xp.asarray(x, dtype=xp.float64)
371
+ yarr = xp.asarray(y, dtype=xp.float64)
372
+ res = trapezoid(y, x)
373
+ resarr = trapezoid(yarr, xarr)
374
+ xp_assert_close(res, resarr)
375
+
376
+
377
+ class TestQMCQuad:
378
+ @pytest.mark.thread_unsafe
379
+ def test_input_validation(self):
380
+ message = "`func` must be callable."
381
+ with pytest.raises(TypeError, match=message):
382
+ qmc_quad("a duck", [0, 0], [1, 1])
383
+
384
+ message = "`func` must evaluate the integrand at points..."
385
+ with pytest.raises(ValueError, match=message):
386
+ qmc_quad(lambda: 1, [0, 0], [1, 1])
387
+
388
+ def func(x):
389
+ assert x.ndim == 1
390
+ return np.sum(x)
391
+ message = "Exception encountered when attempting vectorized call..."
392
+ with pytest.warns(UserWarning, match=message):
393
+ qmc_quad(func, [0, 0], [1, 1])
394
+
395
+ message = "`n_points` must be an integer."
396
+ with pytest.raises(TypeError, match=message):
397
+ qmc_quad(lambda x: 1, [0, 0], [1, 1], n_points=1024.5)
398
+
399
+ message = "`n_estimates` must be an integer."
400
+ with pytest.raises(TypeError, match=message):
401
+ qmc_quad(lambda x: 1, [0, 0], [1, 1], n_estimates=8.5)
402
+
403
+ message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
404
+ with pytest.raises(TypeError, match=message):
405
+ qmc_quad(lambda x: 1, [0, 0], [1, 1], qrng="a duck")
406
+
407
+ message = "`qrng` must be initialized with dimensionality equal to "
408
+ with pytest.raises(ValueError, match=message):
409
+ qmc_quad(lambda x: 1, [0, 0], [1, 1], qrng=stats.qmc.Sobol(1))
410
+
411
+ message = r"`log` must be boolean \(`True` or `False`\)."
412
+ with pytest.raises(TypeError, match=message):
413
+ qmc_quad(lambda x: 1, [0, 0], [1, 1], log=10)
414
+
415
+ def basic_test(self, n_points=2**8, n_estimates=8, signs=None):
416
+ if signs is None:
417
+ signs = np.ones(2)
418
+ ndim = 2
419
+ mean = np.zeros(ndim)
420
+ cov = np.eye(ndim)
421
+
422
+ def func(x):
423
+ return stats.multivariate_normal.pdf(x.T, mean, cov)
424
+
425
+ rng = np.random.default_rng(2879434385674690281)
426
+ qrng = stats.qmc.Sobol(ndim, seed=rng)
427
+ a = np.zeros(ndim)
428
+ b = np.ones(ndim) * signs
429
+ res = qmc_quad(func, a, b, n_points=n_points,
430
+ n_estimates=n_estimates, qrng=qrng)
431
+ ref = stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
432
+ atol = special.stdtrit(n_estimates-1, 0.995) * res.standard_error # 99% CI
433
+ assert_allclose(res.integral, ref, atol=atol)
434
+ assert np.prod(signs)*res.integral > 0
435
+
436
+ rng = np.random.default_rng(2879434385674690281)
437
+ qrng = stats.qmc.Sobol(ndim, seed=rng)
438
+ logres = qmc_quad(lambda *args: np.log(func(*args)), a, b,
439
+ n_points=n_points, n_estimates=n_estimates,
440
+ log=True, qrng=qrng)
441
+ assert_allclose(np.exp(logres.integral), res.integral, rtol=1e-14)
442
+ assert np.imag(logres.integral) == (np.pi if np.prod(signs) < 0 else 0)
443
+ assert_allclose(np.exp(logres.standard_error),
444
+ res.standard_error, rtol=1e-14, atol=1e-16)
445
+
446
+ @pytest.mark.parametrize("n_points", [2**8, 2**12])
447
+ @pytest.mark.parametrize("n_estimates", [8, 16])
448
+ def test_basic(self, n_points, n_estimates):
449
+ self.basic_test(n_points, n_estimates)
450
+
451
+ @pytest.mark.parametrize("signs", [[1, 1], [-1, -1], [-1, 1], [1, -1]])
452
+ def test_sign(self, signs):
453
+ self.basic_test(signs=signs)
454
+
455
+ @pytest.mark.thread_unsafe
456
+ @pytest.mark.parametrize("log", [False, True])
457
+ def test_zero(self, log):
458
+ message = "A lower limit was equal to an upper limit, so"
459
+ with pytest.warns(UserWarning, match=message):
460
+ res = qmc_quad(lambda x: 1, [0, 0], [0, 1], log=log)
461
+ assert res.integral == (-np.inf if log else 0)
462
+ assert res.standard_error == 0
463
+
464
+ def test_flexible_input(self):
465
+ # check that qrng is not required
466
+ # also checks that for 1d problems, a and b can be scalars
467
+ def func(x):
468
+ return stats.norm.pdf(x, scale=2)
469
+
470
+ res = qmc_quad(func, 0, 1)
471
+ ref = stats.norm.cdf(1, scale=2) - stats.norm.cdf(0, scale=2)
472
+ assert_allclose(res.integral, ref, 1e-2)
473
+
474
+
475
+ def cumulative_simpson_nd_reference(y, *, x=None, dx=None, initial=None, axis=-1):
476
+ # Use cumulative_trapezoid if length of y < 3
477
+ if y.shape[axis] < 3:
478
+ if initial is None:
479
+ return cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=None)
480
+ else:
481
+ return initial + cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=0)
482
+
483
+ # Ensure that working axis is last axis
484
+ y = np.moveaxis(y, axis, -1)
485
+ x = np.moveaxis(x, axis, -1) if np.ndim(x) > 1 else x
486
+ dx = np.moveaxis(dx, axis, -1) if np.ndim(dx) > 1 else dx
487
+ initial = np.moveaxis(initial, axis, -1) if np.ndim(initial) > 1 else initial
488
+
489
+ # If `x` is not present, create it from `dx`
490
+ n = y.shape[-1]
491
+ x = dx * np.arange(n) if dx is not None else x
492
+ # Similarly, if `initial` is not present, set it to 0
493
+ initial_was_none = initial is None
494
+ initial = 0 if initial_was_none else initial
495
+
496
+ # `np.apply_along_axis` accepts only one array, so concatenate arguments
497
+ x = np.broadcast_to(x, y.shape)
498
+ initial = np.broadcast_to(initial, y.shape[:-1] + (1,))
499
+ z = np.concatenate((y, x, initial), axis=-1)
500
+
501
+ # Use `np.apply_along_axis` to compute result
502
+ def f(z):
503
+ return cumulative_simpson(z[:n], x=z[n:2*n], initial=z[2*n:])
504
+ res = np.apply_along_axis(f, -1, z)
505
+
506
+ # Remove `initial` and undo axis move as needed
507
+ res = res[..., 1:] if initial_was_none else res
508
+ res = np.moveaxis(res, -1, axis)
509
+ return res
510
+
511
+
512
+ class TestCumulativeSimpson:
513
+ x0 = np.arange(4)
514
+ y0 = x0**2
515
+
516
+ @pytest.mark.parametrize('use_dx', (False, True))
517
+ @pytest.mark.parametrize('use_initial', (False, True))
518
+ def test_1d(self, use_dx, use_initial):
519
+ # Test for exact agreement with polynomial of highest
520
+ # possible order (3 if `dx` is constant, 2 otherwise).
521
+ rng = np.random.default_rng(82456839535679456794)
522
+ n = 10
523
+
524
+ # Generate random polynomials and ground truth
525
+ # integral of appropriate order
526
+ order = 3 if use_dx else 2
527
+ dx = rng.random()
528
+ x = (np.sort(rng.random(n)) if order == 2
529
+ else np.arange(n)*dx + rng.random())
530
+ i = np.arange(order + 1)[:, np.newaxis]
531
+ c = rng.random(order + 1)[:, np.newaxis]
532
+ y = np.sum(c*x**i, axis=0)
533
+ Y = np.sum(c*x**(i + 1)/(i + 1), axis=0)
534
+ ref = Y if use_initial else (Y-Y[0])[1:]
535
+
536
+ # Integrate with `cumulative_simpson`
537
+ initial = Y[0] if use_initial else None
538
+ kwarg = {'dx': dx} if use_dx else {'x': x}
539
+ res = cumulative_simpson(y, **kwarg, initial=initial)
540
+
541
+ # Compare result against reference
542
+ if not use_dx:
543
+ assert_allclose(res, ref, rtol=2e-15)
544
+ else:
545
+ i0 = 0 if use_initial else 1
546
+ # all terms are "close"
547
+ assert_allclose(res, ref, rtol=0.0025)
548
+ # only even-interval terms are "exact"
549
+ assert_allclose(res[i0::2], ref[i0::2], rtol=2e-15)
550
+
551
+ @pytest.mark.parametrize('axis', np.arange(-3, 3))
552
+ @pytest.mark.parametrize('x_ndim', (1, 3))
553
+ @pytest.mark.parametrize('x_len', (1, 2, 7))
554
+ @pytest.mark.parametrize('i_ndim', (None, 0, 3,))
555
+ @pytest.mark.parametrize('dx', (None, True))
556
+ def test_nd(self, axis, x_ndim, x_len, i_ndim, dx):
557
+ # Test behavior of `cumulative_simpson` with N-D `y`
558
+ rng = np.random.default_rng(82456839535679456794)
559
+
560
+ # determine shapes
561
+ shape = [5, 6, x_len]
562
+ shape[axis], shape[-1] = shape[-1], shape[axis]
563
+ shape_len_1 = shape.copy()
564
+ shape_len_1[axis] = 1
565
+ i_shape = shape_len_1 if i_ndim == 3 else ()
566
+
567
+ # initialize arguments
568
+ y = rng.random(size=shape)
569
+ x, dx = None, None
570
+ if dx:
571
+ dx = rng.random(size=shape_len_1) if x_ndim > 1 else rng.random()
572
+ else:
573
+ x = (np.sort(rng.random(size=shape), axis=axis) if x_ndim > 1
574
+ else np.sort(rng.random(size=shape[axis])))
575
+ initial = None if i_ndim is None else rng.random(size=i_shape)
576
+
577
+ # compare results
578
+ res = cumulative_simpson(y, x=x, dx=dx, initial=initial, axis=axis)
579
+ ref = cumulative_simpson_nd_reference(y, x=x, dx=dx, initial=initial, axis=axis)
580
+ np.testing.assert_allclose(res, ref, rtol=1e-15)
581
+
582
+ @pytest.mark.parametrize(('message', 'kwarg_update'), [
583
+ ("x must be strictly increasing", dict(x=[2, 2, 3, 4])),
584
+ ("x must be strictly increasing", dict(x=[x0, [2, 2, 4, 8]], y=[y0, y0])),
585
+ ("x must be strictly increasing", dict(x=[x0, x0, x0], y=[y0, y0, y0], axis=0)),
586
+ ("At least one point is required", dict(x=[], y=[])),
587
+ ("`axis=4` is not valid for `y` with `y.ndim=1`", dict(axis=4)),
588
+ ("shape of `x` must be the same as `y` or 1-D", dict(x=np.arange(5))),
589
+ ("`initial` must either be a scalar or...", dict(initial=np.arange(5))),
590
+ ("`dx` must either be a scalar or...", dict(x=None, dx=np.arange(5))),
591
+ ])
592
+ def test_simpson_exceptions(self, message, kwarg_update):
593
+ kwargs0 = dict(y=self.y0, x=self.x0, dx=None, initial=None, axis=-1)
594
+ with pytest.raises(ValueError, match=message):
595
+ cumulative_simpson(**dict(kwargs0, **kwarg_update))
596
+
597
+ def test_special_cases(self):
598
+ # Test special cases not checked elsewhere
599
+ rng = np.random.default_rng(82456839535679456794)
600
+ y = rng.random(size=10)
601
+ res = cumulative_simpson(y, dx=0)
602
+ assert_equal(res, 0)
603
+
604
+ # Should add tests of:
605
+ # - all elements of `x` identical
606
+ # These should work as they do for `simpson`
607
+
608
+ def _get_theoretical_diff_between_simps_and_cum_simps(self, y, x):
609
+ """`cumulative_simpson` and `simpson` can be tested against other to verify
610
+ they give consistent results. `simpson` will iteratively be called with
611
+ successively higher upper limits of integration. This function calculates
612
+ the theoretical correction required to `simpson` at even intervals to match
613
+ with `cumulative_simpson`.
614
+ """
615
+ d = np.diff(x, axis=-1)
616
+ sub_integrals_h1 = _cumulative_simpson_unequal_intervals(y, d)
617
+ sub_integrals_h2 = _cumulative_simpson_unequal_intervals(
618
+ y[..., ::-1], d[..., ::-1]
619
+ )[..., ::-1]
620
+
621
+ # Concatenate to build difference array
622
+ zeros_shape = (*y.shape[:-1], 1)
623
+ theoretical_difference = np.concatenate(
624
+ [
625
+ np.zeros(zeros_shape),
626
+ (sub_integrals_h1[..., 1:] - sub_integrals_h2[..., :-1]),
627
+ np.zeros(zeros_shape),
628
+ ],
629
+ axis=-1,
630
+ )
631
+ # Differences only expected at even intervals. Odd intervals will
632
+ # match exactly so there is no correction
633
+ theoretical_difference[..., 1::2] = 0.0
634
+ # Note: the first interval will not match from this correction as
635
+ # `simpson` uses the trapezoidal rule
636
+ return theoretical_difference
637
+
638
+ @pytest.mark.thread_unsafe
639
+ @pytest.mark.slow
640
+ @given(
641
+ y=hyp_num.arrays(
642
+ np.float64,
643
+ hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
644
+ elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
645
+ )
646
+ )
647
+ def test_cumulative_simpson_against_simpson_with_default_dx(
648
+ self, y
649
+ ):
650
+ """Theoretically, the output of `cumulative_simpson` will be identical
651
+ to `simpson` at all even indices and in the last index. The first index
652
+ will not match as `simpson` uses the trapezoidal rule when there are only two
653
+ data points. Odd indices after the first index are shown to match with
654
+ a mathematically-derived correction."""
655
+ def simpson_reference(y):
656
+ return np.stack(
657
+ [simpson(y[..., :i], dx=1.0) for i in range(2, y.shape[-1]+1)], axis=-1,
658
+ )
659
+
660
+ res = cumulative_simpson(y, dx=1.0)
661
+ ref = simpson_reference(y)
662
+ theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
663
+ y, x=np.arange(y.shape[-1])
664
+ )
665
+ np.testing.assert_allclose(
666
+ res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:]
667
+ )
668
+
669
+ @pytest.mark.thread_unsafe
670
+ @pytest.mark.slow
671
+ @given(
672
+ y=hyp_num.arrays(
673
+ np.float64,
674
+ hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
675
+ elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
676
+ )
677
+ )
678
+ def test_cumulative_simpson_against_simpson(
679
+ self, y
680
+ ):
681
+ """Theoretically, the output of `cumulative_simpson` will be identical
682
+ to `simpson` at all even indices and in the last index. The first index
683
+ will not match as `simpson` uses the trapezoidal rule when there are only two
684
+ data points. Odd indices after the first index are shown to match with
685
+ a mathematically-derived correction."""
686
+ interval = 10/(y.shape[-1] - 1)
687
+ x = np.linspace(0, 10, num=y.shape[-1])
688
+ x[1:] = x[1:] + 0.2*interval*np.random.uniform(-1, 1, len(x) - 1)
689
+
690
+ def simpson_reference(y, x):
691
+ return np.stack(
692
+ [simpson(y[..., :i], x=x[..., :i]) for i in range(2, y.shape[-1]+1)],
693
+ axis=-1,
694
+ )
695
+
696
+ res = cumulative_simpson(y, x=x)
697
+ ref = simpson_reference(y, x)
698
+ theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
699
+ y, x
700
+ )
701
+ np.testing.assert_allclose(
702
+ res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:]
703
+ )
704
+
705
+ class TestLebedev:
706
+ def test_input_validation(self):
707
+ # only certain rules are available
708
+ message = "Order n=-1 not available..."
709
+ with pytest.raises(NotImplementedError, match=message):
710
+ integrate.lebedev_rule(-1)
711
+
712
+ def test_quadrature(self):
713
+ # Test points/weights to integrate an example function
714
+
715
+ def f(x):
716
+ return np.exp(x[0])
717
+
718
+ x, w = integrate.lebedev_rule(15)
719
+ res = w @ f(x)
720
+ ref = 14.7680137457653 # lebedev_rule reference [3]
721
+ assert_allclose(res, ref, rtol=1e-14)
722
+ assert_allclose(np.sum(w), 4 * np.pi)
723
+
724
+ @pytest.mark.parametrize('order', list(range(3, 32, 2)) + list(range(35, 132, 6)))
725
+ def test_properties(self, order):
726
+ x, w = integrate.lebedev_rule(order)
727
+ # dispersion should be maximal; no clear spherical mean
728
+ with np.errstate(divide='ignore', invalid='ignore'):
729
+ res = stats.directional_stats(x.T, axis=0)
730
+ assert_allclose(res.mean_resultant_length, 0, atol=1e-15)
731
+ # weights should sum to 4*pi (surface area of unit sphere)
732
+ assert_allclose(np.sum(w), 4*np.pi)
llava_video/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py ADDED
@@ -0,0 +1,1153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable-error-code="attr-defined"
2
+ import os
3
+ import pytest
4
+ import math
5
+
6
+ import numpy as np
7
+ from numpy.testing import assert_allclose
8
+
9
+ from scipy.conftest import array_api_compatible
10
+ import scipy._lib._elementwise_iterative_method as eim
11
+ from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
12
+ from scipy._lib._array_api import array_namespace, xp_size, xp_ravel, xp_copy, is_numpy
13
+ from scipy import special, stats
14
+ from scipy.integrate import quad_vec, nsum, tanhsinh as _tanhsinh
15
+ from scipy.integrate._tanhsinh import _pair_cache
16
+ from scipy.stats._discrete_distns import _gen_harmonic_gt1
17
+
18
+
19
+ def norm_pdf(x, xp=None):
20
+ xp = array_namespace(x) if xp is None else xp
21
+ return 1/(2*xp.pi)**0.5 * xp.exp(-x**2/2)
22
+
23
+ def norm_logpdf(x, xp=None):
24
+ xp = array_namespace(x) if xp is None else xp
25
+ return -0.5*math.log(2*xp.pi) - x**2/2
26
+
27
+
28
+ def _vectorize(xp):
29
+ # xp-compatible version of np.vectorize
30
+ # assumes arguments are all arrays of the same shape
31
+ def decorator(f):
32
+ def wrapped(*arg_arrays):
33
+ shape = arg_arrays[0].shape
34
+ arg_arrays = [xp_ravel(arg_array) for arg_array in arg_arrays]
35
+ res = []
36
+ for i in range(math.prod(shape)):
37
+ arg_scalars = [arg_array[i] for arg_array in arg_arrays]
38
+ res.append(f(*arg_scalars))
39
+ return res
40
+
41
+ return wrapped
42
+
43
+ return decorator
44
+
45
+
46
+ @array_api_compatible
47
+ @pytest.mark.usefixtures("skip_xp_backends")
48
+ @pytest.mark.skip_xp_backends(
49
+ 'array_api_strict', reason='Currently uses fancy indexing assignment.'
50
+ )
51
+ @pytest.mark.skip_xp_backends(
52
+ 'jax.numpy', reason='JAX arrays do not support item assignment.'
53
+ )
54
+ class TestTanhSinh:
55
+
56
+ # Test problems from [1] Section 6
57
+ def f1(self, t):
58
+ return t * np.log(1 + t)
59
+
60
+ f1.ref = 0.25
61
+ f1.b = 1
62
+
63
+ def f2(self, t):
64
+ return t ** 2 * np.arctan(t)
65
+
66
+ f2.ref = (np.pi - 2 + 2 * np.log(2)) / 12
67
+ f2.b = 1
68
+
69
+ def f3(self, t):
70
+ return np.exp(t) * np.cos(t)
71
+
72
+ f3.ref = (np.exp(np.pi / 2) - 1) / 2
73
+ f3.b = np.pi / 2
74
+
75
+ def f4(self, t):
76
+ a = np.sqrt(2 + t ** 2)
77
+ return np.arctan(a) / ((1 + t ** 2) * a)
78
+
79
+ f4.ref = 5 * np.pi ** 2 / 96
80
+ f4.b = 1
81
+
82
+ def f5(self, t):
83
+ return np.sqrt(t) * np.log(t)
84
+
85
+ f5.ref = -4 / 9
86
+ f5.b = 1
87
+
88
+ def f6(self, t):
89
+ return np.sqrt(1 - t ** 2)
90
+
91
+ f6.ref = np.pi / 4
92
+ f6.b = 1
93
+
94
+ def f7(self, t):
95
+ return np.sqrt(t) / np.sqrt(1 - t ** 2)
96
+
97
+ f7.ref = 2 * np.sqrt(np.pi) * special.gamma(3 / 4) / special.gamma(1 / 4)
98
+ f7.b = 1
99
+
100
+ def f8(self, t):
101
+ return np.log(t) ** 2
102
+
103
+ f8.ref = 2
104
+ f8.b = 1
105
+
106
+ def f9(self, t):
107
+ return np.log(np.cos(t))
108
+
109
+ f9.ref = -np.pi * np.log(2) / 2
110
+ f9.b = np.pi / 2
111
+
112
+ def f10(self, t):
113
+ return np.sqrt(np.tan(t))
114
+
115
+ f10.ref = np.pi * np.sqrt(2) / 2
116
+ f10.b = np.pi / 2
117
+
118
+ def f11(self, t):
119
+ return 1 / (1 + t ** 2)
120
+
121
+ f11.ref = np.pi / 2
122
+ f11.b = np.inf
123
+
124
+ def f12(self, t):
125
+ return np.exp(-t) / np.sqrt(t)
126
+
127
+ f12.ref = np.sqrt(np.pi)
128
+ f12.b = np.inf
129
+
130
+ def f13(self, t):
131
+ return np.exp(-t ** 2 / 2)
132
+
133
+ f13.ref = np.sqrt(np.pi / 2)
134
+ f13.b = np.inf
135
+
136
+ def f14(self, t):
137
+ return np.exp(-t) * np.cos(t)
138
+
139
+ f14.ref = 0.5
140
+ f14.b = np.inf
141
+
142
+ def f15(self, t):
143
+ return np.sin(t) / t
144
+
145
+ f15.ref = np.pi / 2
146
+ f15.b = np.inf
147
+
148
+ def error(self, res, ref, log=False, xp=None):
149
+ xp = array_namespace(res, ref) if xp is None else xp
150
+ err = abs(res - ref)
151
+
152
+ if not log:
153
+ return err
154
+
155
+ with np.errstate(divide='ignore'):
156
+ return xp.log10(err)
157
+
158
+ def test_input_validation(self, xp):
159
+ f = self.f1
160
+
161
+ zero = xp.asarray(0)
162
+ f_b = xp.asarray(f.b)
163
+
164
+ message = '`f` must be callable.'
165
+ with pytest.raises(ValueError, match=message):
166
+ _tanhsinh(42, zero, f_b)
167
+
168
+ message = '...must be True or False.'
169
+ with pytest.raises(ValueError, match=message):
170
+ _tanhsinh(f, zero, f_b, log=2)
171
+
172
+ message = '...must be real numbers.'
173
+ with pytest.raises(ValueError, match=message):
174
+ _tanhsinh(f, xp.asarray(1+1j), f_b)
175
+ with pytest.raises(ValueError, match=message):
176
+ _tanhsinh(f, zero, f_b, atol='ekki')
177
+ with pytest.raises(ValueError, match=message):
178
+ _tanhsinh(f, zero, f_b, rtol=pytest)
179
+
180
+ message = '...must be non-negative and finite.'
181
+ with pytest.raises(ValueError, match=message):
182
+ _tanhsinh(f, zero, f_b, rtol=-1)
183
+ with pytest.raises(ValueError, match=message):
184
+ _tanhsinh(f, zero, f_b, atol=xp.inf)
185
+
186
+ message = '...may not be positive infinity.'
187
+ with pytest.raises(ValueError, match=message):
188
+ _tanhsinh(f, zero, f_b, rtol=xp.inf, log=True)
189
+ with pytest.raises(ValueError, match=message):
190
+ _tanhsinh(f, zero, f_b, atol=xp.inf, log=True)
191
+
192
+ message = '...must be integers.'
193
+ with pytest.raises(ValueError, match=message):
194
+ _tanhsinh(f, zero, f_b, maxlevel=object())
195
+ # with pytest.raises(ValueError, match=message): # unused for now
196
+ # _tanhsinh(f, zero, f_b, maxfun=1+1j)
197
+ with pytest.raises(ValueError, match=message):
198
+ _tanhsinh(f, zero, f_b, minlevel="migratory coconut")
199
+
200
+ message = '...must be non-negative.'
201
+ with pytest.raises(ValueError, match=message):
202
+ _tanhsinh(f, zero, f_b, maxlevel=-1)
203
+ # with pytest.raises(ValueError, match=message): # unused for now
204
+ # _tanhsinh(f, zero, f_b, maxfun=-1)
205
+ with pytest.raises(ValueError, match=message):
206
+ _tanhsinh(f, zero, f_b, minlevel=-1)
207
+
208
+ message = '...must be True or False.'
209
+ with pytest.raises(ValueError, match=message):
210
+ _tanhsinh(f, zero, f_b, preserve_shape=2)
211
+
212
+ message = '...must be callable.'
213
+ with pytest.raises(ValueError, match=message):
214
+ _tanhsinh(f, zero, f_b, callback='elderberry')
215
+
216
+ @pytest.mark.parametrize("limits, ref", [
217
+ [(0, math.inf), 0.5], # b infinite
218
+ [(-math.inf, 0), 0.5], # a infinite
219
+ [(-math.inf, math.inf), 1.], # a and b infinite
220
+ [(math.inf, -math.inf), -1.], # flipped limits
221
+ [(1, -1), stats.norm.cdf(-1.) - stats.norm.cdf(1.)], # flipped limits
222
+ ])
223
+ def test_integral_transforms(self, limits, ref, xp):
224
+ # Check that the integral transforms are behaving for both normal and
225
+ # log integration
226
+ limits = [xp.asarray(limit) for limit in limits]
227
+ dtype = xp.asarray(float(limits[0])).dtype
228
+ ref = xp.asarray(ref, dtype=dtype)
229
+
230
+ res = _tanhsinh(norm_pdf, *limits)
231
+ xp_assert_close(res.integral, ref)
232
+
233
+ logres = _tanhsinh(norm_logpdf, *limits, log=True)
234
+ xp_assert_close(xp.exp(logres.integral), ref, check_dtype=False)
235
+ # Transformation should not make the result complex unnecessarily
236
+ xp_test = array_namespace(*limits) # we need xp.isdtype
237
+ assert (xp_test.isdtype(logres.integral.dtype, "real floating") if ref > 0
238
+ else xp_test.isdtype(logres.integral.dtype, "complex floating"))
239
+
240
+ xp_assert_close(xp.exp(logres.error), res.error, atol=1e-16, check_dtype=False)
241
+
242
+ # 15 skipped intentionally; it's very difficult numerically
243
+ @pytest.mark.skip_xp_backends(np_only=True,
244
+ reason='Cumbersome to convert everything.')
245
+ @pytest.mark.parametrize('f_number', range(1, 15))
246
+ def test_basic(self, f_number, xp):
247
+ f = getattr(self, f"f{f_number}")
248
+ rtol = 2e-8
249
+ res = _tanhsinh(f, 0, f.b, rtol=rtol)
250
+ assert_allclose(res.integral, f.ref, rtol=rtol)
251
+ if f_number not in {14}: # mildly underestimates error here
252
+ true_error = abs(self.error(res.integral, f.ref)/res.integral)
253
+ assert true_error < res.error
254
+
255
+ if f_number in {7, 10, 12}: # succeeds, but doesn't know it
256
+ return
257
+
258
+ assert res.success
259
+ assert res.status == 0
260
+
261
+ @pytest.mark.skip_xp_backends(np_only=True,
262
+ reason="Distributions aren't xp-compatible.")
263
+ @pytest.mark.parametrize('ref', (0.5, [0.4, 0.6]))
264
+ @pytest.mark.parametrize('case', stats._distr_params.distcont)
265
+ def test_accuracy(self, ref, case, xp):
266
+ distname, params = case
267
+ if distname in {'dgamma', 'dweibull', 'laplace', 'kstwo'}:
268
+ # should split up interval at first-derivative discontinuity
269
+ pytest.skip('tanh-sinh is not great for non-smooth integrands')
270
+ if (distname in {'studentized_range', 'levy_stable'}
271
+ and not int(os.getenv('SCIPY_XSLOW', 0))):
272
+ pytest.skip('This case passes, but it is too slow.')
273
+ dist = getattr(stats, distname)(*params)
274
+ x = dist.interval(ref)
275
+ res = _tanhsinh(dist.pdf, *x)
276
+ assert_allclose(res.integral, ref)
277
+
278
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
279
+ def test_vectorization(self, shape, xp):
280
+ # Test for correct functionality, output shapes, and dtypes for various
281
+ # input shapes.
282
+ rng = np.random.default_rng(82456839535679456794)
283
+ a = xp.asarray(rng.random(shape))
284
+ b = xp.asarray(rng.random(shape))
285
+ p = xp.asarray(rng.random(shape))
286
+ n = math.prod(shape)
287
+
288
+ def f(x, p):
289
+ f.ncall += 1
290
+ f.feval += 1 if (xp_size(x) == n or x.ndim <= 1) else x.shape[-1]
291
+ return x**p
292
+ f.ncall = 0
293
+ f.feval = 0
294
+
295
+ @_vectorize(xp)
296
+ def _tanhsinh_single(a, b, p):
297
+ return _tanhsinh(lambda x: x**p, a, b)
298
+
299
+ res = _tanhsinh(f, a, b, args=(p,))
300
+ refs = _tanhsinh_single(a, b, p)
301
+
302
+ xp_test = array_namespace(a) # need xp.stack, isdtype
303
+ attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
304
+ for attr in attrs:
305
+ ref_attr = xp_test.stack([getattr(ref, attr) for ref in refs])
306
+ res_attr = xp_ravel(getattr(res, attr))
307
+ xp_assert_close(res_attr, ref_attr, rtol=1e-15)
308
+ assert getattr(res, attr).shape == shape
309
+
310
+ assert xp_test.isdtype(res.success.dtype, 'bool')
311
+ assert xp_test.isdtype(res.status.dtype, 'integral')
312
+ assert xp_test.isdtype(res.nfev.dtype, 'integral')
313
+ assert xp_test.isdtype(res.maxlevel.dtype, 'integral')
314
+ assert xp.max(res.nfev) == f.feval
315
+ # maxlevel = 2 -> 3 function calls (2 initialization, 1 work)
316
+ assert xp.max(res.maxlevel) >= 2
317
+ assert xp.max(res.maxlevel) == f.ncall
318
+
319
+ def test_flags(self, xp):
320
+ # Test cases that should produce different status flags; show that all
321
+ # can be produced simultaneously.
322
+ def f(xs, js):
323
+ f.nit += 1
324
+ funcs = [lambda x: xp.exp(-x**2), # converges
325
+ lambda x: xp.exp(x), # reaches maxiter due to order=2
326
+ lambda x: xp.full_like(x, xp.nan)] # stops due to NaN
327
+ res = []
328
+ for i in range(xp_size(js)):
329
+ x = xs[i, ...]
330
+ j = int(xp_ravel(js)[i])
331
+ res.append(funcs[j](x))
332
+ return xp.stack(res)
333
+ f.nit = 0
334
+
335
+ args = (xp.arange(3, dtype=xp.int64),)
336
+ a = xp.asarray([xp.inf]*3)
337
+ b = xp.asarray([-xp.inf] * 3)
338
+ res = _tanhsinh(f, a, b, maxlevel=5, args=args)
339
+ ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
340
+ xp_assert_equal(res.status, ref_flags)
341
+
342
+ def test_flags_preserve_shape(self, xp):
343
+ # Same test as above but using `preserve_shape` option to simplify.
344
+ def f(x):
345
+ res = [xp.exp(-x[0]**2), # converges
346
+ xp.exp(x[1]), # reaches maxiter due to order=2
347
+ xp.full_like(x[2], xp.nan)] # stops due to NaN
348
+ return xp.stack(res)
349
+
350
+ a = xp.asarray([xp.inf] * 3)
351
+ b = xp.asarray([-xp.inf] * 3)
352
+ res = _tanhsinh(f, a, b, maxlevel=5, preserve_shape=True)
353
+ ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
354
+ xp_assert_equal(res.status, ref_flags)
355
+
356
+ def test_preserve_shape(self, xp):
357
+ # Test `preserve_shape` option
358
+ def f(x, xp):
359
+ return xp.stack([xp.stack([x, xp.sin(10 * x)]),
360
+ xp.stack([xp.cos(30 * x), x * xp.sin(100 * x)])])
361
+
362
+ ref = quad_vec(lambda x: f(x, np), 0, 1)
363
+ res = _tanhsinh(lambda x: f(x, xp), xp.asarray(0), xp.asarray(1),
364
+ preserve_shape=True)
365
+ dtype = xp.asarray(0.).dtype
366
+ xp_assert_close(res.integral, xp.asarray(ref[0], dtype=dtype))
367
+
368
+ def test_convergence(self, xp):
369
+ # demonstrate that number of accurate digits doubles each iteration
370
+ dtype = xp.float64 # this only works with good precision
371
+ def f(t):
372
+ return t * xp.log(1 + t)
373
+ ref = xp.asarray(0.25, dtype=dtype)
374
+ a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype)
375
+
376
+ last_logerr = 0
377
+ for i in range(4):
378
+ res = _tanhsinh(f, a, b, minlevel=0, maxlevel=i)
379
+ logerr = self.error(res.integral, ref, log=True, xp=xp)
380
+ assert (logerr < last_logerr * 2 or logerr < -15.5)
381
+ last_logerr = logerr
382
+
383
+ def test_options_and_result_attributes(self, xp):
384
+ # demonstrate that options are behaving as advertised and status
385
+ # messages are as intended
386
+ xp_test = array_namespace(xp.asarray(1.)) # need xp.atan
387
+
388
+ def f(x):
389
+ f.calls += 1
390
+ f.feval += xp_size(xp.asarray(x))
391
+ return x**2 * xp_test.atan(x)
392
+
393
+ f.ref = xp.asarray((math.pi - 2 + 2 * math.log(2)) / 12, dtype=xp.float64)
394
+
395
+ default_rtol = 1e-12
396
+ default_atol = f.ref * default_rtol # effective default absolute tol
397
+
398
+ # Keep things simpler by leaving tolerances fixed rather than
399
+ # having to make them dtype-dependent
400
+ a = xp.asarray(0., dtype=xp.float64)
401
+ b = xp.asarray(1., dtype=xp.float64)
402
+
403
+ # Test default options
404
+ f.feval, f.calls = 0, 0
405
+ ref = _tanhsinh(f, a, b)
406
+ assert self.error(ref.integral, f.ref) < ref.error < default_atol
407
+ assert ref.nfev == f.feval
408
+ ref.calls = f.calls # reference number of function calls
409
+ assert ref.success
410
+ assert ref.status == 0
411
+
412
+ # Test `maxlevel` equal to required max level
413
+ # We should get all the same results
414
+ f.feval, f.calls = 0, 0
415
+ maxlevel = int(ref.maxlevel)
416
+ res = _tanhsinh(f, a, b, maxlevel=maxlevel)
417
+ res.calls = f.calls
418
+ assert res == ref
419
+
420
+ # Now reduce the maximum level. We won't meet tolerances.
421
+ f.feval, f.calls = 0, 0
422
+ maxlevel -= 1
423
+ assert maxlevel >= 2 # can't compare errors otherwise
424
+ res = _tanhsinh(f, a, b, maxlevel=maxlevel)
425
+ assert self.error(res.integral, f.ref) < res.error > default_atol
426
+ assert res.nfev == f.feval < ref.nfev
427
+ assert f.calls == ref.calls - 1
428
+ assert not res.success
429
+ assert res.status == eim._ECONVERR
430
+
431
+ # `maxfun` is currently not enforced
432
+
433
+ # # Test `maxfun` equal to required number of function evaluations
434
+ # # We should get all the same results
435
+ # f.feval, f.calls = 0, 0
436
+ # maxfun = ref.nfev
437
+ # res = _tanhsinh(f, 0, f.b, maxfun = maxfun)
438
+ # assert res == ref
439
+ #
440
+ # # Now reduce `maxfun`. We won't meet tolerances.
441
+ # f.feval, f.calls = 0, 0
442
+ # maxfun -= 1
443
+ # res = _tanhsinh(f, 0, f.b, maxfun=maxfun)
444
+ # assert self.error(res.integral, f.ref) < res.error > default_atol
445
+ # assert res.nfev == f.feval < ref.nfev
446
+ # assert f.calls == ref.calls - 1
447
+ # assert not res.success
448
+ # assert res.status == 2
449
+
450
+ # Take this result to be the new reference
451
+ ref = res
452
+ ref.calls = f.calls
453
+
454
+ # Test `atol`
455
+ f.feval, f.calls = 0, 0
456
+ # With this tolerance, we should get the exact same result as ref
457
+ atol = np.nextafter(float(ref.error), np.inf)
458
+ res = _tanhsinh(f, a, b, rtol=0, atol=atol)
459
+ assert res.integral == ref.integral
460
+ assert res.error == ref.error
461
+ assert res.nfev == f.feval == ref.nfev
462
+ assert f.calls == ref.calls
463
+ # Except the result is considered to be successful
464
+ assert res.success
465
+ assert res.status == 0
466
+
467
+ f.feval, f.calls = 0, 0
468
+ # With a tighter tolerance, we should get a more accurate result
469
+ atol = np.nextafter(float(ref.error), -np.inf)
470
+ res = _tanhsinh(f, a, b, rtol=0, atol=atol)
471
+ assert self.error(res.integral, f.ref) < res.error < atol
472
+ assert res.nfev == f.feval > ref.nfev
473
+ assert f.calls > ref.calls
474
+ assert res.success
475
+ assert res.status == 0
476
+
477
+ # Test `rtol`
478
+ f.feval, f.calls = 0, 0
479
+ # With this tolerance, we should get the exact same result as ref
480
+ rtol = np.nextafter(float(ref.error/ref.integral), np.inf)
481
+ res = _tanhsinh(f, a, b, rtol=rtol)
482
+ assert res.integral == ref.integral
483
+ assert res.error == ref.error
484
+ assert res.nfev == f.feval == ref.nfev
485
+ assert f.calls == ref.calls
486
+ # Except the result is considered to be successful
487
+ assert res.success
488
+ assert res.status == 0
489
+
490
+ f.feval, f.calls = 0, 0
491
+ # With a tighter tolerance, we should get a more accurate result
492
+ rtol = np.nextafter(float(ref.error/ref.integral), -np.inf)
493
+ res = _tanhsinh(f, a, b, rtol=rtol)
494
+ assert self.error(res.integral, f.ref)/f.ref < res.error/res.integral < rtol
495
+ assert res.nfev == f.feval > ref.nfev
496
+ assert f.calls > ref.calls
497
+ assert res.success
498
+ assert res.status == 0
499
+
500
+ @pytest.mark.skip_xp_backends('torch', reason=
501
+ 'https://github.com/scipy/scipy/pull/21149#issuecomment-2330477359',
502
+ )
503
+ @pytest.mark.parametrize('rtol', [1e-4, 1e-14])
504
+ def test_log(self, rtol, xp):
505
+ # Test equivalence of log-integration and regular integration
506
+ test_tols = dict(atol=1e-18, rtol=1e-15)
507
+
508
+ # Positive integrand (real log-integrand)
509
+ a = xp.asarray(-1., dtype=xp.float64)
510
+ b = xp.asarray(2., dtype=xp.float64)
511
+ res = _tanhsinh(norm_logpdf, a, b, log=True, rtol=math.log(rtol))
512
+ ref = _tanhsinh(norm_pdf, a, b, rtol=rtol)
513
+ xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols)
514
+ xp_assert_close(xp.exp(res.error), ref.error, **test_tols)
515
+ assert res.nfev == ref.nfev
516
+
517
+ # Real integrand (complex log-integrand)
518
+ def f(x):
519
+ return -norm_logpdf(x)*norm_pdf(x)
520
+
521
+ def logf(x):
522
+ return xp.log(norm_logpdf(x) + 0j) + norm_logpdf(x) + xp.pi * 1j
523
+
524
+ a = xp.asarray(-xp.inf, dtype=xp.float64)
525
+ b = xp.asarray(xp.inf, dtype=xp.float64)
526
+ res = _tanhsinh(logf, a, b, log=True)
527
+ ref = _tanhsinh(f, a, b)
528
+ # In gh-19173, we saw `invalid` warnings on one CI platform.
529
+ # Silencing `all` because I can't reproduce locally and don't want
530
+ # to risk the need to run CI again.
531
+ with np.errstate(all='ignore'):
532
+ xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols,
533
+ check_dtype=False)
534
+ xp_assert_close(xp.exp(res.error), ref.error, **test_tols,
535
+ check_dtype=False)
536
+ assert res.nfev == ref.nfev
537
+
538
+ def test_complex(self, xp):
539
+ # Test integration of complex integrand
540
+ # Finite limits
541
+ def f(x):
542
+ return xp.exp(1j * x)
543
+
544
+ a, b = xp.asarray(0.), xp.asarray(xp.pi/4)
545
+ res = _tanhsinh(f, a, b)
546
+ ref = math.sqrt(2)/2 + (1-math.sqrt(2)/2)*1j
547
+ xp_assert_close(res.integral, xp.asarray(ref))
548
+
549
+ # Infinite limits
550
+ def f(x):
551
+ return norm_pdf(x) + 1j/2*norm_pdf(x/2)
552
+
553
+ a, b = xp.asarray(xp.inf), xp.asarray(-xp.inf)
554
+ res = _tanhsinh(f, a, b)
555
+ xp_assert_close(res.integral, xp.asarray(-(1+1j)))
556
+
557
+ @pytest.mark.parametrize("maxlevel", range(4))
558
+ def test_minlevel(self, maxlevel, xp):
559
+ # Verify that minlevel does not change the values at which the
560
+ # integrand is evaluated or the integral/error estimates, only the
561
+ # number of function calls
562
+
563
+ # need `xp.concat`, `xp.atan`, and `xp.sort`
564
+ xp_test = array_namespace(xp.asarray(1.))
565
+
566
+ def f(x):
567
+ f.calls += 1
568
+ f.feval += xp_size(xp.asarray(x))
569
+ f.x = xp_test.concat((f.x, xp_ravel(x)))
570
+ return x**2 * xp_test.atan(x)
571
+
572
+ f.feval, f.calls, f.x = 0, 0, xp.asarray([])
573
+
574
+ a = xp.asarray(0, dtype=xp.float64)
575
+ b = xp.asarray(1, dtype=xp.float64)
576
+ ref = _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel)
577
+ ref_x = xp_test.sort(f.x)
578
+
579
+ for minlevel in range(0, maxlevel + 1):
580
+ f.feval, f.calls, f.x = 0, 0, xp.asarray([])
581
+ options = dict(minlevel=minlevel, maxlevel=maxlevel)
582
+ res = _tanhsinh(f, a, b, **options)
583
+ # Should be very close; all that has changed is the order of values
584
+ xp_assert_close(res.integral, ref.integral, rtol=4e-16)
585
+ # Difference in absolute errors << magnitude of integral
586
+ xp_assert_close(res.error, ref.error, atol=4e-16 * ref.integral)
587
+ assert res.nfev == f.feval == f.x.shape[0]
588
+ assert f.calls == maxlevel - minlevel + 1 + 1 # 1 validation call
589
+ assert res.status == ref.status
590
+ xp_assert_equal(ref_x, xp_test.sort(f.x))
591
+
592
+ def test_improper_integrals(self, xp):
593
+ # Test handling of infinite limits of integration (mixed with finite limits)
594
+ def f(x):
595
+ x[xp.isinf(x)] = xp.nan
596
+ return xp.exp(-x**2)
597
+ a = xp.asarray([-xp.inf, 0, -xp.inf, xp.inf, -20, -xp.inf, -20])
598
+ b = xp.asarray([xp.inf, xp.inf, 0, -xp.inf, 20, 20, xp.inf])
599
+ ref = math.sqrt(math.pi)
600
+ ref = xp.asarray([ref, ref/2, ref/2, -ref, ref, ref, ref])
601
+ res = _tanhsinh(f, a, b)
602
+ xp_assert_close(res.integral, ref)
603
+
604
+ @pytest.mark.parametrize("limits", ((0, 3), ([-math.inf, 0], [3, 3])))
605
+ @pytest.mark.parametrize("dtype", ('float32', 'float64'))
606
+ def test_dtype(self, limits, dtype, xp):
607
+ # Test that dtypes are preserved
608
+ dtype = getattr(xp, dtype)
609
+ a, b = xp.asarray(limits, dtype=dtype)
610
+
611
+ def f(x):
612
+ assert x.dtype == dtype
613
+ return xp.exp(x)
614
+
615
+ rtol = 1e-12 if dtype == xp.float64 else 1e-5
616
+ res = _tanhsinh(f, a, b, rtol=rtol)
617
+ assert res.integral.dtype == dtype
618
+ assert res.error.dtype == dtype
619
+ assert xp.all(res.success)
620
+ xp_assert_close(res.integral, xp.exp(b)-xp.exp(a))
621
+
622
+ def test_maxiter_callback(self, xp):
623
+ # Test behavior of `maxiter` parameter and `callback` interface
624
+ a, b = xp.asarray(-xp.inf), xp.asarray(xp.inf)
625
+ def f(x):
626
+ return xp.exp(-x*x)
627
+
628
+ minlevel, maxlevel = 0, 2
629
+ maxiter = maxlevel - minlevel + 1
630
+ kwargs = dict(minlevel=minlevel, maxlevel=maxlevel, rtol=1e-15)
631
+ res = _tanhsinh(f, a, b, **kwargs)
632
+ assert not res.success
633
+ assert res.maxlevel == maxlevel
634
+
635
+ def callback(res):
636
+ callback.iter += 1
637
+ callback.res = res
638
+ assert hasattr(res, 'integral')
639
+ assert res.status == 1
640
+ if callback.iter == maxiter:
641
+ raise StopIteration
642
+ callback.iter = -1 # callback called once before first iteration
643
+ callback.res = None
644
+
645
+ del kwargs['maxlevel']
646
+ res2 = _tanhsinh(f, a, b, **kwargs, callback=callback)
647
+ # terminating with callback is identical to terminating due to maxiter
648
+ # (except for `status`)
649
+ for key in res.keys():
650
+ if key == 'status':
651
+ assert res[key] == -2
652
+ assert res2[key] == -4
653
+ else:
654
+ assert res2[key] == callback.res[key] == res[key]
655
+
656
+ def test_jumpstart(self, xp):
657
+ # The intermediate results at each level i should be the same as the
658
+ # final results when jumpstarting at level i; i.e. minlevel=maxlevel=i
659
+ a = xp.asarray(-xp.inf, dtype=xp.float64)
660
+ b = xp.asarray(xp.inf, dtype=xp.float64)
661
+
662
+ def f(x):
663
+ return xp.exp(-x*x)
664
+
665
+ def callback(res):
666
+ callback.integrals.append(xp_copy(res.integral)[()])
667
+ callback.errors.append(xp_copy(res.error)[()])
668
+ callback.integrals = []
669
+ callback.errors = []
670
+
671
+ maxlevel = 4
672
+ _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel, callback=callback)
673
+
674
+ for i in range(maxlevel + 1):
675
+ res = _tanhsinh(f, a, b, minlevel=i, maxlevel=i)
676
+ xp_assert_close(callback.integrals[1+i], res.integral, rtol=1e-15)
677
+ xp_assert_close(callback.errors[1+i], res.error, rtol=1e-15, atol=1e-16)
678
+
679
+ def test_special_cases(self, xp):
680
+ # Test edge cases and other special cases
681
+ a, b = xp.asarray(0), xp.asarray(1)
682
+ xp_test = array_namespace(a, b) # need `xp.isdtype`
683
+
684
+ def f(x):
685
+ assert xp_test.isdtype(x.dtype, "real floating")
686
+ return x
687
+
688
+ res = _tanhsinh(f, a, b)
689
+ assert res.success
690
+ xp_assert_close(res.integral, xp.asarray(0.5))
691
+
692
+ # Test levels 0 and 1; error is NaN
693
+ res = _tanhsinh(f, a, b, maxlevel=0)
694
+ assert res.integral > 0
695
+ xp_assert_equal(res.error, xp.asarray(xp.nan))
696
+ res = _tanhsinh(f, a, b, maxlevel=1)
697
+ assert res.integral > 0
698
+ xp_assert_equal(res.error, xp.asarray(xp.nan))
699
+
700
+ # Test equal left and right integration limits
701
+ res = _tanhsinh(f, b, b)
702
+ assert res.success
703
+ assert res.maxlevel == -1
704
+ xp_assert_close(res.integral, xp.asarray(0.))
705
+
706
+ # Test scalar `args` (not in tuple)
707
+ def f(x, c):
708
+ return x**c
709
+
710
+ res = _tanhsinh(f, a, b, args=29)
711
+ xp_assert_close(res.integral, xp.asarray(1/30))
712
+
713
+ # Test NaNs
714
+ a = xp.asarray([xp.nan, 0, 0, 0])
715
+ b = xp.asarray([1, xp.nan, 1, 1])
716
+ c = xp.asarray([1, 1, xp.nan, 1])
717
+ res = _tanhsinh(f, a, b, args=(c,))
718
+ xp_assert_close(res.integral, xp.asarray([xp.nan, xp.nan, xp.nan, 0.5]))
719
+ xp_assert_equal(res.error[:3], xp.full((3,), xp.nan))
720
+ xp_assert_equal(res.status, xp.asarray([-3, -3, -3, 0], dtype=xp.int32))
721
+ xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
722
+ xp_assert_equal(res.nfev[:3], xp.full((3,), 1, dtype=xp.int32))
723
+
724
+ # Test complex integral followed by real integral
725
+ # Previously, h0 was of the result dtype. If the `dtype` were complex,
726
+ # this could lead to complex cached abscissae/weights. If these get
727
+ # cast to real dtype for a subsequent real integral, we would get a
728
+ # ComplexWarning. Check that this is avoided.
729
+ _pair_cache.xjc = xp.empty(0)
730
+ _pair_cache.wj = xp.empty(0)
731
+ _pair_cache.indices = [0]
732
+ _pair_cache.h0 = None
733
+ a, b = xp.asarray(0), xp.asarray(1)
734
+ res = _tanhsinh(lambda x: xp.asarray(x*1j), a, b)
735
+ xp_assert_close(res.integral, xp.asarray(0.5*1j))
736
+ res = _tanhsinh(lambda x: x, a, b)
737
+ xp_assert_close(res.integral, xp.asarray(0.5))
738
+
739
+ # Test zero-size
740
+ shape = (0, 3)
741
+ res = _tanhsinh(lambda x: x, xp.asarray(0), xp.zeros(shape))
742
+ attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
743
+ for attr in attrs:
744
+ assert res[attr].shape == shape
745
+
746
+ @pytest.mark.skip_xp_backends(np_only=True)
747
+ def test_compress_nodes_weights_gh21496(self, xp):
748
+ # See discussion in:
749
+ # https://github.com/scipy/scipy/pull/21496#discussion_r1878681049
750
+ # This would cause "ValueError: attempt to get argmax of an empty sequence"
751
+ # Check that this has been resolved.
752
+ x = np.full(65, 3)
753
+ x[-1] = 1000
754
+ _tanhsinh(np.sin, 1, x)
755
+
756
+
757
+ @array_api_compatible
758
+ @pytest.mark.usefixtures("skip_xp_backends")
759
+ @pytest.mark.skip_xp_backends('array_api_strict', reason='No fancy indexing.')
760
+ @pytest.mark.skip_xp_backends('jax.numpy', reason='No mutation.')
761
+ class TestNSum:
762
+ rng = np.random.default_rng(5895448232066142650)
763
+ p = rng.uniform(1, 10, size=10).tolist()
764
+
765
+ def f1(self, k):
766
+ # Integers are never passed to `f1`; if they were, we'd get
767
+ # integer to negative integer power error
768
+ return k**(-2)
769
+
770
+ f1.ref = np.pi**2/6
771
+ f1.a = 1
772
+ f1.b = np.inf
773
+ f1.args = tuple()
774
+
775
+ def f2(self, k, p):
776
+ return 1 / k**p
777
+
778
+ f2.ref = special.zeta(p, 1)
779
+ f2.a = 1.
780
+ f2.b = np.inf
781
+ f2.args = (p,)
782
+
783
+ def f3(self, k, p):
784
+ return 1 / k**p
785
+
786
+ f3.a = 1
787
+ f3.b = rng.integers(5, 15, size=(3, 1))
788
+ f3.ref = _gen_harmonic_gt1(f3.b, p)
789
+ f3.args = (p,)
790
+
791
+ def test_input_validation(self, xp):
792
+ f = self.f1
793
+ a, b = xp.asarray(f.a), xp.asarray(f.b)
794
+
795
+ message = '`f` must be callable.'
796
+ with pytest.raises(ValueError, match=message):
797
+ nsum(42, a, b)
798
+
799
+ message = '...must be True or False.'
800
+ with pytest.raises(ValueError, match=message):
801
+ nsum(f, a, b, log=2)
802
+
803
+ message = '...must be real numbers.'
804
+ with pytest.raises(ValueError, match=message):
805
+ nsum(f, xp.asarray(1+1j), b)
806
+ with pytest.raises(ValueError, match=message):
807
+ nsum(f, a, xp.asarray(1+1j))
808
+ with pytest.raises(ValueError, match=message):
809
+ nsum(f, a, b, step=xp.asarray(1+1j))
810
+ with pytest.raises(ValueError, match=message):
811
+ nsum(f, a, b, tolerances=dict(atol='ekki'))
812
+ with pytest.raises(ValueError, match=message):
813
+ nsum(f, a, b, tolerances=dict(rtol=pytest))
814
+
815
+ with np.errstate(all='ignore'):
816
+ res = nsum(f, xp.asarray([np.nan, np.inf]), xp.asarray(1.))
817
+ assert xp.all((res.status == -1) & xp.isnan(res.sum)
818
+ & xp.isnan(res.error) & ~res.success & res.nfev == 1)
819
+ res = nsum(f, xp.asarray(10.), xp.asarray([np.nan, 1]))
820
+ assert xp.all((res.status == -1) & xp.isnan(res.sum)
821
+ & xp.isnan(res.error) & ~res.success & res.nfev == 1)
822
+ res = nsum(f, xp.asarray(1.), xp.asarray(10.),
823
+ step=xp.asarray([xp.nan, -xp.inf, xp.inf, -1, 0]))
824
+ assert xp.all((res.status == -1) & xp.isnan(res.sum)
825
+ & xp.isnan(res.error) & ~res.success & res.nfev == 1)
826
+
827
+ message = '...must be non-negative and finite.'
828
+ with pytest.raises(ValueError, match=message):
829
+ nsum(f, a, b, tolerances=dict(rtol=-1))
830
+ with pytest.raises(ValueError, match=message):
831
+ nsum(f, a, b, tolerances=dict(atol=np.inf))
832
+
833
+ message = '...may not be positive infinity.'
834
+ with pytest.raises(ValueError, match=message):
835
+ nsum(f, a, b, tolerances=dict(rtol=np.inf), log=True)
836
+ with pytest.raises(ValueError, match=message):
837
+ nsum(f, a, b, tolerances=dict(atol=np.inf), log=True)
838
+
839
+ message = '...must be a non-negative integer.'
840
+ with pytest.raises(ValueError, match=message):
841
+ nsum(f, a, b, maxterms=3.5)
842
+ with pytest.raises(ValueError, match=message):
843
+ nsum(f, a, b, maxterms=-2)
844
+
845
+ @pytest.mark.parametrize('f_number', range(1, 4))
846
+ def test_basic(self, f_number, xp):
847
+ dtype = xp.asarray(1.).dtype
848
+ f = getattr(self, f"f{f_number}")
849
+ a, b = xp.asarray(f.a), xp.asarray(f.b),
850
+ args = tuple(xp.asarray(arg) for arg in f.args)
851
+ ref = xp.asarray(f.ref, dtype=dtype)
852
+ res = nsum(f, a, b, args=args)
853
+ xp_assert_close(res.sum, ref)
854
+ xp_assert_equal(res.status, xp.zeros(ref.shape, dtype=xp.int32))
855
+ xp_test = array_namespace(a) # CuPy doesn't have `bool`
856
+ xp_assert_equal(res.success, xp.ones(ref.shape, dtype=xp_test.bool))
857
+
858
+ with np.errstate(divide='ignore'):
859
+ logres = nsum(lambda *args: xp.log(f(*args)),
860
+ a, b, log=True, args=args)
861
+ xp_assert_close(xp.exp(logres.sum), res.sum)
862
+ xp_assert_close(xp.exp(logres.error), res.error, atol=1e-15)
863
+ xp_assert_equal(logres.status, res.status)
864
+ xp_assert_equal(logres.success, res.success)
865
+
866
+ @pytest.mark.parametrize('maxterms', [0, 1, 10, 20, 100])
867
+ def test_integral(self, maxterms, xp):
868
+ # test precise behavior of integral approximation
869
+ f = self.f1
870
+
871
+ def logf(x):
872
+ return -2*xp.log(x)
873
+
874
+ def F(x):
875
+ return -1 / x
876
+
877
+ a = xp.asarray([1, 5], dtype=xp.float64)[:, xp.newaxis]
878
+ b = xp.asarray([20, 100, xp.inf], dtype=xp.float64)[:, xp.newaxis, xp.newaxis]
879
+ step = xp.asarray([0.5, 1, 2], dtype=xp.float64).reshape((-1, 1, 1, 1))
880
+ nsteps = xp.floor((b - a)/step)
881
+ b_original = b
882
+ b = a + nsteps*step
883
+
884
+ k = a + maxterms*step
885
+ # partial sum
886
+ direct = xp.sum(f(a + xp.arange(maxterms)*step), axis=-1, keepdims=True)
887
+ integral = (F(b) - F(k))/step # integral approximation of remainder
888
+ low = direct + integral + f(b) # theoretical lower bound
889
+ high = direct + integral + f(k) # theoretical upper bound
890
+ ref_sum = (low + high)/2 # nsum uses average of the two
891
+ ref_err = (high - low)/2 # error (assuming perfect quadrature)
892
+
893
+ # correct reference values where number of terms < maxterms
894
+ xp_test = array_namespace(a) # torch needs broadcast_arrays
895
+ a, b, step = xp_test.broadcast_arrays(a, b, step)
896
+ for i in np.ndindex(a.shape):
897
+ ai, bi, stepi = float(a[i]), float(b[i]), float(step[i])
898
+ if (bi - ai)/stepi + 1 <= maxterms:
899
+ direct = xp.sum(f(xp.arange(ai, bi+stepi, stepi, dtype=xp.float64)))
900
+ ref_sum[i] = direct
901
+ ref_err[i] = direct * xp.finfo(direct.dtype).eps
902
+
903
+ rtol = 1e-12
904
+ res = nsum(f, a, b_original, step=step, maxterms=maxterms,
905
+ tolerances=dict(rtol=rtol))
906
+ xp_assert_close(res.sum, ref_sum, rtol=10*rtol)
907
+ xp_assert_close(res.error, ref_err, rtol=100*rtol)
908
+
909
+ i = ((b_original - a)/step + 1 <= maxterms)
910
+ xp_assert_close(res.sum[i], ref_sum[i], rtol=1e-15)
911
+ xp_assert_close(res.error[i], ref_err[i], rtol=1e-15)
912
+
913
+ logres = nsum(logf, a, b_original, step=step, log=True,
914
+ tolerances=dict(rtol=math.log(rtol)), maxterms=maxterms)
915
+ xp_assert_close(xp.exp(logres.sum), res.sum)
916
+ xp_assert_close(xp.exp(logres.error), res.error)
917
+
918
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
919
+ def test_vectorization(self, shape, xp):
920
+ # Test for correct functionality, output shapes, and dtypes for various
921
+ # input shapes.
922
+ rng = np.random.default_rng(82456839535679456794)
923
+ a = rng.integers(1, 10, size=shape)
924
+ # when the sum can be computed directly or `maxterms` is large enough
925
+ # to meet `atol`, there are slight differences (for good reason)
926
+ # between vectorized call and looping.
927
+ b = np.inf
928
+ p = rng.random(shape) + 1
929
+ n = math.prod(shape)
930
+
931
+ def f(x, p):
932
+ f.feval += 1 if (x.size == n or x.ndim <= 1) else x.shape[-1]
933
+ return 1 / x ** p
934
+
935
+ f.feval = 0
936
+
937
+ @np.vectorize
938
+ def nsum_single(a, b, p, maxterms):
939
+ return nsum(lambda x: 1 / x**p, a, b, maxterms=maxterms)
940
+
941
+ res = nsum(f, xp.asarray(a), xp.asarray(b), maxterms=1000,
942
+ args=(xp.asarray(p),))
943
+ refs = nsum_single(a, b, p, maxterms=1000).ravel()
944
+
945
+ attrs = ['sum', 'error', 'success', 'status', 'nfev']
946
+ for attr in attrs:
947
+ ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
948
+ res_attr = getattr(res, attr)
949
+ xp_assert_close(xp_ravel(res_attr), xp.asarray(ref_attr), rtol=1e-15)
950
+ assert res_attr.shape == shape
951
+
952
+ xp_test = array_namespace(xp.asarray(1.))
953
+ assert xp_test.isdtype(res.success.dtype, 'bool')
954
+ assert xp_test.isdtype(res.status.dtype, 'integral')
955
+ assert xp_test.isdtype(res.nfev.dtype, 'integral')
956
+ if is_numpy(xp): # other libraries might have different number
957
+ assert int(xp.max(res.nfev)) == f.feval
958
+
959
+ def test_status(self, xp):
960
+ f = self.f2
961
+
962
+ p = [2, 2, 0.9, 1.1, 2, 2]
963
+ a = xp.asarray([0, 0, 1, 1, 1, np.nan], dtype=xp.float64)
964
+ b = xp.asarray([10, np.inf, np.inf, np.inf, np.inf, np.inf], dtype=xp.float64)
965
+ ref = special.zeta(p, 1)
966
+ p = xp.asarray(p, dtype=xp.float64)
967
+
968
+ with np.errstate(divide='ignore'): # intentionally dividing by zero
969
+ res = nsum(f, a, b, args=(p,))
970
+
971
+ ref_success = xp.asarray([False, False, False, False, True, False])
972
+ ref_status = xp.asarray([-3, -3, -2, -4, 0, -1], dtype=xp.int32)
973
+ xp_assert_equal(res.success, ref_success)
974
+ xp_assert_equal(res.status, ref_status)
975
+ xp_assert_close(res.sum[res.success], xp.asarray(ref)[res.success])
976
+
977
+ def test_nfev(self, xp):
978
+ def f(x):
979
+ f.nfev += xp_size(x)
980
+ return 1 / x**2
981
+
982
+ f.nfev = 0
983
+ res = nsum(f, xp.asarray(1), xp.asarray(10))
984
+ assert res.nfev == f.nfev
985
+
986
+ f.nfev = 0
987
+ res = nsum(f, xp.asarray(1), xp.asarray(xp.inf), tolerances=dict(atol=1e-6))
988
+ assert res.nfev == f.nfev
989
+
990
+ def test_inclusive(self, xp):
991
+ # There was an edge case off-by one bug when `_direct` was called with
992
+ # `inclusive=True`. Check that this is resolved.
993
+ a = xp.asarray([1, 4])
994
+ b = xp.asarray(xp.inf)
995
+ res = nsum(lambda k: 1 / k ** 2, a, b,
996
+ maxterms=500, tolerances=dict(atol=0.1))
997
+ ref = nsum(lambda k: 1 / k ** 2, a, b)
998
+ assert xp.all(res.sum > (ref.sum - res.error))
999
+ assert xp.all(res.sum < (ref.sum + res.error))
1000
+
1001
+ @pytest.mark.parametrize('log', [True, False])
1002
+ def test_infinite_bounds(self, log, xp):
1003
+ a = xp.asarray([1, -np.inf, -np.inf])
1004
+ b = xp.asarray([np.inf, -1, np.inf])
1005
+ c = xp.asarray([1, 2, 3])
1006
+
1007
+ def f(x, a):
1008
+ return (xp.log(xp.tanh(a / 2)) - a*xp.abs(x) if log
1009
+ else xp.tanh(a/2) * xp.exp(-a*xp.abs(x)))
1010
+
1011
+ res = nsum(f, a, b, args=(c,), log=log)
1012
+ ref = xp.asarray([stats.dlaplace.sf(0, 1), stats.dlaplace.sf(0, 2), 1])
1013
+ ref = xp.log(ref) if log else ref
1014
+ atol = (1e-10 if a.dtype==xp.float64 else 1e-5) if log else 0
1015
+ xp_assert_close(res.sum, xp.asarray(ref, dtype=a.dtype), atol=atol)
1016
+
1017
+ # # Make sure the sign of `x` passed into `f` is correct.
1018
+ def f(x, c):
1019
+ return -3*xp.log(c*x) if log else 1 / (c*x)**3
1020
+
1021
+ a = xp.asarray([1, -np.inf])
1022
+ b = xp.asarray([np.inf, -1])
1023
+ arg = xp.asarray([1, -1])
1024
+ res = nsum(f, a, b, args=(arg,), log=log)
1025
+ ref = np.log(special.zeta(3)) if log else special.zeta(3)
1026
+ xp_assert_close(res.sum, xp.full(a.shape, ref, dtype=a.dtype))
1027
+
1028
+ def test_decreasing_check(self, xp):
1029
+ # Test accuracy when we start sum on an uphill slope.
1030
+ # Without the decreasing check, the terms would look small enough to
1031
+ # use the integral approximation. Because the function is not decreasing,
1032
+ # the error is not bounded by the magnitude of the last term of the
1033
+ # partial sum. In this case, the error would be ~1e-4, causing the test
1034
+ # to fail.
1035
+ def f(x):
1036
+ return xp.exp(-x ** 2)
1037
+
1038
+ a, b = xp.asarray(-25, dtype=xp.float64), xp.asarray(np.inf, dtype=xp.float64)
1039
+ res = nsum(f, a, b)
1040
+
1041
+ # Reference computed with mpmath:
1042
+ # from mpmath import mp
1043
+ # mp.dps = 50
1044
+ # def fmp(x): return mp.exp(-x**2)
1045
+ # ref = mp.nsum(fmp, (-25, 0)) + mp.nsum(fmp, (1, mp.inf))
1046
+ ref = xp.asarray(1.772637204826652, dtype=xp.float64)
1047
+
1048
+ xp_assert_close(res.sum, ref, rtol=1e-15)
1049
+
1050
+ def test_special_case(self, xp):
1051
+ # test equal lower/upper limit
1052
+ f = self.f1
1053
+ a = b = xp.asarray(2)
1054
+ res = nsum(f, a, b)
1055
+ xp_assert_equal(res.sum, xp.asarray(f(2)))
1056
+
1057
+ # Test scalar `args` (not in tuple)
1058
+ res = nsum(self.f2, xp.asarray(1), xp.asarray(np.inf), args=xp.asarray(2))
1059
+ xp_assert_close(res.sum, xp.asarray(self.f1.ref)) # f1.ref is correct w/ args=2
1060
+
1061
+ # Test 0 size input
1062
+ a = xp.empty((3, 1, 1)) # arbitrary broadcastable shapes
1063
+ b = xp.empty((0, 1)) # could use Hypothesis
1064
+ p = xp.empty(4) # but it's overkill
1065
+ shape = np.broadcast_shapes(a.shape, b.shape, p.shape)
1066
+ res = nsum(self.f2, a, b, args=(p,))
1067
+ assert res.sum.shape == shape
1068
+ assert res.status.shape == shape
1069
+ assert res.nfev.shape == shape
1070
+
1071
+ # Test maxterms=0
1072
+ def f(x):
1073
+ with np.errstate(divide='ignore'):
1074
+ return 1 / x
1075
+
1076
+ res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=0)
1077
+ assert xp.isnan(res.sum)
1078
+ assert xp.isnan(res.error)
1079
+ assert res.status == -2
1080
+
1081
+ res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=1)
1082
+ assert xp.isnan(res.sum)
1083
+ assert xp.isnan(res.error)
1084
+ assert res.status == -3
1085
+
1086
+ # Test NaNs
1087
+ # should skip both direct and integral methods if there are NaNs
1088
+ a = xp.asarray([xp.nan, 1, 1, 1])
1089
+ b = xp.asarray([xp.inf, xp.nan, xp.inf, xp.inf])
1090
+ p = xp.asarray([2, 2, xp.nan, 2])
1091
+ res = nsum(self.f2, a, b, args=(p,))
1092
+ xp_assert_close(res.sum, xp.asarray([xp.nan, xp.nan, xp.nan, self.f1.ref]))
1093
+ xp_assert_close(res.error[:3], xp.full((3,), xp.nan))
1094
+ xp_assert_equal(res.status, xp.asarray([-1, -1, -3, 0], dtype=xp.int32))
1095
+ xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
1096
+ # Ideally res.nfev[2] would be 1, but `tanhsinh` has some function evals
1097
+ xp_assert_equal(res.nfev[:2], xp.full((2,), 1, dtype=xp.int32))
1098
+
1099
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
1100
+ def test_dtype(self, dtype, xp):
1101
+ dtype = getattr(xp, dtype)
1102
+
1103
+ def f(k):
1104
+ assert k.dtype == dtype
1105
+ return 1 / k ** xp.asarray(2, dtype=dtype)
1106
+
1107
+ a = xp.asarray(1, dtype=dtype)
1108
+ b = xp.asarray([10, xp.inf], dtype=dtype)
1109
+ res = nsum(f, a, b)
1110
+ assert res.sum.dtype == dtype
1111
+ assert res.error.dtype == dtype
1112
+
1113
+ rtol = 1e-12 if dtype == xp.float64 else 1e-6
1114
+ ref = _gen_harmonic_gt1(np.asarray([10, xp.inf]), 2)
1115
+ xp_assert_close(res.sum, xp.asarray(ref, dtype=dtype), rtol=rtol)
1116
+
1117
+ @pytest.mark.parametrize('case', [(10, 100), (100, 10)])
1118
+ def test_nondivisible_interval(self, case, xp):
1119
+ # When the limits of the sum are such that (b - a)/step
1120
+ # is not exactly integral, check that only floor((b - a)/step)
1121
+ # terms are included.
1122
+ n, maxterms = case
1123
+
1124
+ def f(k):
1125
+ return 1 / k ** 2
1126
+
1127
+ a = np.e
1128
+ step = 1 / 3
1129
+ b0 = a + n * step
1130
+ i = np.arange(-2, 3)
1131
+ b = b0 + i * np.spacing(b0)
1132
+ ns = np.floor((b - a) / step)
1133
+ assert len(set(ns)) == 2
1134
+
1135
+ a, b = xp.asarray(a, dtype=xp.float64), xp.asarray(b, dtype=xp.float64)
1136
+ step, ns = xp.asarray(step, dtype=xp.float64), xp.asarray(ns, dtype=xp.float64)
1137
+ res = nsum(f, a, b, step=step, maxterms=maxterms)
1138
+ xp_assert_equal(xp.diff(ns) > 0, xp.diff(res.sum) > 0)
1139
+ xp_assert_close(res.sum[-1], res.sum[0] + f(b0))
1140
+
1141
+ @pytest.mark.skip_xp_backends(np_only=True, reason='Needs beta function.')
1142
+ def test_logser_kurtosis_gh20648(self, xp):
1143
+ # Some functions return NaN at infinity rather than 0 like they should.
1144
+ # Check that this is accounted for.
1145
+ ref = stats.yulesimon.moment(4, 5)
1146
+ def f(x):
1147
+ return stats.yulesimon._pmf(x, 5) * x**4
1148
+
1149
+ with np.errstate(invalid='ignore'):
1150
+ assert np.isnan(f(np.inf))
1151
+
1152
+ res = nsum(f, 1, np.inf)
1153
+ assert_allclose(res.sum, ref)
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_backward.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+
26
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cudnn_rnn.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_cudnn_rnn_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _cudnn_rnn(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
27
+ return at::_ops::_cudnn_rnn::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _cudnn_rnn(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
32
+ return at::_ops::_cudnn_rnn::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state);
33
+ }
34
+ }
35
+
36
+ // aten::_cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
37
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _cudnn_rnn_symint(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
38
+ return at::_ops::_cudnn_rnn::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _cudnn_rnn(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
43
+ return at::_ops::_cudnn_rnn::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state);
44
+ }
45
+ }
46
+
47
+ // aten::_cudnn_rnn.out(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))
48
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
49
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state, out0, out1, out2, out3, out4);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
54
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state, out0, out1, out2, out3, out4);
55
+ }
56
+ }
57
+
58
+ // aten::_cudnn_rnn.out(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))
59
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4) {
60
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state, out0, out1, out2, out3, out4);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4) {
65
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, c10::fromIntArrayRefSlow(batch_sizes), dropout_state, out0, out1, out2, out3, out4);
66
+ }
67
+ }
68
+
69
+ // aten::_cudnn_rnn.out(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))
70
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
71
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, out0, out1, out2, out3, out4);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state) {
76
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, out0, out1, out2, out3, out4);
77
+ }
78
+ }
79
+
80
+ // aten::_cudnn_rnn.out(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!))
81
+ inline ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_symint_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4) {
82
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, out0, out1, out2, out3, out4);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> _cudnn_rnn_outf(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const ::std::optional<at::Tensor> & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4) {
87
+ return at::_ops::_cudnn_rnn_out::call(input, weight, weight_stride0, weight_buf, hx, cx, mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, out0, out1, out2, out3, out4);
88
+ }
89
+ }
90
+
91
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_cummax_helper.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_cummax_helper_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
26
+ inline void _cummax_helper(const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim) {
27
+ return at::_ops::_cummax_helper::call(self, values, indices, dim);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _fake_quantize_learnable_per_channel_affine_backward {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t, double);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_fake_quantize_learnable_per_channel_affine_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_fake_quantize_learnable_per_channel_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & grad, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, int64_t quant_min, int64_t quant_max, double grad_factor);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, int64_t quant_min, int64_t quant_max, double grad_factor);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_sin {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_sin")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sin(Tensor[] self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
26
+ };
27
+
28
+ struct TORCH_API _foreach_sin_ {
29
+ using schema = void (at::TensorList);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_sin_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sin_(Tensor(a!)[] self) -> ()")
35
+ static void call(at::TensorList self);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
37
+ };
38
+
39
+ struct TORCH_API _foreach_sin_out {
40
+ using schema = void (at::TensorList, at::TensorList);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_sin")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sin.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
46
+ static void call(at::TensorList self, at::TensorList out);
47
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
48
+ };
49
+
50
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tan.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_foreach_tan_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_foreach_tan(Tensor[] self) -> Tensor[]
26
+ inline ::std::vector<at::Tensor> _foreach_tan(at::TensorList self) {
27
+ return at::_ops::_foreach_tan::call(self);
28
+ }
29
+
30
+ // aten::_foreach_tan_(Tensor(a!)[] self) -> ()
31
+ inline void _foreach_tan_(at::TensorList self) {
32
+ return at::_ops::_foreach_tan_::call(self);
33
+ }
34
+
35
+ // aten::_foreach_tan.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
36
+ inline void _foreach_tan_out(at::TensorList out, at::TensorList self) {
37
+ return at::_ops::_foreach_tan_out::call(self, out);
38
+ }
39
+ // aten::_foreach_tan.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
40
+ inline void _foreach_tan_outf(at::TensorList self, at::TensorList out) {
41
+ return at::_ops::_foreach_tan_out::call(self, out);
42
+ }
43
+
44
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_fw_primal_copy_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor _fw_primal_copy(const at::Tensor & self, int64_t level);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> _linalg_eigh(const at::Tensor & A, c10::string_view UPLO="L", bool compute_v=true);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _linalg_eigh_out(at::Tensor & eigenvalues, at::Tensor & eigenvectors, const at::Tensor & A, c10::string_view UPLO="L", bool compute_v=true);
22
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _linalg_eigh_outf(const at::Tensor & A, c10::string_view UPLO, bool compute_v, at::Tensor & eigenvalues, at::Tensor & eigenvectors);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_solve_ex_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> _linalg_solve_ex(const at::Tensor & A, const at::Tensor & B, bool left=true, bool check_errors=false);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_scale_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _masked_scale {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, double);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_masked_scale")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_masked_scale(Tensor self, Tensor mask, float scale) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & mask, double scale);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, double scale);
26
+ };
27
+
28
+ struct TORCH_API _masked_scale_out {
29
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, double, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_masked_scale")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_masked_scale.out(Tensor self, Tensor mask, float scale, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_sum_backward.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_nested_sum_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_nested_sum_backward(Tensor grad, Tensor self, int[1]? dim, bool keepdim=False) -> Tensor
26
+ inline at::Tensor _nested_sum_backward(const at::Tensor & grad, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false) {
27
+ return at::_ops::_nested_sum_backward::call(grad, self, dim, keepdim);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_view_from_buffer_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _nested_view_from_buffer {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_view_from_buffer")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a)")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & nested_size, const at::Tensor & nested_strides, const at::Tensor & offsets);
26
+ };
27
+
28
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_pack_padded_sequence_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> _pack_padded_sequence(const at::Tensor & input, const at::Tensor & lengths, bool batch_first);
20
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> _pack_padded_sequence_out(const at::Tensor & input, const at::Tensor & lengths, bool batch_first, at::Tensor & out0, at::Tensor & out1);
21
+ } // namespace native
22
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,c10::SymInt,c10::SymInt,at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_cudnn_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional<at::Tensor> & attn_bias, bool compute_log_sumexp, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, ::std::optional<double> scale=::std::nullopt);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_for_cpu_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, double dropout_p, bool is_causal, const ::std::optional<at::Tensor> & attn_mask={}, ::std::optional<double> scale=::std::nullopt);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_sparse_csc_tensor_unsafe_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
26
+ inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}) {
27
+ return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt());
28
+ }
29
+ // aten::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
30
+ inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory) {
31
+ return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, dtype, layout, device, pin_memory);
32
+ }
33
+
34
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_mm_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _sparse_semi_structured_mm(const at::Tensor & mat1, const at::Tensor & mat1_meta, const at::Tensor & mat2, ::std::optional<at::ScalarType> out_dtype=::std::nullopt);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & _test_autograd_multiple_dispatch_view_copy_out(at::Tensor & out, const at::Tensor & self);
21
+ TORCH_API at::Tensor & _test_autograd_multiple_dispatch_view_copy_outf(const at::Tensor & self, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_thnn_fused_lstm_cell_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _thnn_fused_lstm_cell_backward(const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias) {
27
+ return at::_ops::_thnn_fused_lstm_cell_backward::call(grad_hy, grad_cy, cx, cy, workspace, has_bias);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _to_sparse_csr {
18
+ using schema = at::Tensor (const at::Tensor &, ::std::optional<int64_t>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_to_sparse_csr")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, ::std::optional<int64_t> dense_dim);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional<int64_t> dense_dim);
26
+ };
27
+
28
+ struct TORCH_API _to_sparse_csr_out {
29
+ using schema = at::Tensor & (const at::Tensor &, ::std::optional<int64_t>, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_to_sparse_csr")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_to_sparse_csr.out(Tensor self, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, ::std::optional<int64_t> dense_dim, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional<int64_t> dense_dim, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/_unsafe_masked_index.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_unsafe_masked_index_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor
26
+ inline at::Tensor _unsafe_masked_index(const at::Tensor & self, const at::Tensor & mask, const c10::List<::std::optional<at::Tensor>> & indices, const at::Scalar & fill) {
27
+ return at::_ops::_unsafe_masked_index::call(self, mask, indices, fill);
28
+ }
29
+
30
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/addr_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API addr {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addr")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha);
26
+ };
27
+
28
+ struct TORCH_API addr_ {
29
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addr_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha);
37
+ };
38
+
39
+ struct TORCH_API addr_out {
40
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::addr")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "addr.out(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & vec1, const at::Tensor & vec2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/all_cuda_dispatch.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor all(const at::Tensor & self, int64_t dim, bool keepdim=false);
21
+ TORCH_API at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool keepdim=false);
22
+ TORCH_API at::Tensor & all_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & out);
23
+ TORCH_API at::Tensor all(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
24
+ TORCH_API at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
25
+ TORCH_API at::Tensor & all_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, at::Tensor & out);
26
+ TORCH_API at::Tensor all(const at::Tensor & self);
27
+ TORCH_API at::Tensor & all_out(at::Tensor & out, const at::Tensor & self);
28
+ TORCH_API at::Tensor & all_outf(const at::Tensor & self, at::Tensor & out);
29
+
30
+ } // namespace cuda
31
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/binary_cross_entropy_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor
26
+ inline at::Tensor binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
27
+ return at::_ops::binary_cross_entropy::call(self, target, weight, reduction);
28
+ }
29
+
30
+ // aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & binary_cross_entropy_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, int64_t reduction=at::Reduction::Mean) {
32
+ return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out);
33
+ }
34
+ // aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & binary_cross_entropy_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight, int64_t reduction, at::Tensor & out) {
36
+ return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out);
37
+ }
38
+
39
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/cat_cuda_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor cat(const at::ITensorListRef & tensors, int64_t dim=0);
21
+ TORCH_API at::Tensor & cat_out(at::Tensor & out, const at::ITensorListRef & tensors, int64_t dim=0);
22
+ TORCH_API at::Tensor & cat_outf(const at::ITensorListRef & tensors, int64_t dim, at::Tensor & out);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose1d_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor conv_transpose1d_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1));
20
+ } // namespace native
21
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/elu_backward_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor elu_backward(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
21
+ TORCH_API at::Tensor & elu_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result);
22
+ TORCH_API at::Tensor & elu_backward_outf(const at::Tensor & grad_output, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale, bool is_result, const at::Tensor & self_or_result, at::Tensor & grad_input);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fft_irfft2.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/fft_irfft2_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::fft_irfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
26
+ inline at::Tensor fft_irfft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
27
+ return at::_ops::fft_irfft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ at::Tensor fft_irfft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
32
+ return at::_ops::fft_irfft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm);
33
+ }
34
+ }
35
+
36
+ // aten::fft_irfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor
37
+ inline at::Tensor fft_irfft2_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
38
+ return at::_ops::fft_irfft2::call(self, s, dim, norm);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ at::Tensor fft_irfft2(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
43
+ return at::_ops::fft_irfft2::call(self, s, dim, norm);
44
+ }
45
+ }
46
+
47
+ // aten::fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
48
+ inline at::Tensor & fft_irfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
49
+ return at::_ops::fft_irfft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ at::Tensor & fft_irfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
54
+ return at::_ops::fft_irfft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
55
+ }
56
+ }
57
+
58
+ // aten::fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
59
+ inline at::Tensor & fft_irfft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
60
+ return at::_ops::fft_irfft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ at::Tensor & fft_irfft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
65
+ return at::_ops::fft_irfft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out);
66
+ }
67
+ }
68
+
69
+ // aten::fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
70
+ inline at::Tensor & fft_irfft2_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
71
+ return at::_ops::fft_irfft2_out::call(self, s, dim, norm, out);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ at::Tensor & fft_irfft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional<c10::string_view> norm=::std::nullopt) {
76
+ return at::_ops::fft_irfft2_out::call(self, s, dim, norm, out);
77
+ }
78
+ }
79
+
80
+ // aten::fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!)
81
+ inline at::Tensor & fft_irfft2_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
82
+ return at::_ops::fft_irfft2_out::call(self, s, dim, norm, out);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ at::Tensor & fft_irfft2_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional<c10::string_view> norm, at::Tensor & out) {
87
+ return at::_ops::fft_irfft2_out::call(self, s, dim, norm, out);
88
+ }
89
+ }
90
+
91
+ }
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool2d_backward_meta_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor fractional_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices);
21
+ TORCH_API at::Tensor & fractional_max_pool2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices);
22
+ TORCH_API at::Tensor & fractional_max_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input);
23
+
24
+ } // namespace meta
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> fractional_max_pool3d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples);
21
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> fractional_max_pool3d_out(at::Tensor & output, at::Tensor & indices, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples);
22
+ TORCH_API ::std::tuple<at::Tensor &,at::Tensor &> fractional_max_pool3d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples, at::Tensor & output, at::Tensor & indices);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/hardtanh_backward_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API hardtanh_backward_grad_input {
18
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "grad_input")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & grad_input);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & grad_input);
26
+ };
27
+
28
+ struct TORCH_API hardtanh_backward {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh_backward")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val);
37
+ };
38
+
39
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/huber_loss_backward_cuda_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor & huber_loss_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta);
21
+ TORCH_API at::Tensor & huber_loss_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double delta, at::Tensor & grad_input);
22
+
23
+ } // namespace cuda
24
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_add_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor index_add(const at::Tensor & self, at::Dimname dim, const at::Tensor & index, const at::Tensor & source, const at::Scalar & alpha=1);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_meta.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_index_Tensor : public TensorIteratorBase {
21
+
22
+ template <bool SIZES = false, bool STRIDES = false>
23
+ struct TORCH_API precompute_out {
24
+
25
+ precompute_out<true, STRIDES> set_sizes(at::DimVector value) {
26
+ static_assert(SIZES == false, "sizes already set");
27
+ precompute_out<true, STRIDES> ret;
28
+ ret.sizes = value;
29
+ ret.strides = this->strides;
30
+ return ret;
31
+ }
32
+
33
+
34
+ precompute_out<SIZES, true> set_strides(at::DimVector value) {
35
+ static_assert(STRIDES == false, "strides already set");
36
+ precompute_out<SIZES, true> ret;
37
+ ret.sizes = this->sizes;
38
+ ret.strides = value;
39
+ return ret;
40
+ }
41
+
42
+ at::DimVector sizes;
43
+ at::DimVector strides;
44
+ };
45
+ using meta_return_ty = precompute_out <true, true>;
46
+ meta_return_ty meta(const at::Tensor & self, at::IOptTensorListRef indices);
47
+ };
48
+
49
+ } // namespace native
50
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/index_reduce_meta_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor index_reduce(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true);
21
+ TORCH_API at::Tensor & index_reduce_out(at::Tensor & out, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true);
22
+ TORCH_API at::Tensor & index_reduce_outf(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self, at::Tensor & out);
23
+ TORCH_API at::Tensor & index_reduce_(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & source, c10::string_view reduce, bool include_self=true);
24
+
25
+ } // namespace meta
26
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/is_pinned_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API bool is_pinned(const at::Tensor & self, ::std::optional<at::Device> device=::std::nullopt);
21
+
22
+ } // namespace compositeexplicitautograd
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/logaddexp_cuda_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor logaddexp(const at::Tensor & self, const at::Tensor & other);
21
+ TORCH_API at::Tensor & logaddexp_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & logaddexp_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/logical_or_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API logical_or {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_or")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_or(Tensor self, Tensor other) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
26
+ };
27
+
28
+ struct TORCH_API logical_or_ {
29
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_or_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
37
+ };
38
+
39
+ struct TORCH_API logical_or_out {
40
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::logical_or")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/minimum_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor minimum(const at::Tensor & self, const at::Tensor & other);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
pllava/lib/python3.10/site-packages/torch/include/ATen/ops/nanmedian_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & nanmedian_out(at::Tensor & out, const at::Tensor & self);
21
+ TORCH_API at::Tensor & nanmedian_outf(const at::Tensor & self, at::Tensor & out);
22
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> nanmedian(const at::Tensor & self, int64_t dim, bool keepdim=false);
23
+
24
+ } // namespace compositeexplicitautograd
25
+ } // namespace at