Reset repository and upload final project (part 22)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +24 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_basic.py +877 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_helper.py +54 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_import.py +33 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py +388 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_real_transforms.py +836 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._LICENSE_DOP +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__bvp.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__cubature.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__dop.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__ivp +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__lebedev.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__ode.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__odepack.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__odepack_py.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quad_vec.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadpack.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadpack_py.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadrature.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__rules +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__tanhsinh.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__test_multivariate.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__vode.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._dop.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._lsoda.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._odepack.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._quadpack.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._tests +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/._vode.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/LICENSE_DOP +76 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/__init__.py +122 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_bvp.py +1162 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_cubature.py +731 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-darwin.so +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._base.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._bdf.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._common.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._dop853_coefficients.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._ivp.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._lsoda.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._radau.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._rk.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._tests +0 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/__init__.py +8 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/base.py +298 -0
- .venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py +479 -0
.gitattributes
CHANGED
|
@@ -131,3 +131,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 131 |
.venv_haddock/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 132 |
.venv_haddock/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 133 |
.venv_haddock/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
.venv_haddock/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 132 |
.venv_haddock/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 133 |
.venv_haddock/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 134 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 135 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 136 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_dfitpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 137 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 138 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_fitpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 139 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 140 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 141 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 142 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 143 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 144 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 145 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 146 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_batched_linalg.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 147 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 148 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 149 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_decomp_lu_cython.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 150 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 151 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 152 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 153 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 154 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_matfuncs_expm.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 155 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 156 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 157 |
+
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
.venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_basic.py
ADDED
|
@@ -0,0 +1,877 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 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, err_msg=f"size={size}")
|
| 354 |
+
assert_array_almost_equal(y2, x, decimal=self.ndec, err_msg=f"size={size}")
|
| 355 |
+
|
| 356 |
+
def test_size_accuracy(self):
|
| 357 |
+
# Sanity check for the accuracy for prime and non-prime sized inputs
|
| 358 |
+
if self.rdt == np.float32:
|
| 359 |
+
rtol = 1e-5
|
| 360 |
+
elif self.rdt == np.float64:
|
| 361 |
+
rtol = 1e-10
|
| 362 |
+
|
| 363 |
+
for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
|
| 364 |
+
np.random.seed(1234)
|
| 365 |
+
x = np.random.rand(size).astype(self.rdt)
|
| 366 |
+
y = irfft(rfft(x))
|
| 367 |
+
_assert_close_in_norm(x, y, rtol, size, self.rdt)
|
| 368 |
+
y = rfft(irfft(x))
|
| 369 |
+
_assert_close_in_norm(x, y, rtol, size, self.rdt)
|
| 370 |
+
|
| 371 |
+
def test_invalid_sizes(self):
|
| 372 |
+
assert_raises(ValueError, irfft, [])
|
| 373 |
+
assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
|
| 374 |
+
|
| 375 |
+
def test_complex_input(self):
|
| 376 |
+
assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# self.ndec is bogus; we should have a assert_array_approx_equal for number of
|
| 380 |
+
# significant digits
|
| 381 |
+
|
| 382 |
+
class TestIRFFTDouble(_TestIRFFTBase):
|
| 383 |
+
def setup_method(self):
|
| 384 |
+
self.cdt = np.complex128
|
| 385 |
+
self.rdt = np.float64
|
| 386 |
+
self.ndec = 14
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class TestIRFFTSingle(_TestIRFFTBase):
|
| 390 |
+
def setup_method(self):
|
| 391 |
+
self.cdt = np.complex64
|
| 392 |
+
self.rdt = np.float32
|
| 393 |
+
self.ndec = 5
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class Testfft2:
|
| 397 |
+
def setup_method(self):
|
| 398 |
+
np.random.seed(1234)
|
| 399 |
+
|
| 400 |
+
def test_regression_244(self):
|
| 401 |
+
"""FFT returns wrong result with axes parameter."""
|
| 402 |
+
# fftn (and hence fft2) used to break when both axes and shape were
|
| 403 |
+
# used
|
| 404 |
+
x = numpy.ones((4, 4, 2))
|
| 405 |
+
y = fft2(x, shape=(8, 8), axes=(-3, -2))
|
| 406 |
+
y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
|
| 407 |
+
assert_array_almost_equal(y, y_r)
|
| 408 |
+
|
| 409 |
+
def test_invalid_sizes(self):
|
| 410 |
+
assert_raises(ValueError, fft2, [[]])
|
| 411 |
+
assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class TestFftnSingle:
|
| 415 |
+
def setup_method(self):
|
| 416 |
+
np.random.seed(1234)
|
| 417 |
+
|
| 418 |
+
def test_definition(self):
|
| 419 |
+
x = [[1, 2, 3],
|
| 420 |
+
[4, 5, 6],
|
| 421 |
+
[7, 8, 9]]
|
| 422 |
+
y = fftn(np.array(x, np.float32))
|
| 423 |
+
assert_(y.dtype == np.complex64,
|
| 424 |
+
msg="double precision output with single precision")
|
| 425 |
+
|
| 426 |
+
y_r = np.array(fftn(x), np.complex64)
|
| 427 |
+
assert_array_almost_equal_nulp(y, y_r)
|
| 428 |
+
|
| 429 |
+
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
|
| 430 |
+
def test_size_accuracy_small(self, size):
|
| 431 |
+
rng = np.random.default_rng(1234)
|
| 432 |
+
x = rng.random((size, size)) + 1j*rng.random((size, size))
|
| 433 |
+
y1 = fftn(x.real.astype(np.float32))
|
| 434 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
| 435 |
+
|
| 436 |
+
assert_equal(y1.dtype, np.complex64)
|
| 437 |
+
assert_array_almost_equal_nulp(y1, y2, 2000)
|
| 438 |
+
|
| 439 |
+
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
|
| 440 |
+
def test_size_accuracy_large(self, size):
|
| 441 |
+
rand = np.random.default_rng(1234)
|
| 442 |
+
x = rand.random((size, 3)) + 1j*rand.random((size, 3))
|
| 443 |
+
y1 = fftn(x.real.astype(np.float32))
|
| 444 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
| 445 |
+
|
| 446 |
+
assert_equal(y1.dtype, np.complex64)
|
| 447 |
+
assert_array_almost_equal_nulp(y1, y2, 2000)
|
| 448 |
+
|
| 449 |
+
def test_definition_float16(self):
|
| 450 |
+
x = [[1, 2, 3],
|
| 451 |
+
[4, 5, 6],
|
| 452 |
+
[7, 8, 9]]
|
| 453 |
+
y = fftn(np.array(x, np.float16))
|
| 454 |
+
assert_equal(y.dtype, np.complex64)
|
| 455 |
+
y_r = np.array(fftn(x), np.complex64)
|
| 456 |
+
assert_array_almost_equal_nulp(y, y_r)
|
| 457 |
+
|
| 458 |
+
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
|
| 459 |
+
def test_float16_input_small(self, size):
|
| 460 |
+
rng = np.random.default_rng(1234)
|
| 461 |
+
x = rng.random((size, size)) + 1j * rng.random((size, size))
|
| 462 |
+
y1 = fftn(x.real.astype(np.float16))
|
| 463 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
| 464 |
+
|
| 465 |
+
assert_equal(y1.dtype, np.complex64)
|
| 466 |
+
assert_array_almost_equal_nulp(y1, y2, 5e5)
|
| 467 |
+
|
| 468 |
+
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
|
| 469 |
+
def test_float16_input_large(self, size):
|
| 470 |
+
rng = np.random.default_rng(1234)
|
| 471 |
+
x = rng.random((size, 3)) + 1j*rng.random((size, 3))
|
| 472 |
+
y1 = fftn(x.real.astype(np.float16))
|
| 473 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
| 474 |
+
|
| 475 |
+
assert_equal(y1.dtype, np.complex64)
|
| 476 |
+
assert_array_almost_equal_nulp(y1, y2, 2e6)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
class TestFftn:
|
| 480 |
+
def setup_method(self):
|
| 481 |
+
np.random.seed(1234)
|
| 482 |
+
|
| 483 |
+
def test_definition(self):
|
| 484 |
+
x = [[1, 2, 3],
|
| 485 |
+
[4, 5, 6],
|
| 486 |
+
[7, 8, 9]]
|
| 487 |
+
y = fftn(x)
|
| 488 |
+
assert_array_almost_equal(y, direct_dftn(x))
|
| 489 |
+
|
| 490 |
+
x = random((20, 26))
|
| 491 |
+
assert_array_almost_equal(fftn(x), direct_dftn(x))
|
| 492 |
+
|
| 493 |
+
x = random((5, 4, 3, 20))
|
| 494 |
+
assert_array_almost_equal(fftn(x), direct_dftn(x))
|
| 495 |
+
|
| 496 |
+
def test_axes_argument(self):
|
| 497 |
+
# plane == ji_plane, x== kji_space
|
| 498 |
+
plane1 = [[1, 2, 3],
|
| 499 |
+
[4, 5, 6],
|
| 500 |
+
[7, 8, 9]]
|
| 501 |
+
plane2 = [[10, 11, 12],
|
| 502 |
+
[13, 14, 15],
|
| 503 |
+
[16, 17, 18]]
|
| 504 |
+
plane3 = [[19, 20, 21],
|
| 505 |
+
[22, 23, 24],
|
| 506 |
+
[25, 26, 27]]
|
| 507 |
+
ki_plane1 = [[1, 2, 3],
|
| 508 |
+
[10, 11, 12],
|
| 509 |
+
[19, 20, 21]]
|
| 510 |
+
ki_plane2 = [[4, 5, 6],
|
| 511 |
+
[13, 14, 15],
|
| 512 |
+
[22, 23, 24]]
|
| 513 |
+
ki_plane3 = [[7, 8, 9],
|
| 514 |
+
[16, 17, 18],
|
| 515 |
+
[25, 26, 27]]
|
| 516 |
+
jk_plane1 = [[1, 10, 19],
|
| 517 |
+
[4, 13, 22],
|
| 518 |
+
[7, 16, 25]]
|
| 519 |
+
jk_plane2 = [[2, 11, 20],
|
| 520 |
+
[5, 14, 23],
|
| 521 |
+
[8, 17, 26]]
|
| 522 |
+
jk_plane3 = [[3, 12, 21],
|
| 523 |
+
[6, 15, 24],
|
| 524 |
+
[9, 18, 27]]
|
| 525 |
+
kj_plane1 = [[1, 4, 7],
|
| 526 |
+
[10, 13, 16], [19, 22, 25]]
|
| 527 |
+
kj_plane2 = [[2, 5, 8],
|
| 528 |
+
[11, 14, 17], [20, 23, 26]]
|
| 529 |
+
kj_plane3 = [[3, 6, 9],
|
| 530 |
+
[12, 15, 18], [21, 24, 27]]
|
| 531 |
+
ij_plane1 = [[1, 4, 7],
|
| 532 |
+
[2, 5, 8],
|
| 533 |
+
[3, 6, 9]]
|
| 534 |
+
ij_plane2 = [[10, 13, 16],
|
| 535 |
+
[11, 14, 17],
|
| 536 |
+
[12, 15, 18]]
|
| 537 |
+
ij_plane3 = [[19, 22, 25],
|
| 538 |
+
[20, 23, 26],
|
| 539 |
+
[21, 24, 27]]
|
| 540 |
+
ik_plane1 = [[1, 10, 19],
|
| 541 |
+
[2, 11, 20],
|
| 542 |
+
[3, 12, 21]]
|
| 543 |
+
ik_plane2 = [[4, 13, 22],
|
| 544 |
+
[5, 14, 23],
|
| 545 |
+
[6, 15, 24]]
|
| 546 |
+
ik_plane3 = [[7, 16, 25],
|
| 547 |
+
[8, 17, 26],
|
| 548 |
+
[9, 18, 27]]
|
| 549 |
+
ijk_space = [jk_plane1, jk_plane2, jk_plane3]
|
| 550 |
+
ikj_space = [kj_plane1, kj_plane2, kj_plane3]
|
| 551 |
+
jik_space = [ik_plane1, ik_plane2, ik_plane3]
|
| 552 |
+
jki_space = [ki_plane1, ki_plane2, ki_plane3]
|
| 553 |
+
kij_space = [ij_plane1, ij_plane2, ij_plane3]
|
| 554 |
+
x = array([plane1, plane2, plane3])
|
| 555 |
+
|
| 556 |
+
assert_array_almost_equal(fftn(x),
|
| 557 |
+
fftn(x, axes=(-3, -2, -1))) # kji_space
|
| 558 |
+
assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
|
| 559 |
+
assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
|
| 560 |
+
y = fftn(x, axes=(2, 1, 0)) # ijk_space
|
| 561 |
+
assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
|
| 562 |
+
y = fftn(x, axes=(2, 0, 1)) # ikj_space
|
| 563 |
+
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
|
| 564 |
+
fftn(ikj_space))
|
| 565 |
+
y = fftn(x, axes=(1, 2, 0)) # jik_space
|
| 566 |
+
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
|
| 567 |
+
fftn(jik_space))
|
| 568 |
+
y = fftn(x, axes=(1, 0, 2)) # jki_space
|
| 569 |
+
assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
|
| 570 |
+
y = fftn(x, axes=(0, 2, 1)) # kij_space
|
| 571 |
+
assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
|
| 572 |
+
|
| 573 |
+
y = fftn(x, axes=(-2, -1)) # ji_plane
|
| 574 |
+
assert_array_almost_equal(fftn(plane1), y[0])
|
| 575 |
+
assert_array_almost_equal(fftn(plane2), y[1])
|
| 576 |
+
assert_array_almost_equal(fftn(plane3), y[2])
|
| 577 |
+
|
| 578 |
+
y = fftn(x, axes=(1, 2)) # ji_plane
|
| 579 |
+
assert_array_almost_equal(fftn(plane1), y[0])
|
| 580 |
+
assert_array_almost_equal(fftn(plane2), y[1])
|
| 581 |
+
assert_array_almost_equal(fftn(plane3), y[2])
|
| 582 |
+
|
| 583 |
+
y = fftn(x, axes=(-3, -2)) # kj_plane
|
| 584 |
+
assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
|
| 585 |
+
assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
|
| 586 |
+
assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
|
| 587 |
+
|
| 588 |
+
y = fftn(x, axes=(-3, -1)) # ki_plane
|
| 589 |
+
assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
|
| 590 |
+
assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
|
| 591 |
+
assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
|
| 592 |
+
|
| 593 |
+
y = fftn(x, axes=(-1, -2)) # ij_plane
|
| 594 |
+
assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
|
| 595 |
+
assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
|
| 596 |
+
assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
|
| 597 |
+
|
| 598 |
+
y = fftn(x, axes=(-1, -3)) # ik_plane
|
| 599 |
+
assert_array_almost_equal(fftn(ik_plane1),
|
| 600 |
+
swapaxes(y[:, 0, :], -1, -2))
|
| 601 |
+
assert_array_almost_equal(fftn(ik_plane2),
|
| 602 |
+
swapaxes(y[:, 1, :], -1, -2))
|
| 603 |
+
assert_array_almost_equal(fftn(ik_plane3),
|
| 604 |
+
swapaxes(y[:, 2, :], -1, -2))
|
| 605 |
+
|
| 606 |
+
y = fftn(x, axes=(-2, -3)) # jk_plane
|
| 607 |
+
assert_array_almost_equal(fftn(jk_plane1),
|
| 608 |
+
swapaxes(y[:, :, 0], -1, -2))
|
| 609 |
+
assert_array_almost_equal(fftn(jk_plane2),
|
| 610 |
+
swapaxes(y[:, :, 1], -1, -2))
|
| 611 |
+
assert_array_almost_equal(fftn(jk_plane3),
|
| 612 |
+
swapaxes(y[:, :, 2], -1, -2))
|
| 613 |
+
|
| 614 |
+
y = fftn(x, axes=(-1,)) # i_line
|
| 615 |
+
for i in range(3):
|
| 616 |
+
for j in range(3):
|
| 617 |
+
assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
|
| 618 |
+
y = fftn(x, axes=(-2,)) # j_line
|
| 619 |
+
for i in range(3):
|
| 620 |
+
for j in range(3):
|
| 621 |
+
assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
|
| 622 |
+
y = fftn(x, axes=(0,)) # k_line
|
| 623 |
+
for i in range(3):
|
| 624 |
+
for j in range(3):
|
| 625 |
+
assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
|
| 626 |
+
|
| 627 |
+
y = fftn(x, axes=()) # point
|
| 628 |
+
assert_array_almost_equal(y, x)
|
| 629 |
+
|
| 630 |
+
def test_shape_argument(self):
|
| 631 |
+
small_x = [[1, 2, 3],
|
| 632 |
+
[4, 5, 6]]
|
| 633 |
+
large_x1 = [[1, 2, 3, 0],
|
| 634 |
+
[4, 5, 6, 0],
|
| 635 |
+
[0, 0, 0, 0],
|
| 636 |
+
[0, 0, 0, 0]]
|
| 637 |
+
|
| 638 |
+
y = fftn(small_x, shape=(4, 4))
|
| 639 |
+
assert_array_almost_equal(y, fftn(large_x1))
|
| 640 |
+
|
| 641 |
+
y = fftn(small_x, shape=(3, 4))
|
| 642 |
+
assert_array_almost_equal(y, fftn(large_x1[:-1]))
|
| 643 |
+
|
| 644 |
+
def test_shape_axes_argument(self):
|
| 645 |
+
small_x = [[1, 2, 3],
|
| 646 |
+
[4, 5, 6],
|
| 647 |
+
[7, 8, 9]]
|
| 648 |
+
large_x1 = array([[1, 2, 3, 0],
|
| 649 |
+
[4, 5, 6, 0],
|
| 650 |
+
[7, 8, 9, 0],
|
| 651 |
+
[0, 0, 0, 0]])
|
| 652 |
+
y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
|
| 653 |
+
assert_array_almost_equal(y, fftn(large_x1))
|
| 654 |
+
y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
|
| 655 |
+
|
| 656 |
+
assert_array_almost_equal(y, swapaxes(
|
| 657 |
+
fftn(swapaxes(large_x1, -1, -2)), -1, -2))
|
| 658 |
+
|
| 659 |
+
def test_shape_axes_argument2(self):
|
| 660 |
+
# Change shape of the last axis
|
| 661 |
+
x = numpy.random.random((10, 5, 3, 7))
|
| 662 |
+
y = fftn(x, axes=(-1,), shape=(8,))
|
| 663 |
+
assert_array_almost_equal(y, fft(x, axis=-1, n=8))
|
| 664 |
+
|
| 665 |
+
# Change shape of an arbitrary axis which is not the last one
|
| 666 |
+
x = numpy.random.random((10, 5, 3, 7))
|
| 667 |
+
y = fftn(x, axes=(-2,), shape=(8,))
|
| 668 |
+
assert_array_almost_equal(y, fft(x, axis=-2, n=8))
|
| 669 |
+
|
| 670 |
+
# Change shape of axes: cf #244, where shape and axes were mixed up
|
| 671 |
+
x = numpy.random.random((4, 4, 2))
|
| 672 |
+
y = fftn(x, axes=(-3, -2), shape=(8, 8))
|
| 673 |
+
assert_array_almost_equal(y,
|
| 674 |
+
numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
|
| 675 |
+
|
| 676 |
+
def test_shape_argument_more(self):
|
| 677 |
+
x = zeros((4, 4, 2))
|
| 678 |
+
with assert_raises(ValueError,
|
| 679 |
+
match="when given, axes and shape arguments"
|
| 680 |
+
" have to be of the same length"):
|
| 681 |
+
fftn(x, shape=(8, 8, 2, 1))
|
| 682 |
+
|
| 683 |
+
def test_invalid_sizes(self):
|
| 684 |
+
with assert_raises(ValueError,
|
| 685 |
+
match="invalid number of data points"
|
| 686 |
+
r" \(\[1, 0\]\) specified"):
|
| 687 |
+
fftn([[]])
|
| 688 |
+
|
| 689 |
+
with assert_raises(ValueError,
|
| 690 |
+
match="invalid number of data points"
|
| 691 |
+
r" \(\[4, -3\]\) specified"):
|
| 692 |
+
fftn([[1, 1], [2, 2]], (4, -3))
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
class TestIfftn:
|
| 696 |
+
dtype = None
|
| 697 |
+
cdtype = None
|
| 698 |
+
|
| 699 |
+
def setup_method(self):
|
| 700 |
+
np.random.seed(1234)
|
| 701 |
+
|
| 702 |
+
@pytest.mark.parametrize('dtype,cdtype,maxnlp',
|
| 703 |
+
[(np.float64, np.complex128, 2000),
|
| 704 |
+
(np.float32, np.complex64, 3500)])
|
| 705 |
+
def test_definition(self, dtype, cdtype, maxnlp):
|
| 706 |
+
rng = np.random.default_rng(1234)
|
| 707 |
+
x = np.array([[1, 2, 3],
|
| 708 |
+
[4, 5, 6],
|
| 709 |
+
[7, 8, 9]], dtype=dtype)
|
| 710 |
+
y = ifftn(x)
|
| 711 |
+
assert_equal(y.dtype, cdtype)
|
| 712 |
+
assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
|
| 713 |
+
|
| 714 |
+
x = rng.random((20, 26))
|
| 715 |
+
assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
|
| 716 |
+
|
| 717 |
+
x = rng.random((5, 4, 3, 20))
|
| 718 |
+
assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
|
| 719 |
+
|
| 720 |
+
@pytest.mark.parametrize('maxnlp', [2000, 3500])
|
| 721 |
+
@pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
|
| 722 |
+
def test_random_complex(self, maxnlp, size):
|
| 723 |
+
rng = np.random.default_rng(1234)
|
| 724 |
+
x = rng.random([size, size]) + 1j * rng.random([size, size])
|
| 725 |
+
assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
|
| 726 |
+
assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
|
| 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 |
+
ifftn([[]])
|
| 733 |
+
|
| 734 |
+
with assert_raises(ValueError,
|
| 735 |
+
match="invalid number of data points"
|
| 736 |
+
r" \(\[4, -3\]\) specified"):
|
| 737 |
+
ifftn([[1, 1], [2, 2]], (4, -3))
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
class FakeArray:
|
| 741 |
+
def __init__(self, data):
|
| 742 |
+
self._data = data
|
| 743 |
+
self.__array_interface__ = data.__array_interface__
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
class FakeArray2:
|
| 747 |
+
def __init__(self, data):
|
| 748 |
+
self._data = data
|
| 749 |
+
|
| 750 |
+
def __array__(self, dtype=None, copy=None):
|
| 751 |
+
return self._data
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class TestOverwrite:
|
| 755 |
+
"""Check input overwrite behavior of the FFT functions."""
|
| 756 |
+
|
| 757 |
+
real_dtypes = (np.float32, np.float64)
|
| 758 |
+
dtypes = real_dtypes + (np.complex64, np.complex128)
|
| 759 |
+
fftsizes = [8, 16, 32]
|
| 760 |
+
|
| 761 |
+
def _check(self, x, routine, fftsize, axis, overwrite_x):
|
| 762 |
+
x2 = x.copy()
|
| 763 |
+
for fake in [lambda x: x, FakeArray, FakeArray2]:
|
| 764 |
+
routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
|
| 765 |
+
|
| 766 |
+
sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
|
| 767 |
+
f"axis={axis!r}, overwrite_x={overwrite_x!r})")
|
| 768 |
+
if not overwrite_x:
|
| 769 |
+
assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
|
| 770 |
+
|
| 771 |
+
def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
|
| 772 |
+
fftsize, overwrite_x):
|
| 773 |
+
np.random.seed(1234)
|
| 774 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 775 |
+
data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
|
| 776 |
+
else:
|
| 777 |
+
data = np.random.randn(*shape)
|
| 778 |
+
data = data.astype(dtype)
|
| 779 |
+
|
| 780 |
+
self._check(data, routine, fftsize, axis,
|
| 781 |
+
overwrite_x=overwrite_x)
|
| 782 |
+
|
| 783 |
+
@pytest.mark.parametrize('dtype', dtypes)
|
| 784 |
+
@pytest.mark.parametrize('fftsize', fftsizes)
|
| 785 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
| 786 |
+
@pytest.mark.parametrize('shape,axes', [((16,), -1),
|
| 787 |
+
((16, 2), 0),
|
| 788 |
+
((2, 16), 1)])
|
| 789 |
+
def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
|
| 790 |
+
overwritable = (np.complex128, np.complex64)
|
| 791 |
+
self._check_1d(fft, dtype, shape, axes, overwritable,
|
| 792 |
+
fftsize, overwrite_x)
|
| 793 |
+
self._check_1d(ifft, dtype, shape, axes, overwritable,
|
| 794 |
+
fftsize, overwrite_x)
|
| 795 |
+
|
| 796 |
+
@pytest.mark.parametrize('dtype', real_dtypes)
|
| 797 |
+
@pytest.mark.parametrize('fftsize', fftsizes)
|
| 798 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
| 799 |
+
@pytest.mark.parametrize('shape,axes', [((16,), -1),
|
| 800 |
+
((16, 2), 0),
|
| 801 |
+
((2, 16), 1)])
|
| 802 |
+
def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
|
| 803 |
+
overwritable = self.real_dtypes
|
| 804 |
+
self._check_1d(irfft, dtype, shape, axes, overwritable,
|
| 805 |
+
fftsize, overwrite_x)
|
| 806 |
+
self._check_1d(rfft, dtype, shape, axes, overwritable,
|
| 807 |
+
fftsize, overwrite_x)
|
| 808 |
+
|
| 809 |
+
def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
|
| 810 |
+
overwrite_x):
|
| 811 |
+
np.random.seed(1234)
|
| 812 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 813 |
+
data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
|
| 814 |
+
else:
|
| 815 |
+
data = np.random.randn(*shape)
|
| 816 |
+
data = data.astype(dtype)
|
| 817 |
+
|
| 818 |
+
def fftshape_iter(shp):
|
| 819 |
+
if len(shp) <= 0:
|
| 820 |
+
yield ()
|
| 821 |
+
else:
|
| 822 |
+
for j in (shp[0]//2, shp[0], shp[0]*2):
|
| 823 |
+
for rest in fftshape_iter(shp[1:]):
|
| 824 |
+
yield (j,) + rest
|
| 825 |
+
|
| 826 |
+
if axes is None:
|
| 827 |
+
part_shape = shape
|
| 828 |
+
else:
|
| 829 |
+
part_shape = tuple(np.take(shape, axes))
|
| 830 |
+
|
| 831 |
+
for fftshape in fftshape_iter(part_shape):
|
| 832 |
+
self._check(data, routine, fftshape, axes,
|
| 833 |
+
overwrite_x=overwrite_x)
|
| 834 |
+
if data.ndim > 1:
|
| 835 |
+
self._check(data.T, routine, fftshape, axes,
|
| 836 |
+
overwrite_x=overwrite_x)
|
| 837 |
+
|
| 838 |
+
@pytest.mark.parametrize('dtype', dtypes)
|
| 839 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
| 840 |
+
@pytest.mark.parametrize('shape,axes', [((16,), None),
|
| 841 |
+
((16,), (0,)),
|
| 842 |
+
((16, 2), (0,)),
|
| 843 |
+
((2, 16), (1,)),
|
| 844 |
+
((8, 16), None),
|
| 845 |
+
((8, 16), (0, 1)),
|
| 846 |
+
((8, 16, 2), (0, 1)),
|
| 847 |
+
((8, 16, 2), (1, 2)),
|
| 848 |
+
((8, 16, 2), (0,)),
|
| 849 |
+
((8, 16, 2), (1,)),
|
| 850 |
+
((8, 16, 2), (2,)),
|
| 851 |
+
((8, 16, 2), None),
|
| 852 |
+
((8, 16, 2), (0, 1, 2))])
|
| 853 |
+
def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
|
| 854 |
+
overwritable = (np.complex128, np.complex64)
|
| 855 |
+
self._check_nd_one(fftn, dtype, shape, axes, overwritable,
|
| 856 |
+
overwrite_x)
|
| 857 |
+
self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
|
| 858 |
+
overwrite_x)
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
@pytest.mark.parametrize('func', [fftn, ifftn, fft2])
|
| 862 |
+
def test_shape_axes_ndarray(func):
|
| 863 |
+
# Test fftn and ifftn work with NumPy arrays for shape and axes arguments
|
| 864 |
+
# Regression test for gh-13342
|
| 865 |
+
a = np.random.rand(10, 10)
|
| 866 |
+
|
| 867 |
+
expect = func(a, shape=(5, 5))
|
| 868 |
+
actual = func(a, shape=np.array([5, 5]))
|
| 869 |
+
assert_equal(expect, actual)
|
| 870 |
+
|
| 871 |
+
expect = func(a, axes=(-1,))
|
| 872 |
+
actual = func(a, axes=np.array([-1,]))
|
| 873 |
+
assert_equal(expect, actual)
|
| 874 |
+
|
| 875 |
+
expect = func(a, shape=(4, 7), axes=(1, 0))
|
| 876 |
+
actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
|
| 877 |
+
assert_equal(expect, actual)
|
.venv_haddock/lib/python3.12/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)
|
.venv_haddock/lib/python3.12/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")
|
.venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
.venv_haddock/lib/python3.12/site-packages/scipy/fftpack/tests/test_real_transforms.py
ADDED
|
@@ -0,0 +1,836 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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[f'x{i}'] for i in range(8)]
|
| 15 |
+
Y = [MDATA[f'y{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[f'dct_{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[f'dst_{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=f"Size {i} failed")
|
| 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=f"Size {i} failed")
|
| 385 |
+
|
| 386 |
+
class TestIDCTIDouble(_TestIDCTBase):
|
| 387 |
+
def setup_method(self):
|
| 388 |
+
self.rdt = np.float64
|
| 389 |
+
self.dec = 10
|
| 390 |
+
self.type = 1
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class TestIDCTIFloat(_TestIDCTBase):
|
| 394 |
+
def setup_method(self):
|
| 395 |
+
self.rdt = np.float32
|
| 396 |
+
self.dec = 4
|
| 397 |
+
self.type = 1
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class TestIDCTIInt(_TestIDCTBase):
|
| 401 |
+
def setup_method(self):
|
| 402 |
+
self.rdt = int
|
| 403 |
+
self.dec = 4
|
| 404 |
+
self.type = 1
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class TestIDCTIIDouble(_TestIDCTBase):
|
| 408 |
+
def setup_method(self):
|
| 409 |
+
self.rdt = np.float64
|
| 410 |
+
self.dec = 10
|
| 411 |
+
self.type = 2
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class TestIDCTIIFloat(_TestIDCTBase):
|
| 415 |
+
def setup_method(self):
|
| 416 |
+
self.rdt = np.float32
|
| 417 |
+
self.dec = 5
|
| 418 |
+
self.type = 2
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class TestIDCTIIInt(_TestIDCTBase):
|
| 422 |
+
def setup_method(self):
|
| 423 |
+
self.rdt = int
|
| 424 |
+
self.dec = 5
|
| 425 |
+
self.type = 2
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class TestIDCTIIIDouble(_TestIDCTBase):
|
| 429 |
+
def setup_method(self):
|
| 430 |
+
self.rdt = np.float64
|
| 431 |
+
self.dec = 14
|
| 432 |
+
self.type = 3
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class TestIDCTIIIFloat(_TestIDCTBase):
|
| 436 |
+
def setup_method(self):
|
| 437 |
+
self.rdt = np.float32
|
| 438 |
+
self.dec = 5
|
| 439 |
+
self.type = 3
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class TestIDCTIIIInt(_TestIDCTBase):
|
| 443 |
+
def setup_method(self):
|
| 444 |
+
self.rdt = int
|
| 445 |
+
self.dec = 5
|
| 446 |
+
self.type = 3
|
| 447 |
+
|
| 448 |
+
class TestIDCTIVDouble(_TestIDCTBase):
|
| 449 |
+
def setup_method(self):
|
| 450 |
+
self.rdt = np.float64
|
| 451 |
+
self.dec = 12
|
| 452 |
+
self.type = 4
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class TestIDCTIVFloat(_TestIDCTBase):
|
| 456 |
+
def setup_method(self):
|
| 457 |
+
self.rdt = np.float32
|
| 458 |
+
self.dec = 5
|
| 459 |
+
self.type = 4
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class TestIDCTIVInt(_TestIDCTBase):
|
| 463 |
+
def setup_method(self):
|
| 464 |
+
self.rdt = int
|
| 465 |
+
self.dec = 5
|
| 466 |
+
self.type = 4
|
| 467 |
+
|
| 468 |
+
class _TestDSTBase:
|
| 469 |
+
def setup_method(self):
|
| 470 |
+
self.rdt = None # dtype
|
| 471 |
+
self.dec = None # number of decimals to match
|
| 472 |
+
self.type = None # dst type
|
| 473 |
+
|
| 474 |
+
@pytest.fixture
|
| 475 |
+
def dst_lock(self):
|
| 476 |
+
return threading.Lock()
|
| 477 |
+
|
| 478 |
+
def test_definition(self, dst_lock):
|
| 479 |
+
for i in FFTWDATA_SIZES:
|
| 480 |
+
with dst_lock:
|
| 481 |
+
xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
|
| 482 |
+
y = dst(xr, type=self.type)
|
| 483 |
+
assert_equal(y.dtype, dt)
|
| 484 |
+
# XXX: we divide by np.max(y) because the tests fail otherwise. We
|
| 485 |
+
# should really use something like assert_array_approx_equal. The
|
| 486 |
+
# difference is due to fftw using a better algorithm w.r.t error
|
| 487 |
+
# propagation compared to the ones from fftpack.
|
| 488 |
+
assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
|
| 489 |
+
err_msg=f"Size {i} failed")
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class _TestDSTIBase(_TestDSTBase):
|
| 493 |
+
def test_definition_ortho(self):
|
| 494 |
+
# Test orthornomal mode.
|
| 495 |
+
dt = np.result_type(np.float32, self.rdt)
|
| 496 |
+
for xr in X:
|
| 497 |
+
x = np.array(xr, dtype=self.rdt)
|
| 498 |
+
y = dst(x, norm='ortho', type=1)
|
| 499 |
+
y2 = naive_dst1(x, norm='ortho')
|
| 500 |
+
assert_equal(y.dtype, dt)
|
| 501 |
+
assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
|
| 502 |
+
|
| 503 |
+
class _TestDSTIVBase(_TestDSTBase):
|
| 504 |
+
def test_definition_ortho(self):
|
| 505 |
+
# Test orthornomal mode.
|
| 506 |
+
dt = np.result_type(np.float32, self.rdt)
|
| 507 |
+
for xr in X:
|
| 508 |
+
x = np.array(xr, dtype=self.rdt)
|
| 509 |
+
y = dst(x, norm='ortho', type=4)
|
| 510 |
+
y2 = naive_dst4(x, norm='ortho')
|
| 511 |
+
assert_equal(y.dtype, dt)
|
| 512 |
+
assert_array_almost_equal(y, y2, decimal=self.dec)
|
| 513 |
+
|
| 514 |
+
class TestDSTIDouble(_TestDSTIBase):
|
| 515 |
+
def setup_method(self):
|
| 516 |
+
self.rdt = np.float64
|
| 517 |
+
self.dec = 12
|
| 518 |
+
self.type = 1
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class TestDSTIFloat(_TestDSTIBase):
|
| 522 |
+
def setup_method(self):
|
| 523 |
+
self.rdt = np.float32
|
| 524 |
+
self.dec = 4
|
| 525 |
+
self.type = 1
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class TestDSTIInt(_TestDSTIBase):
|
| 529 |
+
def setup_method(self):
|
| 530 |
+
self.rdt = int
|
| 531 |
+
self.dec = 5
|
| 532 |
+
self.type = 1
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class TestDSTIIDouble(_TestDSTBase):
|
| 536 |
+
def setup_method(self):
|
| 537 |
+
self.rdt = np.float64
|
| 538 |
+
self.dec = 14
|
| 539 |
+
self.type = 2
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class TestDSTIIFloat(_TestDSTBase):
|
| 543 |
+
def setup_method(self):
|
| 544 |
+
self.rdt = np.float32
|
| 545 |
+
self.dec = 6
|
| 546 |
+
self.type = 2
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class TestDSTIIInt(_TestDSTBase):
|
| 550 |
+
def setup_method(self):
|
| 551 |
+
self.rdt = int
|
| 552 |
+
self.dec = 6
|
| 553 |
+
self.type = 2
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class TestDSTIIIDouble(_TestDSTBase):
|
| 557 |
+
def setup_method(self):
|
| 558 |
+
self.rdt = np.float64
|
| 559 |
+
self.dec = 14
|
| 560 |
+
self.type = 3
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class TestDSTIIIFloat(_TestDSTBase):
|
| 564 |
+
def setup_method(self):
|
| 565 |
+
self.rdt = np.float32
|
| 566 |
+
self.dec = 7
|
| 567 |
+
self.type = 3
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
class TestDSTIIIInt(_TestDSTBase):
|
| 571 |
+
def setup_method(self):
|
| 572 |
+
self.rdt = int
|
| 573 |
+
self.dec = 7
|
| 574 |
+
self.type = 3
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class TestDSTIVDouble(_TestDSTIVBase):
|
| 578 |
+
def setup_method(self):
|
| 579 |
+
self.rdt = np.float64
|
| 580 |
+
self.dec = 12
|
| 581 |
+
self.type = 4
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class TestDSTIVFloat(_TestDSTIVBase):
|
| 585 |
+
def setup_method(self):
|
| 586 |
+
self.rdt = np.float32
|
| 587 |
+
self.dec = 4
|
| 588 |
+
self.type = 4
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class TestDSTIVInt(_TestDSTIVBase):
|
| 592 |
+
def setup_method(self):
|
| 593 |
+
self.rdt = int
|
| 594 |
+
self.dec = 5
|
| 595 |
+
self.type = 4
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class _TestIDSTBase:
|
| 599 |
+
def setup_method(self):
|
| 600 |
+
self.rdt = None
|
| 601 |
+
self.dec = None
|
| 602 |
+
self.type = None
|
| 603 |
+
|
| 604 |
+
@pytest.fixture
|
| 605 |
+
def idst_lock(self):
|
| 606 |
+
return threading.Lock()
|
| 607 |
+
|
| 608 |
+
def test_definition(self, idst_lock):
|
| 609 |
+
for i in FFTWDATA_SIZES:
|
| 610 |
+
with idst_lock:
|
| 611 |
+
xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
|
| 612 |
+
x = idst(yr, type=self.type)
|
| 613 |
+
if self.type == 1:
|
| 614 |
+
x /= 2 * (i+1)
|
| 615 |
+
else:
|
| 616 |
+
x /= 2 * i
|
| 617 |
+
assert_equal(x.dtype, dt)
|
| 618 |
+
# XXX: we divide by np.max(x) because the tests fail otherwise. We
|
| 619 |
+
# should really use something like assert_array_approx_equal. The
|
| 620 |
+
# difference is due to fftw using a better algorithm w.r.t error
|
| 621 |
+
# propagation compared to the ones from fftpack.
|
| 622 |
+
assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
|
| 623 |
+
err_msg=f"Size {i} failed")
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
class TestIDSTIDouble(_TestIDSTBase):
|
| 627 |
+
def setup_method(self):
|
| 628 |
+
self.rdt = np.float64
|
| 629 |
+
self.dec = 12
|
| 630 |
+
self.type = 1
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
class TestIDSTIFloat(_TestIDSTBase):
|
| 634 |
+
def setup_method(self):
|
| 635 |
+
self.rdt = np.float32
|
| 636 |
+
self.dec = 4
|
| 637 |
+
self.type = 1
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
class TestIDSTIInt(_TestIDSTBase):
|
| 641 |
+
def setup_method(self):
|
| 642 |
+
self.rdt = int
|
| 643 |
+
self.dec = 4
|
| 644 |
+
self.type = 1
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class TestIDSTIIDouble(_TestIDSTBase):
|
| 648 |
+
def setup_method(self):
|
| 649 |
+
self.rdt = np.float64
|
| 650 |
+
self.dec = 14
|
| 651 |
+
self.type = 2
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
class TestIDSTIIFloat(_TestIDSTBase):
|
| 655 |
+
def setup_method(self):
|
| 656 |
+
self.rdt = np.float32
|
| 657 |
+
self.dec = 6
|
| 658 |
+
self.type = 2
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
class TestIDSTIIInt(_TestIDSTBase):
|
| 662 |
+
def setup_method(self):
|
| 663 |
+
self.rdt = int
|
| 664 |
+
self.dec = 6
|
| 665 |
+
self.type = 2
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
class TestIDSTIIIDouble(_TestIDSTBase):
|
| 669 |
+
def setup_method(self):
|
| 670 |
+
self.rdt = np.float64
|
| 671 |
+
self.dec = 14
|
| 672 |
+
self.type = 3
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class TestIDSTIIIFloat(_TestIDSTBase):
|
| 676 |
+
def setup_method(self):
|
| 677 |
+
self.rdt = np.float32
|
| 678 |
+
self.dec = 6
|
| 679 |
+
self.type = 3
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class TestIDSTIIIInt(_TestIDSTBase):
|
| 683 |
+
def setup_method(self):
|
| 684 |
+
self.rdt = int
|
| 685 |
+
self.dec = 6
|
| 686 |
+
self.type = 3
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
class TestIDSTIVDouble(_TestIDSTBase):
|
| 690 |
+
def setup_method(self):
|
| 691 |
+
self.rdt = np.float64
|
| 692 |
+
self.dec = 12
|
| 693 |
+
self.type = 4
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class TestIDSTIVFloat(_TestIDSTBase):
|
| 697 |
+
def setup_method(self):
|
| 698 |
+
self.rdt = np.float32
|
| 699 |
+
self.dec = 6
|
| 700 |
+
self.type = 4
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class TestIDSTIVnt(_TestIDSTBase):
|
| 704 |
+
def setup_method(self):
|
| 705 |
+
self.rdt = int
|
| 706 |
+
self.dec = 6
|
| 707 |
+
self.type = 4
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
class TestOverwrite:
|
| 711 |
+
"""Check input overwrite behavior."""
|
| 712 |
+
|
| 713 |
+
real_dtypes = [np.float32, np.float64]
|
| 714 |
+
|
| 715 |
+
def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
|
| 716 |
+
x2 = x.copy()
|
| 717 |
+
routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
|
| 718 |
+
|
| 719 |
+
sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
|
| 720 |
+
f"axis={axis!r}, overwrite_x={overwrite_x!r})")
|
| 721 |
+
if not overwrite_x:
|
| 722 |
+
assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
|
| 723 |
+
|
| 724 |
+
def _check_1d(self, routine, dtype, shape, axis):
|
| 725 |
+
rng = np.random.RandomState(1234)
|
| 726 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 727 |
+
data = rng.randn(*shape) + 1j*rng.randn(*shape)
|
| 728 |
+
else:
|
| 729 |
+
data = rng.randn(*shape)
|
| 730 |
+
data = data.astype(dtype)
|
| 731 |
+
|
| 732 |
+
for type in [1, 2, 3, 4]:
|
| 733 |
+
for overwrite_x in [True, False]:
|
| 734 |
+
for norm in [None, 'ortho']:
|
| 735 |
+
self._check(data, routine, type, None, axis, norm,
|
| 736 |
+
overwrite_x)
|
| 737 |
+
|
| 738 |
+
def test_dct(self):
|
| 739 |
+
for dtype in self.real_dtypes:
|
| 740 |
+
self._check_1d(dct, dtype, (16,), -1)
|
| 741 |
+
self._check_1d(dct, dtype, (16, 2), 0)
|
| 742 |
+
self._check_1d(dct, dtype, (2, 16), 1)
|
| 743 |
+
|
| 744 |
+
def test_idct(self):
|
| 745 |
+
for dtype in self.real_dtypes:
|
| 746 |
+
self._check_1d(idct, dtype, (16,), -1)
|
| 747 |
+
self._check_1d(idct, dtype, (16, 2), 0)
|
| 748 |
+
self._check_1d(idct, dtype, (2, 16), 1)
|
| 749 |
+
|
| 750 |
+
def test_dst(self):
|
| 751 |
+
for dtype in self.real_dtypes:
|
| 752 |
+
self._check_1d(dst, dtype, (16,), -1)
|
| 753 |
+
self._check_1d(dst, dtype, (16, 2), 0)
|
| 754 |
+
self._check_1d(dst, dtype, (2, 16), 1)
|
| 755 |
+
|
| 756 |
+
def test_idst(self):
|
| 757 |
+
for dtype in self.real_dtypes:
|
| 758 |
+
self._check_1d(idst, dtype, (16,), -1)
|
| 759 |
+
self._check_1d(idst, dtype, (16, 2), 0)
|
| 760 |
+
self._check_1d(idst, dtype, (2, 16), 1)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
class Test_DCTN_IDCTN:
|
| 764 |
+
dec = 14
|
| 765 |
+
dct_type = [1, 2, 3, 4]
|
| 766 |
+
norms = [None, 'ortho']
|
| 767 |
+
rstate = np.random.RandomState(1234)
|
| 768 |
+
shape = (32, 16)
|
| 769 |
+
data = rstate.randn(*shape)
|
| 770 |
+
|
| 771 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
| 772 |
+
(dstn, idstn)])
|
| 773 |
+
@pytest.mark.parametrize('axes', [None,
|
| 774 |
+
1, (1,), [1],
|
| 775 |
+
0, (0,), [0],
|
| 776 |
+
(0, 1), [0, 1],
|
| 777 |
+
(-2, -1), [-2, -1]])
|
| 778 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
| 779 |
+
@pytest.mark.parametrize('norm', ['ortho'])
|
| 780 |
+
def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
|
| 781 |
+
tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
|
| 782 |
+
tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
|
| 783 |
+
assert_array_almost_equal(self.data, tmp, decimal=12)
|
| 784 |
+
|
| 785 |
+
@pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
|
| 786 |
+
(dstn, dst_2d_ref)])
|
| 787 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
| 788 |
+
@pytest.mark.parametrize('norm', norms)
|
| 789 |
+
def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
|
| 790 |
+
dct_type, norm):
|
| 791 |
+
y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
|
| 792 |
+
y2 = fforward_ref(self.data, type=dct_type, norm=norm)
|
| 793 |
+
assert_array_almost_equal(y1, y2, decimal=11)
|
| 794 |
+
|
| 795 |
+
@pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
|
| 796 |
+
(idstn, idst_2d_ref)])
|
| 797 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
| 798 |
+
@pytest.mark.parametrize('norm', [None, 'ortho'])
|
| 799 |
+
def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
|
| 800 |
+
dct_type, norm):
|
| 801 |
+
fdata = dctn(self.data, type=dct_type, norm=norm)
|
| 802 |
+
y1 = finverse(fdata, type=dct_type, norm=norm)
|
| 803 |
+
y2 = finverse_ref(fdata, type=dct_type, norm=norm)
|
| 804 |
+
assert_array_almost_equal(y1, y2, decimal=11)
|
| 805 |
+
|
| 806 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
| 807 |
+
(dstn, idstn)])
|
| 808 |
+
def test_axes_and_shape(self, fforward, finverse):
|
| 809 |
+
with assert_raises(ValueError,
|
| 810 |
+
match="when given, axes and shape arguments"
|
| 811 |
+
" have to be of the same length"):
|
| 812 |
+
fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
|
| 813 |
+
|
| 814 |
+
with assert_raises(ValueError,
|
| 815 |
+
match="when given, axes and shape arguments"
|
| 816 |
+
" have to be of the same length"):
|
| 817 |
+
fforward(self.data, shape=self.data.shape[0], axes=None)
|
| 818 |
+
|
| 819 |
+
with assert_raises(ValueError,
|
| 820 |
+
match="when given, axes and shape arguments"
|
| 821 |
+
" have to be of the same length"):
|
| 822 |
+
fforward(self.data, shape=self.data.shape, axes=0)
|
| 823 |
+
|
| 824 |
+
@pytest.mark.parametrize('fforward', [dctn, dstn])
|
| 825 |
+
def test_shape(self, fforward):
|
| 826 |
+
tmp = fforward(self.data, shape=(128, 128), axes=None)
|
| 827 |
+
assert_equal(tmp.shape, (128, 128))
|
| 828 |
+
|
| 829 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
| 830 |
+
(dstn, idstn)])
|
| 831 |
+
@pytest.mark.parametrize('axes', [1, (1,), [1],
|
| 832 |
+
0, (0,), [0]])
|
| 833 |
+
def test_shape_is_none_with_axes(self, fforward, finverse, axes):
|
| 834 |
+
tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
|
| 835 |
+
tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
|
| 836 |
+
assert_array_almost_equal(self.data, tmp, decimal=self.dec)
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._LICENSE_DOP
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__bvp.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__cubature.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__dop.cpython-312-darwin.so
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__ivp
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__lebedev.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__ode.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__odepack.cpython-312-darwin.so
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__odepack_py.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quad_vec.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadpack.cpython-312-darwin.so
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadpack_py.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__quadrature.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__rules
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__tanhsinh.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__test_multivariate.cpython-312-darwin.so
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/.__vode.cpython-312-darwin.so
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._dop.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._lsoda.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._odepack.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._quadpack.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._tests
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/._vode.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/LICENSE_DOP
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (C) 2025 SciPy developers
|
| 2 |
+
|
| 3 |
+
Redistribution and use in source and binary forms, with or without
|
| 4 |
+
modification, are permitted provided that the following conditions are met:
|
| 5 |
+
|
| 6 |
+
a. Redistributions of source code must retain the above copyright notice,
|
| 7 |
+
this list of conditions and the following disclaimer.
|
| 8 |
+
b. Redistributions in binary form must reproduce the above copyright
|
| 9 |
+
notice, this list of conditions and the following disclaimer in the
|
| 10 |
+
documentation and/or other materials provided with the distribution.
|
| 11 |
+
c. Names of the SciPy Developers may not be used to endorse or promote
|
| 12 |
+
products derived from this software without specific prior written
|
| 13 |
+
permission.
|
| 14 |
+
|
| 15 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 16 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 17 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
| 18 |
+
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
|
| 19 |
+
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
|
| 20 |
+
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
| 21 |
+
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
| 22 |
+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
| 23 |
+
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
| 24 |
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
|
| 25 |
+
THE POSSIBILITY OF SUCH DAMAGE.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
DOP library consisting Dormand-Prince (4)5 and 8(5,3) integrators, is a
|
| 29 |
+
C translation of the Fortran code written by Ernst Hairer, and Gerhard
|
| 30 |
+
Wanner with the original descriptions below.
|
| 31 |
+
|
| 32 |
+
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
| 33 |
+
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
| 34 |
+
NUMERICAL SOLUTION OF A SYSTEM OF FIRST 0RDER
|
| 35 |
+
ORDINARY DIFFERENTIAL EQUATIONS Y'=F(X,Y).
|
| 36 |
+
THIS IS AN EXPLICIT RUNGE-KUTTA METHOD OF ORDER 8(5,3)
|
| 37 |
+
DUE TO DORMAND & PRINCE (WITH STEPSIZE CONTROL AND
|
| 38 |
+
DENSE OUTPUT)
|
| 39 |
+
|
| 40 |
+
AUTHORS: E. HAIRER AND G. WANNER
|
| 41 |
+
UNIVERSITE DE GENEVE, DEPT. DE MATHEMATIQUES
|
| 42 |
+
CH-1211 GENEVE 24, SWITZERLAND
|
| 43 |
+
E-MAIL: Ernst.Hairer@math.unige.ch
|
| 44 |
+
Gerhard.Wanner@math.unige.ch
|
| 45 |
+
|
| 46 |
+
THIS CODE IS DESCRIBED IN:
|
| 47 |
+
E. HAIRER, S.P. NORSETT AND G. WANNER, SOLVING ORDINARY
|
| 48 |
+
DIFFERENTIAL EQUATIONS I. NONSTIFF PROBLEMS. 2ND EDITION.
|
| 49 |
+
SPRINGER SERIES IN COMPUTATIONAL MATHEMATICS,
|
| 50 |
+
SPRINGER-VERLAG (1993)
|
| 51 |
+
|
| 52 |
+
VERSION OF APRIL 25, 1996
|
| 53 |
+
(latest correction of a small bug: August 8, 2005)
|
| 54 |
+
|
| 55 |
+
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
| 56 |
+
NUMERICAL SOLUTION OF A SYSTEM OF FIRST 0RDER
|
| 57 |
+
ORDINARY DIFFERENTIAL EQUATIONS Y'=F(X,Y).
|
| 58 |
+
THIS IS AN EXPLICIT RUNGE-KUTTA METHOD OF ORDER (4)5
|
| 59 |
+
DUE TO DORMAND & PRINCE (WITH STEPSIZE CONTROL AND
|
| 60 |
+
DENSE OUTPUT).
|
| 61 |
+
|
| 62 |
+
AUTHORS: E. HAIRER AND G. WANNER
|
| 63 |
+
UNIVERSITE DE GENEVE, DEPT. DE MATHEMATIQUES
|
| 64 |
+
CH-1211 GENEVE 24, SWITZERLAND
|
| 65 |
+
E-MAIL: Ernst.Hairer@math.unige.ch
|
| 66 |
+
Gerhard.Wanner@math.unige.ch
|
| 67 |
+
|
| 68 |
+
THIS CODE IS DESCRIBED IN:
|
| 69 |
+
E. HAIRER, S.P. NORSETT AND G. WANNER, SOLVING ORDINARY
|
| 70 |
+
DIFFERENTIAL EQUATIONS I. NONSTIFF PROBLEMS. 2ND EDITION.
|
| 71 |
+
SPRINGER SERIES IN COMPUTATIONAL MATHEMATICS,
|
| 72 |
+
SPRINGER-VERLAG (1993)
|
| 73 |
+
|
| 74 |
+
VERSION OF APRIL 25, 1996
|
| 75 |
+
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
| 76 |
+
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
.venv_haddock/lib/python3.12/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
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_bvp.py
ADDED
|
@@ -0,0 +1,1162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from scipy._lib._array_api import xp_capabilities
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
EPS = np.finfo(float).eps
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def estimate_fun_jac(fun, x, y, p, f0=None):
|
| 17 |
+
"""Estimate derivatives of an ODE system rhs with forward differences.
|
| 18 |
+
|
| 19 |
+
Returns
|
| 20 |
+
-------
|
| 21 |
+
df_dy : ndarray, shape (n, n, m)
|
| 22 |
+
Derivatives with respect to y. An element (i, j, q) corresponds to
|
| 23 |
+
d f_i(x_q, y_q) / d (y_q)_j.
|
| 24 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 25 |
+
Derivatives with respect to p. An element (i, j, q) corresponds to
|
| 26 |
+
d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
|
| 27 |
+
"""
|
| 28 |
+
n, m = y.shape
|
| 29 |
+
if f0 is None:
|
| 30 |
+
f0 = fun(x, y, p)
|
| 31 |
+
|
| 32 |
+
dtype = y.dtype
|
| 33 |
+
|
| 34 |
+
df_dy = np.empty((n, n, m), dtype=dtype)
|
| 35 |
+
h = EPS**0.5 * (1 + np.abs(y))
|
| 36 |
+
for i in range(n):
|
| 37 |
+
y_new = y.copy()
|
| 38 |
+
y_new[i] += h[i]
|
| 39 |
+
hi = y_new[i] - y[i]
|
| 40 |
+
f_new = fun(x, y_new, p)
|
| 41 |
+
df_dy[:, i, :] = (f_new - f0) / hi
|
| 42 |
+
|
| 43 |
+
k = p.shape[0]
|
| 44 |
+
if k == 0:
|
| 45 |
+
df_dp = None
|
| 46 |
+
else:
|
| 47 |
+
df_dp = np.empty((n, k, m), dtype=dtype)
|
| 48 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 49 |
+
for i in range(k):
|
| 50 |
+
p_new = p.copy()
|
| 51 |
+
p_new[i] += h[i]
|
| 52 |
+
hi = p_new[i] - p[i]
|
| 53 |
+
f_new = fun(x, y, p_new)
|
| 54 |
+
df_dp[:, i, :] = (f_new - f0) / hi
|
| 55 |
+
|
| 56 |
+
return df_dy, df_dp
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def estimate_bc_jac(bc, ya, yb, p, bc0=None):
|
| 60 |
+
"""Estimate derivatives of boundary conditions with forward differences.
|
| 61 |
+
|
| 62 |
+
Returns
|
| 63 |
+
-------
|
| 64 |
+
dbc_dya : ndarray, shape (n + k, n)
|
| 65 |
+
Derivatives with respect to ya. An element (i, j) corresponds to
|
| 66 |
+
d bc_i / d ya_j.
|
| 67 |
+
dbc_dyb : ndarray, shape (n + k, n)
|
| 68 |
+
Derivatives with respect to yb. An element (i, j) corresponds to
|
| 69 |
+
d bc_i / d ya_j.
|
| 70 |
+
dbc_dp : ndarray with shape (n + k, k) or None
|
| 71 |
+
Derivatives with respect to p. An element (i, j) corresponds to
|
| 72 |
+
d bc_i / d p_j. If `p` is empty, None is returned.
|
| 73 |
+
"""
|
| 74 |
+
n = ya.shape[0]
|
| 75 |
+
k = p.shape[0]
|
| 76 |
+
|
| 77 |
+
if bc0 is None:
|
| 78 |
+
bc0 = bc(ya, yb, p)
|
| 79 |
+
|
| 80 |
+
dtype = ya.dtype
|
| 81 |
+
|
| 82 |
+
dbc_dya = np.empty((n, n + k), dtype=dtype)
|
| 83 |
+
h = EPS**0.5 * (1 + np.abs(ya))
|
| 84 |
+
for i in range(n):
|
| 85 |
+
ya_new = ya.copy()
|
| 86 |
+
ya_new[i] += h[i]
|
| 87 |
+
hi = ya_new[i] - ya[i]
|
| 88 |
+
bc_new = bc(ya_new, yb, p)
|
| 89 |
+
dbc_dya[i] = (bc_new - bc0) / hi
|
| 90 |
+
dbc_dya = dbc_dya.T
|
| 91 |
+
|
| 92 |
+
h = EPS**0.5 * (1 + np.abs(yb))
|
| 93 |
+
dbc_dyb = np.empty((n, n + k), dtype=dtype)
|
| 94 |
+
for i in range(n):
|
| 95 |
+
yb_new = yb.copy()
|
| 96 |
+
yb_new[i] += h[i]
|
| 97 |
+
hi = yb_new[i] - yb[i]
|
| 98 |
+
bc_new = bc(ya, yb_new, p)
|
| 99 |
+
dbc_dyb[i] = (bc_new - bc0) / hi
|
| 100 |
+
dbc_dyb = dbc_dyb.T
|
| 101 |
+
|
| 102 |
+
if k == 0:
|
| 103 |
+
dbc_dp = None
|
| 104 |
+
else:
|
| 105 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 106 |
+
dbc_dp = np.empty((k, n + k), dtype=dtype)
|
| 107 |
+
for i in range(k):
|
| 108 |
+
p_new = p.copy()
|
| 109 |
+
p_new[i] += h[i]
|
| 110 |
+
hi = p_new[i] - p[i]
|
| 111 |
+
bc_new = bc(ya, yb, p_new)
|
| 112 |
+
dbc_dp[i] = (bc_new - bc0) / hi
|
| 113 |
+
dbc_dp = dbc_dp.T
|
| 114 |
+
|
| 115 |
+
return dbc_dya, dbc_dyb, dbc_dp
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def compute_jac_indices(n, m, k):
|
| 119 |
+
"""Compute indices for the collocation system Jacobian construction.
|
| 120 |
+
|
| 121 |
+
See `construct_global_jac` for the explanation.
|
| 122 |
+
"""
|
| 123 |
+
i_col = np.repeat(np.arange((m - 1) * n), n)
|
| 124 |
+
j_col = (np.tile(np.arange(n), n * (m - 1)) +
|
| 125 |
+
np.repeat(np.arange(m - 1) * n, n**2))
|
| 126 |
+
|
| 127 |
+
i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
|
| 128 |
+
j_bc = np.tile(np.arange(n), n + k)
|
| 129 |
+
|
| 130 |
+
i_p_col = np.repeat(np.arange((m - 1) * n), k)
|
| 131 |
+
j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
|
| 132 |
+
|
| 133 |
+
i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
|
| 134 |
+
j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
|
| 135 |
+
|
| 136 |
+
i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
|
| 137 |
+
j = np.hstack((j_col, j_col + n,
|
| 138 |
+
j_bc, j_bc + (m - 1) * n,
|
| 139 |
+
j_p_col, j_p_bc))
|
| 140 |
+
|
| 141 |
+
return i, j
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def stacked_matmul(a, b):
|
| 145 |
+
"""Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
|
| 146 |
+
|
| 147 |
+
Empirical optimization. Use outer Python loop and BLAS for large
|
| 148 |
+
matrices, otherwise use a single einsum call.
|
| 149 |
+
"""
|
| 150 |
+
if a.shape[1] > 50:
|
| 151 |
+
out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
|
| 152 |
+
for i in range(a.shape[0]):
|
| 153 |
+
out[i] = np.dot(a[i], b[i])
|
| 154 |
+
return out
|
| 155 |
+
else:
|
| 156 |
+
return np.einsum('...ij,...jk->...ik', a, b)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
|
| 160 |
+
df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
|
| 161 |
+
"""Construct the Jacobian of the collocation system.
|
| 162 |
+
|
| 163 |
+
There are n * m + k functions: m - 1 collocations residuals, each
|
| 164 |
+
containing n components, followed by n + k boundary condition residuals.
|
| 165 |
+
|
| 166 |
+
There are n * m + k variables: m vectors of y, each containing n
|
| 167 |
+
components, followed by k values of vector p.
|
| 168 |
+
|
| 169 |
+
For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
|
| 170 |
+
the following sparsity structure:
|
| 171 |
+
|
| 172 |
+
1 1 2 2 0 0 0 0 5
|
| 173 |
+
1 1 2 2 0 0 0 0 5
|
| 174 |
+
0 0 1 1 2 2 0 0 5
|
| 175 |
+
0 0 1 1 2 2 0 0 5
|
| 176 |
+
0 0 0 0 1 1 2 2 5
|
| 177 |
+
0 0 0 0 1 1 2 2 5
|
| 178 |
+
|
| 179 |
+
3 3 0 0 0 0 4 4 6
|
| 180 |
+
3 3 0 0 0 0 4 4 6
|
| 181 |
+
3 3 0 0 0 0 4 4 6
|
| 182 |
+
|
| 183 |
+
Zeros denote identically zero values, other values denote different kinds
|
| 184 |
+
of blocks in the matrix (see below). The blank row indicates the separation
|
| 185 |
+
of collocation residuals from boundary conditions. And the blank column
|
| 186 |
+
indicates the separation of y values from p values.
|
| 187 |
+
|
| 188 |
+
Refer to [1]_ (p. 306) for the formula of n x n blocks for derivatives
|
| 189 |
+
of collocation residuals with respect to y.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
----------
|
| 193 |
+
n : int
|
| 194 |
+
Number of equations in the ODE system.
|
| 195 |
+
m : int
|
| 196 |
+
Number of nodes in the mesh.
|
| 197 |
+
k : int
|
| 198 |
+
Number of the unknown parameters.
|
| 199 |
+
i_jac, j_jac : ndarray
|
| 200 |
+
Row and column indices returned by `compute_jac_indices`. They
|
| 201 |
+
represent different blocks in the Jacobian matrix in the following
|
| 202 |
+
order (see the scheme above):
|
| 203 |
+
|
| 204 |
+
* 1: m - 1 diagonal n x n blocks for the collocation residuals.
|
| 205 |
+
* 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
|
| 206 |
+
* 3 : (n + k) x n block for the dependency of the boundary
|
| 207 |
+
conditions on ya.
|
| 208 |
+
* 4: (n + k) x n block for the dependency of the boundary
|
| 209 |
+
conditions on yb.
|
| 210 |
+
* 5: (m - 1) * n x k block for the dependency of the collocation
|
| 211 |
+
residuals on p.
|
| 212 |
+
* 6: (n + k) x k block for the dependency of the boundary
|
| 213 |
+
conditions on p.
|
| 214 |
+
|
| 215 |
+
df_dy : ndarray, shape (n, n, m)
|
| 216 |
+
Jacobian of f with respect to y computed at the mesh nodes.
|
| 217 |
+
df_dy_middle : ndarray, shape (n, n, m - 1)
|
| 218 |
+
Jacobian of f with respect to y computed at the middle between the
|
| 219 |
+
mesh nodes.
|
| 220 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 221 |
+
Jacobian of f with respect to p computed at the mesh nodes.
|
| 222 |
+
df_dp_middle : ndarray with shape (n, k, m - 1) or None
|
| 223 |
+
Jacobian of f with respect to p computed at the middle between the
|
| 224 |
+
mesh nodes.
|
| 225 |
+
dbc_dya, dbc_dyb : ndarray, shape (n, n)
|
| 226 |
+
Jacobian of bc with respect to ya and yb.
|
| 227 |
+
dbc_dp : ndarray with shape (n, k) or None
|
| 228 |
+
Jacobian of bc with respect to p.
|
| 229 |
+
|
| 230 |
+
Returns
|
| 231 |
+
-------
|
| 232 |
+
J : csc_matrix, shape (n * m + k, n * m + k)
|
| 233 |
+
Jacobian of the collocation system in a sparse form.
|
| 234 |
+
|
| 235 |
+
References
|
| 236 |
+
----------
|
| 237 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 238 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 239 |
+
Number 3, pp. 299-316, 2001.
|
| 240 |
+
"""
|
| 241 |
+
df_dy = np.transpose(df_dy, (2, 0, 1))
|
| 242 |
+
df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
|
| 243 |
+
|
| 244 |
+
h = h[:, np.newaxis, np.newaxis]
|
| 245 |
+
|
| 246 |
+
dtype = df_dy.dtype
|
| 247 |
+
|
| 248 |
+
# Computing diagonal n x n blocks.
|
| 249 |
+
dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
|
| 250 |
+
dPhi_dy_0[:] = -np.identity(n)
|
| 251 |
+
dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
|
| 252 |
+
T = stacked_matmul(df_dy_middle, df_dy[:-1])
|
| 253 |
+
dPhi_dy_0 -= h**2 / 12 * T
|
| 254 |
+
|
| 255 |
+
# Computing off-diagonal n x n blocks.
|
| 256 |
+
dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
|
| 257 |
+
dPhi_dy_1[:] = np.identity(n)
|
| 258 |
+
dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
|
| 259 |
+
T = stacked_matmul(df_dy_middle, df_dy[1:])
|
| 260 |
+
dPhi_dy_1 += h**2 / 12 * T
|
| 261 |
+
|
| 262 |
+
values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
|
| 263 |
+
dbc_dyb.ravel()))
|
| 264 |
+
|
| 265 |
+
if k > 0:
|
| 266 |
+
df_dp = np.transpose(df_dp, (2, 0, 1))
|
| 267 |
+
df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
|
| 268 |
+
T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
|
| 269 |
+
df_dp_middle += 0.125 * h * T
|
| 270 |
+
dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
|
| 271 |
+
values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
|
| 272 |
+
|
| 273 |
+
J = coo_matrix((values, (i_jac, j_jac)))
|
| 274 |
+
return csc_matrix(J)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def collocation_fun(fun, y, p, x, h):
|
| 278 |
+
"""Evaluate collocation residuals.
|
| 279 |
+
|
| 280 |
+
This function lies in the core of the method. The solution is sought
|
| 281 |
+
as a cubic C1 continuous spline with derivatives matching the ODE rhs
|
| 282 |
+
at given nodes `x`. Collocation conditions are formed from the equality
|
| 283 |
+
of the spline derivatives and rhs of the ODE system in the middle points
|
| 284 |
+
between nodes.
|
| 285 |
+
|
| 286 |
+
Such method is classified to Lobbato IIIA family in ODE literature.
|
| 287 |
+
Refer to [1]_ for the formula and some discussion.
|
| 288 |
+
|
| 289 |
+
Returns
|
| 290 |
+
-------
|
| 291 |
+
col_res : ndarray, shape (n, m - 1)
|
| 292 |
+
Collocation residuals at the middle points of the mesh intervals.
|
| 293 |
+
y_middle : ndarray, shape (n, m - 1)
|
| 294 |
+
Values of the cubic spline evaluated at the middle points of the mesh
|
| 295 |
+
intervals.
|
| 296 |
+
f : ndarray, shape (n, m)
|
| 297 |
+
RHS of the ODE system evaluated at the mesh nodes.
|
| 298 |
+
f_middle : ndarray, shape (n, m - 1)
|
| 299 |
+
RHS of the ODE system evaluated at the middle points of the mesh
|
| 300 |
+
intervals (and using `y_middle`).
|
| 301 |
+
|
| 302 |
+
References
|
| 303 |
+
----------
|
| 304 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 305 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 306 |
+
Number 3, pp. 299-316, 2001.
|
| 307 |
+
"""
|
| 308 |
+
f = fun(x, y, p)
|
| 309 |
+
y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
|
| 310 |
+
0.125 * h * (f[:, 1:] - f[:, :-1]))
|
| 311 |
+
f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
|
| 312 |
+
col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
|
| 313 |
+
4 * f_middle)
|
| 314 |
+
|
| 315 |
+
return col_res, y_middle, f, f_middle
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
|
| 319 |
+
"""Create the function and the Jacobian for the collocation system."""
|
| 320 |
+
x_middle = x[:-1] + 0.5 * h
|
| 321 |
+
i_jac, j_jac = compute_jac_indices(n, m, k)
|
| 322 |
+
|
| 323 |
+
def col_fun(y, p):
|
| 324 |
+
return collocation_fun(fun, y, p, x, h)
|
| 325 |
+
|
| 326 |
+
def sys_jac(y, p, y_middle, f, f_middle, bc0):
|
| 327 |
+
if fun_jac is None:
|
| 328 |
+
df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
|
| 329 |
+
df_dy_middle, df_dp_middle = estimate_fun_jac(
|
| 330 |
+
fun, x_middle, y_middle, p, f_middle)
|
| 331 |
+
else:
|
| 332 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 333 |
+
df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
|
| 334 |
+
|
| 335 |
+
if bc_jac is None:
|
| 336 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
|
| 337 |
+
p, bc0)
|
| 338 |
+
else:
|
| 339 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
|
| 340 |
+
|
| 341 |
+
return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
|
| 342 |
+
df_dy_middle, df_dp, df_dp_middle, dbc_dya,
|
| 343 |
+
dbc_dyb, dbc_dp)
|
| 344 |
+
|
| 345 |
+
return col_fun, sys_jac
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
|
| 349 |
+
"""Solve the nonlinear collocation system by a Newton method.
|
| 350 |
+
|
| 351 |
+
This is a simple Newton method with a backtracking line search. As
|
| 352 |
+
advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
|
| 353 |
+
is used, where J is the Jacobian matrix at the current iteration and r is
|
| 354 |
+
the vector or collocation residuals (values of the system lhs).
|
| 355 |
+
|
| 356 |
+
The method alters between full Newton iterations and the fixed-Jacobian
|
| 357 |
+
iterations based
|
| 358 |
+
|
| 359 |
+
There are other tricks proposed in [1]_, but they are not used as they
|
| 360 |
+
don't seem to improve anything significantly, and even break the
|
| 361 |
+
convergence on some test problems I tried.
|
| 362 |
+
|
| 363 |
+
All important parameters of the algorithm are defined inside the function.
|
| 364 |
+
|
| 365 |
+
Parameters
|
| 366 |
+
----------
|
| 367 |
+
n : int
|
| 368 |
+
Number of equations in the ODE system.
|
| 369 |
+
m : int
|
| 370 |
+
Number of nodes in the mesh.
|
| 371 |
+
h : ndarray, shape (m-1,)
|
| 372 |
+
Mesh intervals.
|
| 373 |
+
col_fun : callable
|
| 374 |
+
Function computing collocation residuals.
|
| 375 |
+
bc : callable
|
| 376 |
+
Function computing boundary condition residuals.
|
| 377 |
+
jac : callable
|
| 378 |
+
Function computing the Jacobian of the whole system (including
|
| 379 |
+
collocation and boundary condition residuals). It is supposed to
|
| 380 |
+
return csc_matrix.
|
| 381 |
+
y : ndarray, shape (n, m)
|
| 382 |
+
Initial guess for the function values at the mesh nodes.
|
| 383 |
+
p : ndarray, shape (k,)
|
| 384 |
+
Initial guess for the unknown parameters.
|
| 385 |
+
B : ndarray with shape (n, n) or None
|
| 386 |
+
Matrix to force the S y(a) = 0 condition for a problems with the
|
| 387 |
+
singular term. If None, the singular term is assumed to be absent.
|
| 388 |
+
bvp_tol : float
|
| 389 |
+
Tolerance to which we want to solve a BVP.
|
| 390 |
+
bc_tol : float
|
| 391 |
+
Tolerance to which we want to satisfy the boundary conditions.
|
| 392 |
+
|
| 393 |
+
Returns
|
| 394 |
+
-------
|
| 395 |
+
y : ndarray, shape (n, m)
|
| 396 |
+
Final iterate for the function values at the mesh nodes.
|
| 397 |
+
p : ndarray, shape (k,)
|
| 398 |
+
Final iterate for the unknown parameters.
|
| 399 |
+
singular : bool
|
| 400 |
+
True, if the LU decomposition failed because Jacobian turned out
|
| 401 |
+
to be singular.
|
| 402 |
+
|
| 403 |
+
References
|
| 404 |
+
----------
|
| 405 |
+
.. [1] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 406 |
+
Boundary Value Problems for Ordinary Differential Equations",
|
| 407 |
+
Philidelphia, PA: Society for Industrial and Applied Mathematics,
|
| 408 |
+
1995.
|
| 409 |
+
"""
|
| 410 |
+
# We know that the solution residuals at the middle points of the mesh
|
| 411 |
+
# are connected with collocation residuals r_middle = 1.5 * col_res / h.
|
| 412 |
+
# As our BVP solver tries to decrease relative residuals below a certain
|
| 413 |
+
# tolerance, it seems reasonable to terminated Newton iterations by
|
| 414 |
+
# comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
|
| 415 |
+
# which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
|
| 416 |
+
# the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
|
| 417 |
+
# should be computed as follows:
|
| 418 |
+
tol_r = 2/3 * h * 5e-2 * bvp_tol
|
| 419 |
+
|
| 420 |
+
# Maximum allowed number of Jacobian evaluation and factorization, in
|
| 421 |
+
# other words, the maximum number of full Newton iterations. A small value
|
| 422 |
+
# is recommended in the literature.
|
| 423 |
+
max_njev = 4
|
| 424 |
+
|
| 425 |
+
# Maximum number of iterations, considering that some of them can be
|
| 426 |
+
# performed with the fixed Jacobian. In theory, such iterations are cheap,
|
| 427 |
+
# but it's not that simple in Python.
|
| 428 |
+
max_iter = 8
|
| 429 |
+
|
| 430 |
+
# Minimum relative improvement of the criterion function to accept the
|
| 431 |
+
# step (Armijo constant).
|
| 432 |
+
sigma = 0.2
|
| 433 |
+
|
| 434 |
+
# Step size decrease factor for backtracking.
|
| 435 |
+
tau = 0.5
|
| 436 |
+
|
| 437 |
+
# Maximum number of backtracking steps, the minimum step is then
|
| 438 |
+
# tau ** n_trial.
|
| 439 |
+
n_trial = 4
|
| 440 |
+
|
| 441 |
+
col_res, y_middle, f, f_middle = col_fun(y, p)
|
| 442 |
+
bc_res = bc(y[:, 0], y[:, -1], p)
|
| 443 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 444 |
+
|
| 445 |
+
njev = 0
|
| 446 |
+
singular = False
|
| 447 |
+
recompute_jac = True
|
| 448 |
+
for iteration in range(max_iter):
|
| 449 |
+
if recompute_jac:
|
| 450 |
+
J = jac(y, p, y_middle, f, f_middle, bc_res)
|
| 451 |
+
njev += 1
|
| 452 |
+
try:
|
| 453 |
+
LU = splu(J)
|
| 454 |
+
except RuntimeError:
|
| 455 |
+
singular = True
|
| 456 |
+
break
|
| 457 |
+
|
| 458 |
+
step = LU.solve(res)
|
| 459 |
+
cost = np.dot(step, step)
|
| 460 |
+
|
| 461 |
+
y_step = step[:m * n].reshape((n, m), order='F')
|
| 462 |
+
p_step = step[m * n:]
|
| 463 |
+
|
| 464 |
+
alpha = 1
|
| 465 |
+
for trial in range(n_trial + 1):
|
| 466 |
+
y_new = y - alpha * y_step
|
| 467 |
+
if B is not None:
|
| 468 |
+
y_new[:, 0] = np.dot(B, y_new[:, 0])
|
| 469 |
+
p_new = p - alpha * p_step
|
| 470 |
+
|
| 471 |
+
col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
|
| 472 |
+
bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
|
| 473 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 474 |
+
|
| 475 |
+
step_new = LU.solve(res)
|
| 476 |
+
cost_new = np.dot(step_new, step_new)
|
| 477 |
+
if cost_new < (1 - 2 * alpha * sigma) * cost:
|
| 478 |
+
break
|
| 479 |
+
|
| 480 |
+
if trial < n_trial:
|
| 481 |
+
alpha *= tau
|
| 482 |
+
|
| 483 |
+
y = y_new
|
| 484 |
+
p = p_new
|
| 485 |
+
|
| 486 |
+
if njev == max_njev:
|
| 487 |
+
break
|
| 488 |
+
|
| 489 |
+
if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
|
| 490 |
+
np.all(np.abs(bc_res) < bc_tol)):
|
| 491 |
+
break
|
| 492 |
+
|
| 493 |
+
# If the full step was taken, then we are going to continue with
|
| 494 |
+
# the same Jacobian. This is the approach of BVP_SOLVER.
|
| 495 |
+
if alpha == 1:
|
| 496 |
+
step = step_new
|
| 497 |
+
cost = cost_new
|
| 498 |
+
recompute_jac = False
|
| 499 |
+
else:
|
| 500 |
+
recompute_jac = True
|
| 501 |
+
|
| 502 |
+
return y, p, singular
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def print_iteration_header():
|
| 506 |
+
print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
|
| 507 |
+
f"{'Total nodes':^15}{'Nodes added':^15}")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
|
| 511 |
+
nodes_added):
|
| 512 |
+
print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
|
| 513 |
+
f"{total_nodes:^15}{nodes_added:^15}")
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class BVPResult(OptimizeResult):
|
| 517 |
+
pass
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
TERMINATION_MESSAGES = {
|
| 521 |
+
0: "The algorithm converged to the desired accuracy.",
|
| 522 |
+
1: "The maximum number of mesh nodes is exceeded.",
|
| 523 |
+
2: "A singular Jacobian encountered when solving the collocation system.",
|
| 524 |
+
3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
|
| 529 |
+
"""Estimate rms values of collocation residuals using Lobatto quadrature.
|
| 530 |
+
|
| 531 |
+
The residuals are defined as the difference between the derivatives of
|
| 532 |
+
our solution and rhs of the ODE system. We use relative residuals, i.e.,
|
| 533 |
+
normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
|
| 534 |
+
normalized integrals of the squared relative residuals over each interval.
|
| 535 |
+
Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
|
| 536 |
+
fact that residuals at the mesh nodes are identically zero.
|
| 537 |
+
|
| 538 |
+
In [2] they don't normalize integrals by interval lengths, which gives
|
| 539 |
+
a higher rate of convergence of the residuals by the factor of h**0.5.
|
| 540 |
+
I chose to do such normalization for an ease of interpretation of return
|
| 541 |
+
values as RMS estimates.
|
| 542 |
+
|
| 543 |
+
Returns
|
| 544 |
+
-------
|
| 545 |
+
rms_res : ndarray, shape (m - 1,)
|
| 546 |
+
Estimated rms values of the relative residuals over each interval.
|
| 547 |
+
|
| 548 |
+
References
|
| 549 |
+
----------
|
| 550 |
+
.. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
|
| 551 |
+
.. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 552 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 553 |
+
Number 3, pp. 299-316, 2001.
|
| 554 |
+
"""
|
| 555 |
+
x_middle = x[:-1] + 0.5 * h
|
| 556 |
+
s = 0.5 * h * (3/7)**0.5
|
| 557 |
+
x1 = x_middle + s
|
| 558 |
+
x2 = x_middle - s
|
| 559 |
+
y1 = sol(x1)
|
| 560 |
+
y2 = sol(x2)
|
| 561 |
+
y1_prime = sol(x1, 1)
|
| 562 |
+
y2_prime = sol(x2, 1)
|
| 563 |
+
f1 = fun(x1, y1, p)
|
| 564 |
+
f2 = fun(x2, y2, p)
|
| 565 |
+
r1 = y1_prime - f1
|
| 566 |
+
r2 = y2_prime - f2
|
| 567 |
+
|
| 568 |
+
r_middle /= 1 + np.abs(f_middle)
|
| 569 |
+
r1 /= 1 + np.abs(f1)
|
| 570 |
+
r2 /= 1 + np.abs(f2)
|
| 571 |
+
|
| 572 |
+
r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
|
| 573 |
+
r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
|
| 574 |
+
r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
|
| 575 |
+
|
| 576 |
+
return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def create_spline(y, yp, x, h):
|
| 580 |
+
"""Create a cubic spline given values and derivatives.
|
| 581 |
+
|
| 582 |
+
Formulas for the coefficients are taken from interpolate.CubicSpline.
|
| 583 |
+
|
| 584 |
+
Returns
|
| 585 |
+
-------
|
| 586 |
+
sol : PPoly
|
| 587 |
+
Constructed spline as a PPoly instance.
|
| 588 |
+
"""
|
| 589 |
+
from scipy.interpolate import PPoly
|
| 590 |
+
|
| 591 |
+
n, m = y.shape
|
| 592 |
+
c = np.empty((4, n, m - 1), dtype=y.dtype)
|
| 593 |
+
slope = (y[:, 1:] - y[:, :-1]) / h
|
| 594 |
+
t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
|
| 595 |
+
c[0] = t / h
|
| 596 |
+
c[1] = (slope - yp[:, :-1]) / h - t
|
| 597 |
+
c[2] = yp[:, :-1]
|
| 598 |
+
c[3] = y[:, :-1]
|
| 599 |
+
c = np.moveaxis(c, 1, 0)
|
| 600 |
+
|
| 601 |
+
return PPoly(c, x, extrapolate=True, axis=1)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def modify_mesh(x, insert_1, insert_2):
|
| 605 |
+
"""Insert nodes into a mesh.
|
| 606 |
+
|
| 607 |
+
Nodes removal logic is not established, its impact on the solver is
|
| 608 |
+
presumably negligible. So, only insertion is done in this function.
|
| 609 |
+
|
| 610 |
+
Parameters
|
| 611 |
+
----------
|
| 612 |
+
x : ndarray, shape (m,)
|
| 613 |
+
Mesh nodes.
|
| 614 |
+
insert_1 : ndarray
|
| 615 |
+
Intervals to each insert 1 new node in the middle.
|
| 616 |
+
insert_2 : ndarray
|
| 617 |
+
Intervals to each insert 2 new nodes, such that divide an interval
|
| 618 |
+
into 3 equal parts.
|
| 619 |
+
|
| 620 |
+
Returns
|
| 621 |
+
-------
|
| 622 |
+
x_new : ndarray
|
| 623 |
+
New mesh nodes.
|
| 624 |
+
|
| 625 |
+
Notes
|
| 626 |
+
-----
|
| 627 |
+
`insert_1` and `insert_2` should not have common values.
|
| 628 |
+
"""
|
| 629 |
+
# Because np.insert implementation apparently varies with a version of
|
| 630 |
+
# NumPy, we use a simple and reliable approach with sorting.
|
| 631 |
+
return np.sort(np.hstack((
|
| 632 |
+
x,
|
| 633 |
+
0.5 * (x[insert_1] + x[insert_1 + 1]),
|
| 634 |
+
(2 * x[insert_2] + x[insert_2 + 1]) / 3,
|
| 635 |
+
(x[insert_2] + 2 * x[insert_2 + 1]) / 3
|
| 636 |
+
)))
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
|
| 640 |
+
"""Wrap functions for unified usage in the solver."""
|
| 641 |
+
if fun_jac is None:
|
| 642 |
+
fun_jac_wrapped = None
|
| 643 |
+
|
| 644 |
+
if bc_jac is None:
|
| 645 |
+
bc_jac_wrapped = None
|
| 646 |
+
|
| 647 |
+
if k == 0:
|
| 648 |
+
def fun_p(x, y, _):
|
| 649 |
+
return np.asarray(fun(x, y), dtype)
|
| 650 |
+
|
| 651 |
+
def bc_wrapped(ya, yb, _):
|
| 652 |
+
return np.asarray(bc(ya, yb), dtype)
|
| 653 |
+
|
| 654 |
+
if fun_jac is not None:
|
| 655 |
+
def fun_jac_p(x, y, _):
|
| 656 |
+
return np.asarray(fun_jac(x, y), dtype), None
|
| 657 |
+
|
| 658 |
+
if bc_jac is not None:
|
| 659 |
+
def bc_jac_wrapped(ya, yb, _):
|
| 660 |
+
dbc_dya, dbc_dyb = bc_jac(ya, yb)
|
| 661 |
+
return (np.asarray(dbc_dya, dtype),
|
| 662 |
+
np.asarray(dbc_dyb, dtype), None)
|
| 663 |
+
else:
|
| 664 |
+
def fun_p(x, y, p):
|
| 665 |
+
return np.asarray(fun(x, y, p), dtype)
|
| 666 |
+
|
| 667 |
+
def bc_wrapped(x, y, p):
|
| 668 |
+
return np.asarray(bc(x, y, p), dtype)
|
| 669 |
+
|
| 670 |
+
if fun_jac is not None:
|
| 671 |
+
def fun_jac_p(x, y, p):
|
| 672 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 673 |
+
return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
|
| 674 |
+
|
| 675 |
+
if bc_jac is not None:
|
| 676 |
+
def bc_jac_wrapped(ya, yb, p):
|
| 677 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
|
| 678 |
+
return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
|
| 679 |
+
np.asarray(dbc_dp, dtype))
|
| 680 |
+
|
| 681 |
+
if S is None:
|
| 682 |
+
fun_wrapped = fun_p
|
| 683 |
+
else:
|
| 684 |
+
def fun_wrapped(x, y, p):
|
| 685 |
+
f = fun_p(x, y, p)
|
| 686 |
+
if x[0] == a:
|
| 687 |
+
f[:, 0] = np.dot(D, f[:, 0])
|
| 688 |
+
f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
|
| 689 |
+
else:
|
| 690 |
+
f += np.dot(S, y) / (x - a)
|
| 691 |
+
return f
|
| 692 |
+
|
| 693 |
+
if fun_jac is not None:
|
| 694 |
+
if S is None:
|
| 695 |
+
fun_jac_wrapped = fun_jac_p
|
| 696 |
+
else:
|
| 697 |
+
Sr = S[:, :, np.newaxis]
|
| 698 |
+
|
| 699 |
+
def fun_jac_wrapped(x, y, p):
|
| 700 |
+
df_dy, df_dp = fun_jac_p(x, y, p)
|
| 701 |
+
if x[0] == a:
|
| 702 |
+
df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
|
| 703 |
+
df_dy[:, :, 1:] += Sr / (x[1:] - a)
|
| 704 |
+
else:
|
| 705 |
+
df_dy += Sr / (x - a)
|
| 706 |
+
|
| 707 |
+
return df_dy, df_dp
|
| 708 |
+
|
| 709 |
+
return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
@xp_capabilities(np_only=True)
|
| 713 |
+
def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
|
| 714 |
+
tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
|
| 715 |
+
"""Solve a boundary value problem for a system of ODEs.
|
| 716 |
+
|
| 717 |
+
This function numerically solves a first order system of ODEs subject to
|
| 718 |
+
two-point boundary conditions::
|
| 719 |
+
|
| 720 |
+
dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
|
| 721 |
+
bc(y(a), y(b), p) = 0
|
| 722 |
+
|
| 723 |
+
Here x is a 1-D independent variable, y(x) is an n-D
|
| 724 |
+
vector-valued function and p is a k-D vector of unknown
|
| 725 |
+
parameters which is to be found along with y(x). For the problem to be
|
| 726 |
+
determined, there must be n + k boundary conditions, i.e., bc must be an
|
| 727 |
+
(n + k)-D function.
|
| 728 |
+
|
| 729 |
+
The last singular term on the right-hand side of the system is optional.
|
| 730 |
+
It is defined by an n-by-n matrix S, such that the solution must satisfy
|
| 731 |
+
S y(a) = 0. This condition will be forced during iterations, so it must not
|
| 732 |
+
contradict boundary conditions. See [2]_ for the explanation how this term
|
| 733 |
+
is handled when solving BVPs numerically.
|
| 734 |
+
|
| 735 |
+
Problems in a complex domain can be solved as well. In this case, y and p
|
| 736 |
+
are considered to be complex, and f and bc are assumed to be complex-valued
|
| 737 |
+
functions, but x stays real. Note that f and bc must be complex
|
| 738 |
+
differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
|
| 739 |
+
should rewrite your problem for real and imaginary parts separately. To
|
| 740 |
+
solve a problem in a complex domain, pass an initial guess for y with a
|
| 741 |
+
complex data type (see below).
|
| 742 |
+
|
| 743 |
+
Parameters
|
| 744 |
+
----------
|
| 745 |
+
fun : callable
|
| 746 |
+
Right-hand side of the system. The calling signature is ``fun(x, y)``,
|
| 747 |
+
or ``fun(x, y, p)`` if parameters are present. All arguments are
|
| 748 |
+
ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
|
| 749 |
+
``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
|
| 750 |
+
return value must be an array with shape (n, m) and with the same
|
| 751 |
+
layout as ``y``.
|
| 752 |
+
bc : callable
|
| 753 |
+
Function evaluating residuals of the boundary conditions. The calling
|
| 754 |
+
signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
|
| 755 |
+
present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
|
| 756 |
+
and ``p`` with shape (k,). The return value must be an array with
|
| 757 |
+
shape (n + k,).
|
| 758 |
+
x : array_like, shape (m,)
|
| 759 |
+
Initial mesh. Must be a strictly increasing sequence of real numbers
|
| 760 |
+
with ``x[0]=a`` and ``x[-1]=b``.
|
| 761 |
+
y : array_like, shape (n, m)
|
| 762 |
+
Initial guess for the function values at the mesh nodes, ith column
|
| 763 |
+
corresponds to ``x[i]``. For problems in a complex domain pass `y`
|
| 764 |
+
with a complex data type (even if the initial guess is purely real).
|
| 765 |
+
p : array_like with shape (k,) or None, optional
|
| 766 |
+
Initial guess for the unknown parameters. If None (default), it is
|
| 767 |
+
assumed that the problem doesn't depend on any parameters.
|
| 768 |
+
S : array_like with shape (n, n) or None
|
| 769 |
+
Matrix defining the singular term. If None (default), the problem is
|
| 770 |
+
solved without the singular term.
|
| 771 |
+
fun_jac : callable or None, optional
|
| 772 |
+
Function computing derivatives of f with respect to y and p. The
|
| 773 |
+
calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
|
| 774 |
+
parameters are present. The return must contain 1 or 2 elements in the
|
| 775 |
+
following order:
|
| 776 |
+
|
| 777 |
+
* df_dy : array_like with shape (n, n, m), where an element
|
| 778 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
|
| 779 |
+
* df_dp : array_like with shape (n, k, m), where an element
|
| 780 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
|
| 781 |
+
|
| 782 |
+
Here q numbers nodes at which x and y are defined, whereas i and j
|
| 783 |
+
number vector components. If the problem is solved without unknown
|
| 784 |
+
parameters, df_dp should not be returned.
|
| 785 |
+
|
| 786 |
+
If `fun_jac` is None (default), the derivatives will be estimated
|
| 787 |
+
by the forward finite differences.
|
| 788 |
+
bc_jac : callable or None, optional
|
| 789 |
+
Function computing derivatives of bc with respect to ya, yb, and p.
|
| 790 |
+
The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
|
| 791 |
+
if parameters are present. The return must contain 2 or 3 elements in
|
| 792 |
+
the following order:
|
| 793 |
+
|
| 794 |
+
* dbc_dya : array_like with shape (n, n), where an element (i, j)
|
| 795 |
+
equals to d bc_i(ya, yb, p) / d ya_j.
|
| 796 |
+
* dbc_dyb : array_like with shape (n, n), where an element (i, j)
|
| 797 |
+
equals to d bc_i(ya, yb, p) / d yb_j.
|
| 798 |
+
* dbc_dp : array_like with shape (n, k), where an element (i, j)
|
| 799 |
+
equals to d bc_i(ya, yb, p) / d p_j.
|
| 800 |
+
|
| 801 |
+
If the problem is solved without unknown parameters, dbc_dp should not
|
| 802 |
+
be returned.
|
| 803 |
+
|
| 804 |
+
If `bc_jac` is None (default), the derivatives will be estimated by
|
| 805 |
+
the forward finite differences.
|
| 806 |
+
tol : float, optional
|
| 807 |
+
Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
|
| 808 |
+
where y is the found solution, then the solver tries to achieve on each
|
| 809 |
+
mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
|
| 810 |
+
estimated in a root mean squared sense (using a numerical quadrature
|
| 811 |
+
formula). Default is 1e-3.
|
| 812 |
+
max_nodes : int, optional
|
| 813 |
+
Maximum allowed number of the mesh nodes. If exceeded, the algorithm
|
| 814 |
+
terminates. Default is 1000.
|
| 815 |
+
verbose : {0, 1, 2}, optional
|
| 816 |
+
Level of algorithm's verbosity:
|
| 817 |
+
|
| 818 |
+
* 0 (default) : work silently.
|
| 819 |
+
* 1 : display a termination report.
|
| 820 |
+
* 2 : display progress during iterations.
|
| 821 |
+
bc_tol : float, optional
|
| 822 |
+
Desired absolute tolerance for the boundary condition residuals: `bc`
|
| 823 |
+
value should satisfy ``abs(bc) < bc_tol`` component-wise.
|
| 824 |
+
Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
|
| 825 |
+
tolerance.
|
| 826 |
+
|
| 827 |
+
Returns
|
| 828 |
+
-------
|
| 829 |
+
Bunch object with the following fields defined:
|
| 830 |
+
sol : PPoly
|
| 831 |
+
Found solution for y as `scipy.interpolate.PPoly` instance, a C1
|
| 832 |
+
continuous cubic spline.
|
| 833 |
+
p : ndarray or None, shape (k,)
|
| 834 |
+
Found parameters. None, if the parameters were not present in the
|
| 835 |
+
problem.
|
| 836 |
+
x : ndarray, shape (m,)
|
| 837 |
+
Nodes of the final mesh.
|
| 838 |
+
y : ndarray, shape (n, m)
|
| 839 |
+
Solution values at the mesh nodes.
|
| 840 |
+
yp : ndarray, shape (n, m)
|
| 841 |
+
Solution derivatives at the mesh nodes.
|
| 842 |
+
rms_residuals : ndarray, shape (m - 1,)
|
| 843 |
+
RMS values of the relative residuals over each mesh interval (see the
|
| 844 |
+
description of `tol` parameter).
|
| 845 |
+
niter : int
|
| 846 |
+
Number of completed iterations.
|
| 847 |
+
status : int
|
| 848 |
+
Reason for algorithm termination:
|
| 849 |
+
|
| 850 |
+
* 0: The algorithm converged to the desired accuracy.
|
| 851 |
+
* 1: The maximum number of mesh nodes is exceeded.
|
| 852 |
+
* 2: A singular Jacobian encountered when solving the collocation
|
| 853 |
+
system.
|
| 854 |
+
|
| 855 |
+
message : string
|
| 856 |
+
Verbal description of the termination reason.
|
| 857 |
+
success : bool
|
| 858 |
+
True if the algorithm converged to the desired accuracy (``status=0``).
|
| 859 |
+
|
| 860 |
+
Notes
|
| 861 |
+
-----
|
| 862 |
+
This function implements a 4th order collocation algorithm with the
|
| 863 |
+
control of residuals similar to [1]_. A collocation system is solved
|
| 864 |
+
by a damped Newton method with an affine-invariant criterion function as
|
| 865 |
+
described in [3]_.
|
| 866 |
+
|
| 867 |
+
Note that in [1]_ integral residuals are defined without normalization
|
| 868 |
+
by interval lengths. So, their definition is different by a multiplier of
|
| 869 |
+
h**0.5 (h is an interval length) from the definition used here.
|
| 870 |
+
|
| 871 |
+
.. versionadded:: 0.18.0
|
| 872 |
+
|
| 873 |
+
References
|
| 874 |
+
----------
|
| 875 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 876 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 877 |
+
Number 3, pp. 299-316, 2001.
|
| 878 |
+
.. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
|
| 879 |
+
Solver", J. Numer. Anal., Ind. Appl. Math. (JNAIAM), Vol. 1,
|
| 880 |
+
Number 2, pp. 201-217, 2006.
|
| 881 |
+
.. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 882 |
+
Boundary Value Problems for Ordinary Differential Equations",
|
| 883 |
+
Philidelphia, PA: Society for Industrial and Applied Mathematics,
|
| 884 |
+
1995.
|
| 885 |
+
:doi:`10.1137/1.9781611971231`
|
| 886 |
+
.. [4] `Cauchy-Riemann equations
|
| 887 |
+
<https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
|
| 888 |
+
Wikipedia.
|
| 889 |
+
|
| 890 |
+
Examples
|
| 891 |
+
--------
|
| 892 |
+
In the first example, we solve Bratu's problem::
|
| 893 |
+
|
| 894 |
+
y'' + k * exp(y) = 0
|
| 895 |
+
y(0) = y(1) = 0
|
| 896 |
+
|
| 897 |
+
for k = 1.
|
| 898 |
+
|
| 899 |
+
We rewrite the equation as a first-order system and implement its
|
| 900 |
+
right-hand side evaluation::
|
| 901 |
+
|
| 902 |
+
y1' = y2
|
| 903 |
+
y2' = -exp(y1)
|
| 904 |
+
|
| 905 |
+
>>> import numpy as np
|
| 906 |
+
>>> def fun(x, y):
|
| 907 |
+
... return np.vstack((y[1], -np.exp(y[0])))
|
| 908 |
+
|
| 909 |
+
Implement evaluation of the boundary condition residuals:
|
| 910 |
+
|
| 911 |
+
>>> def bc(ya, yb):
|
| 912 |
+
... return np.array([ya[0], yb[0]])
|
| 913 |
+
|
| 914 |
+
Define the initial mesh with 5 nodes:
|
| 915 |
+
|
| 916 |
+
>>> x = np.linspace(0, 1, 5)
|
| 917 |
+
|
| 918 |
+
This problem is known to have two solutions. To obtain both of them, we
|
| 919 |
+
use two different initial guesses for y. We denote them by subscripts
|
| 920 |
+
a and b.
|
| 921 |
+
|
| 922 |
+
>>> y_a = np.zeros((2, x.size))
|
| 923 |
+
>>> y_b = np.zeros((2, x.size))
|
| 924 |
+
>>> y_b[0] = 3
|
| 925 |
+
|
| 926 |
+
Now we are ready to run the solver.
|
| 927 |
+
|
| 928 |
+
>>> from scipy.integrate import solve_bvp
|
| 929 |
+
>>> res_a = solve_bvp(fun, bc, x, y_a)
|
| 930 |
+
>>> res_b = solve_bvp(fun, bc, x, y_b)
|
| 931 |
+
|
| 932 |
+
Let's plot the two found solutions. We take an advantage of having the
|
| 933 |
+
solution in a spline form to produce a smooth plot.
|
| 934 |
+
|
| 935 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 936 |
+
>>> y_plot_a = res_a.sol(x_plot)[0]
|
| 937 |
+
>>> y_plot_b = res_b.sol(x_plot)[0]
|
| 938 |
+
>>> import matplotlib.pyplot as plt
|
| 939 |
+
>>> plt.plot(x_plot, y_plot_a, label='y_a')
|
| 940 |
+
>>> plt.plot(x_plot, y_plot_b, label='y_b')
|
| 941 |
+
>>> plt.legend()
|
| 942 |
+
>>> plt.xlabel("x")
|
| 943 |
+
>>> plt.ylabel("y")
|
| 944 |
+
>>> plt.show()
|
| 945 |
+
|
| 946 |
+
We see that the two solutions have similar shape, but differ in scale
|
| 947 |
+
significantly.
|
| 948 |
+
|
| 949 |
+
In the second example, we solve a simple Sturm-Liouville problem::
|
| 950 |
+
|
| 951 |
+
y'' + k**2 * y = 0
|
| 952 |
+
y(0) = y(1) = 0
|
| 953 |
+
|
| 954 |
+
It is known that a non-trivial solution y = A * sin(k * x) is possible for
|
| 955 |
+
k = pi * n, where n is an integer. To establish the normalization constant
|
| 956 |
+
A = 1 we add a boundary condition::
|
| 957 |
+
|
| 958 |
+
y'(0) = k
|
| 959 |
+
|
| 960 |
+
Again, we rewrite our equation as a first-order system and implement its
|
| 961 |
+
right-hand side evaluation::
|
| 962 |
+
|
| 963 |
+
y1' = y2
|
| 964 |
+
y2' = -k**2 * y1
|
| 965 |
+
|
| 966 |
+
>>> def fun(x, y, p):
|
| 967 |
+
... k = p[0]
|
| 968 |
+
... return np.vstack((y[1], -k**2 * y[0]))
|
| 969 |
+
|
| 970 |
+
Note that parameters p are passed as a vector (with one element in our
|
| 971 |
+
case).
|
| 972 |
+
|
| 973 |
+
Implement the boundary conditions:
|
| 974 |
+
|
| 975 |
+
>>> def bc(ya, yb, p):
|
| 976 |
+
... k = p[0]
|
| 977 |
+
... return np.array([ya[0], yb[0], ya[1] - k])
|
| 978 |
+
|
| 979 |
+
Set up the initial mesh and guess for y. We aim to find the solution for
|
| 980 |
+
k = 2 * pi, to achieve that we set values of y to approximately follow
|
| 981 |
+
sin(2 * pi * x):
|
| 982 |
+
|
| 983 |
+
>>> x = np.linspace(0, 1, 5)
|
| 984 |
+
>>> y = np.zeros((2, x.size))
|
| 985 |
+
>>> y[0, 1] = 1
|
| 986 |
+
>>> y[0, 3] = -1
|
| 987 |
+
|
| 988 |
+
Run the solver with 6 as an initial guess for k.
|
| 989 |
+
|
| 990 |
+
>>> sol = solve_bvp(fun, bc, x, y, p=[6])
|
| 991 |
+
|
| 992 |
+
We see that the found k is approximately correct:
|
| 993 |
+
|
| 994 |
+
>>> sol.p[0]
|
| 995 |
+
6.28329460046
|
| 996 |
+
|
| 997 |
+
And, finally, plot the solution to see the anticipated sinusoid:
|
| 998 |
+
|
| 999 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 1000 |
+
>>> y_plot = sol.sol(x_plot)[0]
|
| 1001 |
+
>>> plt.plot(x_plot, y_plot)
|
| 1002 |
+
>>> plt.xlabel("x")
|
| 1003 |
+
>>> plt.ylabel("y")
|
| 1004 |
+
>>> plt.show()
|
| 1005 |
+
"""
|
| 1006 |
+
x = np.asarray(x, dtype=float)
|
| 1007 |
+
if x.ndim != 1:
|
| 1008 |
+
raise ValueError("`x` must be 1 dimensional.")
|
| 1009 |
+
h = np.diff(x)
|
| 1010 |
+
if np.any(h <= 0):
|
| 1011 |
+
raise ValueError("`x` must be strictly increasing.")
|
| 1012 |
+
a = x[0]
|
| 1013 |
+
|
| 1014 |
+
y = np.asarray(y)
|
| 1015 |
+
if np.issubdtype(y.dtype, np.complexfloating):
|
| 1016 |
+
dtype = complex
|
| 1017 |
+
else:
|
| 1018 |
+
dtype = float
|
| 1019 |
+
y = y.astype(dtype, copy=False)
|
| 1020 |
+
|
| 1021 |
+
if y.ndim != 2:
|
| 1022 |
+
raise ValueError("`y` must be 2 dimensional.")
|
| 1023 |
+
if y.shape[1] != x.shape[0]:
|
| 1024 |
+
raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
|
| 1025 |
+
f"has {y.shape[1]}.")
|
| 1026 |
+
|
| 1027 |
+
if p is None:
|
| 1028 |
+
p = np.array([])
|
| 1029 |
+
else:
|
| 1030 |
+
p = np.asarray(p, dtype=dtype)
|
| 1031 |
+
if p.ndim != 1:
|
| 1032 |
+
raise ValueError("`p` must be 1 dimensional.")
|
| 1033 |
+
|
| 1034 |
+
if tol < 100 * EPS:
|
| 1035 |
+
warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
|
| 1036 |
+
tol = 100 * EPS
|
| 1037 |
+
|
| 1038 |
+
if verbose not in [0, 1, 2]:
|
| 1039 |
+
raise ValueError("`verbose` must be in [0, 1, 2].")
|
| 1040 |
+
|
| 1041 |
+
n = y.shape[0]
|
| 1042 |
+
k = p.shape[0]
|
| 1043 |
+
|
| 1044 |
+
if S is not None:
|
| 1045 |
+
S = np.asarray(S, dtype=dtype)
|
| 1046 |
+
if S.shape != (n, n):
|
| 1047 |
+
raise ValueError(f"`S` is expected to have shape {(n, n)}, "
|
| 1048 |
+
f"but actually has {S.shape}")
|
| 1049 |
+
|
| 1050 |
+
# Compute I - S^+ S to impose necessary boundary conditions.
|
| 1051 |
+
B = np.identity(n) - np.dot(pinv(S), S)
|
| 1052 |
+
|
| 1053 |
+
y[:, 0] = np.dot(B, y[:, 0])
|
| 1054 |
+
|
| 1055 |
+
# Compute (I - S)^+ to correct derivatives at x=a.
|
| 1056 |
+
D = pinv(np.identity(n) - S)
|
| 1057 |
+
else:
|
| 1058 |
+
B = None
|
| 1059 |
+
D = None
|
| 1060 |
+
|
| 1061 |
+
if bc_tol is None:
|
| 1062 |
+
bc_tol = tol
|
| 1063 |
+
|
| 1064 |
+
# Maximum number of iterations
|
| 1065 |
+
max_iteration = 10
|
| 1066 |
+
|
| 1067 |
+
fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
|
| 1068 |
+
fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
|
| 1069 |
+
|
| 1070 |
+
f = fun_wrapped(x, y, p)
|
| 1071 |
+
if f.shape != y.shape:
|
| 1072 |
+
raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
|
| 1073 |
+
f"but actually has {f.shape}.")
|
| 1074 |
+
|
| 1075 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1076 |
+
if bc_res.shape != (n + k,):
|
| 1077 |
+
raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
|
| 1078 |
+
f"but actually has {bc_res.shape}.")
|
| 1079 |
+
|
| 1080 |
+
status = 0
|
| 1081 |
+
iteration = 0
|
| 1082 |
+
if verbose == 2:
|
| 1083 |
+
print_iteration_header()
|
| 1084 |
+
|
| 1085 |
+
while True:
|
| 1086 |
+
m = x.shape[0]
|
| 1087 |
+
|
| 1088 |
+
col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
|
| 1089 |
+
fun_jac_wrapped, bc_jac_wrapped, x, h)
|
| 1090 |
+
y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
|
| 1091 |
+
y, p, B, tol, bc_tol)
|
| 1092 |
+
iteration += 1
|
| 1093 |
+
|
| 1094 |
+
col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
|
| 1095 |
+
p, x, h)
|
| 1096 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1097 |
+
max_bc_res = np.max(abs(bc_res))
|
| 1098 |
+
|
| 1099 |
+
# This relation is not trivial, but can be verified.
|
| 1100 |
+
r_middle = 1.5 * col_res / h
|
| 1101 |
+
sol = create_spline(y, f, x, h)
|
| 1102 |
+
rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
|
| 1103 |
+
r_middle, f_middle)
|
| 1104 |
+
max_rms_res = np.max(rms_res)
|
| 1105 |
+
|
| 1106 |
+
if singular:
|
| 1107 |
+
status = 2
|
| 1108 |
+
break
|
| 1109 |
+
|
| 1110 |
+
insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
|
| 1111 |
+
insert_2, = np.nonzero(rms_res >= 100 * tol)
|
| 1112 |
+
nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
|
| 1113 |
+
|
| 1114 |
+
if m + nodes_added > max_nodes:
|
| 1115 |
+
status = 1
|
| 1116 |
+
if verbose == 2:
|
| 1117 |
+
nodes_added = f"({nodes_added})"
|
| 1118 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res,
|
| 1119 |
+
m, nodes_added)
|
| 1120 |
+
break
|
| 1121 |
+
|
| 1122 |
+
if verbose == 2:
|
| 1123 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
|
| 1124 |
+
nodes_added)
|
| 1125 |
+
|
| 1126 |
+
if nodes_added > 0:
|
| 1127 |
+
x = modify_mesh(x, insert_1, insert_2)
|
| 1128 |
+
h = np.diff(x)
|
| 1129 |
+
y = sol(x)
|
| 1130 |
+
elif max_bc_res <= bc_tol:
|
| 1131 |
+
status = 0
|
| 1132 |
+
break
|
| 1133 |
+
elif iteration >= max_iteration:
|
| 1134 |
+
status = 3
|
| 1135 |
+
break
|
| 1136 |
+
|
| 1137 |
+
if verbose > 0:
|
| 1138 |
+
if status == 0:
|
| 1139 |
+
print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
|
| 1140 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1141 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1142 |
+
elif status == 1:
|
| 1143 |
+
print(f"Number of nodes is exceeded after iteration {iteration}. \n"
|
| 1144 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1145 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1146 |
+
elif status == 2:
|
| 1147 |
+
print("Singular Jacobian encountered when solving the collocation "
|
| 1148 |
+
f"system on iteration {iteration}. \n"
|
| 1149 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1150 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1151 |
+
elif status == 3:
|
| 1152 |
+
print("The solver was unable to satisfy boundary conditions "
|
| 1153 |
+
f"tolerance on iteration {iteration}. \n"
|
| 1154 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1155 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1156 |
+
|
| 1157 |
+
if p.size == 0:
|
| 1158 |
+
p = None
|
| 1159 |
+
|
| 1160 |
+
return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
|
| 1161 |
+
niter=iteration, status=status,
|
| 1162 |
+
message=TERMINATION_MESSAGES[status], success=status == 0)
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_cubature.py
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_promote,
|
| 14 |
+
xp_capabilities
|
| 15 |
+
)
|
| 16 |
+
from scipy._lib._util import MapWrapper
|
| 17 |
+
|
| 18 |
+
from scipy.integrate._rules import (
|
| 19 |
+
ProductNestedFixed,
|
| 20 |
+
GaussKronrodQuadrature,
|
| 21 |
+
GenzMalikCubature,
|
| 22 |
+
)
|
| 23 |
+
from scipy.integrate._rules._base import _split_subregion
|
| 24 |
+
|
| 25 |
+
__all__ = ['cubature']
|
| 26 |
+
|
| 27 |
+
Array: TypeAlias = Any # To be changed to an array-api-typing Protocol later
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class CubatureRegion:
|
| 32 |
+
estimate: Array
|
| 33 |
+
error: Array
|
| 34 |
+
a: Array
|
| 35 |
+
b: Array
|
| 36 |
+
_xp: ModuleType = field(repr=False)
|
| 37 |
+
|
| 38 |
+
def __lt__(self, other):
|
| 39 |
+
# Consider regions with higher error estimates as being "less than" regions with
|
| 40 |
+
# lower order estimates, so that regions with high error estimates are placed at
|
| 41 |
+
# the top of the heap.
|
| 42 |
+
|
| 43 |
+
this_err = self._xp.max(self._xp.abs(self.error))
|
| 44 |
+
other_err = self._xp.max(self._xp.abs(other.error))
|
| 45 |
+
|
| 46 |
+
return this_err > other_err
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@dataclass
|
| 50 |
+
class CubatureResult:
|
| 51 |
+
estimate: Array
|
| 52 |
+
error: Array
|
| 53 |
+
status: str
|
| 54 |
+
regions: list[CubatureRegion]
|
| 55 |
+
subdivisions: int
|
| 56 |
+
atol: float
|
| 57 |
+
rtol: float
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@xp_capabilities(allow_dask_compute=True, jax_jit=False)
|
| 61 |
+
def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
|
| 62 |
+
args=(), workers=1, points=None):
|
| 63 |
+
r"""
|
| 64 |
+
Adaptive cubature of multidimensional array-valued function.
|
| 65 |
+
|
| 66 |
+
Given an arbitrary integration rule, this function returns an estimate of the
|
| 67 |
+
integral to the requested tolerance over the region defined by the arrays `a` and
|
| 68 |
+
`b` specifying the corners of a hypercube.
|
| 69 |
+
|
| 70 |
+
Convergence is not guaranteed for all integrals.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
f : callable
|
| 75 |
+
Function to integrate. `f` must have the signature::
|
| 76 |
+
|
| 77 |
+
f(x : ndarray, *args) -> ndarray
|
| 78 |
+
|
| 79 |
+
`f` should accept arrays ``x`` of shape::
|
| 80 |
+
|
| 81 |
+
(npoints, ndim)
|
| 82 |
+
|
| 83 |
+
and output arrays of shape::
|
| 84 |
+
|
| 85 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 86 |
+
|
| 87 |
+
In this case, `cubature` will return arrays of shape::
|
| 88 |
+
|
| 89 |
+
(output_dim_1, ..., output_dim_n)
|
| 90 |
+
a, b : array_like
|
| 91 |
+
Lower and upper limits of integration as 1D arrays specifying the left and right
|
| 92 |
+
endpoints of the intervals being integrated over. Limits can be infinite.
|
| 93 |
+
rule : str, optional
|
| 94 |
+
Rule used to estimate the integral. If passing a string, the options are
|
| 95 |
+
"gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
|
| 96 |
+
"gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
|
| 97 |
+
Cartesian product rule is used. "gk21", "gk15" are also supported for
|
| 98 |
+
compatibility with `quad_vec`. See Notes.
|
| 99 |
+
rtol, atol : float, optional
|
| 100 |
+
Relative and absolute tolerances. Iterations are performed until the error is
|
| 101 |
+
estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
|
| 102 |
+
relative accuracy (number of correct digits), while `atol` controls absolute
|
| 103 |
+
accuracy (number of correct decimal places). To achieve the desired `rtol`, set
|
| 104 |
+
`atol` to be smaller than the smallest value that can be expected from
|
| 105 |
+
``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
|
| 106 |
+
larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
|
| 107 |
+
Conversely, to achieve the desired `atol`, set `rtol` such that
|
| 108 |
+
``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
|
| 109 |
+
`rtol` and 0 for `atol`.
|
| 110 |
+
max_subdivisions : int, optional
|
| 111 |
+
Upper bound on the number of subdivisions to perform. Default is 10,000.
|
| 112 |
+
args : tuple, optional
|
| 113 |
+
Additional positional args passed to `f`, if any.
|
| 114 |
+
workers : int or map-like callable, optional
|
| 115 |
+
If `workers` is an integer, part of the computation is done in parallel
|
| 116 |
+
subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
|
| 117 |
+
Supply `-1` to use all cores available to the Process. Alternatively, supply a
|
| 118 |
+
map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
|
| 119 |
+
evaluating the population in parallel. This evaluation is carried out as
|
| 120 |
+
``workers(func, iterable)``.
|
| 121 |
+
points : list of array_like, optional
|
| 122 |
+
List of points to avoid evaluating `f` at, under the condition that the rule
|
| 123 |
+
being used does not evaluate `f` on the boundary of a region (which is the
|
| 124 |
+
case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
|
| 125 |
+
a singularity at the specified point. This should be a list of array-likes where
|
| 126 |
+
each element has length ``ndim``. Default is empty. See Examples.
|
| 127 |
+
|
| 128 |
+
Returns
|
| 129 |
+
-------
|
| 130 |
+
res : object
|
| 131 |
+
Object containing the results of the estimation. It has the following
|
| 132 |
+
attributes:
|
| 133 |
+
|
| 134 |
+
estimate : ndarray
|
| 135 |
+
Estimate of the value of the integral over the overall region specified.
|
| 136 |
+
error : ndarray
|
| 137 |
+
Estimate of the error of the approximation over the overall region
|
| 138 |
+
specified.
|
| 139 |
+
status : str
|
| 140 |
+
Whether the estimation was successful. Can be either: "converged",
|
| 141 |
+
"not_converged".
|
| 142 |
+
subdivisions : int
|
| 143 |
+
Number of subdivisions performed.
|
| 144 |
+
atol, rtol : float
|
| 145 |
+
Requested tolerances for the approximation.
|
| 146 |
+
regions: list of object
|
| 147 |
+
List of objects containing the estimates of the integral over smaller
|
| 148 |
+
regions of the domain.
|
| 149 |
+
|
| 150 |
+
Each object in ``regions`` has the following attributes:
|
| 151 |
+
|
| 152 |
+
a, b : ndarray
|
| 153 |
+
Points describing the corners of the region. If the original integral
|
| 154 |
+
contained infinite limits or was over a region described by `region`,
|
| 155 |
+
then `a` and `b` are in the transformed coordinates.
|
| 156 |
+
estimate : ndarray
|
| 157 |
+
Estimate of the value of the integral over this region.
|
| 158 |
+
error : ndarray
|
| 159 |
+
Estimate of the error of the approximation over this region.
|
| 160 |
+
|
| 161 |
+
Notes
|
| 162 |
+
-----
|
| 163 |
+
The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
|
| 164 |
+
implementation of QUADPACK's DQAG* algorithms, implementing global error control and
|
| 165 |
+
adaptive subdivision.
|
| 166 |
+
|
| 167 |
+
The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
|
| 168 |
+
in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
|
| 169 |
+
cubature can be found in [2]_.
|
| 170 |
+
|
| 171 |
+
The rules currently supported via the `rule` argument are:
|
| 172 |
+
|
| 173 |
+
- ``"gauss-kronrod"``, 21-node Gauss-Kronrod
|
| 174 |
+
- ``"genz-malik"``, n-node Genz-Malik
|
| 175 |
+
|
| 176 |
+
If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
|
| 177 |
+
corresponding Cartesian product rule will be found by taking the Cartesian product
|
| 178 |
+
of the nodes in the 1D case. This means that the number of nodes scales
|
| 179 |
+
exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
|
| 180 |
+
moderate number of dimensions.
|
| 181 |
+
|
| 182 |
+
Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
|
| 183 |
+
so in this situation using "genz-malik" might be preferable.
|
| 184 |
+
|
| 185 |
+
Infinite limits are handled with an appropriate variable transformation. Assuming
|
| 186 |
+
``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
|
| 187 |
+
|
| 188 |
+
If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 189 |
+
will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
|
| 190 |
+
|
| 191 |
+
If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 192 |
+
will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
|
| 193 |
+
:math:`t \in (0, 1)`.
|
| 194 |
+
|
| 195 |
+
If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
|
| 196 |
+
variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
|
| 197 |
+
:math:`t \in (0, 1)`.
|
| 198 |
+
|
| 199 |
+
References
|
| 200 |
+
----------
|
| 201 |
+
.. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
|
| 202 |
+
Integration, files: dqk21.f, dqk15.f (1983).
|
| 203 |
+
|
| 204 |
+
.. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
|
| 205 |
+
numerical integration over an N-dimensional rectangular region, Journal of
|
| 206 |
+
Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
|
| 207 |
+
ISSN 0377-0427
|
| 208 |
+
:doi:`10.1016/0771-050X(80)90039-X`
|
| 209 |
+
|
| 210 |
+
Examples
|
| 211 |
+
--------
|
| 212 |
+
**1D integral with vector output**:
|
| 213 |
+
|
| 214 |
+
.. math::
|
| 215 |
+
|
| 216 |
+
\int^1_0 \mathbf f(x) \text dx
|
| 217 |
+
|
| 218 |
+
Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
|
| 219 |
+
specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
|
| 220 |
+
integration with 21 nodes.
|
| 221 |
+
|
| 222 |
+
>>> import numpy as np
|
| 223 |
+
>>> from scipy.integrate import cubature
|
| 224 |
+
>>> def f(x, n):
|
| 225 |
+
... # Make sure x and n are broadcastable
|
| 226 |
+
... return x[:, np.newaxis]**n[np.newaxis, :]
|
| 227 |
+
>>> res = cubature(
|
| 228 |
+
... f,
|
| 229 |
+
... a=[0],
|
| 230 |
+
... b=[1],
|
| 231 |
+
... args=(np.arange(10),),
|
| 232 |
+
... )
|
| 233 |
+
>>> res.estimate
|
| 234 |
+
array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ,
|
| 235 |
+
0.16666667, 0.14285714, 0.125 , 0.11111111, 0.1 ])
|
| 236 |
+
|
| 237 |
+
**7D integral with arbitrary-shaped array output**::
|
| 238 |
+
|
| 239 |
+
f(x) = cos(2*pi*r + alphas @ x)
|
| 240 |
+
|
| 241 |
+
for some ``r`` and ``alphas``, and the integral is performed over the unit
|
| 242 |
+
hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
|
| 243 |
+
dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
|
| 244 |
+
avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
|
| 245 |
+
|
| 246 |
+
>>> import numpy as np
|
| 247 |
+
>>> from scipy.integrate import cubature
|
| 248 |
+
>>> def f(x, r, alphas):
|
| 249 |
+
... # f(x) = cos(2*pi*r + alphas @ x)
|
| 250 |
+
... # Need to allow r and alphas to be arbitrary shape
|
| 251 |
+
... npoints, ndim = x.shape[0], x.shape[-1]
|
| 252 |
+
... alphas = alphas[np.newaxis, ...]
|
| 253 |
+
... x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
|
| 254 |
+
... return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
|
| 255 |
+
>>> rng = np.random.default_rng()
|
| 256 |
+
>>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
|
| 257 |
+
>>> res = cubature(
|
| 258 |
+
... f=f,
|
| 259 |
+
... a=np.array([0, 0, 0, 0, 0, 0, 0]),
|
| 260 |
+
... b=np.array([1, 1, 1, 1, 1, 1, 1]),
|
| 261 |
+
... rtol=1e-5,
|
| 262 |
+
... rule="genz-malik",
|
| 263 |
+
... args=(r, alphas),
|
| 264 |
+
... )
|
| 265 |
+
>>> res.estimate
|
| 266 |
+
array([[-0.79812452, 0.35246913, -0.52273628],
|
| 267 |
+
[ 0.88392779, 0.59139899, 0.41895111]])
|
| 268 |
+
|
| 269 |
+
**Parallel computation with** `workers`:
|
| 270 |
+
|
| 271 |
+
>>> from concurrent.futures import ThreadPoolExecutor
|
| 272 |
+
>>> with ThreadPoolExecutor() as executor:
|
| 273 |
+
... res = cubature(
|
| 274 |
+
... f=f,
|
| 275 |
+
... a=np.array([0, 0, 0, 0, 0, 0, 0]),
|
| 276 |
+
... b=np.array([1, 1, 1, 1, 1, 1, 1]),
|
| 277 |
+
... rtol=1e-5,
|
| 278 |
+
... rule="genz-malik",
|
| 279 |
+
... args=(r, alphas),
|
| 280 |
+
... workers=executor.map,
|
| 281 |
+
... )
|
| 282 |
+
>>> res.estimate
|
| 283 |
+
array([[-0.79812452, 0.35246913, -0.52273628],
|
| 284 |
+
[ 0.88392779, 0.59139899, 0.41895111]])
|
| 285 |
+
|
| 286 |
+
**2D integral with infinite limits**:
|
| 287 |
+
|
| 288 |
+
.. math::
|
| 289 |
+
|
| 290 |
+
\int^{ \infty }_{ -\infty }
|
| 291 |
+
\int^{ \infty }_{ -\infty }
|
| 292 |
+
e^{-x^2-y^2}
|
| 293 |
+
\text dy
|
| 294 |
+
\text dx
|
| 295 |
+
|
| 296 |
+
>>> def gaussian(x):
|
| 297 |
+
... return np.exp(-np.sum(x**2, axis=-1))
|
| 298 |
+
>>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
|
| 299 |
+
>>> res.estimate
|
| 300 |
+
3.1415926
|
| 301 |
+
|
| 302 |
+
**1D integral with singularities avoided using** `points`:
|
| 303 |
+
|
| 304 |
+
.. math::
|
| 305 |
+
|
| 306 |
+
\int^{ 1 }_{ -1 }
|
| 307 |
+
\frac{\sin(x)}{x}
|
| 308 |
+
\text dx
|
| 309 |
+
|
| 310 |
+
It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
|
| 311 |
+
|
| 312 |
+
>>> def sinc(x):
|
| 313 |
+
... return np.sin(x)/x
|
| 314 |
+
>>> res = cubature(sinc, [-1], [1], points=[[0]])
|
| 315 |
+
>>> res.estimate
|
| 316 |
+
1.8921661
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
# It is also possible to use a custom rule, but this is not yet part of the public
|
| 320 |
+
# API. An example of this can be found in the class scipy.integrate._rules.Rule.
|
| 321 |
+
|
| 322 |
+
xp = array_namespace(a, b)
|
| 323 |
+
max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
|
| 324 |
+
points = [] if points is None else points
|
| 325 |
+
|
| 326 |
+
# Convert a and b to arrays and convert each point in points to an array, promoting
|
| 327 |
+
# each to a common floating dtype.
|
| 328 |
+
a, b, *points = xp_promote(a, b, *points, broadcast=True, force_floating=True,
|
| 329 |
+
xp=xp)
|
| 330 |
+
result_dtype = a.dtype
|
| 331 |
+
|
| 332 |
+
if xp_size(a) == 0 or xp_size(b) == 0:
|
| 333 |
+
raise ValueError("`a` and `b` must be nonempty")
|
| 334 |
+
|
| 335 |
+
if a.ndim != 1 or b.ndim != 1:
|
| 336 |
+
raise ValueError("`a` and `b` must be 1D arrays")
|
| 337 |
+
|
| 338 |
+
# If the rule is a string, convert to a corresponding product rule
|
| 339 |
+
if isinstance(rule, str):
|
| 340 |
+
ndim = xp_size(a)
|
| 341 |
+
|
| 342 |
+
if rule == "genz-malik":
|
| 343 |
+
rule = GenzMalikCubature(ndim, xp=xp)
|
| 344 |
+
else:
|
| 345 |
+
quadratues = {
|
| 346 |
+
"gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
|
| 347 |
+
|
| 348 |
+
# Also allow names quad_vec uses:
|
| 349 |
+
"gk21": GaussKronrodQuadrature(21, xp=xp),
|
| 350 |
+
"gk15": GaussKronrodQuadrature(15, xp=xp),
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
base_rule = quadratues.get(rule)
|
| 354 |
+
|
| 355 |
+
if base_rule is None:
|
| 356 |
+
raise ValueError(f"unknown rule {rule}")
|
| 357 |
+
|
| 358 |
+
rule = ProductNestedFixed([base_rule] * ndim)
|
| 359 |
+
|
| 360 |
+
# If any of limits are the wrong way around (a > b), flip them and keep track of
|
| 361 |
+
# the sign.
|
| 362 |
+
sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
|
| 363 |
+
|
| 364 |
+
a_flipped = xp.min(xp.stack([a, b]), axis=0)
|
| 365 |
+
b_flipped = xp.max(xp.stack([a, b]), axis=0)
|
| 366 |
+
|
| 367 |
+
a, b = a_flipped, b_flipped
|
| 368 |
+
|
| 369 |
+
# If any of the limits are infinite, apply a transformation
|
| 370 |
+
if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
|
| 371 |
+
f = _InfiniteLimitsTransform(f, a, b, xp=xp)
|
| 372 |
+
a, b = f.transformed_limits
|
| 373 |
+
|
| 374 |
+
# Map points from the original coordinates to the new transformed coordinates.
|
| 375 |
+
#
|
| 376 |
+
# `points` is a list of arrays of shape (ndim,), but transformations are applied
|
| 377 |
+
# to arrays of shape (npoints, ndim).
|
| 378 |
+
#
|
| 379 |
+
# It is not possible to combine all the points into one array and then apply
|
| 380 |
+
# f.inv to all of them at once since `points` needs to remain iterable.
|
| 381 |
+
# Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
|
| 382 |
+
# applied, and then each is reshaped back to (ndim,).
|
| 383 |
+
points = [xp.reshape(point, (1, -1)) for point in points]
|
| 384 |
+
points = [f.inv(point) for point in points]
|
| 385 |
+
points = [xp.reshape(point, (-1,)) for point in points]
|
| 386 |
+
|
| 387 |
+
# Include any problematic points introduced by the transformation
|
| 388 |
+
points.extend(f.points)
|
| 389 |
+
|
| 390 |
+
# If any problematic points are specified, divide the initial region so that these
|
| 391 |
+
# points lie on the edge of a subregion.
|
| 392 |
+
#
|
| 393 |
+
# This means ``f`` won't be evaluated there if the rule being used has no evaluation
|
| 394 |
+
# points on the boundary.
|
| 395 |
+
if len(points) == 0:
|
| 396 |
+
initial_regions = [(a, b)]
|
| 397 |
+
else:
|
| 398 |
+
initial_regions = _split_region_at_points(a, b, points, xp)
|
| 399 |
+
|
| 400 |
+
regions = []
|
| 401 |
+
est = 0.0
|
| 402 |
+
err = 0.0
|
| 403 |
+
|
| 404 |
+
for a_k, b_k in initial_regions:
|
| 405 |
+
est_k = rule.estimate(f, a_k, b_k, args)
|
| 406 |
+
err_k = rule.estimate_error(f, a_k, b_k, args)
|
| 407 |
+
regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
|
| 408 |
+
|
| 409 |
+
est += est_k
|
| 410 |
+
err += err_k
|
| 411 |
+
|
| 412 |
+
subdivisions = 0
|
| 413 |
+
success = True
|
| 414 |
+
|
| 415 |
+
with MapWrapper(workers) as mapwrapper:
|
| 416 |
+
while xp.any(err > atol + rtol * xp.abs(est)):
|
| 417 |
+
# region_k is the region with highest estimated error
|
| 418 |
+
region_k = heapq.heappop(regions)
|
| 419 |
+
|
| 420 |
+
est_k = region_k.estimate
|
| 421 |
+
err_k = region_k.error
|
| 422 |
+
|
| 423 |
+
a_k, b_k = region_k.a, region_k.b
|
| 424 |
+
|
| 425 |
+
# Subtract the estimate of the integral and its error over this region from
|
| 426 |
+
# the current global estimates, since these will be refined in the loop over
|
| 427 |
+
# all subregions.
|
| 428 |
+
est -= est_k
|
| 429 |
+
err -= err_k
|
| 430 |
+
|
| 431 |
+
# Find all 2^ndim subregions formed by splitting region_k along each axis,
|
| 432 |
+
# e.g. for 1D integrals this splits an estimate over an interval into an
|
| 433 |
+
# estimate over two subintervals, for 3D integrals this splits an estimate
|
| 434 |
+
# over a cube into 8 subcubes.
|
| 435 |
+
#
|
| 436 |
+
# For each of the new subregions, calculate an estimate for the integral and
|
| 437 |
+
# the error there, and push these regions onto the heap for potential
|
| 438 |
+
# further subdividing.
|
| 439 |
+
|
| 440 |
+
executor_args = zip(
|
| 441 |
+
itertools.repeat(f),
|
| 442 |
+
itertools.repeat(rule),
|
| 443 |
+
itertools.repeat(args),
|
| 444 |
+
_split_subregion(a_k, b_k, xp),
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
for subdivision_result in mapwrapper(_process_subregion, executor_args):
|
| 448 |
+
a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
|
| 449 |
+
|
| 450 |
+
est += est_sub
|
| 451 |
+
err += err_sub
|
| 452 |
+
|
| 453 |
+
new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
|
| 454 |
+
|
| 455 |
+
heapq.heappush(regions, new_region)
|
| 456 |
+
|
| 457 |
+
subdivisions += 1
|
| 458 |
+
|
| 459 |
+
if subdivisions >= max_subdivisions:
|
| 460 |
+
success = False
|
| 461 |
+
break
|
| 462 |
+
|
| 463 |
+
status = "converged" if success else "not_converged"
|
| 464 |
+
|
| 465 |
+
# Apply sign change to handle any limits which were initially flipped.
|
| 466 |
+
est = sign * est
|
| 467 |
+
|
| 468 |
+
return CubatureResult(
|
| 469 |
+
estimate=est,
|
| 470 |
+
error=err,
|
| 471 |
+
status=status,
|
| 472 |
+
subdivisions=subdivisions,
|
| 473 |
+
regions=regions,
|
| 474 |
+
atol=atol,
|
| 475 |
+
rtol=rtol,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def _process_subregion(data):
|
| 480 |
+
f, rule, args, coord = data
|
| 481 |
+
a_k_sub, b_k_sub = coord
|
| 482 |
+
|
| 483 |
+
est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
|
| 484 |
+
err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
|
| 485 |
+
|
| 486 |
+
return a_k_sub, b_k_sub, est_sub, err_sub
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _is_strictly_in_region(a, b, point, xp):
|
| 490 |
+
if xp.all(point == a) or xp.all(point == b):
|
| 491 |
+
return False
|
| 492 |
+
|
| 493 |
+
return xp.all(a <= point) and xp.all(point <= b)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def _split_region_at_points(a, b, points, xp):
|
| 497 |
+
"""
|
| 498 |
+
Given the integration limits `a` and `b` describing a rectangular region and a list
|
| 499 |
+
of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
|
| 500 |
+
initial region into smaller subregion such that no `points` lie strictly inside
|
| 501 |
+
any of the subregions.
|
| 502 |
+
"""
|
| 503 |
+
|
| 504 |
+
regions = [(a, b)]
|
| 505 |
+
|
| 506 |
+
for point in points:
|
| 507 |
+
if xp.any(xp.isinf(point)):
|
| 508 |
+
# If a point is specified at infinity, ignore.
|
| 509 |
+
#
|
| 510 |
+
# This case occurs when points are given by the user to avoid, but after
|
| 511 |
+
# applying a transformation, they are removed.
|
| 512 |
+
continue
|
| 513 |
+
|
| 514 |
+
new_subregions = []
|
| 515 |
+
|
| 516 |
+
for a_k, b_k in regions:
|
| 517 |
+
if _is_strictly_in_region(a_k, b_k, point, xp):
|
| 518 |
+
subregions = _split_subregion(a_k, b_k, xp, point)
|
| 519 |
+
|
| 520 |
+
for left, right in subregions:
|
| 521 |
+
# Skip any zero-width regions.
|
| 522 |
+
if xp.any(left == right):
|
| 523 |
+
continue
|
| 524 |
+
else:
|
| 525 |
+
new_subregions.append((left, right))
|
| 526 |
+
|
| 527 |
+
new_subregions.extend(subregions)
|
| 528 |
+
|
| 529 |
+
else:
|
| 530 |
+
new_subregions.append((a_k, b_k))
|
| 531 |
+
|
| 532 |
+
regions = new_subregions
|
| 533 |
+
|
| 534 |
+
return regions
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class _VariableTransform:
|
| 538 |
+
"""
|
| 539 |
+
A transformation that can be applied to an integral.
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
@property
|
| 543 |
+
def transformed_limits(self):
|
| 544 |
+
"""
|
| 545 |
+
New limits of integration after applying the transformation.
|
| 546 |
+
"""
|
| 547 |
+
|
| 548 |
+
raise NotImplementedError
|
| 549 |
+
|
| 550 |
+
@property
|
| 551 |
+
def points(self):
|
| 552 |
+
"""
|
| 553 |
+
Any problematic points introduced by the transformation.
|
| 554 |
+
|
| 555 |
+
These should be specified as points where ``_VariableTransform(f)(self, point)``
|
| 556 |
+
would be problematic.
|
| 557 |
+
|
| 558 |
+
For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
|
| 559 |
+
univariate integral, then points should return ``[ [1], [-1] ]``.
|
| 560 |
+
"""
|
| 561 |
+
|
| 562 |
+
return []
|
| 563 |
+
|
| 564 |
+
def inv(self, x):
|
| 565 |
+
"""
|
| 566 |
+
Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
|
| 567 |
+
is the function after the transformation is applied, then::
|
| 568 |
+
|
| 569 |
+
f(x) = g(self.inv(x))
|
| 570 |
+
"""
|
| 571 |
+
|
| 572 |
+
raise NotImplementedError
|
| 573 |
+
|
| 574 |
+
def __call__(self, t, *args, **kwargs):
|
| 575 |
+
"""
|
| 576 |
+
Apply the transformation to ``f`` and multiply by the Jacobian determinant.
|
| 577 |
+
This should be the new integrand after the transformation has been applied so
|
| 578 |
+
that the following is satisfied::
|
| 579 |
+
|
| 580 |
+
f_transformed = _VariableTransform(f)
|
| 581 |
+
|
| 582 |
+
cubature(f, a, b) == cubature(
|
| 583 |
+
f_transformed,
|
| 584 |
+
*f_transformed.transformed_limits(a, b),
|
| 585 |
+
)
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
raise NotImplementedError
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class _InfiniteLimitsTransform(_VariableTransform):
|
| 592 |
+
r"""
|
| 593 |
+
Transformation for handling infinite limits.
|
| 594 |
+
|
| 595 |
+
Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
|
| 596 |
+
|
| 597 |
+
If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 598 |
+
will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
|
| 599 |
+
|
| 600 |
+
If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 601 |
+
will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
|
| 602 |
+
:math:`t \in (0, 1)`.
|
| 603 |
+
|
| 604 |
+
If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
|
| 605 |
+
variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
|
| 606 |
+
:math:`t \in (0, 1)`.
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
def __init__(self, f, a, b, xp):
|
| 610 |
+
self._xp = xp
|
| 611 |
+
|
| 612 |
+
self._f = f
|
| 613 |
+
self._orig_a = a
|
| 614 |
+
self._orig_b = b
|
| 615 |
+
|
| 616 |
+
# (-oo, oo) will be mapped to (-1, 1).
|
| 617 |
+
self._double_inf_pos = (a == -math.inf) & (b == math.inf)
|
| 618 |
+
|
| 619 |
+
# (start, oo) will be mapped to (0, 1).
|
| 620 |
+
start_inf_mask = (a != -math.inf) & (b == math.inf)
|
| 621 |
+
|
| 622 |
+
# (-oo, end) will be mapped to (0, 1).
|
| 623 |
+
inf_end_mask = (a == -math.inf) & (b != math.inf)
|
| 624 |
+
|
| 625 |
+
# This is handled by making the transformation t = -x and reducing it to
|
| 626 |
+
# the other semi-infinite case.
|
| 627 |
+
self._semi_inf_pos = start_inf_mask | inf_end_mask
|
| 628 |
+
|
| 629 |
+
# Since we flip the limits, we don't need to separately multiply the
|
| 630 |
+
# integrand by -1.
|
| 631 |
+
self._orig_a[inf_end_mask] = -b[inf_end_mask]
|
| 632 |
+
self._orig_b[inf_end_mask] = -a[inf_end_mask]
|
| 633 |
+
|
| 634 |
+
self._num_inf = self._xp.sum(
|
| 635 |
+
self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
|
| 636 |
+
).__int__()
|
| 637 |
+
|
| 638 |
+
@property
|
| 639 |
+
def transformed_limits(self):
|
| 640 |
+
a = xp_copy(self._orig_a)
|
| 641 |
+
b = xp_copy(self._orig_b)
|
| 642 |
+
|
| 643 |
+
a[self._double_inf_pos] = -1
|
| 644 |
+
b[self._double_inf_pos] = 1
|
| 645 |
+
|
| 646 |
+
a[self._semi_inf_pos] = 0
|
| 647 |
+
b[self._semi_inf_pos] = 1
|
| 648 |
+
|
| 649 |
+
return a, b
|
| 650 |
+
|
| 651 |
+
@property
|
| 652 |
+
def points(self):
|
| 653 |
+
# If there are infinite limits, then the origin becomes a problematic point
|
| 654 |
+
# due to a division by zero there.
|
| 655 |
+
|
| 656 |
+
# If the function using this class only wraps f when a and b contain infinite
|
| 657 |
+
# limits, this condition will always be met (as is the case with cubature).
|
| 658 |
+
#
|
| 659 |
+
# If a and b do not contain infinite limits but f is still wrapped with this
|
| 660 |
+
# class, then without this condition the initial region of integration will
|
| 661 |
+
# be split around the origin unnecessarily.
|
| 662 |
+
if self._num_inf != 0:
|
| 663 |
+
return [self._xp.zeros(self._orig_a.shape)]
|
| 664 |
+
else:
|
| 665 |
+
return []
|
| 666 |
+
|
| 667 |
+
def inv(self, x):
|
| 668 |
+
t = xp_copy(x)
|
| 669 |
+
npoints = x.shape[0]
|
| 670 |
+
|
| 671 |
+
double_inf_mask = self._xp.tile(
|
| 672 |
+
self._double_inf_pos[self._xp.newaxis, :],
|
| 673 |
+
(npoints, 1),
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
semi_inf_mask = self._xp.tile(
|
| 677 |
+
self._semi_inf_pos[self._xp.newaxis, :],
|
| 678 |
+
(npoints, 1),
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
# If any components of x are 0, then this component will be mapped to infinity
|
| 682 |
+
# under the transformation used for doubly-infinite limits.
|
| 683 |
+
#
|
| 684 |
+
# Handle the zero values and non-zero values separately to avoid division by
|
| 685 |
+
# zero.
|
| 686 |
+
zero_mask = x[double_inf_mask] == 0
|
| 687 |
+
non_zero_mask = double_inf_mask & ~zero_mask
|
| 688 |
+
t[zero_mask] = math.inf
|
| 689 |
+
t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
|
| 690 |
+
|
| 691 |
+
start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
|
| 692 |
+
t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
|
| 693 |
+
|
| 694 |
+
return t
|
| 695 |
+
|
| 696 |
+
def __call__(self, t, *args, **kwargs):
|
| 697 |
+
x = xp_copy(t)
|
| 698 |
+
npoints = t.shape[0]
|
| 699 |
+
|
| 700 |
+
double_inf_mask = self._xp.tile(
|
| 701 |
+
self._double_inf_pos[self._xp.newaxis, :],
|
| 702 |
+
(npoints, 1),
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
semi_inf_mask = self._xp.tile(
|
| 706 |
+
self._semi_inf_pos[self._xp.newaxis, :],
|
| 707 |
+
(npoints, 1),
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
# For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
|
| 711 |
+
x[double_inf_mask] = (
|
| 712 |
+
(1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
|
| 716 |
+
|
| 717 |
+
# For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
|
| 718 |
+
x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
|
| 719 |
+
|
| 720 |
+
jacobian_det = 1/self._xp.prod(
|
| 721 |
+
self._xp.reshape(
|
| 722 |
+
t[semi_inf_mask | double_inf_mask]**2,
|
| 723 |
+
(-1, self._num_inf),
|
| 724 |
+
),
|
| 725 |
+
axis=-1,
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
f_x = self._f(x, *args, **kwargs)
|
| 729 |
+
jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
|
| 730 |
+
|
| 731 |
+
return f_x * jacobian_det
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-darwin.so
ADDED
|
Binary file (85.4 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._base.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._bdf.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._common.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._dop853_coefficients.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._ivp.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._lsoda.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._radau.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._rk.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/._tests
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/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
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/base.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import GenericAlias
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def check_arguments(fun, y0, support_complex):
|
| 6 |
+
"""Helper function for checking arguments common to all solvers."""
|
| 7 |
+
y0 = np.asarray(y0)
|
| 8 |
+
if np.issubdtype(y0.dtype, np.complexfloating):
|
| 9 |
+
if not support_complex:
|
| 10 |
+
raise ValueError("`y0` is complex, but the chosen solver does "
|
| 11 |
+
"not support integration in a complex domain.")
|
| 12 |
+
dtype = complex
|
| 13 |
+
else:
|
| 14 |
+
dtype = float
|
| 15 |
+
y0 = y0.astype(dtype, copy=False)
|
| 16 |
+
|
| 17 |
+
if y0.ndim != 1:
|
| 18 |
+
raise ValueError("`y0` must be 1-dimensional.")
|
| 19 |
+
|
| 20 |
+
if not np.isfinite(y0).all():
|
| 21 |
+
raise ValueError("All components of the initial state `y0` must be finite.")
|
| 22 |
+
|
| 23 |
+
def fun_wrapped(t, y):
|
| 24 |
+
return np.asarray(fun(t, y), dtype=dtype)
|
| 25 |
+
|
| 26 |
+
return fun_wrapped, y0
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class OdeSolver:
|
| 30 |
+
"""Base class for ODE solvers.
|
| 31 |
+
|
| 32 |
+
In order to implement a new solver you need to follow the guidelines:
|
| 33 |
+
|
| 34 |
+
1. A constructor must accept parameters presented in the base class
|
| 35 |
+
(listed below) along with any other parameters specific to a solver.
|
| 36 |
+
2. A constructor must accept arbitrary extraneous arguments
|
| 37 |
+
``**extraneous``, but warn that these arguments are irrelevant
|
| 38 |
+
using `common.warn_extraneous` function. Do not pass these
|
| 39 |
+
arguments to the base class.
|
| 40 |
+
3. A solver must implement a private method `_step_impl(self)` which
|
| 41 |
+
propagates a solver one step further. It must return tuple
|
| 42 |
+
``(success, message)``, where ``success`` is a boolean indicating
|
| 43 |
+
whether a step was successful, and ``message`` is a string
|
| 44 |
+
containing description of a failure if a step failed or None
|
| 45 |
+
otherwise.
|
| 46 |
+
4. A solver must implement a private method `_dense_output_impl(self)`,
|
| 47 |
+
which returns a `DenseOutput` object covering the last successful
|
| 48 |
+
step.
|
| 49 |
+
5. A solver must have attributes listed below in Attributes section.
|
| 50 |
+
Note that ``t_old`` and ``step_size`` are updated automatically.
|
| 51 |
+
6. Use `fun(self, t, y)` method for the system rhs evaluation, this
|
| 52 |
+
way the number of function evaluations (`nfev`) will be tracked
|
| 53 |
+
automatically.
|
| 54 |
+
7. For convenience, a base class provides `fun_single(self, t, y)` and
|
| 55 |
+
`fun_vectorized(self, t, y)` for evaluating the rhs in
|
| 56 |
+
non-vectorized and vectorized fashions respectively (regardless of
|
| 57 |
+
how `fun` from the constructor is implemented). These calls don't
|
| 58 |
+
increment `nfev`.
|
| 59 |
+
8. If a solver uses a Jacobian matrix and LU decompositions, it should
|
| 60 |
+
track the number of Jacobian evaluations (`njev`) and the number of
|
| 61 |
+
LU decompositions (`nlu`).
|
| 62 |
+
9. By convention, the function evaluations used to compute a finite
|
| 63 |
+
difference approximation of the Jacobian should not be counted in
|
| 64 |
+
`nfev`, thus use `fun_single(self, t, y)` or
|
| 65 |
+
`fun_vectorized(self, t, y)` when computing a finite difference
|
| 66 |
+
approximation of the Jacobian.
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
----------
|
| 70 |
+
fun : callable
|
| 71 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 72 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 73 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 74 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 75 |
+
information.
|
| 76 |
+
t0 : float
|
| 77 |
+
Initial time.
|
| 78 |
+
y0 : array_like, shape (n,)
|
| 79 |
+
Initial state.
|
| 80 |
+
t_bound : float
|
| 81 |
+
Boundary time --- the integration won't continue beyond it. It also
|
| 82 |
+
determines the direction of the integration.
|
| 83 |
+
vectorized : bool
|
| 84 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
| 85 |
+
|
| 86 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 87 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 88 |
+
|
| 89 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 90 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 91 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 92 |
+
the returned array is the time derivative of the state corresponding
|
| 93 |
+
with a column of ``y``).
|
| 94 |
+
|
| 95 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 96 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
| 97 |
+
will result in slower execution for other methods. It can also
|
| 98 |
+
result in slower overall execution for 'Radau' and 'BDF' in some
|
| 99 |
+
circumstances (e.g. small ``len(y0)``).
|
| 100 |
+
support_complex : bool, optional
|
| 101 |
+
Whether integration in a complex domain should be supported.
|
| 102 |
+
Generally determined by a derived solver class capabilities.
|
| 103 |
+
Default is False.
|
| 104 |
+
|
| 105 |
+
Attributes
|
| 106 |
+
----------
|
| 107 |
+
n : int
|
| 108 |
+
Number of equations.
|
| 109 |
+
status : string
|
| 110 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 111 |
+
t_bound : float
|
| 112 |
+
Boundary time.
|
| 113 |
+
direction : float
|
| 114 |
+
Integration direction: +1 or -1.
|
| 115 |
+
t : float
|
| 116 |
+
Current time.
|
| 117 |
+
y : ndarray
|
| 118 |
+
Current state.
|
| 119 |
+
t_old : float
|
| 120 |
+
Previous time. None if no steps were made yet.
|
| 121 |
+
step_size : float
|
| 122 |
+
Size of the last successful step. None if no steps were made yet.
|
| 123 |
+
nfev : int
|
| 124 |
+
Number of the system's rhs evaluations.
|
| 125 |
+
njev : int
|
| 126 |
+
Number of the Jacobian evaluations.
|
| 127 |
+
nlu : int
|
| 128 |
+
Number of LU decompositions.
|
| 129 |
+
"""
|
| 130 |
+
TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
|
| 131 |
+
|
| 132 |
+
# generic type compatibility with scipy-stubs
|
| 133 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 134 |
+
|
| 135 |
+
def __init__(self, fun, t0, y0, t_bound, vectorized,
|
| 136 |
+
support_complex=False):
|
| 137 |
+
self.t_old = None
|
| 138 |
+
self.t = t0
|
| 139 |
+
self._fun, self.y = check_arguments(fun, y0, support_complex)
|
| 140 |
+
self.t_bound = t_bound
|
| 141 |
+
self.vectorized = vectorized
|
| 142 |
+
|
| 143 |
+
if vectorized:
|
| 144 |
+
def fun_single(t, y):
|
| 145 |
+
return self._fun(t, y[:, None]).ravel()
|
| 146 |
+
fun_vectorized = self._fun
|
| 147 |
+
else:
|
| 148 |
+
fun_single = self._fun
|
| 149 |
+
|
| 150 |
+
def fun_vectorized(t, y):
|
| 151 |
+
f = np.empty_like(y)
|
| 152 |
+
for i, yi in enumerate(y.T):
|
| 153 |
+
f[:, i] = self._fun(t, yi)
|
| 154 |
+
return f
|
| 155 |
+
|
| 156 |
+
def fun(t, y):
|
| 157 |
+
self.nfev += 1
|
| 158 |
+
return self.fun_single(t, y)
|
| 159 |
+
|
| 160 |
+
self.fun = fun
|
| 161 |
+
self.fun_single = fun_single
|
| 162 |
+
self.fun_vectorized = fun_vectorized
|
| 163 |
+
|
| 164 |
+
self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
|
| 165 |
+
self.n = self.y.size
|
| 166 |
+
self.status = 'running'
|
| 167 |
+
|
| 168 |
+
self.nfev = 0
|
| 169 |
+
self.njev = 0
|
| 170 |
+
self.nlu = 0
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def step_size(self):
|
| 174 |
+
if self.t_old is None:
|
| 175 |
+
return None
|
| 176 |
+
else:
|
| 177 |
+
return np.abs(self.t - self.t_old)
|
| 178 |
+
|
| 179 |
+
def step(self):
|
| 180 |
+
"""Perform one integration step.
|
| 181 |
+
|
| 182 |
+
Returns
|
| 183 |
+
-------
|
| 184 |
+
message : string or None
|
| 185 |
+
Report from the solver. Typically a reason for a failure if
|
| 186 |
+
`self.status` is 'failed' after the step was taken or None
|
| 187 |
+
otherwise.
|
| 188 |
+
"""
|
| 189 |
+
if self.status != 'running':
|
| 190 |
+
raise RuntimeError("Attempt to step on a failed or finished "
|
| 191 |
+
"solver.")
|
| 192 |
+
|
| 193 |
+
if self.n == 0 or self.t == self.t_bound:
|
| 194 |
+
# Handle corner cases of empty solver or no integration.
|
| 195 |
+
self.t_old = self.t
|
| 196 |
+
self.t = self.t_bound
|
| 197 |
+
message = None
|
| 198 |
+
self.status = 'finished'
|
| 199 |
+
else:
|
| 200 |
+
t = self.t
|
| 201 |
+
success, message = self._step_impl()
|
| 202 |
+
|
| 203 |
+
if not success:
|
| 204 |
+
self.status = 'failed'
|
| 205 |
+
else:
|
| 206 |
+
self.t_old = t
|
| 207 |
+
if self.direction * (self.t - self.t_bound) >= 0:
|
| 208 |
+
self.status = 'finished'
|
| 209 |
+
|
| 210 |
+
return message
|
| 211 |
+
|
| 212 |
+
def dense_output(self):
|
| 213 |
+
"""Compute a local interpolant over the last successful step.
|
| 214 |
+
|
| 215 |
+
Returns
|
| 216 |
+
-------
|
| 217 |
+
sol : `DenseOutput`
|
| 218 |
+
Local interpolant over the last successful step.
|
| 219 |
+
"""
|
| 220 |
+
if self.t_old is None:
|
| 221 |
+
raise RuntimeError("Dense output is available after a successful "
|
| 222 |
+
"step was made.")
|
| 223 |
+
|
| 224 |
+
if self.n == 0 or self.t == self.t_old:
|
| 225 |
+
# Handle corner cases of empty solver and no integration.
|
| 226 |
+
return ConstantDenseOutput(self.t_old, self.t, self.y)
|
| 227 |
+
else:
|
| 228 |
+
return self._dense_output_impl()
|
| 229 |
+
|
| 230 |
+
def _step_impl(self):
|
| 231 |
+
raise NotImplementedError
|
| 232 |
+
|
| 233 |
+
def _dense_output_impl(self):
|
| 234 |
+
raise NotImplementedError
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class DenseOutput:
|
| 238 |
+
"""Base class for local interpolant over step made by an ODE solver.
|
| 239 |
+
|
| 240 |
+
It interpolates between `t_min` and `t_max` (see Attributes below).
|
| 241 |
+
Evaluation outside this interval is not forbidden, but the accuracy is not
|
| 242 |
+
guaranteed.
|
| 243 |
+
|
| 244 |
+
Attributes
|
| 245 |
+
----------
|
| 246 |
+
t_min, t_max : float
|
| 247 |
+
Time range of the interpolation.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
# generic type compatibility with scipy-stubs
|
| 251 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 252 |
+
|
| 253 |
+
def __init__(self, t_old, t):
|
| 254 |
+
self.t_old = t_old
|
| 255 |
+
self.t = t
|
| 256 |
+
self.t_min = min(t, t_old)
|
| 257 |
+
self.t_max = max(t, t_old)
|
| 258 |
+
|
| 259 |
+
def __call__(self, t):
|
| 260 |
+
"""Evaluate the interpolant.
|
| 261 |
+
|
| 262 |
+
Parameters
|
| 263 |
+
----------
|
| 264 |
+
t : float or array_like with shape (n_points,)
|
| 265 |
+
Points to evaluate the solution at.
|
| 266 |
+
|
| 267 |
+
Returns
|
| 268 |
+
-------
|
| 269 |
+
y : ndarray, shape (n,) or (n, n_points)
|
| 270 |
+
Computed values. Shape depends on whether `t` was a scalar or a
|
| 271 |
+
1-D array.
|
| 272 |
+
"""
|
| 273 |
+
t = np.asarray(t)
|
| 274 |
+
if t.ndim > 1:
|
| 275 |
+
raise ValueError("`t` must be a float or a 1-D array.")
|
| 276 |
+
return self._call_impl(t)
|
| 277 |
+
|
| 278 |
+
def _call_impl(self, t):
|
| 279 |
+
raise NotImplementedError
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class ConstantDenseOutput(DenseOutput):
|
| 283 |
+
"""Constant value interpolator.
|
| 284 |
+
|
| 285 |
+
This class used for degenerate integration cases: equal integration limits
|
| 286 |
+
or a system with 0 equations.
|
| 287 |
+
"""
|
| 288 |
+
def __init__(self, t_old, t, value):
|
| 289 |
+
super().__init__(t_old, t)
|
| 290 |
+
self.value = value
|
| 291 |
+
|
| 292 |
+
def _call_impl(self, t):
|
| 293 |
+
if t.ndim == 0:
|
| 294 |
+
return self.value
|
| 295 |
+
else:
|
| 296 |
+
ret = np.empty((self.value.shape[0], t.shape[0]))
|
| 297 |
+
ret[:] = self.value[:, None]
|
| 298 |
+
return ret
|
.venv_haddock/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 198 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 199 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
| 200 |
+
vectorized=False, first_step=None, **extraneous):
|
| 201 |
+
warn_extraneous(extraneous)
|
| 202 |
+
super().__init__(fun, t0, y0, t_bound, vectorized,
|
| 203 |
+
support_complex=True)
|
| 204 |
+
self.max_step = validate_max_step(max_step)
|
| 205 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
| 206 |
+
f = self.fun(self.t, self.y)
|
| 207 |
+
if first_step is None:
|
| 208 |
+
self.h_abs = select_initial_step(self.fun, self.t, self.y,
|
| 209 |
+
t_bound, max_step, f,
|
| 210 |
+
self.direction, 1,
|
| 211 |
+
self.rtol, self.atol)
|
| 212 |
+
else:
|
| 213 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
| 214 |
+
self.h_abs_old = None
|
| 215 |
+
self.error_norm_old = None
|
| 216 |
+
|
| 217 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
| 218 |
+
|
| 219 |
+
self.jac_factor = None
|
| 220 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
| 221 |
+
if issparse(self.J):
|
| 222 |
+
def lu(A):
|
| 223 |
+
self.nlu += 1
|
| 224 |
+
return splu(A)
|
| 225 |
+
|
| 226 |
+
def solve_lu(LU, b):
|
| 227 |
+
return LU.solve(b)
|
| 228 |
+
|
| 229 |
+
I = eye(self.n, format='csc', dtype=self.y.dtype)
|
| 230 |
+
else:
|
| 231 |
+
def lu(A):
|
| 232 |
+
self.nlu += 1
|
| 233 |
+
return lu_factor(A, overwrite_a=True)
|
| 234 |
+
|
| 235 |
+
def solve_lu(LU, b):
|
| 236 |
+
return lu_solve(LU, b, overwrite_b=True)
|
| 237 |
+
|
| 238 |
+
I = np.identity(self.n, dtype=self.y.dtype)
|
| 239 |
+
|
| 240 |
+
self.lu = lu
|
| 241 |
+
self.solve_lu = solve_lu
|
| 242 |
+
self.I = I
|
| 243 |
+
|
| 244 |
+
kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
|
| 245 |
+
self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
|
| 246 |
+
self.alpha = (1 - kappa) * self.gamma
|
| 247 |
+
self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
|
| 248 |
+
|
| 249 |
+
D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
|
| 250 |
+
D[0] = self.y
|
| 251 |
+
D[1] = f * self.h_abs * self.direction
|
| 252 |
+
self.D = D
|
| 253 |
+
|
| 254 |
+
self.order = 1
|
| 255 |
+
self.n_equal_steps = 0
|
| 256 |
+
self.LU = None
|
| 257 |
+
|
| 258 |
+
def _validate_jac(self, jac, sparsity):
|
| 259 |
+
t0 = self.t
|
| 260 |
+
y0 = self.y
|
| 261 |
+
|
| 262 |
+
if jac is None:
|
| 263 |
+
if sparsity is not None:
|
| 264 |
+
if issparse(sparsity):
|
| 265 |
+
sparsity = csc_matrix(sparsity)
|
| 266 |
+
groups = group_columns(sparsity)
|
| 267 |
+
sparsity = (sparsity, groups)
|
| 268 |
+
|
| 269 |
+
def jac_wrapped(t, y):
|
| 270 |
+
self.njev += 1
|
| 271 |
+
f = self.fun_single(t, y)
|
| 272 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
| 273 |
+
self.atol, self.jac_factor,
|
| 274 |
+
sparsity)
|
| 275 |
+
return J
|
| 276 |
+
J = jac_wrapped(t0, y0)
|
| 277 |
+
elif callable(jac):
|
| 278 |
+
J = jac(t0, y0)
|
| 279 |
+
self.njev += 1
|
| 280 |
+
if issparse(J):
|
| 281 |
+
J = csc_matrix(J, dtype=y0.dtype)
|
| 282 |
+
|
| 283 |
+
def jac_wrapped(t, y):
|
| 284 |
+
self.njev += 1
|
| 285 |
+
return csc_matrix(jac(t, y), dtype=y0.dtype)
|
| 286 |
+
else:
|
| 287 |
+
J = np.asarray(J, dtype=y0.dtype)
|
| 288 |
+
|
| 289 |
+
def jac_wrapped(t, y):
|
| 290 |
+
self.njev += 1
|
| 291 |
+
return np.asarray(jac(t, y), dtype=y0.dtype)
|
| 292 |
+
|
| 293 |
+
if J.shape != (self.n, self.n):
|
| 294 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 295 |
+
f" but actually has {J.shape}.")
|
| 296 |
+
else:
|
| 297 |
+
if issparse(jac):
|
| 298 |
+
J = csc_matrix(jac, dtype=y0.dtype)
|
| 299 |
+
else:
|
| 300 |
+
J = np.asarray(jac, dtype=y0.dtype)
|
| 301 |
+
|
| 302 |
+
if J.shape != (self.n, self.n):
|
| 303 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 304 |
+
f" but actually has {J.shape}.")
|
| 305 |
+
jac_wrapped = None
|
| 306 |
+
|
| 307 |
+
return jac_wrapped, J
|
| 308 |
+
|
| 309 |
+
def _step_impl(self):
|
| 310 |
+
t = self.t
|
| 311 |
+
D = self.D
|
| 312 |
+
|
| 313 |
+
max_step = self.max_step
|
| 314 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
| 315 |
+
if self.h_abs > max_step:
|
| 316 |
+
h_abs = max_step
|
| 317 |
+
change_D(D, self.order, max_step / self.h_abs)
|
| 318 |
+
self.n_equal_steps = 0
|
| 319 |
+
elif self.h_abs < min_step:
|
| 320 |
+
h_abs = min_step
|
| 321 |
+
change_D(D, self.order, min_step / self.h_abs)
|
| 322 |
+
self.n_equal_steps = 0
|
| 323 |
+
else:
|
| 324 |
+
h_abs = self.h_abs
|
| 325 |
+
|
| 326 |
+
atol = self.atol
|
| 327 |
+
rtol = self.rtol
|
| 328 |
+
order = self.order
|
| 329 |
+
|
| 330 |
+
alpha = self.alpha
|
| 331 |
+
gamma = self.gamma
|
| 332 |
+
error_const = self.error_const
|
| 333 |
+
|
| 334 |
+
J = self.J
|
| 335 |
+
LU = self.LU
|
| 336 |
+
current_jac = self.jac is None
|
| 337 |
+
|
| 338 |
+
step_accepted = False
|
| 339 |
+
while not step_accepted:
|
| 340 |
+
if h_abs < min_step:
|
| 341 |
+
return False, self.TOO_SMALL_STEP
|
| 342 |
+
|
| 343 |
+
h = h_abs * self.direction
|
| 344 |
+
t_new = t + h
|
| 345 |
+
|
| 346 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
| 347 |
+
t_new = self.t_bound
|
| 348 |
+
change_D(D, order, np.abs(t_new - t) / h_abs)
|
| 349 |
+
self.n_equal_steps = 0
|
| 350 |
+
LU = None
|
| 351 |
+
|
| 352 |
+
h = t_new - t
|
| 353 |
+
h_abs = np.abs(h)
|
| 354 |
+
|
| 355 |
+
y_predict = np.sum(D[:order + 1], axis=0)
|
| 356 |
+
|
| 357 |
+
scale = atol + rtol * np.abs(y_predict)
|
| 358 |
+
psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order]
|
| 359 |
+
|
| 360 |
+
converged = False
|
| 361 |
+
c = h / alpha[order]
|
| 362 |
+
while not converged:
|
| 363 |
+
if LU is None:
|
| 364 |
+
LU = self.lu(self.I - c * J)
|
| 365 |
+
|
| 366 |
+
converged, n_iter, y_new, d = solve_bdf_system(
|
| 367 |
+
self.fun, t_new, y_predict, c, psi, LU, self.solve_lu,
|
| 368 |
+
scale, self.newton_tol)
|
| 369 |
+
|
| 370 |
+
if not converged:
|
| 371 |
+
if current_jac:
|
| 372 |
+
break
|
| 373 |
+
J = self.jac(t_new, y_predict)
|
| 374 |
+
LU = None
|
| 375 |
+
current_jac = True
|
| 376 |
+
|
| 377 |
+
if not converged:
|
| 378 |
+
factor = 0.5
|
| 379 |
+
h_abs *= factor
|
| 380 |
+
change_D(D, order, factor)
|
| 381 |
+
self.n_equal_steps = 0
|
| 382 |
+
LU = None
|
| 383 |
+
continue
|
| 384 |
+
|
| 385 |
+
safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
|
| 386 |
+
+ n_iter)
|
| 387 |
+
|
| 388 |
+
scale = atol + rtol * np.abs(y_new)
|
| 389 |
+
error = error_const[order] * d
|
| 390 |
+
error_norm = norm(error / scale)
|
| 391 |
+
|
| 392 |
+
if error_norm > 1:
|
| 393 |
+
factor = max(MIN_FACTOR,
|
| 394 |
+
safety * error_norm ** (-1 / (order + 1)))
|
| 395 |
+
h_abs *= factor
|
| 396 |
+
change_D(D, order, factor)
|
| 397 |
+
self.n_equal_steps = 0
|
| 398 |
+
# As we didn't have problems with convergence, we don't
|
| 399 |
+
# reset LU here.
|
| 400 |
+
else:
|
| 401 |
+
step_accepted = True
|
| 402 |
+
|
| 403 |
+
self.n_equal_steps += 1
|
| 404 |
+
|
| 405 |
+
self.t = t_new
|
| 406 |
+
self.y = y_new
|
| 407 |
+
|
| 408 |
+
self.h_abs = h_abs
|
| 409 |
+
self.J = J
|
| 410 |
+
self.LU = LU
|
| 411 |
+
|
| 412 |
+
# Update differences. The principal relation here is
|
| 413 |
+
# D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D
|
| 414 |
+
# contained difference for previous interpolating polynomial and
|
| 415 |
+
# d = D^{k + 1} y_n. Thus this elegant code follows.
|
| 416 |
+
D[order + 2] = d - D[order + 1]
|
| 417 |
+
D[order + 1] = d
|
| 418 |
+
for i in reversed(range(order + 1)):
|
| 419 |
+
D[i] += D[i + 1]
|
| 420 |
+
|
| 421 |
+
if self.n_equal_steps < order + 1:
|
| 422 |
+
return True, None
|
| 423 |
+
|
| 424 |
+
if order > 1:
|
| 425 |
+
error_m = error_const[order - 1] * D[order]
|
| 426 |
+
error_m_norm = norm(error_m / scale)
|
| 427 |
+
else:
|
| 428 |
+
error_m_norm = np.inf
|
| 429 |
+
|
| 430 |
+
if order < MAX_ORDER:
|
| 431 |
+
error_p = error_const[order + 1] * D[order + 2]
|
| 432 |
+
error_p_norm = norm(error_p / scale)
|
| 433 |
+
else:
|
| 434 |
+
error_p_norm = np.inf
|
| 435 |
+
|
| 436 |
+
error_norms = np.array([error_m_norm, error_norm, error_p_norm])
|
| 437 |
+
with np.errstate(divide='ignore'):
|
| 438 |
+
factors = error_norms ** (-1 / np.arange(order, order + 3))
|
| 439 |
+
|
| 440 |
+
delta_order = np.argmax(factors) - 1
|
| 441 |
+
order += delta_order
|
| 442 |
+
self.order = order
|
| 443 |
+
|
| 444 |
+
factor = min(MAX_FACTOR, safety * np.max(factors))
|
| 445 |
+
self.h_abs *= factor
|
| 446 |
+
change_D(D, order, factor)
|
| 447 |
+
self.n_equal_steps = 0
|
| 448 |
+
self.LU = None
|
| 449 |
+
|
| 450 |
+
return True, None
|
| 451 |
+
|
| 452 |
+
def _dense_output_impl(self):
|
| 453 |
+
return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction,
|
| 454 |
+
self.order, self.D[:self.order + 1].copy())
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class BdfDenseOutput(DenseOutput):
|
| 458 |
+
def __init__(self, t_old, t, h, order, D):
|
| 459 |
+
super().__init__(t_old, t)
|
| 460 |
+
self.order = order
|
| 461 |
+
self.t_shift = self.t - h * np.arange(self.order)
|
| 462 |
+
self.denom = h * (1 + np.arange(self.order))
|
| 463 |
+
self.D = D
|
| 464 |
+
|
| 465 |
+
def _call_impl(self, t):
|
| 466 |
+
if t.ndim == 0:
|
| 467 |
+
x = (t - self.t_shift) / self.denom
|
| 468 |
+
p = np.cumprod(x)
|
| 469 |
+
else:
|
| 470 |
+
x = (t - self.t_shift[:, None]) / self.denom[:, None]
|
| 471 |
+
p = np.cumprod(x, axis=0)
|
| 472 |
+
|
| 473 |
+
y = np.dot(self.D[1:].T, p)
|
| 474 |
+
if y.ndim == 1:
|
| 475 |
+
y += self.D[0]
|
| 476 |
+
else:
|
| 477 |
+
y += self.D[0, :, None]
|
| 478 |
+
|
| 479 |
+
return y
|