jasonfan commited on
Commit
5d96719
·
verified ·
1 Parent(s): efd07f8

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. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md +25 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py +9 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py +251 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py +221 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py +109 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py +0 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py +1013 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py +505 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_realtransforms.py +693 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py +63 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/__init__.py +0 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py +96 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py +98 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py +502 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py +206 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py +574 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py +84 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py +249 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/__init__.py +103 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_basic.py +428 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_helper.py +115 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py +554 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py +598 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/basic.py +20 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/helper.py +19 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py +22 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py +19 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py +0 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py +879 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py +54 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py +33 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py +388 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py +837 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/__init__.py +122 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_bvp.py +1154 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_cubature.py +728 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py +8 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py +290 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py +478 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py +451 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py +193 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py +755 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py +224 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py +572 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py +601 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py +0 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py +1287 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py +37 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_lebedev.py +0 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ode.py +1388 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2010-2019 Max-Planck-Society
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above copyright notice, this
10
+ list of conditions and the following disclaimer in the documentation and/or
11
+ other materials provided with the distribution.
12
+ * Neither the name of the copyright holder nor the names of its contributors may
13
+ be used to endorse or promote products derived from this software without
14
+ specific prior written permission.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
20
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
23
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """ FFT backend using pypocketfft """
2
+
3
+ from .basic import *
4
+ from .realtransforms import *
5
+ from .helper import *
6
+
7
+ from scipy._lib._testutils import PytestTester
8
+ test = PytestTester(__name__)
9
+ del PytestTester
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Discrete Fourier Transforms - basic.py
3
+ """
4
+ import numpy as np
5
+ import functools
6
+ from . import pypocketfft as pfft
7
+ from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
8
+ _fix_shape, _fix_shape_1d, _normalization,
9
+ _workers)
10
+
11
+ def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
12
+ workers=None, *, plan=None):
13
+ """ Return discrete Fourier transform of real or complex sequence. """
14
+ if plan is not None:
15
+ raise NotImplementedError('Passing a precomputed plan is not yet '
16
+ 'supported by scipy.fft functions')
17
+ tmp = _asfarray(x)
18
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
19
+ norm = _normalization(norm, forward)
20
+ workers = _workers(workers)
21
+
22
+ if n is not None:
23
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
24
+ overwrite_x = overwrite_x or copied
25
+ elif tmp.shape[axis] < 1:
26
+ message = f"invalid number of data points ({tmp.shape[axis]}) specified"
27
+ raise ValueError(message)
28
+
29
+ out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
30
+
31
+ return pfft.c2c(tmp, (axis,), forward, norm, out, workers)
32
+
33
+
34
+ fft = functools.partial(c2c, True)
35
+ fft.__name__ = 'fft'
36
+ ifft = functools.partial(c2c, False)
37
+ ifft.__name__ = 'ifft'
38
+
39
+
40
+ def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
41
+ workers=None, *, plan=None):
42
+ """
43
+ Discrete Fourier transform of a real sequence.
44
+ """
45
+ if plan is not None:
46
+ raise NotImplementedError('Passing a precomputed plan is not yet '
47
+ 'supported by scipy.fft functions')
48
+ tmp = _asfarray(x)
49
+ norm = _normalization(norm, forward)
50
+ workers = _workers(workers)
51
+
52
+ if not np.isrealobj(tmp):
53
+ raise TypeError("x must be a real sequence")
54
+
55
+ if n is not None:
56
+ tmp, _ = _fix_shape_1d(tmp, n, axis)
57
+ elif tmp.shape[axis] < 1:
58
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
59
+
60
+ # Note: overwrite_x is not utilised
61
+ return pfft.r2c(tmp, (axis,), forward, norm, None, workers)
62
+
63
+
64
+ rfft = functools.partial(r2c, True)
65
+ rfft.__name__ = 'rfft'
66
+ ihfft = functools.partial(r2c, False)
67
+ ihfft.__name__ = 'ihfft'
68
+
69
+
70
+ def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
71
+ workers=None, *, plan=None):
72
+ """
73
+ Return inverse discrete Fourier transform of real sequence x.
74
+ """
75
+ if plan is not None:
76
+ raise NotImplementedError('Passing a precomputed plan is not yet '
77
+ 'supported by scipy.fft functions')
78
+ tmp = _asfarray(x)
79
+ norm = _normalization(norm, forward)
80
+ workers = _workers(workers)
81
+
82
+ # TODO: Optimize for hermitian and real?
83
+ if np.isrealobj(tmp):
84
+ tmp = tmp + 0.j
85
+
86
+ # Last axis utilizes hermitian symmetry
87
+ if n is None:
88
+ n = (tmp.shape[axis] - 1) * 2
89
+ if n < 1:
90
+ raise ValueError(f"Invalid number of data points ({n}) specified")
91
+ else:
92
+ tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis)
93
+
94
+ # Note: overwrite_x is not utilized
95
+ return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers)
96
+
97
+
98
+ hfft = functools.partial(c2r, True)
99
+ hfft.__name__ = 'hfft'
100
+ irfft = functools.partial(c2r, False)
101
+ irfft.__name__ = 'irfft'
102
+
103
+
104
+ def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
105
+ *, plan=None):
106
+ """
107
+ 2-D discrete Fourier transform of a Hermitian sequence
108
+ """
109
+ if plan is not None:
110
+ raise NotImplementedError('Passing a precomputed plan is not yet '
111
+ 'supported by scipy.fft functions')
112
+ return hfftn(x, s, axes, norm, overwrite_x, workers)
113
+
114
+
115
+ def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
116
+ *, plan=None):
117
+ """
118
+ 2-D discrete inverse Fourier transform of a Hermitian sequence
119
+ """
120
+ if plan is not None:
121
+ raise NotImplementedError('Passing a precomputed plan is not yet '
122
+ 'supported by scipy.fft functions')
123
+ return ihfftn(x, s, axes, norm, overwrite_x, workers)
124
+
125
+
126
+ def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
127
+ workers=None, *, plan=None):
128
+ """
129
+ Return multidimensional discrete Fourier transform.
130
+ """
131
+ if plan is not None:
132
+ raise NotImplementedError('Passing a precomputed plan is not yet '
133
+ 'supported by scipy.fft functions')
134
+ tmp = _asfarray(x)
135
+
136
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
137
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
138
+ workers = _workers(workers)
139
+
140
+ if len(axes) == 0:
141
+ return x
142
+
143
+ tmp, copied = _fix_shape(tmp, shape, axes)
144
+ overwrite_x = overwrite_x or copied
145
+
146
+ norm = _normalization(norm, forward)
147
+ out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
148
+
149
+ return pfft.c2c(tmp, axes, forward, norm, out, workers)
150
+
151
+
152
+ fftn = functools.partial(c2cn, True)
153
+ fftn.__name__ = 'fftn'
154
+ ifftn = functools.partial(c2cn, False)
155
+ ifftn.__name__ = 'ifftn'
156
+
157
+ def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
158
+ workers=None, *, plan=None):
159
+ """Return multidimensional discrete Fourier transform of real input"""
160
+ if plan is not None:
161
+ raise NotImplementedError('Passing a precomputed plan is not yet '
162
+ 'supported by scipy.fft functions')
163
+ tmp = _asfarray(x)
164
+
165
+ if not np.isrealobj(tmp):
166
+ raise TypeError("x must be a real sequence")
167
+
168
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
169
+ tmp, _ = _fix_shape(tmp, shape, axes)
170
+ norm = _normalization(norm, forward)
171
+ workers = _workers(workers)
172
+
173
+ if len(axes) == 0:
174
+ raise ValueError("at least 1 axis must be transformed")
175
+
176
+ # Note: overwrite_x is not utilized
177
+ return pfft.r2c(tmp, axes, forward, norm, None, workers)
178
+
179
+
180
+ rfftn = functools.partial(r2cn, True)
181
+ rfftn.__name__ = 'rfftn'
182
+ ihfftn = functools.partial(r2cn, False)
183
+ ihfftn.__name__ = 'ihfftn'
184
+
185
+
186
+ def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
187
+ workers=None, *, plan=None):
188
+ """Multidimensional inverse discrete fourier transform with real output"""
189
+ if plan is not None:
190
+ raise NotImplementedError('Passing a precomputed plan is not yet '
191
+ 'supported by scipy.fft functions')
192
+ tmp = _asfarray(x)
193
+
194
+ # TODO: Optimize for hermitian and real?
195
+ if np.isrealobj(tmp):
196
+ tmp = tmp + 0.j
197
+
198
+ noshape = s is None
199
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
200
+
201
+ if len(axes) == 0:
202
+ raise ValueError("at least 1 axis must be transformed")
203
+
204
+ shape = list(shape)
205
+ if noshape:
206
+ shape[-1] = (x.shape[axes[-1]] - 1) * 2
207
+
208
+ norm = _normalization(norm, forward)
209
+ workers = _workers(workers)
210
+
211
+ # Last axis utilizes hermitian symmetry
212
+ lastsize = shape[-1]
213
+ shape[-1] = (shape[-1] // 2) + 1
214
+
215
+ tmp, _ = tuple(_fix_shape(tmp, shape, axes))
216
+
217
+ # Note: overwrite_x is not utilized
218
+ return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers)
219
+
220
+
221
+ hfftn = functools.partial(c2rn, True)
222
+ hfftn.__name__ = 'hfftn'
223
+ irfftn = functools.partial(c2rn, False)
224
+ irfftn.__name__ = 'irfftn'
225
+
226
+
227
+ def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False):
228
+ """FFT of a real sequence, returning fftpack half complex format"""
229
+ tmp = _asfarray(x)
230
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
231
+ norm = _normalization(norm, forward)
232
+ workers = _workers(None)
233
+
234
+ if tmp.dtype.kind == 'c':
235
+ raise TypeError('x must be a real sequence')
236
+
237
+ if n is not None:
238
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
239
+ overwrite_x = overwrite_x or copied
240
+ elif tmp.shape[axis] < 1:
241
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
242
+
243
+ out = (tmp if overwrite_x else None)
244
+
245
+ return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers)
246
+
247
+
248
+ rfft_fftpack = functools.partial(r2r_fftpack, True)
249
+ rfft_fftpack.__name__ = 'rfft_fftpack'
250
+ irfft_fftpack = functools.partial(r2r_fftpack, False)
251
+ irfft_fftpack.__name__ = 'irfft_fftpack'
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numbers import Number
2
+ import operator
3
+ import os
4
+ import threading
5
+ import contextlib
6
+
7
+ import numpy as np
8
+
9
+ from scipy._lib._util import copy_if_needed
10
+
11
+ # good_size is exposed (and used) from this import
12
+ from .pypocketfft import good_size, prev_good_size
13
+
14
+
15
+ __all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers']
16
+
17
+ _config = threading.local()
18
+ _cpu_count = os.cpu_count()
19
+
20
+
21
+ def _iterable_of_int(x, name=None):
22
+ """Convert ``x`` to an iterable sequence of int
23
+
24
+ Parameters
25
+ ----------
26
+ x : value, or sequence of values, convertible to int
27
+ name : str, optional
28
+ Name of the argument being converted, only used in the error message
29
+
30
+ Returns
31
+ -------
32
+ y : ``List[int]``
33
+ """
34
+ if isinstance(x, Number):
35
+ x = (x,)
36
+
37
+ try:
38
+ x = [operator.index(a) for a in x]
39
+ except TypeError as e:
40
+ name = name or "value"
41
+ raise ValueError(f"{name} must be a scalar or iterable of integers") from e
42
+
43
+ return x
44
+
45
+
46
+ def _init_nd_shape_and_axes(x, shape, axes):
47
+ """Handles shape and axes arguments for nd transforms"""
48
+ noshape = shape is None
49
+ noaxes = axes is None
50
+
51
+ if not noaxes:
52
+ axes = _iterable_of_int(axes, 'axes')
53
+ axes = [a + x.ndim if a < 0 else a for a in axes]
54
+
55
+ if any(a >= x.ndim or a < 0 for a in axes):
56
+ raise ValueError("axes exceeds dimensionality of input")
57
+ if len(set(axes)) != len(axes):
58
+ raise ValueError("all axes must be unique")
59
+
60
+ if not noshape:
61
+ shape = _iterable_of_int(shape, 'shape')
62
+
63
+ if axes and len(axes) != len(shape):
64
+ raise ValueError("when given, axes and shape arguments"
65
+ " have to be of the same length")
66
+ if noaxes:
67
+ if len(shape) > x.ndim:
68
+ raise ValueError("shape requires more axes than are present")
69
+ axes = range(x.ndim - len(shape), x.ndim)
70
+
71
+ shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)]
72
+ elif noaxes:
73
+ shape = list(x.shape)
74
+ axes = range(x.ndim)
75
+ else:
76
+ shape = [x.shape[a] for a in axes]
77
+
78
+ if any(s < 1 for s in shape):
79
+ raise ValueError(
80
+ f"invalid number of data points ({shape}) specified")
81
+
82
+ return tuple(shape), list(axes)
83
+
84
+
85
+ def _asfarray(x):
86
+ """
87
+ Convert to array with floating or complex dtype.
88
+
89
+ float16 values are also promoted to float32.
90
+ """
91
+ if not hasattr(x, "dtype"):
92
+ x = np.asarray(x)
93
+
94
+ if x.dtype == np.float16:
95
+ return np.asarray(x, np.float32)
96
+ elif x.dtype.kind not in 'fc':
97
+ return np.asarray(x, np.float64)
98
+
99
+ # Require native byte order
100
+ dtype = x.dtype.newbyteorder('=')
101
+ # Always align input
102
+ copy = True if not x.flags['ALIGNED'] else copy_if_needed
103
+ return np.array(x, dtype=dtype, copy=copy)
104
+
105
+ def _datacopied(arr, original):
106
+ """
107
+ Strict check for `arr` not sharing any data with `original`,
108
+ under the assumption that arr = asarray(original)
109
+ """
110
+ if arr is original:
111
+ return False
112
+ if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
113
+ return False
114
+ return arr.base is None
115
+
116
+
117
+ def _fix_shape(x, shape, axes):
118
+ """Internal auxiliary function for _raw_fft, _raw_fftnd."""
119
+ must_copy = False
120
+
121
+ # Build an nd slice with the dimensions to be read from x
122
+ index = [slice(None)]*x.ndim
123
+ for n, ax in zip(shape, axes):
124
+ if x.shape[ax] >= n:
125
+ index[ax] = slice(0, n)
126
+ else:
127
+ index[ax] = slice(0, x.shape[ax])
128
+ must_copy = True
129
+
130
+ index = tuple(index)
131
+
132
+ if not must_copy:
133
+ return x[index], False
134
+
135
+ s = list(x.shape)
136
+ for n, axis in zip(shape, axes):
137
+ s[axis] = n
138
+
139
+ z = np.zeros(s, x.dtype)
140
+ z[index] = x[index]
141
+ return z, True
142
+
143
+
144
+ def _fix_shape_1d(x, n, axis):
145
+ if n < 1:
146
+ raise ValueError(
147
+ f"invalid number of data points ({n}) specified")
148
+
149
+ return _fix_shape(x, (n,), (axis,))
150
+
151
+
152
+ _NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2}
153
+
154
+
155
+ def _normalization(norm, forward):
156
+ """Returns the pypocketfft normalization mode from the norm argument"""
157
+ try:
158
+ inorm = _NORM_MAP[norm]
159
+ return inorm if forward else (2 - inorm)
160
+ except KeyError:
161
+ raise ValueError(
162
+ f'Invalid norm value {norm!r}, should '
163
+ 'be "backward", "ortho" or "forward"') from None
164
+
165
+
166
+ def _workers(workers):
167
+ if workers is None:
168
+ return getattr(_config, 'default_workers', 1)
169
+
170
+ if workers < 0:
171
+ if workers >= -_cpu_count:
172
+ workers += 1 + _cpu_count
173
+ else:
174
+ raise ValueError(f"workers value out of range; got {workers}, must not be"
175
+ f" less than {-_cpu_count}")
176
+ elif workers == 0:
177
+ raise ValueError("workers must not be zero")
178
+
179
+ return workers
180
+
181
+
182
+ @contextlib.contextmanager
183
+ def set_workers(workers):
184
+ """Context manager for the default number of workers used in `scipy.fft`
185
+
186
+ Parameters
187
+ ----------
188
+ workers : int
189
+ The default number of workers to use
190
+
191
+ Examples
192
+ --------
193
+ >>> import numpy as np
194
+ >>> from scipy import fft, signal
195
+ >>> rng = np.random.default_rng()
196
+ >>> x = rng.standard_normal((128, 64))
197
+ >>> with fft.set_workers(4):
198
+ ... y = signal.fftconvolve(x, x)
199
+
200
+ """
201
+ old_workers = get_workers()
202
+ _config.default_workers = _workers(operator.index(workers))
203
+ try:
204
+ yield
205
+ finally:
206
+ _config.default_workers = old_workers
207
+
208
+
209
+ def get_workers():
210
+ """Returns the default number of workers within the current context
211
+
212
+ Examples
213
+ --------
214
+ >>> from scipy import fft
215
+ >>> fft.get_workers()
216
+ 1
217
+ >>> with fft.set_workers(4):
218
+ ... fft.get_workers()
219
+ 4
220
+ """
221
+ return getattr(_config, 'default_workers', 1)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from . import pypocketfft as pfft
3
+ from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
4
+ _fix_shape, _fix_shape_1d, _normalization, _workers)
5
+ import functools
6
+
7
+
8
+ def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None,
9
+ overwrite_x=False, workers=None, orthogonalize=None):
10
+ """Forward or backward 1-D DCT/DST
11
+
12
+ Parameters
13
+ ----------
14
+ forward : bool
15
+ Transform direction (determines type and normalisation)
16
+ transform : {pypocketfft.dct, pypocketfft.dst}
17
+ The transform to perform
18
+ """
19
+ tmp = _asfarray(x)
20
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
21
+ norm = _normalization(norm, forward)
22
+ workers = _workers(workers)
23
+
24
+ if not forward:
25
+ if type == 2:
26
+ type = 3
27
+ elif type == 3:
28
+ type = 2
29
+
30
+ if n is not None:
31
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
32
+ overwrite_x = overwrite_x or copied
33
+ elif tmp.shape[axis] < 1:
34
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
35
+
36
+ out = (tmp if overwrite_x else None)
37
+
38
+ # For complex input, transform real and imaginary components separably
39
+ if np.iscomplexobj(x):
40
+ out = np.empty_like(tmp) if out is None else out
41
+ transform(tmp.real, type, (axis,), norm, out.real, workers)
42
+ transform(tmp.imag, type, (axis,), norm, out.imag, workers)
43
+ return out
44
+
45
+ return transform(tmp, type, (axis,), norm, out, workers, orthogonalize)
46
+
47
+
48
+ dct = functools.partial(_r2r, True, pfft.dct)
49
+ dct.__name__ = 'dct'
50
+ idct = functools.partial(_r2r, False, pfft.dct)
51
+ idct.__name__ = 'idct'
52
+
53
+ dst = functools.partial(_r2r, True, pfft.dst)
54
+ dst.__name__ = 'dst'
55
+ idst = functools.partial(_r2r, False, pfft.dst)
56
+ idst.__name__ = 'idst'
57
+
58
+
59
+ def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None,
60
+ overwrite_x=False, workers=None, orthogonalize=None):
61
+ """Forward or backward nd DCT/DST
62
+
63
+ Parameters
64
+ ----------
65
+ forward : bool
66
+ Transform direction (determines type and normalisation)
67
+ transform : {pypocketfft.dct, pypocketfft.dst}
68
+ The transform to perform
69
+ """
70
+ tmp = _asfarray(x)
71
+
72
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
73
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
74
+
75
+ if len(axes) == 0:
76
+ return x
77
+
78
+ tmp, copied = _fix_shape(tmp, shape, axes)
79
+ overwrite_x = overwrite_x or copied
80
+
81
+ if not forward:
82
+ if type == 2:
83
+ type = 3
84
+ elif type == 3:
85
+ type = 2
86
+
87
+ norm = _normalization(norm, forward)
88
+ workers = _workers(workers)
89
+ out = (tmp if overwrite_x else None)
90
+
91
+ # For complex input, transform real and imaginary components separably
92
+ if np.iscomplexobj(x):
93
+ out = np.empty_like(tmp) if out is None else out
94
+ transform(tmp.real, type, axes, norm, out.real, workers)
95
+ transform(tmp.imag, type, axes, norm, out.imag, workers)
96
+ return out
97
+
98
+ return transform(tmp, type, axes, norm, out, workers, orthogonalize)
99
+
100
+
101
+ dctn = functools.partial(_r2rn, True, pfft.dct)
102
+ dctn.__name__ = 'dctn'
103
+ idctn = functools.partial(_r2rn, False, pfft.dct)
104
+ idctn.__name__ = 'idctn'
105
+
106
+ dstn = functools.partial(_r2rn, True, pfft.dst)
107
+ dstn.__name__ = 'dstn'
108
+ idstn = functools.partial(_r2rn, False, pfft.dst)
109
+ idstn.__name__ = 'idstn'
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py ADDED
@@ -0,0 +1,1013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
4
+ assert_array_almost_equal_nulp, assert_array_less,
5
+ assert_allclose)
6
+ import pytest
7
+ from pytest import raises as assert_raises
8
+ from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn,
9
+ rfft, irfft, rfftn, irfftn,
10
+ hfft, ihfft, hfftn, ihfftn)
11
+
12
+ from numpy import (arange, array, asarray, zeros, dot, exp, pi,
13
+ swapaxes, cdouble)
14
+ import numpy as np
15
+ import numpy.fft
16
+ from numpy.random import rand
17
+
18
+ # "large" composite numbers supported by FFT._PYPOCKETFFT
19
+ LARGE_COMPOSITE_SIZES = [
20
+ 2**13,
21
+ 2**5 * 3**5,
22
+ 2**3 * 3**3 * 5**2,
23
+ ]
24
+ SMALL_COMPOSITE_SIZES = [
25
+ 2,
26
+ 2*3*5,
27
+ 2*2*3*3,
28
+ ]
29
+ # prime
30
+ LARGE_PRIME_SIZES = [
31
+ 2011
32
+ ]
33
+ SMALL_PRIME_SIZES = [
34
+ 29
35
+ ]
36
+
37
+
38
+ def _assert_close_in_norm(x, y, rtol, size, rdt):
39
+ # helper function for testing
40
+ err_msg = f"size: {size} rdt: {rdt}"
41
+ assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
42
+
43
+
44
+ def random(size):
45
+ return rand(*size)
46
+
47
+ def swap_byteorder(arr):
48
+ """Returns the same array with swapped byteorder"""
49
+ dtype = arr.dtype.newbyteorder('S')
50
+ return arr.astype(dtype)
51
+
52
+ def direct_dft(x):
53
+ x = asarray(x)
54
+ n = len(x)
55
+ y = zeros(n, dtype=cdouble)
56
+ w = -arange(n)*(2j*pi/n)
57
+ for i in range(n):
58
+ y[i] = dot(exp(i*w), x)
59
+ return y
60
+
61
+
62
+ def direct_idft(x):
63
+ x = asarray(x)
64
+ n = len(x)
65
+ y = zeros(n, dtype=cdouble)
66
+ w = arange(n)*(2j*pi/n)
67
+ for i in range(n):
68
+ y[i] = dot(exp(i*w), x)/n
69
+ return y
70
+
71
+
72
+ def direct_dftn(x):
73
+ x = asarray(x)
74
+ for axis in range(x.ndim):
75
+ x = fft(x, axis=axis)
76
+ return x
77
+
78
+
79
+ def direct_idftn(x):
80
+ x = asarray(x)
81
+ for axis in range(x.ndim):
82
+ x = ifft(x, axis=axis)
83
+ return x
84
+
85
+
86
+ def direct_rdft(x):
87
+ x = asarray(x)
88
+ n = len(x)
89
+ w = -arange(n)*(2j*pi/n)
90
+ y = zeros(n//2+1, dtype=cdouble)
91
+ for i in range(n//2+1):
92
+ y[i] = dot(exp(i*w), x)
93
+ return y
94
+
95
+
96
+ def direct_irdft(x, n):
97
+ x = asarray(x)
98
+ x1 = zeros(n, dtype=cdouble)
99
+ for i in range(n//2+1):
100
+ x1[i] = x[i]
101
+ if i > 0 and 2*i < n:
102
+ x1[n-i] = np.conj(x[i])
103
+ return direct_idft(x1).real
104
+
105
+
106
+ def direct_rdftn(x):
107
+ return fftn(rfft(x), axes=range(x.ndim - 1))
108
+
109
+
110
+ class _TestFFTBase:
111
+ def setup_method(self):
112
+ self.cdt = None
113
+ self.rdt = None
114
+ np.random.seed(1234)
115
+
116
+ def test_definition(self):
117
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
118
+ y = fft(x)
119
+ assert_equal(y.dtype, self.cdt)
120
+ y1 = direct_dft(x)
121
+ assert_array_almost_equal(y,y1)
122
+ x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
123
+ assert_array_almost_equal(fft(x),direct_dft(x))
124
+
125
+ def test_n_argument_real(self):
126
+ x1 = np.array([1,2,3,4], dtype=self.rdt)
127
+ x2 = np.array([1,2,3,4], dtype=self.rdt)
128
+ y = fft([x1,x2],n=4)
129
+ assert_equal(y.dtype, self.cdt)
130
+ assert_equal(y.shape,(2,4))
131
+ assert_array_almost_equal(y[0],direct_dft(x1))
132
+ assert_array_almost_equal(y[1],direct_dft(x2))
133
+
134
+ def _test_n_argument_complex(self):
135
+ x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
136
+ x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
137
+ y = fft([x1,x2],n=4)
138
+ assert_equal(y.dtype, self.cdt)
139
+ assert_equal(y.shape,(2,4))
140
+ assert_array_almost_equal(y[0],direct_dft(x1))
141
+ assert_array_almost_equal(y[1],direct_dft(x2))
142
+
143
+ def test_djbfft(self):
144
+ for i in range(2,14):
145
+ n = 2**i
146
+ x = np.arange(n)
147
+ y = fft(x.astype(complex))
148
+ y2 = numpy.fft.fft(x)
149
+ assert_array_almost_equal(y,y2)
150
+ y = fft(x)
151
+ assert_array_almost_equal(y,y2)
152
+
153
+ def test_invalid_sizes(self):
154
+ assert_raises(ValueError, fft, [])
155
+ assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
156
+
157
+
158
+ class TestLongDoubleFFT(_TestFFTBase):
159
+ def setup_method(self):
160
+ self.cdt = np.clongdouble
161
+ self.rdt = np.longdouble
162
+
163
+
164
+ class TestDoubleFFT(_TestFFTBase):
165
+ def setup_method(self):
166
+ self.cdt = np.cdouble
167
+ self.rdt = np.float64
168
+
169
+
170
+ class TestSingleFFT(_TestFFTBase):
171
+ def setup_method(self):
172
+ self.cdt = np.complex64
173
+ self.rdt = np.float32
174
+
175
+
176
+ class TestFloat16FFT:
177
+
178
+ def test_1_argument_real(self):
179
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
180
+ y = fft(x1, n=4)
181
+ assert_equal(y.dtype, np.complex64)
182
+ assert_equal(y.shape, (4, ))
183
+ assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
184
+
185
+ def test_n_argument_real(self):
186
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
187
+ x2 = np.array([1, 2, 3, 4], dtype=np.float16)
188
+ y = fft([x1, x2], n=4)
189
+ assert_equal(y.dtype, np.complex64)
190
+ assert_equal(y.shape, (2, 4))
191
+ assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
192
+ assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
193
+
194
+
195
+ class _TestIFFTBase:
196
+ def setup_method(self):
197
+ np.random.seed(1234)
198
+
199
+ def test_definition(self):
200
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
201
+ y = ifft(x)
202
+ y1 = direct_idft(x)
203
+ assert_equal(y.dtype, self.cdt)
204
+ assert_array_almost_equal(y,y1)
205
+
206
+ x = np.array([1,2,3,4+0j,5], self.cdt)
207
+ assert_array_almost_equal(ifft(x),direct_idft(x))
208
+
209
+ def test_definition_real(self):
210
+ x = np.array([1,2,3,4,1,2,3,4], self.rdt)
211
+ y = ifft(x)
212
+ assert_equal(y.dtype, self.cdt)
213
+ y1 = direct_idft(x)
214
+ assert_array_almost_equal(y,y1)
215
+
216
+ x = np.array([1,2,3,4,5], dtype=self.rdt)
217
+ assert_equal(y.dtype, self.cdt)
218
+ assert_array_almost_equal(ifft(x),direct_idft(x))
219
+
220
+ def test_djbfft(self):
221
+ for i in range(2,14):
222
+ n = 2**i
223
+ x = np.arange(n)
224
+ y = ifft(x.astype(self.cdt))
225
+ y2 = numpy.fft.ifft(x.astype(self.cdt))
226
+ assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
227
+ y = ifft(x)
228
+ assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
229
+
230
+ def test_random_complex(self):
231
+ for size in [1,51,111,100,200,64,128,256,1024]:
232
+ x = random([size]).astype(self.cdt)
233
+ x = random([size]).astype(self.cdt) + 1j*x
234
+ y1 = ifft(fft(x))
235
+ y2 = fft(ifft(x))
236
+ assert_equal(y1.dtype, self.cdt)
237
+ assert_equal(y2.dtype, self.cdt)
238
+ assert_array_almost_equal(y1, x)
239
+ assert_array_almost_equal(y2, x)
240
+
241
+ def test_random_real(self):
242
+ for size in [1,51,111,100,200,64,128,256,1024]:
243
+ x = random([size]).astype(self.rdt)
244
+ y1 = ifft(fft(x))
245
+ y2 = fft(ifft(x))
246
+ assert_equal(y1.dtype, self.cdt)
247
+ assert_equal(y2.dtype, self.cdt)
248
+ assert_array_almost_equal(y1, x)
249
+ assert_array_almost_equal(y2, x)
250
+
251
+ def test_size_accuracy(self):
252
+ # Sanity check for the accuracy for prime and non-prime sized inputs
253
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
254
+ np.random.seed(1234)
255
+ x = np.random.rand(size).astype(self.rdt)
256
+ y = ifft(fft(x))
257
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
258
+ y = fft(ifft(x))
259
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
260
+
261
+ x = (x + 1j*np.random.rand(size)).astype(self.cdt)
262
+ y = ifft(fft(x))
263
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
264
+ y = fft(ifft(x))
265
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
266
+
267
+ def test_invalid_sizes(self):
268
+ assert_raises(ValueError, ifft, [])
269
+ assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
270
+
271
+
272
+ @pytest.mark.skipif(np.longdouble is np.float64,
273
+ reason="Long double is aliased to double")
274
+ class TestLongDoubleIFFT(_TestIFFTBase):
275
+ def setup_method(self):
276
+ self.cdt = np.clongdouble
277
+ self.rdt = np.longdouble
278
+ self.rtol = 1e-10
279
+ self.atol = 1e-10
280
+
281
+
282
+ class TestDoubleIFFT(_TestIFFTBase):
283
+ def setup_method(self):
284
+ self.cdt = np.complex128
285
+ self.rdt = np.float64
286
+ self.rtol = 1e-10
287
+ self.atol = 1e-10
288
+
289
+
290
+ class TestSingleIFFT(_TestIFFTBase):
291
+ def setup_method(self):
292
+ self.cdt = np.complex64
293
+ self.rdt = np.float32
294
+ self.rtol = 1e-5
295
+ self.atol = 1e-4
296
+
297
+
298
+ class _TestRFFTBase:
299
+ def setup_method(self):
300
+ np.random.seed(1234)
301
+
302
+ def test_definition(self):
303
+ for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
304
+ x = np.array(t, dtype=self.rdt)
305
+ y = rfft(x)
306
+ y1 = direct_rdft(x)
307
+ assert_array_almost_equal(y,y1)
308
+ assert_equal(y.dtype, self.cdt)
309
+
310
+ def test_djbfft(self):
311
+ for i in range(2,14):
312
+ n = 2**i
313
+ x = np.arange(n)
314
+ y1 = np.fft.rfft(x)
315
+ y = rfft(x)
316
+ assert_array_almost_equal(y,y1)
317
+
318
+ def test_invalid_sizes(self):
319
+ assert_raises(ValueError, rfft, [])
320
+ assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
321
+
322
+ def test_complex_input(self):
323
+ x = np.zeros(10, dtype=self.cdt)
324
+ with assert_raises(TypeError, match="x must be a real sequence"):
325
+ rfft(x)
326
+
327
+ # See gh-5790
328
+ class MockSeries:
329
+ def __init__(self, data):
330
+ self.data = np.asarray(data)
331
+
332
+ def __getattr__(self, item):
333
+ try:
334
+ return getattr(self.data, item)
335
+ except AttributeError as e:
336
+ raise AttributeError("'MockSeries' object "
337
+ f"has no attribute '{item}'") from e
338
+
339
+ def test_non_ndarray_with_dtype(self):
340
+ x = np.array([1., 2., 3., 4., 5.])
341
+ xs = _TestRFFTBase.MockSeries(x)
342
+
343
+ expected = [1, 2, 3, 4, 5]
344
+ rfft(xs)
345
+
346
+ # Data should not have been overwritten
347
+ assert_equal(x, expected)
348
+ assert_equal(xs.data, expected)
349
+
350
+ @pytest.mark.skipif(np.longdouble is np.float64,
351
+ reason="Long double is aliased to double")
352
+ class TestRFFTLongDouble(_TestRFFTBase):
353
+ def setup_method(self):
354
+ self.cdt = np.clongdouble
355
+ self.rdt = np.longdouble
356
+
357
+
358
+ class TestRFFTDouble(_TestRFFTBase):
359
+ def setup_method(self):
360
+ self.cdt = np.complex128
361
+ self.rdt = np.float64
362
+
363
+
364
+ class TestRFFTSingle(_TestRFFTBase):
365
+ def setup_method(self):
366
+ self.cdt = np.complex64
367
+ self.rdt = np.float32
368
+
369
+
370
+ class _TestIRFFTBase:
371
+ def setup_method(self):
372
+ np.random.seed(1234)
373
+
374
+ def test_definition(self):
375
+ x1 = [1,2+3j,4+1j,1+2j,3+4j]
376
+ x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
377
+ x1 = x1_1[:5]
378
+ x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
379
+ x2 = x2_1[:5]
380
+
381
+ def _test(x, xr):
382
+ y = irfft(np.array(x, dtype=self.cdt), n=len(xr))
383
+ y1 = direct_irdft(x, len(xr))
384
+ assert_equal(y.dtype, self.rdt)
385
+ assert_array_almost_equal(y,y1, decimal=self.ndec)
386
+ assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
387
+
388
+ _test(x1, x1_1)
389
+ _test(x2, x2_1)
390
+
391
+ def test_djbfft(self):
392
+ for i in range(2,14):
393
+ n = 2**i
394
+ x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2)
395
+ x[0] = 0
396
+ if n % 2 == 0:
397
+ x[-1] = np.real(x[-1])
398
+ y1 = np.fft.irfft(x)
399
+ y = irfft(x)
400
+ assert_array_almost_equal(y,y1)
401
+
402
+ def test_random_real(self):
403
+ for size in [1,51,111,100,200,64,128,256,1024]:
404
+ x = random([size]).astype(self.rdt)
405
+ y1 = irfft(rfft(x), n=size)
406
+ y2 = rfft(irfft(x, n=(size*2-1)))
407
+ assert_equal(y1.dtype, self.rdt)
408
+ assert_equal(y2.dtype, self.cdt)
409
+ assert_array_almost_equal(y1, x, decimal=self.ndec,
410
+ err_msg="size=%d" % size)
411
+ assert_array_almost_equal(y2, x, decimal=self.ndec,
412
+ err_msg="size=%d" % size)
413
+
414
+ def test_size_accuracy(self):
415
+ # Sanity check for the accuracy for prime and non-prime sized inputs
416
+ if self.rdt == np.float32:
417
+ rtol = 1e-5
418
+ elif self.rdt == np.float64:
419
+ rtol = 1e-10
420
+
421
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
422
+ np.random.seed(1234)
423
+ x = np.random.rand(size).astype(self.rdt)
424
+ y = irfft(rfft(x), len(x))
425
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
426
+ y = rfft(irfft(x, 2 * len(x) - 1))
427
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
428
+
429
+ def test_invalid_sizes(self):
430
+ assert_raises(ValueError, irfft, [])
431
+ assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
432
+
433
+
434
+ # self.ndec is bogus; we should have a assert_array_approx_equal for number of
435
+ # significant digits
436
+
437
+ @pytest.mark.skipif(np.longdouble is np.float64,
438
+ reason="Long double is aliased to double")
439
+ class TestIRFFTLongDouble(_TestIRFFTBase):
440
+ def setup_method(self):
441
+ self.cdt = np.complex128
442
+ self.rdt = np.float64
443
+ self.ndec = 14
444
+
445
+
446
+ class TestIRFFTDouble(_TestIRFFTBase):
447
+ def setup_method(self):
448
+ self.cdt = np.complex128
449
+ self.rdt = np.float64
450
+ self.ndec = 14
451
+
452
+
453
+ class TestIRFFTSingle(_TestIRFFTBase):
454
+ def setup_method(self):
455
+ self.cdt = np.complex64
456
+ self.rdt = np.float32
457
+ self.ndec = 5
458
+
459
+
460
+ class TestFftnSingle:
461
+ def setup_method(self):
462
+ np.random.seed(1234)
463
+
464
+ def test_definition(self):
465
+ x = [[1, 2, 3],
466
+ [4, 5, 6],
467
+ [7, 8, 9]]
468
+ y = fftn(np.array(x, np.float32))
469
+ assert_(y.dtype == np.complex64,
470
+ msg="double precision output with single precision")
471
+
472
+ y_r = np.array(fftn(x), np.complex64)
473
+ assert_array_almost_equal_nulp(y, y_r)
474
+
475
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
476
+ def test_size_accuracy_small(self, size):
477
+ rng = np.random.default_rng(1234)
478
+ x = rng.random((size, size)) + 1j * rng.random((size, size))
479
+ y1 = fftn(x.real.astype(np.float32))
480
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
481
+
482
+ assert_equal(y1.dtype, np.complex64)
483
+ assert_array_almost_equal_nulp(y1, y2, 2000)
484
+
485
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
486
+ def test_size_accuracy_large(self, size):
487
+ rng = np.random.default_rng(1234)
488
+ x = rng.random((size, 3)) + 1j * rng.random((size, 3))
489
+ y1 = fftn(x.real.astype(np.float32))
490
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
491
+
492
+ assert_equal(y1.dtype, np.complex64)
493
+ assert_array_almost_equal_nulp(y1, y2, 2000)
494
+
495
+ def test_definition_float16(self):
496
+ x = [[1, 2, 3],
497
+ [4, 5, 6],
498
+ [7, 8, 9]]
499
+ y = fftn(np.array(x, np.float16))
500
+ assert_equal(y.dtype, np.complex64)
501
+ y_r = np.array(fftn(x), np.complex64)
502
+ assert_array_almost_equal_nulp(y, y_r)
503
+
504
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
505
+ def test_float16_input_small(self, size):
506
+ rng = np.random.default_rng(1234)
507
+ x = rng.random((size, size)) + 1j*rng.random((size, size))
508
+ y1 = fftn(x.real.astype(np.float16))
509
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
510
+
511
+ assert_equal(y1.dtype, np.complex64)
512
+ assert_array_almost_equal_nulp(y1, y2, 5e5)
513
+
514
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
515
+ def test_float16_input_large(self, size):
516
+ rng = np.random.default_rng(1234)
517
+ x = rng.random((size, 3)) + 1j*rng.random((size, 3))
518
+ y1 = fftn(x.real.astype(np.float16))
519
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
520
+
521
+ assert_equal(y1.dtype, np.complex64)
522
+ assert_array_almost_equal_nulp(y1, y2, 2e6)
523
+
524
+
525
+ class TestFftn:
526
+ def setup_method(self):
527
+ np.random.seed(1234)
528
+
529
+ def test_definition(self):
530
+ x = [[1, 2, 3],
531
+ [4, 5, 6],
532
+ [7, 8, 9]]
533
+ y = fftn(x)
534
+ assert_array_almost_equal(y, direct_dftn(x))
535
+
536
+ x = random((20, 26))
537
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
538
+
539
+ x = random((5, 4, 3, 20))
540
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
541
+
542
+ def test_axes_argument(self):
543
+ # plane == ji_plane, x== kji_space
544
+ plane1 = [[1, 2, 3],
545
+ [4, 5, 6],
546
+ [7, 8, 9]]
547
+ plane2 = [[10, 11, 12],
548
+ [13, 14, 15],
549
+ [16, 17, 18]]
550
+ plane3 = [[19, 20, 21],
551
+ [22, 23, 24],
552
+ [25, 26, 27]]
553
+ ki_plane1 = [[1, 2, 3],
554
+ [10, 11, 12],
555
+ [19, 20, 21]]
556
+ ki_plane2 = [[4, 5, 6],
557
+ [13, 14, 15],
558
+ [22, 23, 24]]
559
+ ki_plane3 = [[7, 8, 9],
560
+ [16, 17, 18],
561
+ [25, 26, 27]]
562
+ jk_plane1 = [[1, 10, 19],
563
+ [4, 13, 22],
564
+ [7, 16, 25]]
565
+ jk_plane2 = [[2, 11, 20],
566
+ [5, 14, 23],
567
+ [8, 17, 26]]
568
+ jk_plane3 = [[3, 12, 21],
569
+ [6, 15, 24],
570
+ [9, 18, 27]]
571
+ kj_plane1 = [[1, 4, 7],
572
+ [10, 13, 16], [19, 22, 25]]
573
+ kj_plane2 = [[2, 5, 8],
574
+ [11, 14, 17], [20, 23, 26]]
575
+ kj_plane3 = [[3, 6, 9],
576
+ [12, 15, 18], [21, 24, 27]]
577
+ ij_plane1 = [[1, 4, 7],
578
+ [2, 5, 8],
579
+ [3, 6, 9]]
580
+ ij_plane2 = [[10, 13, 16],
581
+ [11, 14, 17],
582
+ [12, 15, 18]]
583
+ ij_plane3 = [[19, 22, 25],
584
+ [20, 23, 26],
585
+ [21, 24, 27]]
586
+ ik_plane1 = [[1, 10, 19],
587
+ [2, 11, 20],
588
+ [3, 12, 21]]
589
+ ik_plane2 = [[4, 13, 22],
590
+ [5, 14, 23],
591
+ [6, 15, 24]]
592
+ ik_plane3 = [[7, 16, 25],
593
+ [8, 17, 26],
594
+ [9, 18, 27]]
595
+ ijk_space = [jk_plane1, jk_plane2, jk_plane3]
596
+ ikj_space = [kj_plane1, kj_plane2, kj_plane3]
597
+ jik_space = [ik_plane1, ik_plane2, ik_plane3]
598
+ jki_space = [ki_plane1, ki_plane2, ki_plane3]
599
+ kij_space = [ij_plane1, ij_plane2, ij_plane3]
600
+ x = array([plane1, plane2, plane3])
601
+
602
+ assert_array_almost_equal(fftn(x),
603
+ fftn(x, axes=(-3, -2, -1))) # kji_space
604
+ assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
605
+ assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
606
+ y = fftn(x, axes=(2, 1, 0)) # ijk_space
607
+ assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
608
+ y = fftn(x, axes=(2, 0, 1)) # ikj_space
609
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
610
+ fftn(ikj_space))
611
+ y = fftn(x, axes=(1, 2, 0)) # jik_space
612
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
613
+ fftn(jik_space))
614
+ y = fftn(x, axes=(1, 0, 2)) # jki_space
615
+ assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
616
+ y = fftn(x, axes=(0, 2, 1)) # kij_space
617
+ assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
618
+
619
+ y = fftn(x, axes=(-2, -1)) # ji_plane
620
+ assert_array_almost_equal(fftn(plane1), y[0])
621
+ assert_array_almost_equal(fftn(plane2), y[1])
622
+ assert_array_almost_equal(fftn(plane3), y[2])
623
+
624
+ y = fftn(x, axes=(1, 2)) # ji_plane
625
+ assert_array_almost_equal(fftn(plane1), y[0])
626
+ assert_array_almost_equal(fftn(plane2), y[1])
627
+ assert_array_almost_equal(fftn(plane3), y[2])
628
+
629
+ y = fftn(x, axes=(-3, -2)) # kj_plane
630
+ assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
631
+ assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
632
+ assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
633
+
634
+ y = fftn(x, axes=(-3, -1)) # ki_plane
635
+ assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
636
+ assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
637
+ assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
638
+
639
+ y = fftn(x, axes=(-1, -2)) # ij_plane
640
+ assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
641
+ assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
642
+ assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
643
+
644
+ y = fftn(x, axes=(-1, -3)) # ik_plane
645
+ assert_array_almost_equal(fftn(ik_plane1),
646
+ swapaxes(y[:, 0, :], -1, -2))
647
+ assert_array_almost_equal(fftn(ik_plane2),
648
+ swapaxes(y[:, 1, :], -1, -2))
649
+ assert_array_almost_equal(fftn(ik_plane3),
650
+ swapaxes(y[:, 2, :], -1, -2))
651
+
652
+ y = fftn(x, axes=(-2, -3)) # jk_plane
653
+ assert_array_almost_equal(fftn(jk_plane1),
654
+ swapaxes(y[:, :, 0], -1, -2))
655
+ assert_array_almost_equal(fftn(jk_plane2),
656
+ swapaxes(y[:, :, 1], -1, -2))
657
+ assert_array_almost_equal(fftn(jk_plane3),
658
+ swapaxes(y[:, :, 2], -1, -2))
659
+
660
+ y = fftn(x, axes=(-1,)) # i_line
661
+ for i in range(3):
662
+ for j in range(3):
663
+ assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
664
+ y = fftn(x, axes=(-2,)) # j_line
665
+ for i in range(3):
666
+ for j in range(3):
667
+ assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
668
+ y = fftn(x, axes=(0,)) # k_line
669
+ for i in range(3):
670
+ for j in range(3):
671
+ assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
672
+
673
+ y = fftn(x, axes=()) # point
674
+ assert_array_almost_equal(y, x)
675
+
676
+ def test_shape_argument(self):
677
+ small_x = [[1, 2, 3],
678
+ [4, 5, 6]]
679
+ large_x1 = [[1, 2, 3, 0],
680
+ [4, 5, 6, 0],
681
+ [0, 0, 0, 0],
682
+ [0, 0, 0, 0]]
683
+
684
+ y = fftn(small_x, s=(4, 4))
685
+ assert_array_almost_equal(y, fftn(large_x1))
686
+
687
+ y = fftn(small_x, s=(3, 4))
688
+ assert_array_almost_equal(y, fftn(large_x1[:-1]))
689
+
690
+ def test_shape_axes_argument(self):
691
+ small_x = [[1, 2, 3],
692
+ [4, 5, 6],
693
+ [7, 8, 9]]
694
+ large_x1 = array([[1, 2, 3, 0],
695
+ [4, 5, 6, 0],
696
+ [7, 8, 9, 0],
697
+ [0, 0, 0, 0]])
698
+ y = fftn(small_x, s=(4, 4), axes=(-2, -1))
699
+ assert_array_almost_equal(y, fftn(large_x1))
700
+ y = fftn(small_x, s=(4, 4), axes=(-1, -2))
701
+
702
+ assert_array_almost_equal(y, swapaxes(
703
+ fftn(swapaxes(large_x1, -1, -2)), -1, -2))
704
+
705
+ def test_shape_axes_argument2(self):
706
+ # Change shape of the last axis
707
+ x = numpy.random.random((10, 5, 3, 7))
708
+ y = fftn(x, axes=(-1,), s=(8,))
709
+ assert_array_almost_equal(y, fft(x, axis=-1, n=8))
710
+
711
+ # Change shape of an arbitrary axis which is not the last one
712
+ x = numpy.random.random((10, 5, 3, 7))
713
+ y = fftn(x, axes=(-2,), s=(8,))
714
+ assert_array_almost_equal(y, fft(x, axis=-2, n=8))
715
+
716
+ # Change shape of axes: cf #244, where shape and axes were mixed up
717
+ x = numpy.random.random((4, 4, 2))
718
+ y = fftn(x, axes=(-3, -2), s=(8, 8))
719
+ assert_array_almost_equal(y,
720
+ numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
721
+
722
+ def test_shape_argument_more(self):
723
+ x = zeros((4, 4, 2))
724
+ with assert_raises(ValueError,
725
+ match="shape requires more axes than are present"):
726
+ fftn(x, s=(8, 8, 2, 1))
727
+
728
+ def test_invalid_sizes(self):
729
+ with assert_raises(ValueError,
730
+ match="invalid number of data points"
731
+ r" \(\[1, 0\]\) specified"):
732
+ fftn([[]])
733
+
734
+ with assert_raises(ValueError,
735
+ match="invalid number of data points"
736
+ r" \(\[4, -3\]\) specified"):
737
+ fftn([[1, 1], [2, 2]], (4, -3))
738
+
739
+ def test_no_axes(self):
740
+ x = numpy.random.random((2,2,2))
741
+ assert_allclose(fftn(x, axes=[]), x, atol=1e-7)
742
+
743
+ def test_regression_244(self):
744
+ """FFT returns wrong result with axes parameter."""
745
+ # fftn (and hence fft2) used to break when both axes and shape were used
746
+ x = numpy.ones((4, 4, 2))
747
+ y = fftn(x, s=(8, 8), axes=(-3, -2))
748
+ y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
749
+ assert_allclose(y, y_r)
750
+
751
+
752
+ class TestIfftn:
753
+ dtype = None
754
+ cdtype = None
755
+
756
+ def setup_method(self):
757
+ np.random.seed(1234)
758
+
759
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
760
+ [(np.float64, np.complex128, 2000),
761
+ (np.float32, np.complex64, 3500)])
762
+ def test_definition(self, dtype, cdtype, maxnlp):
763
+ rng = np.random.default_rng(1234)
764
+ x = np.array([[1, 2, 3],
765
+ [4, 5, 6],
766
+ [7, 8, 9]], dtype=dtype)
767
+ y = ifftn(x)
768
+ assert_equal(y.dtype, cdtype)
769
+ assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
770
+
771
+ x = rng.random((20, 26))
772
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
773
+
774
+ x = rng.random((5, 4, 3, 20))
775
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
776
+
777
+ @pytest.mark.parametrize('maxnlp', [2000, 3500])
778
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
779
+ def test_random_complex(self, maxnlp, size):
780
+ rng = np.random.default_rng(1234)
781
+ x = rng.random([size, size]) + 1j * rng.random([size, size])
782
+ assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
783
+ assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
784
+
785
+ def test_invalid_sizes(self):
786
+ with assert_raises(ValueError,
787
+ match="invalid number of data points"
788
+ r" \(\[1, 0\]\) specified"):
789
+ ifftn([[]])
790
+
791
+ with assert_raises(ValueError,
792
+ match="invalid number of data points"
793
+ r" \(\[4, -3\]\) specified"):
794
+ ifftn([[1, 1], [2, 2]], (4, -3))
795
+
796
+ def test_no_axes(self):
797
+ x = numpy.random.random((2,2,2))
798
+ assert_allclose(ifftn(x, axes=[]), x, atol=1e-7)
799
+
800
+ class TestRfftn:
801
+ dtype = None
802
+ cdtype = None
803
+
804
+ def setup_method(self):
805
+ np.random.seed(1234)
806
+
807
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
808
+ [(np.float64, np.complex128, 2000),
809
+ (np.float32, np.complex64, 3500)])
810
+ def test_definition(self, dtype, cdtype, maxnlp):
811
+ rng = np.random.default_rng(1234)
812
+ x = np.array([[1, 2, 3],
813
+ [4, 5, 6],
814
+ [7, 8, 9]], dtype=dtype)
815
+ y = rfftn(x)
816
+ assert_equal(y.dtype, cdtype)
817
+ assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp)
818
+
819
+ x = rng.random((20, 26))
820
+ assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
821
+
822
+ x = rng.random((5, 4, 3, 20))
823
+ assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
824
+
825
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
826
+ def test_random(self, size):
827
+ rng = np.random.default_rng(1234)
828
+ x = rng.random([size, size])
829
+ assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10)
830
+
831
+ @pytest.mark.parametrize('func', [rfftn, irfftn])
832
+ def test_invalid_sizes(self, func):
833
+ with assert_raises(ValueError,
834
+ match="invalid number of data points"
835
+ r" \(\[1, 0\]\) specified"):
836
+ func([[]])
837
+
838
+ with assert_raises(ValueError,
839
+ match="invalid number of data points"
840
+ r" \(\[4, -3\]\) specified"):
841
+ func([[1, 1], [2, 2]], (4, -3))
842
+
843
+ @pytest.mark.parametrize('func', [rfftn, irfftn])
844
+ def test_no_axes(self, func):
845
+ with assert_raises(ValueError,
846
+ match="at least 1 axis must be transformed"):
847
+ func([], axes=[])
848
+
849
+ def test_complex_input(self):
850
+ with assert_raises(TypeError, match="x must be a real sequence"):
851
+ rfftn(np.zeros(10, dtype=np.complex64))
852
+
853
+
854
+ class FakeArray:
855
+ def __init__(self, data):
856
+ self._data = data
857
+ self.__array_interface__ = data.__array_interface__
858
+
859
+
860
+ class FakeArray2:
861
+ def __init__(self, data):
862
+ self._data = data
863
+
864
+ def __array__(self, dtype=None, copy=None):
865
+ return self._data
866
+
867
+ # TODO: Is this test actually valuable? The behavior it's testing shouldn't be
868
+ # relied upon by users except for overwrite_x = False
869
+ class TestOverwrite:
870
+ """Check input overwrite behavior of the FFT functions."""
871
+
872
+ real_dtypes = [np.float32, np.float64, np.longdouble]
873
+ dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble]
874
+ fftsizes = [8, 16, 32]
875
+
876
+ def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite):
877
+ x2 = x.copy()
878
+ for fake in [lambda x: x, FakeArray, FakeArray2]:
879
+ routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
880
+
881
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
882
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
883
+ if not should_overwrite:
884
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
885
+
886
+ def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
887
+ fftsize, overwrite_x):
888
+ np.random.seed(1234)
889
+ if np.issubdtype(dtype, np.complexfloating):
890
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
891
+ else:
892
+ data = np.random.randn(*shape)
893
+ data = data.astype(dtype)
894
+
895
+ should_overwrite = (overwrite_x
896
+ and dtype in overwritable_dtypes
897
+ and fftsize <= shape[axis])
898
+ self._check(data, routine, fftsize, axis,
899
+ overwrite_x=overwrite_x,
900
+ should_overwrite=should_overwrite)
901
+
902
+ @pytest.mark.parametrize('dtype', dtypes)
903
+ @pytest.mark.parametrize('fftsize', fftsizes)
904
+ @pytest.mark.parametrize('overwrite_x', [True, False])
905
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
906
+ ((16, 2), 0),
907
+ ((2, 16), 1)])
908
+ def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
909
+ overwritable = (np.clongdouble, np.complex128, np.complex64)
910
+ self._check_1d(fft, dtype, shape, axes, overwritable,
911
+ fftsize, overwrite_x)
912
+ self._check_1d(ifft, dtype, shape, axes, overwritable,
913
+ fftsize, overwrite_x)
914
+
915
+ @pytest.mark.parametrize('dtype', real_dtypes)
916
+ @pytest.mark.parametrize('fftsize', fftsizes)
917
+ @pytest.mark.parametrize('overwrite_x', [True, False])
918
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
919
+ ((16, 2), 0),
920
+ ((2, 16), 1)])
921
+ def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
922
+ overwritable = self.real_dtypes
923
+ self._check_1d(irfft, dtype, shape, axes, overwritable,
924
+ fftsize, overwrite_x)
925
+ self._check_1d(rfft, dtype, shape, axes, overwritable,
926
+ fftsize, overwrite_x)
927
+
928
+ def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
929
+ overwrite_x):
930
+ np.random.seed(1234)
931
+ if np.issubdtype(dtype, np.complexfloating):
932
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
933
+ else:
934
+ data = np.random.randn(*shape)
935
+ data = data.astype(dtype)
936
+
937
+ def fftshape_iter(shp):
938
+ if len(shp) <= 0:
939
+ yield ()
940
+ else:
941
+ for j in (shp[0]//2, shp[0], shp[0]*2):
942
+ for rest in fftshape_iter(shp[1:]):
943
+ yield (j,) + rest
944
+
945
+ def part_shape(shape, axes):
946
+ if axes is None:
947
+ return shape
948
+ else:
949
+ return tuple(np.take(shape, axes))
950
+
951
+ def should_overwrite(data, shape, axes):
952
+ s = part_shape(data.shape, axes)
953
+ return (overwrite_x and
954
+ np.prod(shape) <= np.prod(s)
955
+ and dtype in overwritable_dtypes)
956
+
957
+ for fftshape in fftshape_iter(part_shape(shape, axes)):
958
+ self._check(data, routine, fftshape, axes,
959
+ overwrite_x=overwrite_x,
960
+ should_overwrite=should_overwrite(data, fftshape, axes))
961
+ if data.ndim > 1:
962
+ # check fortran order
963
+ self._check(data.T, routine, fftshape, axes,
964
+ overwrite_x=overwrite_x,
965
+ should_overwrite=should_overwrite(
966
+ data.T, fftshape, axes))
967
+
968
+ @pytest.mark.parametrize('dtype', dtypes)
969
+ @pytest.mark.parametrize('overwrite_x', [True, False])
970
+ @pytest.mark.parametrize('shape,axes', [((16,), None),
971
+ ((16,), (0,)),
972
+ ((16, 2), (0,)),
973
+ ((2, 16), (1,)),
974
+ ((8, 16), None),
975
+ ((8, 16), (0, 1)),
976
+ ((8, 16, 2), (0, 1)),
977
+ ((8, 16, 2), (1, 2)),
978
+ ((8, 16, 2), (0,)),
979
+ ((8, 16, 2), (1,)),
980
+ ((8, 16, 2), (2,)),
981
+ ((8, 16, 2), None),
982
+ ((8, 16, 2), (0, 1, 2))])
983
+ def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
984
+ overwritable = (np.clongdouble, np.complex128, np.complex64)
985
+ self._check_nd_one(fftn, dtype, shape, axes, overwritable,
986
+ overwrite_x)
987
+ self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
988
+ overwrite_x)
989
+
990
+
991
+ @pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
992
+ rfft, irfft, rfftn, irfftn])
993
+ def test_invalid_norm(func):
994
+ x = np.arange(10, dtype=float)
995
+ with assert_raises(ValueError,
996
+ match='Invalid norm value \'o\', should be'
997
+ ' "backward", "ortho" or "forward"'):
998
+ func(x, norm='o')
999
+
1000
+
1001
+ @pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
1002
+ irfft, irfftn, hfft, hfftn])
1003
+ def test_swapped_byte_order_complex(func):
1004
+ rng = np.random.RandomState(1234)
1005
+ x = rng.rand(10) + 1j * rng.rand(10)
1006
+ assert_allclose(func(swap_byteorder(x)), func(x))
1007
+
1008
+
1009
+ @pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn])
1010
+ def test_swapped_byte_order_real(func):
1011
+ rng = np.random.RandomState(1234)
1012
+ x = rng.rand(10)
1013
+ assert_allclose(func(swap_byteorder(x)), func(x))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os.path import join, dirname
2
+ from collections.abc import Callable
3
+ from threading import Lock
4
+
5
+ import numpy as np
6
+ from numpy.testing import (
7
+ assert_array_almost_equal, assert_equal, assert_allclose)
8
+ import pytest
9
+ from pytest import raises as assert_raises
10
+
11
+ from scipy.fft._pocketfft.realtransforms import (
12
+ dct, idct, dst, idst, dctn, idctn, dstn, idstn)
13
+
14
+ fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests')
15
+
16
+ MDATA_COUNT = 8
17
+ FFTWDATA_COUNT = 14
18
+
19
+ def is_longdouble_binary_compatible():
20
+ try:
21
+ one = np.frombuffer(
22
+ b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00',
23
+ dtype='<f16')
24
+ return one == np.longdouble(1.)
25
+ except TypeError:
26
+ return False
27
+
28
+
29
+ @pytest.fixture(scope="module")
30
+ def reference_data():
31
+ # Matlab reference data
32
+ MDATA = np.load(join(fftpack_test_dir, 'test.npz'))
33
+ X = [MDATA['x%d' % i] for i in range(MDATA_COUNT)]
34
+ Y = [MDATA['y%d' % i] for i in range(MDATA_COUNT)]
35
+
36
+ # FFTW reference data: the data are organized as follows:
37
+ # * SIZES is an array containing all available sizes
38
+ # * for every type (1, 2, 3, 4) and every size, the array dct_type_size
39
+ # contains the output of the DCT applied to the input np.linspace(0, size-1,
40
+ # size)
41
+ FFTWDATA_DOUBLE = np.load(join(fftpack_test_dir, 'fftw_double_ref.npz'))
42
+ FFTWDATA_SINGLE = np.load(join(fftpack_test_dir, 'fftw_single_ref.npz'))
43
+ FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
44
+ assert len(FFTWDATA_SIZES) == FFTWDATA_COUNT
45
+
46
+ if is_longdouble_binary_compatible():
47
+ FFTWDATA_LONGDOUBLE = np.load(
48
+ join(fftpack_test_dir, 'fftw_longdouble_ref.npz'))
49
+ else:
50
+ FFTWDATA_LONGDOUBLE = {k: v.astype(np.longdouble)
51
+ for k,v in FFTWDATA_DOUBLE.items()}
52
+
53
+ ref = {
54
+ 'FFTWDATA_LONGDOUBLE': FFTWDATA_LONGDOUBLE,
55
+ 'FFTWDATA_DOUBLE': FFTWDATA_DOUBLE,
56
+ 'FFTWDATA_SINGLE': FFTWDATA_SINGLE,
57
+ 'FFTWDATA_SIZES': FFTWDATA_SIZES,
58
+ 'X': X,
59
+ 'Y': Y
60
+ }
61
+
62
+ yield ref
63
+
64
+ if is_longdouble_binary_compatible():
65
+ FFTWDATA_LONGDOUBLE.close()
66
+ FFTWDATA_SINGLE.close()
67
+ FFTWDATA_DOUBLE.close()
68
+ MDATA.close()
69
+
70
+
71
+ @pytest.fixture(params=range(FFTWDATA_COUNT))
72
+ def fftwdata_size(request, reference_data):
73
+ return reference_data['FFTWDATA_SIZES'][request.param]
74
+
75
+ @pytest.fixture(params=range(MDATA_COUNT))
76
+ def mdata_x(request, reference_data):
77
+ return reference_data['X'][request.param]
78
+
79
+
80
+ @pytest.fixture(params=range(MDATA_COUNT))
81
+ def mdata_xy(request, reference_data):
82
+ y = reference_data['Y'][request.param]
83
+ x = reference_data['X'][request.param]
84
+ return x, y
85
+
86
+
87
+ @pytest.fixture
88
+ def ref_lock():
89
+ return Lock()
90
+
91
+
92
+ def fftw_dct_ref(type, size, dt, reference_data):
93
+ x = np.linspace(0, size-1, size).astype(dt)
94
+ dt = np.result_type(np.float32, dt)
95
+ if dt == np.float64:
96
+ data = reference_data['FFTWDATA_DOUBLE']
97
+ elif dt == np.float32:
98
+ data = reference_data['FFTWDATA_SINGLE']
99
+ elif dt == np.longdouble:
100
+ data = reference_data['FFTWDATA_LONGDOUBLE']
101
+ else:
102
+ raise ValueError()
103
+ y = (data['dct_%d_%d' % (type, size)]).astype(dt)
104
+ return x, y, dt
105
+
106
+
107
+ def fftw_dst_ref(type, size, dt, reference_data):
108
+ x = np.linspace(0, size-1, size).astype(dt)
109
+ dt = np.result_type(np.float32, dt)
110
+ if dt == np.float64:
111
+ data = reference_data['FFTWDATA_DOUBLE']
112
+ elif dt == np.float32:
113
+ data = reference_data['FFTWDATA_SINGLE']
114
+ elif dt == np.longdouble:
115
+ data = reference_data['FFTWDATA_LONGDOUBLE']
116
+ else:
117
+ raise ValueError()
118
+ y = (data['dst_%d_%d' % (type, size)]).astype(dt)
119
+ return x, y, dt
120
+
121
+
122
+ def ref_2d(func, x, **kwargs):
123
+ """Calculate 2-D reference data from a 1d transform"""
124
+ x = np.array(x, copy=True)
125
+ for row in range(x.shape[0]):
126
+ x[row, :] = func(x[row, :], **kwargs)
127
+ for col in range(x.shape[1]):
128
+ x[:, col] = func(x[:, col], **kwargs)
129
+ return x
130
+
131
+
132
+ def naive_dct1(x, norm=None):
133
+ """Calculate textbook definition version of DCT-I."""
134
+ x = np.array(x, copy=True)
135
+ N = len(x)
136
+ M = N-1
137
+ y = np.zeros(N)
138
+ m0, m = 1, 2
139
+ if norm == 'ortho':
140
+ m0 = np.sqrt(1.0/M)
141
+ m = np.sqrt(2.0/M)
142
+ for k in range(N):
143
+ for n in range(1, N-1):
144
+ y[k] += m*x[n]*np.cos(np.pi*n*k/M)
145
+ y[k] += m0 * x[0]
146
+ y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
147
+ if norm == 'ortho':
148
+ y[0] *= 1/np.sqrt(2)
149
+ y[N-1] *= 1/np.sqrt(2)
150
+ return y
151
+
152
+
153
+ def naive_dst1(x, norm=None):
154
+ """Calculate textbook definition version of DST-I."""
155
+ x = np.array(x, copy=True)
156
+ N = len(x)
157
+ M = N+1
158
+ y = np.zeros(N)
159
+ for k in range(N):
160
+ for n in range(N):
161
+ y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
162
+ if norm == 'ortho':
163
+ y *= np.sqrt(0.5/M)
164
+ return y
165
+
166
+
167
+ def naive_dct4(x, norm=None):
168
+ """Calculate textbook definition version of DCT-IV."""
169
+ x = np.array(x, copy=True)
170
+ N = len(x)
171
+ y = np.zeros(N)
172
+ for k in range(N):
173
+ for n in range(N):
174
+ y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
175
+ if norm == 'ortho':
176
+ y *= np.sqrt(2.0/N)
177
+ else:
178
+ y *= 2
179
+ return y
180
+
181
+
182
+ def naive_dst4(x, norm=None):
183
+ """Calculate textbook definition version of DST-IV."""
184
+ x = np.array(x, copy=True)
185
+ N = len(x)
186
+ y = np.zeros(N)
187
+ for k in range(N):
188
+ for n in range(N):
189
+ y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
190
+ if norm == 'ortho':
191
+ y *= np.sqrt(2.0/N)
192
+ else:
193
+ y *= 2
194
+ return y
195
+
196
+
197
+ @pytest.mark.parametrize('dtype', [np.complex64, np.complex128, np.clongdouble])
198
+ @pytest.mark.parametrize('transform', [dct, dst, idct, idst])
199
+ def test_complex(transform, dtype):
200
+ y = transform(1j*np.arange(5, dtype=dtype))
201
+ x = 1j*transform(np.arange(5))
202
+ assert_array_almost_equal(x, y)
203
+
204
+
205
+ DecMapType = dict[
206
+ tuple[Callable[..., np.ndarray], type[np.floating] | type[int], int],
207
+ int,
208
+ ]
209
+
210
+ # map (transform, dtype, type) -> decimal
211
+ dec_map: DecMapType = {
212
+ # DCT
213
+ (dct, np.float64, 1): 13,
214
+ (dct, np.float32, 1): 6,
215
+
216
+ (dct, np.float64, 2): 14,
217
+ (dct, np.float32, 2): 5,
218
+
219
+ (dct, np.float64, 3): 14,
220
+ (dct, np.float32, 3): 5,
221
+
222
+ (dct, np.float64, 4): 13,
223
+ (dct, np.float32, 4): 6,
224
+
225
+ # IDCT
226
+ (idct, np.float64, 1): 14,
227
+ (idct, np.float32, 1): 6,
228
+
229
+ (idct, np.float64, 2): 14,
230
+ (idct, np.float32, 2): 5,
231
+
232
+ (idct, np.float64, 3): 14,
233
+ (idct, np.float32, 3): 5,
234
+
235
+ (idct, np.float64, 4): 14,
236
+ (idct, np.float32, 4): 6,
237
+
238
+ # DST
239
+ (dst, np.float64, 1): 13,
240
+ (dst, np.float32, 1): 6,
241
+
242
+ (dst, np.float64, 2): 14,
243
+ (dst, np.float32, 2): 6,
244
+
245
+ (dst, np.float64, 3): 14,
246
+ (dst, np.float32, 3): 7,
247
+
248
+ (dst, np.float64, 4): 13,
249
+ (dst, np.float32, 4): 5,
250
+
251
+ # IDST
252
+ (idst, np.float64, 1): 14,
253
+ (idst, np.float32, 1): 6,
254
+
255
+ (idst, np.float64, 2): 14,
256
+ (idst, np.float32, 2): 6,
257
+
258
+ (idst, np.float64, 3): 14,
259
+ (idst, np.float32, 3): 6,
260
+
261
+ (idst, np.float64, 4): 14,
262
+ (idst, np.float32, 4): 6,
263
+ }
264
+
265
+ for k,v in dec_map.copy().items():
266
+ if k[1] == np.float64:
267
+ dec_map[(k[0], np.longdouble, k[2])] = v
268
+ elif k[1] == np.float32:
269
+ dec_map[(k[0], int, k[2])] = v
270
+
271
+
272
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
273
+ @pytest.mark.parametrize('type', [1, 2, 3, 4])
274
+ class TestDCT:
275
+ def test_definition(self, rdt, type, fftwdata_size,
276
+ reference_data, ref_lock):
277
+ with ref_lock:
278
+ x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
279
+ y = dct(x, type=type)
280
+ assert_equal(y.dtype, dt)
281
+ dec = dec_map[(dct, rdt, type)]
282
+ assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
283
+
284
+ @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64])
285
+ def test_axis(self, rdt, type, size):
286
+ nt = 2
287
+ dec = dec_map[(dct, rdt, type)]
288
+ x = np.random.randn(nt, size)
289
+ y = dct(x, type=type)
290
+ for j in range(nt):
291
+ assert_array_almost_equal(y[j], dct(x[j], type=type),
292
+ decimal=dec)
293
+
294
+ x = x.T
295
+ y = dct(x, axis=0, type=type)
296
+ for j in range(nt):
297
+ assert_array_almost_equal(y[:,j], dct(x[:,j], type=type),
298
+ decimal=dec)
299
+
300
+
301
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
302
+ def test_dct1_definition_ortho(rdt, mdata_x):
303
+ # Test orthornomal mode.
304
+ dec = dec_map[(dct, rdt, 1)]
305
+ x = np.array(mdata_x, dtype=rdt)
306
+ dt = np.result_type(np.float32, rdt)
307
+ y = dct(x, norm='ortho', type=1)
308
+ y2 = naive_dct1(x, norm='ortho')
309
+ assert_equal(y.dtype, dt)
310
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
311
+
312
+
313
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
314
+ def test_dct2_definition_matlab(mdata_xy, rdt):
315
+ # Test correspondence with matlab (orthornomal mode).
316
+ dt = np.result_type(np.float32, rdt)
317
+ x = np.array(mdata_xy[0], dtype=dt)
318
+
319
+ yr = mdata_xy[1]
320
+ y = dct(x, norm="ortho", type=2)
321
+ dec = dec_map[(dct, rdt, 2)]
322
+ assert_equal(y.dtype, dt)
323
+ assert_array_almost_equal(y, yr, decimal=dec)
324
+
325
+
326
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
327
+ def test_dct3_definition_ortho(mdata_x, rdt):
328
+ # Test orthornomal mode.
329
+ x = np.array(mdata_x, dtype=rdt)
330
+ dt = np.result_type(np.float32, rdt)
331
+ y = dct(x, norm='ortho', type=2)
332
+ xi = dct(y, norm="ortho", type=3)
333
+ dec = dec_map[(dct, rdt, 3)]
334
+ assert_equal(xi.dtype, dt)
335
+ assert_array_almost_equal(xi, x, decimal=dec)
336
+
337
+
338
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
339
+ def test_dct4_definition_ortho(mdata_x, rdt):
340
+ # Test orthornomal mode.
341
+ x = np.array(mdata_x, dtype=rdt)
342
+ dt = np.result_type(np.float32, rdt)
343
+ y = dct(x, norm='ortho', type=4)
344
+ y2 = naive_dct4(x, norm='ortho')
345
+ dec = dec_map[(dct, rdt, 4)]
346
+ assert_equal(y.dtype, dt)
347
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
348
+
349
+
350
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
351
+ @pytest.mark.parametrize('type', [1, 2, 3, 4])
352
+ def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
353
+ with ref_lock:
354
+ xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
355
+ x = idct(yr, type=type)
356
+ dec = dec_map[(idct, rdt, type)]
357
+ assert_equal(x.dtype, dt)
358
+ assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
359
+
360
+
361
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
362
+ @pytest.mark.parametrize('type', [1, 2, 3, 4])
363
+ def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
364
+ with ref_lock:
365
+ xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
366
+ y = dst(xr, type=type)
367
+ dec = dec_map[(dst, rdt, type)]
368
+ assert_equal(y.dtype, dt)
369
+ assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
370
+
371
+
372
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
373
+ def test_dst1_definition_ortho(rdt, mdata_x):
374
+ # Test orthornomal mode.
375
+ dec = dec_map[(dst, rdt, 1)]
376
+ x = np.array(mdata_x, dtype=rdt)
377
+ dt = np.result_type(np.float32, rdt)
378
+ y = dst(x, norm='ortho', type=1)
379
+ y2 = naive_dst1(x, norm='ortho')
380
+ assert_equal(y.dtype, dt)
381
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
382
+
383
+
384
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
385
+ def test_dst4_definition_ortho(rdt, mdata_x):
386
+ # Test orthornomal mode.
387
+ dec = dec_map[(dst, rdt, 4)]
388
+ x = np.array(mdata_x, dtype=rdt)
389
+ dt = np.result_type(np.float32, rdt)
390
+ y = dst(x, norm='ortho', type=4)
391
+ y2 = naive_dst4(x, norm='ortho')
392
+ assert_equal(y.dtype, dt)
393
+ assert_array_almost_equal(y, y2, decimal=dec)
394
+
395
+
396
+ @pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
397
+ @pytest.mark.parametrize('type', [1, 2, 3, 4])
398
+ def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
399
+ with ref_lock:
400
+ xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
401
+ x = idst(yr, type=type)
402
+ dec = dec_map[(idst, rdt, type)]
403
+ assert_equal(x.dtype, dt)
404
+ assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
405
+
406
+
407
+ @pytest.mark.parametrize('routine', [dct, dst, idct, idst])
408
+ @pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble])
409
+ @pytest.mark.parametrize('shape, axis', [
410
+ ((16,), -1), ((16, 2), 0), ((2, 16), 1)
411
+ ])
412
+ @pytest.mark.parametrize('type', [1, 2, 3, 4])
413
+ @pytest.mark.parametrize('overwrite_x', [True, False])
414
+ @pytest.mark.parametrize('norm', [None, 'ortho'])
415
+ def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x):
416
+ # Check input overwrite behavior
417
+ np.random.seed(1234)
418
+ if np.issubdtype(dtype, np.complexfloating):
419
+ x = np.random.randn(*shape) + 1j*np.random.randn(*shape)
420
+ else:
421
+ x = np.random.randn(*shape)
422
+ x = x.astype(dtype)
423
+ x2 = x.copy()
424
+ routine(x2, type, None, axis, norm, overwrite_x=overwrite_x)
425
+
426
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, "
427
+ f"overwrite_x={overwrite_x!r})")
428
+ if not overwrite_x:
429
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
430
+
431
+
432
+ class Test_DCTN_IDCTN:
433
+ dec = 14
434
+ dct_type = [1, 2, 3, 4]
435
+ norms = [None, 'backward', 'ortho', 'forward']
436
+ rstate = np.random.RandomState(1234)
437
+ shape = (32, 16)
438
+ data = rstate.randn(*shape)
439
+
440
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
441
+ (dstn, idstn)])
442
+ @pytest.mark.parametrize('axes', [None,
443
+ 1, (1,), [1],
444
+ 0, (0,), [0],
445
+ (0, 1), [0, 1],
446
+ (-2, -1), [-2, -1]])
447
+ @pytest.mark.parametrize('dct_type', dct_type)
448
+ @pytest.mark.parametrize('norm', ['ortho'])
449
+ def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
450
+ tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
451
+ tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
452
+ assert_array_almost_equal(self.data, tmp, decimal=12)
453
+
454
+ @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)])
455
+ @pytest.mark.parametrize('dct_type', dct_type)
456
+ @pytest.mark.parametrize('norm', norms)
457
+ def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm):
458
+ y1 = funcn(self.data, type=dct_type, axes=None, norm=norm)
459
+ y2 = ref_2d(func, self.data, type=dct_type, norm=norm)
460
+ assert_array_almost_equal(y1, y2, decimal=11)
461
+
462
+ @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)])
463
+ @pytest.mark.parametrize('dct_type', dct_type)
464
+ @pytest.mark.parametrize('norm', norms)
465
+ def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm):
466
+ fdata = dctn(self.data, type=dct_type, norm=norm)
467
+ y1 = funcn(fdata, type=dct_type, norm=norm)
468
+ y2 = ref_2d(func, fdata, type=dct_type, norm=norm)
469
+ assert_array_almost_equal(y1, y2, decimal=11)
470
+
471
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
472
+ (dstn, idstn)])
473
+ def test_axes_and_shape(self, fforward, finverse):
474
+ with assert_raises(ValueError,
475
+ match="when given, axes and shape arguments"
476
+ " have to be of the same length"):
477
+ fforward(self.data, s=self.data.shape[0], axes=(0, 1))
478
+
479
+ with assert_raises(ValueError,
480
+ match="when given, axes and shape arguments"
481
+ " have to be of the same length"):
482
+ fforward(self.data, s=self.data.shape, axes=0)
483
+
484
+ @pytest.mark.parametrize('fforward', [dctn, dstn])
485
+ def test_shape(self, fforward):
486
+ tmp = fforward(self.data, s=(128, 128), axes=None)
487
+ assert_equal(tmp.shape, (128, 128))
488
+
489
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
490
+ (dstn, idstn)])
491
+ @pytest.mark.parametrize('axes', [1, (1,), [1],
492
+ 0, (0,), [0]])
493
+ def test_shape_is_none_with_axes(self, fforward, finverse, axes):
494
+ tmp = fforward(self.data, s=None, axes=axes, norm='ortho')
495
+ tmp = finverse(tmp, s=None, axes=axes, norm='ortho')
496
+ assert_array_almost_equal(self.data, tmp, decimal=self.dec)
497
+
498
+
499
+ @pytest.mark.parametrize('func', [dct, dctn, idct, idctn,
500
+ dst, dstn, idst, idstn])
501
+ def test_swapped_byte_order(func):
502
+ rng = np.random.RandomState(1234)
503
+ x = rng.rand(10)
504
+ swapped_dt = x.dtype.newbyteorder('S')
505
+ assert_allclose(func(x.astype(swapped_dt)), func(x))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_realtransforms.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._basic import _dispatch
2
+ from scipy._lib.uarray import Dispatchable
3
+ import numpy as np
4
+
5
+ __all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
6
+
7
+
8
+ @_dispatch
9
+ def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
10
+ workers=None, *, orthogonalize=None):
11
+ """
12
+ Return multidimensional Discrete Cosine Transform along the specified axes.
13
+
14
+ Parameters
15
+ ----------
16
+ x : array_like
17
+ The input array.
18
+ type : {1, 2, 3, 4}, optional
19
+ Type of the DCT (see Notes). Default type is 2.
20
+ s : int or array_like of ints or None, optional
21
+ The shape of the result. If both `s` and `axes` (see below) are None,
22
+ `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
23
+ ``numpy.take(x.shape, axes, axis=0)``.
24
+ If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
25
+ If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
26
+ ``s[i]``.
27
+ If any element of `s` is -1, the size of the corresponding dimension of
28
+ `x` is used.
29
+ axes : int or array_like of ints or None, optional
30
+ Axes over which the DCT is computed. If not given, the last ``len(s)``
31
+ axes are used, or all axes if `s` is also not specified.
32
+ norm : {"backward", "ortho", "forward"}, optional
33
+ Normalization mode (see Notes). Default is "backward".
34
+ overwrite_x : bool, optional
35
+ If True, the contents of `x` can be destroyed; the default is False.
36
+ workers : int, optional
37
+ Maximum number of workers to use for parallel computation. If negative,
38
+ the value wraps around from ``os.cpu_count()``.
39
+ See :func:`~scipy.fft.fft` for more details.
40
+ orthogonalize : bool, optional
41
+ Whether to use the orthogonalized DCT variant (see Notes).
42
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
43
+
44
+ .. versionadded:: 1.8.0
45
+
46
+ Returns
47
+ -------
48
+ y : ndarray of real
49
+ The transformed input array.
50
+
51
+ See Also
52
+ --------
53
+ idctn : Inverse multidimensional DCT
54
+
55
+ Notes
56
+ -----
57
+ For full details of the DCT types and normalization modes, as well as
58
+ references, see `dct`.
59
+
60
+ Examples
61
+ --------
62
+ >>> import numpy as np
63
+ >>> from scipy.fft import dctn, idctn
64
+ >>> rng = np.random.default_rng()
65
+ >>> y = rng.standard_normal((16, 16))
66
+ >>> np.allclose(y, idctn(dctn(y)))
67
+ True
68
+
69
+ """
70
+ return (Dispatchable(x, np.ndarray),)
71
+
72
+
73
+ @_dispatch
74
+ def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
75
+ workers=None, orthogonalize=None):
76
+ """
77
+ Return multidimensional Inverse Discrete Cosine Transform along the specified axes.
78
+
79
+ Parameters
80
+ ----------
81
+ x : array_like
82
+ The input array.
83
+ type : {1, 2, 3, 4}, optional
84
+ Type of the DCT (see Notes). Default type is 2.
85
+ s : int or array_like of ints or None, optional
86
+ The shape of the result. If both `s` and `axes` (see below) are
87
+ None, `s` is ``x.shape``; if `s` is None but `axes` is
88
+ not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
89
+ If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
90
+ If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
91
+ ``s[i]``.
92
+ If any element of `s` is -1, the size of the corresponding dimension of
93
+ `x` is used.
94
+ axes : int or array_like of ints or None, optional
95
+ Axes over which the IDCT is computed. If not given, the last ``len(s)``
96
+ axes are used, or all axes if `s` is also not specified.
97
+ norm : {"backward", "ortho", "forward"}, optional
98
+ Normalization mode (see Notes). Default is "backward".
99
+ overwrite_x : bool, optional
100
+ If True, the contents of `x` can be destroyed; the default is False.
101
+ workers : int, optional
102
+ Maximum number of workers to use for parallel computation. If negative,
103
+ the value wraps around from ``os.cpu_count()``.
104
+ See :func:`~scipy.fft.fft` for more details.
105
+ orthogonalize : bool, optional
106
+ Whether to use the orthogonalized IDCT variant (see Notes).
107
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
108
+
109
+ .. versionadded:: 1.8.0
110
+
111
+ Returns
112
+ -------
113
+ y : ndarray of real
114
+ The transformed input array.
115
+
116
+ See Also
117
+ --------
118
+ dctn : multidimensional DCT
119
+
120
+ Notes
121
+ -----
122
+ For full details of the IDCT types and normalization modes, as well as
123
+ references, see `idct`.
124
+
125
+ Examples
126
+ --------
127
+ >>> import numpy as np
128
+ >>> from scipy.fft import dctn, idctn
129
+ >>> rng = np.random.default_rng()
130
+ >>> y = rng.standard_normal((16, 16))
131
+ >>> np.allclose(y, idctn(dctn(y)))
132
+ True
133
+
134
+ """
135
+ return (Dispatchable(x, np.ndarray),)
136
+
137
+
138
+ @_dispatch
139
+ def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
140
+ workers=None, orthogonalize=None):
141
+ """
142
+ Return multidimensional Discrete Sine Transform along the specified axes.
143
+
144
+ Parameters
145
+ ----------
146
+ x : array_like
147
+ The input array.
148
+ type : {1, 2, 3, 4}, optional
149
+ Type of the DST (see Notes). Default type is 2.
150
+ s : int or array_like of ints or None, optional
151
+ The shape of the result. If both `s` and `axes` (see below) are None,
152
+ `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
153
+ ``numpy.take(x.shape, axes, axis=0)``.
154
+ If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
155
+ If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
156
+ ``s[i]``.
157
+ If any element of `shape` is -1, the size of the corresponding dimension
158
+ of `x` is used.
159
+ axes : int or array_like of ints or None, optional
160
+ Axes over which the DST is computed. If not given, the last ``len(s)``
161
+ axes are used, or all axes if `s` is also not specified.
162
+ norm : {"backward", "ortho", "forward"}, optional
163
+ Normalization mode (see Notes). Default is "backward".
164
+ overwrite_x : bool, optional
165
+ If True, the contents of `x` can be destroyed; the default is False.
166
+ workers : int, optional
167
+ Maximum number of workers to use for parallel computation. If negative,
168
+ the value wraps around from ``os.cpu_count()``.
169
+ See :func:`~scipy.fft.fft` for more details.
170
+ orthogonalize : bool, optional
171
+ Whether to use the orthogonalized DST variant (see Notes).
172
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
173
+
174
+ .. versionadded:: 1.8.0
175
+
176
+ Returns
177
+ -------
178
+ y : ndarray of real
179
+ The transformed input array.
180
+
181
+ See Also
182
+ --------
183
+ idstn : Inverse multidimensional DST
184
+
185
+ Notes
186
+ -----
187
+ For full details of the DST types and normalization modes, as well as
188
+ references, see `dst`.
189
+
190
+ Examples
191
+ --------
192
+ >>> import numpy as np
193
+ >>> from scipy.fft import dstn, idstn
194
+ >>> rng = np.random.default_rng()
195
+ >>> y = rng.standard_normal((16, 16))
196
+ >>> np.allclose(y, idstn(dstn(y)))
197
+ True
198
+
199
+ """
200
+ return (Dispatchable(x, np.ndarray),)
201
+
202
+
203
+ @_dispatch
204
+ def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
205
+ workers=None, orthogonalize=None):
206
+ """
207
+ Return multidimensional Inverse Discrete Sine Transform along the specified axes.
208
+
209
+ Parameters
210
+ ----------
211
+ x : array_like
212
+ The input array.
213
+ type : {1, 2, 3, 4}, optional
214
+ Type of the DST (see Notes). Default type is 2.
215
+ s : int or array_like of ints or None, optional
216
+ The shape of the result. If both `s` and `axes` (see below) are None,
217
+ `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
218
+ ``numpy.take(x.shape, axes, axis=0)``.
219
+ If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
220
+ If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
221
+ ``s[i]``.
222
+ If any element of `s` is -1, the size of the corresponding dimension of
223
+ `x` is used.
224
+ axes : int or array_like of ints or None, optional
225
+ Axes over which the IDST is computed. If not given, the last ``len(s)``
226
+ axes are used, or all axes if `s` is also not specified.
227
+ norm : {"backward", "ortho", "forward"}, optional
228
+ Normalization mode (see Notes). Default is "backward".
229
+ overwrite_x : bool, optional
230
+ If True, the contents of `x` can be destroyed; the default is False.
231
+ workers : int, optional
232
+ Maximum number of workers to use for parallel computation. If negative,
233
+ the value wraps around from ``os.cpu_count()``.
234
+ See :func:`~scipy.fft.fft` for more details.
235
+ orthogonalize : bool, optional
236
+ Whether to use the orthogonalized IDST variant (see Notes).
237
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
238
+
239
+ .. versionadded:: 1.8.0
240
+
241
+ Returns
242
+ -------
243
+ y : ndarray of real
244
+ The transformed input array.
245
+
246
+ See Also
247
+ --------
248
+ dstn : multidimensional DST
249
+
250
+ Notes
251
+ -----
252
+ For full details of the IDST types and normalization modes, as well as
253
+ references, see `idst`.
254
+
255
+ Examples
256
+ --------
257
+ >>> import numpy as np
258
+ >>> from scipy.fft import dstn, idstn
259
+ >>> rng = np.random.default_rng()
260
+ >>> y = rng.standard_normal((16, 16))
261
+ >>> np.allclose(y, idstn(dstn(y)))
262
+ True
263
+
264
+ """
265
+ return (Dispatchable(x, np.ndarray),)
266
+
267
+
268
+ @_dispatch
269
+ def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
270
+ orthogonalize=None):
271
+ r"""Return the Discrete Cosine Transform of arbitrary type sequence x.
272
+
273
+ Parameters
274
+ ----------
275
+ x : array_like
276
+ The input array.
277
+ type : {1, 2, 3, 4}, optional
278
+ Type of the DCT (see Notes). Default type is 2.
279
+ n : int, optional
280
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
281
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
282
+ default results in ``n = x.shape[axis]``.
283
+ axis : int, optional
284
+ Axis along which the dct is computed; the default is over the
285
+ last axis (i.e., ``axis=-1``).
286
+ norm : {"backward", "ortho", "forward"}, optional
287
+ Normalization mode (see Notes). Default is "backward".
288
+ overwrite_x : bool, optional
289
+ If True, the contents of `x` can be destroyed; the default is False.
290
+ workers : int, optional
291
+ Maximum number of workers to use for parallel computation. If negative,
292
+ the value wraps around from ``os.cpu_count()``.
293
+ See :func:`~scipy.fft.fft` for more details.
294
+ orthogonalize : bool, optional
295
+ Whether to use the orthogonalized DCT variant (see Notes).
296
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
297
+
298
+ .. versionadded:: 1.8.0
299
+
300
+ Returns
301
+ -------
302
+ y : ndarray of real
303
+ The transformed input array.
304
+
305
+ See Also
306
+ --------
307
+ idct : Inverse DCT
308
+
309
+ Notes
310
+ -----
311
+ For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
312
+ MATLAB ``dct(x)``.
313
+
314
+ .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
315
+ correspondence with the direct Fourier transform. To recover
316
+ it you must specify ``orthogonalize=False``.
317
+
318
+ For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
319
+ overall factor in both directions. By default, the transform is also
320
+ orthogonalized which for types 1, 2 and 3 means the transform definition is
321
+ modified to give orthogonality of the DCT matrix (see below).
322
+
323
+ For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
324
+ scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
325
+ ``norm="forward"`` the ``1/N`` normalization is applied to the forward
326
+ `dct` instead and the `idct` is unnormalized.
327
+
328
+ There are, theoretically, 8 types of the DCT, only the first 4 types are
329
+ implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the'
330
+ Inverse DCT generally refers to DCT type 3.
331
+
332
+ **Type I**
333
+
334
+ There are several definitions of the DCT-I; we use the following
335
+ (for ``norm="backward"``)
336
+
337
+ .. math::
338
+
339
+ y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
340
+ \frac{\pi k n}{N-1} \right)
341
+
342
+ If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
343
+ scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
344
+ by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
345
+ corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
346
+
347
+ .. note::
348
+ The DCT-I is only supported for input size > 1.
349
+
350
+ **Type II**
351
+
352
+ There are several definitions of the DCT-II; we use the following
353
+ (for ``norm="backward"``)
354
+
355
+ .. math::
356
+
357
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
358
+
359
+ If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
360
+ when combined with ``norm="ortho"``, makes the corresponding matrix of
361
+ coefficients orthonormal (``O @ O.T = np.eye(N)``).
362
+
363
+ **Type III**
364
+
365
+ There are several definitions, we use the following (for
366
+ ``norm="backward"``)
367
+
368
+ .. math::
369
+
370
+ y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
371
+
372
+ If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
373
+ :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
374
+ corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
375
+
376
+ The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
377
+ to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
378
+ the orthonormalized DCT-II.
379
+
380
+ **Type IV**
381
+
382
+ There are several definitions of the DCT-IV; we use the following
383
+ (for ``norm="backward"``)
384
+
385
+ .. math::
386
+
387
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
388
+
389
+ ``orthogonalize`` has no effect here, as the DCT-IV matrix is already
390
+ orthogonal up to a scale factor of ``2N``.
391
+
392
+ References
393
+ ----------
394
+ .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
395
+ Makhoul, `IEEE Transactions on acoustics, speech and signal
396
+ processing` vol. 28(1), pp. 27-34,
397
+ :doi:`10.1109/TASSP.1980.1163351` (1980).
398
+ .. [2] Wikipedia, "Discrete cosine transform",
399
+ https://en.wikipedia.org/wiki/Discrete_cosine_transform
400
+
401
+ Examples
402
+ --------
403
+ The Type 1 DCT is equivalent to the FFT (though faster) for real,
404
+ even-symmetrical inputs. The output is also real and even-symmetrical.
405
+ Half of the FFT input is used to generate half of the FFT output:
406
+
407
+ >>> from scipy.fft import fft, dct
408
+ >>> import numpy as np
409
+ >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
410
+ array([ 30., -8., 6., -2., 6., -8.])
411
+ >>> dct(np.array([4., 3., 5., 10.]), 1)
412
+ array([ 30., -8., 6., -2.])
413
+
414
+ """
415
+ return (Dispatchable(x, np.ndarray),)
416
+
417
+
418
+ @_dispatch
419
+ def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
420
+ workers=None, orthogonalize=None):
421
+ """
422
+ Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
423
+
424
+ Parameters
425
+ ----------
426
+ x : array_like
427
+ The input array.
428
+ type : {1, 2, 3, 4}, optional
429
+ Type of the DCT (see Notes). Default type is 2.
430
+ n : int, optional
431
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
432
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
433
+ default results in ``n = x.shape[axis]``.
434
+ axis : int, optional
435
+ Axis along which the idct is computed; the default is over the
436
+ last axis (i.e., ``axis=-1``).
437
+ norm : {"backward", "ortho", "forward"}, optional
438
+ Normalization mode (see Notes). Default is "backward".
439
+ overwrite_x : bool, optional
440
+ If True, the contents of `x` can be destroyed; the default is False.
441
+ workers : int, optional
442
+ Maximum number of workers to use for parallel computation. If negative,
443
+ the value wraps around from ``os.cpu_count()``.
444
+ See :func:`~scipy.fft.fft` for more details.
445
+ orthogonalize : bool, optional
446
+ Whether to use the orthogonalized IDCT variant (see Notes).
447
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
448
+
449
+ .. versionadded:: 1.8.0
450
+
451
+ Returns
452
+ -------
453
+ idct : ndarray of real
454
+ The transformed input array.
455
+
456
+ See Also
457
+ --------
458
+ dct : Forward DCT
459
+
460
+ Notes
461
+ -----
462
+ For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
463
+ MATLAB ``idct(x)``.
464
+
465
+ .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
466
+ correspondence with the inverse direct Fourier transform. To
467
+ recover it you must specify ``orthogonalize=False``.
468
+
469
+ For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
470
+ overall factor in both directions. By default, the transform is also
471
+ orthogonalized which for types 1, 2 and 3 means the transform definition is
472
+ modified to give orthogonality of the IDCT matrix (see `dct` for the full
473
+ definitions).
474
+
475
+ 'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
476
+
477
+ The IDCT is equivalent to a normal DCT except for the normalization and
478
+ type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
479
+ other's inverses.
480
+
481
+ Examples
482
+ --------
483
+ The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
484
+ inputs. The output is also real and even-symmetrical. Half of the IFFT
485
+ input is used to generate half of the IFFT output:
486
+
487
+ >>> from scipy.fft import ifft, idct
488
+ >>> import numpy as np
489
+ >>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
490
+ array([ 4., 3., 5., 10., 5., 3.])
491
+ >>> idct(np.array([ 30., -8., 6., -2.]), 1)
492
+ array([ 4., 3., 5., 10.])
493
+
494
+ """
495
+ return (Dispatchable(x, np.ndarray),)
496
+
497
+
498
+ @_dispatch
499
+ def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
500
+ orthogonalize=None):
501
+ r"""
502
+ Return the Discrete Sine Transform of arbitrary type sequence x.
503
+
504
+ Parameters
505
+ ----------
506
+ x : array_like
507
+ The input array.
508
+ type : {1, 2, 3, 4}, optional
509
+ Type of the DST (see Notes). Default type is 2.
510
+ n : int, optional
511
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
512
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
513
+ default results in ``n = x.shape[axis]``.
514
+ axis : int, optional
515
+ Axis along which the dst is computed; the default is over the
516
+ last axis (i.e., ``axis=-1``).
517
+ norm : {"backward", "ortho", "forward"}, optional
518
+ Normalization mode (see Notes). Default is "backward".
519
+ overwrite_x : bool, optional
520
+ If True, the contents of `x` can be destroyed; the default is False.
521
+ workers : int, optional
522
+ Maximum number of workers to use for parallel computation. If negative,
523
+ the value wraps around from ``os.cpu_count()``.
524
+ See :func:`~scipy.fft.fft` for more details.
525
+ orthogonalize : bool, optional
526
+ Whether to use the orthogonalized DST variant (see Notes).
527
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
528
+
529
+ .. versionadded:: 1.8.0
530
+
531
+ Returns
532
+ -------
533
+ dst : ndarray of reals
534
+ The transformed input array.
535
+
536
+ See Also
537
+ --------
538
+ idst : Inverse DST
539
+
540
+ Notes
541
+ -----
542
+ .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
543
+ correspondence with the direct Fourier transform. To recover
544
+ it you must specify ``orthogonalize=False``.
545
+
546
+ For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
547
+ overall factor in both directions. By default, the transform is also
548
+ orthogonalized which for types 2 and 3 means the transform definition is
549
+ modified to give orthogonality of the DST matrix (see below).
550
+
551
+ For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
552
+ scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
553
+
554
+ There are, theoretically, 8 types of the DST for different combinations of
555
+ even/odd boundary conditions and boundary off sets [1]_, only the first
556
+ 4 types are implemented in SciPy.
557
+
558
+ **Type I**
559
+
560
+ There are several definitions of the DST-I; we use the following for
561
+ ``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
562
+ :math:`n=N`.
563
+
564
+ .. math::
565
+
566
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
567
+
568
+ Note that the DST-I is only supported for input size > 1.
569
+ The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`.
570
+ The orthonormalized DST-I is exactly its own inverse.
571
+
572
+ ``orthogonalize`` has no effect here, as the DST-I matrix is already
573
+ orthogonal up to a scale factor of ``2N``.
574
+
575
+ **Type II**
576
+
577
+ There are several definitions of the DST-II; we use the following for
578
+ ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
579
+ :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1`
580
+
581
+ .. math::
582
+
583
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
584
+
585
+ If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
586
+ combined with ``norm="ortho"``, makes the corresponding matrix of
587
+ coefficients orthonormal (``O @ O.T = np.eye(N)``).
588
+
589
+ **Type III**
590
+
591
+ There are several definitions of the DST-III, we use the following (for
592
+ ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
593
+ even around :math:`n=N-1`
594
+
595
+ .. math::
596
+
597
+ y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
598
+ \frac{\pi(2k+1)(n+1)}{2N}\right)
599
+
600
+ If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
601
+ which, when combined with ``norm="ortho"``, makes the corresponding matrix
602
+ of coefficients orthonormal (``O @ O.T = np.eye(N)``).
603
+
604
+ The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
605
+ to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
606
+ orthonormalized DST-II.
607
+
608
+ **Type IV**
609
+
610
+ There are several definitions of the DST-IV, we use the following (for
611
+ ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and
612
+ even around :math:`n=N-0.5`
613
+
614
+ .. math::
615
+
616
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
617
+
618
+ ``orthogonalize`` has no effect here, as the DST-IV matrix is already
619
+ orthogonal up to a scale factor of ``2N``.
620
+
621
+ The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
622
+ orthonormalized DST-IV is exactly its own inverse.
623
+
624
+ References
625
+ ----------
626
+ .. [1] Wikipedia, "Discrete sine transform",
627
+ https://en.wikipedia.org/wiki/Discrete_sine_transform
628
+
629
+ """
630
+ return (Dispatchable(x, np.ndarray),)
631
+
632
+
633
+ @_dispatch
634
+ def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
635
+ workers=None, orthogonalize=None):
636
+ """
637
+ Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
638
+
639
+ Parameters
640
+ ----------
641
+ x : array_like
642
+ The input array.
643
+ type : {1, 2, 3, 4}, optional
644
+ Type of the DST (see Notes). Default type is 2.
645
+ n : int, optional
646
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
647
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
648
+ default results in ``n = x.shape[axis]``.
649
+ axis : int, optional
650
+ Axis along which the idst is computed; the default is over the
651
+ last axis (i.e., ``axis=-1``).
652
+ norm : {"backward", "ortho", "forward"}, optional
653
+ Normalization mode (see Notes). Default is "backward".
654
+ overwrite_x : bool, optional
655
+ If True, the contents of `x` can be destroyed; the default is False.
656
+ workers : int, optional
657
+ Maximum number of workers to use for parallel computation. If negative,
658
+ the value wraps around from ``os.cpu_count()``.
659
+ See :func:`~scipy.fft.fft` for more details.
660
+ orthogonalize : bool, optional
661
+ Whether to use the orthogonalized IDST variant (see Notes).
662
+ Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
663
+
664
+ .. versionadded:: 1.8.0
665
+
666
+ Returns
667
+ -------
668
+ idst : ndarray of real
669
+ The transformed input array.
670
+
671
+ See Also
672
+ --------
673
+ dst : Forward DST
674
+
675
+ Notes
676
+ -----
677
+ .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
678
+ correspondence with the inverse direct Fourier transform.
679
+
680
+ For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
681
+ overall factor in both directions. By default, the transform is also
682
+ orthogonalized which for types 2 and 3 means the transform definition is
683
+ modified to give orthogonality of the DST matrix (see `dst` for the full
684
+ definitions).
685
+
686
+ 'The' IDST is the IDST-II, which is the same as the normalized DST-III.
687
+
688
+ The IDST is equivalent to a normal DST except for the normalization and
689
+ type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
690
+ other's inverses.
691
+
692
+ """
693
+ return (Dispatchable(x, np.ndarray),)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy._lib._array_api import array_namespace
2
+ import numpy as np
3
+ from . import _pocketfft
4
+
5
+ __all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
6
+
7
+
8
+ def _execute(pocketfft_func, x, type, s, axes, norm,
9
+ overwrite_x, workers, orthogonalize):
10
+ xp = array_namespace(x)
11
+ x = np.asarray(x)
12
+ y = pocketfft_func(x, type, s, axes, norm,
13
+ overwrite_x=overwrite_x, workers=workers,
14
+ orthogonalize=orthogonalize)
15
+ return xp.asarray(y)
16
+
17
+
18
+ def dctn(x, type=2, s=None, axes=None, norm=None,
19
+ overwrite_x=False, workers=None, *, orthogonalize=None):
20
+ return _execute(_pocketfft.dctn, x, type, s, axes, norm,
21
+ overwrite_x, workers, orthogonalize)
22
+
23
+
24
+ def idctn(x, type=2, s=None, axes=None, norm=None,
25
+ overwrite_x=False, workers=None, *, orthogonalize=None):
26
+ return _execute(_pocketfft.idctn, x, type, s, axes, norm,
27
+ overwrite_x, workers, orthogonalize)
28
+
29
+
30
+ def dstn(x, type=2, s=None, axes=None, norm=None,
31
+ overwrite_x=False, workers=None, orthogonalize=None):
32
+ return _execute(_pocketfft.dstn, x, type, s, axes, norm,
33
+ overwrite_x, workers, orthogonalize)
34
+
35
+
36
+ def idstn(x, type=2, s=None, axes=None, norm=None,
37
+ overwrite_x=False, workers=None, *, orthogonalize=None):
38
+ return _execute(_pocketfft.idstn, x, type, s, axes, norm,
39
+ overwrite_x, workers, orthogonalize)
40
+
41
+
42
+ def dct(x, type=2, n=None, axis=-1, norm=None,
43
+ overwrite_x=False, workers=None, orthogonalize=None):
44
+ return _execute(_pocketfft.dct, x, type, n, axis, norm,
45
+ overwrite_x, workers, orthogonalize)
46
+
47
+
48
+ def idct(x, type=2, n=None, axis=-1, norm=None,
49
+ overwrite_x=False, workers=None, orthogonalize=None):
50
+ return _execute(_pocketfft.idct, x, type, n, axis, norm,
51
+ overwrite_x, workers, orthogonalize)
52
+
53
+
54
+ def dst(x, type=2, n=None, axis=-1, norm=None,
55
+ overwrite_x=False, workers=None, orthogonalize=None):
56
+ return _execute(_pocketfft.dst, x, type, n, axis, norm,
57
+ overwrite_x, workers, orthogonalize)
58
+
59
+
60
+ def idst(x, type=2, n=None, axis=-1, norm=None,
61
+ overwrite_x=False, workers=None, orthogonalize=None):
62
+ return _execute(_pocketfft.idst, x, type, n, axis, norm,
63
+ overwrite_x, workers, orthogonalize)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import scipy.fft
3
+ import threading
4
+
5
+ class _MockFunction:
6
+ def __init__(self, return_value = None):
7
+ self.number_calls = threading.local()
8
+ self.return_value = return_value
9
+ self.last_args = threading.local()
10
+
11
+ def __call__(self, *args, **kwargs):
12
+ if not hasattr(self.number_calls, 'c'):
13
+ self.number_calls.c = 0
14
+
15
+ self.number_calls.c += 1
16
+ self.last_args.l = (args, kwargs)
17
+ return self.return_value
18
+
19
+
20
+ fft = _MockFunction(np.random.random(10))
21
+ fft2 = _MockFunction(np.random.random(10))
22
+ fftn = _MockFunction(np.random.random(10))
23
+
24
+ ifft = _MockFunction(np.random.random(10))
25
+ ifft2 = _MockFunction(np.random.random(10))
26
+ ifftn = _MockFunction(np.random.random(10))
27
+
28
+ rfft = _MockFunction(np.random.random(10))
29
+ rfft2 = _MockFunction(np.random.random(10))
30
+ rfftn = _MockFunction(np.random.random(10))
31
+
32
+ irfft = _MockFunction(np.random.random(10))
33
+ irfft2 = _MockFunction(np.random.random(10))
34
+ irfftn = _MockFunction(np.random.random(10))
35
+
36
+ hfft = _MockFunction(np.random.random(10))
37
+ hfft2 = _MockFunction(np.random.random(10))
38
+ hfftn = _MockFunction(np.random.random(10))
39
+
40
+ ihfft = _MockFunction(np.random.random(10))
41
+ ihfft2 = _MockFunction(np.random.random(10))
42
+ ihfftn = _MockFunction(np.random.random(10))
43
+
44
+ dct = _MockFunction(np.random.random(10))
45
+ idct = _MockFunction(np.random.random(10))
46
+ dctn = _MockFunction(np.random.random(10))
47
+ idctn = _MockFunction(np.random.random(10))
48
+
49
+ dst = _MockFunction(np.random.random(10))
50
+ idst = _MockFunction(np.random.random(10))
51
+ dstn = _MockFunction(np.random.random(10))
52
+ idstn = _MockFunction(np.random.random(10))
53
+
54
+ fht = _MockFunction(np.random.random(10))
55
+ ifht = _MockFunction(np.random.random(10))
56
+
57
+
58
+ __ua_domain__ = "numpy.scipy.fft"
59
+
60
+
61
+ _implements = {
62
+ scipy.fft.fft: fft,
63
+ scipy.fft.fft2: fft2,
64
+ scipy.fft.fftn: fftn,
65
+ scipy.fft.ifft: ifft,
66
+ scipy.fft.ifft2: ifft2,
67
+ scipy.fft.ifftn: ifftn,
68
+ scipy.fft.rfft: rfft,
69
+ scipy.fft.rfft2: rfft2,
70
+ scipy.fft.rfftn: rfftn,
71
+ scipy.fft.irfft: irfft,
72
+ scipy.fft.irfft2: irfft2,
73
+ scipy.fft.irfftn: irfftn,
74
+ scipy.fft.hfft: hfft,
75
+ scipy.fft.hfft2: hfft2,
76
+ scipy.fft.hfftn: hfftn,
77
+ scipy.fft.ihfft: ihfft,
78
+ scipy.fft.ihfft2: ihfft2,
79
+ scipy.fft.ihfftn: ihfftn,
80
+ scipy.fft.dct: dct,
81
+ scipy.fft.idct: idct,
82
+ scipy.fft.dctn: dctn,
83
+ scipy.fft.idctn: idctn,
84
+ scipy.fft.dst: dst,
85
+ scipy.fft.idst: idst,
86
+ scipy.fft.dstn: dstn,
87
+ scipy.fft.idstn: idstn,
88
+ scipy.fft.fht: fht,
89
+ scipy.fft.ifht: ifht
90
+ }
91
+
92
+
93
+ def __ua_function__(method, args, kwargs):
94
+ fn = _implements.get(method)
95
+ return (fn(*args, **kwargs) if fn is not None
96
+ else NotImplemented)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ import numpy as np
4
+ import scipy.fft
5
+ from scipy.fft import _fftlog, _pocketfft, set_backend
6
+ from scipy.fft.tests import mock_backend
7
+
8
+ from numpy.testing import assert_allclose, assert_equal
9
+ import pytest
10
+
11
+ fnames = ('fft', 'fft2', 'fftn',
12
+ 'ifft', 'ifft2', 'ifftn',
13
+ 'rfft', 'rfft2', 'rfftn',
14
+ 'irfft', 'irfft2', 'irfftn',
15
+ 'dct', 'idct', 'dctn', 'idctn',
16
+ 'dst', 'idst', 'dstn', 'idstn',
17
+ 'fht', 'ifht')
18
+
19
+ np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn,
20
+ np.fft.ifft, np.fft.ifft2, np.fft.ifftn,
21
+ np.fft.rfft, np.fft.rfft2, np.fft.rfftn,
22
+ np.fft.irfft, np.fft.irfft2, np.fft.irfftn,
23
+ np.fft.hfft, _pocketfft.hfft2, _pocketfft.hfftn, # np has no hfftn
24
+ np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn,
25
+ _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn,
26
+ _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.idstn,
27
+ # must provide required kwargs for fht, ifht
28
+ partial(_fftlog.fht, dln=2, mu=0.5),
29
+ partial(_fftlog.ifht, dln=2, mu=0.5))
30
+
31
+ funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
32
+ scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
33
+ scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
34
+ scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
35
+ scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
36
+ scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn,
37
+ scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn,
38
+ scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn,
39
+ # must provide required kwargs for fht, ifht
40
+ partial(scipy.fft.fht, dln=2, mu=0.5),
41
+ partial(scipy.fft.ifht, dln=2, mu=0.5))
42
+
43
+ mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
44
+ mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
45
+ mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
46
+ mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
47
+ mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
48
+ mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn,
49
+ mock_backend.dct, mock_backend.idct,
50
+ mock_backend.dctn, mock_backend.idctn,
51
+ mock_backend.dst, mock_backend.idst,
52
+ mock_backend.dstn, mock_backend.idstn,
53
+ mock_backend.fht, mock_backend.ifht)
54
+
55
+
56
+ @pytest.mark.parametrize("func, np_func, mock", zip(funcs, np_funcs, mocks))
57
+ def test_backend_call(func, np_func, mock):
58
+ x = np.arange(20).reshape((10,2))
59
+ answer = np_func(x.astype(np.float64))
60
+ assert_allclose(func(x), answer, atol=1e-10)
61
+
62
+ with set_backend(mock_backend, only=True):
63
+ mock.number_calls.c = 0
64
+ y = func(x)
65
+ assert_equal(y, mock.return_value)
66
+ assert_equal(mock.number_calls.c, 1)
67
+
68
+ assert_allclose(func(x), answer, atol=1e-10)
69
+
70
+
71
+ plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
72
+ scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
73
+ scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
74
+ scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
75
+ scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
76
+ scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn)
77
+
78
+ plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
79
+ mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
80
+ mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
81
+ mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
82
+ mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
83
+ mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn)
84
+
85
+
86
+ @pytest.mark.parametrize("func, mock", zip(plan_funcs, plan_mocks))
87
+ def test_backend_plan(func, mock):
88
+ x = np.arange(20).reshape((10, 2))
89
+
90
+ with pytest.raises(NotImplementedError, match='precomputed plan'):
91
+ func(x, plan='foo')
92
+
93
+ with set_backend(mock_backend, only=True):
94
+ mock.number_calls.c = 0
95
+ y = func(x, plan='foo')
96
+ assert_equal(y, mock.return_value)
97
+ assert_equal(mock.number_calls.c, 1)
98
+ assert_equal(mock.last_args.l[1]['plan'], 'foo')
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import queue
2
+ import threading
3
+ import multiprocessing
4
+ import numpy as np
5
+ import pytest
6
+ from numpy.random import random
7
+ from numpy.testing import assert_array_almost_equal, assert_allclose
8
+ from pytest import raises as assert_raises
9
+ import scipy.fft as fft
10
+ from scipy.conftest import array_api_compatible
11
+ from scipy._lib._array_api import (
12
+ array_namespace, xp_size, xp_assert_close, xp_assert_equal
13
+ )
14
+
15
+ pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
16
+ skip_xp_backends = pytest.mark.skip_xp_backends
17
+
18
+
19
+ # Expected input dtypes. Note that `scipy.fft` is more flexible for numpy,
20
+ # but for C2C transforms like `fft.fft`, the array API standard only mandates
21
+ # that complex dtypes should work, float32/float64 aren't guaranteed to.
22
+ def get_expected_input_dtype(func, xp):
23
+ if func in [fft.fft, fft.fftn, fft.fft2,
24
+ fft.ifft, fft.ifftn, fft.ifft2,
25
+ fft.hfft, fft.hfftn, fft.hfft2,
26
+ fft.irfft, fft.irfftn, fft.irfft2]:
27
+ dtype = xp.complex128
28
+ elif func in [fft.rfft, fft.rfftn, fft.rfft2,
29
+ fft.ihfft, fft.ihfftn, fft.ihfft2]:
30
+ dtype = xp.float64
31
+ else:
32
+ raise ValueError(f'Unknown FFT function: {func}')
33
+
34
+ return dtype
35
+
36
+
37
+ def fft1(x):
38
+ L = len(x)
39
+ phase = -2j*np.pi*(np.arange(L)/float(L))
40
+ phase = np.arange(L).reshape(-1, 1) * phase
41
+ return np.sum(x*np.exp(phase), axis=1)
42
+
43
+ class TestFFT:
44
+
45
+ def test_identity(self, xp):
46
+ maxlen = 512
47
+ x = xp.asarray(random(maxlen) + 1j*random(maxlen))
48
+ xr = xp.asarray(random(maxlen))
49
+ # Check some powers of 2 and some primes
50
+ for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]:
51
+ xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
52
+ xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
53
+
54
+ @skip_xp_backends(np_only=True, reason='significant overhead for some backends')
55
+ def test_identity_extensive(self, xp):
56
+ maxlen = 512
57
+ x = xp.asarray(random(maxlen) + 1j*random(maxlen))
58
+ xr = xp.asarray(random(maxlen))
59
+ for i in range(1, maxlen):
60
+ xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
61
+ xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
62
+
63
+ def test_fft(self, xp):
64
+ x = random(30) + 1j*random(30)
65
+ expect = xp.asarray(fft1(x))
66
+ x = xp.asarray(x)
67
+ xp_assert_close(fft.fft(x), expect)
68
+ xp_assert_close(fft.fft(x, norm="backward"), expect)
69
+ xp_assert_close(fft.fft(x, norm="ortho"),
70
+ expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),)
71
+ xp_assert_close(fft.fft(x, norm="forward"), expect / 30)
72
+
73
+ @skip_xp_backends(np_only=True, reason='some backends allow `n=0`')
74
+ def test_fft_n(self, xp):
75
+ x = xp.asarray([1, 2, 3], dtype=xp.complex128)
76
+ assert_raises(ValueError, fft.fft, x, 0)
77
+
78
+ def test_ifft(self, xp):
79
+ x = xp.asarray(random(30) + 1j*random(30))
80
+ xp_assert_close(fft.ifft(fft.fft(x)), x)
81
+ for norm in ["backward", "ortho", "forward"]:
82
+ xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x)
83
+
84
+ def test_fft2(self, xp):
85
+ x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
86
+ expect = fft.fft(fft.fft(x, axis=1), axis=0)
87
+ xp_assert_close(fft.fft2(x), expect)
88
+ xp_assert_close(fft.fft2(x, norm="backward"), expect)
89
+ xp_assert_close(fft.fft2(x, norm="ortho"),
90
+ expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
91
+ xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20))
92
+
93
+ def test_ifft2(self, xp):
94
+ x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
95
+ expect = fft.ifft(fft.ifft(x, axis=1), axis=0)
96
+ xp_assert_close(fft.ifft2(x), expect)
97
+ xp_assert_close(fft.ifft2(x, norm="backward"), expect)
98
+ xp_assert_close(fft.ifft2(x, norm="ortho"),
99
+ expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
100
+ xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20))
101
+
102
+ def test_fftn(self, xp):
103
+ x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
104
+ expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0)
105
+ xp_assert_close(fft.fftn(x), expect)
106
+ xp_assert_close(fft.fftn(x, norm="backward"), expect)
107
+ xp_assert_close(fft.fftn(x, norm="ortho"),
108
+ expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
109
+ xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10))
110
+
111
+ def test_ifftn(self, xp):
112
+ x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
113
+ expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0)
114
+ xp_assert_close(fft.ifftn(x), expect, rtol=1e-7)
115
+ xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7)
116
+ xp_assert_close(
117
+ fft.ifftn(x, norm="ortho"),
118
+ fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
119
+ )
120
+ xp_assert_close(fft.ifftn(x, norm="forward"),
121
+ expect * (30 * 20 * 10),
122
+ rtol=1e-7)
123
+
124
+ def test_rfft(self, xp):
125
+ x = xp.asarray(random(29), dtype=xp.float64)
126
+ for n in [xp_size(x), 2*xp_size(x)]:
127
+ for norm in [None, "backward", "ortho", "forward"]:
128
+ xp_assert_close(fft.rfft(x, n=n, norm=norm),
129
+ fft.fft(xp.asarray(x, dtype=xp.complex128),
130
+ n=n, norm=norm)[:(n//2 + 1)])
131
+ xp_assert_close(
132
+ fft.rfft(x, n=n, norm="ortho"),
133
+ fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64))
134
+ )
135
+
136
+ def test_irfft(self, xp):
137
+ x = xp.asarray(random(30))
138
+ xp_assert_close(fft.irfft(fft.rfft(x)), x)
139
+ for norm in ["backward", "ortho", "forward"]:
140
+ xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x)
141
+
142
+ def test_rfft2(self, xp):
143
+ x = xp.asarray(random((30, 20)), dtype=xp.float64)
144
+ expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
145
+ xp_assert_close(fft.rfft2(x), expect)
146
+ xp_assert_close(fft.rfft2(x, norm="backward"), expect)
147
+ xp_assert_close(fft.rfft2(x, norm="ortho"),
148
+ expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
149
+ xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20))
150
+
151
+ def test_irfft2(self, xp):
152
+ x = xp.asarray(random((30, 20)))
153
+ xp_assert_close(fft.irfft2(fft.rfft2(x)), x)
154
+ for norm in ["backward", "ortho", "forward"]:
155
+ xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x)
156
+
157
+ def test_rfftn(self, xp):
158
+ x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
159
+ expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
160
+ xp_assert_close(fft.rfftn(x), expect)
161
+ xp_assert_close(fft.rfftn(x, norm="backward"), expect)
162
+ xp_assert_close(fft.rfftn(x, norm="ortho"),
163
+ expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
164
+ xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10))
165
+
166
+ def test_irfftn(self, xp):
167
+ x = xp.asarray(random((30, 20, 10)))
168
+ xp_assert_close(fft.irfftn(fft.rfftn(x)), x)
169
+ for norm in ["backward", "ortho", "forward"]:
170
+ xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x)
171
+
172
+ def test_hfft(self, xp):
173
+ x = random(14) + 1j*random(14)
174
+ x_herm = np.concatenate((random(1), x, random(1)))
175
+ x = np.concatenate((x_herm, x[::-1].conj()))
176
+ x = xp.asarray(x)
177
+ x_herm = xp.asarray(x_herm)
178
+ expect = xp.real(fft.fft(x))
179
+ xp_assert_close(fft.hfft(x_herm), expect)
180
+ xp_assert_close(fft.hfft(x_herm, norm="backward"), expect)
181
+ xp_assert_close(fft.hfft(x_herm, norm="ortho"),
182
+ expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)))
183
+ xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30)
184
+
185
+ def test_ihfft(self, xp):
186
+ x = random(14) + 1j*random(14)
187
+ x_herm = np.concatenate((random(1), x, random(1)))
188
+ x = np.concatenate((x_herm, x[::-1].conj()))
189
+ x = xp.asarray(x)
190
+ x_herm = xp.asarray(x_herm)
191
+ xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm)
192
+ for norm in ["backward", "ortho", "forward"]:
193
+ xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm)
194
+
195
+ def test_hfft2(self, xp):
196
+ x = xp.asarray(random((30, 20)))
197
+ xp_assert_close(fft.hfft2(fft.ihfft2(x)), x)
198
+ for norm in ["backward", "ortho", "forward"]:
199
+ xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x)
200
+
201
+ def test_ihfft2(self, xp):
202
+ x = xp.asarray(random((30, 20)), dtype=xp.float64)
203
+ expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
204
+ xp_assert_close(fft.ihfft2(x), expect)
205
+ xp_assert_close(fft.ihfft2(x, norm="backward"), expect)
206
+ xp_assert_close(
207
+ fft.ihfft2(x, norm="ortho"),
208
+ expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))
209
+ )
210
+ xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20))
211
+
212
+ def test_hfftn(self, xp):
213
+ x = xp.asarray(random((30, 20, 10)))
214
+ xp_assert_close(fft.hfftn(fft.ihfftn(x)), x)
215
+ for norm in ["backward", "ortho", "forward"]:
216
+ xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x)
217
+
218
+ def test_ihfftn(self, xp):
219
+ x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
220
+ expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
221
+ xp_assert_close(expect, fft.ihfftn(x))
222
+ xp_assert_close(expect, fft.ihfftn(x, norm="backward"))
223
+ xp_assert_close(
224
+ fft.ihfftn(x, norm="ortho"),
225
+ expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
226
+ )
227
+ xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10))
228
+
229
+ def _check_axes(self, op, xp):
230
+ dtype = get_expected_input_dtype(op, xp)
231
+ x = xp.asarray(random((30, 20, 10)), dtype=dtype)
232
+ axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
233
+ xp_test = array_namespace(x)
234
+ for a in axes:
235
+ op_tr = op(xp_test.permute_dims(x, axes=a))
236
+ tr_op = xp_test.permute_dims(op(x, axes=a), axes=a)
237
+ xp_assert_close(op_tr, tr_op)
238
+
239
+ @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, fft.rfftn, fft.irfftn])
240
+ def test_axes_standard(self, op, xp):
241
+ self._check_axes(op, xp)
242
+
243
+ @pytest.mark.parametrize("op", [fft.hfftn, fft.ihfftn])
244
+ def test_axes_non_standard(self, op, xp):
245
+ self._check_axes(op, xp)
246
+
247
+ @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn,
248
+ fft.rfftn, fft.irfftn])
249
+ def test_axes_subset_with_shape_standard(self, op, xp):
250
+ dtype = get_expected_input_dtype(op, xp)
251
+ x = xp.asarray(random((16, 8, 4)), dtype=dtype)
252
+ axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
253
+ xp_test = array_namespace(x)
254
+ for a in axes:
255
+ # different shape on the first two axes
256
+ shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
257
+ for ax in range(x.ndim)])
258
+ # transform only the first two axes
259
+ op_tr = op(xp_test.permute_dims(x, axes=a),
260
+ s=shape[:2], axes=(0, 1))
261
+ tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]),
262
+ axes=a)
263
+ xp_assert_close(op_tr, tr_op)
264
+
265
+ @pytest.mark.parametrize("op", [fft.fft2, fft.ifft2,
266
+ fft.rfft2, fft.irfft2,
267
+ fft.hfft2, fft.ihfft2,
268
+ fft.hfftn, fft.ihfftn])
269
+ def test_axes_subset_with_shape_non_standard(self, op, xp):
270
+ dtype = get_expected_input_dtype(op, xp)
271
+ x = xp.asarray(random((16, 8, 4)), dtype=dtype)
272
+ axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
273
+ xp_test = array_namespace(x)
274
+ for a in axes:
275
+ # different shape on the first two axes
276
+ shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
277
+ for ax in range(x.ndim)])
278
+ # transform only the first two axes
279
+ op_tr = op(xp_test.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1))
280
+ tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a)
281
+ xp_assert_close(op_tr, tr_op)
282
+
283
+ def test_all_1d_norm_preserving(self, xp):
284
+ # verify that round-trip transforms are norm-preserving
285
+ x = xp.asarray(random(30), dtype=xp.float64)
286
+ xp_test = array_namespace(x)
287
+ x_norm = xp_test.linalg.vector_norm(x)
288
+ n = xp_size(x) * 2
289
+ func_pairs = [(fft.rfft, fft.irfft),
290
+ # hfft: order so the first function takes x.size samples
291
+ # (necessary for comparison to x_norm above)
292
+ (fft.ihfft, fft.hfft),
293
+ # functions that expect complex dtypes at the end
294
+ (fft.fft, fft.ifft),
295
+ ]
296
+ for forw, back in func_pairs:
297
+ if forw == fft.fft:
298
+ x = xp.asarray(x, dtype=xp.complex128)
299
+ x_norm = xp_test.linalg.vector_norm(x)
300
+ for n in [xp_size(x), 2*xp_size(x)]:
301
+ for norm in ['backward', 'ortho', 'forward']:
302
+ tmp = forw(x, n=n, norm=norm)
303
+ tmp = back(tmp, n=n, norm=norm)
304
+ xp_assert_close(xp_test.linalg.vector_norm(tmp), x_norm)
305
+
306
+ @skip_xp_backends(np_only=True)
307
+ @pytest.mark.parametrize("dtype", [np.float16, np.longdouble])
308
+ def test_dtypes_nonstandard(self, dtype):
309
+ x = random(30).astype(dtype)
310
+ out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble}
311
+ x_complex = x.astype(out_dtypes[dtype])
312
+
313
+ res_fft = fft.ifft(fft.fft(x))
314
+ res_rfft = fft.irfft(fft.rfft(x))
315
+ res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
316
+ # Check both numerical results and exact dtype matches
317
+ assert_array_almost_equal(res_fft, x_complex)
318
+ assert_array_almost_equal(res_rfft, x)
319
+ assert_array_almost_equal(res_hfft, x)
320
+ assert res_fft.dtype == x_complex.dtype
321
+ assert res_rfft.dtype == np.result_type(np.float32, x.dtype)
322
+ assert res_hfft.dtype == np.result_type(np.float32, x.dtype)
323
+
324
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
325
+ def test_dtypes_real(self, dtype, xp):
326
+ x = xp.asarray(random(30), dtype=getattr(xp, dtype))
327
+
328
+ res_rfft = fft.irfft(fft.rfft(x))
329
+ res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
330
+ # Check both numerical results and exact dtype matches
331
+ xp_assert_close(res_rfft, x)
332
+ xp_assert_close(res_hfft, x)
333
+
334
+ @pytest.mark.parametrize("dtype", ["complex64", "complex128"])
335
+ def test_dtypes_complex(self, dtype, xp):
336
+ rng = np.random.default_rng(1234)
337
+ x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype))
338
+
339
+ res_fft = fft.ifft(fft.fft(x))
340
+ # Check both numerical results and exact dtype matches
341
+ xp_assert_close(res_fft, x)
342
+
343
+ @skip_xp_backends(np_only=True,
344
+ reason='array-likes only supported for NumPy backend')
345
+ @pytest.mark.parametrize("op", [fft.fft, fft.ifft,
346
+ fft.fft2, fft.ifft2,
347
+ fft.fftn, fft.ifftn,
348
+ fft.rfft, fft.irfft,
349
+ fft.rfft2, fft.irfft2,
350
+ fft.rfftn, fft.irfftn,
351
+ fft.hfft, fft.ihfft,
352
+ fft.hfft2, fft.ihfft2,
353
+ fft.hfftn, fft.ihfftn,])
354
+ def test_array_like(self, xp, op):
355
+ x = [[[1.0, 1.0], [1.0, 1.0]],
356
+ [[1.0, 1.0], [1.0, 1.0]],
357
+ [[1.0, 1.0], [1.0, 1.0]]]
358
+ xp_assert_close(op(x), op(xp.asarray(x)))
359
+
360
+
361
+ @skip_xp_backends(np_only=True)
362
+ @pytest.mark.parametrize(
363
+ "dtype",
364
+ [np.float32, np.float64, np.longdouble,
365
+ np.complex64, np.complex128, np.clongdouble])
366
+ @pytest.mark.parametrize("order", ["F", 'non-contiguous'])
367
+ @pytest.mark.parametrize(
368
+ "fft",
369
+ [fft.fft, fft.fft2, fft.fftn,
370
+ fft.ifft, fft.ifft2, fft.ifftn])
371
+ def test_fft_with_order(dtype, order, fft):
372
+ # Check that FFT/IFFT produces identical results for C, Fortran and
373
+ # non contiguous arrays
374
+ rng = np.random.RandomState(42)
375
+ X = rng.rand(8, 7, 13).astype(dtype, copy=False)
376
+ if order == 'F':
377
+ Y = np.asfortranarray(X)
378
+ else:
379
+ # Make a non contiguous array
380
+ Y = X[::-1]
381
+ X = np.ascontiguousarray(X[::-1])
382
+
383
+ if fft.__name__.endswith('fft'):
384
+ for axis in range(3):
385
+ X_res = fft(X, axis=axis)
386
+ Y_res = fft(Y, axis=axis)
387
+ assert_array_almost_equal(X_res, Y_res)
388
+ elif fft.__name__.endswith(('fft2', 'fftn')):
389
+ axes = [(0, 1), (1, 2), (0, 2)]
390
+ if fft.__name__.endswith('fftn'):
391
+ axes.extend([(0,), (1,), (2,), None])
392
+ for ax in axes:
393
+ X_res = fft(X, axes=ax)
394
+ Y_res = fft(Y, axes=ax)
395
+ assert_array_almost_equal(X_res, Y_res)
396
+ else:
397
+ raise ValueError
398
+
399
+
400
+ @skip_xp_backends(cpu_only=True)
401
+ class TestFFTThreadSafe:
402
+ threads = 16
403
+ input_shape = (800, 200)
404
+
405
+ def _test_mtsame(self, func, *args, xp=None):
406
+ def worker(args, q):
407
+ q.put(func(*args))
408
+
409
+ q = queue.Queue()
410
+ expected = func(*args)
411
+
412
+ # Spin off a bunch of threads to call the same function simultaneously
413
+ t = [threading.Thread(target=worker, args=(args, q))
414
+ for i in range(self.threads)]
415
+ [x.start() for x in t]
416
+
417
+ [x.join() for x in t]
418
+
419
+ # Make sure all threads returned the correct value
420
+ for i in range(self.threads):
421
+ xp_assert_equal(
422
+ q.get(timeout=5), expected,
423
+ err_msg='Function returned wrong value in multithreaded context'
424
+ )
425
+
426
+ def test_fft(self, xp):
427
+ a = xp.ones(self.input_shape, dtype=xp.complex128)
428
+ self._test_mtsame(fft.fft, a, xp=xp)
429
+
430
+ def test_ifft(self, xp):
431
+ a = xp.full(self.input_shape, 1+0j)
432
+ self._test_mtsame(fft.ifft, a, xp=xp)
433
+
434
+ def test_rfft(self, xp):
435
+ a = xp.ones(self.input_shape)
436
+ self._test_mtsame(fft.rfft, a, xp=xp)
437
+
438
+ def test_irfft(self, xp):
439
+ a = xp.full(self.input_shape, 1+0j)
440
+ self._test_mtsame(fft.irfft, a, xp=xp)
441
+
442
+ def test_hfft(self, xp):
443
+ a = xp.ones(self.input_shape, dtype=xp.complex64)
444
+ self._test_mtsame(fft.hfft, a, xp=xp)
445
+
446
+ def test_ihfft(self, xp):
447
+ a = xp.ones(self.input_shape)
448
+ self._test_mtsame(fft.ihfft, a, xp=xp)
449
+
450
+
451
+ @skip_xp_backends(np_only=True)
452
+ @pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft])
453
+ def test_multiprocess(func):
454
+ # Test that fft still works after fork (gh-10422)
455
+
456
+ with multiprocessing.Pool(2) as p:
457
+ res = p.map(func, [np.ones(100) for _ in range(4)])
458
+
459
+ expect = func(np.ones(100))
460
+ for x in res:
461
+ assert_allclose(x, expect)
462
+
463
+
464
+ class TestIRFFTN:
465
+
466
+ def test_not_last_axis_success(self, xp):
467
+ ar, ai = np.random.random((2, 16, 8, 32))
468
+ a = ar + 1j*ai
469
+ a = xp.asarray(a)
470
+
471
+ axes = (-2,)
472
+
473
+ # Should not raise error
474
+ fft.irfftn(a, axes=axes)
475
+
476
+
477
+ @pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft,
478
+ fft.fftn, fft.ifftn,
479
+ fft.rfftn, fft.irfftn, fft.hfft, fft.ihfft])
480
+ def test_non_standard_params(func, xp):
481
+ if func in [fft.rfft, fft.rfftn, fft.ihfft]:
482
+ dtype = xp.float64
483
+ else:
484
+ dtype = xp.complex128
485
+
486
+ if xp.__name__ != 'numpy':
487
+ x = xp.asarray([1, 2, 3], dtype=dtype)
488
+ # func(x) should not raise an exception
489
+ func(x)
490
+ assert_raises(ValueError, func, x, workers=2)
491
+ # `plan` param is not tested since SciPy does not use it currently
492
+ # but should be tested if it comes into use
493
+
494
+
495
+ @pytest.mark.parametrize("dtype", ['float32', 'float64'])
496
+ @pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.irfft,
497
+ fft.fftn, fft.ifftn,
498
+ fft.irfftn, fft.hfft,])
499
+ def test_real_input(func, dtype, xp):
500
+ x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype))
501
+ # func(x) should not raise an exception
502
+ func(x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import math
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from scipy.fft._fftlog import fht, ifht, fhtoffset
8
+ from scipy.special import poch
9
+
10
+ from scipy.conftest import array_api_compatible
11
+ from scipy._lib._array_api import xp_assert_close, xp_assert_less, array_namespace
12
+
13
+ pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),]
14
+ skip_xp_backends = pytest.mark.skip_xp_backends
15
+
16
+
17
+ def test_fht_agrees_with_fftlog(xp):
18
+ # check that fht numerically agrees with the output from Fortran FFTLog,
19
+ # the results were generated with the provided `fftlogtest` program,
20
+ # after fixing how the k array is generated (divide range by n-1, not n)
21
+
22
+ # test function, analytical Hankel transform is of the same form
23
+ def f(r, mu):
24
+ return r**(mu+1)*np.exp(-r**2/2)
25
+
26
+ r = np.logspace(-4, 4, 16)
27
+
28
+ dln = np.log(r[1]/r[0])
29
+ mu = 0.3
30
+ offset = 0.0
31
+ bias = 0.0
32
+
33
+ a = xp.asarray(f(r, mu))
34
+
35
+ # test 1: compute as given
36
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
37
+ theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
38
+ -0.1949518286432330E-02, +0.3789220182554077E-02,
39
+ +0.5093959119952945E-03, +0.2785387803618774E-01,
40
+ +0.9944952700848897E-01, +0.4599202164586588E+00,
41
+ +0.3157462160881342E+00, -0.8201236844404755E-03,
42
+ -0.7834031308271878E-03, +0.3931444945110708E-03,
43
+ -0.2697710625194777E-03, +0.3568398050238820E-03,
44
+ -0.5554454827797206E-03, +0.8286331026468585E-03]
45
+ theirs = xp.asarray(theirs, dtype=xp.float64)
46
+ xp_assert_close(ours, theirs)
47
+
48
+ # test 2: change to optimal offset
49
+ offset = fhtoffset(dln, mu, bias=bias)
50
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
51
+ theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
52
+ +0.3150140927838524E-03, +0.9149121960963704E-03,
53
+ +0.5808089753959363E-02, +0.2548065256377240E-01,
54
+ +0.1339477692089897E+00, +0.4821530509479356E+00,
55
+ +0.2659899781579785E+00, -0.1116475278448113E-01,
56
+ +0.1791441617592385E-02, -0.4181810476548056E-03,
57
+ +0.1314963536765343E-03, -0.5422057743066297E-04,
58
+ +0.3208681804170443E-04, -0.2696849476008234E-04]
59
+ theirs = xp.asarray(theirs, dtype=xp.float64)
60
+ xp_assert_close(ours, theirs)
61
+
62
+ # test 3: positive bias
63
+ bias = 0.8
64
+ offset = fhtoffset(dln, mu, bias=bias)
65
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
66
+ theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
67
+ +0.1065374386206564E+00, -0.5121739602708132E-01,
68
+ +0.2636649319269470E-01, +0.1697209218849693E-01,
69
+ +0.1250215614723183E+00, +0.4739583261486729E+00,
70
+ +0.2841149874912028E+00, -0.8312764741645729E-02,
71
+ +0.1024233505508988E-02, -0.1644902767389120E-03,
72
+ +0.3305775476926270E-04, -0.7786993194882709E-05,
73
+ +0.1962258449520547E-05, -0.8977895734909250E-06]
74
+ theirs = xp.asarray(theirs, dtype=xp.float64)
75
+ xp_assert_close(ours, theirs)
76
+
77
+ # test 4: negative bias
78
+ bias = -0.8
79
+ offset = fhtoffset(dln, mu, bias=bias)
80
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
81
+ theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
82
+ +0.2123969254700955E-03, +0.1009558244834628E-02,
83
+ +0.5131386375222176E-02, +0.2461678673516286E-01,
84
+ +0.1235812845384476E+00, +0.4719570096404403E+00,
85
+ +0.2893487490631317E+00, -0.1686570611318716E-01,
86
+ +0.2231398155172505E-01, -0.1480742256379873E-01,
87
+ +0.1692387813500801E+00, +0.3097490354365797E+00,
88
+ +2.7593607182401860E+00, 10.5251075070045800E+00]
89
+ theirs = xp.asarray(theirs, dtype=xp.float64)
90
+ xp_assert_close(ours, theirs)
91
+
92
+
93
+ @pytest.mark.parametrize('optimal', [True, False])
94
+ @pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
95
+ @pytest.mark.parametrize('bias', [0, 0.1, -0.1])
96
+ @pytest.mark.parametrize('n', [64, 63])
97
+ def test_fht_identity(n, bias, offset, optimal, xp):
98
+ rng = np.random.RandomState(3491349965)
99
+
100
+ a = xp.asarray(rng.standard_normal(n))
101
+ dln = rng.uniform(-1, 1)
102
+ mu = rng.uniform(-2, 2)
103
+
104
+ if optimal:
105
+ offset = fhtoffset(dln, mu, initial=offset, bias=bias)
106
+
107
+ A = fht(a, dln, mu, offset=offset, bias=bias)
108
+ a_ = ifht(A, dln, mu, offset=offset, bias=bias)
109
+
110
+ xp_assert_close(a_, a, rtol=1.5e-7)
111
+
112
+
113
+
114
+
115
+ @pytest.mark.thread_unsafe
116
+ def test_fht_special_cases(xp):
117
+ rng = np.random.RandomState(3491349965)
118
+
119
+ a = xp.asarray(rng.standard_normal(64))
120
+ dln = rng.uniform(-1, 1)
121
+
122
+ # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...}
123
+
124
+ # case 1: x in M, y in M => well-defined transform
125
+ mu, bias = -4.0, 1.0
126
+ with warnings.catch_warnings(record=True) as record:
127
+ fht(a, dln, mu, bias=bias)
128
+ assert not record, 'fht warned about a well-defined transform'
129
+
130
+ # case 2: x not in M, y in M => well-defined transform
131
+ mu, bias = -2.5, 0.5
132
+ with warnings.catch_warnings(record=True) as record:
133
+ fht(a, dln, mu, bias=bias)
134
+ assert not record, 'fht warned about a well-defined transform'
135
+
136
+ # with fht_lock:
137
+ # case 3: x in M, y not in M => singular transform
138
+ mu, bias = -3.5, 0.5
139
+ with pytest.warns(Warning) as record:
140
+ fht(a, dln, mu, bias=bias)
141
+ assert record, 'fht did not warn about a singular transform'
142
+
143
+ # with fht_lock:
144
+ # case 4: x not in M, y in M => singular inverse transform
145
+ mu, bias = -2.5, 0.5
146
+ with pytest.warns(Warning) as record:
147
+ ifht(a, dln, mu, bias=bias)
148
+ assert record, 'ifht did not warn about a singular transform'
149
+
150
+
151
+ @pytest.mark.parametrize('n', [64, 63])
152
+ def test_fht_exact(n, xp):
153
+ rng = np.random.RandomState(3491349965)
154
+
155
+ # for a(r) a power law r^\gamma, the fast Hankel transform produces the
156
+ # exact continuous Hankel transform if biased with q = \gamma
157
+
158
+ mu = rng.uniform(0, 3)
159
+
160
+ # convergence of HT: -1-mu < gamma < 1/2
161
+ gamma = rng.uniform(-1-mu, 1/2)
162
+
163
+ r = np.logspace(-2, 2, n)
164
+ a = xp.asarray(r**gamma)
165
+
166
+ dln = np.log(r[1]/r[0])
167
+
168
+ offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
169
+
170
+ A = fht(a, dln, mu, offset=offset, bias=gamma)
171
+
172
+ k = np.exp(offset)/r[::-1]
173
+
174
+ # analytical result
175
+ At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma))
176
+
177
+ xp_assert_close(A, At)
178
+
179
+ @skip_xp_backends(np_only=True,
180
+ reason='array-likes only supported for NumPy backend')
181
+ @pytest.mark.parametrize("op", [fht, ifht])
182
+ def test_array_like(xp, op):
183
+ x = [[[1.0, 1.0], [1.0, 1.0]],
184
+ [[1.0, 1.0], [1.0, 1.0]],
185
+ [[1.0, 1.0], [1.0, 1.0]]]
186
+ xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0))
187
+
188
+ @pytest.mark.parametrize('n', [128, 129])
189
+ def test_gh_21661(xp, n):
190
+ one = xp.asarray(1.0)
191
+ xp_test = array_namespace(one)
192
+ mu = 0.0
193
+ r = np.logspace(-7, 1, n)
194
+ dln = math.log(r[1] / r[0])
195
+ offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu)
196
+ r = xp.asarray(r, dtype=one.dtype)
197
+ k = math.exp(offset) / xp_test.flip(r, axis=-1)
198
+
199
+ def f(x, mu):
200
+ return x**(mu + 1)*xp.exp(-x**2/2)
201
+
202
+ a_r = f(r, mu)
203
+ fht_val = fht(a_r, dln, mu=mu, offset=offset)
204
+ a_k = f(k, mu)
205
+ rel_err = xp.max(xp.abs((fht_val - a_k) / a_k))
206
+ xp_assert_less(rel_err, xp.asarray(7.28e+16)[()])
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Includes test functions for fftpack.helper module
2
+
3
+ Copied from fftpack.helper by Pearu Peterson, October 2005
4
+ Modified for Array API, 2023
5
+
6
+ """
7
+ from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes
8
+ from numpy.testing import assert_equal
9
+ from pytest import raises as assert_raises
10
+ import pytest
11
+ import numpy as np
12
+ import sys
13
+ from scipy.conftest import array_api_compatible
14
+ from scipy._lib._array_api import (
15
+ xp_assert_close, get_xp_devices, xp_device, array_namespace
16
+ )
17
+ from scipy import fft
18
+
19
+ pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
20
+ skip_xp_backends = pytest.mark.skip_xp_backends
21
+
22
+ _5_smooth_numbers = [
23
+ 2, 3, 4, 5, 6, 8, 9, 10,
24
+ 2 * 3 * 5,
25
+ 2**3 * 3**5,
26
+ 2**3 * 3**3 * 5**2,
27
+ ]
28
+
29
+ def test_next_fast_len():
30
+ for n in _5_smooth_numbers:
31
+ assert_equal(next_fast_len(n), n)
32
+
33
+
34
+ def _assert_n_smooth(x, n):
35
+ x_orig = x
36
+ if n < 2:
37
+ assert False
38
+
39
+ while True:
40
+ q, r = divmod(x, 2)
41
+ if r != 0:
42
+ break
43
+ x = q
44
+
45
+ for d in range(3, n+1, 2):
46
+ while True:
47
+ q, r = divmod(x, d)
48
+ if r != 0:
49
+ break
50
+ x = q
51
+
52
+ assert x == 1, \
53
+ f'x={x_orig} is not {n}-smooth, remainder={x}'
54
+
55
+
56
+ @skip_xp_backends(np_only=True)
57
+ class TestNextFastLen:
58
+
59
+ def test_next_fast_len(self):
60
+ np.random.seed(1234)
61
+
62
+ def nums():
63
+ yield from range(1, 1000)
64
+ yield 2**5 * 3**5 * 4**5 + 1
65
+
66
+ for n in nums():
67
+ m = next_fast_len(n)
68
+ _assert_n_smooth(m, 11)
69
+ assert m == next_fast_len(n, False)
70
+
71
+ m = next_fast_len(n, True)
72
+ _assert_n_smooth(m, 5)
73
+
74
+ def test_np_integers(self):
75
+ ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64]
76
+ for ityp in ITYPES:
77
+ x = ityp(12345)
78
+ testN = next_fast_len(x)
79
+ assert_equal(testN, next_fast_len(int(x)))
80
+
81
+ def testnext_fast_len_small(self):
82
+ hams = {
83
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15,
84
+ 16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000
85
+ }
86
+ for x, y in hams.items():
87
+ assert_equal(next_fast_len(x, True), y)
88
+
89
+ @pytest.mark.xfail(sys.maxsize < 2**32,
90
+ reason="Hamming Numbers too large for 32-bit",
91
+ raises=ValueError, strict=True)
92
+ def testnext_fast_len_big(self):
93
+ hams = {
94
+ 510183360: 510183360, 510183360 + 1: 512000000,
95
+ 511000000: 512000000,
96
+ 854296875: 854296875, 854296875 + 1: 859963392,
97
+ 196608000000: 196608000000, 196608000000 + 1: 196830000000,
98
+ 8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208,
99
+ 206391214080000: 206391214080000,
100
+ 206391214080000 + 1: 206624260800000,
101
+ 470184984576000: 470184984576000,
102
+ 470184984576000 + 1: 470715894135000,
103
+ 7222041363087360: 7222041363087360,
104
+ 7222041363087360 + 1: 7230196133913600,
105
+ # power of 5 5**23
106
+ 11920928955078125: 11920928955078125,
107
+ 11920928955078125 - 1: 11920928955078125,
108
+ # power of 3 3**34
109
+ 16677181699666569: 16677181699666569,
110
+ 16677181699666569 - 1: 16677181699666569,
111
+ # power of 2 2**54
112
+ 18014398509481984: 18014398509481984,
113
+ 18014398509481984 - 1: 18014398509481984,
114
+ # above this, int(ceil(n)) == int(ceil(n+1))
115
+ 19200000000000000: 19200000000000000,
116
+ 19200000000000000 + 1: 19221679687500000,
117
+ 288230376151711744: 288230376151711744,
118
+ 288230376151711744 + 1: 288325195312500000,
119
+ 288325195312500000 - 1: 288325195312500000,
120
+ 288325195312500000: 288325195312500000,
121
+ 288325195312500000 + 1: 288555831593533440,
122
+ }
123
+ for x, y in hams.items():
124
+ assert_equal(next_fast_len(x, True), y)
125
+
126
+ def test_keyword_args(self):
127
+ assert next_fast_len(11, real=True) == 12
128
+ assert next_fast_len(target=7, real=False) == 7
129
+
130
+ @skip_xp_backends(np_only=True)
131
+ class TestPrevFastLen:
132
+
133
+ def test_prev_fast_len(self):
134
+ np.random.seed(1234)
135
+
136
+ def nums():
137
+ yield from range(1, 1000)
138
+ yield 2**5 * 3**5 * 4**5 + 1
139
+
140
+ for n in nums():
141
+ m = prev_fast_len(n)
142
+ _assert_n_smooth(m, 11)
143
+ assert m == prev_fast_len(n, False)
144
+
145
+ m = prev_fast_len(n, True)
146
+ _assert_n_smooth(m, 5)
147
+
148
+ def test_np_integers(self):
149
+ ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32,
150
+ np.uint64]
151
+ for ityp in ITYPES:
152
+ x = ityp(12345)
153
+ testN = prev_fast_len(x)
154
+ assert_equal(testN, prev_fast_len(int(x)))
155
+
156
+ testN = prev_fast_len(x, real=True)
157
+ assert_equal(testN, prev_fast_len(int(x), real=True))
158
+
159
+ def testprev_fast_len_small(self):
160
+ hams = {
161
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15,
162
+ 16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000
163
+ }
164
+ for x, y in hams.items():
165
+ assert_equal(prev_fast_len(x, True), y)
166
+
167
+ hams = {
168
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10,
169
+ 11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18,
170
+ 19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121,
171
+ 1021: 1008, 1536: 1536, 51200000: 51200000
172
+ }
173
+ for x, y in hams.items():
174
+ assert_equal(prev_fast_len(x, False), y)
175
+
176
+ @pytest.mark.xfail(sys.maxsize < 2**32,
177
+ reason="Hamming Numbers too large for 32-bit",
178
+ raises=ValueError, strict=True)
179
+ def testprev_fast_len_big(self):
180
+ hams = {
181
+ # 2**6 * 3**13 * 5**1
182
+ 510183360: 510183360,
183
+ 510183360 + 1: 510183360,
184
+ 510183360 - 1: 509607936, # 2**21 * 3**5
185
+ # 2**6 * 5**6 * 7**1 * 73**1
186
+ 511000000: 510183360,
187
+ 511000000 + 1: 510183360,
188
+ 511000000 - 1: 510183360, # 2**6 * 3**13 * 5**1
189
+ # 3**7 * 5**8
190
+ 854296875: 854296875,
191
+ 854296875 + 1: 854296875,
192
+ 854296875 - 1: 850305600, # 2**6 * 3**12 * 5**2
193
+ # 2**22 * 3**1 * 5**6
194
+ 196608000000: 196608000000,
195
+ 196608000000 + 1: 196608000000,
196
+ 196608000000 - 1: 195910410240, # 2**13 * 3**14 * 5**1
197
+ # 2**5 * 3**2 * 5**15
198
+ 8789062500000: 8789062500000,
199
+ 8789062500000 + 1: 8789062500000,
200
+ 8789062500000 - 1: 8748000000000, # 2**11 * 3**7 * 5**9
201
+ # 2**24 * 3**9 * 5**4
202
+ 206391214080000: 206391214080000,
203
+ 206391214080000 + 1: 206391214080000,
204
+ 206391214080000 - 1: 206158430208000, # 2**39 * 3**1 * 5**3
205
+ # 2**18 * 3**15 * 5**3
206
+ 470184984576000: 470184984576000,
207
+ 470184984576000 + 1: 470184984576000,
208
+ 470184984576000 - 1: 469654673817600, # 2**33 * 3**7 **5**2
209
+ # 2**25 * 3**16 * 5**1
210
+ 7222041363087360: 7222041363087360,
211
+ 7222041363087360 + 1: 7222041363087360,
212
+ 7222041363087360 - 1: 7213895789838336, # 2**40 * 3**8
213
+ # power of 5 5**23
214
+ 11920928955078125: 11920928955078125,
215
+ 11920928955078125 + 1: 11920928955078125,
216
+ 11920928955078125 - 1: 11901557422080000, # 2**14 * 3**19 * 5**4
217
+ # power of 3 3**34
218
+ 16677181699666569: 16677181699666569,
219
+ 16677181699666569 + 1: 16677181699666569,
220
+ 16677181699666569 - 1: 16607531250000000, # 2**7 * 3**12 * 5**12
221
+ # power of 2 2**54
222
+ 18014398509481984: 18014398509481984,
223
+ 18014398509481984 + 1: 18014398509481984,
224
+ 18014398509481984 - 1: 18000000000000000, # 2**16 * 3**2 * 5**15
225
+ # 2**20 * 3**1 * 5**14
226
+ 19200000000000000: 19200000000000000,
227
+ 19200000000000000 + 1: 19200000000000000,
228
+ 19200000000000000 - 1: 19131876000000000, # 2**11 * 3**14 * 5**9
229
+ # 2**58
230
+ 288230376151711744: 288230376151711744,
231
+ 288230376151711744 + 1: 288230376151711744,
232
+ 288230376151711744 - 1: 288000000000000000, # 2**20 * 3**2 * 5**15
233
+ # 2**5 * 3**10 * 5**16
234
+ 288325195312500000: 288325195312500000,
235
+ 288325195312500000 + 1: 288325195312500000,
236
+ 288325195312500000 - 1: 288230376151711744, # 2**58
237
+ }
238
+ for x, y in hams.items():
239
+ assert_equal(prev_fast_len(x, True), y)
240
+
241
+ def test_keyword_args(self):
242
+ assert prev_fast_len(11, real=True) == 10
243
+ assert prev_fast_len(target=7, real=False) == 7
244
+
245
+
246
+ @skip_xp_backends(cpu_only=True)
247
+ class Test_init_nd_shape_and_axes:
248
+
249
+ def test_py_0d_defaults(self, xp):
250
+ x = xp.asarray(4)
251
+ shape = None
252
+ axes = None
253
+
254
+ shape_expected = ()
255
+ axes_expected = []
256
+
257
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
258
+
259
+ assert shape_res == shape_expected
260
+ assert axes_res == axes_expected
261
+
262
+ def test_xp_0d_defaults(self, xp):
263
+ x = xp.asarray(7.)
264
+ shape = None
265
+ axes = None
266
+
267
+ shape_expected = ()
268
+ axes_expected = []
269
+
270
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
271
+
272
+ assert shape_res == shape_expected
273
+ assert axes_res == axes_expected
274
+
275
+ def test_py_1d_defaults(self, xp):
276
+ x = xp.asarray([1, 2, 3])
277
+ shape = None
278
+ axes = None
279
+
280
+ shape_expected = (3,)
281
+ axes_expected = [0]
282
+
283
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
284
+
285
+ assert shape_res == shape_expected
286
+ assert axes_res == axes_expected
287
+
288
+ def test_xp_1d_defaults(self, xp):
289
+ x = xp.arange(0, 1, .1)
290
+ shape = None
291
+ axes = None
292
+
293
+ shape_expected = (10,)
294
+ axes_expected = [0]
295
+
296
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
297
+
298
+ assert shape_res == shape_expected
299
+ assert axes_res == axes_expected
300
+
301
+ def test_py_2d_defaults(self, xp):
302
+ x = xp.asarray([[1, 2, 3, 4],
303
+ [5, 6, 7, 8]])
304
+ shape = None
305
+ axes = None
306
+
307
+ shape_expected = (2, 4)
308
+ axes_expected = [0, 1]
309
+
310
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
311
+
312
+ assert shape_res == shape_expected
313
+ assert axes_res == axes_expected
314
+
315
+ def test_xp_2d_defaults(self, xp):
316
+ x = xp.arange(0, 1, .1)
317
+ x = xp.reshape(x, (5, 2))
318
+ shape = None
319
+ axes = None
320
+
321
+ shape_expected = (5, 2)
322
+ axes_expected = [0, 1]
323
+
324
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
325
+
326
+ assert shape_res == shape_expected
327
+ assert axes_res == axes_expected
328
+
329
+ def test_xp_5d_defaults(self, xp):
330
+ x = xp.zeros([6, 2, 5, 3, 4])
331
+ shape = None
332
+ axes = None
333
+
334
+ shape_expected = (6, 2, 5, 3, 4)
335
+ axes_expected = [0, 1, 2, 3, 4]
336
+
337
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
338
+
339
+ assert shape_res == shape_expected
340
+ assert axes_res == axes_expected
341
+
342
+ def test_xp_5d_set_shape(self, xp):
343
+ x = xp.zeros([6, 2, 5, 3, 4])
344
+ shape = [10, -1, -1, 1, 4]
345
+ axes = None
346
+
347
+ shape_expected = (10, 2, 5, 1, 4)
348
+ axes_expected = [0, 1, 2, 3, 4]
349
+
350
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
351
+
352
+ assert shape_res == shape_expected
353
+ assert axes_res == axes_expected
354
+
355
+ def test_xp_5d_set_axes(self, xp):
356
+ x = xp.zeros([6, 2, 5, 3, 4])
357
+ shape = None
358
+ axes = [4, 1, 2]
359
+
360
+ shape_expected = (4, 2, 5)
361
+ axes_expected = [4, 1, 2]
362
+
363
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
364
+
365
+ assert shape_res == shape_expected
366
+ assert axes_res == axes_expected
367
+
368
+ def test_xp_5d_set_shape_axes(self, xp):
369
+ x = xp.zeros([6, 2, 5, 3, 4])
370
+ shape = [10, -1, 2]
371
+ axes = [1, 0, 3]
372
+
373
+ shape_expected = (10, 6, 2)
374
+ axes_expected = [1, 0, 3]
375
+
376
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
377
+
378
+ assert shape_res == shape_expected
379
+ assert axes_res == axes_expected
380
+
381
+ def test_shape_axes_subset(self, xp):
382
+ x = xp.zeros((2, 3, 4, 5))
383
+ shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None)
384
+
385
+ assert shape == (5, 5, 5)
386
+ assert axes == [1, 2, 3]
387
+
388
+ def test_errors(self, xp):
389
+ x = xp.zeros(1)
390
+ with assert_raises(ValueError, match="axes must be a scalar or "
391
+ "iterable of integers"):
392
+ _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]])
393
+
394
+ with assert_raises(ValueError, match="axes must be a scalar or "
395
+ "iterable of integers"):
396
+ _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.])
397
+
398
+ with assert_raises(ValueError,
399
+ match="axes exceeds dimensionality of input"):
400
+ _init_nd_shape_and_axes(x, shape=None, axes=[1])
401
+
402
+ with assert_raises(ValueError,
403
+ match="axes exceeds dimensionality of input"):
404
+ _init_nd_shape_and_axes(x, shape=None, axes=[-2])
405
+
406
+ with assert_raises(ValueError,
407
+ match="all axes must be unique"):
408
+ _init_nd_shape_and_axes(x, shape=None, axes=[0, 0])
409
+
410
+ with assert_raises(ValueError, match="shape must be a scalar or "
411
+ "iterable of integers"):
412
+ _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None)
413
+
414
+ with assert_raises(ValueError, match="shape must be a scalar or "
415
+ "iterable of integers"):
416
+ _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None)
417
+
418
+ with assert_raises(ValueError,
419
+ match="when given, axes and shape arguments"
420
+ " have to be of the same length"):
421
+ _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]),
422
+ shape=[1, 2, 3], axes=[1])
423
+
424
+ with assert_raises(ValueError,
425
+ match="invalid number of data points"
426
+ r" \(\[0\]\) specified"):
427
+ _init_nd_shape_and_axes(x, shape=[0], axes=None)
428
+
429
+ with assert_raises(ValueError,
430
+ match="invalid number of data points"
431
+ r" \(\[-2\]\) specified"):
432
+ _init_nd_shape_and_axes(x, shape=-2, axes=None)
433
+
434
+
435
+ class TestFFTShift:
436
+
437
+ def test_definition(self, xp):
438
+ x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1])
439
+ y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4])
440
+ xp_assert_close(fft.fftshift(x), y)
441
+ xp_assert_close(fft.ifftshift(y), x)
442
+ x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1])
443
+ y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4])
444
+ xp_assert_close(fft.fftshift(x), y)
445
+ xp_assert_close(fft.ifftshift(y), x)
446
+
447
+ def test_inverse(self, xp):
448
+ for n in [1, 4, 9, 100, 211]:
449
+ x = xp.asarray(np.random.random((n,)))
450
+ xp_assert_close(fft.ifftshift(fft.fftshift(x)), x)
451
+
452
+ @skip_xp_backends('cupy', reason='cupy/cupy#8393')
453
+ def test_axes_keyword(self, xp):
454
+ freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]])
455
+ shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]])
456
+ xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted)
457
+ xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,)))
458
+ xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs)
459
+ xp_assert_close(fft.ifftshift(shifted, axes=0),
460
+ fft.ifftshift(shifted, axes=(0,)))
461
+ xp_assert_close(fft.fftshift(freqs), shifted)
462
+ xp_assert_close(fft.ifftshift(shifted), freqs)
463
+
464
+ @skip_xp_backends('cupy', reason='cupy/cupy#8393')
465
+ def test_uneven_dims(self, xp):
466
+ """ Test 2D input, which has uneven dimension sizes """
467
+ freqs = xp.asarray([
468
+ [0, 1],
469
+ [2, 3],
470
+ [4, 5]
471
+ ], dtype=xp.float64)
472
+
473
+ # shift in dimension 0
474
+ shift_dim0 = xp.asarray([
475
+ [4, 5],
476
+ [0, 1],
477
+ [2, 3]
478
+ ], dtype=xp.float64)
479
+ xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0)
480
+ xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs)
481
+ xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0)
482
+ xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs)
483
+
484
+ # shift in dimension 1
485
+ shift_dim1 = xp.asarray([
486
+ [1, 0],
487
+ [3, 2],
488
+ [5, 4]
489
+ ], dtype=xp.float64)
490
+ xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1)
491
+ xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs)
492
+
493
+ # shift in both dimensions
494
+ shift_dim_both = xp.asarray([
495
+ [5, 4],
496
+ [1, 0],
497
+ [3, 2]
498
+ ], dtype=xp.float64)
499
+ xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both)
500
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs)
501
+ xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both)
502
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs)
503
+
504
+ # axes=None (default) shift in all dimensions
505
+ xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both)
506
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs)
507
+ xp_assert_close(fft.fftshift(freqs), shift_dim_both)
508
+ xp_assert_close(fft.ifftshift(shift_dim_both), freqs)
509
+
510
+
511
+ @skip_xp_backends("cupy",
512
+ reason="CuPy has not implemented the `device` param")
513
+ @skip_xp_backends("jax.numpy",
514
+ reason="JAX has not implemented the `device` param")
515
+ class TestFFTFreq:
516
+
517
+ def test_definition(self, xp):
518
+ x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64)
519
+ x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64)
520
+
521
+ # default dtype varies across backends
522
+
523
+ y = 9 * fft.fftfreq(9, xp=xp)
524
+ xp_assert_close(y, x, check_dtype=False, check_namespace=True)
525
+
526
+ y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp)
527
+ xp_assert_close(y, x, check_dtype=False)
528
+
529
+ y = 10 * fft.fftfreq(10, xp=xp)
530
+ xp_assert_close(y, x2, check_dtype=False)
531
+
532
+ y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp)
533
+ xp_assert_close(y, x2, check_dtype=False)
534
+
535
+ def test_device(self, xp):
536
+ xp_test = array_namespace(xp.empty(0))
537
+ devices = get_xp_devices(xp)
538
+ for d in devices:
539
+ y = fft.fftfreq(9, xp=xp, device=d)
540
+ x = xp_test.empty(0, device=d)
541
+ assert xp_device(y) == xp_device(x)
542
+
543
+
544
+ @skip_xp_backends("cupy",
545
+ reason="CuPy has not implemented the `device` param")
546
+ @skip_xp_backends("jax.numpy",
547
+ reason="JAX has not implemented the `device` param")
548
+ class TestRFFTFreq:
549
+
550
+ def test_definition(self, xp):
551
+ x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64)
552
+ x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64)
553
+
554
+ # default dtype varies across backends
555
+
556
+ y = 9 * fft.rfftfreq(9, xp=xp)
557
+ xp_assert_close(y, x, check_dtype=False, check_namespace=True)
558
+
559
+ y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp)
560
+ xp_assert_close(y, x, check_dtype=False)
561
+
562
+ y = 10 * fft.rfftfreq(10, xp=xp)
563
+ xp_assert_close(y, x2, check_dtype=False)
564
+
565
+ y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp)
566
+ xp_assert_close(y, x2, check_dtype=False)
567
+
568
+ def test_device(self, xp):
569
+ xp_test = array_namespace(xp.empty(0))
570
+ devices = get_xp_devices(xp)
571
+ for d in devices:
572
+ y = fft.rfftfreq(9, xp=xp, device=d)
573
+ x = xp_test.empty(0, device=d)
574
+ assert xp_device(y) == xp_device(x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy import fft
2
+ import numpy as np
3
+ import pytest
4
+ from numpy.testing import assert_allclose
5
+ import multiprocessing
6
+ import os
7
+
8
+
9
+ @pytest.fixture(scope='module')
10
+ def x():
11
+ return np.random.randn(512, 128) # Must be large enough to qualify for mt
12
+
13
+
14
+ @pytest.mark.parametrize("func", [
15
+ fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn,
16
+ fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn,
17
+ fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn,
18
+ fft.dct, fft.idct, fft.dctn, fft.idctn,
19
+ fft.dst, fft.idst, fft.dstn, fft.idstn,
20
+ ])
21
+ @pytest.mark.parametrize("workers", [2, -1])
22
+ def test_threaded_same(x, func, workers):
23
+ expected = func(x, workers=1)
24
+ actual = func(x, workers=workers)
25
+ assert_allclose(actual, expected)
26
+
27
+
28
+ def _mt_fft(x):
29
+ return fft.fft(x, workers=2)
30
+
31
+
32
+ @pytest.mark.slow
33
+ def test_mixed_threads_processes(x):
34
+ # Test that the fft threadpool is safe to use before & after fork
35
+
36
+ expect = fft.fft(x, workers=2)
37
+
38
+ with multiprocessing.Pool(2) as p:
39
+ res = p.map(_mt_fft, [x for _ in range(4)])
40
+
41
+ for r in res:
42
+ assert_allclose(r, expect)
43
+
44
+ fft.fft(x, workers=2)
45
+
46
+
47
+ def test_invalid_workers(x):
48
+ cpus = os.cpu_count()
49
+
50
+ fft.ifft([1], workers=-cpus)
51
+
52
+ with pytest.raises(ValueError, match='workers must not be zero'):
53
+ fft.fft(x, workers=0)
54
+
55
+ with pytest.raises(ValueError, match='workers value out of range'):
56
+ fft.ifft(x, workers=-cpus-1)
57
+
58
+
59
+ def test_set_get_workers():
60
+ cpus = os.cpu_count()
61
+ assert fft.get_workers() == 1
62
+ with fft.set_workers(4):
63
+ assert fft.get_workers() == 4
64
+
65
+ with fft.set_workers(-1):
66
+ assert fft.get_workers() == cpus
67
+
68
+ assert fft.get_workers() == 4
69
+
70
+ assert fft.get_workers() == 1
71
+
72
+ with fft.set_workers(-cpus):
73
+ assert fft.get_workers() == 1
74
+
75
+
76
+ def test_set_workers_invalid():
77
+
78
+ with pytest.raises(ValueError, match='workers must not be zero'):
79
+ with fft.set_workers(0):
80
+ pass
81
+
82
+ with pytest.raises(ValueError, match='workers value out of range'):
83
+ with fft.set_workers(-os.cpu_count()-1):
84
+ pass
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.testing import assert_allclose, assert_array_equal
3
+ import pytest
4
+ import math
5
+
6
+ from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn
7
+ import scipy.fft as fft
8
+ from scipy import fftpack
9
+ from scipy.conftest import array_api_compatible
10
+ from scipy._lib._array_api import xp_copy, xp_assert_close
11
+
12
+ pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
13
+ skip_xp_backends = pytest.mark.skip_xp_backends
14
+
15
+ SQRT_2 = math.sqrt(2)
16
+
17
+ # scipy.fft wraps the fftpack versions but with normalized inverse transforms.
18
+ # So, the forward transforms and definitions are already thoroughly tested in
19
+ # fftpack/test_real_transforms.py
20
+
21
+
22
+ @skip_xp_backends(cpu_only=True)
23
+ @pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
24
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
25
+ @pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16])
26
+ @pytest.mark.parametrize("axis", [0, 1])
27
+ @pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
28
+ @pytest.mark.parametrize("orthogonalize", [False, True])
29
+ def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp):
30
+ # Test the identity f^-1(f(x)) == x
31
+ x = xp.asarray(np.random.rand(n, n))
32
+
33
+ y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
34
+ z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
35
+ xp_assert_close(z, x)
36
+
37
+ pad = [(0, 0)] * 2
38
+ pad[axis] = (0, 4)
39
+
40
+ y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
41
+ z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize)
42
+ xp_assert_close(z2, x)
43
+
44
+
45
+ @skip_xp_backends(np_only=True,
46
+ reason='`overwrite_x` only supported for NumPy backend.')
47
+ @pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
48
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
49
+ @pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
50
+ np.complex64, np.complex128])
51
+ @pytest.mark.parametrize("axis", [0, 1])
52
+ @pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
53
+ @pytest.mark.parametrize("overwrite_x", [True, False])
54
+ def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm,
55
+ overwrite_x):
56
+ # Test the identity f^-1(f(x)) == x
57
+ x = np.random.rand(7, 8).astype(dtype)
58
+ x_orig = x.copy()
59
+
60
+ y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
61
+ y_orig = y.copy()
62
+ z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
63
+ if not overwrite_x:
64
+ assert_allclose(z, x, rtol=1e-6, atol=1e-6)
65
+ assert_array_equal(x, x_orig)
66
+ assert_array_equal(y, y_orig)
67
+ else:
68
+ assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
69
+
70
+
71
+ @skip_xp_backends(cpu_only=True)
72
+ @pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
73
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
74
+ @pytest.mark.parametrize("shape, axes",
75
+ [
76
+ ((4, 4), 0),
77
+ ((4, 4), 1),
78
+ ((4, 4), None),
79
+ ((4, 4), (0, 1)),
80
+ ((10, 12), None),
81
+ ((10, 12), (0, 1)),
82
+ ((4, 5, 6), None),
83
+ ((4, 5, 6), 1),
84
+ ((4, 5, 6), (0, 2)),
85
+ ])
86
+ @pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
87
+ @pytest.mark.parametrize("orthogonalize", [False, True])
88
+ def test_identity_nd(forward, backward, type, shape, axes, norm,
89
+ orthogonalize, xp):
90
+ # Test the identity f^-1(f(x)) == x
91
+
92
+ x = xp.asarray(np.random.random(shape))
93
+
94
+ if axes is not None:
95
+ shape = np.take(shape, axes)
96
+
97
+ y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
98
+ z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
99
+ xp_assert_close(z, x)
100
+
101
+ if axes is None:
102
+ pad = [(0, 4)] * x.ndim
103
+ elif isinstance(axes, int):
104
+ pad = [(0, 0)] * x.ndim
105
+ pad[axes] = (0, 4)
106
+ else:
107
+ pad = [(0, 0)] * x.ndim
108
+
109
+ for a in axes:
110
+ pad[a] = (0, 4)
111
+
112
+ # TODO write an array-agnostic pad
113
+ y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
114
+ z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize)
115
+ xp_assert_close(z2, x)
116
+
117
+
118
+ @skip_xp_backends(np_only=True,
119
+ reason='`overwrite_x` only supported for NumPy backend.')
120
+ @pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
121
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
122
+ @pytest.mark.parametrize("shape, axes",
123
+ [
124
+ ((4, 5), 0),
125
+ ((4, 5), 1),
126
+ ((4, 5), None),
127
+ ])
128
+ @pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
129
+ np.complex64, np.complex128])
130
+ @pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
131
+ @pytest.mark.parametrize("overwrite_x", [False, True])
132
+ def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype,
133
+ norm, overwrite_x):
134
+ # Test the identity f^-1(f(x)) == x
135
+
136
+ x = np.random.random(shape).astype(dtype)
137
+ x_orig = x.copy()
138
+
139
+ if axes is not None:
140
+ shape = np.take(shape, axes)
141
+
142
+ y = forward(x, type, axes=axes, norm=norm)
143
+ y_orig = y.copy()
144
+ z = backward(y, type, axes=axes, norm=norm)
145
+ if overwrite_x:
146
+ assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
147
+ else:
148
+ assert_allclose(z, x, rtol=1e-6, atol=1e-6)
149
+ assert_array_equal(x, x_orig)
150
+ assert_array_equal(y, y_orig)
151
+
152
+
153
+ @skip_xp_backends(cpu_only=True)
154
+ @pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', 'dstn'])
155
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
156
+ @pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
157
+ def test_fftpack_equivalience(func, type, norm, xp):
158
+ x = np.random.rand(8, 16)
159
+ fftpack_res = xp.asarray(getattr(fftpack, func)(x, type, norm=norm))
160
+ x = xp.asarray(x)
161
+ fft_res = getattr(fft, func)(x, type, norm=norm)
162
+
163
+ xp_assert_close(fft_res, fftpack_res)
164
+
165
+
166
+ @skip_xp_backends(cpu_only=True)
167
+ @pytest.mark.parametrize("func", [dct, dst, dctn, dstn])
168
+ @pytest.mark.parametrize("type", [1, 2, 3, 4])
169
+ def test_orthogonalize_default(func, type, xp):
170
+ # Test orthogonalize is the default when norm="ortho", but not otherwise
171
+ x = xp.asarray(np.random.rand(100))
172
+
173
+ for norm, ortho in [
174
+ ("forward", False),
175
+ ("backward", False),
176
+ ("ortho", True),
177
+ ]:
178
+ a = func(x, type=type, norm=norm, orthogonalize=ortho)
179
+ b = func(x, type=type, norm=norm)
180
+ xp_assert_close(a, b)
181
+
182
+
183
+ @skip_xp_backends(cpu_only=True)
184
+ @pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
185
+ @pytest.mark.parametrize("func, type", [
186
+ (dct, 4), (dst, 1), (dst, 4)])
187
+ def test_orthogonalize_noop(func, type, norm, xp):
188
+ # Transforms where orthogonalize is a no-op
189
+ x = xp.asarray(np.random.rand(100))
190
+ y1 = func(x, type=type, norm=norm, orthogonalize=True)
191
+ y2 = func(x, type=type, norm=norm, orthogonalize=False)
192
+ xp_assert_close(y1, y2)
193
+
194
+
195
+ @skip_xp_backends('jax.numpy',
196
+ reason='jax arrays do not support item assignment',
197
+ cpu_only=True)
198
+ @pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
199
+ def test_orthogonalize_dct1(norm, xp):
200
+ x = xp.asarray(np.random.rand(100))
201
+
202
+ x2 = xp_copy(x, xp=xp)
203
+ x2[0] *= SQRT_2
204
+ x2[-1] *= SQRT_2
205
+
206
+ y1 = dct(x, type=1, norm=norm, orthogonalize=True)
207
+ y2 = dct(x2, type=1, norm=norm, orthogonalize=False)
208
+
209
+ y2[0] /= SQRT_2
210
+ y2[-1] /= SQRT_2
211
+ xp_assert_close(y1, y2)
212
+
213
+
214
+ @skip_xp_backends('jax.numpy',
215
+ reason='jax arrays do not support item assignment',
216
+ cpu_only=True)
217
+ @pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
218
+ @pytest.mark.parametrize("func", [dct, dst])
219
+ def test_orthogonalize_dcst2(func, norm, xp):
220
+ x = xp.asarray(np.random.rand(100))
221
+ y1 = func(x, type=2, norm=norm, orthogonalize=True)
222
+ y2 = func(x, type=2, norm=norm, orthogonalize=False)
223
+
224
+ y2[0 if func == dct else -1] /= SQRT_2
225
+ xp_assert_close(y1, y2)
226
+
227
+
228
+ @skip_xp_backends('jax.numpy',
229
+ reason='jax arrays do not support item assignment',
230
+ cpu_only=True)
231
+ @pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
232
+ @pytest.mark.parametrize("func", [dct, dst])
233
+ def test_orthogonalize_dcst3(func, norm, xp):
234
+ x = xp.asarray(np.random.rand(100))
235
+ x2 = xp_copy(x, xp=xp)
236
+ x2[0 if func == dct else -1] *= SQRT_2
237
+
238
+ y1 = func(x, type=3, norm=norm, orthogonalize=True)
239
+ y2 = func(x2, type=3, norm=norm, orthogonalize=False)
240
+ xp_assert_close(y1, y2)
241
+
242
+ @skip_xp_backends(np_only=True,
243
+ reason='array-likes only supported for NumPy backend')
244
+ @pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn])
245
+ def test_array_like(xp, func):
246
+ x = [[[1.0, 1.0], [1.0, 1.0]],
247
+ [[1.0, 1.0], [1.0, 1.0]],
248
+ [[1.0, 1.0], [1.0, 1.0]]]
249
+ xp_assert_close(func(x), func(xp.asarray(x)))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =========================================================
3
+ Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
4
+ =========================================================
5
+
6
+ .. legacy::
7
+
8
+ New code should use :mod:`scipy.fft`.
9
+
10
+ Fast Fourier Transforms (FFTs)
11
+ ==============================
12
+
13
+ .. autosummary::
14
+ :toctree: generated/
15
+
16
+ fft - Fast (discrete) Fourier Transform (FFT)
17
+ ifft - Inverse FFT
18
+ fft2 - 2-D FFT
19
+ ifft2 - 2-D inverse FFT
20
+ fftn - N-D FFT
21
+ ifftn - N-D inverse FFT
22
+ rfft - FFT of strictly real-valued sequence
23
+ irfft - Inverse of rfft
24
+ dct - Discrete cosine transform
25
+ idct - Inverse discrete cosine transform
26
+ dctn - N-D Discrete cosine transform
27
+ idctn - N-D Inverse discrete cosine transform
28
+ dst - Discrete sine transform
29
+ idst - Inverse discrete sine transform
30
+ dstn - N-D Discrete sine transform
31
+ idstn - N-D Inverse discrete sine transform
32
+
33
+ Differential and pseudo-differential operators
34
+ ==============================================
35
+
36
+ .. autosummary::
37
+ :toctree: generated/
38
+
39
+ diff - Differentiation and integration of periodic sequences
40
+ tilbert - Tilbert transform: cs_diff(x,h,h)
41
+ itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
42
+ hilbert - Hilbert transform: cs_diff(x,inf,inf)
43
+ ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
44
+ cs_diff - cosh/sinh pseudo-derivative of periodic sequences
45
+ sc_diff - sinh/cosh pseudo-derivative of periodic sequences
46
+ ss_diff - sinh/sinh pseudo-derivative of periodic sequences
47
+ cc_diff - cosh/cosh pseudo-derivative of periodic sequences
48
+ shift - Shift periodic sequences
49
+
50
+ Helper functions
51
+ ================
52
+
53
+ .. autosummary::
54
+ :toctree: generated/
55
+
56
+ fftshift - Shift the zero-frequency component to the center of the spectrum
57
+ ifftshift - The inverse of `fftshift`
58
+ fftfreq - Return the Discrete Fourier Transform sample frequencies
59
+ rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
60
+ next_fast_len - Find the optimal length to zero-pad an FFT for speed
61
+
62
+ Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
63
+ exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
64
+
65
+ Convolutions (:mod:`scipy.fftpack.convolve`)
66
+ ============================================
67
+
68
+ .. module:: scipy.fftpack.convolve
69
+
70
+ .. autosummary::
71
+ :toctree: generated/
72
+
73
+ convolve
74
+ convolve_z
75
+ init_convolution_kernel
76
+ destroy_convolve_cache
77
+
78
+ """
79
+
80
+
81
+ __all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
82
+ 'fft2','ifft2',
83
+ 'diff',
84
+ 'tilbert','itilbert','hilbert','ihilbert',
85
+ 'sc_diff','cs_diff','cc_diff','ss_diff',
86
+ 'shift',
87
+ 'fftfreq', 'rfftfreq',
88
+ 'fftshift', 'ifftshift',
89
+ 'next_fast_len',
90
+ 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
91
+ ]
92
+
93
+ from ._basic import *
94
+ from ._pseudo_diffs import *
95
+ from ._helper import *
96
+ from ._realtransforms import *
97
+
98
+ # Deprecated namespaces, to be removed in v2.0.0
99
+ from . import basic, helper, pseudo_diffs, realtransforms
100
+
101
+ from scipy._lib._testutils import PytestTester
102
+ test = PytestTester(__name__)
103
+ del PytestTester
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_basic.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Discrete Fourier Transforms - _basic.py
3
+ """
4
+ # Created by Pearu Peterson, August,September 2002
5
+ __all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
6
+ 'fft2','ifft2']
7
+
8
+ from scipy.fft import _pocketfft
9
+ from ._helper import _good_shape
10
+
11
+
12
+ def fft(x, n=None, axis=-1, overwrite_x=False):
13
+ """
14
+ Return discrete Fourier transform of real or complex sequence.
15
+
16
+ The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
17
+
18
+ ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
19
+
20
+ Parameters
21
+ ----------
22
+ x : array_like
23
+ Array to Fourier transform.
24
+ n : int, optional
25
+ Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
26
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
27
+ default results in ``n = x.shape[axis]``.
28
+ axis : int, optional
29
+ Axis along which the fft's are computed; the default is over the
30
+ last axis (i.e., ``axis=-1``).
31
+ overwrite_x : bool, optional
32
+ If True, the contents of `x` can be destroyed; the default is False.
33
+
34
+ Returns
35
+ -------
36
+ z : complex ndarray
37
+ with the elements::
38
+
39
+ [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even
40
+ [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd
41
+
42
+ where::
43
+
44
+ y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
45
+
46
+ See Also
47
+ --------
48
+ ifft : Inverse FFT
49
+ rfft : FFT of a real sequence
50
+
51
+ Notes
52
+ -----
53
+ The packing of the result is "standard": If ``A = fft(a, n)``, then
54
+ ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
55
+ positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
56
+ terms, in order of decreasingly negative frequency. So ,for an 8-point
57
+ transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
58
+ To rearrange the fft output so that the zero-frequency component is
59
+ centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`.
60
+
61
+ Both single and double precision routines are implemented. Half precision
62
+ inputs will be converted to single precision. Non-floating-point inputs
63
+ will be converted to double precision. Long-double precision inputs are
64
+ not supported.
65
+
66
+ This function is most efficient when `n` is a power of two, and least
67
+ efficient when `n` is prime.
68
+
69
+ Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
70
+ If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
71
+
72
+ If the data type of `x` is real, a "real FFT" algorithm is automatically
73
+ used, which roughly halves the computation time. To increase efficiency
74
+ a little further, use `rfft`, which does the same calculation, but only
75
+ outputs half of the symmetrical spectrum. If the data is both real and
76
+ symmetrical, the `dct` can again double the efficiency by generating
77
+ half of the spectrum from half of the signal.
78
+
79
+ Examples
80
+ --------
81
+ >>> import numpy as np
82
+ >>> from scipy.fftpack import fft, ifft
83
+ >>> x = np.arange(5)
84
+ >>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy.
85
+ True
86
+
87
+ """
88
+ return _pocketfft.fft(x, n, axis, None, overwrite_x)
89
+
90
+
91
+ def ifft(x, n=None, axis=-1, overwrite_x=False):
92
+ """
93
+ Return discrete inverse Fourier transform of real or complex sequence.
94
+
95
+ The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
96
+
97
+ ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
98
+
99
+ Parameters
100
+ ----------
101
+ x : array_like
102
+ Transformed data to invert.
103
+ n : int, optional
104
+ Length of the inverse Fourier transform. If ``n < x.shape[axis]``,
105
+ `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
106
+ The default results in ``n = x.shape[axis]``.
107
+ axis : int, optional
108
+ Axis along which the ifft's are computed; the default is over the
109
+ last axis (i.e., ``axis=-1``).
110
+ overwrite_x : bool, optional
111
+ If True, the contents of `x` can be destroyed; the default is False.
112
+
113
+ Returns
114
+ -------
115
+ ifft : ndarray of floats
116
+ The inverse discrete Fourier transform.
117
+
118
+ See Also
119
+ --------
120
+ fft : Forward FFT
121
+
122
+ Notes
123
+ -----
124
+ Both single and double precision routines are implemented. Half precision
125
+ inputs will be converted to single precision. Non-floating-point inputs
126
+ will be converted to double precision. Long-double precision inputs are
127
+ not supported.
128
+
129
+ This function is most efficient when `n` is a power of two, and least
130
+ efficient when `n` is prime.
131
+
132
+ If the data type of `x` is real, a "real IFFT" algorithm is automatically
133
+ used, which roughly halves the computation time.
134
+
135
+ Examples
136
+ --------
137
+ >>> from scipy.fftpack import fft, ifft
138
+ >>> import numpy as np
139
+ >>> x = np.arange(5)
140
+ >>> np.allclose(ifft(fft(x)), x, atol=1e-15) # within numerical accuracy.
141
+ True
142
+
143
+ """
144
+ return _pocketfft.ifft(x, n, axis, None, overwrite_x)
145
+
146
+
147
+ def rfft(x, n=None, axis=-1, overwrite_x=False):
148
+ """
149
+ Discrete Fourier transform of a real sequence.
150
+
151
+ Parameters
152
+ ----------
153
+ x : array_like, real-valued
154
+ The data to transform.
155
+ n : int, optional
156
+ Defines the length of the Fourier transform. If `n` is not specified
157
+ (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
158
+ `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
159
+ axis : int, optional
160
+ The axis along which the transform is applied. The default is the
161
+ last axis.
162
+ overwrite_x : bool, optional
163
+ If set to true, the contents of `x` can be overwritten. Default is
164
+ False.
165
+
166
+ Returns
167
+ -------
168
+ z : real ndarray
169
+ The returned real array contains::
170
+
171
+ [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even
172
+ [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd
173
+
174
+ where::
175
+
176
+ y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
177
+ j = 0..n-1
178
+
179
+ See Also
180
+ --------
181
+ fft, irfft, scipy.fft.rfft
182
+
183
+ Notes
184
+ -----
185
+ Within numerical accuracy, ``y == rfft(irfft(y))``.
186
+
187
+ Both single and double precision routines are implemented. Half precision
188
+ inputs will be converted to single precision. Non-floating-point inputs
189
+ will be converted to double precision. Long-double precision inputs are
190
+ not supported.
191
+
192
+ To get an output with a complex datatype, consider using the newer
193
+ function `scipy.fft.rfft`.
194
+
195
+ Examples
196
+ --------
197
+ >>> from scipy.fftpack import fft, rfft
198
+ >>> a = [9, -9, 1, 3]
199
+ >>> fft(a)
200
+ array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j])
201
+ >>> rfft(a)
202
+ array([ 4., 8., 12., 16.])
203
+
204
+ """
205
+ return _pocketfft.rfft_fftpack(x, n, axis, None, overwrite_x)
206
+
207
+
208
+ def irfft(x, n=None, axis=-1, overwrite_x=False):
209
+ """
210
+ Return inverse discrete Fourier transform of real sequence x.
211
+
212
+ The contents of `x` are interpreted as the output of the `rfft`
213
+ function.
214
+
215
+ Parameters
216
+ ----------
217
+ x : array_like
218
+ Transformed data to invert.
219
+ n : int, optional
220
+ Length of the inverse Fourier transform.
221
+ If n < x.shape[axis], x is truncated.
222
+ If n > x.shape[axis], x is zero-padded.
223
+ The default results in n = x.shape[axis].
224
+ axis : int, optional
225
+ Axis along which the ifft's are computed; the default is over
226
+ the last axis (i.e., axis=-1).
227
+ overwrite_x : bool, optional
228
+ If True, the contents of `x` can be destroyed; the default is False.
229
+
230
+ Returns
231
+ -------
232
+ irfft : ndarray of floats
233
+ The inverse discrete Fourier transform.
234
+
235
+ See Also
236
+ --------
237
+ rfft, ifft, scipy.fft.irfft
238
+
239
+ Notes
240
+ -----
241
+ The returned real array contains::
242
+
243
+ [y(0),y(1),...,y(n-1)]
244
+
245
+ where for n is even::
246
+
247
+ y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
248
+ * exp(sqrt(-1)*j*k* 2*pi/n)
249
+ + c.c. + x[0] + (-1)**(j) x[n-1])
250
+
251
+ and for n is odd::
252
+
253
+ y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
254
+ * exp(sqrt(-1)*j*k* 2*pi/n)
255
+ + c.c. + x[0])
256
+
257
+ c.c. denotes complex conjugate of preceding expression.
258
+
259
+ For details on input parameters, see `rfft`.
260
+
261
+ To process (conjugate-symmetric) frequency-domain data with a complex
262
+ datatype, consider using the newer function `scipy.fft.irfft`.
263
+
264
+ Examples
265
+ --------
266
+ >>> from scipy.fftpack import rfft, irfft
267
+ >>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
268
+ >>> irfft(a)
269
+ array([ 2.6 , -3.16405192, 1.24398433, -1.14955713, 1.46962473])
270
+ >>> irfft(rfft(a))
271
+ array([1., 2., 3., 4., 5.])
272
+
273
+ """
274
+ return _pocketfft.irfft_fftpack(x, n, axis, None, overwrite_x)
275
+
276
+
277
+ def fftn(x, shape=None, axes=None, overwrite_x=False):
278
+ """
279
+ Return multidimensional discrete Fourier transform.
280
+
281
+ The returned array contains::
282
+
283
+ y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
284
+ x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
285
+
286
+ where d = len(x.shape) and n = x.shape.
287
+
288
+ Parameters
289
+ ----------
290
+ x : array_like
291
+ The (N-D) array to transform.
292
+ shape : int or array_like of ints or None, optional
293
+ The shape of the result. If both `shape` and `axes` (see below) are
294
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
295
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
296
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
297
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
298
+ length ``shape[i]``.
299
+ If any element of `shape` is -1, the size of the corresponding
300
+ dimension of `x` is used.
301
+ axes : int or array_like of ints or None, optional
302
+ The axes of `x` (`y` if `shape` is not None) along which the
303
+ transform is applied.
304
+ The default is over all axes.
305
+ overwrite_x : bool, optional
306
+ If True, the contents of `x` can be destroyed. Default is False.
307
+
308
+ Returns
309
+ -------
310
+ y : complex-valued N-D NumPy array
311
+ The (N-D) DFT of the input array.
312
+
313
+ See Also
314
+ --------
315
+ ifftn
316
+
317
+ Notes
318
+ -----
319
+ If ``x`` is real-valued, then
320
+ ``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
321
+
322
+ Both single and double precision routines are implemented. Half precision
323
+ inputs will be converted to single precision. Non-floating-point inputs
324
+ will be converted to double precision. Long-double precision inputs are
325
+ not supported.
326
+
327
+ Examples
328
+ --------
329
+ >>> import numpy as np
330
+ >>> from scipy.fftpack import fftn, ifftn
331
+ >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
332
+ >>> np.allclose(y, fftn(ifftn(y)))
333
+ True
334
+
335
+ """
336
+ shape = _good_shape(x, shape, axes)
337
+ return _pocketfft.fftn(x, shape, axes, None, overwrite_x)
338
+
339
+
340
+ def ifftn(x, shape=None, axes=None, overwrite_x=False):
341
+ """
342
+ Return inverse multidimensional discrete Fourier transform.
343
+
344
+ The sequence can be of an arbitrary type.
345
+
346
+ The returned array contains::
347
+
348
+ y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
349
+ x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
350
+
351
+ where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
352
+
353
+ For description of parameters see `fftn`.
354
+
355
+ See Also
356
+ --------
357
+ fftn : for detailed information.
358
+
359
+ Examples
360
+ --------
361
+ >>> from scipy.fftpack import fftn, ifftn
362
+ >>> import numpy as np
363
+ >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
364
+ >>> np.allclose(y, ifftn(fftn(y)))
365
+ True
366
+
367
+ """
368
+ shape = _good_shape(x, shape, axes)
369
+ return _pocketfft.ifftn(x, shape, axes, None, overwrite_x)
370
+
371
+
372
+ def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
373
+ """
374
+ 2-D discrete Fourier transform.
375
+
376
+ Return the 2-D discrete Fourier transform of the 2-D argument
377
+ `x`.
378
+
379
+ See Also
380
+ --------
381
+ fftn : for detailed information.
382
+
383
+ Examples
384
+ --------
385
+ >>> import numpy as np
386
+ >>> from scipy.fftpack import fft2, ifft2
387
+ >>> y = np.mgrid[:5, :5][0]
388
+ >>> y
389
+ array([[0, 0, 0, 0, 0],
390
+ [1, 1, 1, 1, 1],
391
+ [2, 2, 2, 2, 2],
392
+ [3, 3, 3, 3, 3],
393
+ [4, 4, 4, 4, 4]])
394
+ >>> np.allclose(y, ifft2(fft2(y)))
395
+ True
396
+ """
397
+ return fftn(x,shape,axes,overwrite_x)
398
+
399
+
400
+ def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
401
+ """
402
+ 2-D discrete inverse Fourier transform of real or complex sequence.
403
+
404
+ Return inverse 2-D discrete Fourier transform of
405
+ arbitrary type sequence x.
406
+
407
+ See `ifft` for more information.
408
+
409
+ See Also
410
+ --------
411
+ fft2, ifft
412
+
413
+ Examples
414
+ --------
415
+ >>> import numpy as np
416
+ >>> from scipy.fftpack import fft2, ifft2
417
+ >>> y = np.mgrid[:5, :5][0]
418
+ >>> y
419
+ array([[0, 0, 0, 0, 0],
420
+ [1, 1, 1, 1, 1],
421
+ [2, 2, 2, 2, 2],
422
+ [3, 3, 3, 3, 3],
423
+ [4, 4, 4, 4, 4]])
424
+ >>> np.allclose(y, fft2(ifft2(y)))
425
+ True
426
+
427
+ """
428
+ return ifftn(x,shape,axes,overwrite_x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_helper.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ from numpy.fft import fftshift, ifftshift, fftfreq
5
+
6
+ import scipy.fft._pocketfft.helper as _helper
7
+
8
+ __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
9
+
10
+
11
+ def rfftfreq(n, d=1.0):
12
+ """DFT sample frequencies (for usage with rfft, irfft).
13
+
14
+ The returned float array contains the frequency bins in
15
+ cycles/unit (with zero at the start) given a window length `n` and a
16
+ sample spacing `d`::
17
+
18
+ f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n) if n is even
19
+ f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n) if n is odd
20
+
21
+ Parameters
22
+ ----------
23
+ n : int
24
+ Window length.
25
+ d : scalar, optional
26
+ Sample spacing. Default is 1.
27
+
28
+ Returns
29
+ -------
30
+ out : ndarray
31
+ The array of length `n`, containing the sample frequencies.
32
+
33
+ Examples
34
+ --------
35
+ >>> import numpy as np
36
+ >>> from scipy import fftpack
37
+ >>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
38
+ >>> sig_fft = fftpack.rfft(sig)
39
+ >>> n = sig_fft.size
40
+ >>> timestep = 0.1
41
+ >>> freq = fftpack.rfftfreq(n, d=timestep)
42
+ >>> freq
43
+ array([ 0. , 1.25, 1.25, 2.5 , 2.5 , 3.75, 3.75, 5. ])
44
+
45
+ """
46
+ n = operator.index(n)
47
+ if n < 0:
48
+ raise ValueError(f"n = {n} is not valid. "
49
+ "n must be a nonnegative integer.")
50
+
51
+ return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
52
+
53
+
54
+ def next_fast_len(target):
55
+ """
56
+ Find the next fast size of input data to `fft`, for zero-padding, etc.
57
+
58
+ SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
59
+ returns the next composite of the prime factors 2, 3, and 5 which is
60
+ greater than or equal to `target`. (These are also known as 5-smooth
61
+ numbers, regular numbers, or Hamming numbers.)
62
+
63
+ Parameters
64
+ ----------
65
+ target : int
66
+ Length to start searching from. Must be a positive integer.
67
+
68
+ Returns
69
+ -------
70
+ out : int
71
+ The first 5-smooth number greater than or equal to `target`.
72
+
73
+ Notes
74
+ -----
75
+ .. versionadded:: 0.18.0
76
+
77
+ Examples
78
+ --------
79
+ On a particular machine, an FFT of prime length takes 133 ms:
80
+
81
+ >>> from scipy import fftpack
82
+ >>> import numpy as np
83
+ >>> rng = np.random.default_rng()
84
+ >>> min_len = 10007 # prime length is worst case for speed
85
+ >>> a = rng.standard_normal(min_len)
86
+ >>> b = fftpack.fft(a)
87
+
88
+ Zero-padding to the next 5-smooth length reduces computation time to
89
+ 211 us, a speedup of 630 times:
90
+
91
+ >>> fftpack.next_fast_len(min_len)
92
+ 10125
93
+ >>> b = fftpack.fft(a, 10125)
94
+
95
+ Rounding up to the next power of 2 is not optimal, taking 367 us to
96
+ compute, 1.7 times as long as the 5-smooth size:
97
+
98
+ >>> b = fftpack.fft(a, 16384)
99
+
100
+ """
101
+ # Real transforms use regular sizes so this is backwards compatible
102
+ return _helper.good_size(target, True)
103
+
104
+
105
+ def _good_shape(x, shape, axes):
106
+ """Ensure that shape argument is valid for scipy.fftpack
107
+
108
+ scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
109
+ """
110
+ if shape is not None and axes is None:
111
+ shape = _helper._iterable_of_int(shape, 'shape')
112
+ if len(shape) != np.ndim(x):
113
+ raise ValueError("when given, axes and shape arguments"
114
+ " have to be of the same length")
115
+ return shape
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Differential and pseudo-differential operators.
3
+ """
4
+ # Created by Pearu Peterson, September 2002
5
+
6
+ __all__ = ['diff',
7
+ 'tilbert','itilbert','hilbert','ihilbert',
8
+ 'cs_diff','cc_diff','sc_diff','ss_diff',
9
+ 'shift']
10
+
11
+ import threading
12
+
13
+ from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
14
+ from . import convolve
15
+
16
+ from scipy.fft._pocketfft.helper import _datacopied
17
+
18
+
19
+ _cache = threading.local()
20
+
21
+
22
+ def diff(x,order=1,period=None, _cache=_cache):
23
+ """
24
+ Return kth derivative (or integral) of a periodic sequence x.
25
+
26
+ If x_j and y_j are Fourier coefficients of periodic functions x
27
+ and y, respectively, then::
28
+
29
+ y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
30
+ y_0 = 0 if order is not 0.
31
+
32
+ Parameters
33
+ ----------
34
+ x : array_like
35
+ Input array.
36
+ order : int, optional
37
+ The order of differentiation. Default order is 1. If order is
38
+ negative, then integration is carried out under the assumption
39
+ that ``x_0 == 0``.
40
+ period : float, optional
41
+ The assumed period of the sequence. Default is ``2*pi``.
42
+
43
+ Notes
44
+ -----
45
+ If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
46
+ numerical accuracy).
47
+
48
+ For odd order and even ``len(x)``, the Nyquist mode is taken zero.
49
+
50
+ """
51
+ if isinstance(_cache, threading.local):
52
+ if not hasattr(_cache, 'diff_cache'):
53
+ _cache.diff_cache = {}
54
+ _cache = _cache.diff_cache
55
+
56
+ tmp = asarray(x)
57
+ if order == 0:
58
+ return tmp
59
+ if iscomplexobj(tmp):
60
+ return diff(tmp.real, order, period, _cache)+1j*diff(
61
+ tmp.imag, order, period, _cache)
62
+ if period is not None:
63
+ c = 2*pi/period
64
+ else:
65
+ c = 1.0
66
+ n = len(x)
67
+ omega = _cache.get((n,order,c))
68
+ if omega is None:
69
+ if len(_cache) > 20:
70
+ while _cache:
71
+ _cache.popitem()
72
+
73
+ def kernel(k,order=order,c=c):
74
+ if k:
75
+ return pow(c*k,order)
76
+ return 0
77
+ omega = convolve.init_convolution_kernel(n,kernel,d=order,
78
+ zero_nyquist=1)
79
+ _cache[(n,order,c)] = omega
80
+ overwrite_x = _datacopied(tmp, x)
81
+ return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
82
+ overwrite_x=overwrite_x)
83
+
84
+
85
+ def tilbert(x, h, period=None, _cache=_cache):
86
+ """
87
+ Return h-Tilbert transform of a periodic sequence x.
88
+
89
+ If x_j and y_j are Fourier coefficients of periodic functions x
90
+ and y, respectively, then::
91
+
92
+ y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
93
+ y_0 = 0
94
+
95
+ Parameters
96
+ ----------
97
+ x : array_like
98
+ The input array to transform.
99
+ h : float
100
+ Defines the parameter of the Tilbert transform.
101
+ period : float, optional
102
+ The assumed period of the sequence. Default period is ``2*pi``.
103
+
104
+ Returns
105
+ -------
106
+ tilbert : ndarray
107
+ The result of the transform.
108
+
109
+ Notes
110
+ -----
111
+ If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
112
+ ``tilbert(itilbert(x)) == x``.
113
+
114
+ If ``2 * pi * h / period`` is approximately 10 or larger, then
115
+ numerically ``tilbert == hilbert``
116
+ (theoretically oo-Tilbert == Hilbert).
117
+
118
+ For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
119
+
120
+ """
121
+ if isinstance(_cache, threading.local):
122
+ if not hasattr(_cache, 'tilbert_cache'):
123
+ _cache.tilbert_cache = {}
124
+ _cache = _cache.tilbert_cache
125
+
126
+ tmp = asarray(x)
127
+ if iscomplexobj(tmp):
128
+ return tilbert(tmp.real, h, period, _cache) + \
129
+ 1j * tilbert(tmp.imag, h, period, _cache)
130
+
131
+ if period is not None:
132
+ h = h * 2 * pi / period
133
+
134
+ n = len(x)
135
+ omega = _cache.get((n, h))
136
+ if omega is None:
137
+ if len(_cache) > 20:
138
+ while _cache:
139
+ _cache.popitem()
140
+
141
+ def kernel(k, h=h):
142
+ if k:
143
+ return 1.0/tanh(h*k)
144
+
145
+ return 0
146
+
147
+ omega = convolve.init_convolution_kernel(n, kernel, d=1)
148
+ _cache[(n,h)] = omega
149
+
150
+ overwrite_x = _datacopied(tmp, x)
151
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
152
+
153
+
154
+ def itilbert(x,h,period=None, _cache=_cache):
155
+ """
156
+ Return inverse h-Tilbert transform of a periodic sequence x.
157
+
158
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
159
+ and y, respectively, then::
160
+
161
+ y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
162
+ y_0 = 0
163
+
164
+ For more details, see `tilbert`.
165
+
166
+ """
167
+ if isinstance(_cache, threading.local):
168
+ if not hasattr(_cache, 'itilbert_cache'):
169
+ _cache.itilbert_cache = {}
170
+ _cache = _cache.itilbert_cache
171
+
172
+ tmp = asarray(x)
173
+ if iscomplexobj(tmp):
174
+ return itilbert(tmp.real, h, period, _cache) + \
175
+ 1j*itilbert(tmp.imag, h, period, _cache)
176
+ if period is not None:
177
+ h = h*2*pi/period
178
+ n = len(x)
179
+ omega = _cache.get((n,h))
180
+ if omega is None:
181
+ if len(_cache) > 20:
182
+ while _cache:
183
+ _cache.popitem()
184
+
185
+ def kernel(k,h=h):
186
+ if k:
187
+ return -tanh(h*k)
188
+ return 0
189
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
190
+ _cache[(n,h)] = omega
191
+ overwrite_x = _datacopied(tmp, x)
192
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
193
+
194
+
195
+ def hilbert(x, _cache=_cache):
196
+ """
197
+ Return Hilbert transform of a periodic sequence x.
198
+
199
+ If x_j and y_j are Fourier coefficients of periodic functions x
200
+ and y, respectively, then::
201
+
202
+ y_j = sqrt(-1)*sign(j) * x_j
203
+ y_0 = 0
204
+
205
+ Parameters
206
+ ----------
207
+ x : array_like
208
+ The input array, should be periodic.
209
+ _cache : dict, optional
210
+ Dictionary that contains the kernel used to do a convolution with.
211
+
212
+ Returns
213
+ -------
214
+ y : ndarray
215
+ The transformed input.
216
+
217
+ See Also
218
+ --------
219
+ scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
220
+ transform.
221
+
222
+ Notes
223
+ -----
224
+ If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
225
+
226
+ For even len(x), the Nyquist mode of x is taken zero.
227
+
228
+ The sign of the returned transform does not have a factor -1 that is more
229
+ often than not found in the definition of the Hilbert transform. Note also
230
+ that `scipy.signal.hilbert` does have an extra -1 factor compared to this
231
+ function.
232
+
233
+ """
234
+ if isinstance(_cache, threading.local):
235
+ if not hasattr(_cache, 'hilbert_cache'):
236
+ _cache.hilbert_cache = {}
237
+ _cache = _cache.hilbert_cache
238
+
239
+ tmp = asarray(x)
240
+ if iscomplexobj(tmp):
241
+ return hilbert(tmp.real, _cache) + 1j * hilbert(tmp.imag, _cache)
242
+ n = len(x)
243
+ omega = _cache.get(n)
244
+ if omega is None:
245
+ if len(_cache) > 20:
246
+ while _cache:
247
+ _cache.popitem()
248
+
249
+ def kernel(k):
250
+ if k > 0:
251
+ return 1.0
252
+ elif k < 0:
253
+ return -1.0
254
+ return 0.0
255
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
256
+ _cache[n] = omega
257
+ overwrite_x = _datacopied(tmp, x)
258
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
259
+
260
+
261
+ def ihilbert(x, _cache=_cache):
262
+ """
263
+ Return inverse Hilbert transform of a periodic sequence x.
264
+
265
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
266
+ and y, respectively, then::
267
+
268
+ y_j = -sqrt(-1)*sign(j) * x_j
269
+ y_0 = 0
270
+
271
+ """
272
+ if isinstance(_cache, threading.local):
273
+ if not hasattr(_cache, 'ihilbert_cache'):
274
+ _cache.ihilbert_cache = {}
275
+ _cache = _cache.ihilbert_cache
276
+ return -hilbert(x, _cache)
277
+
278
+
279
+ def cs_diff(x, a, b, period=None, _cache=_cache):
280
+ """
281
+ Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
282
+
283
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
284
+ and y, respectively, then::
285
+
286
+ y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
287
+ y_0 = 0
288
+
289
+ Parameters
290
+ ----------
291
+ x : array_like
292
+ The array to take the pseudo-derivative from.
293
+ a, b : float
294
+ Defines the parameters of the cosh/sinh pseudo-differential
295
+ operator.
296
+ period : float, optional
297
+ The period of the sequence. Default period is ``2*pi``.
298
+
299
+ Returns
300
+ -------
301
+ cs_diff : ndarray
302
+ Pseudo-derivative of periodic sequence `x`.
303
+
304
+ Notes
305
+ -----
306
+ For even len(`x`), the Nyquist mode of `x` is taken as zero.
307
+
308
+ """
309
+ if isinstance(_cache, threading.local):
310
+ if not hasattr(_cache, 'cs_diff_cache'):
311
+ _cache.cs_diff_cache = {}
312
+ _cache = _cache.cs_diff_cache
313
+
314
+ tmp = asarray(x)
315
+ if iscomplexobj(tmp):
316
+ return cs_diff(tmp.real, a, b, period, _cache) + \
317
+ 1j*cs_diff(tmp.imag, a, b, period, _cache)
318
+ if period is not None:
319
+ a = a*2*pi/period
320
+ b = b*2*pi/period
321
+ n = len(x)
322
+ omega = _cache.get((n,a,b))
323
+ if omega is None:
324
+ if len(_cache) > 20:
325
+ while _cache:
326
+ _cache.popitem()
327
+
328
+ def kernel(k,a=a,b=b):
329
+ if k:
330
+ return -cosh(a*k)/sinh(b*k)
331
+ return 0
332
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
333
+ _cache[(n,a,b)] = omega
334
+ overwrite_x = _datacopied(tmp, x)
335
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
336
+
337
+
338
+ def sc_diff(x, a, b, period=None, _cache=_cache):
339
+ """
340
+ Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
341
+
342
+ If x_j and y_j are Fourier coefficients of periodic functions x
343
+ and y, respectively, then::
344
+
345
+ y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
346
+ y_0 = 0
347
+
348
+ Parameters
349
+ ----------
350
+ x : array_like
351
+ Input array.
352
+ a,b : float
353
+ Defines the parameters of the sinh/cosh pseudo-differential
354
+ operator.
355
+ period : float, optional
356
+ The period of the sequence x. Default is 2*pi.
357
+
358
+ Notes
359
+ -----
360
+ ``sc_diff(cs_diff(x,a,b),b,a) == x``
361
+ For even ``len(x)``, the Nyquist mode of x is taken as zero.
362
+
363
+ """
364
+ if isinstance(_cache, threading.local):
365
+ if not hasattr(_cache, 'sc_diff_cache'):
366
+ _cache.sc_diff_cache = {}
367
+ _cache = _cache.sc_diff_cache
368
+
369
+ tmp = asarray(x)
370
+ if iscomplexobj(tmp):
371
+ return sc_diff(tmp.real, a, b, period, _cache) + \
372
+ 1j * sc_diff(tmp.imag, a, b, period, _cache)
373
+ if period is not None:
374
+ a = a*2*pi/period
375
+ b = b*2*pi/period
376
+ n = len(x)
377
+ omega = _cache.get((n,a,b))
378
+ if omega is None:
379
+ if len(_cache) > 20:
380
+ while _cache:
381
+ _cache.popitem()
382
+
383
+ def kernel(k,a=a,b=b):
384
+ if k:
385
+ return sinh(a*k)/cosh(b*k)
386
+ return 0
387
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
388
+ _cache[(n,a,b)] = omega
389
+ overwrite_x = _datacopied(tmp, x)
390
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
391
+
392
+
393
+ def ss_diff(x, a, b, period=None, _cache=_cache):
394
+ """
395
+ Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
396
+
397
+ If x_j and y_j are Fourier coefficients of periodic functions x
398
+ and y, respectively, then::
399
+
400
+ y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
401
+ y_0 = a/b * x_0
402
+
403
+ Parameters
404
+ ----------
405
+ x : array_like
406
+ The array to take the pseudo-derivative from.
407
+ a,b
408
+ Defines the parameters of the sinh/sinh pseudo-differential
409
+ operator.
410
+ period : float, optional
411
+ The period of the sequence x. Default is ``2*pi``.
412
+
413
+ Notes
414
+ -----
415
+ ``ss_diff(ss_diff(x,a,b),b,a) == x``
416
+
417
+ """
418
+ if isinstance(_cache, threading.local):
419
+ if not hasattr(_cache, 'ss_diff_cache'):
420
+ _cache.ss_diff_cache = {}
421
+ _cache = _cache.ss_diff_cache
422
+
423
+ tmp = asarray(x)
424
+ if iscomplexobj(tmp):
425
+ return ss_diff(tmp.real, a, b, period, _cache) + \
426
+ 1j*ss_diff(tmp.imag, a, b, period, _cache)
427
+ if period is not None:
428
+ a = a*2*pi/period
429
+ b = b*2*pi/period
430
+ n = len(x)
431
+ omega = _cache.get((n,a,b))
432
+ if omega is None:
433
+ if len(_cache) > 20:
434
+ while _cache:
435
+ _cache.popitem()
436
+
437
+ def kernel(k,a=a,b=b):
438
+ if k:
439
+ return sinh(a*k)/sinh(b*k)
440
+ return float(a)/b
441
+ omega = convolve.init_convolution_kernel(n,kernel)
442
+ _cache[(n,a,b)] = omega
443
+ overwrite_x = _datacopied(tmp, x)
444
+ return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
445
+
446
+
447
+ def cc_diff(x, a, b, period=None, _cache=_cache):
448
+ """
449
+ Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
450
+
451
+ If x_j and y_j are Fourier coefficients of periodic functions x
452
+ and y, respectively, then::
453
+
454
+ y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
455
+
456
+ Parameters
457
+ ----------
458
+ x : array_like
459
+ The array to take the pseudo-derivative from.
460
+ a,b : float
461
+ Defines the parameters of the sinh/sinh pseudo-differential
462
+ operator.
463
+ period : float, optional
464
+ The period of the sequence x. Default is ``2*pi``.
465
+
466
+ Returns
467
+ -------
468
+ cc_diff : ndarray
469
+ Pseudo-derivative of periodic sequence `x`.
470
+
471
+ Notes
472
+ -----
473
+ ``cc_diff(cc_diff(x,a,b),b,a) == x``
474
+
475
+ """
476
+ if isinstance(_cache, threading.local):
477
+ if not hasattr(_cache, 'cc_diff_cache'):
478
+ _cache.cc_diff_cache = {}
479
+ _cache = _cache.cc_diff_cache
480
+
481
+ tmp = asarray(x)
482
+ if iscomplexobj(tmp):
483
+ return cc_diff(tmp.real, a, b, period, _cache) + \
484
+ 1j * cc_diff(tmp.imag, a, b, period, _cache)
485
+ if period is not None:
486
+ a = a*2*pi/period
487
+ b = b*2*pi/period
488
+ n = len(x)
489
+ omega = _cache.get((n,a,b))
490
+ if omega is None:
491
+ if len(_cache) > 20:
492
+ while _cache:
493
+ _cache.popitem()
494
+
495
+ def kernel(k,a=a,b=b):
496
+ return cosh(a*k)/cosh(b*k)
497
+ omega = convolve.init_convolution_kernel(n,kernel)
498
+ _cache[(n,a,b)] = omega
499
+ overwrite_x = _datacopied(tmp, x)
500
+ return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
501
+
502
+
503
+ def shift(x, a, period=None, _cache=_cache):
504
+ """
505
+ Shift periodic sequence x by a: y(u) = x(u+a).
506
+
507
+ If x_j and y_j are Fourier coefficients of periodic functions x
508
+ and y, respectively, then::
509
+
510
+ y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
511
+
512
+ Parameters
513
+ ----------
514
+ x : array_like
515
+ The array to take the pseudo-derivative from.
516
+ a : float
517
+ Defines the parameters of the sinh/sinh pseudo-differential
518
+ period : float, optional
519
+ The period of the sequences x and y. Default period is ``2*pi``.
520
+ """
521
+ if isinstance(_cache, threading.local):
522
+ if not hasattr(_cache, 'shift_cache'):
523
+ _cache.shift_cache = {}
524
+ _cache = _cache.shift_cache
525
+
526
+ tmp = asarray(x)
527
+ if iscomplexobj(tmp):
528
+ return shift(tmp.real, a, period, _cache) + 1j * shift(
529
+ tmp.imag, a, period, _cache)
530
+ if period is not None:
531
+ a = a*2*pi/period
532
+ n = len(x)
533
+ omega = _cache.get((n,a))
534
+ if omega is None:
535
+ if len(_cache) > 20:
536
+ while _cache:
537
+ _cache.popitem()
538
+
539
+ def kernel_real(k,a=a):
540
+ return cos(a*k)
541
+
542
+ def kernel_imag(k,a=a):
543
+ return sin(a*k)
544
+ omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
545
+ zero_nyquist=0)
546
+ omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
547
+ zero_nyquist=0)
548
+ _cache[(n,a)] = omega_real,omega_imag
549
+ else:
550
+ omega_real,omega_imag = omega
551
+ overwrite_x = _datacopied(tmp, x)
552
+ return convolve.convolve_z(tmp,omega_real,omega_imag,
553
+ overwrite_x=overwrite_x)
554
+
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Real spectrum transforms (DCT, DST, MDCT)
3
+ """
4
+
5
+ __all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
6
+
7
+ from scipy.fft import _pocketfft
8
+ from ._helper import _good_shape
9
+
10
+ _inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
11
+
12
+
13
+ def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
14
+ """
15
+ Return multidimensional Discrete Cosine Transform along the specified axes.
16
+
17
+ Parameters
18
+ ----------
19
+ x : array_like
20
+ The input array.
21
+ type : {1, 2, 3, 4}, optional
22
+ Type of the DCT (see Notes). Default type is 2.
23
+ shape : int or array_like of ints or None, optional
24
+ The shape of the result. If both `shape` and `axes` (see below) are
25
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
26
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
27
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
28
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
29
+ length ``shape[i]``.
30
+ If any element of `shape` is -1, the size of the corresponding
31
+ dimension of `x` is used.
32
+ axes : int or array_like of ints or None, optional
33
+ Axes along which the DCT is computed.
34
+ The default is over all axes.
35
+ norm : {None, 'ortho'}, optional
36
+ Normalization mode (see Notes). Default is None.
37
+ overwrite_x : bool, optional
38
+ If True, the contents of `x` can be destroyed; the default is False.
39
+
40
+ Returns
41
+ -------
42
+ y : ndarray of real
43
+ The transformed input array.
44
+
45
+ See Also
46
+ --------
47
+ idctn : Inverse multidimensional DCT
48
+
49
+ Notes
50
+ -----
51
+ For full details of the DCT types and normalization modes, as well as
52
+ references, see `dct`.
53
+
54
+ Examples
55
+ --------
56
+ >>> import numpy as np
57
+ >>> from scipy.fftpack import dctn, idctn
58
+ >>> rng = np.random.default_rng()
59
+ >>> y = rng.standard_normal((16, 16))
60
+ >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
61
+ True
62
+
63
+ """
64
+ shape = _good_shape(x, shape, axes)
65
+ return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
66
+
67
+
68
+ def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
69
+ """
70
+ Return multidimensional Discrete Cosine Transform along the specified axes.
71
+
72
+ Parameters
73
+ ----------
74
+ x : array_like
75
+ The input array.
76
+ type : {1, 2, 3, 4}, optional
77
+ Type of the DCT (see Notes). Default type is 2.
78
+ shape : int or array_like of ints or None, optional
79
+ The shape of the result. If both `shape` and `axes` (see below) are
80
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
81
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
82
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
83
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
84
+ length ``shape[i]``.
85
+ If any element of `shape` is -1, the size of the corresponding
86
+ dimension of `x` is used.
87
+ axes : int or array_like of ints or None, optional
88
+ Axes along which the IDCT is computed.
89
+ The default is over all axes.
90
+ norm : {None, 'ortho'}, optional
91
+ Normalization mode (see Notes). Default is None.
92
+ overwrite_x : bool, optional
93
+ If True, the contents of `x` can be destroyed; the default is False.
94
+
95
+ Returns
96
+ -------
97
+ y : ndarray of real
98
+ The transformed input array.
99
+
100
+ See Also
101
+ --------
102
+ dctn : multidimensional DCT
103
+
104
+ Notes
105
+ -----
106
+ For full details of the IDCT types and normalization modes, as well as
107
+ references, see `idct`.
108
+
109
+ Examples
110
+ --------
111
+ >>> import numpy as np
112
+ >>> from scipy.fftpack import dctn, idctn
113
+ >>> rng = np.random.default_rng()
114
+ >>> y = rng.standard_normal((16, 16))
115
+ >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
116
+ True
117
+
118
+ """
119
+ type = _inverse_typemap[type]
120
+ shape = _good_shape(x, shape, axes)
121
+ return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
122
+
123
+
124
+ def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
125
+ """
126
+ Return multidimensional Discrete Sine Transform along the specified axes.
127
+
128
+ Parameters
129
+ ----------
130
+ x : array_like
131
+ The input array.
132
+ type : {1, 2, 3, 4}, optional
133
+ Type of the DST (see Notes). Default type is 2.
134
+ shape : int or array_like of ints or None, optional
135
+ The shape of the result. If both `shape` and `axes` (see below) are
136
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
137
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
138
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
139
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
140
+ length ``shape[i]``.
141
+ If any element of `shape` is -1, the size of the corresponding
142
+ dimension of `x` is used.
143
+ axes : int or array_like of ints or None, optional
144
+ Axes along which the DCT is computed.
145
+ The default is over all axes.
146
+ norm : {None, 'ortho'}, optional
147
+ Normalization mode (see Notes). Default is None.
148
+ overwrite_x : bool, optional
149
+ If True, the contents of `x` can be destroyed; the default is False.
150
+
151
+ Returns
152
+ -------
153
+ y : ndarray of real
154
+ The transformed input array.
155
+
156
+ See Also
157
+ --------
158
+ idstn : Inverse multidimensional DST
159
+
160
+ Notes
161
+ -----
162
+ For full details of the DST types and normalization modes, as well as
163
+ references, see `dst`.
164
+
165
+ Examples
166
+ --------
167
+ >>> import numpy as np
168
+ >>> from scipy.fftpack import dstn, idstn
169
+ >>> rng = np.random.default_rng()
170
+ >>> y = rng.standard_normal((16, 16))
171
+ >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
172
+ True
173
+
174
+ """
175
+ shape = _good_shape(x, shape, axes)
176
+ return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
177
+
178
+
179
+ def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
180
+ """
181
+ Return multidimensional Discrete Sine Transform along the specified axes.
182
+
183
+ Parameters
184
+ ----------
185
+ x : array_like
186
+ The input array.
187
+ type : {1, 2, 3, 4}, optional
188
+ Type of the DST (see Notes). Default type is 2.
189
+ shape : int or array_like of ints or None, optional
190
+ The shape of the result. If both `shape` and `axes` (see below) are
191
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
192
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
193
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
194
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
195
+ length ``shape[i]``.
196
+ If any element of `shape` is -1, the size of the corresponding
197
+ dimension of `x` is used.
198
+ axes : int or array_like of ints or None, optional
199
+ Axes along which the IDST is computed.
200
+ The default is over all axes.
201
+ norm : {None, 'ortho'}, optional
202
+ Normalization mode (see Notes). Default is None.
203
+ overwrite_x : bool, optional
204
+ If True, the contents of `x` can be destroyed; the default is False.
205
+
206
+ Returns
207
+ -------
208
+ y : ndarray of real
209
+ The transformed input array.
210
+
211
+ See Also
212
+ --------
213
+ dstn : multidimensional DST
214
+
215
+ Notes
216
+ -----
217
+ For full details of the IDST types and normalization modes, as well as
218
+ references, see `idst`.
219
+
220
+ Examples
221
+ --------
222
+ >>> import numpy as np
223
+ >>> from scipy.fftpack import dstn, idstn
224
+ >>> rng = np.random.default_rng()
225
+ >>> y = rng.standard_normal((16, 16))
226
+ >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
227
+ True
228
+
229
+ """
230
+ type = _inverse_typemap[type]
231
+ shape = _good_shape(x, shape, axes)
232
+ return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
233
+
234
+
235
+ def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
236
+ r"""
237
+ Return the Discrete Cosine Transform of arbitrary type sequence x.
238
+
239
+ Parameters
240
+ ----------
241
+ x : array_like
242
+ The input array.
243
+ type : {1, 2, 3, 4}, optional
244
+ Type of the DCT (see Notes). Default type is 2.
245
+ n : int, optional
246
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
247
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
248
+ default results in ``n = x.shape[axis]``.
249
+ axis : int, optional
250
+ Axis along which the dct is computed; the default is over the
251
+ last axis (i.e., ``axis=-1``).
252
+ norm : {None, 'ortho'}, optional
253
+ Normalization mode (see Notes). Default is None.
254
+ overwrite_x : bool, optional
255
+ If True, the contents of `x` can be destroyed; the default is False.
256
+
257
+ Returns
258
+ -------
259
+ y : ndarray of real
260
+ The transformed input array.
261
+
262
+ See Also
263
+ --------
264
+ idct : Inverse DCT
265
+
266
+ Notes
267
+ -----
268
+ For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
269
+ MATLAB ``dct(x)``.
270
+
271
+ There are, theoretically, 8 types of the DCT, only the first 4 types are
272
+ implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
273
+ Inverse DCT generally refers to DCT type 3.
274
+
275
+ **Type I**
276
+
277
+ There are several definitions of the DCT-I; we use the following
278
+ (for ``norm=None``)
279
+
280
+ .. math::
281
+
282
+ y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
283
+ \frac{\pi k n}{N-1} \right)
284
+
285
+ If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
286
+ factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
287
+ ``f``
288
+
289
+ .. math::
290
+
291
+ f = \begin{cases}
292
+ \frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
293
+ \frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
294
+
295
+ .. versionadded:: 1.2.0
296
+ Orthonormalization in DCT-I.
297
+
298
+ .. note::
299
+ The DCT-I is only supported for input size > 1.
300
+
301
+ **Type II**
302
+
303
+ There are several definitions of the DCT-II; we use the following
304
+ (for ``norm=None``)
305
+
306
+ .. math::
307
+
308
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
309
+
310
+ If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
311
+
312
+ .. math::
313
+ f = \begin{cases}
314
+ \sqrt{\frac{1}{4N}} & \text{if }k=0, \\
315
+ \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
316
+
317
+ which makes the corresponding matrix of coefficients orthonormal
318
+ (``O @ O.T = np.eye(N)``).
319
+
320
+ **Type III**
321
+
322
+ There are several definitions, we use the following (for ``norm=None``)
323
+
324
+ .. math::
325
+
326
+ y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
327
+
328
+ or, for ``norm='ortho'``
329
+
330
+ .. math::
331
+
332
+ y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
333
+ \cos\left(\frac{\pi(2k+1)n}{2N}\right)
334
+
335
+ The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
336
+ to a factor ``2N``. The orthonormalized DCT-III is exactly the inverse of
337
+ the orthonormalized DCT-II.
338
+
339
+ **Type IV**
340
+
341
+ There are several definitions of the DCT-IV; we use the following
342
+ (for ``norm=None``)
343
+
344
+ .. math::
345
+
346
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
347
+
348
+ If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
349
+
350
+ .. math::
351
+
352
+ f = \frac{1}{\sqrt{2N}}
353
+
354
+ .. versionadded:: 1.2.0
355
+ Support for DCT-IV.
356
+
357
+ References
358
+ ----------
359
+ .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
360
+ Makhoul, `IEEE Transactions on acoustics, speech and signal
361
+ processing` vol. 28(1), pp. 27-34,
362
+ :doi:`10.1109/TASSP.1980.1163351` (1980).
363
+ .. [2] Wikipedia, "Discrete cosine transform",
364
+ https://en.wikipedia.org/wiki/Discrete_cosine_transform
365
+
366
+ Examples
367
+ --------
368
+ The Type 1 DCT is equivalent to the FFT (though faster) for real,
369
+ even-symmetrical inputs. The output is also real and even-symmetrical.
370
+ Half of the FFT input is used to generate half of the FFT output:
371
+
372
+ >>> from scipy.fftpack import fft, dct
373
+ >>> import numpy as np
374
+ >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
375
+ array([ 30., -8., 6., -2., 6., -8.])
376
+ >>> dct(np.array([4., 3., 5., 10.]), 1)
377
+ array([ 30., -8., 6., -2.])
378
+
379
+ """
380
+ return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
381
+
382
+
383
+ def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
384
+ """
385
+ Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
386
+
387
+ Parameters
388
+ ----------
389
+ x : array_like
390
+ The input array.
391
+ type : {1, 2, 3, 4}, optional
392
+ Type of the DCT (see Notes). Default type is 2.
393
+ n : int, optional
394
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
395
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
396
+ default results in ``n = x.shape[axis]``.
397
+ axis : int, optional
398
+ Axis along which the idct is computed; the default is over the
399
+ last axis (i.e., ``axis=-1``).
400
+ norm : {None, 'ortho'}, optional
401
+ Normalization mode (see Notes). Default is None.
402
+ overwrite_x : bool, optional
403
+ If True, the contents of `x` can be destroyed; the default is False.
404
+
405
+ Returns
406
+ -------
407
+ idct : ndarray of real
408
+ The transformed input array.
409
+
410
+ See Also
411
+ --------
412
+ dct : Forward DCT
413
+
414
+ Notes
415
+ -----
416
+ For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
417
+ MATLAB ``idct(x)``.
418
+
419
+ 'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
420
+
421
+ IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
422
+ 3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
423
+ of type 4. For the definition of these types, see `dct`.
424
+
425
+ Examples
426
+ --------
427
+ The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
428
+ inputs. The output is also real and even-symmetrical. Half of the IFFT
429
+ input is used to generate half of the IFFT output:
430
+
431
+ >>> from scipy.fftpack import ifft, idct
432
+ >>> import numpy as np
433
+ >>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
434
+ array([ 4., 3., 5., 10., 5., 3.])
435
+ >>> idct(np.array([ 30., -8., 6., -2.]), 1) / 6
436
+ array([ 4., 3., 5., 10.])
437
+
438
+ """
439
+ type = _inverse_typemap[type]
440
+ return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
441
+
442
+
443
+ def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
444
+ r"""
445
+ Return the Discrete Sine Transform of arbitrary type sequence x.
446
+
447
+ Parameters
448
+ ----------
449
+ x : array_like
450
+ The input array.
451
+ type : {1, 2, 3, 4}, optional
452
+ Type of the DST (see Notes). Default type is 2.
453
+ n : int, optional
454
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
455
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
456
+ default results in ``n = x.shape[axis]``.
457
+ axis : int, optional
458
+ Axis along which the dst is computed; the default is over the
459
+ last axis (i.e., ``axis=-1``).
460
+ norm : {None, 'ortho'}, optional
461
+ Normalization mode (see Notes). Default is None.
462
+ overwrite_x : bool, optional
463
+ If True, the contents of `x` can be destroyed; the default is False.
464
+
465
+ Returns
466
+ -------
467
+ dst : ndarray of reals
468
+ The transformed input array.
469
+
470
+ See Also
471
+ --------
472
+ idst : Inverse DST
473
+
474
+ Notes
475
+ -----
476
+ For a single dimension array ``x``.
477
+
478
+ There are, theoretically, 8 types of the DST for different combinations of
479
+ even/odd boundary conditions and boundary off sets [1]_, only the first
480
+ 4 types are implemented in scipy.
481
+
482
+ **Type I**
483
+
484
+ There are several definitions of the DST-I; we use the following
485
+ for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
486
+
487
+ .. math::
488
+
489
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
490
+
491
+ Note that the DST-I is only supported for input size > 1.
492
+ The (unnormalized) DST-I is its own inverse, up to a factor ``2(N+1)``.
493
+ The orthonormalized DST-I is exactly its own inverse.
494
+
495
+ **Type II**
496
+
497
+ There are several definitions of the DST-II; we use the following for
498
+ ``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
499
+ `n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
500
+
501
+ .. math::
502
+
503
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
504
+
505
+ if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
506
+
507
+ .. math::
508
+
509
+ f = \begin{cases}
510
+ \sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
511
+ \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
512
+
513
+ **Type III**
514
+
515
+ There are several definitions of the DST-III, we use the following (for
516
+ ``norm=None``). DST-III assumes the input is odd around `n=-1` and even
517
+ around `n=N-1`
518
+
519
+ .. math::
520
+
521
+ y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
522
+ \frac{\pi(2k+1)(n+1)}{2N}\right)
523
+
524
+ The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
525
+ to a factor ``2N``. The orthonormalized DST-III is exactly the inverse of the
526
+ orthonormalized DST-II.
527
+
528
+ .. versionadded:: 0.11.0
529
+
530
+ **Type IV**
531
+
532
+ There are several definitions of the DST-IV, we use the following (for
533
+ ``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
534
+ around `n=N-0.5`
535
+
536
+ .. math::
537
+
538
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
539
+
540
+ The (unnormalized) DST-IV is its own inverse, up to a factor ``2N``. The
541
+ orthonormalized DST-IV is exactly its own inverse.
542
+
543
+ .. versionadded:: 1.2.0
544
+ Support for DST-IV.
545
+
546
+ References
547
+ ----------
548
+ .. [1] Wikipedia, "Discrete sine transform",
549
+ https://en.wikipedia.org/wiki/Discrete_sine_transform
550
+
551
+ """
552
+ return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
553
+
554
+
555
+ def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
556
+ """
557
+ Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
558
+
559
+ Parameters
560
+ ----------
561
+ x : array_like
562
+ The input array.
563
+ type : {1, 2, 3, 4}, optional
564
+ Type of the DST (see Notes). Default type is 2.
565
+ n : int, optional
566
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
567
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
568
+ default results in ``n = x.shape[axis]``.
569
+ axis : int, optional
570
+ Axis along which the idst is computed; the default is over the
571
+ last axis (i.e., ``axis=-1``).
572
+ norm : {None, 'ortho'}, optional
573
+ Normalization mode (see Notes). Default is None.
574
+ overwrite_x : bool, optional
575
+ If True, the contents of `x` can be destroyed; the default is False.
576
+
577
+ Returns
578
+ -------
579
+ idst : ndarray of real
580
+ The transformed input array.
581
+
582
+ See Also
583
+ --------
584
+ dst : Forward DST
585
+
586
+ Notes
587
+ -----
588
+ 'The' IDST is the IDST of type 2, which is the same as DST of type 3.
589
+
590
+ IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
591
+ 3, and IDST of type 3 is the DST of type 2. For the definition of these
592
+ types, see `dst`.
593
+
594
+ .. versionadded:: 0.11.0
595
+
596
+ """
597
+ type = _inverse_typemap[type]
598
+ return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/basic.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'fft','ifft','fftn','ifftn','rfft','irfft',
9
+ 'fft2','ifft2'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="fftpack", module="basic",
19
+ private_modules=["_basic"], all=__all__,
20
+ attribute=name)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/helper.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
9
+ ]
10
+
11
+
12
+ def __dir__():
13
+ return __all__
14
+
15
+
16
+ def __getattr__(name):
17
+ return _sub_module_deprecation(sub_package="fftpack", module="helper",
18
+ private_modules=["_helper"], all=__all__,
19
+ attribute=name)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'diff',
9
+ 'tilbert', 'itilbert', 'hilbert', 'ihilbert',
10
+ 'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
11
+ 'shift', 'convolve'
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
21
+ private_modules=["_pseudo_diffs"], all=__all__,
22
+ attribute=name)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
9
+ ]
10
+
11
+
12
+ def __dir__():
13
+ return __all__
14
+
15
+
16
+ def __getattr__(name):
17
+ return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
18
+ private_modules=["_realtransforms"], all=__all__,
19
+ attribute=name)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
4
+ assert_array_almost_equal_nulp, assert_array_less)
5
+ import pytest
6
+ from pytest import raises as assert_raises
7
+ from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2
8
+
9
+ from numpy import (arange, array, asarray, zeros, dot, exp, pi,
10
+ swapaxes, double, cdouble)
11
+ import numpy as np
12
+ import numpy.fft
13
+ from numpy.random import rand
14
+
15
+ # "large" composite numbers supported by FFTPACK
16
+ LARGE_COMPOSITE_SIZES = [
17
+ 2**13,
18
+ 2**5 * 3**5,
19
+ 2**3 * 3**3 * 5**2,
20
+ ]
21
+ SMALL_COMPOSITE_SIZES = [
22
+ 2,
23
+ 2*3*5,
24
+ 2*2*3*3,
25
+ ]
26
+ # prime
27
+ LARGE_PRIME_SIZES = [
28
+ 2011
29
+ ]
30
+ SMALL_PRIME_SIZES = [
31
+ 29
32
+ ]
33
+
34
+
35
+ def _assert_close_in_norm(x, y, rtol, size, rdt):
36
+ # helper function for testing
37
+ err_msg = f"size: {size} rdt: {rdt}"
38
+ assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
39
+
40
+
41
+ def random(size):
42
+ return rand(*size)
43
+
44
+
45
+ def direct_dft(x):
46
+ x = asarray(x)
47
+ n = len(x)
48
+ y = zeros(n, dtype=cdouble)
49
+ w = -arange(n)*(2j*pi/n)
50
+ for i in range(n):
51
+ y[i] = dot(exp(i*w), x)
52
+ return y
53
+
54
+
55
+ def direct_idft(x):
56
+ x = asarray(x)
57
+ n = len(x)
58
+ y = zeros(n, dtype=cdouble)
59
+ w = arange(n)*(2j*pi/n)
60
+ for i in range(n):
61
+ y[i] = dot(exp(i*w), x)/n
62
+ return y
63
+
64
+
65
+ def direct_dftn(x):
66
+ x = asarray(x)
67
+ for axis in range(len(x.shape)):
68
+ x = fft(x, axis=axis)
69
+ return x
70
+
71
+
72
+ def direct_idftn(x):
73
+ x = asarray(x)
74
+ for axis in range(len(x.shape)):
75
+ x = ifft(x, axis=axis)
76
+ return x
77
+
78
+
79
+ def direct_rdft(x):
80
+ x = asarray(x)
81
+ n = len(x)
82
+ w = -arange(n)*(2j*pi/n)
83
+ r = zeros(n, dtype=double)
84
+ for i in range(n//2+1):
85
+ y = dot(exp(i*w), x)
86
+ if i:
87
+ r[2*i-1] = y.real
88
+ if 2*i < n:
89
+ r[2*i] = y.imag
90
+ else:
91
+ r[0] = y.real
92
+ return r
93
+
94
+
95
+ def direct_irdft(x):
96
+ x = asarray(x)
97
+ n = len(x)
98
+ x1 = zeros(n, dtype=cdouble)
99
+ for i in range(n//2+1):
100
+ if i:
101
+ if 2*i < n:
102
+ x1[i] = x[2*i-1] + 1j*x[2*i]
103
+ x1[n-i] = x[2*i-1] - 1j*x[2*i]
104
+ else:
105
+ x1[i] = x[2*i-1]
106
+ else:
107
+ x1[0] = x[0]
108
+ return direct_idft(x1).real
109
+
110
+
111
+ class _TestFFTBase:
112
+ def setup_method(self):
113
+ self.cdt = None
114
+ self.rdt = None
115
+ np.random.seed(1234)
116
+
117
+ def test_definition(self):
118
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
119
+ y = fft(x)
120
+ assert_equal(y.dtype, self.cdt)
121
+ y1 = direct_dft(x)
122
+ assert_array_almost_equal(y,y1)
123
+ x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
124
+ assert_array_almost_equal(fft(x),direct_dft(x))
125
+
126
+ def test_n_argument_real(self):
127
+ x1 = np.array([1,2,3,4], dtype=self.rdt)
128
+ x2 = np.array([1,2,3,4], dtype=self.rdt)
129
+ y = fft([x1,x2],n=4)
130
+ assert_equal(y.dtype, self.cdt)
131
+ assert_equal(y.shape,(2,4))
132
+ assert_array_almost_equal(y[0],direct_dft(x1))
133
+ assert_array_almost_equal(y[1],direct_dft(x2))
134
+
135
+ def _test_n_argument_complex(self):
136
+ x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
137
+ x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
138
+ y = fft([x1,x2],n=4)
139
+ assert_equal(y.dtype, self.cdt)
140
+ assert_equal(y.shape,(2,4))
141
+ assert_array_almost_equal(y[0],direct_dft(x1))
142
+ assert_array_almost_equal(y[1],direct_dft(x2))
143
+
144
+ def test_invalid_sizes(self):
145
+ assert_raises(ValueError, fft, [])
146
+ assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
147
+
148
+
149
+ class TestDoubleFFT(_TestFFTBase):
150
+ def setup_method(self):
151
+ self.cdt = np.complex128
152
+ self.rdt = np.float64
153
+
154
+
155
+ class TestSingleFFT(_TestFFTBase):
156
+ def setup_method(self):
157
+ self.cdt = np.complex64
158
+ self.rdt = np.float32
159
+
160
+ reason = ("single-precision FFT implementation is partially disabled, "
161
+ "until accuracy issues with large prime powers are resolved")
162
+
163
+ @pytest.mark.xfail(run=False, reason=reason)
164
+ def test_notice(self):
165
+ pass
166
+
167
+
168
+ class TestFloat16FFT:
169
+
170
+ def test_1_argument_real(self):
171
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
172
+ y = fft(x1, n=4)
173
+ assert_equal(y.dtype, np.complex64)
174
+ assert_equal(y.shape, (4, ))
175
+ assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
176
+
177
+ def test_n_argument_real(self):
178
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
179
+ x2 = np.array([1, 2, 3, 4], dtype=np.float16)
180
+ y = fft([x1, x2], n=4)
181
+ assert_equal(y.dtype, np.complex64)
182
+ assert_equal(y.shape, (2, 4))
183
+ assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
184
+ assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
185
+
186
+
187
+ class _TestIFFTBase:
188
+ def setup_method(self):
189
+ np.random.seed(1234)
190
+
191
+ def test_definition(self):
192
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
193
+ y = ifft(x)
194
+ y1 = direct_idft(x)
195
+ assert_equal(y.dtype, self.cdt)
196
+ assert_array_almost_equal(y,y1)
197
+
198
+ x = np.array([1,2,3,4+0j,5], self.cdt)
199
+ assert_array_almost_equal(ifft(x),direct_idft(x))
200
+
201
+ def test_definition_real(self):
202
+ x = np.array([1,2,3,4,1,2,3,4], self.rdt)
203
+ y = ifft(x)
204
+ assert_equal(y.dtype, self.cdt)
205
+ y1 = direct_idft(x)
206
+ assert_array_almost_equal(y,y1)
207
+
208
+ x = np.array([1,2,3,4,5], dtype=self.rdt)
209
+ assert_equal(y.dtype, self.cdt)
210
+ assert_array_almost_equal(ifft(x),direct_idft(x))
211
+
212
+ def test_random_complex(self):
213
+ for size in [1,51,111,100,200,64,128,256,1024]:
214
+ x = random([size]).astype(self.cdt)
215
+ x = random([size]).astype(self.cdt) + 1j*x
216
+ y1 = ifft(fft(x))
217
+ y2 = fft(ifft(x))
218
+ assert_equal(y1.dtype, self.cdt)
219
+ assert_equal(y2.dtype, self.cdt)
220
+ assert_array_almost_equal(y1, x)
221
+ assert_array_almost_equal(y2, x)
222
+
223
+ def test_random_real(self):
224
+ for size in [1,51,111,100,200,64,128,256,1024]:
225
+ x = random([size]).astype(self.rdt)
226
+ y1 = ifft(fft(x))
227
+ y2 = fft(ifft(x))
228
+ assert_equal(y1.dtype, self.cdt)
229
+ assert_equal(y2.dtype, self.cdt)
230
+ assert_array_almost_equal(y1, x)
231
+ assert_array_almost_equal(y2, x)
232
+
233
+ def test_size_accuracy(self):
234
+ # Sanity check for the accuracy for prime and non-prime sized inputs
235
+ if self.rdt == np.float32:
236
+ rtol = 1e-5
237
+ elif self.rdt == np.float64:
238
+ rtol = 1e-10
239
+
240
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
241
+ np.random.seed(1234)
242
+ x = np.random.rand(size).astype(self.rdt)
243
+ y = ifft(fft(x))
244
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
245
+ y = fft(ifft(x))
246
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
247
+
248
+ x = (x + 1j*np.random.rand(size)).astype(self.cdt)
249
+ y = ifft(fft(x))
250
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
251
+ y = fft(ifft(x))
252
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
253
+
254
+ def test_invalid_sizes(self):
255
+ assert_raises(ValueError, ifft, [])
256
+ assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
257
+
258
+
259
+ class TestDoubleIFFT(_TestIFFTBase):
260
+ def setup_method(self):
261
+ self.cdt = np.complex128
262
+ self.rdt = np.float64
263
+
264
+
265
+ class TestSingleIFFT(_TestIFFTBase):
266
+ def setup_method(self):
267
+ self.cdt = np.complex64
268
+ self.rdt = np.float32
269
+
270
+
271
+ class _TestRFFTBase:
272
+ def setup_method(self):
273
+ np.random.seed(1234)
274
+
275
+ def test_definition(self):
276
+ for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
277
+ x = np.array(t, dtype=self.rdt)
278
+ y = rfft(x)
279
+ y1 = direct_rdft(x)
280
+ assert_array_almost_equal(y,y1)
281
+ assert_equal(y.dtype, self.rdt)
282
+
283
+ def test_invalid_sizes(self):
284
+ assert_raises(ValueError, rfft, [])
285
+ assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
286
+
287
+ # See gh-5790
288
+ class MockSeries:
289
+ def __init__(self, data):
290
+ self.data = np.asarray(data)
291
+
292
+ def __getattr__(self, item):
293
+ try:
294
+ return getattr(self.data, item)
295
+ except AttributeError as e:
296
+ raise AttributeError("'MockSeries' object "
297
+ f"has no attribute '{item}'") from e
298
+
299
+ def test_non_ndarray_with_dtype(self):
300
+ x = np.array([1., 2., 3., 4., 5.])
301
+ xs = _TestRFFTBase.MockSeries(x)
302
+
303
+ expected = [1, 2, 3, 4, 5]
304
+ rfft(xs)
305
+
306
+ # Data should not have been overwritten
307
+ assert_equal(x, expected)
308
+ assert_equal(xs.data, expected)
309
+
310
+ def test_complex_input(self):
311
+ assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64))
312
+
313
+
314
+ class TestRFFTDouble(_TestRFFTBase):
315
+ def setup_method(self):
316
+ self.cdt = np.complex128
317
+ self.rdt = np.float64
318
+
319
+
320
+ class TestRFFTSingle(_TestRFFTBase):
321
+ def setup_method(self):
322
+ self.cdt = np.complex64
323
+ self.rdt = np.float32
324
+
325
+
326
+ class _TestIRFFTBase:
327
+ def setup_method(self):
328
+ np.random.seed(1234)
329
+
330
+ def test_definition(self):
331
+ x1 = [1,2,3,4,1,2,3,4]
332
+ x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
333
+ x2 = [1,2,3,4,1,2,3,4,5]
334
+ x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
335
+
336
+ def _test(x, xr):
337
+ y = irfft(np.array(x, dtype=self.rdt))
338
+ y1 = direct_irdft(x)
339
+ assert_equal(y.dtype, self.rdt)
340
+ assert_array_almost_equal(y,y1, decimal=self.ndec)
341
+ assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
342
+
343
+ _test(x1, x1_1)
344
+ _test(x2, x2_1)
345
+
346
+ def test_random_real(self):
347
+ for size in [1,51,111,100,200,64,128,256,1024]:
348
+ x = random([size]).astype(self.rdt)
349
+ y1 = irfft(rfft(x))
350
+ y2 = rfft(irfft(x))
351
+ assert_equal(y1.dtype, self.rdt)
352
+ assert_equal(y2.dtype, self.rdt)
353
+ assert_array_almost_equal(y1, x, decimal=self.ndec,
354
+ err_msg="size=%d" % size)
355
+ assert_array_almost_equal(y2, x, decimal=self.ndec,
356
+ err_msg="size=%d" % size)
357
+
358
+ def test_size_accuracy(self):
359
+ # Sanity check for the accuracy for prime and non-prime sized inputs
360
+ if self.rdt == np.float32:
361
+ rtol = 1e-5
362
+ elif self.rdt == np.float64:
363
+ rtol = 1e-10
364
+
365
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
366
+ np.random.seed(1234)
367
+ x = np.random.rand(size).astype(self.rdt)
368
+ y = irfft(rfft(x))
369
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
370
+ y = rfft(irfft(x))
371
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
372
+
373
+ def test_invalid_sizes(self):
374
+ assert_raises(ValueError, irfft, [])
375
+ assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
376
+
377
+ def test_complex_input(self):
378
+ assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
379
+
380
+
381
+ # self.ndec is bogus; we should have a assert_array_approx_equal for number of
382
+ # significant digits
383
+
384
+ class TestIRFFTDouble(_TestIRFFTBase):
385
+ def setup_method(self):
386
+ self.cdt = np.complex128
387
+ self.rdt = np.float64
388
+ self.ndec = 14
389
+
390
+
391
+ class TestIRFFTSingle(_TestIRFFTBase):
392
+ def setup_method(self):
393
+ self.cdt = np.complex64
394
+ self.rdt = np.float32
395
+ self.ndec = 5
396
+
397
+
398
+ class Testfft2:
399
+ def setup_method(self):
400
+ np.random.seed(1234)
401
+
402
+ def test_regression_244(self):
403
+ """FFT returns wrong result with axes parameter."""
404
+ # fftn (and hence fft2) used to break when both axes and shape were
405
+ # used
406
+ x = numpy.ones((4, 4, 2))
407
+ y = fft2(x, shape=(8, 8), axes=(-3, -2))
408
+ y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
409
+ assert_array_almost_equal(y, y_r)
410
+
411
+ def test_invalid_sizes(self):
412
+ assert_raises(ValueError, fft2, [[]])
413
+ assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
414
+
415
+
416
+ class TestFftnSingle:
417
+ def setup_method(self):
418
+ np.random.seed(1234)
419
+
420
+ def test_definition(self):
421
+ x = [[1, 2, 3],
422
+ [4, 5, 6],
423
+ [7, 8, 9]]
424
+ y = fftn(np.array(x, np.float32))
425
+ assert_(y.dtype == np.complex64,
426
+ msg="double precision output with single precision")
427
+
428
+ y_r = np.array(fftn(x), np.complex64)
429
+ assert_array_almost_equal_nulp(y, y_r)
430
+
431
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
432
+ def test_size_accuracy_small(self, size):
433
+ rng = np.random.default_rng(1234)
434
+ x = rng.random((size, size)) + 1j*rng.random((size, size))
435
+ y1 = fftn(x.real.astype(np.float32))
436
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
437
+
438
+ assert_equal(y1.dtype, np.complex64)
439
+ assert_array_almost_equal_nulp(y1, y2, 2000)
440
+
441
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
442
+ def test_size_accuracy_large(self, size):
443
+ rand = np.random.default_rng(1234)
444
+ x = rand.random((size, 3)) + 1j*rand.random((size, 3))
445
+ y1 = fftn(x.real.astype(np.float32))
446
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
447
+
448
+ assert_equal(y1.dtype, np.complex64)
449
+ assert_array_almost_equal_nulp(y1, y2, 2000)
450
+
451
+ def test_definition_float16(self):
452
+ x = [[1, 2, 3],
453
+ [4, 5, 6],
454
+ [7, 8, 9]]
455
+ y = fftn(np.array(x, np.float16))
456
+ assert_equal(y.dtype, np.complex64)
457
+ y_r = np.array(fftn(x), np.complex64)
458
+ assert_array_almost_equal_nulp(y, y_r)
459
+
460
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
461
+ def test_float16_input_small(self, size):
462
+ rng = np.random.default_rng(1234)
463
+ x = rng.random((size, size)) + 1j * rng.random((size, size))
464
+ y1 = fftn(x.real.astype(np.float16))
465
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
466
+
467
+ assert_equal(y1.dtype, np.complex64)
468
+ assert_array_almost_equal_nulp(y1, y2, 5e5)
469
+
470
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
471
+ def test_float16_input_large(self, size):
472
+ rng = np.random.default_rng(1234)
473
+ x = rng.random((size, 3)) + 1j*rng.random((size, 3))
474
+ y1 = fftn(x.real.astype(np.float16))
475
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
476
+
477
+ assert_equal(y1.dtype, np.complex64)
478
+ assert_array_almost_equal_nulp(y1, y2, 2e6)
479
+
480
+
481
+ class TestFftn:
482
+ def setup_method(self):
483
+ np.random.seed(1234)
484
+
485
+ def test_definition(self):
486
+ x = [[1, 2, 3],
487
+ [4, 5, 6],
488
+ [7, 8, 9]]
489
+ y = fftn(x)
490
+ assert_array_almost_equal(y, direct_dftn(x))
491
+
492
+ x = random((20, 26))
493
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
494
+
495
+ x = random((5, 4, 3, 20))
496
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
497
+
498
+ def test_axes_argument(self):
499
+ # plane == ji_plane, x== kji_space
500
+ plane1 = [[1, 2, 3],
501
+ [4, 5, 6],
502
+ [7, 8, 9]]
503
+ plane2 = [[10, 11, 12],
504
+ [13, 14, 15],
505
+ [16, 17, 18]]
506
+ plane3 = [[19, 20, 21],
507
+ [22, 23, 24],
508
+ [25, 26, 27]]
509
+ ki_plane1 = [[1, 2, 3],
510
+ [10, 11, 12],
511
+ [19, 20, 21]]
512
+ ki_plane2 = [[4, 5, 6],
513
+ [13, 14, 15],
514
+ [22, 23, 24]]
515
+ ki_plane3 = [[7, 8, 9],
516
+ [16, 17, 18],
517
+ [25, 26, 27]]
518
+ jk_plane1 = [[1, 10, 19],
519
+ [4, 13, 22],
520
+ [7, 16, 25]]
521
+ jk_plane2 = [[2, 11, 20],
522
+ [5, 14, 23],
523
+ [8, 17, 26]]
524
+ jk_plane3 = [[3, 12, 21],
525
+ [6, 15, 24],
526
+ [9, 18, 27]]
527
+ kj_plane1 = [[1, 4, 7],
528
+ [10, 13, 16], [19, 22, 25]]
529
+ kj_plane2 = [[2, 5, 8],
530
+ [11, 14, 17], [20, 23, 26]]
531
+ kj_plane3 = [[3, 6, 9],
532
+ [12, 15, 18], [21, 24, 27]]
533
+ ij_plane1 = [[1, 4, 7],
534
+ [2, 5, 8],
535
+ [3, 6, 9]]
536
+ ij_plane2 = [[10, 13, 16],
537
+ [11, 14, 17],
538
+ [12, 15, 18]]
539
+ ij_plane3 = [[19, 22, 25],
540
+ [20, 23, 26],
541
+ [21, 24, 27]]
542
+ ik_plane1 = [[1, 10, 19],
543
+ [2, 11, 20],
544
+ [3, 12, 21]]
545
+ ik_plane2 = [[4, 13, 22],
546
+ [5, 14, 23],
547
+ [6, 15, 24]]
548
+ ik_plane3 = [[7, 16, 25],
549
+ [8, 17, 26],
550
+ [9, 18, 27]]
551
+ ijk_space = [jk_plane1, jk_plane2, jk_plane3]
552
+ ikj_space = [kj_plane1, kj_plane2, kj_plane3]
553
+ jik_space = [ik_plane1, ik_plane2, ik_plane3]
554
+ jki_space = [ki_plane1, ki_plane2, ki_plane3]
555
+ kij_space = [ij_plane1, ij_plane2, ij_plane3]
556
+ x = array([plane1, plane2, plane3])
557
+
558
+ assert_array_almost_equal(fftn(x),
559
+ fftn(x, axes=(-3, -2, -1))) # kji_space
560
+ assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
561
+ assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
562
+ y = fftn(x, axes=(2, 1, 0)) # ijk_space
563
+ assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
564
+ y = fftn(x, axes=(2, 0, 1)) # ikj_space
565
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
566
+ fftn(ikj_space))
567
+ y = fftn(x, axes=(1, 2, 0)) # jik_space
568
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
569
+ fftn(jik_space))
570
+ y = fftn(x, axes=(1, 0, 2)) # jki_space
571
+ assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
572
+ y = fftn(x, axes=(0, 2, 1)) # kij_space
573
+ assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
574
+
575
+ y = fftn(x, axes=(-2, -1)) # ji_plane
576
+ assert_array_almost_equal(fftn(plane1), y[0])
577
+ assert_array_almost_equal(fftn(plane2), y[1])
578
+ assert_array_almost_equal(fftn(plane3), y[2])
579
+
580
+ y = fftn(x, axes=(1, 2)) # ji_plane
581
+ assert_array_almost_equal(fftn(plane1), y[0])
582
+ assert_array_almost_equal(fftn(plane2), y[1])
583
+ assert_array_almost_equal(fftn(plane3), y[2])
584
+
585
+ y = fftn(x, axes=(-3, -2)) # kj_plane
586
+ assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
587
+ assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
588
+ assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
589
+
590
+ y = fftn(x, axes=(-3, -1)) # ki_plane
591
+ assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
592
+ assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
593
+ assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
594
+
595
+ y = fftn(x, axes=(-1, -2)) # ij_plane
596
+ assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
597
+ assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
598
+ assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
599
+
600
+ y = fftn(x, axes=(-1, -3)) # ik_plane
601
+ assert_array_almost_equal(fftn(ik_plane1),
602
+ swapaxes(y[:, 0, :], -1, -2))
603
+ assert_array_almost_equal(fftn(ik_plane2),
604
+ swapaxes(y[:, 1, :], -1, -2))
605
+ assert_array_almost_equal(fftn(ik_plane3),
606
+ swapaxes(y[:, 2, :], -1, -2))
607
+
608
+ y = fftn(x, axes=(-2, -3)) # jk_plane
609
+ assert_array_almost_equal(fftn(jk_plane1),
610
+ swapaxes(y[:, :, 0], -1, -2))
611
+ assert_array_almost_equal(fftn(jk_plane2),
612
+ swapaxes(y[:, :, 1], -1, -2))
613
+ assert_array_almost_equal(fftn(jk_plane3),
614
+ swapaxes(y[:, :, 2], -1, -2))
615
+
616
+ y = fftn(x, axes=(-1,)) # i_line
617
+ for i in range(3):
618
+ for j in range(3):
619
+ assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
620
+ y = fftn(x, axes=(-2,)) # j_line
621
+ for i in range(3):
622
+ for j in range(3):
623
+ assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
624
+ y = fftn(x, axes=(0,)) # k_line
625
+ for i in range(3):
626
+ for j in range(3):
627
+ assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
628
+
629
+ y = fftn(x, axes=()) # point
630
+ assert_array_almost_equal(y, x)
631
+
632
+ def test_shape_argument(self):
633
+ small_x = [[1, 2, 3],
634
+ [4, 5, 6]]
635
+ large_x1 = [[1, 2, 3, 0],
636
+ [4, 5, 6, 0],
637
+ [0, 0, 0, 0],
638
+ [0, 0, 0, 0]]
639
+
640
+ y = fftn(small_x, shape=(4, 4))
641
+ assert_array_almost_equal(y, fftn(large_x1))
642
+
643
+ y = fftn(small_x, shape=(3, 4))
644
+ assert_array_almost_equal(y, fftn(large_x1[:-1]))
645
+
646
+ def test_shape_axes_argument(self):
647
+ small_x = [[1, 2, 3],
648
+ [4, 5, 6],
649
+ [7, 8, 9]]
650
+ large_x1 = array([[1, 2, 3, 0],
651
+ [4, 5, 6, 0],
652
+ [7, 8, 9, 0],
653
+ [0, 0, 0, 0]])
654
+ y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
655
+ assert_array_almost_equal(y, fftn(large_x1))
656
+ y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
657
+
658
+ assert_array_almost_equal(y, swapaxes(
659
+ fftn(swapaxes(large_x1, -1, -2)), -1, -2))
660
+
661
+ def test_shape_axes_argument2(self):
662
+ # Change shape of the last axis
663
+ x = numpy.random.random((10, 5, 3, 7))
664
+ y = fftn(x, axes=(-1,), shape=(8,))
665
+ assert_array_almost_equal(y, fft(x, axis=-1, n=8))
666
+
667
+ # Change shape of an arbitrary axis which is not the last one
668
+ x = numpy.random.random((10, 5, 3, 7))
669
+ y = fftn(x, axes=(-2,), shape=(8,))
670
+ assert_array_almost_equal(y, fft(x, axis=-2, n=8))
671
+
672
+ # Change shape of axes: cf #244, where shape and axes were mixed up
673
+ x = numpy.random.random((4, 4, 2))
674
+ y = fftn(x, axes=(-3, -2), shape=(8, 8))
675
+ assert_array_almost_equal(y,
676
+ numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
677
+
678
+ def test_shape_argument_more(self):
679
+ x = zeros((4, 4, 2))
680
+ with assert_raises(ValueError,
681
+ match="when given, axes and shape arguments"
682
+ " have to be of the same length"):
683
+ fftn(x, shape=(8, 8, 2, 1))
684
+
685
+ def test_invalid_sizes(self):
686
+ with assert_raises(ValueError,
687
+ match="invalid number of data points"
688
+ r" \(\[1, 0\]\) specified"):
689
+ fftn([[]])
690
+
691
+ with assert_raises(ValueError,
692
+ match="invalid number of data points"
693
+ r" \(\[4, -3\]\) specified"):
694
+ fftn([[1, 1], [2, 2]], (4, -3))
695
+
696
+
697
+ class TestIfftn:
698
+ dtype = None
699
+ cdtype = None
700
+
701
+ def setup_method(self):
702
+ np.random.seed(1234)
703
+
704
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
705
+ [(np.float64, np.complex128, 2000),
706
+ (np.float32, np.complex64, 3500)])
707
+ def test_definition(self, dtype, cdtype, maxnlp):
708
+ rng = np.random.default_rng(1234)
709
+ x = np.array([[1, 2, 3],
710
+ [4, 5, 6],
711
+ [7, 8, 9]], dtype=dtype)
712
+ y = ifftn(x)
713
+ assert_equal(y.dtype, cdtype)
714
+ assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
715
+
716
+ x = rng.random((20, 26))
717
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
718
+
719
+ x = rng.random((5, 4, 3, 20))
720
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
721
+
722
+ @pytest.mark.parametrize('maxnlp', [2000, 3500])
723
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
724
+ def test_random_complex(self, maxnlp, size):
725
+ rng = np.random.default_rng(1234)
726
+ x = rng.random([size, size]) + 1j * rng.random([size, size])
727
+ assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
728
+ assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
729
+
730
+ def test_invalid_sizes(self):
731
+ with assert_raises(ValueError,
732
+ match="invalid number of data points"
733
+ r" \(\[1, 0\]\) specified"):
734
+ ifftn([[]])
735
+
736
+ with assert_raises(ValueError,
737
+ match="invalid number of data points"
738
+ r" \(\[4, -3\]\) specified"):
739
+ ifftn([[1, 1], [2, 2]], (4, -3))
740
+
741
+
742
+ class FakeArray:
743
+ def __init__(self, data):
744
+ self._data = data
745
+ self.__array_interface__ = data.__array_interface__
746
+
747
+
748
+ class FakeArray2:
749
+ def __init__(self, data):
750
+ self._data = data
751
+
752
+ def __array__(self, dtype=None, copy=None):
753
+ return self._data
754
+
755
+
756
+ class TestOverwrite:
757
+ """Check input overwrite behavior of the FFT functions."""
758
+
759
+ real_dtypes = (np.float32, np.float64)
760
+ dtypes = real_dtypes + (np.complex64, np.complex128)
761
+ fftsizes = [8, 16, 32]
762
+
763
+ def _check(self, x, routine, fftsize, axis, overwrite_x):
764
+ x2 = x.copy()
765
+ for fake in [lambda x: x, FakeArray, FakeArray2]:
766
+ routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
767
+
768
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
769
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
770
+ if not overwrite_x:
771
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
772
+
773
+ def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
774
+ fftsize, overwrite_x):
775
+ np.random.seed(1234)
776
+ if np.issubdtype(dtype, np.complexfloating):
777
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
778
+ else:
779
+ data = np.random.randn(*shape)
780
+ data = data.astype(dtype)
781
+
782
+ self._check(data, routine, fftsize, axis,
783
+ overwrite_x=overwrite_x)
784
+
785
+ @pytest.mark.parametrize('dtype', dtypes)
786
+ @pytest.mark.parametrize('fftsize', fftsizes)
787
+ @pytest.mark.parametrize('overwrite_x', [True, False])
788
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
789
+ ((16, 2), 0),
790
+ ((2, 16), 1)])
791
+ def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
792
+ overwritable = (np.complex128, np.complex64)
793
+ self._check_1d(fft, dtype, shape, axes, overwritable,
794
+ fftsize, overwrite_x)
795
+ self._check_1d(ifft, dtype, shape, axes, overwritable,
796
+ fftsize, overwrite_x)
797
+
798
+ @pytest.mark.parametrize('dtype', real_dtypes)
799
+ @pytest.mark.parametrize('fftsize', fftsizes)
800
+ @pytest.mark.parametrize('overwrite_x', [True, False])
801
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
802
+ ((16, 2), 0),
803
+ ((2, 16), 1)])
804
+ def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
805
+ overwritable = self.real_dtypes
806
+ self._check_1d(irfft, dtype, shape, axes, overwritable,
807
+ fftsize, overwrite_x)
808
+ self._check_1d(rfft, dtype, shape, axes, overwritable,
809
+ fftsize, overwrite_x)
810
+
811
+ def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
812
+ overwrite_x):
813
+ np.random.seed(1234)
814
+ if np.issubdtype(dtype, np.complexfloating):
815
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
816
+ else:
817
+ data = np.random.randn(*shape)
818
+ data = data.astype(dtype)
819
+
820
+ def fftshape_iter(shp):
821
+ if len(shp) <= 0:
822
+ yield ()
823
+ else:
824
+ for j in (shp[0]//2, shp[0], shp[0]*2):
825
+ for rest in fftshape_iter(shp[1:]):
826
+ yield (j,) + rest
827
+
828
+ if axes is None:
829
+ part_shape = shape
830
+ else:
831
+ part_shape = tuple(np.take(shape, axes))
832
+
833
+ for fftshape in fftshape_iter(part_shape):
834
+ self._check(data, routine, fftshape, axes,
835
+ overwrite_x=overwrite_x)
836
+ if data.ndim > 1:
837
+ self._check(data.T, routine, fftshape, axes,
838
+ overwrite_x=overwrite_x)
839
+
840
+ @pytest.mark.parametrize('dtype', dtypes)
841
+ @pytest.mark.parametrize('overwrite_x', [True, False])
842
+ @pytest.mark.parametrize('shape,axes', [((16,), None),
843
+ ((16,), (0,)),
844
+ ((16, 2), (0,)),
845
+ ((2, 16), (1,)),
846
+ ((8, 16), None),
847
+ ((8, 16), (0, 1)),
848
+ ((8, 16, 2), (0, 1)),
849
+ ((8, 16, 2), (1, 2)),
850
+ ((8, 16, 2), (0,)),
851
+ ((8, 16, 2), (1,)),
852
+ ((8, 16, 2), (2,)),
853
+ ((8, 16, 2), None),
854
+ ((8, 16, 2), (0, 1, 2))])
855
+ def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
856
+ overwritable = (np.complex128, np.complex64)
857
+ self._check_nd_one(fftn, dtype, shape, axes, overwritable,
858
+ overwrite_x)
859
+ self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
860
+ overwrite_x)
861
+
862
+
863
+ @pytest.mark.parametrize('func', [fftn, ifftn, fft2])
864
+ def test_shape_axes_ndarray(func):
865
+ # Test fftn and ifftn work with NumPy arrays for shape and axes arguments
866
+ # Regression test for gh-13342
867
+ a = np.random.rand(10, 10)
868
+
869
+ expect = func(a, shape=(5, 5))
870
+ actual = func(a, shape=np.array([5, 5]))
871
+ assert_equal(expect, actual)
872
+
873
+ expect = func(a, axes=(-1,))
874
+ actual = func(a, axes=np.array([-1,]))
875
+ assert_equal(expect, actual)
876
+
877
+ expect = func(a, shape=(4, 7), axes=(1, 0))
878
+ actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
879
+ assert_equal(expect, actual)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ __usage__ = """
4
+ Build fftpack:
5
+ python setup_fftpack.py build
6
+ Run tests if scipy is installed:
7
+ python -c 'import scipy;scipy.fftpack.test(<level>)'
8
+ Run tests if fftpack is not installed:
9
+ python tests/test_helper.py [<level>]
10
+ """
11
+
12
+ from numpy.testing import assert_array_almost_equal
13
+ from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq
14
+
15
+ from numpy import pi, random
16
+
17
+ class TestFFTShift:
18
+
19
+ def test_definition(self):
20
+ x = [0,1,2,3,4,-4,-3,-2,-1]
21
+ y = [-4,-3,-2,-1,0,1,2,3,4]
22
+ assert_array_almost_equal(fftshift(x),y)
23
+ assert_array_almost_equal(ifftshift(y),x)
24
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
25
+ y = [-5,-4,-3,-2,-1,0,1,2,3,4]
26
+ assert_array_almost_equal(fftshift(x),y)
27
+ assert_array_almost_equal(ifftshift(y),x)
28
+
29
+ def test_inverse(self):
30
+ for n in [1,4,9,100,211]:
31
+ x = random.random((n,))
32
+ assert_array_almost_equal(ifftshift(fftshift(x)),x)
33
+
34
+
35
+ class TestFFTFreq:
36
+
37
+ def test_definition(self):
38
+ x = [0,1,2,3,4,-4,-3,-2,-1]
39
+ assert_array_almost_equal(9*fftfreq(9),x)
40
+ assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
41
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
42
+ assert_array_almost_equal(10*fftfreq(10),x)
43
+ assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
44
+
45
+
46
+ class TestRFFTFreq:
47
+
48
+ def test_definition(self):
49
+ x = [0,1,1,2,2,3,3,4,4]
50
+ assert_array_almost_equal(9*rfftfreq(9),x)
51
+ assert_array_almost_equal(9*pi*rfftfreq(9,pi),x)
52
+ x = [0,1,1,2,2,3,3,4,4,5]
53
+ assert_array_almost_equal(10*rfftfreq(10),x)
54
+ assert_array_almost_equal(10*pi*rfftfreq(10,pi),x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test possibility of patching fftpack with pyfftw.
2
+
3
+ No module source outside of scipy.fftpack should contain an import of
4
+ the form `from scipy.fftpack import ...`, so that a simple replacement
5
+ of scipy.fftpack by the corresponding fftw interface completely swaps
6
+ the two FFT implementations.
7
+
8
+ Because this simply inspects source files, we only need to run the test
9
+ on one version of Python.
10
+ """
11
+
12
+
13
+ from pathlib import Path
14
+ import re
15
+ import tokenize
16
+ import pytest
17
+ from numpy.testing import assert_
18
+ import scipy
19
+
20
+ class TestFFTPackImport:
21
+ @pytest.mark.slow
22
+ def test_fftpack_import(self):
23
+ base = Path(scipy.__file__).parent
24
+ regexp = r"\s*from.+\.fftpack import .*\n"
25
+ for path in base.rglob("*.py"):
26
+ if base / "fftpack" in path.parents:
27
+ continue
28
+ # use tokenize to auto-detect encoding on systems where no
29
+ # default encoding is defined (e.g., LANG='C')
30
+ with tokenize.open(str(path)) as file:
31
+ assert_(all(not re.fullmatch(regexp, line)
32
+ for line in file),
33
+ f"{path} contains an import from fftpack")
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ __usage__ = """
4
+ Build fftpack:
5
+ python setup_fftpack.py build
6
+ Run tests if scipy is installed:
7
+ python -c 'import scipy;scipy.fftpack.test(<level>)'
8
+ Run tests if fftpack is not installed:
9
+ python tests/test_pseudo_diffs.py [<level>]
10
+ """
11
+
12
+ from numpy.testing import (assert_equal, assert_almost_equal,
13
+ assert_array_almost_equal)
14
+ from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert,
15
+ ihilbert, shift, fftfreq, cs_diff, sc_diff,
16
+ ss_diff, cc_diff)
17
+
18
+ import numpy as np
19
+ from numpy import arange, sin, cos, pi, exp, tanh, sum, sign
20
+ from numpy.random import random
21
+
22
+
23
+ def direct_diff(x,k=1,period=None):
24
+ fx = fft(x)
25
+ n = len(fx)
26
+ if period is None:
27
+ period = 2*pi
28
+ w = fftfreq(n)*2j*pi/period*n
29
+ if k < 0:
30
+ w = 1 / w**k
31
+ w[0] = 0.0
32
+ else:
33
+ w = w**k
34
+ if n > 2000:
35
+ w[250:n-250] = 0.0
36
+ return ifft(w*fx).real
37
+
38
+
39
+ def direct_tilbert(x,h=1,period=None):
40
+ fx = fft(x)
41
+ n = len(fx)
42
+ if period is None:
43
+ period = 2*pi
44
+ w = fftfreq(n)*h*2*pi/period*n
45
+ w[0] = 1
46
+ w = 1j/tanh(w)
47
+ w[0] = 0j
48
+ return ifft(w*fx)
49
+
50
+
51
+ def direct_itilbert(x,h=1,period=None):
52
+ fx = fft(x)
53
+ n = len(fx)
54
+ if period is None:
55
+ period = 2*pi
56
+ w = fftfreq(n)*h*2*pi/period*n
57
+ w = -1j*tanh(w)
58
+ return ifft(w*fx)
59
+
60
+
61
+ def direct_hilbert(x):
62
+ fx = fft(x)
63
+ n = len(fx)
64
+ w = fftfreq(n)*n
65
+ w = 1j*sign(w)
66
+ return ifft(w*fx)
67
+
68
+
69
+ def direct_ihilbert(x):
70
+ return -direct_hilbert(x)
71
+
72
+
73
+ def direct_shift(x,a,period=None):
74
+ n = len(x)
75
+ if period is None:
76
+ k = fftfreq(n)*1j*n
77
+ else:
78
+ k = fftfreq(n)*2j*pi/period*n
79
+ return ifft(fft(x)*exp(k*a)).real
80
+
81
+
82
+ class TestDiff:
83
+
84
+ def test_definition(self):
85
+ for n in [16,17,64,127,32]:
86
+ x = arange(n)*2*pi/n
87
+ assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x)))
88
+ assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2))
89
+ assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3))
90
+ assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4))
91
+ assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5))
92
+ assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3))
93
+ assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4))
94
+ assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x)))
95
+ assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2))
96
+ assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3))
97
+ assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4))
98
+ assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x)))
99
+ assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8)))
100
+ assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8)))
101
+ for k in range(5):
102
+ assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k))
103
+ assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k))
104
+
105
+ def test_period(self):
106
+ for n in [17,64]:
107
+ x = arange(n)/float(n)
108
+ assert_array_almost_equal(diff(sin(2*pi*x),period=1),
109
+ 2*pi*cos(2*pi*x))
110
+ assert_array_almost_equal(diff(sin(2*pi*x),3,period=1),
111
+ -(2*pi)**3*cos(2*pi*x))
112
+
113
+ def test_sin(self):
114
+ for n in [32,64,77]:
115
+ x = arange(n)*2*pi/n
116
+ assert_array_almost_equal(diff(sin(x)),cos(x))
117
+ assert_array_almost_equal(diff(cos(x)),-sin(x))
118
+ assert_array_almost_equal(diff(sin(x),2),-sin(x))
119
+ assert_array_almost_equal(diff(sin(x),4),sin(x))
120
+ assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x))
121
+ assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x)))
122
+
123
+ def test_expr(self):
124
+ for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]:
125
+ x = arange(n)*2*pi/n
126
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
127
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
128
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
129
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
130
+ d1 = diff(f)
131
+ assert_array_almost_equal(d1,df)
132
+ assert_array_almost_equal(diff(df),ddf)
133
+ assert_array_almost_equal(diff(f,2),ddf)
134
+ assert_array_almost_equal(diff(ddf,-1),df)
135
+
136
+ def test_expr_large(self):
137
+ for n in [2048,4096]:
138
+ x = arange(n)*2*pi/n
139
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
140
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
141
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
142
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
143
+ assert_array_almost_equal(diff(f),df)
144
+ assert_array_almost_equal(diff(df),ddf)
145
+ assert_array_almost_equal(diff(ddf,-1),df)
146
+ assert_array_almost_equal(diff(f,2),ddf)
147
+
148
+ def test_int(self):
149
+ n = 64
150
+ x = arange(n)*2*pi/n
151
+ assert_array_almost_equal(diff(sin(x),-1),-cos(x))
152
+ assert_array_almost_equal(diff(sin(x),-2),-sin(x))
153
+ assert_array_almost_equal(diff(sin(x),-4),sin(x))
154
+ assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x))
155
+
156
+ def test_random_even(self):
157
+ rng = np.random.default_rng(1234)
158
+ for k in [0,2,4,6]:
159
+ for n in [60,32,64,56,55]:
160
+ f = rng.random((n,))
161
+ af = sum(f,axis=0)/n
162
+ f = f-af
163
+ # zeroing Nyquist mode:
164
+ f = diff(diff(f,1),-1)
165
+ assert_almost_equal(sum(f,axis=0),0.0)
166
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
167
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
168
+
169
+ def test_random_odd(self):
170
+ rng = np.random.default_rng(1234)
171
+ for k in [0,1,2,3,4,5,6]:
172
+ for n in [33,65,55]:
173
+ f = rng.random((n,))
174
+ af = sum(f,axis=0)/n
175
+ f = f-af
176
+ assert_almost_equal(sum(f,axis=0),0.0)
177
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
178
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
179
+
180
+ def test_zero_nyquist(self):
181
+ rng = np.random.default_rng(1234)
182
+ for k in [0,1,2,3,4,5,6]:
183
+ for n in [32,33,64,56,55]:
184
+ f = rng.random((n,))
185
+ af = sum(f,axis=0)/n
186
+ f = f-af
187
+ # zeroing Nyquist mode:
188
+ f = diff(diff(f,1),-1)
189
+ assert_almost_equal(sum(f,axis=0),0.0)
190
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
191
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
192
+
193
+
194
+ class TestTilbert:
195
+
196
+ def test_definition(self):
197
+ for h in [0.1,0.5,1,5.5,10]:
198
+ for n in [16,17,64,127]:
199
+ x = arange(n)*2*pi/n
200
+ y = tilbert(sin(x),h)
201
+ y1 = direct_tilbert(sin(x),h)
202
+ assert_array_almost_equal(y,y1)
203
+ assert_array_almost_equal(tilbert(sin(x),h),
204
+ direct_tilbert(sin(x),h))
205
+ assert_array_almost_equal(tilbert(sin(2*x),h),
206
+ direct_tilbert(sin(2*x),h))
207
+
208
+ def test_random_even(self):
209
+ for h in [0.1,0.5,1,5.5,10]:
210
+ for n in [32,64,56]:
211
+ f = random((n,))
212
+ af = sum(f,axis=0)/n
213
+ f = f-af
214
+ assert_almost_equal(sum(f,axis=0),0.0)
215
+ assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f)
216
+
217
+ def test_random_odd(self):
218
+ rng = np.random.default_rng(1234)
219
+ for h in [0.1,0.5,1,5.5,10]:
220
+ for n in [33,65,55]:
221
+ f = rng.random((n,))
222
+ af = sum(f,axis=0)/n
223
+ f = f-af
224
+ assert_almost_equal(sum(f,axis=0),0.0)
225
+ assert_array_almost_equal(itilbert(tilbert(f,h),h),f)
226
+ assert_array_almost_equal(tilbert(itilbert(f,h),h),f)
227
+
228
+
229
+ class TestITilbert:
230
+
231
+ def test_definition(self):
232
+ for h in [0.1,0.5,1,5.5,10]:
233
+ for n in [16,17,64,127]:
234
+ x = arange(n)*2*pi/n
235
+ y = itilbert(sin(x),h)
236
+ y1 = direct_itilbert(sin(x),h)
237
+ assert_array_almost_equal(y,y1)
238
+ assert_array_almost_equal(itilbert(sin(x),h),
239
+ direct_itilbert(sin(x),h))
240
+ assert_array_almost_equal(itilbert(sin(2*x),h),
241
+ direct_itilbert(sin(2*x),h))
242
+
243
+
244
+ class TestHilbert:
245
+
246
+ def test_definition(self):
247
+ for n in [16,17,64,127]:
248
+ x = arange(n)*2*pi/n
249
+ y = hilbert(sin(x))
250
+ y1 = direct_hilbert(sin(x))
251
+ assert_array_almost_equal(y,y1)
252
+ assert_array_almost_equal(hilbert(sin(2*x)),
253
+ direct_hilbert(sin(2*x)))
254
+
255
+ def test_tilbert_relation(self):
256
+ for n in [16,17,64,127]:
257
+ x = arange(n)*2*pi/n
258
+ f = sin(x)+cos(2*x)*sin(x)
259
+ y = hilbert(f)
260
+ y1 = direct_hilbert(f)
261
+ assert_array_almost_equal(y,y1)
262
+ y2 = tilbert(f,h=10)
263
+ assert_array_almost_equal(y,y2)
264
+
265
+ def test_random_odd(self):
266
+ rng = np.random.default_rng(1234)
267
+ for n in [33,65,55]:
268
+ f = rng.random((n,))
269
+ af = sum(f,axis=0)/n
270
+ f = f-af
271
+ assert_almost_equal(sum(f,axis=0),0.0)
272
+ assert_array_almost_equal(ihilbert(hilbert(f)),f)
273
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
274
+
275
+ def test_random_even(self):
276
+ rng = np.random.default_rng(1234)
277
+ for n in [32,64,56]:
278
+ f = rng.random((n,))
279
+ af = sum(f,axis=0)/n
280
+ f = f-af
281
+ # zeroing Nyquist mode:
282
+ f = diff(diff(f,1),-1)
283
+ assert_almost_equal(sum(f,axis=0),0.0)
284
+ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f)
285
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
286
+
287
+
288
+ class TestIHilbert:
289
+
290
+ def test_definition(self):
291
+ for n in [16,17,64,127]:
292
+ x = arange(n)*2*pi/n
293
+ y = ihilbert(sin(x))
294
+ y1 = direct_ihilbert(sin(x))
295
+ assert_array_almost_equal(y,y1)
296
+ assert_array_almost_equal(ihilbert(sin(2*x)),
297
+ direct_ihilbert(sin(2*x)))
298
+
299
+ def test_itilbert_relation(self):
300
+ for n in [16,17,64,127]:
301
+ x = arange(n)*2*pi/n
302
+ f = sin(x)+cos(2*x)*sin(x)
303
+ y = ihilbert(f)
304
+ y1 = direct_ihilbert(f)
305
+ assert_array_almost_equal(y,y1)
306
+ y2 = itilbert(f,h=10)
307
+ assert_array_almost_equal(y,y2)
308
+
309
+
310
+ class TestShift:
311
+
312
+ def test_definition(self):
313
+ for n in [18,17,64,127,32,2048,256]:
314
+ x = arange(n)*2*pi/n
315
+ for a in [0.1,3]:
316
+ assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a))
317
+ assert_array_almost_equal(shift(sin(x),a),sin(x+a))
318
+ assert_array_almost_equal(shift(cos(x),a),cos(x+a))
319
+ assert_array_almost_equal(shift(cos(2*x)+sin(x),a),
320
+ cos(2*(x+a))+sin(x+a))
321
+ assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a)))
322
+ assert_array_almost_equal(shift(sin(x),2*pi),sin(x))
323
+ assert_array_almost_equal(shift(sin(x),pi),-sin(x))
324
+ assert_array_almost_equal(shift(sin(x),pi/2),cos(x))
325
+
326
+
327
+ class TestOverwrite:
328
+ """Check input overwrite behavior """
329
+
330
+ real_dtypes = (np.float32, np.float64)
331
+ dtypes = real_dtypes + (np.complex64, np.complex128)
332
+
333
+ def _check(self, x, routine, *args, **kwargs):
334
+ x2 = x.copy()
335
+ routine(x2, *args, **kwargs)
336
+ sig = routine.__name__
337
+ if args:
338
+ sig += repr(args)
339
+ if kwargs:
340
+ sig += repr(kwargs)
341
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
342
+
343
+ def _check_1d(self, routine, dtype, shape, *args, **kwargs):
344
+ # rng = np.random.default_rng(1234)
345
+ rng = np.random.RandomState(1234)
346
+ # np.random.seed(1234)
347
+ if np.issubdtype(dtype, np.complexfloating):
348
+ data = rng.randn(*shape) + 1j*rng.randn(*shape)
349
+ else:
350
+ data = rng.randn(*shape)
351
+ data = data.astype(dtype)
352
+ self._check(data, routine, *args, **kwargs)
353
+
354
+ def test_diff(self):
355
+ for dtype in self.dtypes:
356
+ self._check_1d(diff, dtype, (16,))
357
+
358
+ def test_tilbert(self):
359
+ for dtype in self.dtypes:
360
+ self._check_1d(tilbert, dtype, (16,), 1.6)
361
+
362
+ def test_itilbert(self):
363
+ for dtype in self.dtypes:
364
+ self._check_1d(itilbert, dtype, (16,), 1.6)
365
+
366
+ def test_hilbert(self):
367
+ for dtype in self.dtypes:
368
+ self._check_1d(hilbert, dtype, (16,))
369
+
370
+ def test_cs_diff(self):
371
+ for dtype in self.dtypes:
372
+ self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0)
373
+
374
+ def test_sc_diff(self):
375
+ for dtype in self.dtypes:
376
+ self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0)
377
+
378
+ def test_ss_diff(self):
379
+ for dtype in self.dtypes:
380
+ self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0)
381
+
382
+ def test_cc_diff(self):
383
+ for dtype in self.dtypes:
384
+ self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0)
385
+
386
+ def test_shift(self):
387
+ for dtype in self.dtypes:
388
+ self._check_1d(shift, dtype, (16,), 1.0)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os.path import join, dirname
2
+ import threading
3
+
4
+ import numpy as np
5
+ from numpy.testing import assert_array_almost_equal, assert_equal
6
+ import pytest
7
+ from pytest import raises as assert_raises
8
+
9
+ from scipy.fftpack._realtransforms import (
10
+ dct, idct, dst, idst, dctn, idctn, dstn, idstn)
11
+
12
+ # Matlab reference data
13
+ MDATA = np.load(join(dirname(__file__), 'test.npz'))
14
+ X = [MDATA['x%d' % i] for i in range(8)]
15
+ Y = [MDATA['y%d' % i] for i in range(8)]
16
+
17
+ # FFTW reference data: the data are organized as follows:
18
+ # * SIZES is an array containing all available sizes
19
+ # * for every type (1, 2, 3, 4) and every size, the array dct_type_size
20
+ # contains the output of the DCT applied to the input np.linspace(0, size-1,
21
+ # size)
22
+ FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
23
+ FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
24
+ FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
25
+
26
+
27
+ def fftw_dct_ref(type, size, dt):
28
+ x = np.linspace(0, size-1, size).astype(dt)
29
+ dt = np.result_type(np.float32, dt)
30
+ if dt == np.float64:
31
+ data = FFTWDATA_DOUBLE
32
+ elif dt == np.float32:
33
+ data = FFTWDATA_SINGLE
34
+ else:
35
+ raise ValueError()
36
+ y = (data['dct_%d_%d' % (type, size)]).astype(dt)
37
+ return x, y, dt
38
+
39
+
40
+ def fftw_dst_ref(type, size, dt):
41
+ x = np.linspace(0, size-1, size).astype(dt)
42
+ dt = np.result_type(np.float32, dt)
43
+ if dt == np.float64:
44
+ data = FFTWDATA_DOUBLE
45
+ elif dt == np.float32:
46
+ data = FFTWDATA_SINGLE
47
+ else:
48
+ raise ValueError()
49
+ y = (data['dst_%d_%d' % (type, size)]).astype(dt)
50
+ return x, y, dt
51
+
52
+
53
+ def dct_2d_ref(x, **kwargs):
54
+ """Calculate reference values for testing dct2."""
55
+ x = np.array(x, copy=True)
56
+ for row in range(x.shape[0]):
57
+ x[row, :] = dct(x[row, :], **kwargs)
58
+ for col in range(x.shape[1]):
59
+ x[:, col] = dct(x[:, col], **kwargs)
60
+ return x
61
+
62
+
63
+ def idct_2d_ref(x, **kwargs):
64
+ """Calculate reference values for testing idct2."""
65
+ x = np.array(x, copy=True)
66
+ for row in range(x.shape[0]):
67
+ x[row, :] = idct(x[row, :], **kwargs)
68
+ for col in range(x.shape[1]):
69
+ x[:, col] = idct(x[:, col], **kwargs)
70
+ return x
71
+
72
+
73
+ def dst_2d_ref(x, **kwargs):
74
+ """Calculate reference values for testing dst2."""
75
+ x = np.array(x, copy=True)
76
+ for row in range(x.shape[0]):
77
+ x[row, :] = dst(x[row, :], **kwargs)
78
+ for col in range(x.shape[1]):
79
+ x[:, col] = dst(x[:, col], **kwargs)
80
+ return x
81
+
82
+
83
+ def idst_2d_ref(x, **kwargs):
84
+ """Calculate reference values for testing idst2."""
85
+ x = np.array(x, copy=True)
86
+ for row in range(x.shape[0]):
87
+ x[row, :] = idst(x[row, :], **kwargs)
88
+ for col in range(x.shape[1]):
89
+ x[:, col] = idst(x[:, col], **kwargs)
90
+ return x
91
+
92
+
93
+ def naive_dct1(x, norm=None):
94
+ """Calculate textbook definition version of DCT-I."""
95
+ x = np.array(x, copy=True)
96
+ N = len(x)
97
+ M = N-1
98
+ y = np.zeros(N)
99
+ m0, m = 1, 2
100
+ if norm == 'ortho':
101
+ m0 = np.sqrt(1.0/M)
102
+ m = np.sqrt(2.0/M)
103
+ for k in range(N):
104
+ for n in range(1, N-1):
105
+ y[k] += m*x[n]*np.cos(np.pi*n*k/M)
106
+ y[k] += m0 * x[0]
107
+ y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
108
+ if norm == 'ortho':
109
+ y[0] *= 1/np.sqrt(2)
110
+ y[N-1] *= 1/np.sqrt(2)
111
+ return y
112
+
113
+
114
+ def naive_dst1(x, norm=None):
115
+ """Calculate textbook definition version of DST-I."""
116
+ x = np.array(x, copy=True)
117
+ N = len(x)
118
+ M = N+1
119
+ y = np.zeros(N)
120
+ for k in range(N):
121
+ for n in range(N):
122
+ y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
123
+ if norm == 'ortho':
124
+ y *= np.sqrt(0.5/M)
125
+ return y
126
+
127
+
128
+ def naive_dct4(x, norm=None):
129
+ """Calculate textbook definition version of DCT-IV."""
130
+ x = np.array(x, copy=True)
131
+ N = len(x)
132
+ y = np.zeros(N)
133
+ for k in range(N):
134
+ for n in range(N):
135
+ y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
136
+ if norm == 'ortho':
137
+ y *= np.sqrt(2.0/N)
138
+ else:
139
+ y *= 2
140
+ return y
141
+
142
+
143
+ def naive_dst4(x, norm=None):
144
+ """Calculate textbook definition version of DST-IV."""
145
+ x = np.array(x, copy=True)
146
+ N = len(x)
147
+ y = np.zeros(N)
148
+ for k in range(N):
149
+ for n in range(N):
150
+ y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
151
+ if norm == 'ortho':
152
+ y *= np.sqrt(2.0/N)
153
+ else:
154
+ y *= 2
155
+ return y
156
+
157
+
158
+ class TestComplex:
159
+ def test_dct_complex64(self):
160
+ y = dct(1j*np.arange(5, dtype=np.complex64))
161
+ x = 1j*dct(np.arange(5))
162
+ assert_array_almost_equal(x, y)
163
+
164
+ def test_dct_complex(self):
165
+ y = dct(np.arange(5)*1j)
166
+ x = 1j*dct(np.arange(5))
167
+ assert_array_almost_equal(x, y)
168
+
169
+ def test_idct_complex(self):
170
+ y = idct(np.arange(5)*1j)
171
+ x = 1j*idct(np.arange(5))
172
+ assert_array_almost_equal(x, y)
173
+
174
+ def test_dst_complex64(self):
175
+ y = dst(np.arange(5, dtype=np.complex64)*1j)
176
+ x = 1j*dst(np.arange(5))
177
+ assert_array_almost_equal(x, y)
178
+
179
+ def test_dst_complex(self):
180
+ y = dst(np.arange(5)*1j)
181
+ x = 1j*dst(np.arange(5))
182
+ assert_array_almost_equal(x, y)
183
+
184
+ def test_idst_complex(self):
185
+ y = idst(np.arange(5)*1j)
186
+ x = 1j*idst(np.arange(5))
187
+ assert_array_almost_equal(x, y)
188
+
189
+
190
+ class _TestDCTBase:
191
+ def setup_method(self):
192
+ self.rdt = None
193
+ self.dec = 14
194
+ self.type = None
195
+
196
+ @pytest.fixture
197
+ def dct_lock(self):
198
+ return threading.Lock()
199
+
200
+ def test_definition(self, dct_lock):
201
+ for i in FFTWDATA_SIZES:
202
+ with dct_lock:
203
+ x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
204
+ y = dct(x, type=self.type)
205
+ assert_equal(y.dtype, dt)
206
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
207
+ # should really use something like assert_array_approx_equal. The
208
+ # difference is due to fftw using a better algorithm w.r.t error
209
+ # propagation compared to the ones from fftpack.
210
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
211
+ err_msg="Size %d failed" % i)
212
+
213
+ def test_axis(self):
214
+ nt = 2
215
+ rng = np.random.RandomState(1234)
216
+ for i in [7, 8, 9, 16, 32, 64]:
217
+ x = rng.randn(nt, i)
218
+ y = dct(x, type=self.type)
219
+ for j in range(nt):
220
+ assert_array_almost_equal(y[j], dct(x[j], type=self.type),
221
+ decimal=self.dec)
222
+
223
+ x = x.T
224
+ y = dct(x, axis=0, type=self.type)
225
+ for j in range(nt):
226
+ assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
227
+ decimal=self.dec)
228
+
229
+
230
+ class _TestDCTIBase(_TestDCTBase):
231
+ def test_definition_ortho(self):
232
+ # Test orthornomal mode.
233
+ dt = np.result_type(np.float32, self.rdt)
234
+ for xr in X:
235
+ x = np.array(xr, dtype=self.rdt)
236
+ y = dct(x, norm='ortho', type=1)
237
+ y2 = naive_dct1(x, norm='ortho')
238
+ assert_equal(y.dtype, dt)
239
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
240
+
241
+ class _TestDCTIIBase(_TestDCTBase):
242
+ def test_definition_matlab(self):
243
+ # Test correspondence with MATLAB (orthornomal mode).
244
+ dt = np.result_type(np.float32, self.rdt)
245
+ for xr, yr in zip(X, Y):
246
+ x = np.array(xr, dtype=dt)
247
+ y = dct(x, norm="ortho", type=2)
248
+ assert_equal(y.dtype, dt)
249
+ assert_array_almost_equal(y, yr, decimal=self.dec)
250
+
251
+
252
+ class _TestDCTIIIBase(_TestDCTBase):
253
+ def test_definition_ortho(self):
254
+ # Test orthornomal mode.
255
+ dt = np.result_type(np.float32, self.rdt)
256
+ for xr in X:
257
+ x = np.array(xr, dtype=self.rdt)
258
+ y = dct(x, norm='ortho', type=2)
259
+ xi = dct(y, norm="ortho", type=3)
260
+ assert_equal(xi.dtype, dt)
261
+ assert_array_almost_equal(xi, x, decimal=self.dec)
262
+
263
+ class _TestDCTIVBase(_TestDCTBase):
264
+ def test_definition_ortho(self):
265
+ # Test orthornomal mode.
266
+ dt = np.result_type(np.float32, self.rdt)
267
+ for xr in X:
268
+ x = np.array(xr, dtype=self.rdt)
269
+ y = dct(x, norm='ortho', type=4)
270
+ y2 = naive_dct4(x, norm='ortho')
271
+ assert_equal(y.dtype, dt)
272
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
273
+
274
+
275
+ class TestDCTIDouble(_TestDCTIBase):
276
+ def setup_method(self):
277
+ self.rdt = np.float64
278
+ self.dec = 10
279
+ self.type = 1
280
+
281
+
282
+ class TestDCTIFloat(_TestDCTIBase):
283
+ def setup_method(self):
284
+ self.rdt = np.float32
285
+ self.dec = 4
286
+ self.type = 1
287
+
288
+
289
+ class TestDCTIInt(_TestDCTIBase):
290
+ def setup_method(self):
291
+ self.rdt = int
292
+ self.dec = 5
293
+ self.type = 1
294
+
295
+
296
+ class TestDCTIIDouble(_TestDCTIIBase):
297
+ def setup_method(self):
298
+ self.rdt = np.float64
299
+ self.dec = 10
300
+ self.type = 2
301
+
302
+
303
+ class TestDCTIIFloat(_TestDCTIIBase):
304
+ def setup_method(self):
305
+ self.rdt = np.float32
306
+ self.dec = 5
307
+ self.type = 2
308
+
309
+
310
+ class TestDCTIIInt(_TestDCTIIBase):
311
+ def setup_method(self):
312
+ self.rdt = int
313
+ self.dec = 5
314
+ self.type = 2
315
+
316
+
317
+ class TestDCTIIIDouble(_TestDCTIIIBase):
318
+ def setup_method(self):
319
+ self.rdt = np.float64
320
+ self.dec = 14
321
+ self.type = 3
322
+
323
+
324
+ class TestDCTIIIFloat(_TestDCTIIIBase):
325
+ def setup_method(self):
326
+ self.rdt = np.float32
327
+ self.dec = 5
328
+ self.type = 3
329
+
330
+
331
+ class TestDCTIIIInt(_TestDCTIIIBase):
332
+ def setup_method(self):
333
+ self.rdt = int
334
+ self.dec = 5
335
+ self.type = 3
336
+
337
+
338
+ class TestDCTIVDouble(_TestDCTIVBase):
339
+ def setup_method(self):
340
+ self.rdt = np.float64
341
+ self.dec = 12
342
+ self.type = 3
343
+
344
+
345
+ class TestDCTIVFloat(_TestDCTIVBase):
346
+ def setup_method(self):
347
+ self.rdt = np.float32
348
+ self.dec = 5
349
+ self.type = 3
350
+
351
+
352
+ class TestDCTIVInt(_TestDCTIVBase):
353
+ def setup_method(self):
354
+ self.rdt = int
355
+ self.dec = 5
356
+ self.type = 3
357
+
358
+
359
+ class _TestIDCTBase:
360
+ def setup_method(self):
361
+ self.rdt = None
362
+ self.dec = 14
363
+ self.type = None
364
+
365
+ @pytest.fixture
366
+ def idct_lock(self):
367
+ return threading.Lock()
368
+
369
+ def test_definition(self, idct_lock):
370
+ for i in FFTWDATA_SIZES:
371
+ with idct_lock:
372
+ xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
373
+ x = idct(yr, type=self.type)
374
+ if self.type == 1:
375
+ x /= 2 * (i-1)
376
+ else:
377
+ x /= 2 * i
378
+ assert_equal(x.dtype, dt)
379
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
380
+ # should really use something like assert_array_approx_equal. The
381
+ # difference is due to fftw using a better algorithm w.r.t error
382
+ # propagation compared to the ones from fftpack.
383
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
384
+ err_msg="Size %d failed" % i)
385
+
386
+
387
+ class TestIDCTIDouble(_TestIDCTBase):
388
+ def setup_method(self):
389
+ self.rdt = np.float64
390
+ self.dec = 10
391
+ self.type = 1
392
+
393
+
394
+ class TestIDCTIFloat(_TestIDCTBase):
395
+ def setup_method(self):
396
+ self.rdt = np.float32
397
+ self.dec = 4
398
+ self.type = 1
399
+
400
+
401
+ class TestIDCTIInt(_TestIDCTBase):
402
+ def setup_method(self):
403
+ self.rdt = int
404
+ self.dec = 4
405
+ self.type = 1
406
+
407
+
408
+ class TestIDCTIIDouble(_TestIDCTBase):
409
+ def setup_method(self):
410
+ self.rdt = np.float64
411
+ self.dec = 10
412
+ self.type = 2
413
+
414
+
415
+ class TestIDCTIIFloat(_TestIDCTBase):
416
+ def setup_method(self):
417
+ self.rdt = np.float32
418
+ self.dec = 5
419
+ self.type = 2
420
+
421
+
422
+ class TestIDCTIIInt(_TestIDCTBase):
423
+ def setup_method(self):
424
+ self.rdt = int
425
+ self.dec = 5
426
+ self.type = 2
427
+
428
+
429
+ class TestIDCTIIIDouble(_TestIDCTBase):
430
+ def setup_method(self):
431
+ self.rdt = np.float64
432
+ self.dec = 14
433
+ self.type = 3
434
+
435
+
436
+ class TestIDCTIIIFloat(_TestIDCTBase):
437
+ def setup_method(self):
438
+ self.rdt = np.float32
439
+ self.dec = 5
440
+ self.type = 3
441
+
442
+
443
+ class TestIDCTIIIInt(_TestIDCTBase):
444
+ def setup_method(self):
445
+ self.rdt = int
446
+ self.dec = 5
447
+ self.type = 3
448
+
449
+ class TestIDCTIVDouble(_TestIDCTBase):
450
+ def setup_method(self):
451
+ self.rdt = np.float64
452
+ self.dec = 12
453
+ self.type = 4
454
+
455
+
456
+ class TestIDCTIVFloat(_TestIDCTBase):
457
+ def setup_method(self):
458
+ self.rdt = np.float32
459
+ self.dec = 5
460
+ self.type = 4
461
+
462
+
463
+ class TestIDCTIVInt(_TestIDCTBase):
464
+ def setup_method(self):
465
+ self.rdt = int
466
+ self.dec = 5
467
+ self.type = 4
468
+
469
+ class _TestDSTBase:
470
+ def setup_method(self):
471
+ self.rdt = None # dtype
472
+ self.dec = None # number of decimals to match
473
+ self.type = None # dst type
474
+
475
+ @pytest.fixture
476
+ def dst_lock(self):
477
+ return threading.Lock()
478
+
479
+ def test_definition(self, dst_lock):
480
+ for i in FFTWDATA_SIZES:
481
+ with dst_lock:
482
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
483
+ y = dst(xr, type=self.type)
484
+ assert_equal(y.dtype, dt)
485
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
486
+ # should really use something like assert_array_approx_equal. The
487
+ # difference is due to fftw using a better algorithm w.r.t error
488
+ # propagation compared to the ones from fftpack.
489
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
490
+ err_msg="Size %d failed" % i)
491
+
492
+
493
+ class _TestDSTIBase(_TestDSTBase):
494
+ def test_definition_ortho(self):
495
+ # Test orthornomal mode.
496
+ dt = np.result_type(np.float32, self.rdt)
497
+ for xr in X:
498
+ x = np.array(xr, dtype=self.rdt)
499
+ y = dst(x, norm='ortho', type=1)
500
+ y2 = naive_dst1(x, norm='ortho')
501
+ assert_equal(y.dtype, dt)
502
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
503
+
504
+ class _TestDSTIVBase(_TestDSTBase):
505
+ def test_definition_ortho(self):
506
+ # Test orthornomal mode.
507
+ dt = np.result_type(np.float32, self.rdt)
508
+ for xr in X:
509
+ x = np.array(xr, dtype=self.rdt)
510
+ y = dst(x, norm='ortho', type=4)
511
+ y2 = naive_dst4(x, norm='ortho')
512
+ assert_equal(y.dtype, dt)
513
+ assert_array_almost_equal(y, y2, decimal=self.dec)
514
+
515
+ class TestDSTIDouble(_TestDSTIBase):
516
+ def setup_method(self):
517
+ self.rdt = np.float64
518
+ self.dec = 12
519
+ self.type = 1
520
+
521
+
522
+ class TestDSTIFloat(_TestDSTIBase):
523
+ def setup_method(self):
524
+ self.rdt = np.float32
525
+ self.dec = 4
526
+ self.type = 1
527
+
528
+
529
+ class TestDSTIInt(_TestDSTIBase):
530
+ def setup_method(self):
531
+ self.rdt = int
532
+ self.dec = 5
533
+ self.type = 1
534
+
535
+
536
+ class TestDSTIIDouble(_TestDSTBase):
537
+ def setup_method(self):
538
+ self.rdt = np.float64
539
+ self.dec = 14
540
+ self.type = 2
541
+
542
+
543
+ class TestDSTIIFloat(_TestDSTBase):
544
+ def setup_method(self):
545
+ self.rdt = np.float32
546
+ self.dec = 6
547
+ self.type = 2
548
+
549
+
550
+ class TestDSTIIInt(_TestDSTBase):
551
+ def setup_method(self):
552
+ self.rdt = int
553
+ self.dec = 6
554
+ self.type = 2
555
+
556
+
557
+ class TestDSTIIIDouble(_TestDSTBase):
558
+ def setup_method(self):
559
+ self.rdt = np.float64
560
+ self.dec = 14
561
+ self.type = 3
562
+
563
+
564
+ class TestDSTIIIFloat(_TestDSTBase):
565
+ def setup_method(self):
566
+ self.rdt = np.float32
567
+ self.dec = 7
568
+ self.type = 3
569
+
570
+
571
+ class TestDSTIIIInt(_TestDSTBase):
572
+ def setup_method(self):
573
+ self.rdt = int
574
+ self.dec = 7
575
+ self.type = 3
576
+
577
+
578
+ class TestDSTIVDouble(_TestDSTIVBase):
579
+ def setup_method(self):
580
+ self.rdt = np.float64
581
+ self.dec = 12
582
+ self.type = 4
583
+
584
+
585
+ class TestDSTIVFloat(_TestDSTIVBase):
586
+ def setup_method(self):
587
+ self.rdt = np.float32
588
+ self.dec = 4
589
+ self.type = 4
590
+
591
+
592
+ class TestDSTIVInt(_TestDSTIVBase):
593
+ def setup_method(self):
594
+ self.rdt = int
595
+ self.dec = 5
596
+ self.type = 4
597
+
598
+
599
+ class _TestIDSTBase:
600
+ def setup_method(self):
601
+ self.rdt = None
602
+ self.dec = None
603
+ self.type = None
604
+
605
+ @pytest.fixture
606
+ def idst_lock(self):
607
+ return threading.Lock()
608
+
609
+ def test_definition(self, idst_lock):
610
+ for i in FFTWDATA_SIZES:
611
+ with idst_lock:
612
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
613
+ x = idst(yr, type=self.type)
614
+ if self.type == 1:
615
+ x /= 2 * (i+1)
616
+ else:
617
+ x /= 2 * i
618
+ assert_equal(x.dtype, dt)
619
+ # XXX: we divide by np.max(x) because the tests fail otherwise. We
620
+ # should really use something like assert_array_approx_equal. The
621
+ # difference is due to fftw using a better algorithm w.r.t error
622
+ # propagation compared to the ones from fftpack.
623
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
624
+ err_msg="Size %d failed" % i)
625
+
626
+
627
+ class TestIDSTIDouble(_TestIDSTBase):
628
+ def setup_method(self):
629
+ self.rdt = np.float64
630
+ self.dec = 12
631
+ self.type = 1
632
+
633
+
634
+ class TestIDSTIFloat(_TestIDSTBase):
635
+ def setup_method(self):
636
+ self.rdt = np.float32
637
+ self.dec = 4
638
+ self.type = 1
639
+
640
+
641
+ class TestIDSTIInt(_TestIDSTBase):
642
+ def setup_method(self):
643
+ self.rdt = int
644
+ self.dec = 4
645
+ self.type = 1
646
+
647
+
648
+ class TestIDSTIIDouble(_TestIDSTBase):
649
+ def setup_method(self):
650
+ self.rdt = np.float64
651
+ self.dec = 14
652
+ self.type = 2
653
+
654
+
655
+ class TestIDSTIIFloat(_TestIDSTBase):
656
+ def setup_method(self):
657
+ self.rdt = np.float32
658
+ self.dec = 6
659
+ self.type = 2
660
+
661
+
662
+ class TestIDSTIIInt(_TestIDSTBase):
663
+ def setup_method(self):
664
+ self.rdt = int
665
+ self.dec = 6
666
+ self.type = 2
667
+
668
+
669
+ class TestIDSTIIIDouble(_TestIDSTBase):
670
+ def setup_method(self):
671
+ self.rdt = np.float64
672
+ self.dec = 14
673
+ self.type = 3
674
+
675
+
676
+ class TestIDSTIIIFloat(_TestIDSTBase):
677
+ def setup_method(self):
678
+ self.rdt = np.float32
679
+ self.dec = 6
680
+ self.type = 3
681
+
682
+
683
+ class TestIDSTIIIInt(_TestIDSTBase):
684
+ def setup_method(self):
685
+ self.rdt = int
686
+ self.dec = 6
687
+ self.type = 3
688
+
689
+
690
+ class TestIDSTIVDouble(_TestIDSTBase):
691
+ def setup_method(self):
692
+ self.rdt = np.float64
693
+ self.dec = 12
694
+ self.type = 4
695
+
696
+
697
+ class TestIDSTIVFloat(_TestIDSTBase):
698
+ def setup_method(self):
699
+ self.rdt = np.float32
700
+ self.dec = 6
701
+ self.type = 4
702
+
703
+
704
+ class TestIDSTIVnt(_TestIDSTBase):
705
+ def setup_method(self):
706
+ self.rdt = int
707
+ self.dec = 6
708
+ self.type = 4
709
+
710
+
711
+ class TestOverwrite:
712
+ """Check input overwrite behavior."""
713
+
714
+ real_dtypes = [np.float32, np.float64]
715
+
716
+ def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
717
+ x2 = x.copy()
718
+ routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
719
+
720
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
721
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
722
+ if not overwrite_x:
723
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
724
+
725
+ def _check_1d(self, routine, dtype, shape, axis):
726
+ rng = np.random.RandomState(1234)
727
+ if np.issubdtype(dtype, np.complexfloating):
728
+ data = rng.randn(*shape) + 1j*rng.randn(*shape)
729
+ else:
730
+ data = rng.randn(*shape)
731
+ data = data.astype(dtype)
732
+
733
+ for type in [1, 2, 3, 4]:
734
+ for overwrite_x in [True, False]:
735
+ for norm in [None, 'ortho']:
736
+ self._check(data, routine, type, None, axis, norm,
737
+ overwrite_x)
738
+
739
+ def test_dct(self):
740
+ for dtype in self.real_dtypes:
741
+ self._check_1d(dct, dtype, (16,), -1)
742
+ self._check_1d(dct, dtype, (16, 2), 0)
743
+ self._check_1d(dct, dtype, (2, 16), 1)
744
+
745
+ def test_idct(self):
746
+ for dtype in self.real_dtypes:
747
+ self._check_1d(idct, dtype, (16,), -1)
748
+ self._check_1d(idct, dtype, (16, 2), 0)
749
+ self._check_1d(idct, dtype, (2, 16), 1)
750
+
751
+ def test_dst(self):
752
+ for dtype in self.real_dtypes:
753
+ self._check_1d(dst, dtype, (16,), -1)
754
+ self._check_1d(dst, dtype, (16, 2), 0)
755
+ self._check_1d(dst, dtype, (2, 16), 1)
756
+
757
+ def test_idst(self):
758
+ for dtype in self.real_dtypes:
759
+ self._check_1d(idst, dtype, (16,), -1)
760
+ self._check_1d(idst, dtype, (16, 2), 0)
761
+ self._check_1d(idst, dtype, (2, 16), 1)
762
+
763
+
764
+ class Test_DCTN_IDCTN:
765
+ dec = 14
766
+ dct_type = [1, 2, 3, 4]
767
+ norms = [None, 'ortho']
768
+ rstate = np.random.RandomState(1234)
769
+ shape = (32, 16)
770
+ data = rstate.randn(*shape)
771
+
772
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
773
+ (dstn, idstn)])
774
+ @pytest.mark.parametrize('axes', [None,
775
+ 1, (1,), [1],
776
+ 0, (0,), [0],
777
+ (0, 1), [0, 1],
778
+ (-2, -1), [-2, -1]])
779
+ @pytest.mark.parametrize('dct_type', dct_type)
780
+ @pytest.mark.parametrize('norm', ['ortho'])
781
+ def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
782
+ tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
783
+ tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
784
+ assert_array_almost_equal(self.data, tmp, decimal=12)
785
+
786
+ @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
787
+ (dstn, dst_2d_ref)])
788
+ @pytest.mark.parametrize('dct_type', dct_type)
789
+ @pytest.mark.parametrize('norm', norms)
790
+ def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
791
+ dct_type, norm):
792
+ y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
793
+ y2 = fforward_ref(self.data, type=dct_type, norm=norm)
794
+ assert_array_almost_equal(y1, y2, decimal=11)
795
+
796
+ @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
797
+ (idstn, idst_2d_ref)])
798
+ @pytest.mark.parametrize('dct_type', dct_type)
799
+ @pytest.mark.parametrize('norm', [None, 'ortho'])
800
+ def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
801
+ dct_type, norm):
802
+ fdata = dctn(self.data, type=dct_type, norm=norm)
803
+ y1 = finverse(fdata, type=dct_type, norm=norm)
804
+ y2 = finverse_ref(fdata, type=dct_type, norm=norm)
805
+ assert_array_almost_equal(y1, y2, decimal=11)
806
+
807
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
808
+ (dstn, idstn)])
809
+ def test_axes_and_shape(self, fforward, finverse):
810
+ with assert_raises(ValueError,
811
+ match="when given, axes and shape arguments"
812
+ " have to be of the same length"):
813
+ fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
814
+
815
+ with assert_raises(ValueError,
816
+ match="when given, axes and shape arguments"
817
+ " have to be of the same length"):
818
+ fforward(self.data, shape=self.data.shape[0], axes=None)
819
+
820
+ with assert_raises(ValueError,
821
+ match="when given, axes and shape arguments"
822
+ " have to be of the same length"):
823
+ fforward(self.data, shape=self.data.shape, axes=0)
824
+
825
+ @pytest.mark.parametrize('fforward', [dctn, dstn])
826
+ def test_shape(self, fforward):
827
+ tmp = fforward(self.data, shape=(128, 128), axes=None)
828
+ assert_equal(tmp.shape, (128, 128))
829
+
830
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
831
+ (dstn, idstn)])
832
+ @pytest.mark.parametrize('axes', [1, (1,), [1],
833
+ 0, (0,), [0]])
834
+ def test_shape_is_none_with_axes(self, fforward, finverse, axes):
835
+ tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
836
+ tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
837
+ assert_array_almost_equal(self.data, tmp, decimal=self.dec)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/__init__.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =============================================
3
+ Integration and ODEs (:mod:`scipy.integrate`)
4
+ =============================================
5
+
6
+ .. currentmodule:: scipy.integrate
7
+
8
+ Integrating functions, given function object
9
+ ============================================
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ quad -- General purpose integration
15
+ quad_vec -- General purpose integration of vector-valued functions
16
+ cubature -- General purpose multi-dimensional integration of array-valued functions
17
+ dblquad -- General purpose double integration
18
+ tplquad -- General purpose triple integration
19
+ nquad -- General purpose N-D integration
20
+ tanhsinh -- General purpose elementwise integration
21
+ fixed_quad -- Integrate func(x) using Gaussian quadrature of order n
22
+ newton_cotes -- Weights and error coefficient for Newton-Cotes integration
23
+ lebedev_rule
24
+ qmc_quad -- N-D integration using Quasi-Monte Carlo quadrature
25
+ IntegrationWarning -- Warning on issues during integration
26
+
27
+
28
+ Integrating functions, given fixed samples
29
+ ==========================================
30
+
31
+ .. autosummary::
32
+ :toctree: generated/
33
+
34
+ trapezoid -- Use trapezoidal rule to compute integral.
35
+ cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
36
+ simpson -- Use Simpson's rule to compute integral from samples.
37
+ cumulative_simpson -- Use Simpson's rule to cumulatively compute integral from samples.
38
+ romb -- Use Romberg Integration to compute integral from
39
+ -- (2**k + 1) evenly-spaced samples.
40
+
41
+ .. seealso::
42
+
43
+ :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
44
+ quadrature roots and weights for other weighting factors and regions.
45
+
46
+ Summation
47
+ =========
48
+
49
+ .. autosummary::
50
+ :toctree: generated/
51
+
52
+ nsum
53
+
54
+ Solving initial value problems for ODE systems
55
+ ==============================================
56
+
57
+ The solvers are implemented as individual classes, which can be used directly
58
+ (low-level usage) or through a convenience function.
59
+
60
+ .. autosummary::
61
+ :toctree: generated/
62
+
63
+ solve_ivp -- Convenient function for ODE integration.
64
+ RK23 -- Explicit Runge-Kutta solver of order 3(2).
65
+ RK45 -- Explicit Runge-Kutta solver of order 5(4).
66
+ DOP853 -- Explicit Runge-Kutta solver of order 8.
67
+ Radau -- Implicit Runge-Kutta solver of order 5.
68
+ BDF -- Implicit multi-step variable order (1 to 5) solver.
69
+ LSODA -- LSODA solver from ODEPACK Fortran package.
70
+ OdeSolver -- Base class for ODE solvers.
71
+ DenseOutput -- Local interpolant for computing a dense output.
72
+ OdeSolution -- Class which represents a continuous ODE solution.
73
+
74
+
75
+ Old API
76
+ -------
77
+
78
+ These are the routines developed earlier for SciPy. They wrap older solvers
79
+ implemented in Fortran (mostly ODEPACK). While the interface to them is not
80
+ particularly convenient and certain features are missing compared to the new
81
+ API, the solvers themselves are of good quality and work fast as compiled
82
+ Fortran code. In some cases, it might be worth using this old API.
83
+
84
+ .. autosummary::
85
+ :toctree: generated/
86
+
87
+ odeint -- General integration of ordinary differential equations.
88
+ ode -- Integrate ODE using VODE and ZVODE routines.
89
+ complex_ode -- Convert a complex-valued ODE to real-valued and integrate.
90
+ ODEintWarning -- Warning raised during the execution of `odeint`.
91
+
92
+
93
+ Solving boundary value problems for ODE systems
94
+ ===============================================
95
+
96
+ .. autosummary::
97
+ :toctree: generated/
98
+
99
+ solve_bvp -- Solve a boundary value problem for a system of ODEs.
100
+ """ # noqa: E501
101
+
102
+
103
+ from ._quadrature import *
104
+ from ._odepack_py import *
105
+ from ._quadpack_py import *
106
+ from ._ode import *
107
+ from ._bvp import solve_bvp
108
+ from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
109
+ OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
110
+ from ._quad_vec import quad_vec
111
+ from ._tanhsinh import nsum, tanhsinh
112
+ from ._cubature import cubature
113
+ from ._lebedev import lebedev_rule
114
+
115
+ # Deprecated namespaces, to be removed in v2.0.0
116
+ from . import dop, lsoda, vode, odepack, quadpack
117
+
118
+ __all__ = [s for s in dir() if not s.startswith('_')]
119
+
120
+ from scipy._lib._testutils import PytestTester
121
+ test = PytestTester(__name__)
122
+ del PytestTester
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_bvp.py ADDED
@@ -0,0 +1,1154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Boundary value problem solver."""
2
+ from warnings import warn
3
+
4
+ import numpy as np
5
+ from numpy.linalg import pinv
6
+
7
+ from scipy.sparse import coo_matrix, csc_matrix
8
+ from scipy.sparse.linalg import splu
9
+ from scipy.optimize import OptimizeResult
10
+
11
+
12
+ EPS = np.finfo(float).eps
13
+
14
+
15
+ def estimate_fun_jac(fun, x, y, p, f0=None):
16
+ """Estimate derivatives of an ODE system rhs with forward differences.
17
+
18
+ Returns
19
+ -------
20
+ df_dy : ndarray, shape (n, n, m)
21
+ Derivatives with respect to y. An element (i, j, q) corresponds to
22
+ d f_i(x_q, y_q) / d (y_q)_j.
23
+ df_dp : ndarray with shape (n, k, m) or None
24
+ Derivatives with respect to p. An element (i, j, q) corresponds to
25
+ d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
26
+ """
27
+ n, m = y.shape
28
+ if f0 is None:
29
+ f0 = fun(x, y, p)
30
+
31
+ dtype = y.dtype
32
+
33
+ df_dy = np.empty((n, n, m), dtype=dtype)
34
+ h = EPS**0.5 * (1 + np.abs(y))
35
+ for i in range(n):
36
+ y_new = y.copy()
37
+ y_new[i] += h[i]
38
+ hi = y_new[i] - y[i]
39
+ f_new = fun(x, y_new, p)
40
+ df_dy[:, i, :] = (f_new - f0) / hi
41
+
42
+ k = p.shape[0]
43
+ if k == 0:
44
+ df_dp = None
45
+ else:
46
+ df_dp = np.empty((n, k, m), dtype=dtype)
47
+ h = EPS**0.5 * (1 + np.abs(p))
48
+ for i in range(k):
49
+ p_new = p.copy()
50
+ p_new[i] += h[i]
51
+ hi = p_new[i] - p[i]
52
+ f_new = fun(x, y, p_new)
53
+ df_dp[:, i, :] = (f_new - f0) / hi
54
+
55
+ return df_dy, df_dp
56
+
57
+
58
+ def estimate_bc_jac(bc, ya, yb, p, bc0=None):
59
+ """Estimate derivatives of boundary conditions with forward differences.
60
+
61
+ Returns
62
+ -------
63
+ dbc_dya : ndarray, shape (n + k, n)
64
+ Derivatives with respect to ya. An element (i, j) corresponds to
65
+ d bc_i / d ya_j.
66
+ dbc_dyb : ndarray, shape (n + k, n)
67
+ Derivatives with respect to yb. An element (i, j) corresponds to
68
+ d bc_i / d ya_j.
69
+ dbc_dp : ndarray with shape (n + k, k) or None
70
+ Derivatives with respect to p. An element (i, j) corresponds to
71
+ d bc_i / d p_j. If `p` is empty, None is returned.
72
+ """
73
+ n = ya.shape[0]
74
+ k = p.shape[0]
75
+
76
+ if bc0 is None:
77
+ bc0 = bc(ya, yb, p)
78
+
79
+ dtype = ya.dtype
80
+
81
+ dbc_dya = np.empty((n, n + k), dtype=dtype)
82
+ h = EPS**0.5 * (1 + np.abs(ya))
83
+ for i in range(n):
84
+ ya_new = ya.copy()
85
+ ya_new[i] += h[i]
86
+ hi = ya_new[i] - ya[i]
87
+ bc_new = bc(ya_new, yb, p)
88
+ dbc_dya[i] = (bc_new - bc0) / hi
89
+ dbc_dya = dbc_dya.T
90
+
91
+ h = EPS**0.5 * (1 + np.abs(yb))
92
+ dbc_dyb = np.empty((n, n + k), dtype=dtype)
93
+ for i in range(n):
94
+ yb_new = yb.copy()
95
+ yb_new[i] += h[i]
96
+ hi = yb_new[i] - yb[i]
97
+ bc_new = bc(ya, yb_new, p)
98
+ dbc_dyb[i] = (bc_new - bc0) / hi
99
+ dbc_dyb = dbc_dyb.T
100
+
101
+ if k == 0:
102
+ dbc_dp = None
103
+ else:
104
+ h = EPS**0.5 * (1 + np.abs(p))
105
+ dbc_dp = np.empty((k, n + k), dtype=dtype)
106
+ for i in range(k):
107
+ p_new = p.copy()
108
+ p_new[i] += h[i]
109
+ hi = p_new[i] - p[i]
110
+ bc_new = bc(ya, yb, p_new)
111
+ dbc_dp[i] = (bc_new - bc0) / hi
112
+ dbc_dp = dbc_dp.T
113
+
114
+ return dbc_dya, dbc_dyb, dbc_dp
115
+
116
+
117
+ def compute_jac_indices(n, m, k):
118
+ """Compute indices for the collocation system Jacobian construction.
119
+
120
+ See `construct_global_jac` for the explanation.
121
+ """
122
+ i_col = np.repeat(np.arange((m - 1) * n), n)
123
+ j_col = (np.tile(np.arange(n), n * (m - 1)) +
124
+ np.repeat(np.arange(m - 1) * n, n**2))
125
+
126
+ i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
127
+ j_bc = np.tile(np.arange(n), n + k)
128
+
129
+ i_p_col = np.repeat(np.arange((m - 1) * n), k)
130
+ j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
131
+
132
+ i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
133
+ j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
134
+
135
+ i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
136
+ j = np.hstack((j_col, j_col + n,
137
+ j_bc, j_bc + (m - 1) * n,
138
+ j_p_col, j_p_bc))
139
+
140
+ return i, j
141
+
142
+
143
+ def stacked_matmul(a, b):
144
+ """Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
145
+
146
+ Empirical optimization. Use outer Python loop and BLAS for large
147
+ matrices, otherwise use a single einsum call.
148
+ """
149
+ if a.shape[1] > 50:
150
+ out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
151
+ for i in range(a.shape[0]):
152
+ out[i] = np.dot(a[i], b[i])
153
+ return out
154
+ else:
155
+ return np.einsum('...ij,...jk->...ik', a, b)
156
+
157
+
158
+ def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
159
+ df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
160
+ """Construct the Jacobian of the collocation system.
161
+
162
+ There are n * m + k functions: m - 1 collocations residuals, each
163
+ containing n components, followed by n + k boundary condition residuals.
164
+
165
+ There are n * m + k variables: m vectors of y, each containing n
166
+ components, followed by k values of vector p.
167
+
168
+ For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
169
+ the following sparsity structure:
170
+
171
+ 1 1 2 2 0 0 0 0 5
172
+ 1 1 2 2 0 0 0 0 5
173
+ 0 0 1 1 2 2 0 0 5
174
+ 0 0 1 1 2 2 0 0 5
175
+ 0 0 0 0 1 1 2 2 5
176
+ 0 0 0 0 1 1 2 2 5
177
+
178
+ 3 3 0 0 0 0 4 4 6
179
+ 3 3 0 0 0 0 4 4 6
180
+ 3 3 0 0 0 0 4 4 6
181
+
182
+ Zeros denote identically zero values, other values denote different kinds
183
+ of blocks in the matrix (see below). The blank row indicates the separation
184
+ of collocation residuals from boundary conditions. And the blank column
185
+ indicates the separation of y values from p values.
186
+
187
+ Refer to [1]_ (p. 306) for the formula of n x n blocks for derivatives
188
+ of collocation residuals with respect to y.
189
+
190
+ Parameters
191
+ ----------
192
+ n : int
193
+ Number of equations in the ODE system.
194
+ m : int
195
+ Number of nodes in the mesh.
196
+ k : int
197
+ Number of the unknown parameters.
198
+ i_jac, j_jac : ndarray
199
+ Row and column indices returned by `compute_jac_indices`. They
200
+ represent different blocks in the Jacobian matrix in the following
201
+ order (see the scheme above):
202
+
203
+ * 1: m - 1 diagonal n x n blocks for the collocation residuals.
204
+ * 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
205
+ * 3 : (n + k) x n block for the dependency of the boundary
206
+ conditions on ya.
207
+ * 4: (n + k) x n block for the dependency of the boundary
208
+ conditions on yb.
209
+ * 5: (m - 1) * n x k block for the dependency of the collocation
210
+ residuals on p.
211
+ * 6: (n + k) x k block for the dependency of the boundary
212
+ conditions on p.
213
+
214
+ df_dy : ndarray, shape (n, n, m)
215
+ Jacobian of f with respect to y computed at the mesh nodes.
216
+ df_dy_middle : ndarray, shape (n, n, m - 1)
217
+ Jacobian of f with respect to y computed at the middle between the
218
+ mesh nodes.
219
+ df_dp : ndarray with shape (n, k, m) or None
220
+ Jacobian of f with respect to p computed at the mesh nodes.
221
+ df_dp_middle : ndarray with shape (n, k, m - 1) or None
222
+ Jacobian of f with respect to p computed at the middle between the
223
+ mesh nodes.
224
+ dbc_dya, dbc_dyb : ndarray, shape (n, n)
225
+ Jacobian of bc with respect to ya and yb.
226
+ dbc_dp : ndarray with shape (n, k) or None
227
+ Jacobian of bc with respect to p.
228
+
229
+ Returns
230
+ -------
231
+ J : csc_matrix, shape (n * m + k, n * m + k)
232
+ Jacobian of the collocation system in a sparse form.
233
+
234
+ References
235
+ ----------
236
+ .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
237
+ Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
238
+ Number 3, pp. 299-316, 2001.
239
+ """
240
+ df_dy = np.transpose(df_dy, (2, 0, 1))
241
+ df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
242
+
243
+ h = h[:, np.newaxis, np.newaxis]
244
+
245
+ dtype = df_dy.dtype
246
+
247
+ # Computing diagonal n x n blocks.
248
+ dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
249
+ dPhi_dy_0[:] = -np.identity(n)
250
+ dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
251
+ T = stacked_matmul(df_dy_middle, df_dy[:-1])
252
+ dPhi_dy_0 -= h**2 / 12 * T
253
+
254
+ # Computing off-diagonal n x n blocks.
255
+ dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
256
+ dPhi_dy_1[:] = np.identity(n)
257
+ dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
258
+ T = stacked_matmul(df_dy_middle, df_dy[1:])
259
+ dPhi_dy_1 += h**2 / 12 * T
260
+
261
+ values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
262
+ dbc_dyb.ravel()))
263
+
264
+ if k > 0:
265
+ df_dp = np.transpose(df_dp, (2, 0, 1))
266
+ df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
267
+ T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
268
+ df_dp_middle += 0.125 * h * T
269
+ dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
270
+ values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
271
+
272
+ J = coo_matrix((values, (i_jac, j_jac)))
273
+ return csc_matrix(J)
274
+
275
+
276
+ def collocation_fun(fun, y, p, x, h):
277
+ """Evaluate collocation residuals.
278
+
279
+ This function lies in the core of the method. The solution is sought
280
+ as a cubic C1 continuous spline with derivatives matching the ODE rhs
281
+ at given nodes `x`. Collocation conditions are formed from the equality
282
+ of the spline derivatives and rhs of the ODE system in the middle points
283
+ between nodes.
284
+
285
+ Such method is classified to Lobbato IIIA family in ODE literature.
286
+ Refer to [1]_ for the formula and some discussion.
287
+
288
+ Returns
289
+ -------
290
+ col_res : ndarray, shape (n, m - 1)
291
+ Collocation residuals at the middle points of the mesh intervals.
292
+ y_middle : ndarray, shape (n, m - 1)
293
+ Values of the cubic spline evaluated at the middle points of the mesh
294
+ intervals.
295
+ f : ndarray, shape (n, m)
296
+ RHS of the ODE system evaluated at the mesh nodes.
297
+ f_middle : ndarray, shape (n, m - 1)
298
+ RHS of the ODE system evaluated at the middle points of the mesh
299
+ intervals (and using `y_middle`).
300
+
301
+ References
302
+ ----------
303
+ .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
304
+ Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
305
+ Number 3, pp. 299-316, 2001.
306
+ """
307
+ f = fun(x, y, p)
308
+ y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
309
+ 0.125 * h * (f[:, 1:] - f[:, :-1]))
310
+ f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
311
+ col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
312
+ 4 * f_middle)
313
+
314
+ return col_res, y_middle, f, f_middle
315
+
316
+
317
+ def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
318
+ """Create the function and the Jacobian for the collocation system."""
319
+ x_middle = x[:-1] + 0.5 * h
320
+ i_jac, j_jac = compute_jac_indices(n, m, k)
321
+
322
+ def col_fun(y, p):
323
+ return collocation_fun(fun, y, p, x, h)
324
+
325
+ def sys_jac(y, p, y_middle, f, f_middle, bc0):
326
+ if fun_jac is None:
327
+ df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
328
+ df_dy_middle, df_dp_middle = estimate_fun_jac(
329
+ fun, x_middle, y_middle, p, f_middle)
330
+ else:
331
+ df_dy, df_dp = fun_jac(x, y, p)
332
+ df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
333
+
334
+ if bc_jac is None:
335
+ dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
336
+ p, bc0)
337
+ else:
338
+ dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
339
+
340
+ return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
341
+ df_dy_middle, df_dp, df_dp_middle, dbc_dya,
342
+ dbc_dyb, dbc_dp)
343
+
344
+ return col_fun, sys_jac
345
+
346
+
347
+ def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
348
+ """Solve the nonlinear collocation system by a Newton method.
349
+
350
+ This is a simple Newton method with a backtracking line search. As
351
+ advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
352
+ is used, where J is the Jacobian matrix at the current iteration and r is
353
+ the vector or collocation residuals (values of the system lhs).
354
+
355
+ The method alters between full Newton iterations and the fixed-Jacobian
356
+ iterations based
357
+
358
+ There are other tricks proposed in [1]_, but they are not used as they
359
+ don't seem to improve anything significantly, and even break the
360
+ convergence on some test problems I tried.
361
+
362
+ All important parameters of the algorithm are defined inside the function.
363
+
364
+ Parameters
365
+ ----------
366
+ n : int
367
+ Number of equations in the ODE system.
368
+ m : int
369
+ Number of nodes in the mesh.
370
+ h : ndarray, shape (m-1,)
371
+ Mesh intervals.
372
+ col_fun : callable
373
+ Function computing collocation residuals.
374
+ bc : callable
375
+ Function computing boundary condition residuals.
376
+ jac : callable
377
+ Function computing the Jacobian of the whole system (including
378
+ collocation and boundary condition residuals). It is supposed to
379
+ return csc_matrix.
380
+ y : ndarray, shape (n, m)
381
+ Initial guess for the function values at the mesh nodes.
382
+ p : ndarray, shape (k,)
383
+ Initial guess for the unknown parameters.
384
+ B : ndarray with shape (n, n) or None
385
+ Matrix to force the S y(a) = 0 condition for a problems with the
386
+ singular term. If None, the singular term is assumed to be absent.
387
+ bvp_tol : float
388
+ Tolerance to which we want to solve a BVP.
389
+ bc_tol : float
390
+ Tolerance to which we want to satisfy the boundary conditions.
391
+
392
+ Returns
393
+ -------
394
+ y : ndarray, shape (n, m)
395
+ Final iterate for the function values at the mesh nodes.
396
+ p : ndarray, shape (k,)
397
+ Final iterate for the unknown parameters.
398
+ singular : bool
399
+ True, if the LU decomposition failed because Jacobian turned out
400
+ to be singular.
401
+
402
+ References
403
+ ----------
404
+ .. [1] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
405
+ Boundary Value Problems for Ordinary Differential Equations"
406
+ """
407
+ # We know that the solution residuals at the middle points of the mesh
408
+ # are connected with collocation residuals r_middle = 1.5 * col_res / h.
409
+ # As our BVP solver tries to decrease relative residuals below a certain
410
+ # tolerance, it seems reasonable to terminated Newton iterations by
411
+ # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
412
+ # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
413
+ # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
414
+ # should be computed as follows:
415
+ tol_r = 2/3 * h * 5e-2 * bvp_tol
416
+
417
+ # Maximum allowed number of Jacobian evaluation and factorization, in
418
+ # other words, the maximum number of full Newton iterations. A small value
419
+ # is recommended in the literature.
420
+ max_njev = 4
421
+
422
+ # Maximum number of iterations, considering that some of them can be
423
+ # performed with the fixed Jacobian. In theory, such iterations are cheap,
424
+ # but it's not that simple in Python.
425
+ max_iter = 8
426
+
427
+ # Minimum relative improvement of the criterion function to accept the
428
+ # step (Armijo constant).
429
+ sigma = 0.2
430
+
431
+ # Step size decrease factor for backtracking.
432
+ tau = 0.5
433
+
434
+ # Maximum number of backtracking steps, the minimum step is then
435
+ # tau ** n_trial.
436
+ n_trial = 4
437
+
438
+ col_res, y_middle, f, f_middle = col_fun(y, p)
439
+ bc_res = bc(y[:, 0], y[:, -1], p)
440
+ res = np.hstack((col_res.ravel(order='F'), bc_res))
441
+
442
+ njev = 0
443
+ singular = False
444
+ recompute_jac = True
445
+ for iteration in range(max_iter):
446
+ if recompute_jac:
447
+ J = jac(y, p, y_middle, f, f_middle, bc_res)
448
+ njev += 1
449
+ try:
450
+ LU = splu(J)
451
+ except RuntimeError:
452
+ singular = True
453
+ break
454
+
455
+ step = LU.solve(res)
456
+ cost = np.dot(step, step)
457
+
458
+ y_step = step[:m * n].reshape((n, m), order='F')
459
+ p_step = step[m * n:]
460
+
461
+ alpha = 1
462
+ for trial in range(n_trial + 1):
463
+ y_new = y - alpha * y_step
464
+ if B is not None:
465
+ y_new[:, 0] = np.dot(B, y_new[:, 0])
466
+ p_new = p - alpha * p_step
467
+
468
+ col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
469
+ bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
470
+ res = np.hstack((col_res.ravel(order='F'), bc_res))
471
+
472
+ step_new = LU.solve(res)
473
+ cost_new = np.dot(step_new, step_new)
474
+ if cost_new < (1 - 2 * alpha * sigma) * cost:
475
+ break
476
+
477
+ if trial < n_trial:
478
+ alpha *= tau
479
+
480
+ y = y_new
481
+ p = p_new
482
+
483
+ if njev == max_njev:
484
+ break
485
+
486
+ if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
487
+ np.all(np.abs(bc_res) < bc_tol)):
488
+ break
489
+
490
+ # If the full step was taken, then we are going to continue with
491
+ # the same Jacobian. This is the approach of BVP_SOLVER.
492
+ if alpha == 1:
493
+ step = step_new
494
+ cost = cost_new
495
+ recompute_jac = False
496
+ else:
497
+ recompute_jac = True
498
+
499
+ return y, p, singular
500
+
501
+
502
+ def print_iteration_header():
503
+ print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
504
+ f"{'Total nodes':^15}{'Nodes added':^15}")
505
+
506
+
507
+ def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
508
+ nodes_added):
509
+ print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
510
+ f"{total_nodes:^15}{nodes_added:^15}")
511
+
512
+
513
+ class BVPResult(OptimizeResult):
514
+ pass
515
+
516
+
517
+ TERMINATION_MESSAGES = {
518
+ 0: "The algorithm converged to the desired accuracy.",
519
+ 1: "The maximum number of mesh nodes is exceeded.",
520
+ 2: "A singular Jacobian encountered when solving the collocation system.",
521
+ 3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
522
+ }
523
+
524
+
525
+ def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
526
+ """Estimate rms values of collocation residuals using Lobatto quadrature.
527
+
528
+ The residuals are defined as the difference between the derivatives of
529
+ our solution and rhs of the ODE system. We use relative residuals, i.e.,
530
+ normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
531
+ normalized integrals of the squared relative residuals over each interval.
532
+ Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
533
+ fact that residuals at the mesh nodes are identically zero.
534
+
535
+ In [2] they don't normalize integrals by interval lengths, which gives
536
+ a higher rate of convergence of the residuals by the factor of h**0.5.
537
+ I chose to do such normalization for an ease of interpretation of return
538
+ values as RMS estimates.
539
+
540
+ Returns
541
+ -------
542
+ rms_res : ndarray, shape (m - 1,)
543
+ Estimated rms values of the relative residuals over each interval.
544
+
545
+ References
546
+ ----------
547
+ .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
548
+ .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
549
+ Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
550
+ Number 3, pp. 299-316, 2001.
551
+ """
552
+ x_middle = x[:-1] + 0.5 * h
553
+ s = 0.5 * h * (3/7)**0.5
554
+ x1 = x_middle + s
555
+ x2 = x_middle - s
556
+ y1 = sol(x1)
557
+ y2 = sol(x2)
558
+ y1_prime = sol(x1, 1)
559
+ y2_prime = sol(x2, 1)
560
+ f1 = fun(x1, y1, p)
561
+ f2 = fun(x2, y2, p)
562
+ r1 = y1_prime - f1
563
+ r2 = y2_prime - f2
564
+
565
+ r_middle /= 1 + np.abs(f_middle)
566
+ r1 /= 1 + np.abs(f1)
567
+ r2 /= 1 + np.abs(f2)
568
+
569
+ r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
570
+ r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
571
+ r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
572
+
573
+ return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
574
+
575
+
576
+ def create_spline(y, yp, x, h):
577
+ """Create a cubic spline given values and derivatives.
578
+
579
+ Formulas for the coefficients are taken from interpolate.CubicSpline.
580
+
581
+ Returns
582
+ -------
583
+ sol : PPoly
584
+ Constructed spline as a PPoly instance.
585
+ """
586
+ from scipy.interpolate import PPoly
587
+
588
+ n, m = y.shape
589
+ c = np.empty((4, n, m - 1), dtype=y.dtype)
590
+ slope = (y[:, 1:] - y[:, :-1]) / h
591
+ t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
592
+ c[0] = t / h
593
+ c[1] = (slope - yp[:, :-1]) / h - t
594
+ c[2] = yp[:, :-1]
595
+ c[3] = y[:, :-1]
596
+ c = np.moveaxis(c, 1, 0)
597
+
598
+ return PPoly(c, x, extrapolate=True, axis=1)
599
+
600
+
601
+ def modify_mesh(x, insert_1, insert_2):
602
+ """Insert nodes into a mesh.
603
+
604
+ Nodes removal logic is not established, its impact on the solver is
605
+ presumably negligible. So, only insertion is done in this function.
606
+
607
+ Parameters
608
+ ----------
609
+ x : ndarray, shape (m,)
610
+ Mesh nodes.
611
+ insert_1 : ndarray
612
+ Intervals to each insert 1 new node in the middle.
613
+ insert_2 : ndarray
614
+ Intervals to each insert 2 new nodes, such that divide an interval
615
+ into 3 equal parts.
616
+
617
+ Returns
618
+ -------
619
+ x_new : ndarray
620
+ New mesh nodes.
621
+
622
+ Notes
623
+ -----
624
+ `insert_1` and `insert_2` should not have common values.
625
+ """
626
+ # Because np.insert implementation apparently varies with a version of
627
+ # NumPy, we use a simple and reliable approach with sorting.
628
+ return np.sort(np.hstack((
629
+ x,
630
+ 0.5 * (x[insert_1] + x[insert_1 + 1]),
631
+ (2 * x[insert_2] + x[insert_2 + 1]) / 3,
632
+ (x[insert_2] + 2 * x[insert_2 + 1]) / 3
633
+ )))
634
+
635
+
636
+ def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
637
+ """Wrap functions for unified usage in the solver."""
638
+ if fun_jac is None:
639
+ fun_jac_wrapped = None
640
+
641
+ if bc_jac is None:
642
+ bc_jac_wrapped = None
643
+
644
+ if k == 0:
645
+ def fun_p(x, y, _):
646
+ return np.asarray(fun(x, y), dtype)
647
+
648
+ def bc_wrapped(ya, yb, _):
649
+ return np.asarray(bc(ya, yb), dtype)
650
+
651
+ if fun_jac is not None:
652
+ def fun_jac_p(x, y, _):
653
+ return np.asarray(fun_jac(x, y), dtype), None
654
+
655
+ if bc_jac is not None:
656
+ def bc_jac_wrapped(ya, yb, _):
657
+ dbc_dya, dbc_dyb = bc_jac(ya, yb)
658
+ return (np.asarray(dbc_dya, dtype),
659
+ np.asarray(dbc_dyb, dtype), None)
660
+ else:
661
+ def fun_p(x, y, p):
662
+ return np.asarray(fun(x, y, p), dtype)
663
+
664
+ def bc_wrapped(x, y, p):
665
+ return np.asarray(bc(x, y, p), dtype)
666
+
667
+ if fun_jac is not None:
668
+ def fun_jac_p(x, y, p):
669
+ df_dy, df_dp = fun_jac(x, y, p)
670
+ return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
671
+
672
+ if bc_jac is not None:
673
+ def bc_jac_wrapped(ya, yb, p):
674
+ dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
675
+ return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
676
+ np.asarray(dbc_dp, dtype))
677
+
678
+ if S is None:
679
+ fun_wrapped = fun_p
680
+ else:
681
+ def fun_wrapped(x, y, p):
682
+ f = fun_p(x, y, p)
683
+ if x[0] == a:
684
+ f[:, 0] = np.dot(D, f[:, 0])
685
+ f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
686
+ else:
687
+ f += np.dot(S, y) / (x - a)
688
+ return f
689
+
690
+ if fun_jac is not None:
691
+ if S is None:
692
+ fun_jac_wrapped = fun_jac_p
693
+ else:
694
+ Sr = S[:, :, np.newaxis]
695
+
696
+ def fun_jac_wrapped(x, y, p):
697
+ df_dy, df_dp = fun_jac_p(x, y, p)
698
+ if x[0] == a:
699
+ df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
700
+ df_dy[:, :, 1:] += Sr / (x[1:] - a)
701
+ else:
702
+ df_dy += Sr / (x - a)
703
+
704
+ return df_dy, df_dp
705
+
706
+ return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
707
+
708
+
709
+ def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
710
+ tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
711
+ """Solve a boundary value problem for a system of ODEs.
712
+
713
+ This function numerically solves a first order system of ODEs subject to
714
+ two-point boundary conditions::
715
+
716
+ dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
717
+ bc(y(a), y(b), p) = 0
718
+
719
+ Here x is a 1-D independent variable, y(x) is an n-D
720
+ vector-valued function and p is a k-D vector of unknown
721
+ parameters which is to be found along with y(x). For the problem to be
722
+ determined, there must be n + k boundary conditions, i.e., bc must be an
723
+ (n + k)-D function.
724
+
725
+ The last singular term on the right-hand side of the system is optional.
726
+ It is defined by an n-by-n matrix S, such that the solution must satisfy
727
+ S y(a) = 0. This condition will be forced during iterations, so it must not
728
+ contradict boundary conditions. See [2]_ for the explanation how this term
729
+ is handled when solving BVPs numerically.
730
+
731
+ Problems in a complex domain can be solved as well. In this case, y and p
732
+ are considered to be complex, and f and bc are assumed to be complex-valued
733
+ functions, but x stays real. Note that f and bc must be complex
734
+ differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
735
+ should rewrite your problem for real and imaginary parts separately. To
736
+ solve a problem in a complex domain, pass an initial guess for y with a
737
+ complex data type (see below).
738
+
739
+ Parameters
740
+ ----------
741
+ fun : callable
742
+ Right-hand side of the system. The calling signature is ``fun(x, y)``,
743
+ or ``fun(x, y, p)`` if parameters are present. All arguments are
744
+ ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
745
+ ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
746
+ return value must be an array with shape (n, m) and with the same
747
+ layout as ``y``.
748
+ bc : callable
749
+ Function evaluating residuals of the boundary conditions. The calling
750
+ signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
751
+ present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
752
+ and ``p`` with shape (k,). The return value must be an array with
753
+ shape (n + k,).
754
+ x : array_like, shape (m,)
755
+ Initial mesh. Must be a strictly increasing sequence of real numbers
756
+ with ``x[0]=a`` and ``x[-1]=b``.
757
+ y : array_like, shape (n, m)
758
+ Initial guess for the function values at the mesh nodes, ith column
759
+ corresponds to ``x[i]``. For problems in a complex domain pass `y`
760
+ with a complex data type (even if the initial guess is purely real).
761
+ p : array_like with shape (k,) or None, optional
762
+ Initial guess for the unknown parameters. If None (default), it is
763
+ assumed that the problem doesn't depend on any parameters.
764
+ S : array_like with shape (n, n) or None
765
+ Matrix defining the singular term. If None (default), the problem is
766
+ solved without the singular term.
767
+ fun_jac : callable or None, optional
768
+ Function computing derivatives of f with respect to y and p. The
769
+ calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
770
+ parameters are present. The return must contain 1 or 2 elements in the
771
+ following order:
772
+
773
+ * df_dy : array_like with shape (n, n, m), where an element
774
+ (i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
775
+ * df_dp : array_like with shape (n, k, m), where an element
776
+ (i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
777
+
778
+ Here q numbers nodes at which x and y are defined, whereas i and j
779
+ number vector components. If the problem is solved without unknown
780
+ parameters, df_dp should not be returned.
781
+
782
+ If `fun_jac` is None (default), the derivatives will be estimated
783
+ by the forward finite differences.
784
+ bc_jac : callable or None, optional
785
+ Function computing derivatives of bc with respect to ya, yb, and p.
786
+ The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
787
+ if parameters are present. The return must contain 2 or 3 elements in
788
+ the following order:
789
+
790
+ * dbc_dya : array_like with shape (n, n), where an element (i, j)
791
+ equals to d bc_i(ya, yb, p) / d ya_j.
792
+ * dbc_dyb : array_like with shape (n, n), where an element (i, j)
793
+ equals to d bc_i(ya, yb, p) / d yb_j.
794
+ * dbc_dp : array_like with shape (n, k), where an element (i, j)
795
+ equals to d bc_i(ya, yb, p) / d p_j.
796
+
797
+ If the problem is solved without unknown parameters, dbc_dp should not
798
+ be returned.
799
+
800
+ If `bc_jac` is None (default), the derivatives will be estimated by
801
+ the forward finite differences.
802
+ tol : float, optional
803
+ Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
804
+ where y is the found solution, then the solver tries to achieve on each
805
+ mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
806
+ estimated in a root mean squared sense (using a numerical quadrature
807
+ formula). Default is 1e-3.
808
+ max_nodes : int, optional
809
+ Maximum allowed number of the mesh nodes. If exceeded, the algorithm
810
+ terminates. Default is 1000.
811
+ verbose : {0, 1, 2}, optional
812
+ Level of algorithm's verbosity:
813
+
814
+ * 0 (default) : work silently.
815
+ * 1 : display a termination report.
816
+ * 2 : display progress during iterations.
817
+ bc_tol : float, optional
818
+ Desired absolute tolerance for the boundary condition residuals: `bc`
819
+ value should satisfy ``abs(bc) < bc_tol`` component-wise.
820
+ Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
821
+ tolerance.
822
+
823
+ Returns
824
+ -------
825
+ Bunch object with the following fields defined:
826
+ sol : PPoly
827
+ Found solution for y as `scipy.interpolate.PPoly` instance, a C1
828
+ continuous cubic spline.
829
+ p : ndarray or None, shape (k,)
830
+ Found parameters. None, if the parameters were not present in the
831
+ problem.
832
+ x : ndarray, shape (m,)
833
+ Nodes of the final mesh.
834
+ y : ndarray, shape (n, m)
835
+ Solution values at the mesh nodes.
836
+ yp : ndarray, shape (n, m)
837
+ Solution derivatives at the mesh nodes.
838
+ rms_residuals : ndarray, shape (m - 1,)
839
+ RMS values of the relative residuals over each mesh interval (see the
840
+ description of `tol` parameter).
841
+ niter : int
842
+ Number of completed iterations.
843
+ status : int
844
+ Reason for algorithm termination:
845
+
846
+ * 0: The algorithm converged to the desired accuracy.
847
+ * 1: The maximum number of mesh nodes is exceeded.
848
+ * 2: A singular Jacobian encountered when solving the collocation
849
+ system.
850
+
851
+ message : string
852
+ Verbal description of the termination reason.
853
+ success : bool
854
+ True if the algorithm converged to the desired accuracy (``status=0``).
855
+
856
+ Notes
857
+ -----
858
+ This function implements a 4th order collocation algorithm with the
859
+ control of residuals similar to [1]_. A collocation system is solved
860
+ by a damped Newton method with an affine-invariant criterion function as
861
+ described in [3]_.
862
+
863
+ Note that in [1]_ integral residuals are defined without normalization
864
+ by interval lengths. So, their definition is different by a multiplier of
865
+ h**0.5 (h is an interval length) from the definition used here.
866
+
867
+ .. versionadded:: 0.18.0
868
+
869
+ References
870
+ ----------
871
+ .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
872
+ Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
873
+ Number 3, pp. 299-316, 2001.
874
+ .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
875
+ Solver".
876
+ .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
877
+ Boundary Value Problems for Ordinary Differential Equations".
878
+ .. [4] `Cauchy-Riemann equations
879
+ <https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
880
+ Wikipedia.
881
+
882
+ Examples
883
+ --------
884
+ In the first example, we solve Bratu's problem::
885
+
886
+ y'' + k * exp(y) = 0
887
+ y(0) = y(1) = 0
888
+
889
+ for k = 1.
890
+
891
+ We rewrite the equation as a first-order system and implement its
892
+ right-hand side evaluation::
893
+
894
+ y1' = y2
895
+ y2' = -exp(y1)
896
+
897
+ >>> import numpy as np
898
+ >>> def fun(x, y):
899
+ ... return np.vstack((y[1], -np.exp(y[0])))
900
+
901
+ Implement evaluation of the boundary condition residuals:
902
+
903
+ >>> def bc(ya, yb):
904
+ ... return np.array([ya[0], yb[0]])
905
+
906
+ Define the initial mesh with 5 nodes:
907
+
908
+ >>> x = np.linspace(0, 1, 5)
909
+
910
+ This problem is known to have two solutions. To obtain both of them, we
911
+ use two different initial guesses for y. We denote them by subscripts
912
+ a and b.
913
+
914
+ >>> y_a = np.zeros((2, x.size))
915
+ >>> y_b = np.zeros((2, x.size))
916
+ >>> y_b[0] = 3
917
+
918
+ Now we are ready to run the solver.
919
+
920
+ >>> from scipy.integrate import solve_bvp
921
+ >>> res_a = solve_bvp(fun, bc, x, y_a)
922
+ >>> res_b = solve_bvp(fun, bc, x, y_b)
923
+
924
+ Let's plot the two found solutions. We take an advantage of having the
925
+ solution in a spline form to produce a smooth plot.
926
+
927
+ >>> x_plot = np.linspace(0, 1, 100)
928
+ >>> y_plot_a = res_a.sol(x_plot)[0]
929
+ >>> y_plot_b = res_b.sol(x_plot)[0]
930
+ >>> import matplotlib.pyplot as plt
931
+ >>> plt.plot(x_plot, y_plot_a, label='y_a')
932
+ >>> plt.plot(x_plot, y_plot_b, label='y_b')
933
+ >>> plt.legend()
934
+ >>> plt.xlabel("x")
935
+ >>> plt.ylabel("y")
936
+ >>> plt.show()
937
+
938
+ We see that the two solutions have similar shape, but differ in scale
939
+ significantly.
940
+
941
+ In the second example, we solve a simple Sturm-Liouville problem::
942
+
943
+ y'' + k**2 * y = 0
944
+ y(0) = y(1) = 0
945
+
946
+ It is known that a non-trivial solution y = A * sin(k * x) is possible for
947
+ k = pi * n, where n is an integer. To establish the normalization constant
948
+ A = 1 we add a boundary condition::
949
+
950
+ y'(0) = k
951
+
952
+ Again, we rewrite our equation as a first-order system and implement its
953
+ right-hand side evaluation::
954
+
955
+ y1' = y2
956
+ y2' = -k**2 * y1
957
+
958
+ >>> def fun(x, y, p):
959
+ ... k = p[0]
960
+ ... return np.vstack((y[1], -k**2 * y[0]))
961
+
962
+ Note that parameters p are passed as a vector (with one element in our
963
+ case).
964
+
965
+ Implement the boundary conditions:
966
+
967
+ >>> def bc(ya, yb, p):
968
+ ... k = p[0]
969
+ ... return np.array([ya[0], yb[0], ya[1] - k])
970
+
971
+ Set up the initial mesh and guess for y. We aim to find the solution for
972
+ k = 2 * pi, to achieve that we set values of y to approximately follow
973
+ sin(2 * pi * x):
974
+
975
+ >>> x = np.linspace(0, 1, 5)
976
+ >>> y = np.zeros((2, x.size))
977
+ >>> y[0, 1] = 1
978
+ >>> y[0, 3] = -1
979
+
980
+ Run the solver with 6 as an initial guess for k.
981
+
982
+ >>> sol = solve_bvp(fun, bc, x, y, p=[6])
983
+
984
+ We see that the found k is approximately correct:
985
+
986
+ >>> sol.p[0]
987
+ 6.28329460046
988
+
989
+ And, finally, plot the solution to see the anticipated sinusoid:
990
+
991
+ >>> x_plot = np.linspace(0, 1, 100)
992
+ >>> y_plot = sol.sol(x_plot)[0]
993
+ >>> plt.plot(x_plot, y_plot)
994
+ >>> plt.xlabel("x")
995
+ >>> plt.ylabel("y")
996
+ >>> plt.show()
997
+ """
998
+ x = np.asarray(x, dtype=float)
999
+ if x.ndim != 1:
1000
+ raise ValueError("`x` must be 1 dimensional.")
1001
+ h = np.diff(x)
1002
+ if np.any(h <= 0):
1003
+ raise ValueError("`x` must be strictly increasing.")
1004
+ a = x[0]
1005
+
1006
+ y = np.asarray(y)
1007
+ if np.issubdtype(y.dtype, np.complexfloating):
1008
+ dtype = complex
1009
+ else:
1010
+ dtype = float
1011
+ y = y.astype(dtype, copy=False)
1012
+
1013
+ if y.ndim != 2:
1014
+ raise ValueError("`y` must be 2 dimensional.")
1015
+ if y.shape[1] != x.shape[0]:
1016
+ raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
1017
+ f"has {y.shape[1]}.")
1018
+
1019
+ if p is None:
1020
+ p = np.array([])
1021
+ else:
1022
+ p = np.asarray(p, dtype=dtype)
1023
+ if p.ndim != 1:
1024
+ raise ValueError("`p` must be 1 dimensional.")
1025
+
1026
+ if tol < 100 * EPS:
1027
+ warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
1028
+ tol = 100 * EPS
1029
+
1030
+ if verbose not in [0, 1, 2]:
1031
+ raise ValueError("`verbose` must be in [0, 1, 2].")
1032
+
1033
+ n = y.shape[0]
1034
+ k = p.shape[0]
1035
+
1036
+ if S is not None:
1037
+ S = np.asarray(S, dtype=dtype)
1038
+ if S.shape != (n, n):
1039
+ raise ValueError(f"`S` is expected to have shape {(n, n)}, "
1040
+ f"but actually has {S.shape}")
1041
+
1042
+ # Compute I - S^+ S to impose necessary boundary conditions.
1043
+ B = np.identity(n) - np.dot(pinv(S), S)
1044
+
1045
+ y[:, 0] = np.dot(B, y[:, 0])
1046
+
1047
+ # Compute (I - S)^+ to correct derivatives at x=a.
1048
+ D = pinv(np.identity(n) - S)
1049
+ else:
1050
+ B = None
1051
+ D = None
1052
+
1053
+ if bc_tol is None:
1054
+ bc_tol = tol
1055
+
1056
+ # Maximum number of iterations
1057
+ max_iteration = 10
1058
+
1059
+ fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
1060
+ fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
1061
+
1062
+ f = fun_wrapped(x, y, p)
1063
+ if f.shape != y.shape:
1064
+ raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
1065
+ f"but actually has {f.shape}.")
1066
+
1067
+ bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
1068
+ if bc_res.shape != (n + k,):
1069
+ raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
1070
+ f"but actually has {bc_res.shape}.")
1071
+
1072
+ status = 0
1073
+ iteration = 0
1074
+ if verbose == 2:
1075
+ print_iteration_header()
1076
+
1077
+ while True:
1078
+ m = x.shape[0]
1079
+
1080
+ col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
1081
+ fun_jac_wrapped, bc_jac_wrapped, x, h)
1082
+ y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
1083
+ y, p, B, tol, bc_tol)
1084
+ iteration += 1
1085
+
1086
+ col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
1087
+ p, x, h)
1088
+ bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
1089
+ max_bc_res = np.max(abs(bc_res))
1090
+
1091
+ # This relation is not trivial, but can be verified.
1092
+ r_middle = 1.5 * col_res / h
1093
+ sol = create_spline(y, f, x, h)
1094
+ rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
1095
+ r_middle, f_middle)
1096
+ max_rms_res = np.max(rms_res)
1097
+
1098
+ if singular:
1099
+ status = 2
1100
+ break
1101
+
1102
+ insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
1103
+ insert_2, = np.nonzero(rms_res >= 100 * tol)
1104
+ nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
1105
+
1106
+ if m + nodes_added > max_nodes:
1107
+ status = 1
1108
+ if verbose == 2:
1109
+ nodes_added = f"({nodes_added})"
1110
+ print_iteration_progress(iteration, max_rms_res, max_bc_res,
1111
+ m, nodes_added)
1112
+ break
1113
+
1114
+ if verbose == 2:
1115
+ print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
1116
+ nodes_added)
1117
+
1118
+ if nodes_added > 0:
1119
+ x = modify_mesh(x, insert_1, insert_2)
1120
+ h = np.diff(x)
1121
+ y = sol(x)
1122
+ elif max_bc_res <= bc_tol:
1123
+ status = 0
1124
+ break
1125
+ elif iteration >= max_iteration:
1126
+ status = 3
1127
+ break
1128
+
1129
+ if verbose > 0:
1130
+ if status == 0:
1131
+ print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
1132
+ f"Maximum relative residual: {max_rms_res:.2e} \n"
1133
+ f"Maximum boundary residual: {max_bc_res:.2e}")
1134
+ elif status == 1:
1135
+ print(f"Number of nodes is exceeded after iteration {iteration}. \n"
1136
+ f"Maximum relative residual: {max_rms_res:.2e} \n"
1137
+ f"Maximum boundary residual: {max_bc_res:.2e}")
1138
+ elif status == 2:
1139
+ print("Singular Jacobian encountered when solving the collocation "
1140
+ f"system on iteration {iteration}. \n"
1141
+ f"Maximum relative residual: {max_rms_res:.2e} \n"
1142
+ f"Maximum boundary residual: {max_bc_res:.2e}")
1143
+ elif status == 3:
1144
+ print("The solver was unable to satisfy boundary conditions "
1145
+ f"tolerance on iteration {iteration}. \n"
1146
+ f"Maximum relative residual: {max_rms_res:.2e} \n"
1147
+ f"Maximum boundary residual: {max_bc_res:.2e}")
1148
+
1149
+ if p.size == 0:
1150
+ p = None
1151
+
1152
+ return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
1153
+ niter=iteration, status=status,
1154
+ message=TERMINATION_MESSAGES[status], success=status == 0)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_cubature.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import heapq
3
+ import itertools
4
+
5
+ from dataclasses import dataclass, field
6
+ from types import ModuleType
7
+ from typing import Any, TypeAlias
8
+
9
+ from scipy._lib._array_api import (
10
+ array_namespace,
11
+ xp_size,
12
+ xp_copy,
13
+ xp_broadcast_promote
14
+ )
15
+ from scipy._lib._util import MapWrapper
16
+
17
+ from scipy.integrate._rules import (
18
+ ProductNestedFixed,
19
+ GaussKronrodQuadrature,
20
+ GenzMalikCubature,
21
+ )
22
+ from scipy.integrate._rules._base import _split_subregion
23
+
24
+ __all__ = ['cubature']
25
+
26
+ Array: TypeAlias = Any # To be changed to an array-api-typing Protocol later
27
+
28
+
29
+ @dataclass
30
+ class CubatureRegion:
31
+ estimate: Array
32
+ error: Array
33
+ a: Array
34
+ b: Array
35
+ _xp: ModuleType = field(repr=False)
36
+
37
+ def __lt__(self, other):
38
+ # Consider regions with higher error estimates as being "less than" regions with
39
+ # lower order estimates, so that regions with high error estimates are placed at
40
+ # the top of the heap.
41
+
42
+ this_err = self._xp.max(self._xp.abs(self.error))
43
+ other_err = self._xp.max(self._xp.abs(other.error))
44
+
45
+ return this_err > other_err
46
+
47
+
48
+ @dataclass
49
+ class CubatureResult:
50
+ estimate: Array
51
+ error: Array
52
+ status: str
53
+ regions: list[CubatureRegion]
54
+ subdivisions: int
55
+ atol: float
56
+ rtol: float
57
+
58
+
59
+ def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
60
+ args=(), workers=1, points=None):
61
+ r"""
62
+ Adaptive cubature of multidimensional array-valued function.
63
+
64
+ Given an arbitrary integration rule, this function returns an estimate of the
65
+ integral to the requested tolerance over the region defined by the arrays `a` and
66
+ `b` specifying the corners of a hypercube.
67
+
68
+ Convergence is not guaranteed for all integrals.
69
+
70
+ Parameters
71
+ ----------
72
+ f : callable
73
+ Function to integrate. `f` must have the signature::
74
+
75
+ f(x : ndarray, *args) -> ndarray
76
+
77
+ `f` should accept arrays ``x`` of shape::
78
+
79
+ (npoints, ndim)
80
+
81
+ and output arrays of shape::
82
+
83
+ (npoints, output_dim_1, ..., output_dim_n)
84
+
85
+ In this case, `cubature` will return arrays of shape::
86
+
87
+ (output_dim_1, ..., output_dim_n)
88
+ a, b : array_like
89
+ Lower and upper limits of integration as 1D arrays specifying the left and right
90
+ endpoints of the intervals being integrated over. Limits can be infinite.
91
+ rule : str, optional
92
+ Rule used to estimate the integral. If passing a string, the options are
93
+ "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
94
+ "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
95
+ Cartesian product rule is used. "gk21", "gk15" are also supported for
96
+ compatibility with `quad_vec`. See Notes.
97
+ rtol, atol : float, optional
98
+ Relative and absolute tolerances. Iterations are performed until the error is
99
+ estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
100
+ relative accuracy (number of correct digits), while `atol` controls absolute
101
+ accuracy (number of correct decimal places). To achieve the desired `rtol`, set
102
+ `atol` to be smaller than the smallest value that can be expected from
103
+ ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
104
+ larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
105
+ Conversely, to achieve the desired `atol`, set `rtol` such that
106
+ ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
107
+ `rtol` and 0 for `atol`.
108
+ max_subdivisions : int, optional
109
+ Upper bound on the number of subdivisions to perform. Default is 10,000.
110
+ args : tuple, optional
111
+ Additional positional args passed to `f`, if any.
112
+ workers : int or map-like callable, optional
113
+ If `workers` is an integer, part of the computation is done in parallel
114
+ subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
115
+ Supply `-1` to use all cores available to the Process. Alternatively, supply a
116
+ map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
117
+ evaluating the population in parallel. This evaluation is carried out as
118
+ ``workers(func, iterable)``.
119
+ points : list of array_like, optional
120
+ List of points to avoid evaluating `f` at, under the condition that the rule
121
+ being used does not evaluate `f` on the boundary of a region (which is the
122
+ case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
123
+ a singularity at the specified point. This should be a list of array-likes where
124
+ each element has length ``ndim``. Default is empty. See Examples.
125
+
126
+ Returns
127
+ -------
128
+ res : object
129
+ Object containing the results of the estimation. It has the following
130
+ attributes:
131
+
132
+ estimate : ndarray
133
+ Estimate of the value of the integral over the overall region specified.
134
+ error : ndarray
135
+ Estimate of the error of the approximation over the overall region
136
+ specified.
137
+ status : str
138
+ Whether the estimation was successful. Can be either: "converged",
139
+ "not_converged".
140
+ subdivisions : int
141
+ Number of subdivisions performed.
142
+ atol, rtol : float
143
+ Requested tolerances for the approximation.
144
+ regions: list of object
145
+ List of objects containing the estimates of the integral over smaller
146
+ regions of the domain.
147
+
148
+ Each object in ``regions`` has the following attributes:
149
+
150
+ a, b : ndarray
151
+ Points describing the corners of the region. If the original integral
152
+ contained infinite limits or was over a region described by `region`,
153
+ then `a` and `b` are in the transformed coordinates.
154
+ estimate : ndarray
155
+ Estimate of the value of the integral over this region.
156
+ error : ndarray
157
+ Estimate of the error of the approximation over this region.
158
+
159
+ Notes
160
+ -----
161
+ The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
162
+ implementation of QUADPACK's DQAG* algorithms, implementing global error control and
163
+ adaptive subdivision.
164
+
165
+ The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
166
+ in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
167
+ cubature can be found in [2]_.
168
+
169
+ The rules currently supported via the `rule` argument are:
170
+
171
+ - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
172
+ - ``"genz-malik"``, n-node Genz-Malik
173
+
174
+ If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
175
+ corresponding Cartesian product rule will be found by taking the Cartesian product
176
+ of the nodes in the 1D case. This means that the number of nodes scales
177
+ exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
178
+ moderate number of dimensions.
179
+
180
+ Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
181
+ so in this situation using "genz-malik" might be preferable.
182
+
183
+ Infinite limits are handled with an appropriate variable transformation. Assuming
184
+ ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
185
+
186
+ If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
187
+ will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
188
+
189
+ If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
190
+ will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
191
+ :math:`t \in (0, 1)`.
192
+
193
+ If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
194
+ variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
195
+ :math:`t \in (0, 1)`.
196
+
197
+ References
198
+ ----------
199
+ .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
200
+ Integration, files: dqk21.f, dqk15.f (1983).
201
+
202
+ .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
203
+ numerical integration over an N-dimensional rectangular region, Journal of
204
+ Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
205
+ ISSN 0377-0427
206
+ :doi:`10.1016/0771-050X(80)90039-X`
207
+
208
+ Examples
209
+ --------
210
+ **1D integral with vector output**:
211
+
212
+ .. math::
213
+
214
+ \int^1_0 \mathbf f(x) \text dx
215
+
216
+ Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
217
+ specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
218
+ integration with 21 nodes.
219
+
220
+ >>> import numpy as np
221
+ >>> from scipy.integrate import cubature
222
+ >>> def f(x, n):
223
+ ... # Make sure x and n are broadcastable
224
+ ... return x[:, np.newaxis]**n[np.newaxis, :]
225
+ >>> res = cubature(
226
+ ... f,
227
+ ... a=[0],
228
+ ... b=[1],
229
+ ... args=(np.arange(10),),
230
+ ... )
231
+ >>> res.estimate
232
+ array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ,
233
+ 0.16666667, 0.14285714, 0.125 , 0.11111111, 0.1 ])
234
+
235
+ **7D integral with arbitrary-shaped array output**::
236
+
237
+ f(x) = cos(2*pi*r + alphas @ x)
238
+
239
+ for some ``r`` and ``alphas``, and the integral is performed over the unit
240
+ hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
241
+ dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
242
+ avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
243
+
244
+ >>> import numpy as np
245
+ >>> from scipy.integrate import cubature
246
+ >>> def f(x, r, alphas):
247
+ ... # f(x) = cos(2*pi*r + alphas @ x)
248
+ ... # Need to allow r and alphas to be arbitrary shape
249
+ ... npoints, ndim = x.shape[0], x.shape[-1]
250
+ ... alphas = alphas[np.newaxis, ...]
251
+ ... x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
252
+ ... return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
253
+ >>> rng = np.random.default_rng()
254
+ >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
255
+ >>> res = cubature(
256
+ ... f=f,
257
+ ... a=np.array([0, 0, 0, 0, 0, 0, 0]),
258
+ ... b=np.array([1, 1, 1, 1, 1, 1, 1]),
259
+ ... rtol=1e-5,
260
+ ... rule="genz-malik",
261
+ ... args=(r, alphas),
262
+ ... )
263
+ >>> res.estimate
264
+ array([[-0.79812452, 0.35246913, -0.52273628],
265
+ [ 0.88392779, 0.59139899, 0.41895111]])
266
+
267
+ **Parallel computation with** `workers`:
268
+
269
+ >>> from concurrent.futures import ThreadPoolExecutor
270
+ >>> with ThreadPoolExecutor() as executor:
271
+ ... res = cubature(
272
+ ... f=f,
273
+ ... a=np.array([0, 0, 0, 0, 0, 0, 0]),
274
+ ... b=np.array([1, 1, 1, 1, 1, 1, 1]),
275
+ ... rtol=1e-5,
276
+ ... rule="genz-malik",
277
+ ... args=(r, alphas),
278
+ ... workers=executor.map,
279
+ ... )
280
+ >>> res.estimate
281
+ array([[-0.79812452, 0.35246913, -0.52273628],
282
+ [ 0.88392779, 0.59139899, 0.41895111]])
283
+
284
+ **2D integral with infinite limits**:
285
+
286
+ .. math::
287
+
288
+ \int^{ \infty }_{ -\infty }
289
+ \int^{ \infty }_{ -\infty }
290
+ e^{-x^2-y^2}
291
+ \text dy
292
+ \text dx
293
+
294
+ >>> def gaussian(x):
295
+ ... return np.exp(-np.sum(x**2, axis=-1))
296
+ >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
297
+ >>> res.estimate
298
+ 3.1415926
299
+
300
+ **1D integral with singularities avoided using** `points`:
301
+
302
+ .. math::
303
+
304
+ \int^{ 1 }_{ -1 }
305
+ \frac{\sin(x)}{x}
306
+ \text dx
307
+
308
+ It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
309
+
310
+ >>> def sinc(x):
311
+ ... return np.sin(x)/x
312
+ >>> res = cubature(sinc, [-1], [1], points=[[0]])
313
+ >>> res.estimate
314
+ 1.8921661
315
+ """
316
+
317
+ # It is also possible to use a custom rule, but this is not yet part of the public
318
+ # API. An example of this can be found in the class scipy.integrate._rules.Rule.
319
+
320
+ xp = array_namespace(a, b)
321
+ max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
322
+ points = [] if points is None else points
323
+
324
+ # Convert a and b to arrays and convert each point in points to an array, promoting
325
+ # each to a common floating dtype.
326
+ a, b, *points = xp_broadcast_promote(a, b, *points, force_floating=True)
327
+ result_dtype = a.dtype
328
+
329
+ if xp_size(a) == 0 or xp_size(b) == 0:
330
+ raise ValueError("`a` and `b` must be nonempty")
331
+
332
+ if a.ndim != 1 or b.ndim != 1:
333
+ raise ValueError("`a` and `b` must be 1D arrays")
334
+
335
+ # If the rule is a string, convert to a corresponding product rule
336
+ if isinstance(rule, str):
337
+ ndim = xp_size(a)
338
+
339
+ if rule == "genz-malik":
340
+ rule = GenzMalikCubature(ndim, xp=xp)
341
+ else:
342
+ quadratues = {
343
+ "gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
344
+
345
+ # Also allow names quad_vec uses:
346
+ "gk21": GaussKronrodQuadrature(21, xp=xp),
347
+ "gk15": GaussKronrodQuadrature(15, xp=xp),
348
+ }
349
+
350
+ base_rule = quadratues.get(rule)
351
+
352
+ if base_rule is None:
353
+ raise ValueError(f"unknown rule {rule}")
354
+
355
+ rule = ProductNestedFixed([base_rule] * ndim)
356
+
357
+ # If any of limits are the wrong way around (a > b), flip them and keep track of
358
+ # the sign.
359
+ sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
360
+
361
+ a_flipped = xp.min(xp.stack([a, b]), axis=0)
362
+ b_flipped = xp.max(xp.stack([a, b]), axis=0)
363
+
364
+ a, b = a_flipped, b_flipped
365
+
366
+ # If any of the limits are infinite, apply a transformation
367
+ if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
368
+ f = _InfiniteLimitsTransform(f, a, b, xp=xp)
369
+ a, b = f.transformed_limits
370
+
371
+ # Map points from the original coordinates to the new transformed coordinates.
372
+ #
373
+ # `points` is a list of arrays of shape (ndim,), but transformations are applied
374
+ # to arrays of shape (npoints, ndim).
375
+ #
376
+ # It is not possible to combine all the points into one array and then apply
377
+ # f.inv to all of them at once since `points` needs to remain iterable.
378
+ # Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
379
+ # applied, and then each is reshaped back to (ndim,).
380
+ points = [xp.reshape(point, (1, -1)) for point in points]
381
+ points = [f.inv(point) for point in points]
382
+ points = [xp.reshape(point, (-1,)) for point in points]
383
+
384
+ # Include any problematic points introduced by the transformation
385
+ points.extend(f.points)
386
+
387
+ # If any problematic points are specified, divide the initial region so that these
388
+ # points lie on the edge of a subregion.
389
+ #
390
+ # This means ``f`` won't be evaluated there if the rule being used has no evaluation
391
+ # points on the boundary.
392
+ if len(points) == 0:
393
+ initial_regions = [(a, b)]
394
+ else:
395
+ initial_regions = _split_region_at_points(a, b, points, xp)
396
+
397
+ regions = []
398
+ est = 0.0
399
+ err = 0.0
400
+
401
+ for a_k, b_k in initial_regions:
402
+ est_k = rule.estimate(f, a_k, b_k, args)
403
+ err_k = rule.estimate_error(f, a_k, b_k, args)
404
+ regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
405
+
406
+ est += est_k
407
+ err += err_k
408
+
409
+ subdivisions = 0
410
+ success = True
411
+
412
+ with MapWrapper(workers) as mapwrapper:
413
+ while xp.any(err > atol + rtol * xp.abs(est)):
414
+ # region_k is the region with highest estimated error
415
+ region_k = heapq.heappop(regions)
416
+
417
+ est_k = region_k.estimate
418
+ err_k = region_k.error
419
+
420
+ a_k, b_k = region_k.a, region_k.b
421
+
422
+ # Subtract the estimate of the integral and its error over this region from
423
+ # the current global estimates, since these will be refined in the loop over
424
+ # all subregions.
425
+ est -= est_k
426
+ err -= err_k
427
+
428
+ # Find all 2^ndim subregions formed by splitting region_k along each axis,
429
+ # e.g. for 1D integrals this splits an estimate over an interval into an
430
+ # estimate over two subintervals, for 3D integrals this splits an estimate
431
+ # over a cube into 8 subcubes.
432
+ #
433
+ # For each of the new subregions, calculate an estimate for the integral and
434
+ # the error there, and push these regions onto the heap for potential
435
+ # further subdividing.
436
+
437
+ executor_args = zip(
438
+ itertools.repeat(f),
439
+ itertools.repeat(rule),
440
+ itertools.repeat(args),
441
+ _split_subregion(a_k, b_k, xp),
442
+ )
443
+
444
+ for subdivision_result in mapwrapper(_process_subregion, executor_args):
445
+ a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
446
+
447
+ est += est_sub
448
+ err += err_sub
449
+
450
+ new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
451
+
452
+ heapq.heappush(regions, new_region)
453
+
454
+ subdivisions += 1
455
+
456
+ if subdivisions >= max_subdivisions:
457
+ success = False
458
+ break
459
+
460
+ status = "converged" if success else "not_converged"
461
+
462
+ # Apply sign change to handle any limits which were initially flipped.
463
+ est = sign * est
464
+
465
+ return CubatureResult(
466
+ estimate=est,
467
+ error=err,
468
+ status=status,
469
+ subdivisions=subdivisions,
470
+ regions=regions,
471
+ atol=atol,
472
+ rtol=rtol,
473
+ )
474
+
475
+
476
+ def _process_subregion(data):
477
+ f, rule, args, coord = data
478
+ a_k_sub, b_k_sub = coord
479
+
480
+ est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
481
+ err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
482
+
483
+ return a_k_sub, b_k_sub, est_sub, err_sub
484
+
485
+
486
+ def _is_strictly_in_region(a, b, point, xp):
487
+ if xp.all(point == a) or xp.all(point == b):
488
+ return False
489
+
490
+ return xp.all(a <= point) and xp.all(point <= b)
491
+
492
+
493
+ def _split_region_at_points(a, b, points, xp):
494
+ """
495
+ Given the integration limits `a` and `b` describing a rectangular region and a list
496
+ of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
497
+ initial region into smaller subregion such that no `points` lie strictly inside
498
+ any of the subregions.
499
+ """
500
+
501
+ regions = [(a, b)]
502
+
503
+ for point in points:
504
+ if xp.any(xp.isinf(point)):
505
+ # If a point is specified at infinity, ignore.
506
+ #
507
+ # This case occurs when points are given by the user to avoid, but after
508
+ # applying a transformation, they are removed.
509
+ continue
510
+
511
+ new_subregions = []
512
+
513
+ for a_k, b_k in regions:
514
+ if _is_strictly_in_region(a_k, b_k, point, xp):
515
+ subregions = _split_subregion(a_k, b_k, xp, point)
516
+
517
+ for left, right in subregions:
518
+ # Skip any zero-width regions.
519
+ if xp.any(left == right):
520
+ continue
521
+ else:
522
+ new_subregions.append((left, right))
523
+
524
+ new_subregions.extend(subregions)
525
+
526
+ else:
527
+ new_subregions.append((a_k, b_k))
528
+
529
+ regions = new_subregions
530
+
531
+ return regions
532
+
533
+
534
+ class _VariableTransform:
535
+ """
536
+ A transformation that can be applied to an integral.
537
+ """
538
+
539
+ @property
540
+ def transformed_limits(self):
541
+ """
542
+ New limits of integration after applying the transformation.
543
+ """
544
+
545
+ raise NotImplementedError
546
+
547
+ @property
548
+ def points(self):
549
+ """
550
+ Any problematic points introduced by the transformation.
551
+
552
+ These should be specified as points where ``_VariableTransform(f)(self, point)``
553
+ would be problematic.
554
+
555
+ For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
556
+ univariate integral, then points should return ``[ [1], [-1] ]``.
557
+ """
558
+
559
+ return []
560
+
561
+ def inv(self, x):
562
+ """
563
+ Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
564
+ is the function after the transformation is applied, then::
565
+
566
+ f(x) = g(self.inv(x))
567
+ """
568
+
569
+ raise NotImplementedError
570
+
571
+ def __call__(self, t, *args, **kwargs):
572
+ """
573
+ Apply the transformation to ``f`` and multiply by the Jacobian determinant.
574
+ This should be the new integrand after the transformation has been applied so
575
+ that the following is satisfied::
576
+
577
+ f_transformed = _VariableTransform(f)
578
+
579
+ cubature(f, a, b) == cubature(
580
+ f_transformed,
581
+ *f_transformed.transformed_limits(a, b),
582
+ )
583
+ """
584
+
585
+ raise NotImplementedError
586
+
587
+
588
+ class _InfiniteLimitsTransform(_VariableTransform):
589
+ r"""
590
+ Transformation for handling infinite limits.
591
+
592
+ Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
593
+
594
+ If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
595
+ will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
596
+
597
+ If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
598
+ will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
599
+ :math:`t \in (0, 1)`.
600
+
601
+ If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
602
+ variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
603
+ :math:`t \in (0, 1)`.
604
+ """
605
+
606
+ def __init__(self, f, a, b, xp):
607
+ self._xp = xp
608
+
609
+ self._f = f
610
+ self._orig_a = a
611
+ self._orig_b = b
612
+
613
+ # (-oo, oo) will be mapped to (-1, 1).
614
+ self._double_inf_pos = (a == -math.inf) & (b == math.inf)
615
+
616
+ # (start, oo) will be mapped to (0, 1).
617
+ start_inf_mask = (a != -math.inf) & (b == math.inf)
618
+
619
+ # (-oo, end) will be mapped to (0, 1).
620
+ inf_end_mask = (a == -math.inf) & (b != math.inf)
621
+
622
+ # This is handled by making the transformation t = -x and reducing it to
623
+ # the other semi-infinite case.
624
+ self._semi_inf_pos = start_inf_mask | inf_end_mask
625
+
626
+ # Since we flip the limits, we don't need to separately multiply the
627
+ # integrand by -1.
628
+ self._orig_a[inf_end_mask] = -b[inf_end_mask]
629
+ self._orig_b[inf_end_mask] = -a[inf_end_mask]
630
+
631
+ self._num_inf = self._xp.sum(
632
+ self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
633
+ ).__int__()
634
+
635
+ @property
636
+ def transformed_limits(self):
637
+ a = xp_copy(self._orig_a)
638
+ b = xp_copy(self._orig_b)
639
+
640
+ a[self._double_inf_pos] = -1
641
+ b[self._double_inf_pos] = 1
642
+
643
+ a[self._semi_inf_pos] = 0
644
+ b[self._semi_inf_pos] = 1
645
+
646
+ return a, b
647
+
648
+ @property
649
+ def points(self):
650
+ # If there are infinite limits, then the origin becomes a problematic point
651
+ # due to a division by zero there.
652
+
653
+ # If the function using this class only wraps f when a and b contain infinite
654
+ # limits, this condition will always be met (as is the case with cubature).
655
+ #
656
+ # If a and b do not contain infinite limits but f is still wrapped with this
657
+ # class, then without this condition the initial region of integration will
658
+ # be split around the origin unnecessarily.
659
+ if self._num_inf != 0:
660
+ return [self._xp.zeros(self._orig_a.shape)]
661
+ else:
662
+ return []
663
+
664
+ def inv(self, x):
665
+ t = xp_copy(x)
666
+ npoints = x.shape[0]
667
+
668
+ double_inf_mask = self._xp.tile(
669
+ self._double_inf_pos[self._xp.newaxis, :],
670
+ (npoints, 1),
671
+ )
672
+
673
+ semi_inf_mask = self._xp.tile(
674
+ self._semi_inf_pos[self._xp.newaxis, :],
675
+ (npoints, 1),
676
+ )
677
+
678
+ # If any components of x are 0, then this component will be mapped to infinity
679
+ # under the transformation used for doubly-infinite limits.
680
+ #
681
+ # Handle the zero values and non-zero values separately to avoid division by
682
+ # zero.
683
+ zero_mask = x[double_inf_mask] == 0
684
+ non_zero_mask = double_inf_mask & ~zero_mask
685
+ t[zero_mask] = math.inf
686
+ t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
687
+
688
+ start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
689
+ t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
690
+
691
+ return t
692
+
693
+ def __call__(self, t, *args, **kwargs):
694
+ x = xp_copy(t)
695
+ npoints = t.shape[0]
696
+
697
+ double_inf_mask = self._xp.tile(
698
+ self._double_inf_pos[self._xp.newaxis, :],
699
+ (npoints, 1),
700
+ )
701
+
702
+ semi_inf_mask = self._xp.tile(
703
+ self._semi_inf_pos[self._xp.newaxis, :],
704
+ (npoints, 1),
705
+ )
706
+
707
+ # For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
708
+ x[double_inf_mask] = (
709
+ (1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
710
+ )
711
+
712
+ start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
713
+
714
+ # For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
715
+ x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
716
+
717
+ jacobian_det = 1/self._xp.prod(
718
+ self._xp.reshape(
719
+ t[semi_inf_mask | double_inf_mask]**2,
720
+ (-1, self._num_inf),
721
+ ),
722
+ axis=-1,
723
+ )
724
+
725
+ f_x = self._f(x, *args, **kwargs)
726
+ jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
727
+
728
+ return f_x * jacobian_det
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """Suite of ODE solvers implemented in Python."""
2
+ from .ivp import solve_ivp
3
+ from .rk import RK23, RK45, DOP853
4
+ from .radau import Radau
5
+ from .bdf import BDF
6
+ from .lsoda import LSODA
7
+ from .common import OdeSolution
8
+ from .base import DenseOutput, OdeSolver
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def check_arguments(fun, y0, support_complex):
5
+ """Helper function for checking arguments common to all solvers."""
6
+ y0 = np.asarray(y0)
7
+ if np.issubdtype(y0.dtype, np.complexfloating):
8
+ if not support_complex:
9
+ raise ValueError("`y0` is complex, but the chosen solver does "
10
+ "not support integration in a complex domain.")
11
+ dtype = complex
12
+ else:
13
+ dtype = float
14
+ y0 = y0.astype(dtype, copy=False)
15
+
16
+ if y0.ndim != 1:
17
+ raise ValueError("`y0` must be 1-dimensional.")
18
+
19
+ if not np.isfinite(y0).all():
20
+ raise ValueError("All components of the initial state `y0` must be finite.")
21
+
22
+ def fun_wrapped(t, y):
23
+ return np.asarray(fun(t, y), dtype=dtype)
24
+
25
+ return fun_wrapped, y0
26
+
27
+
28
+ class OdeSolver:
29
+ """Base class for ODE solvers.
30
+
31
+ In order to implement a new solver you need to follow the guidelines:
32
+
33
+ 1. A constructor must accept parameters presented in the base class
34
+ (listed below) along with any other parameters specific to a solver.
35
+ 2. A constructor must accept arbitrary extraneous arguments
36
+ ``**extraneous``, but warn that these arguments are irrelevant
37
+ using `common.warn_extraneous` function. Do not pass these
38
+ arguments to the base class.
39
+ 3. A solver must implement a private method `_step_impl(self)` which
40
+ propagates a solver one step further. It must return tuple
41
+ ``(success, message)``, where ``success`` is a boolean indicating
42
+ whether a step was successful, and ``message`` is a string
43
+ containing description of a failure if a step failed or None
44
+ otherwise.
45
+ 4. A solver must implement a private method `_dense_output_impl(self)`,
46
+ which returns a `DenseOutput` object covering the last successful
47
+ step.
48
+ 5. A solver must have attributes listed below in Attributes section.
49
+ Note that ``t_old`` and ``step_size`` are updated automatically.
50
+ 6. Use `fun(self, t, y)` method for the system rhs evaluation, this
51
+ way the number of function evaluations (`nfev`) will be tracked
52
+ automatically.
53
+ 7. For convenience, a base class provides `fun_single(self, t, y)` and
54
+ `fun_vectorized(self, t, y)` for evaluating the rhs in
55
+ non-vectorized and vectorized fashions respectively (regardless of
56
+ how `fun` from the constructor is implemented). These calls don't
57
+ increment `nfev`.
58
+ 8. If a solver uses a Jacobian matrix and LU decompositions, it should
59
+ track the number of Jacobian evaluations (`njev`) and the number of
60
+ LU decompositions (`nlu`).
61
+ 9. By convention, the function evaluations used to compute a finite
62
+ difference approximation of the Jacobian should not be counted in
63
+ `nfev`, thus use `fun_single(self, t, y)` or
64
+ `fun_vectorized(self, t, y)` when computing a finite difference
65
+ approximation of the Jacobian.
66
+
67
+ Parameters
68
+ ----------
69
+ fun : callable
70
+ Right-hand side of the system: the time derivative of the state ``y``
71
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
72
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
73
+ return an array of the same shape as ``y``. See `vectorized` for more
74
+ information.
75
+ t0 : float
76
+ Initial time.
77
+ y0 : array_like, shape (n,)
78
+ Initial state.
79
+ t_bound : float
80
+ Boundary time --- the integration won't continue beyond it. It also
81
+ determines the direction of the integration.
82
+ vectorized : bool
83
+ Whether `fun` can be called in a vectorized fashion. Default is False.
84
+
85
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
86
+ shape ``(n,)``, where ``n = len(y0)``.
87
+
88
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
89
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
90
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
91
+ the returned array is the time derivative of the state corresponding
92
+ with a column of ``y``).
93
+
94
+ Setting ``vectorized=True`` allows for faster finite difference
95
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
96
+ will result in slower execution for other methods. It can also
97
+ result in slower overall execution for 'Radau' and 'BDF' in some
98
+ circumstances (e.g. small ``len(y0)``).
99
+ support_complex : bool, optional
100
+ Whether integration in a complex domain should be supported.
101
+ Generally determined by a derived solver class capabilities.
102
+ Default is False.
103
+
104
+ Attributes
105
+ ----------
106
+ n : int
107
+ Number of equations.
108
+ status : string
109
+ Current status of the solver: 'running', 'finished' or 'failed'.
110
+ t_bound : float
111
+ Boundary time.
112
+ direction : float
113
+ Integration direction: +1 or -1.
114
+ t : float
115
+ Current time.
116
+ y : ndarray
117
+ Current state.
118
+ t_old : float
119
+ Previous time. None if no steps were made yet.
120
+ step_size : float
121
+ Size of the last successful step. None if no steps were made yet.
122
+ nfev : int
123
+ Number of the system's rhs evaluations.
124
+ njev : int
125
+ Number of the Jacobian evaluations.
126
+ nlu : int
127
+ Number of LU decompositions.
128
+ """
129
+ TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
130
+
131
+ def __init__(self, fun, t0, y0, t_bound, vectorized,
132
+ support_complex=False):
133
+ self.t_old = None
134
+ self.t = t0
135
+ self._fun, self.y = check_arguments(fun, y0, support_complex)
136
+ self.t_bound = t_bound
137
+ self.vectorized = vectorized
138
+
139
+ if vectorized:
140
+ def fun_single(t, y):
141
+ return self._fun(t, y[:, None]).ravel()
142
+ fun_vectorized = self._fun
143
+ else:
144
+ fun_single = self._fun
145
+
146
+ def fun_vectorized(t, y):
147
+ f = np.empty_like(y)
148
+ for i, yi in enumerate(y.T):
149
+ f[:, i] = self._fun(t, yi)
150
+ return f
151
+
152
+ def fun(t, y):
153
+ self.nfev += 1
154
+ return self.fun_single(t, y)
155
+
156
+ self.fun = fun
157
+ self.fun_single = fun_single
158
+ self.fun_vectorized = fun_vectorized
159
+
160
+ self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
161
+ self.n = self.y.size
162
+ self.status = 'running'
163
+
164
+ self.nfev = 0
165
+ self.njev = 0
166
+ self.nlu = 0
167
+
168
+ @property
169
+ def step_size(self):
170
+ if self.t_old is None:
171
+ return None
172
+ else:
173
+ return np.abs(self.t - self.t_old)
174
+
175
+ def step(self):
176
+ """Perform one integration step.
177
+
178
+ Returns
179
+ -------
180
+ message : string or None
181
+ Report from the solver. Typically a reason for a failure if
182
+ `self.status` is 'failed' after the step was taken or None
183
+ otherwise.
184
+ """
185
+ if self.status != 'running':
186
+ raise RuntimeError("Attempt to step on a failed or finished "
187
+ "solver.")
188
+
189
+ if self.n == 0 or self.t == self.t_bound:
190
+ # Handle corner cases of empty solver or no integration.
191
+ self.t_old = self.t
192
+ self.t = self.t_bound
193
+ message = None
194
+ self.status = 'finished'
195
+ else:
196
+ t = self.t
197
+ success, message = self._step_impl()
198
+
199
+ if not success:
200
+ self.status = 'failed'
201
+ else:
202
+ self.t_old = t
203
+ if self.direction * (self.t - self.t_bound) >= 0:
204
+ self.status = 'finished'
205
+
206
+ return message
207
+
208
+ def dense_output(self):
209
+ """Compute a local interpolant over the last successful step.
210
+
211
+ Returns
212
+ -------
213
+ sol : `DenseOutput`
214
+ Local interpolant over the last successful step.
215
+ """
216
+ if self.t_old is None:
217
+ raise RuntimeError("Dense output is available after a successful "
218
+ "step was made.")
219
+
220
+ if self.n == 0 or self.t == self.t_old:
221
+ # Handle corner cases of empty solver and no integration.
222
+ return ConstantDenseOutput(self.t_old, self.t, self.y)
223
+ else:
224
+ return self._dense_output_impl()
225
+
226
+ def _step_impl(self):
227
+ raise NotImplementedError
228
+
229
+ def _dense_output_impl(self):
230
+ raise NotImplementedError
231
+
232
+
233
+ class DenseOutput:
234
+ """Base class for local interpolant over step made by an ODE solver.
235
+
236
+ It interpolates between `t_min` and `t_max` (see Attributes below).
237
+ Evaluation outside this interval is not forbidden, but the accuracy is not
238
+ guaranteed.
239
+
240
+ Attributes
241
+ ----------
242
+ t_min, t_max : float
243
+ Time range of the interpolation.
244
+ """
245
+ def __init__(self, t_old, t):
246
+ self.t_old = t_old
247
+ self.t = t
248
+ self.t_min = min(t, t_old)
249
+ self.t_max = max(t, t_old)
250
+
251
+ def __call__(self, t):
252
+ """Evaluate the interpolant.
253
+
254
+ Parameters
255
+ ----------
256
+ t : float or array_like with shape (n_points,)
257
+ Points to evaluate the solution at.
258
+
259
+ Returns
260
+ -------
261
+ y : ndarray, shape (n,) or (n, n_points)
262
+ Computed values. Shape depends on whether `t` was a scalar or a
263
+ 1-D array.
264
+ """
265
+ t = np.asarray(t)
266
+ if t.ndim > 1:
267
+ raise ValueError("`t` must be a float or a 1-D array.")
268
+ return self._call_impl(t)
269
+
270
+ def _call_impl(self, t):
271
+ raise NotImplementedError
272
+
273
+
274
+ class ConstantDenseOutput(DenseOutput):
275
+ """Constant value interpolator.
276
+
277
+ This class used for degenerate integration cases: equal integration limits
278
+ or a system with 0 equations.
279
+ """
280
+ def __init__(self, t_old, t, value):
281
+ super().__init__(t_old, t)
282
+ self.value = value
283
+
284
+ def _call_impl(self, t):
285
+ if t.ndim == 0:
286
+ return self.value
287
+ else:
288
+ ret = np.empty((self.value.shape[0], t.shape[0]))
289
+ ret[:] = self.value[:, None]
290
+ return ret
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import lu_factor, lu_solve
3
+ from scipy.sparse import issparse, csc_matrix, eye
4
+ from scipy.sparse.linalg import splu
5
+ from scipy.optimize._numdiff import group_columns
6
+ from .common import (validate_max_step, validate_tol, select_initial_step,
7
+ norm, EPS, num_jac, validate_first_step,
8
+ warn_extraneous)
9
+ from .base import OdeSolver, DenseOutput
10
+
11
+
12
+ MAX_ORDER = 5
13
+ NEWTON_MAXITER = 4
14
+ MIN_FACTOR = 0.2
15
+ MAX_FACTOR = 10
16
+
17
+
18
+ def compute_R(order, factor):
19
+ """Compute the matrix for changing the differences array."""
20
+ I = np.arange(1, order + 1)[:, None]
21
+ J = np.arange(1, order + 1)
22
+ M = np.zeros((order + 1, order + 1))
23
+ M[1:, 1:] = (I - 1 - factor * J) / I
24
+ M[0] = 1
25
+ return np.cumprod(M, axis=0)
26
+
27
+
28
+ def change_D(D, order, factor):
29
+ """Change differences array in-place when step size is changed."""
30
+ R = compute_R(order, factor)
31
+ U = compute_R(order, 1)
32
+ RU = R.dot(U)
33
+ D[:order + 1] = np.dot(RU.T, D[:order + 1])
34
+
35
+
36
+ def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol):
37
+ """Solve the algebraic system resulting from BDF method."""
38
+ d = 0
39
+ y = y_predict.copy()
40
+ dy_norm_old = None
41
+ converged = False
42
+ for k in range(NEWTON_MAXITER):
43
+ f = fun(t_new, y)
44
+ if not np.all(np.isfinite(f)):
45
+ break
46
+
47
+ dy = solve_lu(LU, c * f - psi - d)
48
+ dy_norm = norm(dy / scale)
49
+
50
+ if dy_norm_old is None:
51
+ rate = None
52
+ else:
53
+ rate = dy_norm / dy_norm_old
54
+
55
+ if (rate is not None and (rate >= 1 or
56
+ rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)):
57
+ break
58
+
59
+ y += dy
60
+ d += dy
61
+
62
+ if (dy_norm == 0 or
63
+ rate is not None and rate / (1 - rate) * dy_norm < tol):
64
+ converged = True
65
+ break
66
+
67
+ dy_norm_old = dy_norm
68
+
69
+ return converged, k + 1, y, d
70
+
71
+
72
+ class BDF(OdeSolver):
73
+ """Implicit method based on backward-differentiation formulas.
74
+
75
+ This is a variable order method with the order varying automatically from
76
+ 1 to 5. The general framework of the BDF algorithm is described in [1]_.
77
+ This class implements a quasi-constant step size as explained in [2]_.
78
+ The error estimation strategy for the constant-step BDF is derived in [3]_.
79
+ An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.
80
+
81
+ Can be applied in the complex domain.
82
+
83
+ Parameters
84
+ ----------
85
+ fun : callable
86
+ Right-hand side of the system: the time derivative of the state ``y``
87
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
88
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
89
+ return an array of the same shape as ``y``. See `vectorized` for more
90
+ information.
91
+ t0 : float
92
+ Initial time.
93
+ y0 : array_like, shape (n,)
94
+ Initial state.
95
+ t_bound : float
96
+ Boundary time - the integration won't continue beyond it. It also
97
+ determines the direction of the integration.
98
+ first_step : float or None, optional
99
+ Initial step size. Default is ``None`` which means that the algorithm
100
+ should choose.
101
+ max_step : float, optional
102
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
103
+ bounded and determined solely by the solver.
104
+ rtol, atol : float and array_like, optional
105
+ Relative and absolute tolerances. The solver keeps the local error
106
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
107
+ relative accuracy (number of correct digits), while `atol` controls
108
+ absolute accuracy (number of correct decimal places). To achieve the
109
+ desired `rtol`, set `atol` to be smaller than the smallest value that
110
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
111
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
112
+ number of correct digits is not guaranteed. Conversely, to achieve the
113
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
114
+ than `atol`. If components of y have different scales, it might be
115
+ beneficial to set different `atol` values for different components by
116
+ passing array_like with shape (n,) for `atol`. Default values are
117
+ 1e-3 for `rtol` and 1e-6 for `atol`.
118
+ jac : {None, array_like, sparse_matrix, callable}, optional
119
+ Jacobian matrix of the right-hand side of the system with respect to y,
120
+ required by this method. The Jacobian matrix has shape (n, n) and its
121
+ element (i, j) is equal to ``d f_i / d y_j``.
122
+ There are three ways to define the Jacobian:
123
+
124
+ * If array_like or sparse_matrix, the Jacobian is assumed to
125
+ be constant.
126
+ * If callable, the Jacobian is assumed to depend on both
127
+ t and y; it will be called as ``jac(t, y)`` as necessary.
128
+ For the 'Radau' and 'BDF' methods, the return value might be a
129
+ sparse matrix.
130
+ * If None (default), the Jacobian will be approximated by
131
+ finite differences.
132
+
133
+ It is generally recommended to provide the Jacobian rather than
134
+ relying on a finite-difference approximation.
135
+ jac_sparsity : {None, array_like, sparse matrix}, optional
136
+ Defines a sparsity structure of the Jacobian matrix for a
137
+ finite-difference approximation. Its shape must be (n, n). This argument
138
+ is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
139
+ elements in *each* row, providing the sparsity structure will greatly
140
+ speed up the computations [4]_. A zero entry means that a corresponding
141
+ element in the Jacobian is always zero. If None (default), the Jacobian
142
+ is assumed to be dense.
143
+ vectorized : bool, optional
144
+ Whether `fun` can be called in a vectorized fashion. Default is False.
145
+
146
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
147
+ shape ``(n,)``, where ``n = len(y0)``.
148
+
149
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
150
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
151
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
152
+ the returned array is the time derivative of the state corresponding
153
+ with a column of ``y``).
154
+
155
+ Setting ``vectorized=True`` allows for faster finite difference
156
+ approximation of the Jacobian by this method, but may result in slower
157
+ execution overall in some circumstances (e.g. small ``len(y0)``).
158
+
159
+ Attributes
160
+ ----------
161
+ n : int
162
+ Number of equations.
163
+ status : string
164
+ Current status of the solver: 'running', 'finished' or 'failed'.
165
+ t_bound : float
166
+ Boundary time.
167
+ direction : float
168
+ Integration direction: +1 or -1.
169
+ t : float
170
+ Current time.
171
+ y : ndarray
172
+ Current state.
173
+ t_old : float
174
+ Previous time. None if no steps were made yet.
175
+ step_size : float
176
+ Size of the last successful step. None if no steps were made yet.
177
+ nfev : int
178
+ Number of evaluations of the right-hand side.
179
+ njev : int
180
+ Number of evaluations of the Jacobian.
181
+ nlu : int
182
+ Number of LU decompositions.
183
+
184
+ References
185
+ ----------
186
+ .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
187
+ Solution of Ordinary Differential Equations", ACM Transactions on
188
+ Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
189
+ .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
190
+ COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
191
+ .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
192
+ Nonstiff Problems", Sec. III.2.
193
+ .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
194
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
195
+ and its Applications, 13, pp. 117-120, 1974.
196
+ """
197
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
198
+ rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
199
+ vectorized=False, first_step=None, **extraneous):
200
+ warn_extraneous(extraneous)
201
+ super().__init__(fun, t0, y0, t_bound, vectorized,
202
+ support_complex=True)
203
+ self.max_step = validate_max_step(max_step)
204
+ self.rtol, self.atol = validate_tol(rtol, atol, self.n)
205
+ f = self.fun(self.t, self.y)
206
+ if first_step is None:
207
+ self.h_abs = select_initial_step(self.fun, self.t, self.y,
208
+ t_bound, max_step, f,
209
+ self.direction, 1,
210
+ self.rtol, self.atol)
211
+ else:
212
+ self.h_abs = validate_first_step(first_step, t0, t_bound)
213
+ self.h_abs_old = None
214
+ self.error_norm_old = None
215
+
216
+ self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
217
+
218
+ self.jac_factor = None
219
+ self.jac, self.J = self._validate_jac(jac, jac_sparsity)
220
+ if issparse(self.J):
221
+ def lu(A):
222
+ self.nlu += 1
223
+ return splu(A)
224
+
225
+ def solve_lu(LU, b):
226
+ return LU.solve(b)
227
+
228
+ I = eye(self.n, format='csc', dtype=self.y.dtype)
229
+ else:
230
+ def lu(A):
231
+ self.nlu += 1
232
+ return lu_factor(A, overwrite_a=True)
233
+
234
+ def solve_lu(LU, b):
235
+ return lu_solve(LU, b, overwrite_b=True)
236
+
237
+ I = np.identity(self.n, dtype=self.y.dtype)
238
+
239
+ self.lu = lu
240
+ self.solve_lu = solve_lu
241
+ self.I = I
242
+
243
+ kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
244
+ self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
245
+ self.alpha = (1 - kappa) * self.gamma
246
+ self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
247
+
248
+ D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
249
+ D[0] = self.y
250
+ D[1] = f * self.h_abs * self.direction
251
+ self.D = D
252
+
253
+ self.order = 1
254
+ self.n_equal_steps = 0
255
+ self.LU = None
256
+
257
+ def _validate_jac(self, jac, sparsity):
258
+ t0 = self.t
259
+ y0 = self.y
260
+
261
+ if jac is None:
262
+ if sparsity is not None:
263
+ if issparse(sparsity):
264
+ sparsity = csc_matrix(sparsity)
265
+ groups = group_columns(sparsity)
266
+ sparsity = (sparsity, groups)
267
+
268
+ def jac_wrapped(t, y):
269
+ self.njev += 1
270
+ f = self.fun_single(t, y)
271
+ J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
272
+ self.atol, self.jac_factor,
273
+ sparsity)
274
+ return J
275
+ J = jac_wrapped(t0, y0)
276
+ elif callable(jac):
277
+ J = jac(t0, y0)
278
+ self.njev += 1
279
+ if issparse(J):
280
+ J = csc_matrix(J, dtype=y0.dtype)
281
+
282
+ def jac_wrapped(t, y):
283
+ self.njev += 1
284
+ return csc_matrix(jac(t, y), dtype=y0.dtype)
285
+ else:
286
+ J = np.asarray(J, dtype=y0.dtype)
287
+
288
+ def jac_wrapped(t, y):
289
+ self.njev += 1
290
+ return np.asarray(jac(t, y), dtype=y0.dtype)
291
+
292
+ if J.shape != (self.n, self.n):
293
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
294
+ f" but actually has {J.shape}.")
295
+ else:
296
+ if issparse(jac):
297
+ J = csc_matrix(jac, dtype=y0.dtype)
298
+ else:
299
+ J = np.asarray(jac, dtype=y0.dtype)
300
+
301
+ if J.shape != (self.n, self.n):
302
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
303
+ f" but actually has {J.shape}.")
304
+ jac_wrapped = None
305
+
306
+ return jac_wrapped, J
307
+
308
+ def _step_impl(self):
309
+ t = self.t
310
+ D = self.D
311
+
312
+ max_step = self.max_step
313
+ min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
314
+ if self.h_abs > max_step:
315
+ h_abs = max_step
316
+ change_D(D, self.order, max_step / self.h_abs)
317
+ self.n_equal_steps = 0
318
+ elif self.h_abs < min_step:
319
+ h_abs = min_step
320
+ change_D(D, self.order, min_step / self.h_abs)
321
+ self.n_equal_steps = 0
322
+ else:
323
+ h_abs = self.h_abs
324
+
325
+ atol = self.atol
326
+ rtol = self.rtol
327
+ order = self.order
328
+
329
+ alpha = self.alpha
330
+ gamma = self.gamma
331
+ error_const = self.error_const
332
+
333
+ J = self.J
334
+ LU = self.LU
335
+ current_jac = self.jac is None
336
+
337
+ step_accepted = False
338
+ while not step_accepted:
339
+ if h_abs < min_step:
340
+ return False, self.TOO_SMALL_STEP
341
+
342
+ h = h_abs * self.direction
343
+ t_new = t + h
344
+
345
+ if self.direction * (t_new - self.t_bound) > 0:
346
+ t_new = self.t_bound
347
+ change_D(D, order, np.abs(t_new - t) / h_abs)
348
+ self.n_equal_steps = 0
349
+ LU = None
350
+
351
+ h = t_new - t
352
+ h_abs = np.abs(h)
353
+
354
+ y_predict = np.sum(D[:order + 1], axis=0)
355
+
356
+ scale = atol + rtol * np.abs(y_predict)
357
+ psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order]
358
+
359
+ converged = False
360
+ c = h / alpha[order]
361
+ while not converged:
362
+ if LU is None:
363
+ LU = self.lu(self.I - c * J)
364
+
365
+ converged, n_iter, y_new, d = solve_bdf_system(
366
+ self.fun, t_new, y_predict, c, psi, LU, self.solve_lu,
367
+ scale, self.newton_tol)
368
+
369
+ if not converged:
370
+ if current_jac:
371
+ break
372
+ J = self.jac(t_new, y_predict)
373
+ LU = None
374
+ current_jac = True
375
+
376
+ if not converged:
377
+ factor = 0.5
378
+ h_abs *= factor
379
+ change_D(D, order, factor)
380
+ self.n_equal_steps = 0
381
+ LU = None
382
+ continue
383
+
384
+ safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
385
+ + n_iter)
386
+
387
+ scale = atol + rtol * np.abs(y_new)
388
+ error = error_const[order] * d
389
+ error_norm = norm(error / scale)
390
+
391
+ if error_norm > 1:
392
+ factor = max(MIN_FACTOR,
393
+ safety * error_norm ** (-1 / (order + 1)))
394
+ h_abs *= factor
395
+ change_D(D, order, factor)
396
+ self.n_equal_steps = 0
397
+ # As we didn't have problems with convergence, we don't
398
+ # reset LU here.
399
+ else:
400
+ step_accepted = True
401
+
402
+ self.n_equal_steps += 1
403
+
404
+ self.t = t_new
405
+ self.y = y_new
406
+
407
+ self.h_abs = h_abs
408
+ self.J = J
409
+ self.LU = LU
410
+
411
+ # Update differences. The principal relation here is
412
+ # D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D
413
+ # contained difference for previous interpolating polynomial and
414
+ # d = D^{k + 1} y_n. Thus this elegant code follows.
415
+ D[order + 2] = d - D[order + 1]
416
+ D[order + 1] = d
417
+ for i in reversed(range(order + 1)):
418
+ D[i] += D[i + 1]
419
+
420
+ if self.n_equal_steps < order + 1:
421
+ return True, None
422
+
423
+ if order > 1:
424
+ error_m = error_const[order - 1] * D[order]
425
+ error_m_norm = norm(error_m / scale)
426
+ else:
427
+ error_m_norm = np.inf
428
+
429
+ if order < MAX_ORDER:
430
+ error_p = error_const[order + 1] * D[order + 2]
431
+ error_p_norm = norm(error_p / scale)
432
+ else:
433
+ error_p_norm = np.inf
434
+
435
+ error_norms = np.array([error_m_norm, error_norm, error_p_norm])
436
+ with np.errstate(divide='ignore'):
437
+ factors = error_norms ** (-1 / np.arange(order, order + 3))
438
+
439
+ delta_order = np.argmax(factors) - 1
440
+ order += delta_order
441
+ self.order = order
442
+
443
+ factor = min(MAX_FACTOR, safety * np.max(factors))
444
+ self.h_abs *= factor
445
+ change_D(D, order, factor)
446
+ self.n_equal_steps = 0
447
+ self.LU = None
448
+
449
+ return True, None
450
+
451
+ def _dense_output_impl(self):
452
+ return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction,
453
+ self.order, self.D[:self.order + 1].copy())
454
+
455
+
456
+ class BdfDenseOutput(DenseOutput):
457
+ def __init__(self, t_old, t, h, order, D):
458
+ super().__init__(t_old, t)
459
+ self.order = order
460
+ self.t_shift = self.t - h * np.arange(self.order)
461
+ self.denom = h * (1 + np.arange(self.order))
462
+ self.D = D
463
+
464
+ def _call_impl(self, t):
465
+ if t.ndim == 0:
466
+ x = (t - self.t_shift) / self.denom
467
+ p = np.cumprod(x)
468
+ else:
469
+ x = (t - self.t_shift[:, None]) / self.denom[:, None]
470
+ p = np.cumprod(x, axis=0)
471
+
472
+ y = np.dot(self.D[1:].T, p)
473
+ if y.ndim == 1:
474
+ y += self.D[0]
475
+ else:
476
+ y += self.D[0, :, None]
477
+
478
+ return y
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import groupby
2
+ from warnings import warn
3
+ import numpy as np
4
+ from scipy.sparse import find, coo_matrix
5
+
6
+
7
+ EPS = np.finfo(float).eps
8
+
9
+
10
+ def validate_first_step(first_step, t0, t_bound):
11
+ """Assert that first_step is valid and return it."""
12
+ if first_step <= 0:
13
+ raise ValueError("`first_step` must be positive.")
14
+ if first_step > np.abs(t_bound - t0):
15
+ raise ValueError("`first_step` exceeds bounds.")
16
+ return first_step
17
+
18
+
19
+ def validate_max_step(max_step):
20
+ """Assert that max_Step is valid and return it."""
21
+ if max_step <= 0:
22
+ raise ValueError("`max_step` must be positive.")
23
+ return max_step
24
+
25
+
26
+ def warn_extraneous(extraneous):
27
+ """Display a warning for extraneous keyword arguments.
28
+
29
+ The initializer of each solver class is expected to collect keyword
30
+ arguments that it doesn't understand and warn about them. This function
31
+ prints a warning for each key in the supplied dictionary.
32
+
33
+ Parameters
34
+ ----------
35
+ extraneous : dict
36
+ Extraneous keyword arguments
37
+ """
38
+ if extraneous:
39
+ warn("The following arguments have no effect for a chosen solver: "
40
+ f"{', '.join(f'`{x}`' for x in extraneous)}.",
41
+ stacklevel=3)
42
+
43
+
44
+ def validate_tol(rtol, atol, n):
45
+ """Validate tolerance values."""
46
+
47
+ if np.any(rtol < 100 * EPS):
48
+ warn("At least one element of `rtol` is too small. "
49
+ f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.",
50
+ stacklevel=3)
51
+ rtol = np.maximum(rtol, 100 * EPS)
52
+
53
+ atol = np.asarray(atol)
54
+ if atol.ndim > 0 and atol.shape != (n,):
55
+ raise ValueError("`atol` has wrong shape.")
56
+
57
+ if np.any(atol < 0):
58
+ raise ValueError("`atol` must be positive.")
59
+
60
+ return rtol, atol
61
+
62
+
63
+ def norm(x):
64
+ """Compute RMS norm."""
65
+ return np.linalg.norm(x) / x.size ** 0.5
66
+
67
+
68
+ def select_initial_step(fun, t0, y0, t_bound,
69
+ max_step, f0, direction, order, rtol, atol):
70
+ """Empirically select a good initial step.
71
+
72
+ The algorithm is described in [1]_.
73
+
74
+ Parameters
75
+ ----------
76
+ fun : callable
77
+ Right-hand side of the system.
78
+ t0 : float
79
+ Initial value of the independent variable.
80
+ y0 : ndarray, shape (n,)
81
+ Initial value of the dependent variable.
82
+ t_bound : float
83
+ End-point of integration interval; used to ensure that t0+step<=tbound
84
+ and that fun is only evaluated in the interval [t0,tbound]
85
+ max_step : float
86
+ Maximum allowable step size.
87
+ f0 : ndarray, shape (n,)
88
+ Initial value of the derivative, i.e., ``fun(t0, y0)``.
89
+ direction : float
90
+ Integration direction.
91
+ order : float
92
+ Error estimator order. It means that the error controlled by the
93
+ algorithm is proportional to ``step_size ** (order + 1)`.
94
+ rtol : float
95
+ Desired relative tolerance.
96
+ atol : float
97
+ Desired absolute tolerance.
98
+
99
+ Returns
100
+ -------
101
+ h_abs : float
102
+ Absolute value of the suggested initial step.
103
+
104
+ References
105
+ ----------
106
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
107
+ Equations I: Nonstiff Problems", Sec. II.4.
108
+ """
109
+ if y0.size == 0:
110
+ return np.inf
111
+
112
+ interval_length = abs(t_bound - t0)
113
+ if interval_length == 0.0:
114
+ return 0.0
115
+
116
+ scale = atol + np.abs(y0) * rtol
117
+ d0 = norm(y0 / scale)
118
+ d1 = norm(f0 / scale)
119
+ if d0 < 1e-5 or d1 < 1e-5:
120
+ h0 = 1e-6
121
+ else:
122
+ h0 = 0.01 * d0 / d1
123
+ # Check t0+h0*direction doesn't take us beyond t_bound
124
+ h0 = min(h0, interval_length)
125
+ y1 = y0 + h0 * direction * f0
126
+ f1 = fun(t0 + h0 * direction, y1)
127
+ d2 = norm((f1 - f0) / scale) / h0
128
+
129
+ if d1 <= 1e-15 and d2 <= 1e-15:
130
+ h1 = max(1e-6, h0 * 1e-3)
131
+ else:
132
+ h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1))
133
+
134
+ return min(100 * h0, h1, interval_length, max_step)
135
+
136
+
137
+ class OdeSolution:
138
+ """Continuous ODE solution.
139
+
140
+ It is organized as a collection of `DenseOutput` objects which represent
141
+ local interpolants. It provides an algorithm to select a right interpolant
142
+ for each given point.
143
+
144
+ The interpolants cover the range between `t_min` and `t_max` (see
145
+ Attributes below). Evaluation outside this interval is not forbidden, but
146
+ the accuracy is not guaranteed.
147
+
148
+ When evaluating at a breakpoint (one of the values in `ts`) a segment with
149
+ the lower index is selected.
150
+
151
+ Parameters
152
+ ----------
153
+ ts : array_like, shape (n_segments + 1,)
154
+ Time instants between which local interpolants are defined. Must
155
+ be strictly increasing or decreasing (zero segment with two points is
156
+ also allowed).
157
+ interpolants : list of DenseOutput with n_segments elements
158
+ Local interpolants. An i-th interpolant is assumed to be defined
159
+ between ``ts[i]`` and ``ts[i + 1]``.
160
+ alt_segment : boolean
161
+ Requests the alternative interpolant segment selection scheme. At each
162
+ solver integration point, two interpolant segments are available. The
163
+ default (False) and alternative (True) behaviours select the segment
164
+ for which the requested time corresponded to ``t`` and ``t_old``,
165
+ respectively. This functionality is only relevant for testing the
166
+ interpolants' accuracy: different integrators use different
167
+ construction strategies.
168
+
169
+ Attributes
170
+ ----------
171
+ t_min, t_max : float
172
+ Time range of the interpolation.
173
+ """
174
+ def __init__(self, ts, interpolants, alt_segment=False):
175
+ ts = np.asarray(ts)
176
+ d = np.diff(ts)
177
+ # The first case covers integration on zero segment.
178
+ if not ((ts.size == 2 and ts[0] == ts[-1])
179
+ or np.all(d > 0) or np.all(d < 0)):
180
+ raise ValueError("`ts` must be strictly increasing or decreasing.")
181
+
182
+ self.n_segments = len(interpolants)
183
+ if ts.shape != (self.n_segments + 1,):
184
+ raise ValueError("Numbers of time stamps and interpolants "
185
+ "don't match.")
186
+
187
+ self.ts = ts
188
+ self.interpolants = interpolants
189
+ if ts[-1] >= ts[0]:
190
+ self.t_min = ts[0]
191
+ self.t_max = ts[-1]
192
+ self.ascending = True
193
+ self.side = "right" if alt_segment else "left"
194
+ self.ts_sorted = ts
195
+ else:
196
+ self.t_min = ts[-1]
197
+ self.t_max = ts[0]
198
+ self.ascending = False
199
+ self.side = "left" if alt_segment else "right"
200
+ self.ts_sorted = ts[::-1]
201
+
202
+ def _call_single(self, t):
203
+ # Here we preserve a certain symmetry that when t is in self.ts,
204
+ # if alt_segment=False, then we prioritize a segment with a lower
205
+ # index.
206
+ ind = np.searchsorted(self.ts_sorted, t, side=self.side)
207
+
208
+ segment = min(max(ind - 1, 0), self.n_segments - 1)
209
+ if not self.ascending:
210
+ segment = self.n_segments - 1 - segment
211
+
212
+ return self.interpolants[segment](t)
213
+
214
+ def __call__(self, t):
215
+ """Evaluate the solution.
216
+
217
+ Parameters
218
+ ----------
219
+ t : float or array_like with shape (n_points,)
220
+ Points to evaluate at.
221
+
222
+ Returns
223
+ -------
224
+ y : ndarray, shape (n_states,) or (n_states, n_points)
225
+ Computed values. Shape depends on whether `t` is a scalar or a
226
+ 1-D array.
227
+ """
228
+ t = np.asarray(t)
229
+
230
+ if t.ndim == 0:
231
+ return self._call_single(t)
232
+
233
+ order = np.argsort(t)
234
+ reverse = np.empty_like(order)
235
+ reverse[order] = np.arange(order.shape[0])
236
+ t_sorted = t[order]
237
+
238
+ # See comment in self._call_single.
239
+ segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side)
240
+ segments -= 1
241
+ segments[segments < 0] = 0
242
+ segments[segments > self.n_segments - 1] = self.n_segments - 1
243
+ if not self.ascending:
244
+ segments = self.n_segments - 1 - segments
245
+
246
+ ys = []
247
+ group_start = 0
248
+ for segment, group in groupby(segments):
249
+ group_end = group_start + len(list(group))
250
+ y = self.interpolants[segment](t_sorted[group_start:group_end])
251
+ ys.append(y)
252
+ group_start = group_end
253
+
254
+ ys = np.hstack(ys)
255
+ ys = ys[:, reverse]
256
+
257
+ return ys
258
+
259
+
260
+ NUM_JAC_DIFF_REJECT = EPS ** 0.875
261
+ NUM_JAC_DIFF_SMALL = EPS ** 0.75
262
+ NUM_JAC_DIFF_BIG = EPS ** 0.25
263
+ NUM_JAC_MIN_FACTOR = 1e3 * EPS
264
+ NUM_JAC_FACTOR_INCREASE = 10
265
+ NUM_JAC_FACTOR_DECREASE = 0.1
266
+
267
+
268
+ def num_jac(fun, t, y, f, threshold, factor, sparsity=None):
269
+ """Finite differences Jacobian approximation tailored for ODE solvers.
270
+
271
+ This function computes finite difference approximation to the Jacobian
272
+ matrix of `fun` with respect to `y` using forward differences.
273
+ The Jacobian matrix has shape (n, n) and its element (i, j) is equal to
274
+ ``d f_i / d y_j``.
275
+
276
+ A special feature of this function is the ability to correct the step
277
+ size from iteration to iteration. The main idea is to keep the finite
278
+ difference significantly separated from its round-off error which
279
+ approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a
280
+ huge error and assures that the estimated derivative are reasonably close
281
+ to the true values (i.e., the finite difference approximation is at least
282
+ qualitatively reflects the structure of the true Jacobian).
283
+
284
+ Parameters
285
+ ----------
286
+ fun : callable
287
+ Right-hand side of the system implemented in a vectorized fashion.
288
+ t : float
289
+ Current time.
290
+ y : ndarray, shape (n,)
291
+ Current state.
292
+ f : ndarray, shape (n,)
293
+ Value of the right hand side at (t, y).
294
+ threshold : float
295
+ Threshold for `y` value used for computing the step size as
296
+ ``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of
297
+ absolute tolerance (atol) for a solver should be passed as `threshold`.
298
+ factor : ndarray with shape (n,) or None
299
+ Factor to use for computing the step size. Pass None for the very
300
+ evaluation, then use the value returned from this function.
301
+ sparsity : tuple (structure, groups) or None
302
+ Sparsity structure of the Jacobian, `structure` must be csc_matrix.
303
+
304
+ Returns
305
+ -------
306
+ J : ndarray or csc_matrix, shape (n, n)
307
+ Jacobian matrix.
308
+ factor : ndarray, shape (n,)
309
+ Suggested `factor` for the next evaluation.
310
+ """
311
+ y = np.asarray(y)
312
+ n = y.shape[0]
313
+ if n == 0:
314
+ return np.empty((0, 0)), factor
315
+
316
+ if factor is None:
317
+ factor = np.full(n, EPS ** 0.5)
318
+ else:
319
+ factor = factor.copy()
320
+
321
+ # Direct the step as ODE dictates, hoping that such a step won't lead to
322
+ # a problematic region. For complex ODEs it makes sense to use the real
323
+ # part of f as we use steps along real axis.
324
+ f_sign = 2 * (np.real(f) >= 0).astype(float) - 1
325
+ y_scale = f_sign * np.maximum(threshold, np.abs(y))
326
+ h = (y + factor * y_scale) - y
327
+
328
+ # Make sure that the step is not 0 to start with. Not likely it will be
329
+ # executed often.
330
+ for i in np.nonzero(h == 0)[0]:
331
+ while h[i] == 0:
332
+ factor[i] *= 10
333
+ h[i] = (y[i] + factor[i] * y_scale[i]) - y[i]
334
+
335
+ if sparsity is None:
336
+ return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
337
+ else:
338
+ structure, groups = sparsity
339
+ return _sparse_num_jac(fun, t, y, f, h, factor, y_scale,
340
+ structure, groups)
341
+
342
+
343
+ def _dense_num_jac(fun, t, y, f, h, factor, y_scale):
344
+ n = y.shape[0]
345
+ h_vecs = np.diag(h)
346
+ f_new = fun(t, y[:, None] + h_vecs)
347
+ diff = f_new - f[:, None]
348
+ max_ind = np.argmax(np.abs(diff), axis=0)
349
+ r = np.arange(n)
350
+ max_diff = np.abs(diff[max_ind, r])
351
+ scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
352
+
353
+ diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
354
+ if np.any(diff_too_small):
355
+ ind, = np.nonzero(diff_too_small)
356
+ new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
357
+ h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
358
+ h_vecs[ind, ind] = h_new
359
+ f_new = fun(t, y[:, None] + h_vecs[:, ind])
360
+ diff_new = f_new - f[:, None]
361
+ max_ind = np.argmax(np.abs(diff_new), axis=0)
362
+ r = np.arange(ind.shape[0])
363
+ max_diff_new = np.abs(diff_new[max_ind, r])
364
+ scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
365
+
366
+ update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
367
+ if np.any(update):
368
+ update, = np.nonzero(update)
369
+ update_ind = ind[update]
370
+ factor[update_ind] = new_factor[update]
371
+ h[update_ind] = h_new[update]
372
+ diff[:, update_ind] = diff_new[:, update]
373
+ scale[update_ind] = scale_new[update]
374
+ max_diff[update_ind] = max_diff_new[update]
375
+
376
+ diff /= h
377
+
378
+ factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
379
+ factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
380
+ factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
381
+
382
+ return diff, factor
383
+
384
+
385
+ def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups):
386
+ n = y.shape[0]
387
+ n_groups = np.max(groups) + 1
388
+ h_vecs = np.empty((n_groups, n))
389
+ for group in range(n_groups):
390
+ e = np.equal(group, groups)
391
+ h_vecs[group] = h * e
392
+ h_vecs = h_vecs.T
393
+
394
+ f_new = fun(t, y[:, None] + h_vecs)
395
+ df = f_new - f[:, None]
396
+
397
+ i, j, _ = find(structure)
398
+ diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc()
399
+ max_ind = np.array(abs(diff).argmax(axis=0)).ravel()
400
+ r = np.arange(n)
401
+ max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel()
402
+ scale = np.maximum(np.abs(f[max_ind]),
403
+ np.abs(f_new[max_ind, groups[r]]))
404
+
405
+ diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
406
+ if np.any(diff_too_small):
407
+ ind, = np.nonzero(diff_too_small)
408
+ new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
409
+ h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
410
+ h_new_all = np.zeros(n)
411
+ h_new_all[ind] = h_new
412
+
413
+ groups_unique = np.unique(groups[ind])
414
+ groups_map = np.empty(n_groups, dtype=int)
415
+ h_vecs = np.empty((groups_unique.shape[0], n))
416
+ for k, group in enumerate(groups_unique):
417
+ e = np.equal(group, groups)
418
+ h_vecs[k] = h_new_all * e
419
+ groups_map[group] = k
420
+ h_vecs = h_vecs.T
421
+
422
+ f_new = fun(t, y[:, None] + h_vecs)
423
+ df = f_new - f[:, None]
424
+ i, j, _ = find(structure[:, ind])
425
+ diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]],
426
+ (i, j)), shape=(n, ind.shape[0])).tocsc()
427
+
428
+ max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel()
429
+ r = np.arange(ind.shape[0])
430
+ max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel()
431
+ scale_new = np.maximum(
432
+ np.abs(f[max_ind_new]),
433
+ np.abs(f_new[max_ind_new, groups_map[groups[ind]]]))
434
+
435
+ update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
436
+ if np.any(update):
437
+ update, = np.nonzero(update)
438
+ update_ind = ind[update]
439
+ factor[update_ind] = new_factor[update]
440
+ h[update_ind] = h_new[update]
441
+ diff[:, update_ind] = diff_new[:, update]
442
+ scale[update_ind] = scale_new[update]
443
+ max_diff[update_ind] = max_diff_new[update]
444
+
445
+ diff.data /= np.repeat(h, np.diff(diff.indptr))
446
+
447
+ factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
448
+ factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
449
+ factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
450
+
451
+ return diff, factor
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ N_STAGES = 12
4
+ N_STAGES_EXTENDED = 16
5
+ INTERPOLATOR_POWER = 7
6
+
7
+ C = np.array([0.0,
8
+ 0.526001519587677318785587544488e-01,
9
+ 0.789002279381515978178381316732e-01,
10
+ 0.118350341907227396726757197510,
11
+ 0.281649658092772603273242802490,
12
+ 0.333333333333333333333333333333,
13
+ 0.25,
14
+ 0.307692307692307692307692307692,
15
+ 0.651282051282051282051282051282,
16
+ 0.6,
17
+ 0.857142857142857142857142857142,
18
+ 1.0,
19
+ 1.0,
20
+ 0.1,
21
+ 0.2,
22
+ 0.777777777777777777777777777778])
23
+
24
+ A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED))
25
+ A[1, 0] = 5.26001519587677318785587544488e-2
26
+
27
+ A[2, 0] = 1.97250569845378994544595329183e-2
28
+ A[2, 1] = 5.91751709536136983633785987549e-2
29
+
30
+ A[3, 0] = 2.95875854768068491816892993775e-2
31
+ A[3, 2] = 8.87627564304205475450678981324e-2
32
+
33
+ A[4, 0] = 2.41365134159266685502369798665e-1
34
+ A[4, 2] = -8.84549479328286085344864962717e-1
35
+ A[4, 3] = 9.24834003261792003115737966543e-1
36
+
37
+ A[5, 0] = 3.7037037037037037037037037037e-2
38
+ A[5, 3] = 1.70828608729473871279604482173e-1
39
+ A[5, 4] = 1.25467687566822425016691814123e-1
40
+
41
+ A[6, 0] = 3.7109375e-2
42
+ A[6, 3] = 1.70252211019544039314978060272e-1
43
+ A[6, 4] = 6.02165389804559606850219397283e-2
44
+ A[6, 5] = -1.7578125e-2
45
+
46
+ A[7, 0] = 3.70920001185047927108779319836e-2
47
+ A[7, 3] = 1.70383925712239993810214054705e-1
48
+ A[7, 4] = 1.07262030446373284651809199168e-1
49
+ A[7, 5] = -1.53194377486244017527936158236e-2
50
+ A[7, 6] = 8.27378916381402288758473766002e-3
51
+
52
+ A[8, 0] = 6.24110958716075717114429577812e-1
53
+ A[8, 3] = -3.36089262944694129406857109825
54
+ A[8, 4] = -8.68219346841726006818189891453e-1
55
+ A[8, 5] = 2.75920996994467083049415600797e1
56
+ A[8, 6] = 2.01540675504778934086186788979e1
57
+ A[8, 7] = -4.34898841810699588477366255144e1
58
+
59
+ A[9, 0] = 4.77662536438264365890433908527e-1
60
+ A[9, 3] = -2.48811461997166764192642586468
61
+ A[9, 4] = -5.90290826836842996371446475743e-1
62
+ A[9, 5] = 2.12300514481811942347288949897e1
63
+ A[9, 6] = 1.52792336328824235832596922938e1
64
+ A[9, 7] = -3.32882109689848629194453265587e1
65
+ A[9, 8] = -2.03312017085086261358222928593e-2
66
+
67
+ A[10, 0] = -9.3714243008598732571704021658e-1
68
+ A[10, 3] = 5.18637242884406370830023853209
69
+ A[10, 4] = 1.09143734899672957818500254654
70
+ A[10, 5] = -8.14978701074692612513997267357
71
+ A[10, 6] = -1.85200656599969598641566180701e1
72
+ A[10, 7] = 2.27394870993505042818970056734e1
73
+ A[10, 8] = 2.49360555267965238987089396762
74
+ A[10, 9] = -3.0467644718982195003823669022
75
+
76
+ A[11, 0] = 2.27331014751653820792359768449
77
+ A[11, 3] = -1.05344954667372501984066689879e1
78
+ A[11, 4] = -2.00087205822486249909675718444
79
+ A[11, 5] = -1.79589318631187989172765950534e1
80
+ A[11, 6] = 2.79488845294199600508499808837e1
81
+ A[11, 7] = -2.85899827713502369474065508674
82
+ A[11, 8] = -8.87285693353062954433549289258
83
+ A[11, 9] = 1.23605671757943030647266201528e1
84
+ A[11, 10] = 6.43392746015763530355970484046e-1
85
+
86
+ A[12, 0] = 5.42937341165687622380535766363e-2
87
+ A[12, 5] = 4.45031289275240888144113950566
88
+ A[12, 6] = 1.89151789931450038304281599044
89
+ A[12, 7] = -5.8012039600105847814672114227
90
+ A[12, 8] = 3.1116436695781989440891606237e-1
91
+ A[12, 9] = -1.52160949662516078556178806805e-1
92
+ A[12, 10] = 2.01365400804030348374776537501e-1
93
+ A[12, 11] = 4.47106157277725905176885569043e-2
94
+
95
+ A[13, 0] = 5.61675022830479523392909219681e-2
96
+ A[13, 6] = 2.53500210216624811088794765333e-1
97
+ A[13, 7] = -2.46239037470802489917441475441e-1
98
+ A[13, 8] = -1.24191423263816360469010140626e-1
99
+ A[13, 9] = 1.5329179827876569731206322685e-1
100
+ A[13, 10] = 8.20105229563468988491666602057e-3
101
+ A[13, 11] = 7.56789766054569976138603589584e-3
102
+ A[13, 12] = -8.298e-3
103
+
104
+ A[14, 0] = 3.18346481635021405060768473261e-2
105
+ A[14, 5] = 2.83009096723667755288322961402e-2
106
+ A[14, 6] = 5.35419883074385676223797384372e-2
107
+ A[14, 7] = -5.49237485713909884646569340306e-2
108
+ A[14, 10] = -1.08347328697249322858509316994e-4
109
+ A[14, 11] = 3.82571090835658412954920192323e-4
110
+ A[14, 12] = -3.40465008687404560802977114492e-4
111
+ A[14, 13] = 1.41312443674632500278074618366e-1
112
+
113
+ A[15, 0] = -4.28896301583791923408573538692e-1
114
+ A[15, 5] = -4.69762141536116384314449447206
115
+ A[15, 6] = 7.68342119606259904184240953878
116
+ A[15, 7] = 4.06898981839711007970213554331
117
+ A[15, 8] = 3.56727187455281109270669543021e-1
118
+ A[15, 12] = -1.39902416515901462129418009734e-3
119
+ A[15, 13] = 2.9475147891527723389556272149
120
+ A[15, 14] = -9.15095847217987001081870187138
121
+
122
+
123
+ B = A[N_STAGES, :N_STAGES]
124
+
125
+ E3 = np.zeros(N_STAGES + 1)
126
+ E3[:-1] = B.copy()
127
+ E3[0] -= 0.244094488188976377952755905512
128
+ E3[8] -= 0.733846688281611857341361741547
129
+ E3[11] -= 0.220588235294117647058823529412e-1
130
+
131
+ E5 = np.zeros(N_STAGES + 1)
132
+ E5[0] = 0.1312004499419488073250102996e-1
133
+ E5[5] = -0.1225156446376204440720569753e+1
134
+ E5[6] = -0.4957589496572501915214079952
135
+ E5[7] = 0.1664377182454986536961530415e+1
136
+ E5[8] = -0.3503288487499736816886487290
137
+ E5[9] = 0.3341791187130174790297318841
138
+ E5[10] = 0.8192320648511571246570742613e-1
139
+ E5[11] = -0.2235530786388629525884427845e-1
140
+
141
+ # First 3 coefficients are computed separately.
142
+ D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED))
143
+ D[0, 0] = -0.84289382761090128651353491142e+1
144
+ D[0, 5] = 0.56671495351937776962531783590
145
+ D[0, 6] = -0.30689499459498916912797304727e+1
146
+ D[0, 7] = 0.23846676565120698287728149680e+1
147
+ D[0, 8] = 0.21170345824450282767155149946e+1
148
+ D[0, 9] = -0.87139158377797299206789907490
149
+ D[0, 10] = 0.22404374302607882758541771650e+1
150
+ D[0, 11] = 0.63157877876946881815570249290
151
+ D[0, 12] = -0.88990336451333310820698117400e-1
152
+ D[0, 13] = 0.18148505520854727256656404962e+2
153
+ D[0, 14] = -0.91946323924783554000451984436e+1
154
+ D[0, 15] = -0.44360363875948939664310572000e+1
155
+
156
+ D[1, 0] = 0.10427508642579134603413151009e+2
157
+ D[1, 5] = 0.24228349177525818288430175319e+3
158
+ D[1, 6] = 0.16520045171727028198505394887e+3
159
+ D[1, 7] = -0.37454675472269020279518312152e+3
160
+ D[1, 8] = -0.22113666853125306036270938578e+2
161
+ D[1, 9] = 0.77334326684722638389603898808e+1
162
+ D[1, 10] = -0.30674084731089398182061213626e+2
163
+ D[1, 11] = -0.93321305264302278729567221706e+1
164
+ D[1, 12] = 0.15697238121770843886131091075e+2
165
+ D[1, 13] = -0.31139403219565177677282850411e+2
166
+ D[1, 14] = -0.93529243588444783865713862664e+1
167
+ D[1, 15] = 0.35816841486394083752465898540e+2
168
+
169
+ D[2, 0] = 0.19985053242002433820987653617e+2
170
+ D[2, 5] = -0.38703730874935176555105901742e+3
171
+ D[2, 6] = -0.18917813819516756882830838328e+3
172
+ D[2, 7] = 0.52780815920542364900561016686e+3
173
+ D[2, 8] = -0.11573902539959630126141871134e+2
174
+ D[2, 9] = 0.68812326946963000169666922661e+1
175
+ D[2, 10] = -0.10006050966910838403183860980e+1
176
+ D[2, 11] = 0.77771377980534432092869265740
177
+ D[2, 12] = -0.27782057523535084065932004339e+1
178
+ D[2, 13] = -0.60196695231264120758267380846e+2
179
+ D[2, 14] = 0.84320405506677161018159903784e+2
180
+ D[2, 15] = 0.11992291136182789328035130030e+2
181
+
182
+ D[3, 0] = -0.25693933462703749003312586129e+2
183
+ D[3, 5] = -0.15418974869023643374053993627e+3
184
+ D[3, 6] = -0.23152937917604549567536039109e+3
185
+ D[3, 7] = 0.35763911791061412378285349910e+3
186
+ D[3, 8] = 0.93405324183624310003907691704e+2
187
+ D[3, 9] = -0.37458323136451633156875139351e+2
188
+ D[3, 10] = 0.10409964950896230045147246184e+3
189
+ D[3, 11] = 0.29840293426660503123344363579e+2
190
+ D[3, 12] = -0.43533456590011143754432175058e+2
191
+ D[3, 13] = 0.96324553959188282948394950600e+2
192
+ D[3, 14] = -0.39177261675615439165231486172e+2
193
+ D[3, 15] = -0.14972683625798562581422125276e+3
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import numpy as np
3
+ from .bdf import BDF
4
+ from .radau import Radau
5
+ from .rk import RK23, RK45, DOP853
6
+ from .lsoda import LSODA
7
+ from scipy.optimize import OptimizeResult
8
+ from .common import EPS, OdeSolution
9
+ from .base import OdeSolver
10
+
11
+
12
+ METHODS = {'RK23': RK23,
13
+ 'RK45': RK45,
14
+ 'DOP853': DOP853,
15
+ 'Radau': Radau,
16
+ 'BDF': BDF,
17
+ 'LSODA': LSODA}
18
+
19
+
20
+ MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
21
+ 1: "A termination event occurred."}
22
+
23
+
24
+ class OdeResult(OptimizeResult):
25
+ pass
26
+
27
+
28
+ def prepare_events(events):
29
+ """Standardize event functions and extract attributes."""
30
+ if callable(events):
31
+ events = (events,)
32
+
33
+ max_events = np.empty(len(events))
34
+ direction = np.empty(len(events))
35
+ for i, event in enumerate(events):
36
+ terminal = getattr(event, 'terminal', None)
37
+ direction[i] = getattr(event, 'direction', 0)
38
+
39
+ message = ('The `terminal` attribute of each event '
40
+ 'must be a boolean or positive integer.')
41
+ if terminal is None or terminal == 0:
42
+ max_events[i] = np.inf
43
+ elif int(terminal) == terminal and terminal > 0:
44
+ max_events[i] = terminal
45
+ else:
46
+ raise ValueError(message)
47
+
48
+ return events, max_events, direction
49
+
50
+
51
+ def solve_event_equation(event, sol, t_old, t):
52
+ """Solve an equation corresponding to an ODE event.
53
+
54
+ The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
55
+ ODE solver using some sort of interpolation. It is solved by
56
+ `scipy.optimize.brentq` with xtol=atol=4*EPS.
57
+
58
+ Parameters
59
+ ----------
60
+ event : callable
61
+ Function ``event(t, y)``.
62
+ sol : callable
63
+ Function ``sol(t)`` which evaluates an ODE solution between `t_old`
64
+ and `t`.
65
+ t_old, t : float
66
+ Previous and new values of time. They will be used as a bracketing
67
+ interval.
68
+
69
+ Returns
70
+ -------
71
+ root : float
72
+ Found solution.
73
+ """
74
+ from scipy.optimize import brentq
75
+ return brentq(lambda t: event(t, sol(t)), t_old, t,
76
+ xtol=4 * EPS, rtol=4 * EPS)
77
+
78
+
79
+ def handle_events(sol, events, active_events, event_count, max_events,
80
+ t_old, t):
81
+ """Helper function to handle events.
82
+
83
+ Parameters
84
+ ----------
85
+ sol : DenseOutput
86
+ Function ``sol(t)`` which evaluates an ODE solution between `t_old`
87
+ and `t`.
88
+ events : list of callables, length n_events
89
+ Event functions with signatures ``event(t, y)``.
90
+ active_events : ndarray
91
+ Indices of events which occurred.
92
+ event_count : ndarray
93
+ Current number of occurrences for each event.
94
+ max_events : ndarray, shape (n_events,)
95
+ Number of occurrences allowed for each event before integration
96
+ termination is issued.
97
+ t_old, t : float
98
+ Previous and new values of time.
99
+
100
+ Returns
101
+ -------
102
+ root_indices : ndarray
103
+ Indices of events which take zero between `t_old` and `t` and before
104
+ a possible termination.
105
+ roots : ndarray
106
+ Values of t at which events occurred.
107
+ terminate : bool
108
+ Whether a terminal event occurred.
109
+ """
110
+ roots = [solve_event_equation(events[event_index], sol, t_old, t)
111
+ for event_index in active_events]
112
+
113
+ roots = np.asarray(roots)
114
+
115
+ if np.any(event_count[active_events] >= max_events[active_events]):
116
+ if t > t_old:
117
+ order = np.argsort(roots)
118
+ else:
119
+ order = np.argsort(-roots)
120
+ active_events = active_events[order]
121
+ roots = roots[order]
122
+ t = np.nonzero(event_count[active_events]
123
+ >= max_events[active_events])[0][0]
124
+ active_events = active_events[:t + 1]
125
+ roots = roots[:t + 1]
126
+ terminate = True
127
+ else:
128
+ terminate = False
129
+
130
+ return active_events, roots, terminate
131
+
132
+
133
+ def find_active_events(g, g_new, direction):
134
+ """Find which event occurred during an integration step.
135
+
136
+ Parameters
137
+ ----------
138
+ g, g_new : array_like, shape (n_events,)
139
+ Values of event functions at a current and next points.
140
+ direction : ndarray, shape (n_events,)
141
+ Event "direction" according to the definition in `solve_ivp`.
142
+
143
+ Returns
144
+ -------
145
+ active_events : ndarray
146
+ Indices of events which occurred during the step.
147
+ """
148
+ g, g_new = np.asarray(g), np.asarray(g_new)
149
+ up = (g <= 0) & (g_new >= 0)
150
+ down = (g >= 0) & (g_new <= 0)
151
+ either = up | down
152
+ mask = (up & (direction > 0) |
153
+ down & (direction < 0) |
154
+ either & (direction == 0))
155
+
156
+ return np.nonzero(mask)[0]
157
+
158
+
159
+ def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
160
+ events=None, vectorized=False, args=None, **options):
161
+ """Solve an initial value problem for a system of ODEs.
162
+
163
+ This function numerically integrates a system of ordinary differential
164
+ equations given an initial value::
165
+
166
+ dy / dt = f(t, y)
167
+ y(t0) = y0
168
+
169
+ Here t is a 1-D independent variable (time), y(t) is an
170
+ N-D vector-valued function (state), and an N-D
171
+ vector-valued function f(t, y) determines the differential equations.
172
+ The goal is to find y(t) approximately satisfying the differential
173
+ equations, given an initial value y(t0)=y0.
174
+
175
+ Some of the solvers support integration in the complex domain, but note
176
+ that for stiff ODE solvers, the right-hand side must be
177
+ complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
178
+ To solve a problem in the complex domain, pass y0 with a complex data type.
179
+ Another option always available is to rewrite your problem for real and
180
+ imaginary parts separately.
181
+
182
+ Parameters
183
+ ----------
184
+ fun : callable
185
+ Right-hand side of the system: the time derivative of the state ``y``
186
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
187
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
188
+ arguments need to be passed if ``args`` is used (see documentation of
189
+ ``args`` argument). ``fun`` must return an array of the same shape as
190
+ ``y``. See `vectorized` for more information.
191
+ t_span : 2-member sequence
192
+ Interval of integration (t0, tf). The solver starts with t=t0 and
193
+ integrates until it reaches t=tf. Both t0 and tf must be floats
194
+ or values interpretable by the float conversion function.
195
+ y0 : array_like, shape (n,)
196
+ Initial state. For problems in the complex domain, pass `y0` with a
197
+ complex data type (even if the initial value is purely real).
198
+ method : string or `OdeSolver`, optional
199
+ Integration method to use:
200
+
201
+ * 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_.
202
+ The error is controlled assuming accuracy of the fourth-order
203
+ method, but steps are taken using the fifth-order accurate
204
+ formula (local extrapolation is done). A quartic interpolation
205
+ polynomial is used for the dense output [2]_. Can be applied in
206
+ the complex domain.
207
+ * 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error
208
+ is controlled assuming accuracy of the second-order method, but
209
+ steps are taken using the third-order accurate formula (local
210
+ extrapolation is done). A cubic Hermite polynomial is used for the
211
+ dense output. Can be applied in the complex domain.
212
+ * 'DOP853': Explicit Runge-Kutta method of order 8 [13]_.
213
+ Python implementation of the "DOP853" algorithm originally
214
+ written in Fortran [14]_. A 7-th order interpolation polynomial
215
+ accurate to 7-th order is used for the dense output.
216
+ Can be applied in the complex domain.
217
+ * 'Radau': Implicit Runge-Kutta method of the Radau IIA family of
218
+ order 5 [4]_. The error is controlled with a third-order accurate
219
+ embedded formula. A cubic polynomial which satisfies the
220
+ collocation conditions is used for the dense output.
221
+ * 'BDF': Implicit multi-step variable-order (1 to 5) method based
222
+ on a backward differentiation formula for the derivative
223
+ approximation [5]_. The implementation follows the one described
224
+ in [6]_. A quasi-constant step scheme is used and accuracy is
225
+ enhanced using the NDF modification. Can be applied in the
226
+ complex domain.
227
+ * 'LSODA': Adams/BDF method with automatic stiffness detection and
228
+ switching [7]_, [8]_. This is a wrapper of the Fortran solver
229
+ from ODEPACK.
230
+
231
+ Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
232
+ for non-stiff problems and implicit methods ('Radau', 'BDF') for
233
+ stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
234
+ for solving with high precision (low values of `rtol` and `atol`).
235
+
236
+ If not sure, first try to run 'RK45'. If it makes unusually many
237
+ iterations, diverges, or fails, your problem is likely to be stiff and
238
+ you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
239
+ choice, but it might be somewhat less convenient to work with as it
240
+ wraps old Fortran code.
241
+
242
+ You can also pass an arbitrary class derived from `OdeSolver` which
243
+ implements the solver.
244
+ t_eval : array_like or None, optional
245
+ Times at which to store the computed solution, must be sorted and lie
246
+ within `t_span`. If None (default), use points selected by the solver.
247
+ dense_output : bool, optional
248
+ Whether to compute a continuous solution. Default is False.
249
+ events : callable, or list of callables, optional
250
+ Events to track. If None (default), no events will be tracked.
251
+ Each event occurs at the zeros of a continuous function of time and
252
+ state. Each function must have the signature ``event(t, y)`` where
253
+ additional argument have to be passed if ``args`` is used (see
254
+ documentation of ``args`` argument). Each function must return a
255
+ float. The solver will find an accurate value of `t` at which
256
+ ``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
257
+ all zeros will be found. The solver looks for a sign change over
258
+ each step, so if multiple zero crossings occur within one step,
259
+ events may be missed. Additionally each `event` function might
260
+ have the following attributes:
261
+
262
+ terminal: bool or int, optional
263
+ When boolean, whether to terminate integration if this event occurs.
264
+ When integral, termination occurs after the specified the number of
265
+ occurrences of this event.
266
+ Implicitly False if not assigned.
267
+ direction: float, optional
268
+ Direction of a zero crossing. If `direction` is positive,
269
+ `event` will only trigger when going from negative to positive,
270
+ and vice versa if `direction` is negative. If 0, then either
271
+ direction will trigger event. Implicitly 0 if not assigned.
272
+
273
+ You can assign attributes like ``event.terminal = True`` to any
274
+ function in Python.
275
+ vectorized : bool, optional
276
+ Whether `fun` can be called in a vectorized fashion. Default is False.
277
+
278
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
279
+ shape ``(n,)``, where ``n = len(y0)``.
280
+
281
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
282
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
283
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
284
+ the returned array is the time derivative of the state corresponding
285
+ with a column of ``y``).
286
+
287
+ Setting ``vectorized=True`` allows for faster finite difference
288
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
289
+ will result in slower execution for other methods and for 'Radau' and
290
+ 'BDF' in some circumstances (e.g. small ``len(y0)``).
291
+ args : tuple, optional
292
+ Additional arguments to pass to the user-defined functions. If given,
293
+ the additional arguments are passed to all user-defined functions.
294
+ So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
295
+ then `jac` (if given) and any event functions must have the same
296
+ signature, and `args` must be a tuple of length 3.
297
+ **options
298
+ Options passed to a chosen solver. All options available for already
299
+ implemented solvers are listed below.
300
+ first_step : float or None, optional
301
+ Initial step size. Default is `None` which means that the algorithm
302
+ should choose.
303
+ max_step : float, optional
304
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
305
+ bounded and determined solely by the solver.
306
+ rtol, atol : float or array_like, optional
307
+ Relative and absolute tolerances. The solver keeps the local error
308
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
309
+ relative accuracy (number of correct digits), while `atol` controls
310
+ absolute accuracy (number of correct decimal places). To achieve the
311
+ desired `rtol`, set `atol` to be smaller than the smallest value that
312
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
313
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
314
+ number of correct digits is not guaranteed. Conversely, to achieve the
315
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
316
+ than `atol`. If components of y have different scales, it might be
317
+ beneficial to set different `atol` values for different components by
318
+ passing array_like with shape (n,) for `atol`. Default values are
319
+ 1e-3 for `rtol` and 1e-6 for `atol`.
320
+ jac : array_like, sparse_matrix, callable or None, optional
321
+ Jacobian matrix of the right-hand side of the system with respect
322
+ to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
323
+ Jacobian matrix has shape (n, n) and its element (i, j) is equal to
324
+ ``d f_i / d y_j``. There are three ways to define the Jacobian:
325
+
326
+ * If array_like or sparse_matrix, the Jacobian is assumed to
327
+ be constant. Not supported by 'LSODA'.
328
+ * If callable, the Jacobian is assumed to depend on both
329
+ t and y; it will be called as ``jac(t, y)``, as necessary.
330
+ Additional arguments have to be passed if ``args`` is
331
+ used (see documentation of ``args`` argument).
332
+ For 'Radau' and 'BDF' methods, the return value might be a
333
+ sparse matrix.
334
+ * If None (default), the Jacobian will be approximated by
335
+ finite differences.
336
+
337
+ It is generally recommended to provide the Jacobian rather than
338
+ relying on a finite-difference approximation.
339
+ jac_sparsity : array_like, sparse matrix or None, optional
340
+ Defines a sparsity structure of the Jacobian matrix for a finite-
341
+ difference approximation. Its shape must be (n, n). This argument
342
+ is ignored if `jac` is not `None`. If the Jacobian has only few
343
+ non-zero elements in *each* row, providing the sparsity structure
344
+ will greatly speed up the computations [10]_. A zero entry means that
345
+ a corresponding element in the Jacobian is always zero. If None
346
+ (default), the Jacobian is assumed to be dense.
347
+ Not supported by 'LSODA', see `lband` and `uband` instead.
348
+ lband, uband : int or None, optional
349
+ Parameters defining the bandwidth of the Jacobian for the 'LSODA'
350
+ method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
351
+ Default is None. Setting these requires your jac routine to return the
352
+ Jacobian in the packed format: the returned array must have ``n``
353
+ columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
354
+ written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
355
+ The same format is used in `scipy.linalg.solve_banded` (check for an
356
+ illustration). These parameters can be also used with ``jac=None`` to
357
+ reduce the number of Jacobian elements estimated by finite differences.
358
+ min_step : float, optional
359
+ The minimum allowed step size for 'LSODA' method.
360
+ By default `min_step` is zero.
361
+
362
+ Returns
363
+ -------
364
+ Bunch object with the following fields defined:
365
+ t : ndarray, shape (n_points,)
366
+ Time points.
367
+ y : ndarray, shape (n, n_points)
368
+ Values of the solution at `t`.
369
+ sol : `OdeSolution` or None
370
+ Found solution as `OdeSolution` instance; None if `dense_output` was
371
+ set to False.
372
+ t_events : list of ndarray or None
373
+ Contains for each event type a list of arrays at which an event of
374
+ that type event was detected. None if `events` was None.
375
+ y_events : list of ndarray or None
376
+ For each value of `t_events`, the corresponding value of the solution.
377
+ None if `events` was None.
378
+ nfev : int
379
+ Number of evaluations of the right-hand side.
380
+ njev : int
381
+ Number of evaluations of the Jacobian.
382
+ nlu : int
383
+ Number of LU decompositions.
384
+ status : int
385
+ Reason for algorithm termination:
386
+
387
+ * -1: Integration step failed.
388
+ * 0: The solver successfully reached the end of `tspan`.
389
+ * 1: A termination event occurred.
390
+
391
+ message : string
392
+ Human-readable description of the termination reason.
393
+ success : bool
394
+ True if the solver reached the interval end or a termination event
395
+ occurred (``status >= 0``).
396
+
397
+ References
398
+ ----------
399
+ .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
400
+ formulae", Journal of Computational and Applied Mathematics, Vol. 6,
401
+ No. 1, pp. 19-26, 1980.
402
+ .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
403
+ of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
404
+ .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
405
+ Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
406
+ .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
407
+ Stiff and Differential-Algebraic Problems", Sec. IV.8.
408
+ .. [5] `Backward Differentiation Formula
409
+ <https://en.wikipedia.org/wiki/Backward_differentiation_formula>`_
410
+ on Wikipedia.
411
+ .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
412
+ COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
413
+ .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
414
+ Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
415
+ pp. 55-64, 1983.
416
+ .. [8] L. Petzold, "Automatic selection of methods for solving stiff and
417
+ nonstiff systems of ordinary differential equations", SIAM Journal
418
+ on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
419
+ 1983.
420
+ .. [9] `Stiff equation <https://en.wikipedia.org/wiki/Stiff_equation>`_ on
421
+ Wikipedia.
422
+ .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
423
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
424
+ and its Applications, 13, pp. 117-120, 1974.
425
+ .. [11] `Cauchy-Riemann equations
426
+ <https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
427
+ Wikipedia.
428
+ .. [12] `Lotka-Volterra equations
429
+ <https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations>`_
430
+ on Wikipedia.
431
+ .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
432
+ Equations I: Nonstiff Problems", Sec. II.
433
+ .. [14] `Page with original Fortran code of DOP853
434
+ <http://www.unige.ch/~hairer/software.html>`_.
435
+
436
+ Examples
437
+ --------
438
+ Basic exponential decay showing automatically chosen time points.
439
+
440
+ >>> import numpy as np
441
+ >>> from scipy.integrate import solve_ivp
442
+ >>> def exponential_decay(t, y): return -0.5 * y
443
+ >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
444
+ >>> print(sol.t)
445
+ [ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806
446
+ 8.33328988 10. ]
447
+ >>> print(sol.y)
448
+ [[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
449
+ 0.03107158 0.01350781]
450
+ [4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091
451
+ 0.06214316 0.02701561]
452
+ [8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181
453
+ 0.12428631 0.05403123]]
454
+
455
+ Specifying points where the solution is desired.
456
+
457
+ >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
458
+ ... t_eval=[0, 1, 2, 4, 10])
459
+ >>> print(sol.t)
460
+ [ 0 1 2 4 10]
461
+ >>> print(sol.y)
462
+ [[2. 1.21305369 0.73534021 0.27066736 0.01350938]
463
+ [4. 2.42610739 1.47068043 0.54133472 0.02701876]
464
+ [8. 4.85221478 2.94136085 1.08266944 0.05403753]]
465
+
466
+ Cannon fired upward with terminal event upon impact. The ``terminal`` and
467
+ ``direction`` fields of an event are applied by monkey patching a function.
468
+ Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
469
+ at position 0 with velocity +10. Note that the integration never reaches
470
+ t=100 because the event is terminal.
471
+
472
+ >>> def upward_cannon(t, y): return [y[1], -0.5]
473
+ >>> def hit_ground(t, y): return y[0]
474
+ >>> hit_ground.terminal = True
475
+ >>> hit_ground.direction = -1
476
+ >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
477
+ >>> print(sol.t_events)
478
+ [array([40.])]
479
+ >>> print(sol.t)
480
+ [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
481
+ 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
482
+
483
+ Use `dense_output` and `events` to find position, which is 100, at the apex
484
+ of the cannonball's trajectory. Apex is not defined as terminal, so both
485
+ apex and hit_ground are found. There is no information at t=20, so the sol
486
+ attribute is used to evaluate the solution. The sol attribute is returned
487
+ by setting ``dense_output=True``. Alternatively, the `y_events` attribute
488
+ can be used to access the solution at the time of the event.
489
+
490
+ >>> def apex(t, y): return y[1]
491
+ >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
492
+ ... events=(hit_ground, apex), dense_output=True)
493
+ >>> print(sol.t_events)
494
+ [array([40.]), array([20.])]
495
+ >>> print(sol.t)
496
+ [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
497
+ 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
498
+ >>> print(sol.sol(sol.t_events[1][0]))
499
+ [100. 0.]
500
+ >>> print(sol.y_events)
501
+ [array([[-5.68434189e-14, -1.00000000e+01]]),
502
+ array([[1.00000000e+02, 1.77635684e-15]])]
503
+
504
+ As an example of a system with additional parameters, we'll implement
505
+ the Lotka-Volterra equations [12]_.
506
+
507
+ >>> def lotkavolterra(t, z, a, b, c, d):
508
+ ... x, y = z
509
+ ... return [a*x - b*x*y, -c*y + d*x*y]
510
+ ...
511
+
512
+ We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
513
+ argument.
514
+
515
+ >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
516
+ ... dense_output=True)
517
+
518
+ Compute a dense solution and plot it.
519
+
520
+ >>> t = np.linspace(0, 15, 300)
521
+ >>> z = sol.sol(t)
522
+ >>> import matplotlib.pyplot as plt
523
+ >>> plt.plot(t, z.T)
524
+ >>> plt.xlabel('t')
525
+ >>> plt.legend(['x', 'y'], shadow=True)
526
+ >>> plt.title('Lotka-Volterra System')
527
+ >>> plt.show()
528
+
529
+ A couple examples of using solve_ivp to solve the differential
530
+ equation ``y' = Ay`` with complex matrix ``A``.
531
+
532
+ >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
533
+ ... [0.25 + 0.58j, -0.2 + 0.14j, 0],
534
+ ... [0, 0.2 + 0.4j, -0.1 + 0.97j]])
535
+
536
+ Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
537
+
538
+ >>> def deriv_vec(t, y):
539
+ ... return A @ y
540
+ >>> result = solve_ivp(deriv_vec, [0, 25],
541
+ ... np.array([10 + 0j, 20 + 0j, 30 + 0j]),
542
+ ... t_eval=np.linspace(0, 25, 101))
543
+ >>> print(result.y[:, 0])
544
+ [10.+0.j 20.+0.j 30.+0.j]
545
+ >>> print(result.y[:, -1])
546
+ [18.46291039+45.25653651j 10.01569306+36.23293216j
547
+ -4.98662741+80.07360388j]
548
+
549
+ Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
550
+
551
+ >>> def deriv_mat(t, y):
552
+ ... return (A @ y.reshape(3, 3)).flatten()
553
+ >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
554
+ ... [5 + 0j, 6 + 0j, 7 + 0j],
555
+ ... [9 + 0j, 34 + 0j, 78 + 0j]])
556
+
557
+ >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
558
+ ... t_eval=np.linspace(0, 25, 101))
559
+ >>> print(result.y[:, 0].reshape(3, 3))
560
+ [[ 2.+0.j 3.+0.j 4.+0.j]
561
+ [ 5.+0.j 6.+0.j 7.+0.j]
562
+ [ 9.+0.j 34.+0.j 78.+0.j]]
563
+ >>> print(result.y[:, -1].reshape(3, 3))
564
+ [[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j
565
+ 37.83405768 +63.25138759j]
566
+ [ 3.39949503 +11.82123994j 21.32530996 +44.88668871j
567
+ 53.17531184+103.80400411j]
568
+ [ -2.26105874 +22.19277664j -15.1255713 +70.19616341j
569
+ -38.34616845+153.29039931j]]
570
+
571
+
572
+ """
573
+ if method not in METHODS and not (
574
+ inspect.isclass(method) and issubclass(method, OdeSolver)):
575
+ raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
576
+
577
+ t0, tf = map(float, t_span)
578
+
579
+ if args is not None:
580
+ # Wrap the user's fun (and jac, if given) in lambdas to hide the
581
+ # additional parameters. Pass in the original fun as a keyword
582
+ # argument to keep it in the scope of the lambda.
583
+ try:
584
+ _ = [*(args)]
585
+ except TypeError as exp:
586
+ suggestion_tuple = (
587
+ "Supplied 'args' cannot be unpacked. Please supply `args`"
588
+ f" as a tuple (e.g. `args=({args},)`)"
589
+ )
590
+ raise TypeError(suggestion_tuple) from exp
591
+
592
+ def fun(t, x, fun=fun):
593
+ return fun(t, x, *args)
594
+ jac = options.get('jac')
595
+ if callable(jac):
596
+ options['jac'] = lambda t, x: jac(t, x, *args)
597
+
598
+ if t_eval is not None:
599
+ t_eval = np.asarray(t_eval)
600
+ if t_eval.ndim != 1:
601
+ raise ValueError("`t_eval` must be 1-dimensional.")
602
+
603
+ if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
604
+ raise ValueError("Values in `t_eval` are not within `t_span`.")
605
+
606
+ d = np.diff(t_eval)
607
+ if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
608
+ raise ValueError("Values in `t_eval` are not properly sorted.")
609
+
610
+ if tf > t0:
611
+ t_eval_i = 0
612
+ else:
613
+ # Make order of t_eval decreasing to use np.searchsorted.
614
+ t_eval = t_eval[::-1]
615
+ # This will be an upper bound for slices.
616
+ t_eval_i = t_eval.shape[0]
617
+
618
+ if method in METHODS:
619
+ method = METHODS[method]
620
+
621
+ solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
622
+
623
+ if t_eval is None:
624
+ ts = [t0]
625
+ ys = [y0]
626
+ elif t_eval is not None and dense_output:
627
+ ts = []
628
+ ti = [t0]
629
+ ys = []
630
+ else:
631
+ ts = []
632
+ ys = []
633
+
634
+ interpolants = []
635
+
636
+ if events is not None:
637
+ events, max_events, event_dir = prepare_events(events)
638
+ event_count = np.zeros(len(events))
639
+ if args is not None:
640
+ # Wrap user functions in lambdas to hide the additional parameters.
641
+ # The original event function is passed as a keyword argument to the
642
+ # lambda to keep the original function in scope (i.e., avoid the
643
+ # late binding closure "gotcha").
644
+ events = [lambda t, x, event=event: event(t, x, *args)
645
+ for event in events]
646
+ g = [event(t0, y0) for event in events]
647
+ t_events = [[] for _ in range(len(events))]
648
+ y_events = [[] for _ in range(len(events))]
649
+ else:
650
+ t_events = None
651
+ y_events = None
652
+
653
+ status = None
654
+ while status is None:
655
+ message = solver.step()
656
+
657
+ if solver.status == 'finished':
658
+ status = 0
659
+ elif solver.status == 'failed':
660
+ status = -1
661
+ break
662
+
663
+ t_old = solver.t_old
664
+ t = solver.t
665
+ y = solver.y
666
+
667
+ if dense_output:
668
+ sol = solver.dense_output()
669
+ interpolants.append(sol)
670
+ else:
671
+ sol = None
672
+
673
+ if events is not None:
674
+ g_new = [event(t, y) for event in events]
675
+ active_events = find_active_events(g, g_new, event_dir)
676
+ if active_events.size > 0:
677
+ if sol is None:
678
+ sol = solver.dense_output()
679
+
680
+ event_count[active_events] += 1
681
+ root_indices, roots, terminate = handle_events(
682
+ sol, events, active_events, event_count, max_events,
683
+ t_old, t)
684
+
685
+ for e, te in zip(root_indices, roots):
686
+ t_events[e].append(te)
687
+ y_events[e].append(sol(te))
688
+
689
+ if terminate:
690
+ status = 1
691
+ t = roots[-1]
692
+ y = sol(t)
693
+
694
+ g = g_new
695
+
696
+ if t_eval is None:
697
+ donot_append = (len(ts) > 1 and
698
+ ts[-1] == t and
699
+ dense_output)
700
+ if not donot_append:
701
+ ts.append(t)
702
+ ys.append(y)
703
+ else:
704
+ if len(interpolants) > 0:
705
+ interpolants.pop()
706
+ else:
707
+ # The value in t_eval equal to t will be included.
708
+ if solver.direction > 0:
709
+ t_eval_i_new = np.searchsorted(t_eval, t, side='right')
710
+ t_eval_step = t_eval[t_eval_i:t_eval_i_new]
711
+ else:
712
+ t_eval_i_new = np.searchsorted(t_eval, t, side='left')
713
+ # It has to be done with two slice operations, because
714
+ # you can't slice to 0th element inclusive using backward
715
+ # slicing.
716
+ t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1]
717
+
718
+ if t_eval_step.size > 0:
719
+ if sol is None:
720
+ sol = solver.dense_output()
721
+ ts.append(t_eval_step)
722
+ ys.append(sol(t_eval_step))
723
+ t_eval_i = t_eval_i_new
724
+
725
+ if t_eval is not None and dense_output:
726
+ ti.append(t)
727
+
728
+ message = MESSAGES.get(status, message)
729
+
730
+ if t_events is not None:
731
+ t_events = [np.asarray(te) for te in t_events]
732
+ y_events = [np.asarray(ye) for ye in y_events]
733
+
734
+ if t_eval is None:
735
+ ts = np.array(ts)
736
+ ys = np.vstack(ys).T
737
+ elif ts:
738
+ ts = np.hstack(ts)
739
+ ys = np.hstack(ys)
740
+
741
+ if dense_output:
742
+ if t_eval is None:
743
+ sol = OdeSolution(
744
+ ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False
745
+ )
746
+ else:
747
+ sol = OdeSolution(
748
+ ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False
749
+ )
750
+ else:
751
+ sol = None
752
+
753
+ return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events,
754
+ nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu,
755
+ status=status, message=message, success=status >= 0)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.integrate import ode
3
+ from .common import validate_tol, validate_first_step, warn_extraneous
4
+ from .base import OdeSolver, DenseOutput
5
+
6
+
7
+ class LSODA(OdeSolver):
8
+ """Adams/BDF method with automatic stiffness detection and switching.
9
+
10
+ This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
11
+ automatically between the nonstiff Adams method and the stiff BDF method.
12
+ The method was originally detailed in [2]_.
13
+
14
+ Parameters
15
+ ----------
16
+ fun : callable
17
+ Right-hand side of the system: the time derivative of the state ``y``
18
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
19
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
20
+ return an array of the same shape as ``y``. See `vectorized` for more
21
+ information.
22
+ t0 : float
23
+ Initial time.
24
+ y0 : array_like, shape (n,)
25
+ Initial state.
26
+ t_bound : float
27
+ Boundary time - the integration won't continue beyond it. It also
28
+ determines the direction of the integration.
29
+ first_step : float or None, optional
30
+ Initial step size. Default is ``None`` which means that the algorithm
31
+ should choose.
32
+ min_step : float, optional
33
+ Minimum allowed step size. Default is 0.0, i.e., the step size is not
34
+ bounded and determined solely by the solver.
35
+ max_step : float, optional
36
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
37
+ bounded and determined solely by the solver.
38
+ rtol, atol : float and array_like, optional
39
+ Relative and absolute tolerances. The solver keeps the local error
40
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
41
+ relative accuracy (number of correct digits), while `atol` controls
42
+ absolute accuracy (number of correct decimal places). To achieve the
43
+ desired `rtol`, set `atol` to be smaller than the smallest value that
44
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
45
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
46
+ number of correct digits is not guaranteed. Conversely, to achieve the
47
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
48
+ than `atol`. If components of y have different scales, it might be
49
+ beneficial to set different `atol` values for different components by
50
+ passing array_like with shape (n,) for `atol`. Default values are
51
+ 1e-3 for `rtol` and 1e-6 for `atol`.
52
+ jac : None or callable, optional
53
+ Jacobian matrix of the right-hand side of the system with respect to
54
+ ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
55
+ equal to ``d f_i / d y_j``. The function will be called as
56
+ ``jac(t, y)``. If None (default), the Jacobian will be
57
+ approximated by finite differences. It is generally recommended to
58
+ provide the Jacobian rather than relying on a finite-difference
59
+ approximation.
60
+ lband, uband : int or None
61
+ Parameters defining the bandwidth of the Jacobian,
62
+ i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
63
+ these requires your jac routine to return the Jacobian in the packed format:
64
+ the returned array must have ``n`` columns and ``uband + lband + 1``
65
+ rows in which Jacobian diagonals are written. Specifically
66
+ ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
67
+ in `scipy.linalg.solve_banded` (check for an illustration).
68
+ These parameters can be also used with ``jac=None`` to reduce the
69
+ number of Jacobian elements estimated by finite differences.
70
+ vectorized : bool, optional
71
+ Whether `fun` may be called in a vectorized fashion. False (default)
72
+ is recommended for this solver.
73
+
74
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
75
+ shape ``(n,)``, where ``n = len(y0)``.
76
+
77
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
78
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
79
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
80
+ the returned array is the time derivative of the state corresponding
81
+ with a column of ``y``).
82
+
83
+ Setting ``vectorized=True`` allows for faster finite difference
84
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
85
+ will result in slower execution for this solver.
86
+
87
+ Attributes
88
+ ----------
89
+ n : int
90
+ Number of equations.
91
+ status : string
92
+ Current status of the solver: 'running', 'finished' or 'failed'.
93
+ t_bound : float
94
+ Boundary time.
95
+ direction : float
96
+ Integration direction: +1 or -1.
97
+ t : float
98
+ Current time.
99
+ y : ndarray
100
+ Current state.
101
+ t_old : float
102
+ Previous time. None if no steps were made yet.
103
+ nfev : int
104
+ Number of evaluations of the right-hand side.
105
+ njev : int
106
+ Number of evaluations of the Jacobian.
107
+
108
+ References
109
+ ----------
110
+ .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
111
+ Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
112
+ pp. 55-64, 1983.
113
+ .. [2] L. Petzold, "Automatic selection of methods for solving stiff and
114
+ nonstiff systems of ordinary differential equations", SIAM Journal
115
+ on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
116
+ 1983.
117
+ """
118
+ def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
119
+ max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
120
+ uband=None, vectorized=False, **extraneous):
121
+ warn_extraneous(extraneous)
122
+ super().__init__(fun, t0, y0, t_bound, vectorized)
123
+
124
+ if first_step is None:
125
+ first_step = 0 # LSODA value for automatic selection.
126
+ else:
127
+ first_step = validate_first_step(first_step, t0, t_bound)
128
+
129
+ first_step *= self.direction
130
+
131
+ if max_step == np.inf:
132
+ max_step = 0 # LSODA value for infinity.
133
+ elif max_step <= 0:
134
+ raise ValueError("`max_step` must be positive.")
135
+
136
+ if min_step < 0:
137
+ raise ValueError("`min_step` must be nonnegative.")
138
+
139
+ rtol, atol = validate_tol(rtol, atol, self.n)
140
+
141
+ solver = ode(self.fun, jac)
142
+ solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
143
+ min_step=min_step, first_step=first_step,
144
+ lband=lband, uband=uband)
145
+ solver.set_initial_value(y0, t0)
146
+
147
+ # Inject t_bound into rwork array as needed for itask=5.
148
+ solver._integrator.rwork[0] = self.t_bound
149
+ solver._integrator.call_args[4] = solver._integrator.rwork
150
+
151
+ self._lsoda_solver = solver
152
+
153
+ def _step_impl(self):
154
+ solver = self._lsoda_solver
155
+ integrator = solver._integrator
156
+
157
+ # From lsoda.step and lsoda.integrate itask=5 means take a single
158
+ # step and do not go past t_bound.
159
+ itask = integrator.call_args[2]
160
+ integrator.call_args[2] = 5
161
+ solver._y, solver.t = integrator.run(
162
+ solver.f, solver.jac or (lambda: None), solver._y, solver.t,
163
+ self.t_bound, solver.f_params, solver.jac_params)
164
+ integrator.call_args[2] = itask
165
+
166
+ if solver.successful():
167
+ self.t = solver.t
168
+ self.y = solver._y
169
+ # From LSODA Fortran source njev is equal to nlu.
170
+ self.njev = integrator.iwork[12]
171
+ self.nlu = integrator.iwork[12]
172
+ return True, None
173
+ else:
174
+ return False, 'Unexpected istate in LSODA.'
175
+
176
+ def _dense_output_impl(self):
177
+ iwork = self._lsoda_solver._integrator.iwork
178
+ rwork = self._lsoda_solver._integrator.rwork
179
+
180
+ # We want to produce the Nordsieck history array, yh, up to the order
181
+ # used in the last successful iteration. The step size is unimportant
182
+ # because it will be scaled out in LsodaDenseOutput. Some additional
183
+ # work may be required because ODEPACK's LSODA implementation produces
184
+ # the Nordsieck history in the state needed for the next iteration.
185
+
186
+ # iwork[13] contains order from last successful iteration, while
187
+ # iwork[14] contains order to be attempted next.
188
+ order = iwork[13]
189
+
190
+ # rwork[11] contains the step size to be attempted next, while
191
+ # rwork[10] contains step size from last successful iteration.
192
+ h = rwork[11]
193
+
194
+ # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
195
+ # Nordsieck array in state needed for next iteration. We want
196
+ # the entries up to order for the last successful step so use the
197
+ # following.
198
+ yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
199
+ (self.n, order + 1), order='F').copy()
200
+ if iwork[14] < order:
201
+ # If the order is set to decrease then the final column of yh
202
+ # has not been updated within ODEPACK's LSODA
203
+ # implementation because this column will not be used in the
204
+ # next iteration. We must rescale this column to make the
205
+ # associated step size consistent with the other columns.
206
+ yh[:, -1] *= (h / rwork[10]) ** order
207
+
208
+ return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
209
+
210
+
211
+ class LsodaDenseOutput(DenseOutput):
212
+ def __init__(self, t_old, t, h, order, yh):
213
+ super().__init__(t_old, t)
214
+ self.h = h
215
+ self.yh = yh
216
+ self.p = np.arange(order + 1)
217
+
218
+ def _call_impl(self, t):
219
+ if t.ndim == 0:
220
+ x = ((t - self.t) / self.h) ** self.p
221
+ else:
222
+ x = ((t - self.t) / self.h) ** self.p[:, None]
223
+
224
+ return np.dot(self.yh, x)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import lu_factor, lu_solve
3
+ from scipy.sparse import csc_matrix, issparse, eye
4
+ from scipy.sparse.linalg import splu
5
+ from scipy.optimize._numdiff import group_columns
6
+ from .common import (validate_max_step, validate_tol, select_initial_step,
7
+ norm, num_jac, EPS, warn_extraneous,
8
+ validate_first_step)
9
+ from .base import OdeSolver, DenseOutput
10
+
11
+ S6 = 6 ** 0.5
12
+
13
+ # Butcher tableau. A is not used directly, see below.
14
+ C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
15
+ E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
16
+
17
+ # Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
18
+ # and a complex conjugate pair. They are written below.
19
+ MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
20
+ MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
21
+ - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
22
+
23
+ # These are transformation matrices.
24
+ T = np.array([
25
+ [0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
26
+ [0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
27
+ [1, 1, 0]])
28
+ TI = np.array([
29
+ [4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
30
+ [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
31
+ [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
32
+ # These linear combinations are used in the algorithm.
33
+ TI_REAL = TI[0]
34
+ TI_COMPLEX = TI[1] + 1j * TI[2]
35
+
36
+ # Interpolator coefficients.
37
+ P = np.array([
38
+ [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
39
+ [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
40
+ [1/3, -8/3, 10/3]])
41
+
42
+
43
+ NEWTON_MAXITER = 6 # Maximum number of Newton iterations.
44
+ MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
45
+ MAX_FACTOR = 10 # Maximum allowed increase in a step size.
46
+
47
+
48
+ def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
49
+ LU_real, LU_complex, solve_lu):
50
+ """Solve the collocation system.
51
+
52
+ Parameters
53
+ ----------
54
+ fun : callable
55
+ Right-hand side of the system.
56
+ t : float
57
+ Current time.
58
+ y : ndarray, shape (n,)
59
+ Current state.
60
+ h : float
61
+ Step to try.
62
+ Z0 : ndarray, shape (3, n)
63
+ Initial guess for the solution. It determines new values of `y` at
64
+ ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
65
+ scale : ndarray, shape (n)
66
+ Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
67
+ tol : float
68
+ Tolerance to which solve the system. This value is compared with
69
+ the normalized by `scale` error.
70
+ LU_real, LU_complex
71
+ LU decompositions of the system Jacobians.
72
+ solve_lu : callable
73
+ Callable which solves a linear system given a LU decomposition. The
74
+ signature is ``solve_lu(LU, b)``.
75
+
76
+ Returns
77
+ -------
78
+ converged : bool
79
+ Whether iterations converged.
80
+ n_iter : int
81
+ Number of completed iterations.
82
+ Z : ndarray, shape (3, n)
83
+ Found solution.
84
+ rate : float
85
+ The rate of convergence.
86
+ """
87
+ n = y.shape[0]
88
+ M_real = MU_REAL / h
89
+ M_complex = MU_COMPLEX / h
90
+
91
+ W = TI.dot(Z0)
92
+ Z = Z0
93
+
94
+ F = np.empty((3, n))
95
+ ch = h * C
96
+
97
+ dW_norm_old = None
98
+ dW = np.empty_like(W)
99
+ converged = False
100
+ rate = None
101
+ for k in range(NEWTON_MAXITER):
102
+ for i in range(3):
103
+ F[i] = fun(t + ch[i], y + Z[i])
104
+
105
+ if not np.all(np.isfinite(F)):
106
+ break
107
+
108
+ f_real = F.T.dot(TI_REAL) - M_real * W[0]
109
+ f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
110
+
111
+ dW_real = solve_lu(LU_real, f_real)
112
+ dW_complex = solve_lu(LU_complex, f_complex)
113
+
114
+ dW[0] = dW_real
115
+ dW[1] = dW_complex.real
116
+ dW[2] = dW_complex.imag
117
+
118
+ dW_norm = norm(dW / scale)
119
+ if dW_norm_old is not None:
120
+ rate = dW_norm / dW_norm_old
121
+
122
+ if (rate is not None and (rate >= 1 or
123
+ rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
124
+ break
125
+
126
+ W += dW
127
+ Z = T.dot(W)
128
+
129
+ if (dW_norm == 0 or
130
+ rate is not None and rate / (1 - rate) * dW_norm < tol):
131
+ converged = True
132
+ break
133
+
134
+ dW_norm_old = dW_norm
135
+
136
+ return converged, k + 1, Z, rate
137
+
138
+
139
+ def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
140
+ """Predict by which factor to increase/decrease the step size.
141
+
142
+ The algorithm is described in [1]_.
143
+
144
+ Parameters
145
+ ----------
146
+ h_abs, h_abs_old : float
147
+ Current and previous values of the step size, `h_abs_old` can be None
148
+ (see Notes).
149
+ error_norm, error_norm_old : float
150
+ Current and previous values of the error norm, `error_norm_old` can
151
+ be None (see Notes).
152
+
153
+ Returns
154
+ -------
155
+ factor : float
156
+ Predicted factor.
157
+
158
+ Notes
159
+ -----
160
+ If `h_abs_old` and `error_norm_old` are both not None then a two-step
161
+ algorithm is used, otherwise a one-step algorithm is used.
162
+
163
+ References
164
+ ----------
165
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
166
+ Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
167
+ """
168
+ if error_norm_old is None or h_abs_old is None or error_norm == 0:
169
+ multiplier = 1
170
+ else:
171
+ multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
172
+
173
+ with np.errstate(divide='ignore'):
174
+ factor = min(1, multiplier) * error_norm ** -0.25
175
+
176
+ return factor
177
+
178
+
179
+ class Radau(OdeSolver):
180
+ """Implicit Runge-Kutta method of Radau IIA family of order 5.
181
+
182
+ The implementation follows [1]_. The error is controlled with a
183
+ third-order accurate embedded formula. A cubic polynomial which satisfies
184
+ the collocation conditions is used for the dense output.
185
+
186
+ Parameters
187
+ ----------
188
+ fun : callable
189
+ Right-hand side of the system: the time derivative of the state ``y``
190
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
191
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
192
+ return an array of the same shape as ``y``. See `vectorized` for more
193
+ information.
194
+ t0 : float
195
+ Initial time.
196
+ y0 : array_like, shape (n,)
197
+ Initial state.
198
+ t_bound : float
199
+ Boundary time - the integration won't continue beyond it. It also
200
+ determines the direction of the integration.
201
+ first_step : float or None, optional
202
+ Initial step size. Default is ``None`` which means that the algorithm
203
+ should choose.
204
+ max_step : float, optional
205
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
206
+ bounded and determined solely by the solver.
207
+ rtol, atol : float and array_like, optional
208
+ Relative and absolute tolerances. The solver keeps the local error
209
+ estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
210
+ relative accuracy (number of correct digits), while `atol` controls
211
+ absolute accuracy (number of correct decimal places). To achieve the
212
+ desired `rtol`, set `atol` to be smaller than the smallest value that
213
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
214
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
215
+ number of correct digits is not guaranteed. Conversely, to achieve the
216
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
217
+ than `atol`. If components of y have different scales, it might be
218
+ beneficial to set different `atol` values for different components by
219
+ passing array_like with shape (n,) for `atol`. Default values are
220
+ 1e-3 for `rtol` and 1e-6 for `atol`.
221
+ jac : {None, array_like, sparse_matrix, callable}, optional
222
+ Jacobian matrix of the right-hand side of the system with respect to
223
+ y, required by this method. The Jacobian matrix has shape (n, n) and
224
+ its element (i, j) is equal to ``d f_i / d y_j``.
225
+ There are three ways to define the Jacobian:
226
+
227
+ * If array_like or sparse_matrix, the Jacobian is assumed to
228
+ be constant.
229
+ * If callable, the Jacobian is assumed to depend on both
230
+ t and y; it will be called as ``jac(t, y)`` as necessary.
231
+ For the 'Radau' and 'BDF' methods, the return value might be a
232
+ sparse matrix.
233
+ * If None (default), the Jacobian will be approximated by
234
+ finite differences.
235
+
236
+ It is generally recommended to provide the Jacobian rather than
237
+ relying on a finite-difference approximation.
238
+ jac_sparsity : {None, array_like, sparse matrix}, optional
239
+ Defines a sparsity structure of the Jacobian matrix for a
240
+ finite-difference approximation. Its shape must be (n, n). This argument
241
+ is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
242
+ elements in *each* row, providing the sparsity structure will greatly
243
+ speed up the computations [2]_. A zero entry means that a corresponding
244
+ element in the Jacobian is always zero. If None (default), the Jacobian
245
+ is assumed to be dense.
246
+ vectorized : bool, optional
247
+ Whether `fun` can be called in a vectorized fashion. Default is False.
248
+
249
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
250
+ shape ``(n,)``, where ``n = len(y0)``.
251
+
252
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
253
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
254
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
255
+ the returned array is the time derivative of the state corresponding
256
+ with a column of ``y``).
257
+
258
+ Setting ``vectorized=True`` allows for faster finite difference
259
+ approximation of the Jacobian by this method, but may result in slower
260
+ execution overall in some circumstances (e.g. small ``len(y0)``).
261
+
262
+ Attributes
263
+ ----------
264
+ n : int
265
+ Number of equations.
266
+ status : string
267
+ Current status of the solver: 'running', 'finished' or 'failed'.
268
+ t_bound : float
269
+ Boundary time.
270
+ direction : float
271
+ Integration direction: +1 or -1.
272
+ t : float
273
+ Current time.
274
+ y : ndarray
275
+ Current state.
276
+ t_old : float
277
+ Previous time. None if no steps were made yet.
278
+ step_size : float
279
+ Size of the last successful step. None if no steps were made yet.
280
+ nfev : int
281
+ Number of evaluations of the right-hand side.
282
+ njev : int
283
+ Number of evaluations of the Jacobian.
284
+ nlu : int
285
+ Number of LU decompositions.
286
+
287
+ References
288
+ ----------
289
+ .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
290
+ Stiff and Differential-Algebraic Problems", Sec. IV.8.
291
+ .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
292
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
293
+ and its Applications, 13, pp. 117-120, 1974.
294
+ """
295
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
296
+ rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
297
+ vectorized=False, first_step=None, **extraneous):
298
+ warn_extraneous(extraneous)
299
+ super().__init__(fun, t0, y0, t_bound, vectorized)
300
+ self.y_old = None
301
+ self.max_step = validate_max_step(max_step)
302
+ self.rtol, self.atol = validate_tol(rtol, atol, self.n)
303
+ self.f = self.fun(self.t, self.y)
304
+ # Select initial step assuming the same order which is used to control
305
+ # the error.
306
+ if first_step is None:
307
+ self.h_abs = select_initial_step(
308
+ self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
309
+ 3, self.rtol, self.atol)
310
+ else:
311
+ self.h_abs = validate_first_step(first_step, t0, t_bound)
312
+ self.h_abs_old = None
313
+ self.error_norm_old = None
314
+
315
+ self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
316
+ self.sol = None
317
+
318
+ self.jac_factor = None
319
+ self.jac, self.J = self._validate_jac(jac, jac_sparsity)
320
+ if issparse(self.J):
321
+ def lu(A):
322
+ self.nlu += 1
323
+ return splu(A)
324
+
325
+ def solve_lu(LU, b):
326
+ return LU.solve(b)
327
+
328
+ I = eye(self.n, format='csc')
329
+ else:
330
+ def lu(A):
331
+ self.nlu += 1
332
+ return lu_factor(A, overwrite_a=True)
333
+
334
+ def solve_lu(LU, b):
335
+ return lu_solve(LU, b, overwrite_b=True)
336
+
337
+ I = np.identity(self.n)
338
+
339
+ self.lu = lu
340
+ self.solve_lu = solve_lu
341
+ self.I = I
342
+
343
+ self.current_jac = True
344
+ self.LU_real = None
345
+ self.LU_complex = None
346
+ self.Z = None
347
+
348
+ def _validate_jac(self, jac, sparsity):
349
+ t0 = self.t
350
+ y0 = self.y
351
+
352
+ if jac is None:
353
+ if sparsity is not None:
354
+ if issparse(sparsity):
355
+ sparsity = csc_matrix(sparsity)
356
+ groups = group_columns(sparsity)
357
+ sparsity = (sparsity, groups)
358
+
359
+ def jac_wrapped(t, y, f):
360
+ self.njev += 1
361
+ J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
362
+ self.atol, self.jac_factor,
363
+ sparsity)
364
+ return J
365
+ J = jac_wrapped(t0, y0, self.f)
366
+ elif callable(jac):
367
+ J = jac(t0, y0)
368
+ self.njev = 1
369
+ if issparse(J):
370
+ J = csc_matrix(J)
371
+
372
+ def jac_wrapped(t, y, _=None):
373
+ self.njev += 1
374
+ return csc_matrix(jac(t, y), dtype=float)
375
+
376
+ else:
377
+ J = np.asarray(J, dtype=float)
378
+
379
+ def jac_wrapped(t, y, _=None):
380
+ self.njev += 1
381
+ return np.asarray(jac(t, y), dtype=float)
382
+
383
+ if J.shape != (self.n, self.n):
384
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
385
+ f" but actually has {J.shape}.")
386
+ else:
387
+ if issparse(jac):
388
+ J = csc_matrix(jac)
389
+ else:
390
+ J = np.asarray(jac, dtype=float)
391
+
392
+ if J.shape != (self.n, self.n):
393
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
394
+ f" but actually has {J.shape}.")
395
+ jac_wrapped = None
396
+
397
+ return jac_wrapped, J
398
+
399
+ def _step_impl(self):
400
+ t = self.t
401
+ y = self.y
402
+ f = self.f
403
+
404
+ max_step = self.max_step
405
+ atol = self.atol
406
+ rtol = self.rtol
407
+
408
+ min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
409
+ if self.h_abs > max_step:
410
+ h_abs = max_step
411
+ h_abs_old = None
412
+ error_norm_old = None
413
+ elif self.h_abs < min_step:
414
+ h_abs = min_step
415
+ h_abs_old = None
416
+ error_norm_old = None
417
+ else:
418
+ h_abs = self.h_abs
419
+ h_abs_old = self.h_abs_old
420
+ error_norm_old = self.error_norm_old
421
+
422
+ J = self.J
423
+ LU_real = self.LU_real
424
+ LU_complex = self.LU_complex
425
+
426
+ current_jac = self.current_jac
427
+ jac = self.jac
428
+
429
+ rejected = False
430
+ step_accepted = False
431
+ message = None
432
+ while not step_accepted:
433
+ if h_abs < min_step:
434
+ return False, self.TOO_SMALL_STEP
435
+
436
+ h = h_abs * self.direction
437
+ t_new = t + h
438
+
439
+ if self.direction * (t_new - self.t_bound) > 0:
440
+ t_new = self.t_bound
441
+
442
+ h = t_new - t
443
+ h_abs = np.abs(h)
444
+
445
+ if self.sol is None:
446
+ Z0 = np.zeros((3, y.shape[0]))
447
+ else:
448
+ Z0 = self.sol(t + h * C).T - y
449
+
450
+ scale = atol + np.abs(y) * rtol
451
+
452
+ converged = False
453
+ while not converged:
454
+ if LU_real is None or LU_complex is None:
455
+ LU_real = self.lu(MU_REAL / h * self.I - J)
456
+ LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
457
+
458
+ converged, n_iter, Z, rate = solve_collocation_system(
459
+ self.fun, t, y, h, Z0, scale, self.newton_tol,
460
+ LU_real, LU_complex, self.solve_lu)
461
+
462
+ if not converged:
463
+ if current_jac:
464
+ break
465
+
466
+ J = self.jac(t, y, f)
467
+ current_jac = True
468
+ LU_real = None
469
+ LU_complex = None
470
+
471
+ if not converged:
472
+ h_abs *= 0.5
473
+ LU_real = None
474
+ LU_complex = None
475
+ continue
476
+
477
+ y_new = y + Z[-1]
478
+ ZE = Z.T.dot(E) / h
479
+ error = self.solve_lu(LU_real, f + ZE)
480
+ scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
481
+ error_norm = norm(error / scale)
482
+ safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
483
+ + n_iter)
484
+
485
+ if rejected and error_norm > 1:
486
+ error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
487
+ error_norm = norm(error / scale)
488
+
489
+ if error_norm > 1:
490
+ factor = predict_factor(h_abs, h_abs_old,
491
+ error_norm, error_norm_old)
492
+ h_abs *= max(MIN_FACTOR, safety * factor)
493
+
494
+ LU_real = None
495
+ LU_complex = None
496
+ rejected = True
497
+ else:
498
+ step_accepted = True
499
+
500
+ recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
501
+
502
+ factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
503
+ factor = min(MAX_FACTOR, safety * factor)
504
+
505
+ if not recompute_jac and factor < 1.2:
506
+ factor = 1
507
+ else:
508
+ LU_real = None
509
+ LU_complex = None
510
+
511
+ f_new = self.fun(t_new, y_new)
512
+ if recompute_jac:
513
+ J = jac(t_new, y_new, f_new)
514
+ current_jac = True
515
+ elif jac is not None:
516
+ current_jac = False
517
+
518
+ self.h_abs_old = self.h_abs
519
+ self.error_norm_old = error_norm
520
+
521
+ self.h_abs = h_abs * factor
522
+
523
+ self.y_old = y
524
+
525
+ self.t = t_new
526
+ self.y = y_new
527
+ self.f = f_new
528
+
529
+ self.Z = Z
530
+
531
+ self.LU_real = LU_real
532
+ self.LU_complex = LU_complex
533
+ self.current_jac = current_jac
534
+ self.J = J
535
+
536
+ self.t_old = t
537
+ self.sol = self._compute_dense_output()
538
+
539
+ return step_accepted, message
540
+
541
+ def _compute_dense_output(self):
542
+ Q = np.dot(self.Z.T, P)
543
+ return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
544
+
545
+ def _dense_output_impl(self):
546
+ return self.sol
547
+
548
+
549
+ class RadauDenseOutput(DenseOutput):
550
+ def __init__(self, t_old, t, y_old, Q):
551
+ super().__init__(t_old, t)
552
+ self.h = t - t_old
553
+ self.Q = Q
554
+ self.order = Q.shape[1] - 1
555
+ self.y_old = y_old
556
+
557
+ def _call_impl(self, t):
558
+ x = (t - self.t_old) / self.h
559
+ if t.ndim == 0:
560
+ p = np.tile(x, self.order + 1)
561
+ p = np.cumprod(p)
562
+ else:
563
+ p = np.tile(x, (self.order + 1, 1))
564
+ p = np.cumprod(p, axis=0)
565
+ # Here we don't multiply by h, not a mistake.
566
+ y = np.dot(self.Q, p)
567
+ if y.ndim == 2:
568
+ y += self.y_old[:, None]
569
+ else:
570
+ y += self.y_old
571
+
572
+ return y
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from .base import OdeSolver, DenseOutput
3
+ from .common import (validate_max_step, validate_tol, select_initial_step,
4
+ norm, warn_extraneous, validate_first_step)
5
+ from . import dop853_coefficients
6
+
7
+ # Multiply steps computed from asymptotic behaviour of errors by this.
8
+ SAFETY = 0.9
9
+
10
+ MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
11
+ MAX_FACTOR = 10 # Maximum allowed increase in a step size.
12
+
13
+
14
+ def rk_step(fun, t, y, f, h, A, B, C, K):
15
+ """Perform a single Runge-Kutta step.
16
+
17
+ This function computes a prediction of an explicit Runge-Kutta method and
18
+ also estimates the error of a less accurate method.
19
+
20
+ Notation for Butcher tableau is as in [1]_.
21
+
22
+ Parameters
23
+ ----------
24
+ fun : callable
25
+ Right-hand side of the system.
26
+ t : float
27
+ Current time.
28
+ y : ndarray, shape (n,)
29
+ Current state.
30
+ f : ndarray, shape (n,)
31
+ Current value of the derivative, i.e., ``fun(x, y)``.
32
+ h : float
33
+ Step to use.
34
+ A : ndarray, shape (n_stages, n_stages)
35
+ Coefficients for combining previous RK stages to compute the next
36
+ stage. For explicit methods the coefficients at and above the main
37
+ diagonal are zeros.
38
+ B : ndarray, shape (n_stages,)
39
+ Coefficients for combining RK stages for computing the final
40
+ prediction.
41
+ C : ndarray, shape (n_stages,)
42
+ Coefficients for incrementing time for consecutive RK stages.
43
+ The value for the first stage is always zero.
44
+ K : ndarray, shape (n_stages + 1, n)
45
+ Storage array for putting RK stages here. Stages are stored in rows.
46
+ The last row is a linear combination of the previous rows with
47
+ coefficients
48
+
49
+ Returns
50
+ -------
51
+ y_new : ndarray, shape (n,)
52
+ Solution at t + h computed with a higher accuracy.
53
+ f_new : ndarray, shape (n,)
54
+ Derivative ``fun(t + h, y_new)``.
55
+
56
+ References
57
+ ----------
58
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
59
+ Equations I: Nonstiff Problems", Sec. II.4.
60
+ """
61
+ K[0] = f
62
+ for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
63
+ dy = np.dot(K[:s].T, a[:s]) * h
64
+ K[s] = fun(t + c * h, y + dy)
65
+
66
+ y_new = y + h * np.dot(K[:-1].T, B)
67
+ f_new = fun(t + h, y_new)
68
+
69
+ K[-1] = f_new
70
+
71
+ return y_new, f_new
72
+
73
+
74
+ class RungeKutta(OdeSolver):
75
+ """Base class for explicit Runge-Kutta methods."""
76
+ C: np.ndarray = NotImplemented
77
+ A: np.ndarray = NotImplemented
78
+ B: np.ndarray = NotImplemented
79
+ E: np.ndarray = NotImplemented
80
+ P: np.ndarray = NotImplemented
81
+ order: int = NotImplemented
82
+ error_estimator_order: int = NotImplemented
83
+ n_stages: int = NotImplemented
84
+
85
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
86
+ rtol=1e-3, atol=1e-6, vectorized=False,
87
+ first_step=None, **extraneous):
88
+ warn_extraneous(extraneous)
89
+ super().__init__(fun, t0, y0, t_bound, vectorized,
90
+ support_complex=True)
91
+ self.y_old = None
92
+ self.max_step = validate_max_step(max_step)
93
+ self.rtol, self.atol = validate_tol(rtol, atol, self.n)
94
+ self.f = self.fun(self.t, self.y)
95
+ if first_step is None:
96
+ self.h_abs = select_initial_step(
97
+ self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
98
+ self.error_estimator_order, self.rtol, self.atol)
99
+ else:
100
+ self.h_abs = validate_first_step(first_step, t0, t_bound)
101
+ self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
102
+ self.error_exponent = -1 / (self.error_estimator_order + 1)
103
+ self.h_previous = None
104
+
105
+ def _estimate_error(self, K, h):
106
+ return np.dot(K.T, self.E) * h
107
+
108
+ def _estimate_error_norm(self, K, h, scale):
109
+ return norm(self._estimate_error(K, h) / scale)
110
+
111
+ def _step_impl(self):
112
+ t = self.t
113
+ y = self.y
114
+
115
+ max_step = self.max_step
116
+ rtol = self.rtol
117
+ atol = self.atol
118
+
119
+ min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
120
+
121
+ if self.h_abs > max_step:
122
+ h_abs = max_step
123
+ elif self.h_abs < min_step:
124
+ h_abs = min_step
125
+ else:
126
+ h_abs = self.h_abs
127
+
128
+ step_accepted = False
129
+ step_rejected = False
130
+
131
+ while not step_accepted:
132
+ if h_abs < min_step:
133
+ return False, self.TOO_SMALL_STEP
134
+
135
+ h = h_abs * self.direction
136
+ t_new = t + h
137
+
138
+ if self.direction * (t_new - self.t_bound) > 0:
139
+ t_new = self.t_bound
140
+
141
+ h = t_new - t
142
+ h_abs = np.abs(h)
143
+
144
+ y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
145
+ self.B, self.C, self.K)
146
+ scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
147
+ error_norm = self._estimate_error_norm(self.K, h, scale)
148
+
149
+ if error_norm < 1:
150
+ if error_norm == 0:
151
+ factor = MAX_FACTOR
152
+ else:
153
+ factor = min(MAX_FACTOR,
154
+ SAFETY * error_norm ** self.error_exponent)
155
+
156
+ if step_rejected:
157
+ factor = min(1, factor)
158
+
159
+ h_abs *= factor
160
+
161
+ step_accepted = True
162
+ else:
163
+ h_abs *= max(MIN_FACTOR,
164
+ SAFETY * error_norm ** self.error_exponent)
165
+ step_rejected = True
166
+
167
+ self.h_previous = h
168
+ self.y_old = y
169
+
170
+ self.t = t_new
171
+ self.y = y_new
172
+
173
+ self.h_abs = h_abs
174
+ self.f = f_new
175
+
176
+ return True, None
177
+
178
+ def _dense_output_impl(self):
179
+ Q = self.K.T.dot(self.P)
180
+ return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
181
+
182
+
183
+ class RK23(RungeKutta):
184
+ """Explicit Runge-Kutta method of order 3(2).
185
+
186
+ This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
187
+ assuming accuracy of the second-order method, but steps are taken using the
188
+ third-order accurate formula (local extrapolation is done). A cubic Hermite
189
+ polynomial is used for the dense output.
190
+
191
+ Can be applied in the complex domain.
192
+
193
+ Parameters
194
+ ----------
195
+ fun : callable
196
+ Right-hand side of the system: the time derivative of the state ``y``
197
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
198
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
199
+ return an array of the same shape as ``y``. See `vectorized` for more
200
+ information.
201
+ t0 : float
202
+ Initial time.
203
+ y0 : array_like, shape (n,)
204
+ Initial state.
205
+ t_bound : float
206
+ Boundary time - the integration won't continue beyond it. It also
207
+ determines the direction of the integration.
208
+ first_step : float or None, optional
209
+ Initial step size. Default is ``None`` which means that the algorithm
210
+ should choose.
211
+ max_step : float, optional
212
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
213
+ bounded and determined solely by the solver.
214
+ rtol, atol : float and array_like, optional
215
+ Relative and absolute tolerances. The solver keeps the local error
216
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
217
+ relative accuracy (number of correct digits), while `atol` controls
218
+ absolute accuracy (number of correct decimal places). To achieve the
219
+ desired `rtol`, set `atol` to be smaller than the smallest value that
220
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
221
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
222
+ number of correct digits is not guaranteed. Conversely, to achieve the
223
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
224
+ than `atol`. If components of y have different scales, it might be
225
+ beneficial to set different `atol` values for different components by
226
+ passing array_like with shape (n,) for `atol`. Default values are
227
+ 1e-3 for `rtol` and 1e-6 for `atol`.
228
+ vectorized : bool, optional
229
+ Whether `fun` may be called in a vectorized fashion. False (default)
230
+ is recommended for this solver.
231
+
232
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
233
+ shape ``(n,)``, where ``n = len(y0)``.
234
+
235
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
236
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
237
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
238
+ the returned array is the time derivative of the state corresponding
239
+ with a column of ``y``).
240
+
241
+ Setting ``vectorized=True`` allows for faster finite difference
242
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
243
+ will result in slower execution for this solver.
244
+
245
+ Attributes
246
+ ----------
247
+ n : int
248
+ Number of equations.
249
+ status : string
250
+ Current status of the solver: 'running', 'finished' or 'failed'.
251
+ t_bound : float
252
+ Boundary time.
253
+ direction : float
254
+ Integration direction: +1 or -1.
255
+ t : float
256
+ Current time.
257
+ y : ndarray
258
+ Current state.
259
+ t_old : float
260
+ Previous time. None if no steps were made yet.
261
+ step_size : float
262
+ Size of the last successful step. None if no steps were made yet.
263
+ nfev : int
264
+ Number evaluations of the system's right-hand side.
265
+ njev : int
266
+ Number of evaluations of the Jacobian.
267
+ Is always 0 for this solver as it does not use the Jacobian.
268
+ nlu : int
269
+ Number of LU decompositions. Is always 0 for this solver.
270
+
271
+ References
272
+ ----------
273
+ .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
274
+ Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
275
+ """
276
+ order = 3
277
+ error_estimator_order = 2
278
+ n_stages = 3
279
+ C = np.array([0, 1/2, 3/4])
280
+ A = np.array([
281
+ [0, 0, 0],
282
+ [1/2, 0, 0],
283
+ [0, 3/4, 0]
284
+ ])
285
+ B = np.array([2/9, 1/3, 4/9])
286
+ E = np.array([5/72, -1/12, -1/9, 1/8])
287
+ P = np.array([[1, -4 / 3, 5 / 9],
288
+ [0, 1, -2/3],
289
+ [0, 4/3, -8/9],
290
+ [0, -1, 1]])
291
+
292
+
293
+ class RK45(RungeKutta):
294
+ """Explicit Runge-Kutta method of order 5(4).
295
+
296
+ This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
297
+ assuming accuracy of the fourth-order method accuracy, but steps are taken
298
+ using the fifth-order accurate formula (local extrapolation is done).
299
+ A quartic interpolation polynomial is used for the dense output [2]_.
300
+
301
+ Can be applied in the complex domain.
302
+
303
+ Parameters
304
+ ----------
305
+ fun : callable
306
+ Right-hand side of the system. The calling signature is ``fun(t, y)``.
307
+ Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
308
+ It can either have shape (n,); then ``fun`` must return array_like with
309
+ shape (n,). Alternatively it can have shape (n, k); then ``fun``
310
+ must return an array_like with shape (n, k), i.e., each column
311
+ corresponds to a single column in ``y``. The choice between the two
312
+ options is determined by `vectorized` argument (see below).
313
+ t0 : float
314
+ Initial time.
315
+ y0 : array_like, shape (n,)
316
+ Initial state.
317
+ t_bound : float
318
+ Boundary time - the integration won't continue beyond it. It also
319
+ determines the direction of the integration.
320
+ first_step : float or None, optional
321
+ Initial step size. Default is ``None`` which means that the algorithm
322
+ should choose.
323
+ max_step : float, optional
324
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
325
+ bounded and determined solely by the solver.
326
+ rtol, atol : float and array_like, optional
327
+ Relative and absolute tolerances. The solver keeps the local error
328
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
329
+ relative accuracy (number of correct digits), while `atol` controls
330
+ absolute accuracy (number of correct decimal places). To achieve the
331
+ desired `rtol`, set `atol` to be smaller than the smallest value that
332
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
333
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
334
+ number of correct digits is not guaranteed. Conversely, to achieve the
335
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
336
+ than `atol`. If components of y have different scales, it might be
337
+ beneficial to set different `atol` values for different components by
338
+ passing array_like with shape (n,) for `atol`. Default values are
339
+ 1e-3 for `rtol` and 1e-6 for `atol`.
340
+ vectorized : bool, optional
341
+ Whether `fun` is implemented in a vectorized fashion. Default is False.
342
+
343
+ Attributes
344
+ ----------
345
+ n : int
346
+ Number of equations.
347
+ status : string
348
+ Current status of the solver: 'running', 'finished' or 'failed'.
349
+ t_bound : float
350
+ Boundary time.
351
+ direction : float
352
+ Integration direction: +1 or -1.
353
+ t : float
354
+ Current time.
355
+ y : ndarray
356
+ Current state.
357
+ t_old : float
358
+ Previous time. None if no steps were made yet.
359
+ step_size : float
360
+ Size of the last successful step. None if no steps were made yet.
361
+ nfev : int
362
+ Number evaluations of the system's right-hand side.
363
+ njev : int
364
+ Number of evaluations of the Jacobian.
365
+ Is always 0 for this solver as it does not use the Jacobian.
366
+ nlu : int
367
+ Number of LU decompositions. Is always 0 for this solver.
368
+
369
+ References
370
+ ----------
371
+ .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
372
+ formulae", Journal of Computational and Applied Mathematics, Vol. 6,
373
+ No. 1, pp. 19-26, 1980.
374
+ .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
375
+ of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
376
+ """
377
+ order = 5
378
+ error_estimator_order = 4
379
+ n_stages = 6
380
+ C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
381
+ A = np.array([
382
+ [0, 0, 0, 0, 0],
383
+ [1/5, 0, 0, 0, 0],
384
+ [3/40, 9/40, 0, 0, 0],
385
+ [44/45, -56/15, 32/9, 0, 0],
386
+ [19372/6561, -25360/2187, 64448/6561, -212/729, 0],
387
+ [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
388
+ ])
389
+ B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
390
+ E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
391
+ 1/40])
392
+ # Corresponds to the optimum value of c_6 from [2]_.
393
+ P = np.array([
394
+ [1, -8048581381/2820520608, 8663915743/2820520608,
395
+ -12715105075/11282082432],
396
+ [0, 0, 0, 0],
397
+ [0, 131558114200/32700410799, -68118460800/10900136933,
398
+ 87487479700/32700410799],
399
+ [0, -1754552775/470086768, 14199869525/1410260304,
400
+ -10690763975/1880347072],
401
+ [0, 127303824393/49829197408, -318862633887/49829197408,
402
+ 701980252875 / 199316789632],
403
+ [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
404
+ [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
405
+
406
+
407
+ class DOP853(RungeKutta):
408
+ """Explicit Runge-Kutta method of order 8.
409
+
410
+ This is a Python implementation of "DOP853" algorithm originally written
411
+ in Fortran [1]_, [2]_. Note that this is not a literal translation, but
412
+ the algorithmic core and coefficients are the same.
413
+
414
+ Can be applied in the complex domain.
415
+
416
+ Parameters
417
+ ----------
418
+ fun : callable
419
+ Right-hand side of the system. The calling signature is ``fun(t, y)``.
420
+ Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
421
+ It can either have shape (n,); then ``fun`` must return array_like with
422
+ shape (n,). Alternatively it can have shape (n, k); then ``fun``
423
+ must return an array_like with shape (n, k), i.e. each column
424
+ corresponds to a single column in ``y``. The choice between the two
425
+ options is determined by `vectorized` argument (see below).
426
+ t0 : float
427
+ Initial time.
428
+ y0 : array_like, shape (n,)
429
+ Initial state.
430
+ t_bound : float
431
+ Boundary time - the integration won't continue beyond it. It also
432
+ determines the direction of the integration.
433
+ first_step : float or None, optional
434
+ Initial step size. Default is ``None`` which means that the algorithm
435
+ should choose.
436
+ max_step : float, optional
437
+ Maximum allowed step size. Default is np.inf, i.e. the step size is not
438
+ bounded and determined solely by the solver.
439
+ rtol, atol : float and array_like, optional
440
+ Relative and absolute tolerances. The solver keeps the local error
441
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
442
+ relative accuracy (number of correct digits), while `atol` controls
443
+ absolute accuracy (number of correct decimal places). To achieve the
444
+ desired `rtol`, set `atol` to be smaller than the smallest value that
445
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
446
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
447
+ number of correct digits is not guaranteed. Conversely, to achieve the
448
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
449
+ than `atol`. If components of y have different scales, it might be
450
+ beneficial to set different `atol` values for different components by
451
+ passing array_like with shape (n,) for `atol`. Default values are
452
+ 1e-3 for `rtol` and 1e-6 for `atol`.
453
+ vectorized : bool, optional
454
+ Whether `fun` is implemented in a vectorized fashion. Default is False.
455
+
456
+ Attributes
457
+ ----------
458
+ n : int
459
+ Number of equations.
460
+ status : string
461
+ Current status of the solver: 'running', 'finished' or 'failed'.
462
+ t_bound : float
463
+ Boundary time.
464
+ direction : float
465
+ Integration direction: +1 or -1.
466
+ t : float
467
+ Current time.
468
+ y : ndarray
469
+ Current state.
470
+ t_old : float
471
+ Previous time. None if no steps were made yet.
472
+ step_size : float
473
+ Size of the last successful step. None if no steps were made yet.
474
+ nfev : int
475
+ Number evaluations of the system's right-hand side.
476
+ njev : int
477
+ Number of evaluations of the Jacobian. Is always 0 for this solver
478
+ as it does not use the Jacobian.
479
+ nlu : int
480
+ Number of LU decompositions. Is always 0 for this solver.
481
+
482
+ References
483
+ ----------
484
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
485
+ Equations I: Nonstiff Problems", Sec. II.
486
+ .. [2] `Page with original Fortran code of DOP853
487
+ <http://www.unige.ch/~hairer/software.html>`_.
488
+ """
489
+ n_stages = dop853_coefficients.N_STAGES
490
+ order = 8
491
+ error_estimator_order = 7
492
+ A = dop853_coefficients.A[:n_stages, :n_stages]
493
+ B = dop853_coefficients.B
494
+ C = dop853_coefficients.C[:n_stages]
495
+ E3 = dop853_coefficients.E3
496
+ E5 = dop853_coefficients.E5
497
+ D = dop853_coefficients.D
498
+
499
+ A_EXTRA = dop853_coefficients.A[n_stages + 1:]
500
+ C_EXTRA = dop853_coefficients.C[n_stages + 1:]
501
+
502
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
503
+ rtol=1e-3, atol=1e-6, vectorized=False,
504
+ first_step=None, **extraneous):
505
+ super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
506
+ vectorized, first_step, **extraneous)
507
+ self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
508
+ self.n), dtype=self.y.dtype)
509
+ self.K = self.K_extended[:self.n_stages + 1]
510
+
511
+ def _estimate_error(self, K, h): # Left for testing purposes.
512
+ err5 = np.dot(K.T, self.E5)
513
+ err3 = np.dot(K.T, self.E3)
514
+ denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
515
+ correction_factor = np.ones_like(err5)
516
+ mask = denom > 0
517
+ correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
518
+ return h * err5 * correction_factor
519
+
520
+ def _estimate_error_norm(self, K, h, scale):
521
+ err5 = np.dot(K.T, self.E5) / scale
522
+ err3 = np.dot(K.T, self.E3) / scale
523
+ err5_norm_2 = np.linalg.norm(err5)**2
524
+ err3_norm_2 = np.linalg.norm(err3)**2
525
+ if err5_norm_2 == 0 and err3_norm_2 == 0:
526
+ return 0.0
527
+ denom = err5_norm_2 + 0.01 * err3_norm_2
528
+ return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
529
+
530
+ def _dense_output_impl(self):
531
+ K = self.K_extended
532
+ h = self.h_previous
533
+ for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
534
+ start=self.n_stages + 1):
535
+ dy = np.dot(K[:s].T, a[:s]) * h
536
+ K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
537
+
538
+ F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
539
+ dtype=self.y_old.dtype)
540
+
541
+ f_old = K[0]
542
+ delta_y = self.y - self.y_old
543
+
544
+ F[0] = delta_y
545
+ F[1] = h * f_old - delta_y
546
+ F[2] = 2 * delta_y - h * (self.f + f_old)
547
+ F[3:] = h * np.dot(self.D, K)
548
+
549
+ return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
550
+
551
+
552
+ class RkDenseOutput(DenseOutput):
553
+ def __init__(self, t_old, t, y_old, Q):
554
+ super().__init__(t_old, t)
555
+ self.h = t - t_old
556
+ self.Q = Q
557
+ self.order = Q.shape[1] - 1
558
+ self.y_old = y_old
559
+
560
+ def _call_impl(self, t):
561
+ x = (t - self.t_old) / self.h
562
+ if t.ndim == 0:
563
+ p = np.tile(x, self.order + 1)
564
+ p = np.cumprod(p)
565
+ else:
566
+ p = np.tile(x, (self.order + 1, 1))
567
+ p = np.cumprod(p, axis=0)
568
+ y = self.h * np.dot(self.Q, p)
569
+ if y.ndim == 2:
570
+ y += self.y_old[:, None]
571
+ else:
572
+ y += self.y_old
573
+
574
+ return y
575
+
576
+
577
+ class Dop853DenseOutput(DenseOutput):
578
+ def __init__(self, t_old, t, y_old, F):
579
+ super().__init__(t_old, t)
580
+ self.h = t - t_old
581
+ self.F = F
582
+ self.y_old = y_old
583
+
584
+ def _call_impl(self, t):
585
+ x = (t - self.t_old) / self.h
586
+
587
+ if t.ndim == 0:
588
+ y = np.zeros_like(self.y_old)
589
+ else:
590
+ x = x[:, None]
591
+ y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
592
+
593
+ for i, f in enumerate(reversed(self.F)):
594
+ y += f
595
+ if i % 2 == 0:
596
+ y *= x
597
+ else:
598
+ y *= 1 - x
599
+ y += self.y_old
600
+
601
+ return y.T
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py ADDED
@@ -0,0 +1,1287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+ from numpy.testing import (assert_, assert_allclose, assert_array_less,
3
+ assert_equal, assert_no_warnings, suppress_warnings)
4
+ import pytest
5
+ from pytest import raises as assert_raises
6
+ import numpy as np
7
+ from scipy.optimize._numdiff import group_columns
8
+ from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
9
+ from scipy.integrate import OdeSolution
10
+ from scipy.integrate._ivp.common import num_jac, select_initial_step
11
+ from scipy.integrate._ivp.base import ConstantDenseOutput
12
+ from scipy.sparse import coo_matrix, csc_matrix
13
+
14
+
15
+ def fun_zero(t, y):
16
+ return np.zeros_like(y)
17
+
18
+
19
+ def fun_linear(t, y):
20
+ return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
21
+
22
+
23
+ def jac_linear():
24
+ return np.array([[-1, -5], [1, 1]])
25
+
26
+
27
+ def sol_linear(t):
28
+ return np.vstack((-5 * np.sin(2 * t),
29
+ 2 * np.cos(2 * t) + np.sin(2 * t)))
30
+
31
+
32
+ def fun_rational(t, y):
33
+ return np.array([y[1] / t,
34
+ y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
35
+
36
+
37
+ def fun_rational_vectorized(t, y):
38
+ return np.vstack((y[1] / t,
39
+ y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
40
+
41
+
42
+ def jac_rational(t, y):
43
+ return np.array([
44
+ [0, 1 / t],
45
+ [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
46
+ (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
47
+ ])
48
+
49
+
50
+ def jac_rational_sparse(t, y):
51
+ return csc_matrix([
52
+ [0, 1 / t],
53
+ [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
54
+ (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
55
+ ])
56
+
57
+
58
+ def sol_rational(t):
59
+ return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
60
+
61
+
62
+ def fun_medazko(t, y):
63
+ n = y.shape[0] // 2
64
+ k = 100
65
+ c = 4
66
+
67
+ phi = 2 if t <= 5 else 0
68
+ y = np.hstack((phi, 0, y, y[-2]))
69
+
70
+ d = 1 / n
71
+ j = np.arange(n) + 1
72
+ alpha = 2 * (j * d - 1) ** 3 / c ** 2
73
+ beta = (j * d - 1) ** 4 / c ** 2
74
+
75
+ j_2_p1 = 2 * j + 2
76
+ j_2_m3 = 2 * j - 2
77
+ j_2_m1 = 2 * j
78
+ j_2 = 2 * j + 1
79
+
80
+ f = np.empty(2 * n)
81
+ f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
82
+ beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
83
+ k * y[j_2_m1] * y[j_2])
84
+ f[1::2] = -k * y[j_2] * y[j_2_m1]
85
+
86
+ return f
87
+
88
+
89
+ def medazko_sparsity(n):
90
+ cols = []
91
+ rows = []
92
+
93
+ i = np.arange(n) * 2
94
+
95
+ cols.append(i[1:])
96
+ rows.append(i[1:] - 2)
97
+
98
+ cols.append(i)
99
+ rows.append(i)
100
+
101
+ cols.append(i)
102
+ rows.append(i + 1)
103
+
104
+ cols.append(i[:-1])
105
+ rows.append(i[:-1] + 2)
106
+
107
+ i = np.arange(n) * 2 + 1
108
+
109
+ cols.append(i)
110
+ rows.append(i)
111
+
112
+ cols.append(i)
113
+ rows.append(i - 1)
114
+
115
+ cols = np.hstack(cols)
116
+ rows = np.hstack(rows)
117
+
118
+ return coo_matrix((np.ones_like(cols), (cols, rows)))
119
+
120
+
121
+ def fun_complex(t, y):
122
+ return -y
123
+
124
+
125
+ def jac_complex(t, y):
126
+ return -np.eye(y.shape[0])
127
+
128
+
129
+ def jac_complex_sparse(t, y):
130
+ return csc_matrix(jac_complex(t, y))
131
+
132
+
133
+ def sol_complex(t):
134
+ y = (0.5 + 1j) * np.exp(-t)
135
+ return y.reshape((1, -1))
136
+
137
+
138
+ def fun_event_dense_output_LSODA(t, y):
139
+ return y * (t - 2)
140
+
141
+
142
+ def jac_event_dense_output_LSODA(t, y):
143
+ return t - 2
144
+
145
+
146
+ def sol_event_dense_output_LSODA(t):
147
+ return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
148
+
149
+
150
+ def compute_error(y, y_true, rtol, atol):
151
+ e = (y - y_true) / (atol + rtol * np.abs(y_true))
152
+ return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
153
+
154
+ def test_duplicate_timestamps():
155
+ def upward_cannon(t, y):
156
+ return [y[1], -9.80665]
157
+
158
+ def hit_ground(t, y):
159
+ return y[0]
160
+
161
+ hit_ground.terminal = True
162
+ hit_ground.direction = -1
163
+
164
+ sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01],
165
+ max_step=0.05 * 0.001 / 9.80665,
166
+ events=hit_ground, dense_output=True)
167
+ assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]),
168
+ rtol=1e-5, atol=1e-8)
169
+ assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8)
170
+ assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9)
171
+ assert sol.success
172
+ assert_equal(sol.status, 1)
173
+
174
+ @pytest.mark.thread_unsafe
175
+ def test_integration():
176
+ rtol = 1e-3
177
+ atol = 1e-6
178
+ y0 = [1/3, 2/9]
179
+
180
+ for vectorized, method, t_span, jac in product(
181
+ [False, True],
182
+ ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
183
+ [[5, 9], [5, 1]],
184
+ [None, jac_rational, jac_rational_sparse]):
185
+
186
+ if vectorized:
187
+ fun = fun_rational_vectorized
188
+ else:
189
+ fun = fun_rational
190
+
191
+ with suppress_warnings() as sup:
192
+ sup.filter(UserWarning,
193
+ "The following arguments have no effect for a chosen "
194
+ "solver: `jac`")
195
+ res = solve_ivp(fun, t_span, y0, rtol=rtol,
196
+ atol=atol, method=method, dense_output=True,
197
+ jac=jac, vectorized=vectorized)
198
+ assert_equal(res.t[0], t_span[0])
199
+ assert_(res.t_events is None)
200
+ assert_(res.y_events is None)
201
+ assert_(res.success)
202
+ assert_equal(res.status, 0)
203
+
204
+ if method == 'DOP853':
205
+ # DOP853 spends more functions evaluation because it doesn't
206
+ # have enough time to develop big enough step size.
207
+ assert_(res.nfev < 50)
208
+ else:
209
+ assert_(res.nfev < 40)
210
+
211
+ if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
212
+ assert_equal(res.njev, 0)
213
+ assert_equal(res.nlu, 0)
214
+ else:
215
+ assert_(0 < res.njev < 3)
216
+ assert_(0 < res.nlu < 10)
217
+
218
+ y_true = sol_rational(res.t)
219
+ e = compute_error(res.y, y_true, rtol, atol)
220
+ assert_(np.all(e < 5))
221
+
222
+ tc = np.linspace(*t_span)
223
+ yc_true = sol_rational(tc)
224
+ yc = res.sol(tc)
225
+
226
+ e = compute_error(yc, yc_true, rtol, atol)
227
+ assert_(np.all(e < 5))
228
+
229
+ tc = (t_span[0] + t_span[-1]) / 2
230
+ yc_true = sol_rational(tc)
231
+ yc = res.sol(tc)
232
+
233
+ e = compute_error(yc, yc_true, rtol, atol)
234
+ assert_(np.all(e < 5))
235
+
236
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
237
+
238
+
239
+ @pytest.mark.thread_unsafe
240
+ def test_integration_complex():
241
+ rtol = 1e-3
242
+ atol = 1e-6
243
+ y0 = [0.5 + 1j]
244
+ t_span = [0, 1]
245
+ tc = np.linspace(t_span[0], t_span[1])
246
+ for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
247
+ [None, jac_complex, jac_complex_sparse]):
248
+ with suppress_warnings() as sup:
249
+ sup.filter(UserWarning,
250
+ "The following arguments have no effect for a chosen "
251
+ "solver: `jac`")
252
+ res = solve_ivp(fun_complex, t_span, y0, method=method,
253
+ dense_output=True, rtol=rtol, atol=atol, jac=jac)
254
+
255
+ assert_equal(res.t[0], t_span[0])
256
+ assert_(res.t_events is None)
257
+ assert_(res.y_events is None)
258
+ assert_(res.success)
259
+ assert_equal(res.status, 0)
260
+
261
+ if method == 'DOP853':
262
+ assert res.nfev < 35
263
+ else:
264
+ assert res.nfev < 25
265
+
266
+ if method == 'BDF':
267
+ assert_equal(res.njev, 1)
268
+ assert res.nlu < 6
269
+ else:
270
+ assert res.njev == 0
271
+ assert res.nlu == 0
272
+
273
+ y_true = sol_complex(res.t)
274
+ e = compute_error(res.y, y_true, rtol, atol)
275
+ assert np.all(e < 5)
276
+
277
+ yc_true = sol_complex(tc)
278
+ yc = res.sol(tc)
279
+ e = compute_error(yc, yc_true, rtol, atol)
280
+
281
+ assert np.all(e < 5)
282
+
283
+
284
+ @pytest.mark.fail_slow(5)
285
+ def test_integration_sparse_difference():
286
+ n = 200
287
+ t_span = [0, 20]
288
+ y0 = np.zeros(2 * n)
289
+ y0[1::2] = 1
290
+ sparsity = medazko_sparsity(n)
291
+
292
+ for method in ['BDF', 'Radau']:
293
+ res = solve_ivp(fun_medazko, t_span, y0, method=method,
294
+ jac_sparsity=sparsity)
295
+
296
+ assert_equal(res.t[0], t_span[0])
297
+ assert_(res.t_events is None)
298
+ assert_(res.y_events is None)
299
+ assert_(res.success)
300
+ assert_equal(res.status, 0)
301
+
302
+ assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
303
+ assert_allclose(res.y[79, -1], 0, atol=1e-3)
304
+ assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
305
+ assert_allclose(res.y[149, -1], 0, atol=1e-3)
306
+ assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
307
+ assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
308
+ assert_allclose(res.y[238, -1], 0, atol=1e-3)
309
+ assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
310
+
311
+
312
+ def test_integration_const_jac():
313
+ rtol = 1e-3
314
+ atol = 1e-6
315
+ y0 = [0, 2]
316
+ t_span = [0, 2]
317
+ J = jac_linear()
318
+ J_sparse = csc_matrix(J)
319
+
320
+ for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
321
+ res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
322
+ method=method, dense_output=True, jac=jac)
323
+ assert_equal(res.t[0], t_span[0])
324
+ assert_(res.t_events is None)
325
+ assert_(res.y_events is None)
326
+ assert_(res.success)
327
+ assert_equal(res.status, 0)
328
+
329
+ assert_(res.nfev < 100)
330
+ assert_equal(res.njev, 0)
331
+ assert_(0 < res.nlu < 15)
332
+
333
+ y_true = sol_linear(res.t)
334
+ e = compute_error(res.y, y_true, rtol, atol)
335
+ assert_(np.all(e < 10))
336
+
337
+ tc = np.linspace(*t_span)
338
+ yc_true = sol_linear(tc)
339
+ yc = res.sol(tc)
340
+
341
+ e = compute_error(yc, yc_true, rtol, atol)
342
+ assert_(np.all(e < 15))
343
+
344
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
345
+
346
+
347
+ @pytest.mark.slow
348
+ @pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
349
+ def test_integration_stiff(method, num_parallel_threads):
350
+ rtol = 1e-6
351
+ atol = 1e-6
352
+ y0 = [1e4, 0, 0]
353
+ tspan = [0, 1e8]
354
+
355
+ if method == 'LSODA' and num_parallel_threads > 1:
356
+ pytest.skip(reason='LSODA does not allow for concurrent calls')
357
+
358
+ def fun_robertson(t, state):
359
+ x, y, z = state
360
+ return [
361
+ -0.04 * x + 1e4 * y * z,
362
+ 0.04 * x - 1e4 * y * z - 3e7 * y * y,
363
+ 3e7 * y * y,
364
+ ]
365
+
366
+ res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
367
+ atol=atol, method=method)
368
+
369
+ # If the stiff mode is not activated correctly, these numbers will be much bigger
370
+ assert res.nfev < 5000
371
+ assert res.njev < 200
372
+
373
+
374
+ def test_events(num_parallel_threads):
375
+ def event_rational_1(t, y):
376
+ return y[0] - y[1] ** 0.7
377
+
378
+ def event_rational_2(t, y):
379
+ return y[1] ** 0.6 - y[0]
380
+
381
+ def event_rational_3(t, y):
382
+ return t - 7.4
383
+
384
+ event_rational_3.terminal = True
385
+
386
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
387
+ if method == 'LSODA' and num_parallel_threads > 1:
388
+ continue
389
+
390
+ res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
391
+ events=(event_rational_1, event_rational_2))
392
+ assert_equal(res.status, 0)
393
+ assert_equal(res.t_events[0].size, 1)
394
+ assert_equal(res.t_events[1].size, 1)
395
+ assert_(5.3 < res.t_events[0][0] < 5.7)
396
+ assert_(7.3 < res.t_events[1][0] < 7.7)
397
+
398
+ assert_equal(res.y_events[0].shape, (1, 2))
399
+ assert_equal(res.y_events[1].shape, (1, 2))
400
+ assert np.isclose(
401
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
402
+ assert np.isclose(
403
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
404
+
405
+ event_rational_1.direction = 1
406
+ event_rational_2.direction = 1
407
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
408
+ events=(event_rational_1, event_rational_2))
409
+ assert_equal(res.status, 0)
410
+ assert_equal(res.t_events[0].size, 1)
411
+ assert_equal(res.t_events[1].size, 0)
412
+ assert_(5.3 < res.t_events[0][0] < 5.7)
413
+ assert_equal(res.y_events[0].shape, (1, 2))
414
+ assert_equal(res.y_events[1].shape, (0,))
415
+ assert np.isclose(
416
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
417
+
418
+ event_rational_1.direction = -1
419
+ event_rational_2.direction = -1
420
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
421
+ events=(event_rational_1, event_rational_2))
422
+ assert_equal(res.status, 0)
423
+ assert_equal(res.t_events[0].size, 0)
424
+ assert_equal(res.t_events[1].size, 1)
425
+ assert_(7.3 < res.t_events[1][0] < 7.7)
426
+ assert_equal(res.y_events[0].shape, (0,))
427
+ assert_equal(res.y_events[1].shape, (1, 2))
428
+ assert np.isclose(
429
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
430
+
431
+ event_rational_1.direction = 0
432
+ event_rational_2.direction = 0
433
+
434
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
435
+ events=(event_rational_1, event_rational_2,
436
+ event_rational_3), dense_output=True)
437
+ assert_equal(res.status, 1)
438
+ assert_equal(res.t_events[0].size, 1)
439
+ assert_equal(res.t_events[1].size, 0)
440
+ assert_equal(res.t_events[2].size, 1)
441
+ assert_(5.3 < res.t_events[0][0] < 5.7)
442
+ assert_(7.3 < res.t_events[2][0] < 7.5)
443
+ assert_equal(res.y_events[0].shape, (1, 2))
444
+ assert_equal(res.y_events[1].shape, (0,))
445
+ assert_equal(res.y_events[2].shape, (1, 2))
446
+ assert np.isclose(
447
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
448
+ assert np.isclose(
449
+ event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
450
+
451
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
452
+ events=event_rational_1, dense_output=True)
453
+ assert_equal(res.status, 0)
454
+ assert_equal(res.t_events[0].size, 1)
455
+ assert_(5.3 < res.t_events[0][0] < 5.7)
456
+
457
+ assert_equal(res.y_events[0].shape, (1, 2))
458
+ assert np.isclose(
459
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
460
+
461
+ # Also test that termination by event doesn't break interpolants.
462
+ tc = np.linspace(res.t[0], res.t[-1])
463
+ yc_true = sol_rational(tc)
464
+ yc = res.sol(tc)
465
+ e = compute_error(yc, yc_true, 1e-3, 1e-6)
466
+ assert_(np.all(e < 5))
467
+
468
+ # Test that the y_event matches solution
469
+ assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
470
+ rtol=1e-3, atol=1e-6)
471
+
472
+ # Test in backward direction.
473
+ event_rational_1.direction = 0
474
+ event_rational_2.direction = 0
475
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
476
+ if method == 'LSODA' and num_parallel_threads > 1:
477
+ continue
478
+
479
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
480
+ events=(event_rational_1, event_rational_2))
481
+ assert_equal(res.status, 0)
482
+ assert_equal(res.t_events[0].size, 1)
483
+ assert_equal(res.t_events[1].size, 1)
484
+ assert_(5.3 < res.t_events[0][0] < 5.7)
485
+ assert_(7.3 < res.t_events[1][0] < 7.7)
486
+
487
+ assert_equal(res.y_events[0].shape, (1, 2))
488
+ assert_equal(res.y_events[1].shape, (1, 2))
489
+ assert np.isclose(
490
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
491
+ assert np.isclose(
492
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
493
+
494
+ event_rational_1.direction = -1
495
+ event_rational_2.direction = -1
496
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
497
+ events=(event_rational_1, event_rational_2))
498
+ assert_equal(res.status, 0)
499
+ assert_equal(res.t_events[0].size, 1)
500
+ assert_equal(res.t_events[1].size, 0)
501
+ assert_(5.3 < res.t_events[0][0] < 5.7)
502
+
503
+ assert_equal(res.y_events[0].shape, (1, 2))
504
+ assert_equal(res.y_events[1].shape, (0,))
505
+ assert np.isclose(
506
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
507
+
508
+ event_rational_1.direction = 1
509
+ event_rational_2.direction = 1
510
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
511
+ events=(event_rational_1, event_rational_2))
512
+ assert_equal(res.status, 0)
513
+ assert_equal(res.t_events[0].size, 0)
514
+ assert_equal(res.t_events[1].size, 1)
515
+ assert_(7.3 < res.t_events[1][0] < 7.7)
516
+
517
+ assert_equal(res.y_events[0].shape, (0,))
518
+ assert_equal(res.y_events[1].shape, (1, 2))
519
+ assert np.isclose(
520
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
521
+
522
+ event_rational_1.direction = 0
523
+ event_rational_2.direction = 0
524
+
525
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
526
+ events=(event_rational_1, event_rational_2,
527
+ event_rational_3), dense_output=True)
528
+ assert_equal(res.status, 1)
529
+ assert_equal(res.t_events[0].size, 0)
530
+ assert_equal(res.t_events[1].size, 1)
531
+ assert_equal(res.t_events[2].size, 1)
532
+ assert_(7.3 < res.t_events[1][0] < 7.7)
533
+ assert_(7.3 < res.t_events[2][0] < 7.5)
534
+
535
+ assert_equal(res.y_events[0].shape, (0,))
536
+ assert_equal(res.y_events[1].shape, (1, 2))
537
+ assert_equal(res.y_events[2].shape, (1, 2))
538
+ assert np.isclose(
539
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
540
+ assert np.isclose(
541
+ event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
542
+
543
+ # Also test that termination by event doesn't break interpolants.
544
+ tc = np.linspace(res.t[-1], res.t[0])
545
+ yc_true = sol_rational(tc)
546
+ yc = res.sol(tc)
547
+ e = compute_error(yc, yc_true, 1e-3, 1e-6)
548
+ assert_(np.all(e < 5))
549
+
550
+ assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
551
+ rtol=1e-3, atol=1e-6)
552
+ assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
553
+ rtol=1e-3, atol=1e-6)
554
+
555
+
556
+ def _get_harmonic_oscillator():
557
+ def f(t, y):
558
+ return [y[1], -y[0]]
559
+
560
+ def event(t, y):
561
+ return y[0]
562
+
563
+ return f, event
564
+
565
+
566
+ @pytest.mark.parametrize('n_events', [3, 4])
567
+ def test_event_terminal_integer(n_events):
568
+ f, event = _get_harmonic_oscillator()
569
+ event.terminal = n_events
570
+ res = solve_ivp(f, (0, 100), [1, 0], events=event)
571
+ assert len(res.t_events[0]) == n_events
572
+ assert len(res.y_events[0]) == n_events
573
+ assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
574
+
575
+
576
+ def test_event_terminal_iv():
577
+ f, event = _get_harmonic_oscillator()
578
+ args = (f, (0, 100), [1, 0])
579
+
580
+ event.terminal = None
581
+ res = solve_ivp(*args, events=event)
582
+ event.terminal = 0
583
+ ref = solve_ivp(*args, events=event)
584
+ assert_allclose(res.t_events, ref.t_events)
585
+
586
+ message = "The `terminal` attribute..."
587
+ event.terminal = -1
588
+ with pytest.raises(ValueError, match=message):
589
+ solve_ivp(*args, events=event)
590
+ event.terminal = 3.5
591
+ with pytest.raises(ValueError, match=message):
592
+ solve_ivp(*args, events=event)
593
+
594
+
595
+ def test_max_step(num_parallel_threads):
596
+ rtol = 1e-3
597
+ atol = 1e-6
598
+ y0 = [1/3, 2/9]
599
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
600
+ if method is LSODA and num_parallel_threads > 1:
601
+ continue
602
+ for t_span in ([5, 9], [5, 1]):
603
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
604
+ max_step=0.5, atol=atol, method=method,
605
+ dense_output=True)
606
+ assert_equal(res.t[0], t_span[0])
607
+ assert_equal(res.t[-1], t_span[-1])
608
+ assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
609
+ assert_(res.t_events is None)
610
+ assert_(res.success)
611
+ assert_equal(res.status, 0)
612
+
613
+ y_true = sol_rational(res.t)
614
+ e = compute_error(res.y, y_true, rtol, atol)
615
+ assert_(np.all(e < 5))
616
+
617
+ tc = np.linspace(*t_span)
618
+ yc_true = sol_rational(tc)
619
+ yc = res.sol(tc)
620
+
621
+ e = compute_error(yc, yc_true, rtol, atol)
622
+ assert_(np.all(e < 5))
623
+
624
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
625
+
626
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
627
+ t_span[1], max_step=-1)
628
+
629
+ if method is not LSODA:
630
+ solver = method(fun_rational, t_span[0], y0, t_span[1],
631
+ rtol=rtol, atol=atol, max_step=1e-20)
632
+ message = solver.step()
633
+ message = solver.step() # First step succeeds but second step fails.
634
+ assert_equal(solver.status, 'failed')
635
+ assert_("step size is less" in message)
636
+ assert_raises(RuntimeError, solver.step)
637
+
638
+
639
+ def test_first_step(num_parallel_threads):
640
+ rtol = 1e-3
641
+ atol = 1e-6
642
+ y0 = [1/3, 2/9]
643
+ first_step = 0.1
644
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
645
+ if method is LSODA and num_parallel_threads > 1:
646
+ continue
647
+ for t_span in ([5, 9], [5, 1]):
648
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
649
+ max_step=0.5, atol=atol, method=method,
650
+ dense_output=True, first_step=first_step)
651
+
652
+ assert_equal(res.t[0], t_span[0])
653
+ assert_equal(res.t[-1], t_span[-1])
654
+ assert_allclose(first_step, np.abs(res.t[1] - 5))
655
+ assert_(res.t_events is None)
656
+ assert_(res.success)
657
+ assert_equal(res.status, 0)
658
+
659
+ y_true = sol_rational(res.t)
660
+ e = compute_error(res.y, y_true, rtol, atol)
661
+ assert_(np.all(e < 5))
662
+
663
+ tc = np.linspace(*t_span)
664
+ yc_true = sol_rational(tc)
665
+ yc = res.sol(tc)
666
+
667
+ e = compute_error(yc, yc_true, rtol, atol)
668
+ assert_(np.all(e < 5))
669
+
670
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
671
+
672
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
673
+ t_span[1], first_step=-1)
674
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
675
+ t_span[1], first_step=5)
676
+
677
+
678
+ def test_t_eval():
679
+ rtol = 1e-3
680
+ atol = 1e-6
681
+ y0 = [1/3, 2/9]
682
+ for t_span in ([5, 9], [5, 1]):
683
+ t_eval = np.linspace(t_span[0], t_span[1], 10)
684
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
685
+ t_eval=t_eval)
686
+ assert_equal(res.t, t_eval)
687
+ assert_(res.t_events is None)
688
+ assert_(res.success)
689
+ assert_equal(res.status, 0)
690
+
691
+ y_true = sol_rational(res.t)
692
+ e = compute_error(res.y, y_true, rtol, atol)
693
+ assert_(np.all(e < 5))
694
+
695
+ t_eval = [5, 5.01, 7, 8, 8.01, 9]
696
+ res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
697
+ t_eval=t_eval)
698
+ assert_equal(res.t, t_eval)
699
+ assert_(res.t_events is None)
700
+ assert_(res.success)
701
+ assert_equal(res.status, 0)
702
+
703
+ y_true = sol_rational(res.t)
704
+ e = compute_error(res.y, y_true, rtol, atol)
705
+ assert_(np.all(e < 5))
706
+
707
+ t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
708
+ res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
709
+ t_eval=t_eval)
710
+ assert_equal(res.t, t_eval)
711
+ assert_(res.t_events is None)
712
+ assert_(res.success)
713
+ assert_equal(res.status, 0)
714
+
715
+ t_eval = [5.01, 7, 8, 8.01]
716
+ res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
717
+ t_eval=t_eval)
718
+ assert_equal(res.t, t_eval)
719
+ assert_(res.t_events is None)
720
+ assert_(res.success)
721
+ assert_equal(res.status, 0)
722
+
723
+ y_true = sol_rational(res.t)
724
+ e = compute_error(res.y, y_true, rtol, atol)
725
+ assert_(np.all(e < 5))
726
+
727
+ t_eval = [4.99, 3, 1.5, 1.1, 1.01]
728
+ res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
729
+ t_eval=t_eval)
730
+ assert_equal(res.t, t_eval)
731
+ assert_(res.t_events is None)
732
+ assert_(res.success)
733
+ assert_equal(res.status, 0)
734
+
735
+ t_eval = [4, 6]
736
+ assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
737
+ rtol=rtol, atol=atol, t_eval=t_eval)
738
+
739
+
740
+ def test_t_eval_dense_output():
741
+ rtol = 1e-3
742
+ atol = 1e-6
743
+ y0 = [1/3, 2/9]
744
+ t_span = [5, 9]
745
+ t_eval = np.linspace(t_span[0], t_span[1], 10)
746
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
747
+ t_eval=t_eval)
748
+ res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
749
+ t_eval=t_eval, dense_output=True)
750
+ assert_equal(res.t, t_eval)
751
+ assert_(res.t_events is None)
752
+ assert_(res.success)
753
+ assert_equal(res.status, 0)
754
+
755
+ assert_equal(res.t, res_d.t)
756
+ assert_equal(res.y, res_d.y)
757
+ assert_(res_d.t_events is None)
758
+ assert_(res_d.success)
759
+ assert_equal(res_d.status, 0)
760
+
761
+ # if t and y are equal only test values for one case
762
+ y_true = sol_rational(res.t)
763
+ e = compute_error(res.y, y_true, rtol, atol)
764
+ assert_(np.all(e < 5))
765
+
766
+
767
+ @pytest.mark.thread_unsafe
768
+ def test_t_eval_early_event():
769
+ def early_event(t, y):
770
+ return t - 7
771
+
772
+ early_event.terminal = True
773
+
774
+ rtol = 1e-3
775
+ atol = 1e-6
776
+ y0 = [1/3, 2/9]
777
+ t_span = [5, 9]
778
+ t_eval = np.linspace(7.5, 9, 16)
779
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
780
+ with suppress_warnings() as sup:
781
+ sup.filter(UserWarning,
782
+ "The following arguments have no effect for a chosen "
783
+ "solver: `jac`")
784
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
785
+ method=method, t_eval=t_eval, events=early_event,
786
+ jac=jac_rational)
787
+ assert res.success
788
+ assert res.message == 'A termination event occurred.'
789
+ assert res.status == 1
790
+ assert not res.t and not res.y
791
+ assert len(res.t_events) == 1
792
+ assert res.t_events[0].size == 1
793
+ assert res.t_events[0][0] == 7
794
+
795
+
796
+ def test_event_dense_output_LSODA(num_parallel_threads):
797
+ if num_parallel_threads > 1:
798
+ pytest.skip('LSODA does not allow for concurrent execution')
799
+
800
+ def event_lsoda(t, y):
801
+ return y[0] - 2.02e-5
802
+
803
+ rtol = 1e-3
804
+ atol = 1e-6
805
+ y0 = [0.05]
806
+ t_span = [-2, 2]
807
+ first_step = 1e-3
808
+ res = solve_ivp(
809
+ fun_event_dense_output_LSODA,
810
+ t_span,
811
+ y0,
812
+ method="LSODA",
813
+ dense_output=True,
814
+ events=event_lsoda,
815
+ first_step=first_step,
816
+ max_step=1,
817
+ rtol=rtol,
818
+ atol=atol,
819
+ jac=jac_event_dense_output_LSODA,
820
+ )
821
+
822
+ assert_equal(res.t[0], t_span[0])
823
+ assert_equal(res.t[-1], t_span[-1])
824
+ assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
825
+ assert res.success
826
+ assert_equal(res.status, 0)
827
+
828
+ y_true = sol_event_dense_output_LSODA(res.t)
829
+ e = compute_error(res.y, y_true, rtol, atol)
830
+ assert_array_less(e, 5)
831
+
832
+ tc = np.linspace(*t_span)
833
+ yc_true = sol_event_dense_output_LSODA(tc)
834
+ yc = res.sol(tc)
835
+ e = compute_error(yc, yc_true, rtol, atol)
836
+ assert_array_less(e, 5)
837
+
838
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
839
+
840
+
841
+ def test_no_integration():
842
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
843
+ sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
844
+ method=method, dense_output=True)
845
+ assert_equal(sol.sol(4), [2, 3])
846
+ assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
847
+
848
+
849
+ def test_no_integration_class():
850
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
851
+ solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
852
+ solver.step()
853
+ assert_equal(solver.status, 'finished')
854
+ sol = solver.dense_output()
855
+ assert_equal(sol(0.0), [10.0, 0.0])
856
+ assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
857
+
858
+ solver = method(lambda t, y: -y, 0.0, [], np.inf)
859
+ solver.step()
860
+ assert_equal(solver.status, 'finished')
861
+ sol = solver.dense_output()
862
+ assert_equal(sol(100.0), [])
863
+ assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
864
+
865
+
866
+ def test_empty():
867
+ def fun(t, y):
868
+ return np.zeros((0,))
869
+
870
+ y0 = np.zeros((0,))
871
+
872
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
873
+ sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
874
+ method=method, dense_output=True)
875
+ assert_equal(sol.sol(10), np.zeros((0,)))
876
+ assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
877
+
878
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
879
+ sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
880
+ method=method, dense_output=True)
881
+ assert_equal(sol.sol(10), np.zeros((0,)))
882
+ assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
883
+
884
+
885
+ def test_ConstantDenseOutput():
886
+ sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
887
+ assert_allclose(sol(1.5), [1, 2])
888
+ assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
889
+
890
+ sol = ConstantDenseOutput(0, 1, np.array([]))
891
+ assert_allclose(sol(1.5), np.empty(0))
892
+ assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
893
+
894
+
895
+ def test_classes():
896
+ y0 = [1 / 3, 2 / 9]
897
+ for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
898
+ solver = cls(fun_rational, 5, y0, np.inf)
899
+ assert_equal(solver.n, 2)
900
+ assert_equal(solver.status, 'running')
901
+ assert_equal(solver.t_bound, np.inf)
902
+ assert_equal(solver.direction, 1)
903
+ assert_equal(solver.t, 5)
904
+ assert_equal(solver.y, y0)
905
+ assert_(solver.step_size is None)
906
+ if cls is not LSODA:
907
+ assert_(solver.nfev > 0)
908
+ assert_(solver.njev >= 0)
909
+ assert_equal(solver.nlu, 0)
910
+ else:
911
+ assert_equal(solver.nfev, 0)
912
+ assert_equal(solver.njev, 0)
913
+ assert_equal(solver.nlu, 0)
914
+
915
+ assert_raises(RuntimeError, solver.dense_output)
916
+
917
+ message = solver.step()
918
+ assert_equal(solver.status, 'running')
919
+ assert_equal(message, None)
920
+ assert_equal(solver.n, 2)
921
+ assert_equal(solver.t_bound, np.inf)
922
+ assert_equal(solver.direction, 1)
923
+ assert_(solver.t > 5)
924
+ assert_(not np.all(np.equal(solver.y, y0)))
925
+ assert_(solver.step_size > 0)
926
+ assert_(solver.nfev > 0)
927
+ assert_(solver.njev >= 0)
928
+ assert_(solver.nlu >= 0)
929
+ sol = solver.dense_output()
930
+ assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
931
+
932
+
933
+ def test_OdeSolution():
934
+ ts = np.array([0, 2, 5], dtype=float)
935
+ s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
936
+ s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
937
+
938
+ sol = OdeSolution(ts, [s1, s2])
939
+
940
+ assert_equal(sol(-1), [-1])
941
+ assert_equal(sol(1), [-1])
942
+ assert_equal(sol(2), [-1])
943
+ assert_equal(sol(3), [1])
944
+ assert_equal(sol(5), [1])
945
+ assert_equal(sol(6), [1])
946
+
947
+ assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
948
+ np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
949
+
950
+ ts = np.array([10, 4, -3])
951
+ s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
952
+ s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
953
+
954
+ sol = OdeSolution(ts, [s1, s2])
955
+ assert_equal(sol(11), [-1])
956
+ assert_equal(sol(10), [-1])
957
+ assert_equal(sol(5), [-1])
958
+ assert_equal(sol(4), [-1])
959
+ assert_equal(sol(0), [1])
960
+ assert_equal(sol(-3), [1])
961
+ assert_equal(sol(-4), [1])
962
+
963
+ assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
964
+ np.array([[-1, 1, -1, 1, -1, 1, -1]]))
965
+
966
+ ts = np.array([1, 1])
967
+ s = ConstantDenseOutput(1, 1, np.array([10]))
968
+ sol = OdeSolution(ts, [s])
969
+ assert_equal(sol(0), [10])
970
+ assert_equal(sol(1), [10])
971
+ assert_equal(sol(2), [10])
972
+
973
+ assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
974
+
975
+
976
+ def test_num_jac():
977
+ def fun(t, y):
978
+ return np.vstack([
979
+ -0.04 * y[0] + 1e4 * y[1] * y[2],
980
+ 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
981
+ 3e7 * y[1] ** 2
982
+ ])
983
+
984
+ def jac(t, y):
985
+ return np.array([
986
+ [-0.04, 1e4 * y[2], 1e4 * y[1]],
987
+ [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
988
+ [0, 6e7 * y[1], 0]
989
+ ])
990
+
991
+ t = 1
992
+ y = np.array([1, 0, 0])
993
+ J_true = jac(t, y)
994
+ threshold = 1e-5
995
+ f = fun(t, y).ravel()
996
+
997
+ J_num, factor = num_jac(fun, t, y, f, threshold, None)
998
+ assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
999
+
1000
+ J_num, factor = num_jac(fun, t, y, f, threshold, factor)
1001
+ assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
1002
+
1003
+
1004
+ def test_num_jac_sparse():
1005
+ def fun(t, y):
1006
+ e = y[1:]**3 - y[:-1]**2
1007
+ z = np.zeros(y.shape[1])
1008
+ return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
1009
+
1010
+ def structure(n):
1011
+ A = np.zeros((n, n), dtype=int)
1012
+ A[0, 0] = 1
1013
+ A[0, 1] = 1
1014
+ for i in range(1, n - 1):
1015
+ A[i, i - 1: i + 2] = 1
1016
+ A[-1, -1] = 1
1017
+ A[-1, -2] = 1
1018
+
1019
+ return A
1020
+
1021
+ np.random.seed(0)
1022
+ n = 20
1023
+ y = np.random.randn(n)
1024
+ A = structure(n)
1025
+ groups = group_columns(A)
1026
+
1027
+ f = fun(0, y[:, None]).ravel()
1028
+
1029
+ # Compare dense and sparse results, assuming that dense implementation
1030
+ # is correct (as it is straightforward).
1031
+ J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
1032
+ sparsity=(A, groups))
1033
+ J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
1034
+ assert_allclose(J_num_dense, J_num_sparse.toarray(),
1035
+ rtol=1e-12, atol=1e-14)
1036
+ assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
1037
+
1038
+ # Take small factors to trigger their recomputing inside.
1039
+ factor = np.random.uniform(0, 1e-12, size=n)
1040
+ J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
1041
+ sparsity=(A, groups))
1042
+ J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
1043
+
1044
+ assert_allclose(J_num_dense, J_num_sparse.toarray(),
1045
+ rtol=1e-12, atol=1e-14)
1046
+ assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
1047
+
1048
+
1049
+ def test_args():
1050
+
1051
+ # sys3 is actually two decoupled systems. (x, y) form a
1052
+ # linear oscillator, while z is a nonlinear first order
1053
+ # system with equilibria at z=0 and z=1. If k > 0, z=1
1054
+ # is stable and z=0 is unstable.
1055
+
1056
+ def sys3(t, w, omega, k, zfinal):
1057
+ x, y, z = w
1058
+ return [-omega*y, omega*x, k*z*(1 - z)]
1059
+
1060
+ def sys3_jac(t, w, omega, k, zfinal):
1061
+ x, y, z = w
1062
+ J = np.array([[0, -omega, 0],
1063
+ [omega, 0, 0],
1064
+ [0, 0, k*(1 - 2*z)]])
1065
+ return J
1066
+
1067
+ def sys3_x0decreasing(t, w, omega, k, zfinal):
1068
+ x, y, z = w
1069
+ return x
1070
+
1071
+ def sys3_y0increasing(t, w, omega, k, zfinal):
1072
+ x, y, z = w
1073
+ return y
1074
+
1075
+ def sys3_zfinal(t, w, omega, k, zfinal):
1076
+ x, y, z = w
1077
+ return z - zfinal
1078
+
1079
+ # Set the event flags for the event functions.
1080
+ sys3_x0decreasing.direction = -1
1081
+ sys3_y0increasing.direction = 1
1082
+ sys3_zfinal.terminal = True
1083
+
1084
+ omega = 2
1085
+ k = 4
1086
+
1087
+ tfinal = 5
1088
+ zfinal = 0.99
1089
+ # Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
1090
+ # The condition z(tfinal) = zfinal is the terminal event.
1091
+ z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
1092
+
1093
+ w0 = [0, -1, z0]
1094
+
1095
+ # Provide the jac argument and use the Radau method to ensure that the use
1096
+ # of the Jacobian function is exercised.
1097
+ # If event handling is working, the solution will stop at tfinal, not tend.
1098
+ tend = 2*tfinal
1099
+ sol = solve_ivp(sys3, [0, tend], w0,
1100
+ events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
1101
+ dense_output=True, args=(omega, k, zfinal),
1102
+ method='Radau', jac=sys3_jac,
1103
+ rtol=1e-10, atol=1e-13)
1104
+
1105
+ # Check that we got the expected events at the expected times.
1106
+ x0events_t = sol.t_events[0]
1107
+ y0events_t = sol.t_events[1]
1108
+ zfinalevents_t = sol.t_events[2]
1109
+ assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
1110
+ assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
1111
+ assert_allclose(zfinalevents_t, [tfinal])
1112
+
1113
+ # Check that the solution agrees with the known exact solution.
1114
+ t = np.linspace(0, zfinalevents_t[0], 250)
1115
+ w = sol.sol(t)
1116
+ assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
1117
+ assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
1118
+ assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
1119
+ rtol=1e-9, atol=1e-12)
1120
+
1121
+ # Check that the state variables have the expected values at the events.
1122
+ x0events = sol.sol(x0events_t)
1123
+ y0events = sol.sol(y0events_t)
1124
+ zfinalevents = sol.sol(zfinalevents_t)
1125
+ assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
1126
+ assert_allclose(x0events[1], np.ones_like(x0events[1]))
1127
+ assert_allclose(y0events[0], np.ones_like(y0events[0]))
1128
+ assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
1129
+ assert_allclose(zfinalevents[2], [zfinal])
1130
+
1131
+
1132
+ @pytest.mark.thread_unsafe
1133
+ def test_array_rtol():
1134
+ # solve_ivp had a bug with array_like `rtol`; see gh-15482
1135
+ # check that it's fixed
1136
+ def f(t, y):
1137
+ return y[0], y[1]
1138
+
1139
+ # no warning (or error) when `rtol` is array_like
1140
+ sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
1141
+ err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
1142
+
1143
+ # warning when an element of `rtol` is too small
1144
+ with pytest.warns(UserWarning, match="At least one element..."):
1145
+ sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
1146
+ err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
1147
+
1148
+ # tighter rtol improves the error
1149
+ assert err2 < err1
1150
+
1151
+
1152
+ @pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
1153
+ def test_integration_zero_rhs(method, num_parallel_threads):
1154
+ if method == 'LSODA' and num_parallel_threads > 1:
1155
+ pytest.skip(reason='LSODA does not allow for concurrent execution')
1156
+
1157
+ result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
1158
+ assert_(result.success)
1159
+ assert_equal(result.status, 0)
1160
+ assert_allclose(result.y, 1.0, rtol=1e-15)
1161
+
1162
+
1163
+ def test_args_single_value():
1164
+ def fun_with_arg(t, y, a):
1165
+ return a*y
1166
+
1167
+ message = "Supplied 'args' cannot be unpacked."
1168
+ with pytest.raises(TypeError, match=message):
1169
+ solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
1170
+
1171
+ sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
1172
+ assert_allclose(sol.y[0, -1], np.exp(-0.1))
1173
+
1174
+
1175
+ @pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
1176
+ def test_initial_state_finiteness(f0_fill):
1177
+ # regression test for gh-17846
1178
+ msg = "All components of the initial state `y0` must be finite."
1179
+ with pytest.raises(ValueError, match=msg):
1180
+ solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
1181
+
1182
+
1183
+ @pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
1184
+ def test_zero_interval(method):
1185
+ # Case where upper and lower limits of integration are the same
1186
+ # Result of integration should match initial state.
1187
+ # f[y(t)] = 2y(t)
1188
+ def f(t, y):
1189
+ return 2 * y
1190
+ res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
1191
+ assert res.success
1192
+ assert_allclose(res.y[0, -1], 1.0)
1193
+
1194
+
1195
+ @pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
1196
+ def test_tbound_respected_small_interval(method):
1197
+ """Regression test for gh-17341"""
1198
+ SMALL = 1e-4
1199
+
1200
+ # f[y(t)] = 2y(t) on t in [0,SMALL]
1201
+ # undefined otherwise
1202
+ def f(t, y):
1203
+ if t > SMALL:
1204
+ raise ValueError("Function was evaluated outside interval")
1205
+ return 2 * y
1206
+ res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
1207
+ assert res.success
1208
+
1209
+
1210
+ @pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
1211
+ def test_tbound_respected_larger_interval(method):
1212
+ """Regression test for gh-8848"""
1213
+ def V(r):
1214
+ return -11/r + 10 * r / (0.05 + r**2)
1215
+
1216
+ def func(t, p):
1217
+ if t < -17 or t > 2:
1218
+ raise ValueError("Function was evaluated outside interval")
1219
+ P = p[0]
1220
+ Q = p[1]
1221
+ r = np.exp(t)
1222
+ dPdr = r * Q
1223
+ dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
1224
+ return np.array([dPdr, dQdr])
1225
+
1226
+ result = solve_ivp(func,
1227
+ (-17, 2),
1228
+ y0=np.array([1, -11]),
1229
+ max_step=0.03,
1230
+ vectorized=False,
1231
+ t_eval=None,
1232
+ atol=1e-8,
1233
+ rtol=1e-5)
1234
+ assert result.success
1235
+
1236
+
1237
+ @pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
1238
+ def test_tbound_respected_oscillator(method):
1239
+ "Regression test for gh-9198"
1240
+ def reactions_func(t, y):
1241
+ if (t > 205):
1242
+ raise ValueError("Called outside interval")
1243
+ yprime = np.array([1.73307544e-02,
1244
+ 6.49376470e-06,
1245
+ 0.00000000e+00,
1246
+ 0.00000000e+00])
1247
+ return yprime
1248
+
1249
+ def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
1250
+ init_state = np.array([134.08298555, 138.82348612, 100., 0.])
1251
+ t0 = 100.0
1252
+ t1 = 200.0
1253
+ return solve_ivp(reactions_func,
1254
+ (t0, t1),
1255
+ init_state.copy(),
1256
+ dense_output=True,
1257
+ max_step=t1 - t0)
1258
+ result = run_sim2(1000, 100, 100)
1259
+ assert result.success
1260
+
1261
+
1262
+ def test_inital_maxstep():
1263
+ """Verify that select_inital_step respects max_step"""
1264
+ rtol = 1e-3
1265
+ atol = 1e-6
1266
+ y0 = np.array([1/3, 2/9])
1267
+ for (t0, t_bound) in ((5, 9), (5, 1)):
1268
+ for method_order in [RK23.error_estimator_order,
1269
+ RK45.error_estimator_order,
1270
+ DOP853.error_estimator_order,
1271
+ 3, #RADAU
1272
+ 1 #BDF
1273
+ ]:
1274
+ step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
1275
+ np.inf,
1276
+ fun_rational(t0,y0),
1277
+ np.sign(t_bound - t0),
1278
+ method_order,
1279
+ rtol, atol)
1280
+ max_step = step_no_max/2
1281
+ step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
1282
+ max_step,
1283
+ fun_rational(t0, y0),
1284
+ np.sign(t_bound - t0),
1285
+ method_order,
1286
+ rtol, atol)
1287
+ assert_equal(max_step, step_with_max)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from numpy.testing import assert_allclose, assert_
3
+ import numpy as np
4
+ from scipy.integrate import RK23, RK45, DOP853
5
+ from scipy.integrate._ivp import dop853_coefficients
6
+
7
+
8
+ @pytest.mark.parametrize("solver", [RK23, RK45, DOP853])
9
+ def test_coefficient_properties(solver):
10
+ assert_allclose(np.sum(solver.B), 1, rtol=1e-15)
11
+ assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14)
12
+
13
+
14
+ def test_coefficient_properties_dop853():
15
+ assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15)
16
+ assert_allclose(np.sum(dop853_coefficients.A, axis=1),
17
+ dop853_coefficients.C,
18
+ rtol=1e-14)
19
+
20
+
21
+ @pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
22
+ def test_error_estimation(solver_class):
23
+ step = 0.2
24
+ solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step)
25
+ solver.step()
26
+ error_estimate = solver._estimate_error(solver.K, step)
27
+ error = solver.y - np.exp([step])
28
+ assert_(np.abs(error) < np.abs(error_estimate))
29
+
30
+
31
+ @pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
32
+ def test_error_estimation_complex(solver_class):
33
+ h = 0.2
34
+ solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h)
35
+ solver.step()
36
+ err_norm = solver._estimate_error_norm(solver.K, h, scale=[1])
37
+ assert np.isrealobj(err_norm)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_lebedev.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/active_proaction/lib/python3.10/site-packages/scipy/integrate/_ode.py ADDED
@@ -0,0 +1,1388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Pearu Peterson, Pauli Virtanen, John Travers
2
+ """
3
+ First-order ODE integrators.
4
+
5
+ User-friendly interface to various numerical integrators for solving a
6
+ system of first order ODEs with prescribed initial conditions::
7
+
8
+ d y(t)[i]
9
+ --------- = f(t,y(t))[i],
10
+ d t
11
+
12
+ y(t=0)[i] = y0[i],
13
+
14
+ where::
15
+
16
+ i = 0, ..., len(y0) - 1
17
+
18
+ class ode
19
+ ---------
20
+
21
+ A generic interface class to numeric integrators. It has the following
22
+ methods::
23
+
24
+ integrator = ode(f, jac=None)
25
+ integrator = integrator.set_integrator(name, **params)
26
+ integrator = integrator.set_initial_value(y0, t0=0.0)
27
+ integrator = integrator.set_f_params(*args)
28
+ integrator = integrator.set_jac_params(*args)
29
+ y1 = integrator.integrate(t1, step=False, relax=False)
30
+ flag = integrator.successful()
31
+
32
+ class complex_ode
33
+ -----------------
34
+
35
+ This class has the same generic interface as ode, except it can handle complex
36
+ f, y and Jacobians by transparently translating them into the equivalent
37
+ real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
38
+ an alternative to ode with the zvode solver, sometimes performing better.
39
+ """
40
+ # XXX: Integrators must have:
41
+ # ===========================
42
+ # cvode - C version of vode and vodpk with many improvements.
43
+ # Get it from http://www.netlib.org/ode/cvode.tar.gz.
44
+ # To wrap cvode to Python, one must write the extension module by
45
+ # hand. Its interface is too much 'advanced C' that using f2py
46
+ # would be too complicated (or impossible).
47
+ #
48
+ # How to define a new integrator:
49
+ # ===============================
50
+ #
51
+ # class myodeint(IntegratorBase):
52
+ #
53
+ # runner = <odeint function> or None
54
+ #
55
+ # def __init__(self,...): # required
56
+ # <initialize>
57
+ #
58
+ # def reset(self,n,has_jac): # optional
59
+ # # n - the size of the problem (number of equations)
60
+ # # has_jac - whether user has supplied its own routine for Jacobian
61
+ # <allocate memory,initialize further>
62
+ #
63
+ # def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
64
+ # # this method is called to integrate from t=t0 to t=t1
65
+ # # with initial condition y0. f and jac are user-supplied functions
66
+ # # that define the problem. f_params,jac_params are additional
67
+ # # arguments
68
+ # # to these functions.
69
+ # <calculate y1>
70
+ # if <calculation was unsuccessful>:
71
+ # self.success = 0
72
+ # return t1,y1
73
+ #
74
+ # # In addition, one can define step() and run_relax() methods (they
75
+ # # take the same arguments as run()) if the integrator can support
76
+ # # these features (see IntegratorBase doc strings).
77
+ #
78
+ # if myodeint.runner:
79
+ # IntegratorBase.integrator_classes.append(myodeint)
80
+
81
+ __all__ = ['ode', 'complex_ode']
82
+
83
+ import re
84
+ import threading
85
+ import warnings
86
+
87
+ from numpy import asarray, array, zeros, isscalar, real, imag, vstack
88
+
89
+ from . import _vode
90
+ from . import _dop
91
+ from . import _lsoda
92
+
93
+
94
+ _dop_int_dtype = _dop.types.intvar.dtype
95
+ _vode_int_dtype = _vode.types.intvar.dtype
96
+ _lsoda_int_dtype = _lsoda.types.intvar.dtype
97
+
98
+
99
+ # lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
100
+ # zvode; they share the `def run` implementation
101
+ LSODA_LOCK = threading.Lock()
102
+ VODE_LOCK = threading.Lock()
103
+
104
+
105
+ # ------------------------------------------------------------------------------
106
+ # User interface
107
+ # ------------------------------------------------------------------------------
108
+
109
+
110
+ class ode:
111
+ """
112
+ A generic interface class to numeric integrators.
113
+
114
+ Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
115
+
116
+ *Note*: The first two arguments of ``f(t, y, ...)`` are in the
117
+ opposite order of the arguments in the system definition function used
118
+ by `scipy.integrate.odeint`.
119
+
120
+ Parameters
121
+ ----------
122
+ f : callable ``f(t, y, *f_args)``
123
+ Right-hand side of the differential equation. t is a scalar,
124
+ ``y.shape == (n,)``.
125
+ ``f_args`` is set by calling ``set_f_params(*args)``.
126
+ `f` should return a scalar, array or list (not a tuple).
127
+ jac : callable ``jac(t, y, *jac_args)``, optional
128
+ Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
129
+ ``jac_args`` is set by calling ``set_jac_params(*args)``.
130
+
131
+ Attributes
132
+ ----------
133
+ t : float
134
+ Current time.
135
+ y : ndarray
136
+ Current variable values.
137
+
138
+ See also
139
+ --------
140
+ odeint : an integrator with a simpler interface based on lsoda from ODEPACK
141
+ quad : for finding the area under a curve
142
+
143
+ Notes
144
+ -----
145
+ Available integrators are listed below. They can be selected using
146
+ the `set_integrator` method.
147
+
148
+ "vode"
149
+
150
+ Real-valued Variable-coefficient Ordinary Differential Equation
151
+ solver, with fixed-leading-coefficient implementation. It provides
152
+ implicit Adams method (for non-stiff problems) and a method based on
153
+ backward differentiation formulas (BDF) (for stiff problems).
154
+
155
+ Source: http://www.netlib.org/ode/vode.f
156
+
157
+ .. warning::
158
+
159
+ This integrator is not re-entrant. You cannot have two `ode`
160
+ instances using the "vode" integrator at the same time.
161
+
162
+ This integrator accepts the following parameters in `set_integrator`
163
+ method of the `ode` class:
164
+
165
+ - atol : float or sequence
166
+ absolute tolerance for solution
167
+ - rtol : float or sequence
168
+ relative tolerance for solution
169
+ - lband : None or int
170
+ - uband : None or int
171
+ Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
172
+ Setting these requires your jac routine to return the jacobian
173
+ in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
174
+ dimension of the matrix must be (lband+uband+1, len(y)).
175
+ - method: 'adams' or 'bdf'
176
+ Which solver to use, Adams (non-stiff) or BDF (stiff)
177
+ - with_jacobian : bool
178
+ This option is only considered when the user has not supplied a
179
+ Jacobian function and has not indicated (by setting either band)
180
+ that the Jacobian is banded. In this case, `with_jacobian` specifies
181
+ whether the iteration method of the ODE solver's correction step is
182
+ chord iteration with an internally generated full Jacobian or
183
+ functional iteration with no Jacobian.
184
+ - nsteps : int
185
+ Maximum number of (internally defined) steps allowed during one
186
+ call to the solver.
187
+ - first_step : float
188
+ - min_step : float
189
+ - max_step : float
190
+ Limits for the step sizes used by the integrator.
191
+ - order : int
192
+ Maximum order used by the integrator,
193
+ order <= 12 for Adams, <= 5 for BDF.
194
+
195
+ "zvode"
196
+
197
+ Complex-valued Variable-coefficient Ordinary Differential Equation
198
+ solver, with fixed-leading-coefficient implementation. It provides
199
+ implicit Adams method (for non-stiff problems) and a method based on
200
+ backward differentiation formulas (BDF) (for stiff problems).
201
+
202
+ Source: http://www.netlib.org/ode/zvode.f
203
+
204
+ .. warning::
205
+
206
+ This integrator is not re-entrant. You cannot have two `ode`
207
+ instances using the "zvode" integrator at the same time.
208
+
209
+ This integrator accepts the same parameters in `set_integrator`
210
+ as the "vode" solver.
211
+
212
+ .. note::
213
+
214
+ When using ZVODE for a stiff system, it should only be used for
215
+ the case in which the function f is analytic, that is, when each f(i)
216
+ is an analytic function of each y(j). Analyticity means that the
217
+ partial derivative df(i)/dy(j) is a unique complex number, and this
218
+ fact is critical in the way ZVODE solves the dense or banded linear
219
+ systems that arise in the stiff case. For a complex stiff ODE system
220
+ in which f is not analytic, ZVODE is likely to have convergence
221
+ failures, and for this problem one should instead use DVODE on the
222
+ equivalent real system (in the real and imaginary parts of y).
223
+
224
+ "lsoda"
225
+
226
+ Real-valued Variable-coefficient Ordinary Differential Equation
227
+ solver, with fixed-leading-coefficient implementation. It provides
228
+ automatic method switching between implicit Adams method (for non-stiff
229
+ problems) and a method based on backward differentiation formulas (BDF)
230
+ (for stiff problems).
231
+
232
+ Source: http://www.netlib.org/odepack
233
+
234
+ .. warning::
235
+
236
+ This integrator is not re-entrant. You cannot have two `ode`
237
+ instances using the "lsoda" integrator at the same time.
238
+
239
+ This integrator accepts the following parameters in `set_integrator`
240
+ method of the `ode` class:
241
+
242
+ - atol : float or sequence
243
+ absolute tolerance for solution
244
+ - rtol : float or sequence
245
+ relative tolerance for solution
246
+ - lband : None or int
247
+ - uband : None or int
248
+ Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
249
+ Setting these requires your jac routine to return the jacobian
250
+ in packed format, jac_packed[i-j+uband, j] = jac[i,j].
251
+ - with_jacobian : bool
252
+ *Not used.*
253
+ - nsteps : int
254
+ Maximum number of (internally defined) steps allowed during one
255
+ call to the solver.
256
+ - first_step : float
257
+ - min_step : float
258
+ - max_step : float
259
+ Limits for the step sizes used by the integrator.
260
+ - max_order_ns : int
261
+ Maximum order used in the nonstiff case (default 12).
262
+ - max_order_s : int
263
+ Maximum order used in the stiff case (default 5).
264
+ - max_hnil : int
265
+ Maximum number of messages reporting too small step size (t + h = t)
266
+ (default 0)
267
+ - ixpr : int
268
+ Whether to generate extra printing at method switches (default False).
269
+
270
+ "dopri5"
271
+
272
+ This is an explicit runge-kutta method of order (4)5 due to Dormand &
273
+ Prince (with stepsize control and dense output).
274
+
275
+ Authors:
276
+
277
+ E. Hairer and G. Wanner
278
+ Universite de Geneve, Dept. de Mathematiques
279
+ CH-1211 Geneve 24, Switzerland
280
+ e-mail: ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
281
+
282
+ This code is described in [HNW93]_.
283
+
284
+ This integrator accepts the following parameters in set_integrator()
285
+ method of the ode class:
286
+
287
+ - atol : float or sequence
288
+ absolute tolerance for solution
289
+ - rtol : float or sequence
290
+ relative tolerance for solution
291
+ - nsteps : int
292
+ Maximum number of (internally defined) steps allowed during one
293
+ call to the solver.
294
+ - first_step : float
295
+ - max_step : float
296
+ - safety : float
297
+ Safety factor on new step selection (default 0.9)
298
+ - ifactor : float
299
+ - dfactor : float
300
+ Maximum factor to increase/decrease step size by in one step
301
+ - beta : float
302
+ Beta parameter for stabilised step size control.
303
+ - verbosity : int
304
+ Switch for printing messages (< 0 for no messages).
305
+
306
+ "dop853"
307
+
308
+ This is an explicit runge-kutta method of order 8(5,3) due to Dormand
309
+ & Prince (with stepsize control and dense output).
310
+
311
+ Options and references the same as "dopri5".
312
+
313
+ Examples
314
+ --------
315
+
316
+ A problem to integrate and the corresponding jacobian:
317
+
318
+ >>> from scipy.integrate import ode
319
+ >>>
320
+ >>> y0, t0 = [1.0j, 2.0], 0
321
+ >>>
322
+ >>> def f(t, y, arg1):
323
+ ... return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
324
+ >>> def jac(t, y, arg1):
325
+ ... return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
326
+
327
+ The integration:
328
+
329
+ >>> r = ode(f, jac).set_integrator('zvode', method='bdf')
330
+ >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
331
+ >>> t1 = 10
332
+ >>> dt = 1
333
+ >>> while r.successful() and r.t < t1:
334
+ ... print(r.t+dt, r.integrate(r.t+dt))
335
+ 1 [-0.71038232+0.23749653j 0.40000271+0.j ]
336
+ 2.0 [0.19098503-0.52359246j 0.22222356+0.j ]
337
+ 3.0 [0.47153208+0.52701229j 0.15384681+0.j ]
338
+ 4.0 [-0.61905937+0.30726255j 0.11764744+0.j ]
339
+ 5.0 [0.02340997-0.61418799j 0.09523835+0.j ]
340
+ 6.0 [0.58643071+0.339819j 0.08000018+0.j ]
341
+ 7.0 [-0.52070105+0.44525141j 0.06896565+0.j ]
342
+ 8.0 [-0.15986733-0.61234476j 0.06060616+0.j ]
343
+ 9.0 [0.64850462+0.15048982j 0.05405414+0.j ]
344
+ 10.0 [-0.38404699+0.56382299j 0.04878055+0.j ]
345
+
346
+ References
347
+ ----------
348
+ .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
349
+ Differential Equations i. Nonstiff Problems. 2nd edition.
350
+ Springer Series in Computational Mathematics,
351
+ Springer-Verlag (1993)
352
+
353
+ """
354
+
355
+ def __init__(self, f, jac=None):
356
+ self.stiff = 0
357
+ self.f = f
358
+ self.jac = jac
359
+ self.f_params = ()
360
+ self.jac_params = ()
361
+ self._y = []
362
+
363
+ @property
364
+ def y(self):
365
+ return self._y
366
+
367
+ def set_initial_value(self, y, t=0.0):
368
+ """Set initial conditions y(t) = y."""
369
+ if isscalar(y):
370
+ y = [y]
371
+ n_prev = len(self._y)
372
+ if not n_prev:
373
+ self.set_integrator('') # find first available integrator
374
+ self._y = asarray(y, self._integrator.scalar)
375
+ self.t = t
376
+ self._integrator.reset(len(self._y), self.jac is not None)
377
+ return self
378
+
379
+ def set_integrator(self, name, **integrator_params):
380
+ """
381
+ Set integrator by name.
382
+
383
+ Parameters
384
+ ----------
385
+ name : str
386
+ Name of the integrator.
387
+ **integrator_params
388
+ Additional parameters for the integrator.
389
+ """
390
+ integrator = find_integrator(name)
391
+ if integrator is None:
392
+ # FIXME: this really should be raise an exception. Will that break
393
+ # any code?
394
+ message = f'No integrator name match with {name!r} or is not available.'
395
+ warnings.warn(message, stacklevel=2)
396
+ else:
397
+ self._integrator = integrator(**integrator_params)
398
+ if not len(self._y):
399
+ self.t = 0.0
400
+ self._y = array([0.0], self._integrator.scalar)
401
+ self._integrator.reset(len(self._y), self.jac is not None)
402
+ return self
403
+
404
+ def integrate(self, t, step=False, relax=False):
405
+ """Find y=y(t), set y as an initial condition, and return y.
406
+
407
+ Parameters
408
+ ----------
409
+ t : float
410
+ The endpoint of the integration step.
411
+ step : bool
412
+ If True, and if the integrator supports the step method,
413
+ then perform a single integration step and return.
414
+ This parameter is provided in order to expose internals of
415
+ the implementation, and should not be changed from its default
416
+ value in most cases.
417
+ relax : bool
418
+ If True and if the integrator supports the run_relax method,
419
+ then integrate until t_1 >= t and return. ``relax`` is not
420
+ referenced if ``step=True``.
421
+ This parameter is provided in order to expose internals of
422
+ the implementation, and should not be changed from its default
423
+ value in most cases.
424
+
425
+ Returns
426
+ -------
427
+ y : float
428
+ The integrated value at t
429
+ """
430
+ if step and self._integrator.supports_step:
431
+ mth = self._integrator.step
432
+ elif relax and self._integrator.supports_run_relax:
433
+ mth = self._integrator.run_relax
434
+ else:
435
+ mth = self._integrator.run
436
+
437
+ try:
438
+ self._y, self.t = mth(self.f, self.jac or (lambda: None),
439
+ self._y, self.t, t,
440
+ self.f_params, self.jac_params)
441
+ except SystemError as e:
442
+ # f2py issue with tuple returns, see ticket 1187.
443
+ raise ValueError(
444
+ 'Function to integrate must not return a tuple.'
445
+ ) from e
446
+
447
+ return self._y
448
+
449
+ def successful(self):
450
+ """Check if integration was successful."""
451
+ try:
452
+ self._integrator
453
+ except AttributeError:
454
+ self.set_integrator('')
455
+ return self._integrator.success == 1
456
+
457
+ def get_return_code(self):
458
+ """Extracts the return code for the integration to enable better control
459
+ if the integration fails.
460
+
461
+ In general, a return code > 0 implies success, while a return code < 0
462
+ implies failure.
463
+
464
+ Notes
465
+ -----
466
+ This section describes possible return codes and their meaning, for available
467
+ integrators that can be selected by `set_integrator` method.
468
+
469
+ "vode"
470
+
471
+ =========== =======
472
+ Return Code Message
473
+ =========== =======
474
+ 2 Integration successful.
475
+ -1 Excess work done on this call. (Perhaps wrong MF.)
476
+ -2 Excess accuracy requested. (Tolerances too small.)
477
+ -3 Illegal input detected. (See printed message.)
478
+ -4 Repeated error test failures. (Check all input.)
479
+ -5 Repeated convergence failures. (Perhaps bad Jacobian
480
+ supplied or wrong choice of MF or tolerances.)
481
+ -6 Error weight became zero during problem. (Solution
482
+ component i vanished, and ATOL or ATOL(i) = 0.)
483
+ =========== =======
484
+
485
+ "zvode"
486
+
487
+ =========== =======
488
+ Return Code Message
489
+ =========== =======
490
+ 2 Integration successful.
491
+ -1 Excess work done on this call. (Perhaps wrong MF.)
492
+ -2 Excess accuracy requested. (Tolerances too small.)
493
+ -3 Illegal input detected. (See printed message.)
494
+ -4 Repeated error test failures. (Check all input.)
495
+ -5 Repeated convergence failures. (Perhaps bad Jacobian
496
+ supplied or wrong choice of MF or tolerances.)
497
+ -6 Error weight became zero during problem. (Solution
498
+ component i vanished, and ATOL or ATOL(i) = 0.)
499
+ =========== =======
500
+
501
+ "dopri5"
502
+
503
+ =========== =======
504
+ Return Code Message
505
+ =========== =======
506
+ 1 Integration successful.
507
+ 2 Integration successful (interrupted by solout).
508
+ -1 Input is not consistent.
509
+ -2 Larger nsteps is needed.
510
+ -3 Step size becomes too small.
511
+ -4 Problem is probably stiff (interrupted).
512
+ =========== =======
513
+
514
+ "dop853"
515
+
516
+ =========== =======
517
+ Return Code Message
518
+ =========== =======
519
+ 1 Integration successful.
520
+ 2 Integration successful (interrupted by solout).
521
+ -1 Input is not consistent.
522
+ -2 Larger nsteps is needed.
523
+ -3 Step size becomes too small.
524
+ -4 Problem is probably stiff (interrupted).
525
+ =========== =======
526
+
527
+ "lsoda"
528
+
529
+ =========== =======
530
+ Return Code Message
531
+ =========== =======
532
+ 2 Integration successful.
533
+ -1 Excess work done on this call (perhaps wrong Dfun type).
534
+ -2 Excess accuracy requested (tolerances too small).
535
+ -3 Illegal input detected (internal error).
536
+ -4 Repeated error test failures (internal error).
537
+ -5 Repeated convergence failures (perhaps bad Jacobian or tolerances).
538
+ -6 Error weight became zero during problem.
539
+ -7 Internal workspace insufficient to finish (internal error).
540
+ =========== =======
541
+ """
542
+ try:
543
+ self._integrator
544
+ except AttributeError:
545
+ self.set_integrator('')
546
+ return self._integrator.istate
547
+
548
+ def set_f_params(self, *args):
549
+ """Set extra parameters for user-supplied function f."""
550
+ self.f_params = args
551
+ return self
552
+
553
+ def set_jac_params(self, *args):
554
+ """Set extra parameters for user-supplied function jac."""
555
+ self.jac_params = args
556
+ return self
557
+
558
+ def set_solout(self, solout):
559
+ """
560
+ Set callable to be called at every successful integration step.
561
+
562
+ Parameters
563
+ ----------
564
+ solout : callable
565
+ ``solout(t, y)`` is called at each internal integrator step,
566
+ t is a scalar providing the current independent position
567
+ y is the current solution ``y.shape == (n,)``
568
+ solout should return -1 to stop integration
569
+ otherwise it should return None or 0
570
+
571
+ """
572
+ if self._integrator.supports_solout:
573
+ self._integrator.set_solout(solout)
574
+ if self._y is not None:
575
+ self._integrator.reset(len(self._y), self.jac is not None)
576
+ else:
577
+ raise ValueError("selected integrator does not support solout,"
578
+ " choose another one")
579
+
580
+
581
+ def _transform_banded_jac(bjac):
582
+ """
583
+ Convert a real matrix of the form (for example)
584
+
585
+ [0 0 A B] [0 0 0 B]
586
+ [0 0 C D] [0 0 A D]
587
+ [E F G H] to [0 F C H]
588
+ [I J K L] [E J G L]
589
+ [I 0 K 0]
590
+
591
+ That is, every other column is shifted up one.
592
+ """
593
+ # Shift every other column.
594
+ newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
595
+ newjac[1:, ::2] = bjac[:, ::2]
596
+ newjac[:-1, 1::2] = bjac[:, 1::2]
597
+ return newjac
598
+
599
+
600
+ class complex_ode(ode):
601
+ """
602
+ A wrapper of ode for complex systems.
603
+
604
+ This functions similarly as `ode`, but re-maps a complex-valued
605
+ equation system to a real-valued one before using the integrators.
606
+
607
+ Parameters
608
+ ----------
609
+ f : callable ``f(t, y, *f_args)``
610
+ Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
611
+ ``f_args`` is set by calling ``set_f_params(*args)``.
612
+ jac : callable ``jac(t, y, *jac_args)``
613
+ Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
614
+ ``jac_args`` is set by calling ``set_f_params(*args)``.
615
+
616
+ Attributes
617
+ ----------
618
+ t : float
619
+ Current time.
620
+ y : ndarray
621
+ Current variable values.
622
+
623
+ Examples
624
+ --------
625
+ For usage examples, see `ode`.
626
+
627
+ """
628
+
629
+ def __init__(self, f, jac=None):
630
+ self.cf = f
631
+ self.cjac = jac
632
+ if jac is None:
633
+ ode.__init__(self, self._wrap, None)
634
+ else:
635
+ ode.__init__(self, self._wrap, self._wrap_jac)
636
+
637
+ def _wrap(self, t, y, *f_args):
638
+ f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
639
+ # self.tmp is a real-valued array containing the interleaved
640
+ # real and imaginary parts of f.
641
+ self.tmp[::2] = real(f)
642
+ self.tmp[1::2] = imag(f)
643
+ return self.tmp
644
+
645
+ def _wrap_jac(self, t, y, *jac_args):
646
+ # jac is the complex Jacobian computed by the user-defined function.
647
+ jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
648
+
649
+ # jac_tmp is the real version of the complex Jacobian. Each complex
650
+ # entry in jac, say 2+3j, becomes a 2x2 block of the form
651
+ # [2 -3]
652
+ # [3 2]
653
+ jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
654
+ jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
655
+ jac_tmp[1::2, ::2] = imag(jac)
656
+ jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
657
+
658
+ ml = getattr(self._integrator, 'ml', None)
659
+ mu = getattr(self._integrator, 'mu', None)
660
+ if ml is not None or mu is not None:
661
+ # Jacobian is banded. The user's Jacobian function has computed
662
+ # the complex Jacobian in packed format. The corresponding
663
+ # real-valued version has every other column shifted up.
664
+ jac_tmp = _transform_banded_jac(jac_tmp)
665
+
666
+ return jac_tmp
667
+
668
+ @property
669
+ def y(self):
670
+ return self._y[::2] + 1j * self._y[1::2]
671
+
672
+ def set_integrator(self, name, **integrator_params):
673
+ """
674
+ Set integrator by name.
675
+
676
+ Parameters
677
+ ----------
678
+ name : str
679
+ Name of the integrator
680
+ **integrator_params
681
+ Additional parameters for the integrator.
682
+ """
683
+ if name == 'zvode':
684
+ raise ValueError("zvode must be used with ode, not complex_ode")
685
+
686
+ lband = integrator_params.get('lband')
687
+ uband = integrator_params.get('uband')
688
+ if lband is not None or uband is not None:
689
+ # The Jacobian is banded. Override the user-supplied bandwidths
690
+ # (which are for the complex Jacobian) with the bandwidths of
691
+ # the corresponding real-valued Jacobian wrapper of the complex
692
+ # Jacobian.
693
+ integrator_params['lband'] = 2 * (lband or 0) + 1
694
+ integrator_params['uband'] = 2 * (uband or 0) + 1
695
+
696
+ return ode.set_integrator(self, name, **integrator_params)
697
+
698
+ def set_initial_value(self, y, t=0.0):
699
+ """Set initial conditions y(t) = y."""
700
+ y = asarray(y)
701
+ self.tmp = zeros(y.size * 2, 'float')
702
+ self.tmp[::2] = real(y)
703
+ self.tmp[1::2] = imag(y)
704
+ return ode.set_initial_value(self, self.tmp, t)
705
+
706
+ def integrate(self, t, step=False, relax=False):
707
+ """Find y=y(t), set y as an initial condition, and return y.
708
+
709
+ Parameters
710
+ ----------
711
+ t : float
712
+ The endpoint of the integration step.
713
+ step : bool
714
+ If True, and if the integrator supports the step method,
715
+ then perform a single integration step and return.
716
+ This parameter is provided in order to expose internals of
717
+ the implementation, and should not be changed from its default
718
+ value in most cases.
719
+ relax : bool
720
+ If True and if the integrator supports the run_relax method,
721
+ then integrate until t_1 >= t and return. ``relax`` is not
722
+ referenced if ``step=True``.
723
+ This parameter is provided in order to expose internals of
724
+ the implementation, and should not be changed from its default
725
+ value in most cases.
726
+
727
+ Returns
728
+ -------
729
+ y : float
730
+ The integrated value at t
731
+ """
732
+ y = ode.integrate(self, t, step, relax)
733
+ return y[::2] + 1j * y[1::2]
734
+
735
+ def set_solout(self, solout):
736
+ """
737
+ Set callable to be called at every successful integration step.
738
+
739
+ Parameters
740
+ ----------
741
+ solout : callable
742
+ ``solout(t, y)`` is called at each internal integrator step,
743
+ t is a scalar providing the current independent position
744
+ y is the current solution ``y.shape == (n,)``
745
+ solout should return -1 to stop integration
746
+ otherwise it should return None or 0
747
+
748
+ """
749
+ if self._integrator.supports_solout:
750
+ self._integrator.set_solout(solout, complex=True)
751
+ else:
752
+ raise TypeError("selected integrator does not support solouta, "
753
+ "choose another one")
754
+
755
+
756
+ # ------------------------------------------------------------------------------
757
+ # ODE integrators
758
+ # ------------------------------------------------------------------------------
759
+
760
+ def find_integrator(name):
761
+ for cl in IntegratorBase.integrator_classes:
762
+ if re.match(name, cl.__name__, re.I):
763
+ return cl
764
+ return None
765
+
766
+
767
+ class IntegratorConcurrencyError(RuntimeError):
768
+ """
769
+ Failure due to concurrent usage of an integrator that can be used
770
+ only for a single problem at a time.
771
+
772
+ """
773
+
774
+ def __init__(self, name):
775
+ msg = (f"Integrator `{name}` can be used to solve only a single problem "
776
+ "at a time. If you want to integrate multiple problems, "
777
+ "consider using a different integrator (see `ode.set_integrator`)")
778
+ RuntimeError.__init__(self, msg)
779
+
780
+
781
+ class IntegratorBase:
782
+ runner = None # runner is None => integrator is not available
783
+ success = None # success==1 if integrator was called successfully
784
+ istate = None # istate > 0 means success, istate < 0 means failure
785
+ supports_run_relax = None
786
+ supports_step = None
787
+ supports_solout = False
788
+ integrator_classes = []
789
+ scalar = float
790
+
791
+ def acquire_new_handle(self):
792
+ # Some of the integrators have internal state (ancient
793
+ # Fortran...), and so only one instance can use them at a time.
794
+ # We keep track of this, and fail when concurrent usage is tried.
795
+ self.__class__.active_global_handle += 1
796
+ self.handle = self.__class__.active_global_handle
797
+
798
+ def check_handle(self):
799
+ if self.handle is not self.__class__.active_global_handle:
800
+ raise IntegratorConcurrencyError(self.__class__.__name__)
801
+
802
+ def reset(self, n, has_jac):
803
+ """Prepare integrator for call: allocate memory, set flags, etc.
804
+ n - number of equations.
805
+ has_jac - if user has supplied function for evaluating Jacobian.
806
+ """
807
+
808
+ def run(self, f, jac, y0, t0, t1, f_params, jac_params):
809
+ """Integrate from t=t0 to t=t1 using y0 as an initial condition.
810
+ Return 2-tuple (y1,t1) where y1 is the result and t=t1
811
+ defines the stoppage coordinate of the result.
812
+ """
813
+ raise NotImplementedError('all integrators must define '
814
+ 'run(f, jac, t0, t1, y0, f_params, jac_params)')
815
+
816
+ def step(self, f, jac, y0, t0, t1, f_params, jac_params):
817
+ """Make one integration step and return (y1,t1)."""
818
+ raise NotImplementedError(f'{self.__class__.__name__} '
819
+ 'does not support step() method')
820
+
821
+ def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
822
+ """Integrate from t=t0 to t>=t1 and return (y1,t)."""
823
+ raise NotImplementedError(f'{self.__class__.__name__} '
824
+ 'does not support run_relax() method')
825
+
826
+ # XXX: __str__ method for getting visual state of the integrator
827
+
828
+
829
+ def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
830
+ """
831
+ Wrap a banded Jacobian function with a function that pads
832
+ the Jacobian with `ml` rows of zeros.
833
+ """
834
+
835
+ def jac_wrapper(t, y):
836
+ jac = asarray(jacfunc(t, y, *jac_params))
837
+ padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
838
+ return padded_jac
839
+
840
+ return jac_wrapper
841
+
842
+
843
+ class vode(IntegratorBase):
844
+ runner = getattr(_vode, 'dvode', None)
845
+
846
+ messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
847
+ -2: 'Excess accuracy requested. (Tolerances too small.)',
848
+ -3: 'Illegal input detected. (See printed message.)',
849
+ -4: 'Repeated error test failures. (Check all input.)',
850
+ -5: 'Repeated convergence failures. (Perhaps bad'
851
+ ' Jacobian supplied or wrong choice of MF or tolerances.)',
852
+ -6: 'Error weight became zero during problem. (Solution'
853
+ ' component i vanished, and ATOL or ATOL(i) = 0.)'
854
+ }
855
+ supports_run_relax = 1
856
+ supports_step = 1
857
+ active_global_handle = 0
858
+
859
+ def __init__(self,
860
+ method='adams',
861
+ with_jacobian=False,
862
+ rtol=1e-6, atol=1e-12,
863
+ lband=None, uband=None,
864
+ order=12,
865
+ nsteps=500,
866
+ max_step=0.0, # corresponds to infinite
867
+ min_step=0.0,
868
+ first_step=0.0, # determined by solver
869
+ ):
870
+
871
+ if re.match(method, r'adams', re.I):
872
+ self.meth = 1
873
+ elif re.match(method, r'bdf', re.I):
874
+ self.meth = 2
875
+ else:
876
+ raise ValueError(f'Unknown integration method {method}')
877
+ self.with_jacobian = with_jacobian
878
+ self.rtol = rtol
879
+ self.atol = atol
880
+ self.mu = uband
881
+ self.ml = lband
882
+
883
+ self.order = order
884
+ self.nsteps = nsteps
885
+ self.max_step = max_step
886
+ self.min_step = min_step
887
+ self.first_step = first_step
888
+ self.success = 1
889
+
890
+ self.initialized = False
891
+
892
+ def _determine_mf_and_set_bands(self, has_jac):
893
+ """
894
+ Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
895
+
896
+ In the Fortran code, the legal values of `MF` are:
897
+ 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
898
+ -11, -12, -14, -15, -21, -22, -24, -25
899
+ but this Python wrapper does not use negative values.
900
+
901
+ Returns
902
+
903
+ mf = 10*self.meth + miter
904
+
905
+ self.meth is the linear multistep method:
906
+ self.meth == 1: method="adams"
907
+ self.meth == 2: method="bdf"
908
+
909
+ miter is the correction iteration method:
910
+ miter == 0: Functional iteration; no Jacobian involved.
911
+ miter == 1: Chord iteration with user-supplied full Jacobian.
912
+ miter == 2: Chord iteration with internally computed full Jacobian.
913
+ miter == 3: Chord iteration with internally computed diagonal Jacobian.
914
+ miter == 4: Chord iteration with user-supplied banded Jacobian.
915
+ miter == 5: Chord iteration with internally computed banded Jacobian.
916
+
917
+ Side effects: If either self.mu or self.ml is not None and the other is None,
918
+ then the one that is None is set to 0.
919
+ """
920
+
921
+ jac_is_banded = self.mu is not None or self.ml is not None
922
+ if jac_is_banded:
923
+ if self.mu is None:
924
+ self.mu = 0
925
+ if self.ml is None:
926
+ self.ml = 0
927
+
928
+ # has_jac is True if the user provided a Jacobian function.
929
+ if has_jac:
930
+ if jac_is_banded:
931
+ miter = 4
932
+ else:
933
+ miter = 1
934
+ else:
935
+ if jac_is_banded:
936
+ if self.ml == self.mu == 0:
937
+ miter = 3 # Chord iteration with internal diagonal Jacobian.
938
+ else:
939
+ miter = 5 # Chord iteration with internal banded Jacobian.
940
+ else:
941
+ # self.with_jacobian is set by the user in
942
+ # the call to ode.set_integrator.
943
+ if self.with_jacobian:
944
+ miter = 2 # Chord iteration with internal full Jacobian.
945
+ else:
946
+ miter = 0 # Functional iteration; no Jacobian involved.
947
+
948
+ mf = 10 * self.meth + miter
949
+ return mf
950
+
951
+ def reset(self, n, has_jac):
952
+ mf = self._determine_mf_and_set_bands(has_jac)
953
+
954
+ if mf == 10:
955
+ lrw = 20 + 16 * n
956
+ elif mf in [11, 12]:
957
+ lrw = 22 + 16 * n + 2 * n * n
958
+ elif mf == 13:
959
+ lrw = 22 + 17 * n
960
+ elif mf in [14, 15]:
961
+ lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
962
+ elif mf == 20:
963
+ lrw = 20 + 9 * n
964
+ elif mf in [21, 22]:
965
+ lrw = 22 + 9 * n + 2 * n * n
966
+ elif mf == 23:
967
+ lrw = 22 + 10 * n
968
+ elif mf in [24, 25]:
969
+ lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
970
+ else:
971
+ raise ValueError(f'Unexpected mf={mf}')
972
+
973
+ if mf % 10 in [0, 3]:
974
+ liw = 30
975
+ else:
976
+ liw = 30 + n
977
+
978
+ rwork = zeros((lrw,), float)
979
+ rwork[4] = self.first_step
980
+ rwork[5] = self.max_step
981
+ rwork[6] = self.min_step
982
+ self.rwork = rwork
983
+
984
+ iwork = zeros((liw,), _vode_int_dtype)
985
+ if self.ml is not None:
986
+ iwork[0] = self.ml
987
+ if self.mu is not None:
988
+ iwork[1] = self.mu
989
+ iwork[4] = self.order
990
+ iwork[5] = self.nsteps
991
+ iwork[6] = 2 # mxhnil
992
+ self.iwork = iwork
993
+
994
+ self.call_args = [self.rtol, self.atol, 1, 1,
995
+ self.rwork, self.iwork, mf]
996
+ self.success = 1
997
+ self.initialized = False
998
+
999
+ def run(self, f, jac, y0, t0, t1, f_params, jac_params):
1000
+ if self.initialized:
1001
+ self.check_handle()
1002
+ else:
1003
+ self.initialized = True
1004
+ self.acquire_new_handle()
1005
+
1006
+ if self.ml is not None and self.ml > 0:
1007
+ # Banded Jacobian. Wrap the user-provided function with one
1008
+ # that pads the Jacobian array with the extra `self.ml` rows
1009
+ # required by the f2py-generated wrapper.
1010
+ jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
1011
+
1012
+ args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
1013
+ (f_params, jac_params))
1014
+
1015
+ with VODE_LOCK:
1016
+ y1, t, istate = self.runner(*args)
1017
+
1018
+ self.istate = istate
1019
+ if istate < 0:
1020
+ unexpected_istate_msg = f'Unexpected istate={istate:d}'
1021
+ warnings.warn(f'{self.__class__.__name__:s}: '
1022
+ f'{self.messages.get(istate, unexpected_istate_msg):s}',
1023
+ stacklevel=2)
1024
+ self.success = 0
1025
+ else:
1026
+ self.call_args[3] = 2 # upgrade istate from 1 to 2
1027
+ self.istate = 2
1028
+ return y1, t
1029
+
1030
+ def step(self, *args):
1031
+ itask = self.call_args[2]
1032
+ self.call_args[2] = 2
1033
+ r = self.run(*args)
1034
+ self.call_args[2] = itask
1035
+ return r
1036
+
1037
+ def run_relax(self, *args):
1038
+ itask = self.call_args[2]
1039
+ self.call_args[2] = 3
1040
+ r = self.run(*args)
1041
+ self.call_args[2] = itask
1042
+ return r
1043
+
1044
+
1045
+ if vode.runner is not None:
1046
+ IntegratorBase.integrator_classes.append(vode)
1047
+
1048
+
1049
+ class zvode(vode):
1050
+ runner = getattr(_vode, 'zvode', None)
1051
+
1052
+ supports_run_relax = 1
1053
+ supports_step = 1
1054
+ scalar = complex
1055
+ active_global_handle = 0
1056
+
1057
+ def reset(self, n, has_jac):
1058
+ mf = self._determine_mf_and_set_bands(has_jac)
1059
+
1060
+ if mf in (10,):
1061
+ lzw = 15 * n
1062
+ elif mf in (11, 12):
1063
+ lzw = 15 * n + 2 * n ** 2
1064
+ elif mf in (-11, -12):
1065
+ lzw = 15 * n + n ** 2
1066
+ elif mf in (13,):
1067
+ lzw = 16 * n
1068
+ elif mf in (14, 15):
1069
+ lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
1070
+ elif mf in (-14, -15):
1071
+ lzw = 16 * n + (2 * self.ml + self.mu) * n
1072
+ elif mf in (20,):
1073
+ lzw = 8 * n
1074
+ elif mf in (21, 22):
1075
+ lzw = 8 * n + 2 * n ** 2
1076
+ elif mf in (-21, -22):
1077
+ lzw = 8 * n + n ** 2
1078
+ elif mf in (23,):
1079
+ lzw = 9 * n
1080
+ elif mf in (24, 25):
1081
+ lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
1082
+ elif mf in (-24, -25):
1083
+ lzw = 9 * n + (2 * self.ml + self.mu) * n
1084
+
1085
+ lrw = 20 + n
1086
+
1087
+ if mf % 10 in (0, 3):
1088
+ liw = 30
1089
+ else:
1090
+ liw = 30 + n
1091
+
1092
+ zwork = zeros((lzw,), complex)
1093
+ self.zwork = zwork
1094
+
1095
+ rwork = zeros((lrw,), float)
1096
+ rwork[4] = self.first_step
1097
+ rwork[5] = self.max_step
1098
+ rwork[6] = self.min_step
1099
+ self.rwork = rwork
1100
+
1101
+ iwork = zeros((liw,), _vode_int_dtype)
1102
+ if self.ml is not None:
1103
+ iwork[0] = self.ml
1104
+ if self.mu is not None:
1105
+ iwork[1] = self.mu
1106
+ iwork[4] = self.order
1107
+ iwork[5] = self.nsteps
1108
+ iwork[6] = 2 # mxhnil
1109
+ self.iwork = iwork
1110
+
1111
+ self.call_args = [self.rtol, self.atol, 1, 1,
1112
+ self.zwork, self.rwork, self.iwork, mf]
1113
+ self.success = 1
1114
+ self.initialized = False
1115
+
1116
+
1117
+ if zvode.runner is not None:
1118
+ IntegratorBase.integrator_classes.append(zvode)
1119
+
1120
+
1121
+ class dopri5(IntegratorBase):
1122
+ runner = getattr(_dop, 'dopri5', None)
1123
+ name = 'dopri5'
1124
+ supports_solout = True
1125
+
1126
+ messages = {1: 'computation successful',
1127
+ 2: 'computation successful (interrupted by solout)',
1128
+ -1: 'input is not consistent',
1129
+ -2: 'larger nsteps is needed',
1130
+ -3: 'step size becomes too small',
1131
+ -4: 'problem is probably stiff (interrupted)',
1132
+ }
1133
+
1134
+ def __init__(self,
1135
+ rtol=1e-6, atol=1e-12,
1136
+ nsteps=500,
1137
+ max_step=0.0,
1138
+ first_step=0.0, # determined by solver
1139
+ safety=0.9,
1140
+ ifactor=10.0,
1141
+ dfactor=0.2,
1142
+ beta=0.0,
1143
+ method=None,
1144
+ verbosity=-1, # no messages if negative
1145
+ ):
1146
+ self.rtol = rtol
1147
+ self.atol = atol
1148
+ self.nsteps = nsteps
1149
+ self.max_step = max_step
1150
+ self.first_step = first_step
1151
+ self.safety = safety
1152
+ self.ifactor = ifactor
1153
+ self.dfactor = dfactor
1154
+ self.beta = beta
1155
+ self.verbosity = verbosity
1156
+ self.success = 1
1157
+ self.set_solout(None)
1158
+
1159
+ def set_solout(self, solout, complex=False):
1160
+ self.solout = solout
1161
+ self.solout_cmplx = complex
1162
+ if solout is None:
1163
+ self.iout = 0
1164
+ else:
1165
+ self.iout = 1
1166
+
1167
+ def reset(self, n, has_jac):
1168
+ work = zeros((8 * n + 21,), float)
1169
+ work[1] = self.safety
1170
+ work[2] = self.dfactor
1171
+ work[3] = self.ifactor
1172
+ work[4] = self.beta
1173
+ work[5] = self.max_step
1174
+ work[6] = self.first_step
1175
+ self.work = work
1176
+ iwork = zeros((21,), _dop_int_dtype)
1177
+ iwork[0] = self.nsteps
1178
+ iwork[2] = self.verbosity
1179
+ self.iwork = iwork
1180
+ self.call_args = [self.rtol, self.atol, self._solout,
1181
+ self.iout, self.work, self.iwork]
1182
+ self.success = 1
1183
+
1184
+ def run(self, f, jac, y0, t0, t1, f_params, jac_params):
1185
+ x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
1186
+ tuple(self.call_args) + (f_params,)))
1187
+ self.istate = istate
1188
+ if istate < 0:
1189
+ unexpected_istate_msg = f'Unexpected istate={istate:d}'
1190
+ warnings.warn(f'{self.__class__.__name__:s}: '
1191
+ f'{self.messages.get(istate, unexpected_istate_msg):s}',
1192
+ stacklevel=2)
1193
+ self.success = 0
1194
+ return y, x
1195
+
1196
+ def _solout(self, nr, xold, x, y, nd, icomp, con):
1197
+ if self.solout is not None:
1198
+ if self.solout_cmplx:
1199
+ y = y[::2] + 1j * y[1::2]
1200
+ return self.solout(x, y)
1201
+ else:
1202
+ return 1
1203
+
1204
+
1205
+ if dopri5.runner is not None:
1206
+ IntegratorBase.integrator_classes.append(dopri5)
1207
+
1208
+
1209
+ class dop853(dopri5):
1210
+ runner = getattr(_dop, 'dop853', None)
1211
+ name = 'dop853'
1212
+
1213
+ def __init__(self,
1214
+ rtol=1e-6, atol=1e-12,
1215
+ nsteps=500,
1216
+ max_step=0.0,
1217
+ first_step=0.0, # determined by solver
1218
+ safety=0.9,
1219
+ ifactor=6.0,
1220
+ dfactor=0.3,
1221
+ beta=0.0,
1222
+ method=None,
1223
+ verbosity=-1, # no messages if negative
1224
+ ):
1225
+ super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
1226
+ ifactor, dfactor, beta, method, verbosity)
1227
+
1228
+ def reset(self, n, has_jac):
1229
+ work = zeros((11 * n + 21,), float)
1230
+ work[1] = self.safety
1231
+ work[2] = self.dfactor
1232
+ work[3] = self.ifactor
1233
+ work[4] = self.beta
1234
+ work[5] = self.max_step
1235
+ work[6] = self.first_step
1236
+ self.work = work
1237
+ iwork = zeros((21,), _dop_int_dtype)
1238
+ iwork[0] = self.nsteps
1239
+ iwork[2] = self.verbosity
1240
+ self.iwork = iwork
1241
+ self.call_args = [self.rtol, self.atol, self._solout,
1242
+ self.iout, self.work, self.iwork]
1243
+ self.success = 1
1244
+
1245
+
1246
+ if dop853.runner is not None:
1247
+ IntegratorBase.integrator_classes.append(dop853)
1248
+
1249
+
1250
+ class lsoda(IntegratorBase):
1251
+ runner = getattr(_lsoda, 'lsoda', None)
1252
+ active_global_handle = 0
1253
+
1254
+ messages = {
1255
+ 2: "Integration successful.",
1256
+ -1: "Excess work done on this call (perhaps wrong Dfun type).",
1257
+ -2: "Excess accuracy requested (tolerances too small).",
1258
+ -3: "Illegal input detected (internal error).",
1259
+ -4: "Repeated error test failures (internal error).",
1260
+ -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
1261
+ -6: "Error weight became zero during problem.",
1262
+ -7: "Internal workspace insufficient to finish (internal error)."
1263
+ }
1264
+
1265
+ def __init__(self,
1266
+ with_jacobian=False,
1267
+ rtol=1e-6, atol=1e-12,
1268
+ lband=None, uband=None,
1269
+ nsteps=500,
1270
+ max_step=0.0, # corresponds to infinite
1271
+ min_step=0.0,
1272
+ first_step=0.0, # determined by solver
1273
+ ixpr=0,
1274
+ max_hnil=0,
1275
+ max_order_ns=12,
1276
+ max_order_s=5,
1277
+ method=None
1278
+ ):
1279
+
1280
+ self.with_jacobian = with_jacobian
1281
+ self.rtol = rtol
1282
+ self.atol = atol
1283
+ self.mu = uband
1284
+ self.ml = lband
1285
+
1286
+ self.max_order_ns = max_order_ns
1287
+ self.max_order_s = max_order_s
1288
+ self.nsteps = nsteps
1289
+ self.max_step = max_step
1290
+ self.min_step = min_step
1291
+ self.first_step = first_step
1292
+ self.ixpr = ixpr
1293
+ self.max_hnil = max_hnil
1294
+ self.success = 1
1295
+
1296
+ self.initialized = False
1297
+
1298
+ def reset(self, n, has_jac):
1299
+ # Calculate parameters for Fortran subroutine dvode.
1300
+ if has_jac:
1301
+ if self.mu is None and self.ml is None:
1302
+ jt = 1
1303
+ else:
1304
+ if self.mu is None:
1305
+ self.mu = 0
1306
+ if self.ml is None:
1307
+ self.ml = 0
1308
+ jt = 4
1309
+ else:
1310
+ if self.mu is None and self.ml is None:
1311
+ jt = 2
1312
+ else:
1313
+ if self.mu is None:
1314
+ self.mu = 0
1315
+ if self.ml is None:
1316
+ self.ml = 0
1317
+ jt = 5
1318
+ lrn = 20 + (self.max_order_ns + 4) * n
1319
+ if jt in [1, 2]:
1320
+ lrs = 22 + (self.max_order_s + 4) * n + n * n
1321
+ elif jt in [4, 5]:
1322
+ lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
1323
+ else:
1324
+ raise ValueError(f'Unexpected jt={jt}')
1325
+ lrw = max(lrn, lrs)
1326
+ liw = 20 + n
1327
+ rwork = zeros((lrw,), float)
1328
+ rwork[4] = self.first_step
1329
+ rwork[5] = self.max_step
1330
+ rwork[6] = self.min_step
1331
+ self.rwork = rwork
1332
+ iwork = zeros((liw,), _lsoda_int_dtype)
1333
+ if self.ml is not None:
1334
+ iwork[0] = self.ml
1335
+ if self.mu is not None:
1336
+ iwork[1] = self.mu
1337
+ iwork[4] = self.ixpr
1338
+ iwork[5] = self.nsteps
1339
+ iwork[6] = self.max_hnil
1340
+ iwork[7] = self.max_order_ns
1341
+ iwork[8] = self.max_order_s
1342
+ self.iwork = iwork
1343
+ self.call_args = [self.rtol, self.atol, 1, 1,
1344
+ self.rwork, self.iwork, jt]
1345
+ self.success = 1
1346
+ self.initialized = False
1347
+
1348
+ def run(self, f, jac, y0, t0, t1, f_params, jac_params):
1349
+ if self.initialized:
1350
+ self.check_handle()
1351
+ else:
1352
+ self.initialized = True
1353
+ self.acquire_new_handle()
1354
+ args = [f, y0, t0, t1] + self.call_args[:-1] + \
1355
+ [jac, self.call_args[-1], f_params, 0, jac_params]
1356
+
1357
+ with LSODA_LOCK:
1358
+ y1, t, istate = self.runner(*args)
1359
+
1360
+ self.istate = istate
1361
+ if istate < 0:
1362
+ unexpected_istate_msg = f'Unexpected istate={istate:d}'
1363
+ warnings.warn(f'{self.__class__.__name__:s}: '
1364
+ f'{self.messages.get(istate, unexpected_istate_msg):s}',
1365
+ stacklevel=2)
1366
+ self.success = 0
1367
+ else:
1368
+ self.call_args[3] = 2 # upgrade istate from 1 to 2
1369
+ self.istate = 2
1370
+ return y1, t
1371
+
1372
+ def step(self, *args):
1373
+ itask = self.call_args[2]
1374
+ self.call_args[2] = 2
1375
+ r = self.run(*args)
1376
+ self.call_args[2] = itask
1377
+ return r
1378
+
1379
+ def run_relax(self, *args):
1380
+ itask = self.call_args[2]
1381
+ self.call_args[2] = 3
1382
+ r = self.run(*args)
1383
+ self.call_args[2] = itask
1384
+ return r
1385
+
1386
+
1387
+ if lsoda.runner:
1388
+ IntegratorBase.integrator_classes.append(lsoda)