Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py +57 -0
- llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py +35 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__init__.py +110 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py +8 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py +290 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py +479 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py +440 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py +193 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py +748 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py +224 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py +574 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py +601 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py +1135 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py +37 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ode.py +1376 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so +0 -0
- llmeval-env/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py +262 -0
.gitattributes
CHANGED
@@ -185,3 +185,4 @@ env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1500 filter=l
|
|
185 |
env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1500 filter=lfs diff=lfs merge=lfs -text
|
186 |
env-llmeval/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
187 |
env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_flight.so.1500 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
185 |
env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_substrait.so.1500 filter=lfs diff=lfs merge=lfs -text
|
186 |
env-llmeval/lib/python3.10/site-packages/pyarrow/lib.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
187 |
env-llmeval/lib/python3.10/site-packages/pyarrow/libarrow_flight.so.1500 filter=lfs diff=lfs merge=lfs -text
|
188 |
+
llmeval-env/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (12.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc
ADDED
Binary file (154 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc
ADDED
Binary file (8.71 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc
ADDED
Binary file (819 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc
ADDED
Binary file (1.89 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_codata.cpython-310.pyc
ADDED
Binary file (2.27 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/test_constants.cpython-310.pyc
ADDED
Binary file (1.37 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy.constants import find, value, ConstantWarning, c, speed_of_light
|
2 |
+
from numpy.testing import (assert_equal, assert_, assert_almost_equal,
|
3 |
+
suppress_warnings)
|
4 |
+
import scipy.constants._codata as _cd
|
5 |
+
|
6 |
+
|
7 |
+
def test_find():
|
8 |
+
keys = find('weak mixing', disp=False)
|
9 |
+
assert_equal(keys, ['weak mixing angle'])
|
10 |
+
|
11 |
+
keys = find('qwertyuiop', disp=False)
|
12 |
+
assert_equal(keys, [])
|
13 |
+
|
14 |
+
keys = find('natural unit', disp=False)
|
15 |
+
assert_equal(keys, sorted(['natural unit of velocity',
|
16 |
+
'natural unit of action',
|
17 |
+
'natural unit of action in eV s',
|
18 |
+
'natural unit of mass',
|
19 |
+
'natural unit of energy',
|
20 |
+
'natural unit of energy in MeV',
|
21 |
+
'natural unit of momentum',
|
22 |
+
'natural unit of momentum in MeV/c',
|
23 |
+
'natural unit of length',
|
24 |
+
'natural unit of time']))
|
25 |
+
|
26 |
+
|
27 |
+
def test_basic_table_parse():
|
28 |
+
c_s = 'speed of light in vacuum'
|
29 |
+
assert_equal(value(c_s), c)
|
30 |
+
assert_equal(value(c_s), speed_of_light)
|
31 |
+
|
32 |
+
|
33 |
+
def test_basic_lookup():
|
34 |
+
assert_equal('%d %s' % (_cd.c, _cd.unit('speed of light in vacuum')),
|
35 |
+
'299792458 m s^-1')
|
36 |
+
|
37 |
+
|
38 |
+
def test_find_all():
|
39 |
+
assert_(len(find(disp=False)) > 300)
|
40 |
+
|
41 |
+
|
42 |
+
def test_find_single():
|
43 |
+
assert_equal(find('Wien freq', disp=False)[0],
|
44 |
+
'Wien frequency displacement law constant')
|
45 |
+
|
46 |
+
|
47 |
+
def test_2002_vs_2006():
|
48 |
+
assert_almost_equal(value('magn. flux quantum'),
|
49 |
+
value('mag. flux quantum'))
|
50 |
+
|
51 |
+
|
52 |
+
def test_exact_values():
|
53 |
+
# Check that updating stored values with exact ones worked.
|
54 |
+
with suppress_warnings() as sup:
|
55 |
+
sup.filter(ConstantWarning)
|
56 |
+
for key in _cd.exact_values:
|
57 |
+
assert_((_cd.exact_values[key][0] - value(key)) / value(key) == 0)
|
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numpy.testing import assert_equal, assert_allclose
|
2 |
+
import scipy.constants as sc
|
3 |
+
|
4 |
+
|
5 |
+
def test_convert_temperature():
|
6 |
+
assert_equal(sc.convert_temperature(32, 'f', 'Celsius'), 0)
|
7 |
+
assert_equal(sc.convert_temperature([0, 0], 'celsius', 'Kelvin'),
|
8 |
+
[273.15, 273.15])
|
9 |
+
assert_equal(sc.convert_temperature([0, 0], 'kelvin', 'c'),
|
10 |
+
[-273.15, -273.15])
|
11 |
+
assert_equal(sc.convert_temperature([32, 32], 'f', 'k'), [273.15, 273.15])
|
12 |
+
assert_equal(sc.convert_temperature([273.15, 273.15], 'kelvin', 'F'),
|
13 |
+
[32, 32])
|
14 |
+
assert_equal(sc.convert_temperature([0, 0], 'C', 'fahrenheit'), [32, 32])
|
15 |
+
assert_allclose(sc.convert_temperature([0, 0], 'c', 'r'), [491.67, 491.67],
|
16 |
+
rtol=0., atol=1e-13)
|
17 |
+
assert_allclose(sc.convert_temperature([491.67, 491.67], 'Rankine', 'C'),
|
18 |
+
[0., 0.], rtol=0., atol=1e-13)
|
19 |
+
assert_allclose(sc.convert_temperature([491.67, 491.67], 'r', 'F'),
|
20 |
+
[32., 32.], rtol=0., atol=1e-13)
|
21 |
+
assert_allclose(sc.convert_temperature([32, 32], 'fahrenheit', 'R'),
|
22 |
+
[491.67, 491.67], rtol=0., atol=1e-13)
|
23 |
+
assert_allclose(sc.convert_temperature([273.15, 273.15], 'K', 'R'),
|
24 |
+
[491.67, 491.67], rtol=0., atol=1e-13)
|
25 |
+
assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
|
26 |
+
[273.15, 0.], rtol=0., atol=1e-13)
|
27 |
+
|
28 |
+
|
29 |
+
def test_lambda_to_nu():
|
30 |
+
assert_equal(sc.lambda2nu([sc.speed_of_light, 1]), [1, sc.speed_of_light])
|
31 |
+
|
32 |
+
|
33 |
+
def test_nu_to_lambda():
|
34 |
+
assert_equal(sc.nu2lambda([sc.speed_of_light, 1]), [1, sc.speed_of_light])
|
35 |
+
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__init__.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
dblquad -- General purpose double integration
|
17 |
+
tplquad -- General purpose triple integration
|
18 |
+
nquad -- General purpose N-D integration
|
19 |
+
fixed_quad -- Integrate func(x) using Gaussian quadrature of order n
|
20 |
+
quadrature -- Integrate with given tolerance using Gaussian quadrature
|
21 |
+
romberg -- Integrate func using Romberg integration
|
22 |
+
newton_cotes -- Weights and error coefficient for Newton-Cotes integration
|
23 |
+
qmc_quad -- N-D integration using Quasi-Monte Carlo quadrature
|
24 |
+
IntegrationWarning -- Warning on issues during integration
|
25 |
+
AccuracyWarning -- Warning on issues during quadrature integration
|
26 |
+
|
27 |
+
Integrating functions, given fixed samples
|
28 |
+
==========================================
|
29 |
+
|
30 |
+
.. autosummary::
|
31 |
+
:toctree: generated/
|
32 |
+
|
33 |
+
trapezoid -- Use trapezoidal rule to compute integral.
|
34 |
+
cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
|
35 |
+
simpson -- Use Simpson's rule to compute integral from samples.
|
36 |
+
cumulative_simpson -- Use Simpson's rule to cumulatively compute integral from samples.
|
37 |
+
romb -- Use Romberg Integration to compute integral from
|
38 |
+
-- (2**k + 1) evenly-spaced samples.
|
39 |
+
|
40 |
+
.. seealso::
|
41 |
+
|
42 |
+
:mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
|
43 |
+
quadrature roots and weights for other weighting factors and regions.
|
44 |
+
|
45 |
+
Solving initial value problems for ODE systems
|
46 |
+
==============================================
|
47 |
+
|
48 |
+
The solvers are implemented as individual classes, which can be used directly
|
49 |
+
(low-level usage) or through a convenience function.
|
50 |
+
|
51 |
+
.. autosummary::
|
52 |
+
:toctree: generated/
|
53 |
+
|
54 |
+
solve_ivp -- Convenient function for ODE integration.
|
55 |
+
RK23 -- Explicit Runge-Kutta solver of order 3(2).
|
56 |
+
RK45 -- Explicit Runge-Kutta solver of order 5(4).
|
57 |
+
DOP853 -- Explicit Runge-Kutta solver of order 8.
|
58 |
+
Radau -- Implicit Runge-Kutta solver of order 5.
|
59 |
+
BDF -- Implicit multi-step variable order (1 to 5) solver.
|
60 |
+
LSODA -- LSODA solver from ODEPACK Fortran package.
|
61 |
+
OdeSolver -- Base class for ODE solvers.
|
62 |
+
DenseOutput -- Local interpolant for computing a dense output.
|
63 |
+
OdeSolution -- Class which represents a continuous ODE solution.
|
64 |
+
|
65 |
+
|
66 |
+
Old API
|
67 |
+
-------
|
68 |
+
|
69 |
+
These are the routines developed earlier for SciPy. They wrap older solvers
|
70 |
+
implemented in Fortran (mostly ODEPACK). While the interface to them is not
|
71 |
+
particularly convenient and certain features are missing compared to the new
|
72 |
+
API, the solvers themselves are of good quality and work fast as compiled
|
73 |
+
Fortran code. In some cases, it might be worth using this old API.
|
74 |
+
|
75 |
+
.. autosummary::
|
76 |
+
:toctree: generated/
|
77 |
+
|
78 |
+
odeint -- General integration of ordinary differential equations.
|
79 |
+
ode -- Integrate ODE using VODE and ZVODE routines.
|
80 |
+
complex_ode -- Convert a complex-valued ODE to real-valued and integrate.
|
81 |
+
ODEintWarning -- Warning raised during the execution of `odeint`.
|
82 |
+
|
83 |
+
|
84 |
+
Solving boundary value problems for ODE systems
|
85 |
+
===============================================
|
86 |
+
|
87 |
+
.. autosummary::
|
88 |
+
:toctree: generated/
|
89 |
+
|
90 |
+
solve_bvp -- Solve a boundary value problem for a system of ODEs.
|
91 |
+
""" # noqa: E501
|
92 |
+
|
93 |
+
|
94 |
+
from ._quadrature import *
|
95 |
+
from ._odepack_py import *
|
96 |
+
from ._quadpack_py import *
|
97 |
+
from ._ode import *
|
98 |
+
from ._bvp import solve_bvp
|
99 |
+
from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
|
100 |
+
OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
|
101 |
+
from ._quad_vec import quad_vec
|
102 |
+
|
103 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
104 |
+
from . import dop, lsoda, vode, odepack, quadpack
|
105 |
+
|
106 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
107 |
+
|
108 |
+
from scipy._lib._testutils import PytestTester
|
109 |
+
test = PytestTester(__name__)
|
110 |
+
del PytestTester
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc
ADDED
Binary file (35.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc
ADDED
Binary file (38.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc
ADDED
Binary file (10.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc
ADDED
Binary file (15.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc
ADDED
Binary file (49.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc
ADDED
Binary file (35.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc
ADDED
Binary file (601 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc
ADDED
Binary file (630 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc
ADDED
Binary file (670 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc
ADDED
Binary file (613 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (117 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Suite of ODE solvers implemented in Python."""
|
2 |
+
from .ivp import solve_ivp
|
3 |
+
from .rk import RK23, RK45, DOP853
|
4 |
+
from .radau import Radau
|
5 |
+
from .bdf import BDF
|
6 |
+
from .lsoda import LSODA
|
7 |
+
from .common import OdeSolution
|
8 |
+
from .base import DenseOutput, OdeSolver
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (556 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc
ADDED
Binary file (10.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc
ADDED
Binary file (14.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc
ADDED
Binary file (13 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
ADDED
Binary file (4.93 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
ADDED
Binary file (29.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
ADDED
Binary file (8.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc
ADDED
Binary file (22 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
ADDED
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
|
4 |
+
def check_arguments(fun, y0, support_complex):
|
5 |
+
"""Helper function for checking arguments common to all solvers."""
|
6 |
+
y0 = np.asarray(y0)
|
7 |
+
if np.issubdtype(y0.dtype, np.complexfloating):
|
8 |
+
if not support_complex:
|
9 |
+
raise ValueError("`y0` is complex, but the chosen solver does "
|
10 |
+
"not support integration in a complex domain.")
|
11 |
+
dtype = complex
|
12 |
+
else:
|
13 |
+
dtype = float
|
14 |
+
y0 = y0.astype(dtype, copy=False)
|
15 |
+
|
16 |
+
if y0.ndim != 1:
|
17 |
+
raise ValueError("`y0` must be 1-dimensional.")
|
18 |
+
|
19 |
+
if not np.isfinite(y0).all():
|
20 |
+
raise ValueError("All components of the initial state `y0` must be finite.")
|
21 |
+
|
22 |
+
def fun_wrapped(t, y):
|
23 |
+
return np.asarray(fun(t, y), dtype=dtype)
|
24 |
+
|
25 |
+
return fun_wrapped, y0
|
26 |
+
|
27 |
+
|
28 |
+
class OdeSolver:
|
29 |
+
"""Base class for ODE solvers.
|
30 |
+
|
31 |
+
In order to implement a new solver you need to follow the guidelines:
|
32 |
+
|
33 |
+
1. A constructor must accept parameters presented in the base class
|
34 |
+
(listed below) along with any other parameters specific to a solver.
|
35 |
+
2. A constructor must accept arbitrary extraneous arguments
|
36 |
+
``**extraneous``, but warn that these arguments are irrelevant
|
37 |
+
using `common.warn_extraneous` function. Do not pass these
|
38 |
+
arguments to the base class.
|
39 |
+
3. A solver must implement a private method `_step_impl(self)` which
|
40 |
+
propagates a solver one step further. It must return tuple
|
41 |
+
``(success, message)``, where ``success`` is a boolean indicating
|
42 |
+
whether a step was successful, and ``message`` is a string
|
43 |
+
containing description of a failure if a step failed or None
|
44 |
+
otherwise.
|
45 |
+
4. A solver must implement a private method `_dense_output_impl(self)`,
|
46 |
+
which returns a `DenseOutput` object covering the last successful
|
47 |
+
step.
|
48 |
+
5. A solver must have attributes listed below in Attributes section.
|
49 |
+
Note that ``t_old`` and ``step_size`` are updated automatically.
|
50 |
+
6. Use `fun(self, t, y)` method for the system rhs evaluation, this
|
51 |
+
way the number of function evaluations (`nfev`) will be tracked
|
52 |
+
automatically.
|
53 |
+
7. For convenience, a base class provides `fun_single(self, t, y)` and
|
54 |
+
`fun_vectorized(self, t, y)` for evaluating the rhs in
|
55 |
+
non-vectorized and vectorized fashions respectively (regardless of
|
56 |
+
how `fun` from the constructor is implemented). These calls don't
|
57 |
+
increment `nfev`.
|
58 |
+
8. If a solver uses a Jacobian matrix and LU decompositions, it should
|
59 |
+
track the number of Jacobian evaluations (`njev`) and the number of
|
60 |
+
LU decompositions (`nlu`).
|
61 |
+
9. By convention, the function evaluations used to compute a finite
|
62 |
+
difference approximation of the Jacobian should not be counted in
|
63 |
+
`nfev`, thus use `fun_single(self, t, y)` or
|
64 |
+
`fun_vectorized(self, t, y)` when computing a finite difference
|
65 |
+
approximation of the Jacobian.
|
66 |
+
|
67 |
+
Parameters
|
68 |
+
----------
|
69 |
+
fun : callable
|
70 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
71 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
72 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
73 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
74 |
+
information.
|
75 |
+
t0 : float
|
76 |
+
Initial time.
|
77 |
+
y0 : array_like, shape (n,)
|
78 |
+
Initial state.
|
79 |
+
t_bound : float
|
80 |
+
Boundary time --- the integration won't continue beyond it. It also
|
81 |
+
determines the direction of the integration.
|
82 |
+
vectorized : bool
|
83 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
84 |
+
|
85 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
86 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
87 |
+
|
88 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
89 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
90 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
91 |
+
the returned array is the time derivative of the state corresponding
|
92 |
+
with a column of ``y``).
|
93 |
+
|
94 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
95 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
96 |
+
will result in slower execution for other methods. It can also
|
97 |
+
result in slower overall execution for 'Radau' and 'BDF' in some
|
98 |
+
circumstances (e.g. small ``len(y0)``).
|
99 |
+
support_complex : bool, optional
|
100 |
+
Whether integration in a complex domain should be supported.
|
101 |
+
Generally determined by a derived solver class capabilities.
|
102 |
+
Default is False.
|
103 |
+
|
104 |
+
Attributes
|
105 |
+
----------
|
106 |
+
n : int
|
107 |
+
Number of equations.
|
108 |
+
status : string
|
109 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
110 |
+
t_bound : float
|
111 |
+
Boundary time.
|
112 |
+
direction : float
|
113 |
+
Integration direction: +1 or -1.
|
114 |
+
t : float
|
115 |
+
Current time.
|
116 |
+
y : ndarray
|
117 |
+
Current state.
|
118 |
+
t_old : float
|
119 |
+
Previous time. None if no steps were made yet.
|
120 |
+
step_size : float
|
121 |
+
Size of the last successful step. None if no steps were made yet.
|
122 |
+
nfev : int
|
123 |
+
Number of the system's rhs evaluations.
|
124 |
+
njev : int
|
125 |
+
Number of the Jacobian evaluations.
|
126 |
+
nlu : int
|
127 |
+
Number of LU decompositions.
|
128 |
+
"""
|
129 |
+
TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
|
130 |
+
|
131 |
+
def __init__(self, fun, t0, y0, t_bound, vectorized,
|
132 |
+
support_complex=False):
|
133 |
+
self.t_old = None
|
134 |
+
self.t = t0
|
135 |
+
self._fun, self.y = check_arguments(fun, y0, support_complex)
|
136 |
+
self.t_bound = t_bound
|
137 |
+
self.vectorized = vectorized
|
138 |
+
|
139 |
+
if vectorized:
|
140 |
+
def fun_single(t, y):
|
141 |
+
return self._fun(t, y[:, None]).ravel()
|
142 |
+
fun_vectorized = self._fun
|
143 |
+
else:
|
144 |
+
fun_single = self._fun
|
145 |
+
|
146 |
+
def fun_vectorized(t, y):
|
147 |
+
f = np.empty_like(y)
|
148 |
+
for i, yi in enumerate(y.T):
|
149 |
+
f[:, i] = self._fun(t, yi)
|
150 |
+
return f
|
151 |
+
|
152 |
+
def fun(t, y):
|
153 |
+
self.nfev += 1
|
154 |
+
return self.fun_single(t, y)
|
155 |
+
|
156 |
+
self.fun = fun
|
157 |
+
self.fun_single = fun_single
|
158 |
+
self.fun_vectorized = fun_vectorized
|
159 |
+
|
160 |
+
self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
|
161 |
+
self.n = self.y.size
|
162 |
+
self.status = 'running'
|
163 |
+
|
164 |
+
self.nfev = 0
|
165 |
+
self.njev = 0
|
166 |
+
self.nlu = 0
|
167 |
+
|
168 |
+
@property
|
169 |
+
def step_size(self):
|
170 |
+
if self.t_old is None:
|
171 |
+
return None
|
172 |
+
else:
|
173 |
+
return np.abs(self.t - self.t_old)
|
174 |
+
|
175 |
+
def step(self):
|
176 |
+
"""Perform one integration step.
|
177 |
+
|
178 |
+
Returns
|
179 |
+
-------
|
180 |
+
message : string or None
|
181 |
+
Report from the solver. Typically a reason for a failure if
|
182 |
+
`self.status` is 'failed' after the step was taken or None
|
183 |
+
otherwise.
|
184 |
+
"""
|
185 |
+
if self.status != 'running':
|
186 |
+
raise RuntimeError("Attempt to step on a failed or finished "
|
187 |
+
"solver.")
|
188 |
+
|
189 |
+
if self.n == 0 or self.t == self.t_bound:
|
190 |
+
# Handle corner cases of empty solver or no integration.
|
191 |
+
self.t_old = self.t
|
192 |
+
self.t = self.t_bound
|
193 |
+
message = None
|
194 |
+
self.status = 'finished'
|
195 |
+
else:
|
196 |
+
t = self.t
|
197 |
+
success, message = self._step_impl()
|
198 |
+
|
199 |
+
if not success:
|
200 |
+
self.status = 'failed'
|
201 |
+
else:
|
202 |
+
self.t_old = t
|
203 |
+
if self.direction * (self.t - self.t_bound) >= 0:
|
204 |
+
self.status = 'finished'
|
205 |
+
|
206 |
+
return message
|
207 |
+
|
208 |
+
def dense_output(self):
|
209 |
+
"""Compute a local interpolant over the last successful step.
|
210 |
+
|
211 |
+
Returns
|
212 |
+
-------
|
213 |
+
sol : `DenseOutput`
|
214 |
+
Local interpolant over the last successful step.
|
215 |
+
"""
|
216 |
+
if self.t_old is None:
|
217 |
+
raise RuntimeError("Dense output is available after a successful "
|
218 |
+
"step was made.")
|
219 |
+
|
220 |
+
if self.n == 0 or self.t == self.t_old:
|
221 |
+
# Handle corner cases of empty solver and no integration.
|
222 |
+
return ConstantDenseOutput(self.t_old, self.t, self.y)
|
223 |
+
else:
|
224 |
+
return self._dense_output_impl()
|
225 |
+
|
226 |
+
def _step_impl(self):
|
227 |
+
raise NotImplementedError
|
228 |
+
|
229 |
+
def _dense_output_impl(self):
|
230 |
+
raise NotImplementedError
|
231 |
+
|
232 |
+
|
233 |
+
class DenseOutput:
|
234 |
+
"""Base class for local interpolant over step made by an ODE solver.
|
235 |
+
|
236 |
+
It interpolates between `t_min` and `t_max` (see Attributes below).
|
237 |
+
Evaluation outside this interval is not forbidden, but the accuracy is not
|
238 |
+
guaranteed.
|
239 |
+
|
240 |
+
Attributes
|
241 |
+
----------
|
242 |
+
t_min, t_max : float
|
243 |
+
Time range of the interpolation.
|
244 |
+
"""
|
245 |
+
def __init__(self, t_old, t):
|
246 |
+
self.t_old = t_old
|
247 |
+
self.t = t
|
248 |
+
self.t_min = min(t, t_old)
|
249 |
+
self.t_max = max(t, t_old)
|
250 |
+
|
251 |
+
def __call__(self, t):
|
252 |
+
"""Evaluate the interpolant.
|
253 |
+
|
254 |
+
Parameters
|
255 |
+
----------
|
256 |
+
t : float or array_like with shape (n_points,)
|
257 |
+
Points to evaluate the solution at.
|
258 |
+
|
259 |
+
Returns
|
260 |
+
-------
|
261 |
+
y : ndarray, shape (n,) or (n, n_points)
|
262 |
+
Computed values. Shape depends on whether `t` was a scalar or a
|
263 |
+
1-D array.
|
264 |
+
"""
|
265 |
+
t = np.asarray(t)
|
266 |
+
if t.ndim > 1:
|
267 |
+
raise ValueError("`t` must be a float or a 1-D array.")
|
268 |
+
return self._call_impl(t)
|
269 |
+
|
270 |
+
def _call_impl(self, t):
|
271 |
+
raise NotImplementedError
|
272 |
+
|
273 |
+
|
274 |
+
class ConstantDenseOutput(DenseOutput):
|
275 |
+
"""Constant value interpolator.
|
276 |
+
|
277 |
+
This class used for degenerate integration cases: equal integration limits
|
278 |
+
or a system with 0 equations.
|
279 |
+
"""
|
280 |
+
def __init__(self, t_old, t, value):
|
281 |
+
super().__init__(t_old, t)
|
282 |
+
self.value = value
|
283 |
+
|
284 |
+
def _call_impl(self, t):
|
285 |
+
if t.ndim == 0:
|
286 |
+
return self.value
|
287 |
+
else:
|
288 |
+
ret = np.empty((self.value.shape[0], t.shape[0]))
|
289 |
+
ret[:] = self.value[:, None]
|
290 |
+
return ret
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
ADDED
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.linalg import lu_factor, lu_solve
|
3 |
+
from scipy.sparse import issparse, csc_matrix, eye
|
4 |
+
from scipy.sparse.linalg import splu
|
5 |
+
from scipy.optimize._numdiff import group_columns
|
6 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
7 |
+
norm, EPS, num_jac, validate_first_step,
|
8 |
+
warn_extraneous)
|
9 |
+
from .base import OdeSolver, DenseOutput
|
10 |
+
|
11 |
+
|
12 |
+
MAX_ORDER = 5
|
13 |
+
NEWTON_MAXITER = 4
|
14 |
+
MIN_FACTOR = 0.2
|
15 |
+
MAX_FACTOR = 10
|
16 |
+
|
17 |
+
|
18 |
+
def compute_R(order, factor):
|
19 |
+
"""Compute the matrix for changing the differences array."""
|
20 |
+
I = np.arange(1, order + 1)[:, None]
|
21 |
+
J = np.arange(1, order + 1)
|
22 |
+
M = np.zeros((order + 1, order + 1))
|
23 |
+
M[1:, 1:] = (I - 1 - factor * J) / I
|
24 |
+
M[0] = 1
|
25 |
+
return np.cumprod(M, axis=0)
|
26 |
+
|
27 |
+
|
28 |
+
def change_D(D, order, factor):
|
29 |
+
"""Change differences array in-place when step size is changed."""
|
30 |
+
R = compute_R(order, factor)
|
31 |
+
U = compute_R(order, 1)
|
32 |
+
RU = R.dot(U)
|
33 |
+
D[:order + 1] = np.dot(RU.T, D[:order + 1])
|
34 |
+
|
35 |
+
|
36 |
+
def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol):
|
37 |
+
"""Solve the algebraic system resulting from BDF method."""
|
38 |
+
d = 0
|
39 |
+
y = y_predict.copy()
|
40 |
+
dy_norm_old = None
|
41 |
+
converged = False
|
42 |
+
for k in range(NEWTON_MAXITER):
|
43 |
+
f = fun(t_new, y)
|
44 |
+
if not np.all(np.isfinite(f)):
|
45 |
+
break
|
46 |
+
|
47 |
+
dy = solve_lu(LU, c * f - psi - d)
|
48 |
+
dy_norm = norm(dy / scale)
|
49 |
+
|
50 |
+
if dy_norm_old is None:
|
51 |
+
rate = None
|
52 |
+
else:
|
53 |
+
rate = dy_norm / dy_norm_old
|
54 |
+
|
55 |
+
if (rate is not None and (rate >= 1 or
|
56 |
+
rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)):
|
57 |
+
break
|
58 |
+
|
59 |
+
y += dy
|
60 |
+
d += dy
|
61 |
+
|
62 |
+
if (dy_norm == 0 or
|
63 |
+
rate is not None and rate / (1 - rate) * dy_norm < tol):
|
64 |
+
converged = True
|
65 |
+
break
|
66 |
+
|
67 |
+
dy_norm_old = dy_norm
|
68 |
+
|
69 |
+
return converged, k + 1, y, d
|
70 |
+
|
71 |
+
|
72 |
+
class BDF(OdeSolver):
|
73 |
+
"""Implicit method based on backward-differentiation formulas.
|
74 |
+
|
75 |
+
This is a variable order method with the order varying automatically from
|
76 |
+
1 to 5. The general framework of the BDF algorithm is described in [1]_.
|
77 |
+
This class implements a quasi-constant step size as explained in [2]_.
|
78 |
+
The error estimation strategy for the constant-step BDF is derived in [3]_.
|
79 |
+
An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.
|
80 |
+
|
81 |
+
Can be applied in the complex domain.
|
82 |
+
|
83 |
+
Parameters
|
84 |
+
----------
|
85 |
+
fun : callable
|
86 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
87 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
88 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
89 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
90 |
+
information.
|
91 |
+
t0 : float
|
92 |
+
Initial time.
|
93 |
+
y0 : array_like, shape (n,)
|
94 |
+
Initial state.
|
95 |
+
t_bound : float
|
96 |
+
Boundary time - the integration won't continue beyond it. It also
|
97 |
+
determines the direction of the integration.
|
98 |
+
first_step : float or None, optional
|
99 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
100 |
+
should choose.
|
101 |
+
max_step : float, optional
|
102 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
103 |
+
bounded and determined solely by the solver.
|
104 |
+
rtol, atol : float and array_like, optional
|
105 |
+
Relative and absolute tolerances. The solver keeps the local error
|
106 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
107 |
+
relative accuracy (number of correct digits), while `atol` controls
|
108 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
109 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
110 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
111 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
112 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
113 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
114 |
+
than `atol`. If components of y have different scales, it might be
|
115 |
+
beneficial to set different `atol` values for different components by
|
116 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
117 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
118 |
+
jac : {None, array_like, sparse_matrix, callable}, optional
|
119 |
+
Jacobian matrix of the right-hand side of the system with respect to y,
|
120 |
+
required by this method. The Jacobian matrix has shape (n, n) and its
|
121 |
+
element (i, j) is equal to ``d f_i / d y_j``.
|
122 |
+
There are three ways to define the Jacobian:
|
123 |
+
|
124 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
125 |
+
be constant.
|
126 |
+
* If callable, the Jacobian is assumed to depend on both
|
127 |
+
t and y; it will be called as ``jac(t, y)`` as necessary.
|
128 |
+
For the 'Radau' and 'BDF' methods, the return value might be a
|
129 |
+
sparse matrix.
|
130 |
+
* If None (default), the Jacobian will be approximated by
|
131 |
+
finite differences.
|
132 |
+
|
133 |
+
It is generally recommended to provide the Jacobian rather than
|
134 |
+
relying on a finite-difference approximation.
|
135 |
+
jac_sparsity : {None, array_like, sparse matrix}, optional
|
136 |
+
Defines a sparsity structure of the Jacobian matrix for a
|
137 |
+
finite-difference approximation. Its shape must be (n, n). This argument
|
138 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
|
139 |
+
elements in *each* row, providing the sparsity structure will greatly
|
140 |
+
speed up the computations [4]_. A zero entry means that a corresponding
|
141 |
+
element in the Jacobian is always zero. If None (default), the Jacobian
|
142 |
+
is assumed to be dense.
|
143 |
+
vectorized : bool, optional
|
144 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
145 |
+
|
146 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
147 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
148 |
+
|
149 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
150 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
151 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
152 |
+
the returned array is the time derivative of the state corresponding
|
153 |
+
with a column of ``y``).
|
154 |
+
|
155 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
156 |
+
approximation of the Jacobian by this method, but may result in slower
|
157 |
+
execution overall in some circumstances (e.g. small ``len(y0)``).
|
158 |
+
|
159 |
+
Attributes
|
160 |
+
----------
|
161 |
+
n : int
|
162 |
+
Number of equations.
|
163 |
+
status : string
|
164 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
165 |
+
t_bound : float
|
166 |
+
Boundary time.
|
167 |
+
direction : float
|
168 |
+
Integration direction: +1 or -1.
|
169 |
+
t : float
|
170 |
+
Current time.
|
171 |
+
y : ndarray
|
172 |
+
Current state.
|
173 |
+
t_old : float
|
174 |
+
Previous time. None if no steps were made yet.
|
175 |
+
step_size : float
|
176 |
+
Size of the last successful step. None if no steps were made yet.
|
177 |
+
nfev : int
|
178 |
+
Number of evaluations of the right-hand side.
|
179 |
+
njev : int
|
180 |
+
Number of evaluations of the Jacobian.
|
181 |
+
nlu : int
|
182 |
+
Number of LU decompositions.
|
183 |
+
|
184 |
+
References
|
185 |
+
----------
|
186 |
+
.. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
|
187 |
+
Solution of Ordinary Differential Equations", ACM Transactions on
|
188 |
+
Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
|
189 |
+
.. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
|
190 |
+
COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
|
191 |
+
.. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
|
192 |
+
Nonstiff Problems", Sec. III.2.
|
193 |
+
.. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
194 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
195 |
+
and its Applications, 13, pp. 117-120, 1974.
|
196 |
+
"""
|
197 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
198 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
199 |
+
vectorized=False, first_step=None, **extraneous):
|
200 |
+
warn_extraneous(extraneous)
|
201 |
+
super().__init__(fun, t0, y0, t_bound, vectorized,
|
202 |
+
support_complex=True)
|
203 |
+
self.max_step = validate_max_step(max_step)
|
204 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
205 |
+
f = self.fun(self.t, self.y)
|
206 |
+
if first_step is None:
|
207 |
+
self.h_abs = select_initial_step(self.fun, self.t, self.y, f,
|
208 |
+
self.direction, 1,
|
209 |
+
self.rtol, self.atol)
|
210 |
+
else:
|
211 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
212 |
+
self.h_abs_old = None
|
213 |
+
self.error_norm_old = None
|
214 |
+
|
215 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
216 |
+
|
217 |
+
self.jac_factor = None
|
218 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
219 |
+
if issparse(self.J):
|
220 |
+
def lu(A):
|
221 |
+
self.nlu += 1
|
222 |
+
return splu(A)
|
223 |
+
|
224 |
+
def solve_lu(LU, b):
|
225 |
+
return LU.solve(b)
|
226 |
+
|
227 |
+
I = eye(self.n, format='csc', dtype=self.y.dtype)
|
228 |
+
else:
|
229 |
+
def lu(A):
|
230 |
+
self.nlu += 1
|
231 |
+
return lu_factor(A, overwrite_a=True)
|
232 |
+
|
233 |
+
def solve_lu(LU, b):
|
234 |
+
return lu_solve(LU, b, overwrite_b=True)
|
235 |
+
|
236 |
+
I = np.identity(self.n, dtype=self.y.dtype)
|
237 |
+
|
238 |
+
self.lu = lu
|
239 |
+
self.solve_lu = solve_lu
|
240 |
+
self.I = I
|
241 |
+
|
242 |
+
kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
|
243 |
+
self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
|
244 |
+
self.alpha = (1 - kappa) * self.gamma
|
245 |
+
self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
|
246 |
+
|
247 |
+
D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
|
248 |
+
D[0] = self.y
|
249 |
+
D[1] = f * self.h_abs * self.direction
|
250 |
+
self.D = D
|
251 |
+
|
252 |
+
self.order = 1
|
253 |
+
self.n_equal_steps = 0
|
254 |
+
self.LU = None
|
255 |
+
|
256 |
+
def _validate_jac(self, jac, sparsity):
|
257 |
+
t0 = self.t
|
258 |
+
y0 = self.y
|
259 |
+
|
260 |
+
if jac is None:
|
261 |
+
if sparsity is not None:
|
262 |
+
if issparse(sparsity):
|
263 |
+
sparsity = csc_matrix(sparsity)
|
264 |
+
groups = group_columns(sparsity)
|
265 |
+
sparsity = (sparsity, groups)
|
266 |
+
|
267 |
+
def jac_wrapped(t, y):
|
268 |
+
self.njev += 1
|
269 |
+
f = self.fun_single(t, y)
|
270 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
271 |
+
self.atol, self.jac_factor,
|
272 |
+
sparsity)
|
273 |
+
return J
|
274 |
+
J = jac_wrapped(t0, y0)
|
275 |
+
elif callable(jac):
|
276 |
+
J = jac(t0, y0)
|
277 |
+
self.njev += 1
|
278 |
+
if issparse(J):
|
279 |
+
J = csc_matrix(J, dtype=y0.dtype)
|
280 |
+
|
281 |
+
def jac_wrapped(t, y):
|
282 |
+
self.njev += 1
|
283 |
+
return csc_matrix(jac(t, y), dtype=y0.dtype)
|
284 |
+
else:
|
285 |
+
J = np.asarray(J, dtype=y0.dtype)
|
286 |
+
|
287 |
+
def jac_wrapped(t, y):
|
288 |
+
self.njev += 1
|
289 |
+
return np.asarray(jac(t, y), dtype=y0.dtype)
|
290 |
+
|
291 |
+
if J.shape != (self.n, self.n):
|
292 |
+
raise ValueError("`jac` is expected to have shape {}, but "
|
293 |
+
"actually has {}."
|
294 |
+
.format((self.n, self.n), J.shape))
|
295 |
+
else:
|
296 |
+
if issparse(jac):
|
297 |
+
J = csc_matrix(jac, dtype=y0.dtype)
|
298 |
+
else:
|
299 |
+
J = np.asarray(jac, dtype=y0.dtype)
|
300 |
+
|
301 |
+
if J.shape != (self.n, self.n):
|
302 |
+
raise ValueError("`jac` is expected to have shape {}, but "
|
303 |
+
"actually has {}."
|
304 |
+
.format((self.n, self.n), 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
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
ADDED
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import groupby
|
2 |
+
from warnings import warn
|
3 |
+
import numpy as np
|
4 |
+
from scipy.sparse import find, coo_matrix
|
5 |
+
|
6 |
+
|
7 |
+
EPS = np.finfo(float).eps
|
8 |
+
|
9 |
+
|
10 |
+
def validate_first_step(first_step, t0, t_bound):
|
11 |
+
"""Assert that first_step is valid and return it."""
|
12 |
+
if first_step <= 0:
|
13 |
+
raise ValueError("`first_step` must be positive.")
|
14 |
+
if first_step > np.abs(t_bound - t0):
|
15 |
+
raise ValueError("`first_step` exceeds bounds.")
|
16 |
+
return first_step
|
17 |
+
|
18 |
+
|
19 |
+
def validate_max_step(max_step):
|
20 |
+
"""Assert that max_Step is valid and return it."""
|
21 |
+
if max_step <= 0:
|
22 |
+
raise ValueError("`max_step` must be positive.")
|
23 |
+
return max_step
|
24 |
+
|
25 |
+
|
26 |
+
def warn_extraneous(extraneous):
|
27 |
+
"""Display a warning for extraneous keyword arguments.
|
28 |
+
|
29 |
+
The initializer of each solver class is expected to collect keyword
|
30 |
+
arguments that it doesn't understand and warn about them. This function
|
31 |
+
prints a warning for each key in the supplied dictionary.
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
extraneous : dict
|
36 |
+
Extraneous keyword arguments
|
37 |
+
"""
|
38 |
+
if extraneous:
|
39 |
+
warn("The following arguments have no effect for a chosen solver: {}."
|
40 |
+
.format(", ".join(f"`{x}`" for x in extraneous)),
|
41 |
+
stacklevel=3)
|
42 |
+
|
43 |
+
|
44 |
+
def validate_tol(rtol, atol, n):
|
45 |
+
"""Validate tolerance values."""
|
46 |
+
|
47 |
+
if np.any(rtol < 100 * EPS):
|
48 |
+
warn("At least one element of `rtol` is too small. "
|
49 |
+
f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.",
|
50 |
+
stacklevel=3)
|
51 |
+
rtol = np.maximum(rtol, 100 * EPS)
|
52 |
+
|
53 |
+
atol = np.asarray(atol)
|
54 |
+
if atol.ndim > 0 and atol.shape != (n,):
|
55 |
+
raise ValueError("`atol` has wrong shape.")
|
56 |
+
|
57 |
+
if np.any(atol < 0):
|
58 |
+
raise ValueError("`atol` must be positive.")
|
59 |
+
|
60 |
+
return rtol, atol
|
61 |
+
|
62 |
+
|
63 |
+
def norm(x):
|
64 |
+
"""Compute RMS norm."""
|
65 |
+
return np.linalg.norm(x) / x.size ** 0.5
|
66 |
+
|
67 |
+
|
68 |
+
def select_initial_step(fun, t0, y0, f0, direction, order, rtol, atol):
|
69 |
+
"""Empirically select a good initial step.
|
70 |
+
|
71 |
+
The algorithm is described in [1]_.
|
72 |
+
|
73 |
+
Parameters
|
74 |
+
----------
|
75 |
+
fun : callable
|
76 |
+
Right-hand side of the system.
|
77 |
+
t0 : float
|
78 |
+
Initial value of the independent variable.
|
79 |
+
y0 : ndarray, shape (n,)
|
80 |
+
Initial value of the dependent variable.
|
81 |
+
f0 : ndarray, shape (n,)
|
82 |
+
Initial value of the derivative, i.e., ``fun(t0, y0)``.
|
83 |
+
direction : float
|
84 |
+
Integration direction.
|
85 |
+
order : float
|
86 |
+
Error estimator order. It means that the error controlled by the
|
87 |
+
algorithm is proportional to ``step_size ** (order + 1)`.
|
88 |
+
rtol : float
|
89 |
+
Desired relative tolerance.
|
90 |
+
atol : float
|
91 |
+
Desired absolute tolerance.
|
92 |
+
|
93 |
+
Returns
|
94 |
+
-------
|
95 |
+
h_abs : float
|
96 |
+
Absolute value of the suggested initial step.
|
97 |
+
|
98 |
+
References
|
99 |
+
----------
|
100 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
101 |
+
Equations I: Nonstiff Problems", Sec. II.4.
|
102 |
+
"""
|
103 |
+
if y0.size == 0:
|
104 |
+
return np.inf
|
105 |
+
|
106 |
+
scale = atol + np.abs(y0) * rtol
|
107 |
+
d0 = norm(y0 / scale)
|
108 |
+
d1 = norm(f0 / scale)
|
109 |
+
if d0 < 1e-5 or d1 < 1e-5:
|
110 |
+
h0 = 1e-6
|
111 |
+
else:
|
112 |
+
h0 = 0.01 * d0 / d1
|
113 |
+
|
114 |
+
y1 = y0 + h0 * direction * f0
|
115 |
+
f1 = fun(t0 + h0 * direction, y1)
|
116 |
+
d2 = norm((f1 - f0) / scale) / h0
|
117 |
+
|
118 |
+
if d1 <= 1e-15 and d2 <= 1e-15:
|
119 |
+
h1 = max(1e-6, h0 * 1e-3)
|
120 |
+
else:
|
121 |
+
h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1))
|
122 |
+
|
123 |
+
return min(100 * h0, h1)
|
124 |
+
|
125 |
+
|
126 |
+
class OdeSolution:
|
127 |
+
"""Continuous ODE solution.
|
128 |
+
|
129 |
+
It is organized as a collection of `DenseOutput` objects which represent
|
130 |
+
local interpolants. It provides an algorithm to select a right interpolant
|
131 |
+
for each given point.
|
132 |
+
|
133 |
+
The interpolants cover the range between `t_min` and `t_max` (see
|
134 |
+
Attributes below). Evaluation outside this interval is not forbidden, but
|
135 |
+
the accuracy is not guaranteed.
|
136 |
+
|
137 |
+
When evaluating at a breakpoint (one of the values in `ts`) a segment with
|
138 |
+
the lower index is selected.
|
139 |
+
|
140 |
+
Parameters
|
141 |
+
----------
|
142 |
+
ts : array_like, shape (n_segments + 1,)
|
143 |
+
Time instants between which local interpolants are defined. Must
|
144 |
+
be strictly increasing or decreasing (zero segment with two points is
|
145 |
+
also allowed).
|
146 |
+
interpolants : list of DenseOutput with n_segments elements
|
147 |
+
Local interpolants. An i-th interpolant is assumed to be defined
|
148 |
+
between ``ts[i]`` and ``ts[i + 1]``.
|
149 |
+
alt_segment : boolean
|
150 |
+
Requests the alternative interpolant segment selection scheme. At each
|
151 |
+
solver integration point, two interpolant segments are available. The
|
152 |
+
default (False) and alternative (True) behaviours select the segment
|
153 |
+
for which the requested time corresponded to ``t`` and ``t_old``,
|
154 |
+
respectively. This functionality is only relevant for testing the
|
155 |
+
interpolants' accuracy: different integrators use different
|
156 |
+
construction strategies.
|
157 |
+
|
158 |
+
Attributes
|
159 |
+
----------
|
160 |
+
t_min, t_max : float
|
161 |
+
Time range of the interpolation.
|
162 |
+
"""
|
163 |
+
def __init__(self, ts, interpolants, alt_segment=False):
|
164 |
+
ts = np.asarray(ts)
|
165 |
+
d = np.diff(ts)
|
166 |
+
# The first case covers integration on zero segment.
|
167 |
+
if not ((ts.size == 2 and ts[0] == ts[-1])
|
168 |
+
or np.all(d > 0) or np.all(d < 0)):
|
169 |
+
raise ValueError("`ts` must be strictly increasing or decreasing.")
|
170 |
+
|
171 |
+
self.n_segments = len(interpolants)
|
172 |
+
if ts.shape != (self.n_segments + 1,):
|
173 |
+
raise ValueError("Numbers of time stamps and interpolants "
|
174 |
+
"don't match.")
|
175 |
+
|
176 |
+
self.ts = ts
|
177 |
+
self.interpolants = interpolants
|
178 |
+
if ts[-1] >= ts[0]:
|
179 |
+
self.t_min = ts[0]
|
180 |
+
self.t_max = ts[-1]
|
181 |
+
self.ascending = True
|
182 |
+
self.side = "right" if alt_segment else "left"
|
183 |
+
self.ts_sorted = ts
|
184 |
+
else:
|
185 |
+
self.t_min = ts[-1]
|
186 |
+
self.t_max = ts[0]
|
187 |
+
self.ascending = False
|
188 |
+
self.side = "left" if alt_segment else "right"
|
189 |
+
self.ts_sorted = ts[::-1]
|
190 |
+
|
191 |
+
def _call_single(self, t):
|
192 |
+
# Here we preserve a certain symmetry that when t is in self.ts,
|
193 |
+
# if alt_segment=False, then we prioritize a segment with a lower
|
194 |
+
# index.
|
195 |
+
ind = np.searchsorted(self.ts_sorted, t, side=self.side)
|
196 |
+
|
197 |
+
segment = min(max(ind - 1, 0), self.n_segments - 1)
|
198 |
+
if not self.ascending:
|
199 |
+
segment = self.n_segments - 1 - segment
|
200 |
+
|
201 |
+
return self.interpolants[segment](t)
|
202 |
+
|
203 |
+
def __call__(self, t):
|
204 |
+
"""Evaluate the solution.
|
205 |
+
|
206 |
+
Parameters
|
207 |
+
----------
|
208 |
+
t : float or array_like with shape (n_points,)
|
209 |
+
Points to evaluate at.
|
210 |
+
|
211 |
+
Returns
|
212 |
+
-------
|
213 |
+
y : ndarray, shape (n_states,) or (n_states, n_points)
|
214 |
+
Computed values. Shape depends on whether `t` is a scalar or a
|
215 |
+
1-D array.
|
216 |
+
"""
|
217 |
+
t = np.asarray(t)
|
218 |
+
|
219 |
+
if t.ndim == 0:
|
220 |
+
return self._call_single(t)
|
221 |
+
|
222 |
+
order = np.argsort(t)
|
223 |
+
reverse = np.empty_like(order)
|
224 |
+
reverse[order] = np.arange(order.shape[0])
|
225 |
+
t_sorted = t[order]
|
226 |
+
|
227 |
+
# See comment in self._call_single.
|
228 |
+
segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side)
|
229 |
+
segments -= 1
|
230 |
+
segments[segments < 0] = 0
|
231 |
+
segments[segments > self.n_segments - 1] = self.n_segments - 1
|
232 |
+
if not self.ascending:
|
233 |
+
segments = self.n_segments - 1 - segments
|
234 |
+
|
235 |
+
ys = []
|
236 |
+
group_start = 0
|
237 |
+
for segment, group in groupby(segments):
|
238 |
+
group_end = group_start + len(list(group))
|
239 |
+
y = self.interpolants[segment](t_sorted[group_start:group_end])
|
240 |
+
ys.append(y)
|
241 |
+
group_start = group_end
|
242 |
+
|
243 |
+
ys = np.hstack(ys)
|
244 |
+
ys = ys[:, reverse]
|
245 |
+
|
246 |
+
return ys
|
247 |
+
|
248 |
+
|
249 |
+
NUM_JAC_DIFF_REJECT = EPS ** 0.875
|
250 |
+
NUM_JAC_DIFF_SMALL = EPS ** 0.75
|
251 |
+
NUM_JAC_DIFF_BIG = EPS ** 0.25
|
252 |
+
NUM_JAC_MIN_FACTOR = 1e3 * EPS
|
253 |
+
NUM_JAC_FACTOR_INCREASE = 10
|
254 |
+
NUM_JAC_FACTOR_DECREASE = 0.1
|
255 |
+
|
256 |
+
|
257 |
+
def num_jac(fun, t, y, f, threshold, factor, sparsity=None):
|
258 |
+
"""Finite differences Jacobian approximation tailored for ODE solvers.
|
259 |
+
|
260 |
+
This function computes finite difference approximation to the Jacobian
|
261 |
+
matrix of `fun` with respect to `y` using forward differences.
|
262 |
+
The Jacobian matrix has shape (n, n) and its element (i, j) is equal to
|
263 |
+
``d f_i / d y_j``.
|
264 |
+
|
265 |
+
A special feature of this function is the ability to correct the step
|
266 |
+
size from iteration to iteration. The main idea is to keep the finite
|
267 |
+
difference significantly separated from its round-off error which
|
268 |
+
approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a
|
269 |
+
huge error and assures that the estimated derivative are reasonably close
|
270 |
+
to the true values (i.e., the finite difference approximation is at least
|
271 |
+
qualitatively reflects the structure of the true Jacobian).
|
272 |
+
|
273 |
+
Parameters
|
274 |
+
----------
|
275 |
+
fun : callable
|
276 |
+
Right-hand side of the system implemented in a vectorized fashion.
|
277 |
+
t : float
|
278 |
+
Current time.
|
279 |
+
y : ndarray, shape (n,)
|
280 |
+
Current state.
|
281 |
+
f : ndarray, shape (n,)
|
282 |
+
Value of the right hand side at (t, y).
|
283 |
+
threshold : float
|
284 |
+
Threshold for `y` value used for computing the step size as
|
285 |
+
``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of
|
286 |
+
absolute tolerance (atol) for a solver should be passed as `threshold`.
|
287 |
+
factor : ndarray with shape (n,) or None
|
288 |
+
Factor to use for computing the step size. Pass None for the very
|
289 |
+
evaluation, then use the value returned from this function.
|
290 |
+
sparsity : tuple (structure, groups) or None
|
291 |
+
Sparsity structure of the Jacobian, `structure` must be csc_matrix.
|
292 |
+
|
293 |
+
Returns
|
294 |
+
-------
|
295 |
+
J : ndarray or csc_matrix, shape (n, n)
|
296 |
+
Jacobian matrix.
|
297 |
+
factor : ndarray, shape (n,)
|
298 |
+
Suggested `factor` for the next evaluation.
|
299 |
+
"""
|
300 |
+
y = np.asarray(y)
|
301 |
+
n = y.shape[0]
|
302 |
+
if n == 0:
|
303 |
+
return np.empty((0, 0)), factor
|
304 |
+
|
305 |
+
if factor is None:
|
306 |
+
factor = np.full(n, EPS ** 0.5)
|
307 |
+
else:
|
308 |
+
factor = factor.copy()
|
309 |
+
|
310 |
+
# Direct the step as ODE dictates, hoping that such a step won't lead to
|
311 |
+
# a problematic region. For complex ODEs it makes sense to use the real
|
312 |
+
# part of f as we use steps along real axis.
|
313 |
+
f_sign = 2 * (np.real(f) >= 0).astype(float) - 1
|
314 |
+
y_scale = f_sign * np.maximum(threshold, np.abs(y))
|
315 |
+
h = (y + factor * y_scale) - y
|
316 |
+
|
317 |
+
# Make sure that the step is not 0 to start with. Not likely it will be
|
318 |
+
# executed often.
|
319 |
+
for i in np.nonzero(h == 0)[0]:
|
320 |
+
while h[i] == 0:
|
321 |
+
factor[i] *= 10
|
322 |
+
h[i] = (y[i] + factor[i] * y_scale[i]) - y[i]
|
323 |
+
|
324 |
+
if sparsity is None:
|
325 |
+
return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
|
326 |
+
else:
|
327 |
+
structure, groups = sparsity
|
328 |
+
return _sparse_num_jac(fun, t, y, f, h, factor, y_scale,
|
329 |
+
structure, groups)
|
330 |
+
|
331 |
+
|
332 |
+
def _dense_num_jac(fun, t, y, f, h, factor, y_scale):
|
333 |
+
n = y.shape[0]
|
334 |
+
h_vecs = np.diag(h)
|
335 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
336 |
+
diff = f_new - f[:, None]
|
337 |
+
max_ind = np.argmax(np.abs(diff), axis=0)
|
338 |
+
r = np.arange(n)
|
339 |
+
max_diff = np.abs(diff[max_ind, r])
|
340 |
+
scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
|
341 |
+
|
342 |
+
diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
|
343 |
+
if np.any(diff_too_small):
|
344 |
+
ind, = np.nonzero(diff_too_small)
|
345 |
+
new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
|
346 |
+
h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
|
347 |
+
h_vecs[ind, ind] = h_new
|
348 |
+
f_new = fun(t, y[:, None] + h_vecs[:, ind])
|
349 |
+
diff_new = f_new - f[:, None]
|
350 |
+
max_ind = np.argmax(np.abs(diff_new), axis=0)
|
351 |
+
r = np.arange(ind.shape[0])
|
352 |
+
max_diff_new = np.abs(diff_new[max_ind, r])
|
353 |
+
scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
|
354 |
+
|
355 |
+
update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
|
356 |
+
if np.any(update):
|
357 |
+
update, = np.nonzero(update)
|
358 |
+
update_ind = ind[update]
|
359 |
+
factor[update_ind] = new_factor[update]
|
360 |
+
h[update_ind] = h_new[update]
|
361 |
+
diff[:, update_ind] = diff_new[:, update]
|
362 |
+
scale[update_ind] = scale_new[update]
|
363 |
+
max_diff[update_ind] = max_diff_new[update]
|
364 |
+
|
365 |
+
diff /= h
|
366 |
+
|
367 |
+
factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
|
368 |
+
factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
|
369 |
+
factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
|
370 |
+
|
371 |
+
return diff, factor
|
372 |
+
|
373 |
+
|
374 |
+
def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups):
|
375 |
+
n = y.shape[0]
|
376 |
+
n_groups = np.max(groups) + 1
|
377 |
+
h_vecs = np.empty((n_groups, n))
|
378 |
+
for group in range(n_groups):
|
379 |
+
e = np.equal(group, groups)
|
380 |
+
h_vecs[group] = h * e
|
381 |
+
h_vecs = h_vecs.T
|
382 |
+
|
383 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
384 |
+
df = f_new - f[:, None]
|
385 |
+
|
386 |
+
i, j, _ = find(structure)
|
387 |
+
diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc()
|
388 |
+
max_ind = np.array(abs(diff).argmax(axis=0)).ravel()
|
389 |
+
r = np.arange(n)
|
390 |
+
max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel()
|
391 |
+
scale = np.maximum(np.abs(f[max_ind]),
|
392 |
+
np.abs(f_new[max_ind, groups[r]]))
|
393 |
+
|
394 |
+
diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
|
395 |
+
if np.any(diff_too_small):
|
396 |
+
ind, = np.nonzero(diff_too_small)
|
397 |
+
new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
|
398 |
+
h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
|
399 |
+
h_new_all = np.zeros(n)
|
400 |
+
h_new_all[ind] = h_new
|
401 |
+
|
402 |
+
groups_unique = np.unique(groups[ind])
|
403 |
+
groups_map = np.empty(n_groups, dtype=int)
|
404 |
+
h_vecs = np.empty((groups_unique.shape[0], n))
|
405 |
+
for k, group in enumerate(groups_unique):
|
406 |
+
e = np.equal(group, groups)
|
407 |
+
h_vecs[k] = h_new_all * e
|
408 |
+
groups_map[group] = k
|
409 |
+
h_vecs = h_vecs.T
|
410 |
+
|
411 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
412 |
+
df = f_new - f[:, None]
|
413 |
+
i, j, _ = find(structure[:, ind])
|
414 |
+
diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]],
|
415 |
+
(i, j)), shape=(n, ind.shape[0])).tocsc()
|
416 |
+
|
417 |
+
max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel()
|
418 |
+
r = np.arange(ind.shape[0])
|
419 |
+
max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel()
|
420 |
+
scale_new = np.maximum(
|
421 |
+
np.abs(f[max_ind_new]),
|
422 |
+
np.abs(f_new[max_ind_new, groups_map[groups[ind]]]))
|
423 |
+
|
424 |
+
update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
|
425 |
+
if np.any(update):
|
426 |
+
update, = np.nonzero(update)
|
427 |
+
update_ind = ind[update]
|
428 |
+
factor[update_ind] = new_factor[update]
|
429 |
+
h[update_ind] = h_new[update]
|
430 |
+
diff[:, update_ind] = diff_new[:, update]
|
431 |
+
scale[update_ind] = scale_new[update]
|
432 |
+
max_diff[update_ind] = max_diff_new[update]
|
433 |
+
|
434 |
+
diff.data /= np.repeat(h, np.diff(diff.indptr))
|
435 |
+
|
436 |
+
factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
|
437 |
+
factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
|
438 |
+
factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
|
439 |
+
|
440 |
+
return diff, factor
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
N_STAGES = 12
|
4 |
+
N_STAGES_EXTENDED = 16
|
5 |
+
INTERPOLATOR_POWER = 7
|
6 |
+
|
7 |
+
C = np.array([0.0,
|
8 |
+
0.526001519587677318785587544488e-01,
|
9 |
+
0.789002279381515978178381316732e-01,
|
10 |
+
0.118350341907227396726757197510,
|
11 |
+
0.281649658092772603273242802490,
|
12 |
+
0.333333333333333333333333333333,
|
13 |
+
0.25,
|
14 |
+
0.307692307692307692307692307692,
|
15 |
+
0.651282051282051282051282051282,
|
16 |
+
0.6,
|
17 |
+
0.857142857142857142857142857142,
|
18 |
+
1.0,
|
19 |
+
1.0,
|
20 |
+
0.1,
|
21 |
+
0.2,
|
22 |
+
0.777777777777777777777777777778])
|
23 |
+
|
24 |
+
A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED))
|
25 |
+
A[1, 0] = 5.26001519587677318785587544488e-2
|
26 |
+
|
27 |
+
A[2, 0] = 1.97250569845378994544595329183e-2
|
28 |
+
A[2, 1] = 5.91751709536136983633785987549e-2
|
29 |
+
|
30 |
+
A[3, 0] = 2.95875854768068491816892993775e-2
|
31 |
+
A[3, 2] = 8.87627564304205475450678981324e-2
|
32 |
+
|
33 |
+
A[4, 0] = 2.41365134159266685502369798665e-1
|
34 |
+
A[4, 2] = -8.84549479328286085344864962717e-1
|
35 |
+
A[4, 3] = 9.24834003261792003115737966543e-1
|
36 |
+
|
37 |
+
A[5, 0] = 3.7037037037037037037037037037e-2
|
38 |
+
A[5, 3] = 1.70828608729473871279604482173e-1
|
39 |
+
A[5, 4] = 1.25467687566822425016691814123e-1
|
40 |
+
|
41 |
+
A[6, 0] = 3.7109375e-2
|
42 |
+
A[6, 3] = 1.70252211019544039314978060272e-1
|
43 |
+
A[6, 4] = 6.02165389804559606850219397283e-2
|
44 |
+
A[6, 5] = -1.7578125e-2
|
45 |
+
|
46 |
+
A[7, 0] = 3.70920001185047927108779319836e-2
|
47 |
+
A[7, 3] = 1.70383925712239993810214054705e-1
|
48 |
+
A[7, 4] = 1.07262030446373284651809199168e-1
|
49 |
+
A[7, 5] = -1.53194377486244017527936158236e-2
|
50 |
+
A[7, 6] = 8.27378916381402288758473766002e-3
|
51 |
+
|
52 |
+
A[8, 0] = 6.24110958716075717114429577812e-1
|
53 |
+
A[8, 3] = -3.36089262944694129406857109825
|
54 |
+
A[8, 4] = -8.68219346841726006818189891453e-1
|
55 |
+
A[8, 5] = 2.75920996994467083049415600797e1
|
56 |
+
A[8, 6] = 2.01540675504778934086186788979e1
|
57 |
+
A[8, 7] = -4.34898841810699588477366255144e1
|
58 |
+
|
59 |
+
A[9, 0] = 4.77662536438264365890433908527e-1
|
60 |
+
A[9, 3] = -2.48811461997166764192642586468
|
61 |
+
A[9, 4] = -5.90290826836842996371446475743e-1
|
62 |
+
A[9, 5] = 2.12300514481811942347288949897e1
|
63 |
+
A[9, 6] = 1.52792336328824235832596922938e1
|
64 |
+
A[9, 7] = -3.32882109689848629194453265587e1
|
65 |
+
A[9, 8] = -2.03312017085086261358222928593e-2
|
66 |
+
|
67 |
+
A[10, 0] = -9.3714243008598732571704021658e-1
|
68 |
+
A[10, 3] = 5.18637242884406370830023853209
|
69 |
+
A[10, 4] = 1.09143734899672957818500254654
|
70 |
+
A[10, 5] = -8.14978701074692612513997267357
|
71 |
+
A[10, 6] = -1.85200656599969598641566180701e1
|
72 |
+
A[10, 7] = 2.27394870993505042818970056734e1
|
73 |
+
A[10, 8] = 2.49360555267965238987089396762
|
74 |
+
A[10, 9] = -3.0467644718982195003823669022
|
75 |
+
|
76 |
+
A[11, 0] = 2.27331014751653820792359768449
|
77 |
+
A[11, 3] = -1.05344954667372501984066689879e1
|
78 |
+
A[11, 4] = -2.00087205822486249909675718444
|
79 |
+
A[11, 5] = -1.79589318631187989172765950534e1
|
80 |
+
A[11, 6] = 2.79488845294199600508499808837e1
|
81 |
+
A[11, 7] = -2.85899827713502369474065508674
|
82 |
+
A[11, 8] = -8.87285693353062954433549289258
|
83 |
+
A[11, 9] = 1.23605671757943030647266201528e1
|
84 |
+
A[11, 10] = 6.43392746015763530355970484046e-1
|
85 |
+
|
86 |
+
A[12, 0] = 5.42937341165687622380535766363e-2
|
87 |
+
A[12, 5] = 4.45031289275240888144113950566
|
88 |
+
A[12, 6] = 1.89151789931450038304281599044
|
89 |
+
A[12, 7] = -5.8012039600105847814672114227
|
90 |
+
A[12, 8] = 3.1116436695781989440891606237e-1
|
91 |
+
A[12, 9] = -1.52160949662516078556178806805e-1
|
92 |
+
A[12, 10] = 2.01365400804030348374776537501e-1
|
93 |
+
A[12, 11] = 4.47106157277725905176885569043e-2
|
94 |
+
|
95 |
+
A[13, 0] = 5.61675022830479523392909219681e-2
|
96 |
+
A[13, 6] = 2.53500210216624811088794765333e-1
|
97 |
+
A[13, 7] = -2.46239037470802489917441475441e-1
|
98 |
+
A[13, 8] = -1.24191423263816360469010140626e-1
|
99 |
+
A[13, 9] = 1.5329179827876569731206322685e-1
|
100 |
+
A[13, 10] = 8.20105229563468988491666602057e-3
|
101 |
+
A[13, 11] = 7.56789766054569976138603589584e-3
|
102 |
+
A[13, 12] = -8.298e-3
|
103 |
+
|
104 |
+
A[14, 0] = 3.18346481635021405060768473261e-2
|
105 |
+
A[14, 5] = 2.83009096723667755288322961402e-2
|
106 |
+
A[14, 6] = 5.35419883074385676223797384372e-2
|
107 |
+
A[14, 7] = -5.49237485713909884646569340306e-2
|
108 |
+
A[14, 10] = -1.08347328697249322858509316994e-4
|
109 |
+
A[14, 11] = 3.82571090835658412954920192323e-4
|
110 |
+
A[14, 12] = -3.40465008687404560802977114492e-4
|
111 |
+
A[14, 13] = 1.41312443674632500278074618366e-1
|
112 |
+
|
113 |
+
A[15, 0] = -4.28896301583791923408573538692e-1
|
114 |
+
A[15, 5] = -4.69762141536116384314449447206
|
115 |
+
A[15, 6] = 7.68342119606259904184240953878
|
116 |
+
A[15, 7] = 4.06898981839711007970213554331
|
117 |
+
A[15, 8] = 3.56727187455281109270669543021e-1
|
118 |
+
A[15, 12] = -1.39902416515901462129418009734e-3
|
119 |
+
A[15, 13] = 2.9475147891527723389556272149
|
120 |
+
A[15, 14] = -9.15095847217987001081870187138
|
121 |
+
|
122 |
+
|
123 |
+
B = A[N_STAGES, :N_STAGES]
|
124 |
+
|
125 |
+
E3 = np.zeros(N_STAGES + 1)
|
126 |
+
E3[:-1] = B.copy()
|
127 |
+
E3[0] -= 0.244094488188976377952755905512
|
128 |
+
E3[8] -= 0.733846688281611857341361741547
|
129 |
+
E3[11] -= 0.220588235294117647058823529412e-1
|
130 |
+
|
131 |
+
E5 = np.zeros(N_STAGES + 1)
|
132 |
+
E5[0] = 0.1312004499419488073250102996e-1
|
133 |
+
E5[5] = -0.1225156446376204440720569753e+1
|
134 |
+
E5[6] = -0.4957589496572501915214079952
|
135 |
+
E5[7] = 0.1664377182454986536961530415e+1
|
136 |
+
E5[8] = -0.3503288487499736816886487290
|
137 |
+
E5[9] = 0.3341791187130174790297318841
|
138 |
+
E5[10] = 0.8192320648511571246570742613e-1
|
139 |
+
E5[11] = -0.2235530786388629525884427845e-1
|
140 |
+
|
141 |
+
# First 3 coefficients are computed separately.
|
142 |
+
D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED))
|
143 |
+
D[0, 0] = -0.84289382761090128651353491142e+1
|
144 |
+
D[0, 5] = 0.56671495351937776962531783590
|
145 |
+
D[0, 6] = -0.30689499459498916912797304727e+1
|
146 |
+
D[0, 7] = 0.23846676565120698287728149680e+1
|
147 |
+
D[0, 8] = 0.21170345824450282767155149946e+1
|
148 |
+
D[0, 9] = -0.87139158377797299206789907490
|
149 |
+
D[0, 10] = 0.22404374302607882758541771650e+1
|
150 |
+
D[0, 11] = 0.63157877876946881815570249290
|
151 |
+
D[0, 12] = -0.88990336451333310820698117400e-1
|
152 |
+
D[0, 13] = 0.18148505520854727256656404962e+2
|
153 |
+
D[0, 14] = -0.91946323924783554000451984436e+1
|
154 |
+
D[0, 15] = -0.44360363875948939664310572000e+1
|
155 |
+
|
156 |
+
D[1, 0] = 0.10427508642579134603413151009e+2
|
157 |
+
D[1, 5] = 0.24228349177525818288430175319e+3
|
158 |
+
D[1, 6] = 0.16520045171727028198505394887e+3
|
159 |
+
D[1, 7] = -0.37454675472269020279518312152e+3
|
160 |
+
D[1, 8] = -0.22113666853125306036270938578e+2
|
161 |
+
D[1, 9] = 0.77334326684722638389603898808e+1
|
162 |
+
D[1, 10] = -0.30674084731089398182061213626e+2
|
163 |
+
D[1, 11] = -0.93321305264302278729567221706e+1
|
164 |
+
D[1, 12] = 0.15697238121770843886131091075e+2
|
165 |
+
D[1, 13] = -0.31139403219565177677282850411e+2
|
166 |
+
D[1, 14] = -0.93529243588444783865713862664e+1
|
167 |
+
D[1, 15] = 0.35816841486394083752465898540e+2
|
168 |
+
|
169 |
+
D[2, 0] = 0.19985053242002433820987653617e+2
|
170 |
+
D[2, 5] = -0.38703730874935176555105901742e+3
|
171 |
+
D[2, 6] = -0.18917813819516756882830838328e+3
|
172 |
+
D[2, 7] = 0.52780815920542364900561016686e+3
|
173 |
+
D[2, 8] = -0.11573902539959630126141871134e+2
|
174 |
+
D[2, 9] = 0.68812326946963000169666922661e+1
|
175 |
+
D[2, 10] = -0.10006050966910838403183860980e+1
|
176 |
+
D[2, 11] = 0.77771377980534432092869265740
|
177 |
+
D[2, 12] = -0.27782057523535084065932004339e+1
|
178 |
+
D[2, 13] = -0.60196695231264120758267380846e+2
|
179 |
+
D[2, 14] = 0.84320405506677161018159903784e+2
|
180 |
+
D[2, 15] = 0.11992291136182789328035130030e+2
|
181 |
+
|
182 |
+
D[3, 0] = -0.25693933462703749003312586129e+2
|
183 |
+
D[3, 5] = -0.15418974869023643374053993627e+3
|
184 |
+
D[3, 6] = -0.23152937917604549567536039109e+3
|
185 |
+
D[3, 7] = 0.35763911791061412378285349910e+3
|
186 |
+
D[3, 8] = 0.93405324183624310003907691704e+2
|
187 |
+
D[3, 9] = -0.37458323136451633156875139351e+2
|
188 |
+
D[3, 10] = 0.10409964950896230045147246184e+3
|
189 |
+
D[3, 11] = 0.29840293426660503123344363579e+2
|
190 |
+
D[3, 12] = -0.43533456590011143754432175058e+2
|
191 |
+
D[3, 13] = 0.96324553959188282948394950600e+2
|
192 |
+
D[3, 14] = -0.39177261675615439165231486172e+2
|
193 |
+
D[3, 15] = -0.14972683625798562581422125276e+3
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
ADDED
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import numpy as np
|
3 |
+
from .bdf import BDF
|
4 |
+
from .radau import Radau
|
5 |
+
from .rk import RK23, RK45, DOP853
|
6 |
+
from .lsoda import LSODA
|
7 |
+
from scipy.optimize import OptimizeResult
|
8 |
+
from .common import EPS, OdeSolution
|
9 |
+
from .base import OdeSolver
|
10 |
+
|
11 |
+
|
12 |
+
METHODS = {'RK23': RK23,
|
13 |
+
'RK45': RK45,
|
14 |
+
'DOP853': DOP853,
|
15 |
+
'Radau': Radau,
|
16 |
+
'BDF': BDF,
|
17 |
+
'LSODA': LSODA}
|
18 |
+
|
19 |
+
|
20 |
+
MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
|
21 |
+
1: "A termination event occurred."}
|
22 |
+
|
23 |
+
|
24 |
+
class OdeResult(OptimizeResult):
|
25 |
+
pass
|
26 |
+
|
27 |
+
|
28 |
+
def prepare_events(events):
|
29 |
+
"""Standardize event functions and extract attributes."""
|
30 |
+
if callable(events):
|
31 |
+
events = (events,)
|
32 |
+
|
33 |
+
max_events = np.empty(len(events))
|
34 |
+
direction = np.empty(len(events))
|
35 |
+
for i, event in enumerate(events):
|
36 |
+
terminal = getattr(event, 'terminal', None)
|
37 |
+
direction[i] = getattr(event, 'direction', 0)
|
38 |
+
|
39 |
+
message = ('The `terminal` attribute of each event '
|
40 |
+
'must be a boolean or positive integer.')
|
41 |
+
if terminal is None or terminal == 0:
|
42 |
+
max_events[i] = np.inf
|
43 |
+
elif int(terminal) == terminal and terminal > 0:
|
44 |
+
max_events[i] = terminal
|
45 |
+
else:
|
46 |
+
raise ValueError(message)
|
47 |
+
|
48 |
+
return events, max_events, direction
|
49 |
+
|
50 |
+
|
51 |
+
def solve_event_equation(event, sol, t_old, t):
|
52 |
+
"""Solve an equation corresponding to an ODE event.
|
53 |
+
|
54 |
+
The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
|
55 |
+
ODE solver using some sort of interpolation. It is solved by
|
56 |
+
`scipy.optimize.brentq` with xtol=atol=4*EPS.
|
57 |
+
|
58 |
+
Parameters
|
59 |
+
----------
|
60 |
+
event : callable
|
61 |
+
Function ``event(t, y)``.
|
62 |
+
sol : callable
|
63 |
+
Function ``sol(t)`` which evaluates an ODE solution between `t_old`
|
64 |
+
and `t`.
|
65 |
+
t_old, t : float
|
66 |
+
Previous and new values of time. They will be used as a bracketing
|
67 |
+
interval.
|
68 |
+
|
69 |
+
Returns
|
70 |
+
-------
|
71 |
+
root : float
|
72 |
+
Found solution.
|
73 |
+
"""
|
74 |
+
from scipy.optimize import brentq
|
75 |
+
return brentq(lambda t: event(t, sol(t)), t_old, t,
|
76 |
+
xtol=4 * EPS, rtol=4 * EPS)
|
77 |
+
|
78 |
+
|
79 |
+
def handle_events(sol, events, active_events, event_count, max_events,
|
80 |
+
t_old, t):
|
81 |
+
"""Helper function to handle events.
|
82 |
+
|
83 |
+
Parameters
|
84 |
+
----------
|
85 |
+
sol : DenseOutput
|
86 |
+
Function ``sol(t)`` which evaluates an ODE solution between `t_old`
|
87 |
+
and `t`.
|
88 |
+
events : list of callables, length n_events
|
89 |
+
Event functions with signatures ``event(t, y)``.
|
90 |
+
active_events : ndarray
|
91 |
+
Indices of events which occurred.
|
92 |
+
event_count : ndarray
|
93 |
+
Current number of occurrences for each event.
|
94 |
+
max_events : ndarray, shape (n_events,)
|
95 |
+
Number of occurrences allowed for each event before integration
|
96 |
+
termination is issued.
|
97 |
+
t_old, t : float
|
98 |
+
Previous and new values of time.
|
99 |
+
|
100 |
+
Returns
|
101 |
+
-------
|
102 |
+
root_indices : ndarray
|
103 |
+
Indices of events which take zero between `t_old` and `t` and before
|
104 |
+
a possible termination.
|
105 |
+
roots : ndarray
|
106 |
+
Values of t at which events occurred.
|
107 |
+
terminate : bool
|
108 |
+
Whether a terminal event occurred.
|
109 |
+
"""
|
110 |
+
roots = [solve_event_equation(events[event_index], sol, t_old, t)
|
111 |
+
for event_index in active_events]
|
112 |
+
|
113 |
+
roots = np.asarray(roots)
|
114 |
+
|
115 |
+
if np.any(event_count[active_events] >= max_events[active_events]):
|
116 |
+
if t > t_old:
|
117 |
+
order = np.argsort(roots)
|
118 |
+
else:
|
119 |
+
order = np.argsort(-roots)
|
120 |
+
active_events = active_events[order]
|
121 |
+
roots = roots[order]
|
122 |
+
t = np.nonzero(event_count[active_events]
|
123 |
+
>= max_events[active_events])[0][0]
|
124 |
+
active_events = active_events[:t + 1]
|
125 |
+
roots = roots[:t + 1]
|
126 |
+
terminate = True
|
127 |
+
else:
|
128 |
+
terminate = False
|
129 |
+
|
130 |
+
return active_events, roots, terminate
|
131 |
+
|
132 |
+
|
133 |
+
def find_active_events(g, g_new, direction):
|
134 |
+
"""Find which event occurred during an integration step.
|
135 |
+
|
136 |
+
Parameters
|
137 |
+
----------
|
138 |
+
g, g_new : array_like, shape (n_events,)
|
139 |
+
Values of event functions at a current and next points.
|
140 |
+
direction : ndarray, shape (n_events,)
|
141 |
+
Event "direction" according to the definition in `solve_ivp`.
|
142 |
+
|
143 |
+
Returns
|
144 |
+
-------
|
145 |
+
active_events : ndarray
|
146 |
+
Indices of events which occurred during the step.
|
147 |
+
"""
|
148 |
+
g, g_new = np.asarray(g), np.asarray(g_new)
|
149 |
+
up = (g <= 0) & (g_new >= 0)
|
150 |
+
down = (g >= 0) & (g_new <= 0)
|
151 |
+
either = up | down
|
152 |
+
mask = (up & (direction > 0) |
|
153 |
+
down & (direction < 0) |
|
154 |
+
either & (direction == 0))
|
155 |
+
|
156 |
+
return np.nonzero(mask)[0]
|
157 |
+
|
158 |
+
|
159 |
+
def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
|
160 |
+
events=None, vectorized=False, args=None, **options):
|
161 |
+
"""Solve an initial value problem for a system of ODEs.
|
162 |
+
|
163 |
+
This function numerically integrates a system of ordinary differential
|
164 |
+
equations given an initial value::
|
165 |
+
|
166 |
+
dy / dt = f(t, y)
|
167 |
+
y(t0) = y0
|
168 |
+
|
169 |
+
Here t is a 1-D independent variable (time), y(t) is an
|
170 |
+
N-D vector-valued function (state), and an N-D
|
171 |
+
vector-valued function f(t, y) determines the differential equations.
|
172 |
+
The goal is to find y(t) approximately satisfying the differential
|
173 |
+
equations, given an initial value y(t0)=y0.
|
174 |
+
|
175 |
+
Some of the solvers support integration in the complex domain, but note
|
176 |
+
that for stiff ODE solvers, the right-hand side must be
|
177 |
+
complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
|
178 |
+
To solve a problem in the complex domain, pass y0 with a complex data type.
|
179 |
+
Another option always available is to rewrite your problem for real and
|
180 |
+
imaginary parts separately.
|
181 |
+
|
182 |
+
Parameters
|
183 |
+
----------
|
184 |
+
fun : callable
|
185 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
186 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
187 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
|
188 |
+
arguments need to be passed if ``args`` is used (see documentation of
|
189 |
+
``args`` argument). ``fun`` must return an array of the same shape as
|
190 |
+
``y``. See `vectorized` for more information.
|
191 |
+
t_span : 2-member sequence
|
192 |
+
Interval of integration (t0, tf). The solver starts with t=t0 and
|
193 |
+
integrates until it reaches t=tf. Both t0 and tf must be floats
|
194 |
+
or values interpretable by the float conversion function.
|
195 |
+
y0 : array_like, shape (n,)
|
196 |
+
Initial state. For problems in the complex domain, pass `y0` with a
|
197 |
+
complex data type (even if the initial value is purely real).
|
198 |
+
method : string or `OdeSolver`, optional
|
199 |
+
Integration method to use:
|
200 |
+
|
201 |
+
* 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_.
|
202 |
+
The error is controlled assuming accuracy of the fourth-order
|
203 |
+
method, but steps are taken using the fifth-order accurate
|
204 |
+
formula (local extrapolation is done). A quartic interpolation
|
205 |
+
polynomial is used for the dense output [2]_. Can be applied in
|
206 |
+
the complex domain.
|
207 |
+
* 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error
|
208 |
+
is controlled assuming accuracy of the second-order method, but
|
209 |
+
steps are taken using the third-order accurate formula (local
|
210 |
+
extrapolation is done). A cubic Hermite polynomial is used for the
|
211 |
+
dense output. Can be applied in the complex domain.
|
212 |
+
* 'DOP853': Explicit Runge-Kutta method of order 8 [13]_.
|
213 |
+
Python implementation of the "DOP853" algorithm originally
|
214 |
+
written in Fortran [14]_. A 7-th order interpolation polynomial
|
215 |
+
accurate to 7-th order is used for the dense output.
|
216 |
+
Can be applied in the complex domain.
|
217 |
+
* 'Radau': Implicit Runge-Kutta method of the Radau IIA family of
|
218 |
+
order 5 [4]_. The error is controlled with a third-order accurate
|
219 |
+
embedded formula. A cubic polynomial which satisfies the
|
220 |
+
collocation conditions is used for the dense output.
|
221 |
+
* 'BDF': Implicit multi-step variable-order (1 to 5) method based
|
222 |
+
on a backward differentiation formula for the derivative
|
223 |
+
approximation [5]_. The implementation follows the one described
|
224 |
+
in [6]_. A quasi-constant step scheme is used and accuracy is
|
225 |
+
enhanced using the NDF modification. Can be applied in the
|
226 |
+
complex domain.
|
227 |
+
* 'LSODA': Adams/BDF method with automatic stiffness detection and
|
228 |
+
switching [7]_, [8]_. This is a wrapper of the Fortran solver
|
229 |
+
from ODEPACK.
|
230 |
+
|
231 |
+
Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
|
232 |
+
for non-stiff problems and implicit methods ('Radau', 'BDF') for
|
233 |
+
stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
|
234 |
+
for solving with high precision (low values of `rtol` and `atol`).
|
235 |
+
|
236 |
+
If not sure, first try to run 'RK45'. If it makes unusually many
|
237 |
+
iterations, diverges, or fails, your problem is likely to be stiff and
|
238 |
+
you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
|
239 |
+
choice, but it might be somewhat less convenient to work with as it
|
240 |
+
wraps old Fortran code.
|
241 |
+
|
242 |
+
You can also pass an arbitrary class derived from `OdeSolver` which
|
243 |
+
implements the solver.
|
244 |
+
t_eval : array_like or None, optional
|
245 |
+
Times at which to store the computed solution, must be sorted and lie
|
246 |
+
within `t_span`. If None (default), use points selected by the solver.
|
247 |
+
dense_output : bool, optional
|
248 |
+
Whether to compute a continuous solution. Default is False.
|
249 |
+
events : callable, or list of callables, optional
|
250 |
+
Events to track. If None (default), no events will be tracked.
|
251 |
+
Each event occurs at the zeros of a continuous function of time and
|
252 |
+
state. Each function must have the signature ``event(t, y)`` where
|
253 |
+
additional argument have to be passed if ``args`` is used (see
|
254 |
+
documentation of ``args`` argument). Each function must return a
|
255 |
+
float. The solver will find an accurate value of `t` at which
|
256 |
+
``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
|
257 |
+
all zeros will be found. The solver looks for a sign change over
|
258 |
+
each step, so if multiple zero crossings occur within one step,
|
259 |
+
events may be missed. Additionally each `event` function might
|
260 |
+
have the following attributes:
|
261 |
+
|
262 |
+
terminal: bool or int, optional
|
263 |
+
When boolean, whether to terminate integration if this event occurs.
|
264 |
+
When integral, termination occurs after the specified the number of
|
265 |
+
occurences of this event.
|
266 |
+
Implicitly False if not assigned.
|
267 |
+
direction: float, optional
|
268 |
+
Direction of a zero crossing. If `direction` is positive,
|
269 |
+
`event` will only trigger when going from negative to positive,
|
270 |
+
and vice versa if `direction` is negative. If 0, then either
|
271 |
+
direction will trigger event. Implicitly 0 if not assigned.
|
272 |
+
|
273 |
+
You can assign attributes like ``event.terminal = True`` to any
|
274 |
+
function in Python.
|
275 |
+
vectorized : bool, optional
|
276 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
277 |
+
|
278 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
279 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
280 |
+
|
281 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
282 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
283 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
284 |
+
the returned array is the time derivative of the state corresponding
|
285 |
+
with a column of ``y``).
|
286 |
+
|
287 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
288 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
289 |
+
will result in slower execution for other methods and for 'Radau' and
|
290 |
+
'BDF' in some circumstances (e.g. small ``len(y0)``).
|
291 |
+
args : tuple, optional
|
292 |
+
Additional arguments to pass to the user-defined functions. If given,
|
293 |
+
the additional arguments are passed to all user-defined functions.
|
294 |
+
So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
|
295 |
+
then `jac` (if given) and any event functions must have the same
|
296 |
+
signature, and `args` must be a tuple of length 3.
|
297 |
+
**options
|
298 |
+
Options passed to a chosen solver. All options available for already
|
299 |
+
implemented solvers are listed below.
|
300 |
+
first_step : float or None, optional
|
301 |
+
Initial step size. Default is `None` which means that the algorithm
|
302 |
+
should choose.
|
303 |
+
max_step : float, optional
|
304 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
305 |
+
bounded and determined solely by the solver.
|
306 |
+
rtol, atol : float or array_like, optional
|
307 |
+
Relative and absolute tolerances. The solver keeps the local error
|
308 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
309 |
+
relative accuracy (number of correct digits), while `atol` controls
|
310 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
311 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
312 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
313 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
314 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
315 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
316 |
+
than `atol`. If components of y have different scales, it might be
|
317 |
+
beneficial to set different `atol` values for different components by
|
318 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
319 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
320 |
+
jac : array_like, sparse_matrix, callable or None, optional
|
321 |
+
Jacobian matrix of the right-hand side of the system with respect
|
322 |
+
to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
|
323 |
+
Jacobian matrix has shape (n, n) and its element (i, j) is equal to
|
324 |
+
``d f_i / d y_j``. There are three ways to define the Jacobian:
|
325 |
+
|
326 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
327 |
+
be constant. Not supported by 'LSODA'.
|
328 |
+
* If callable, the Jacobian is assumed to depend on both
|
329 |
+
t and y; it will be called as ``jac(t, y)``, as necessary.
|
330 |
+
Additional arguments have to be passed if ``args`` is
|
331 |
+
used (see documentation of ``args`` argument).
|
332 |
+
For 'Radau' and 'BDF' methods, the return value might be a
|
333 |
+
sparse matrix.
|
334 |
+
* If None (default), the Jacobian will be approximated by
|
335 |
+
finite differences.
|
336 |
+
|
337 |
+
It is generally recommended to provide the Jacobian rather than
|
338 |
+
relying on a finite-difference approximation.
|
339 |
+
jac_sparsity : array_like, sparse matrix or None, optional
|
340 |
+
Defines a sparsity structure of the Jacobian matrix for a finite-
|
341 |
+
difference approximation. Its shape must be (n, n). This argument
|
342 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few
|
343 |
+
non-zero elements in *each* row, providing the sparsity structure
|
344 |
+
will greatly speed up the computations [10]_. A zero entry means that
|
345 |
+
a corresponding element in the Jacobian is always zero. If None
|
346 |
+
(default), the Jacobian is assumed to be dense.
|
347 |
+
Not supported by 'LSODA', see `lband` and `uband` instead.
|
348 |
+
lband, uband : int or None, optional
|
349 |
+
Parameters defining the bandwidth of the Jacobian for the 'LSODA'
|
350 |
+
method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
|
351 |
+
Default is None. Setting these requires your jac routine to return the
|
352 |
+
Jacobian in the packed format: the returned array must have ``n``
|
353 |
+
columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
|
354 |
+
written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
|
355 |
+
The same format is used in `scipy.linalg.solve_banded` (check for an
|
356 |
+
illustration). These parameters can be also used with ``jac=None`` to
|
357 |
+
reduce the number of Jacobian elements estimated by finite differences.
|
358 |
+
min_step : float, optional
|
359 |
+
The minimum allowed step size for 'LSODA' method.
|
360 |
+
By default `min_step` is zero.
|
361 |
+
|
362 |
+
Returns
|
363 |
+
-------
|
364 |
+
Bunch object with the following fields defined:
|
365 |
+
t : ndarray, shape (n_points,)
|
366 |
+
Time points.
|
367 |
+
y : ndarray, shape (n, n_points)
|
368 |
+
Values of the solution at `t`.
|
369 |
+
sol : `OdeSolution` or None
|
370 |
+
Found solution as `OdeSolution` instance; None if `dense_output` was
|
371 |
+
set to False.
|
372 |
+
t_events : list of ndarray or None
|
373 |
+
Contains for each event type a list of arrays at which an event of
|
374 |
+
that type event was detected. None if `events` was None.
|
375 |
+
y_events : list of ndarray or None
|
376 |
+
For each value of `t_events`, the corresponding value of the solution.
|
377 |
+
None if `events` was None.
|
378 |
+
nfev : int
|
379 |
+
Number of evaluations of the right-hand side.
|
380 |
+
njev : int
|
381 |
+
Number of evaluations of the Jacobian.
|
382 |
+
nlu : int
|
383 |
+
Number of LU decompositions.
|
384 |
+
status : int
|
385 |
+
Reason for algorithm termination:
|
386 |
+
|
387 |
+
* -1: Integration step failed.
|
388 |
+
* 0: The solver successfully reached the end of `tspan`.
|
389 |
+
* 1: A termination event occurred.
|
390 |
+
|
391 |
+
message : string
|
392 |
+
Human-readable description of the termination reason.
|
393 |
+
success : bool
|
394 |
+
True if the solver reached the interval end or a termination event
|
395 |
+
occurred (``status >= 0``).
|
396 |
+
|
397 |
+
References
|
398 |
+
----------
|
399 |
+
.. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
|
400 |
+
formulae", Journal of Computational and Applied Mathematics, Vol. 6,
|
401 |
+
No. 1, pp. 19-26, 1980.
|
402 |
+
.. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
|
403 |
+
of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
|
404 |
+
.. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
|
405 |
+
Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
|
406 |
+
.. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
|
407 |
+
Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
408 |
+
.. [5] `Backward Differentiation Formula
|
409 |
+
<https://en.wikipedia.org/wiki/Backward_differentiation_formula>`_
|
410 |
+
on Wikipedia.
|
411 |
+
.. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
|
412 |
+
COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
|
413 |
+
.. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
|
414 |
+
Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
|
415 |
+
pp. 55-64, 1983.
|
416 |
+
.. [8] L. Petzold, "Automatic selection of methods for solving stiff and
|
417 |
+
nonstiff systems of ordinary differential equations", SIAM Journal
|
418 |
+
on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
|
419 |
+
1983.
|
420 |
+
.. [9] `Stiff equation <https://en.wikipedia.org/wiki/Stiff_equation>`_ on
|
421 |
+
Wikipedia.
|
422 |
+
.. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
423 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
424 |
+
and its Applications, 13, pp. 117-120, 1974.
|
425 |
+
.. [11] `Cauchy-Riemann equations
|
426 |
+
<https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
|
427 |
+
Wikipedia.
|
428 |
+
.. [12] `Lotka-Volterra equations
|
429 |
+
<https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations>`_
|
430 |
+
on Wikipedia.
|
431 |
+
.. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
432 |
+
Equations I: Nonstiff Problems", Sec. II.
|
433 |
+
.. [14] `Page with original Fortran code of DOP853
|
434 |
+
<http://www.unige.ch/~hairer/software.html>`_.
|
435 |
+
|
436 |
+
Examples
|
437 |
+
--------
|
438 |
+
Basic exponential decay showing automatically chosen time points.
|
439 |
+
|
440 |
+
>>> import numpy as np
|
441 |
+
>>> from scipy.integrate import solve_ivp
|
442 |
+
>>> def exponential_decay(t, y): return -0.5 * y
|
443 |
+
>>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
|
444 |
+
>>> print(sol.t)
|
445 |
+
[ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806
|
446 |
+
8.33328988 10. ]
|
447 |
+
>>> print(sol.y)
|
448 |
+
[[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
|
449 |
+
0.03107158 0.01350781]
|
450 |
+
[4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091
|
451 |
+
0.06214316 0.02701561]
|
452 |
+
[8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181
|
453 |
+
0.12428631 0.05403123]]
|
454 |
+
|
455 |
+
Specifying points where the solution is desired.
|
456 |
+
|
457 |
+
>>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
|
458 |
+
... t_eval=[0, 1, 2, 4, 10])
|
459 |
+
>>> print(sol.t)
|
460 |
+
[ 0 1 2 4 10]
|
461 |
+
>>> print(sol.y)
|
462 |
+
[[2. 1.21305369 0.73534021 0.27066736 0.01350938]
|
463 |
+
[4. 2.42610739 1.47068043 0.54133472 0.02701876]
|
464 |
+
[8. 4.85221478 2.94136085 1.08266944 0.05403753]]
|
465 |
+
|
466 |
+
Cannon fired upward with terminal event upon impact. The ``terminal`` and
|
467 |
+
``direction`` fields of an event are applied by monkey patching a function.
|
468 |
+
Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
|
469 |
+
at position 0 with velocity +10. Note that the integration never reaches
|
470 |
+
t=100 because the event is terminal.
|
471 |
+
|
472 |
+
>>> def upward_cannon(t, y): return [y[1], -0.5]
|
473 |
+
>>> def hit_ground(t, y): return y[0]
|
474 |
+
>>> hit_ground.terminal = True
|
475 |
+
>>> hit_ground.direction = -1
|
476 |
+
>>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
|
477 |
+
>>> print(sol.t_events)
|
478 |
+
[array([40.])]
|
479 |
+
>>> print(sol.t)
|
480 |
+
[0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
|
481 |
+
1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
|
482 |
+
|
483 |
+
Use `dense_output` and `events` to find position, which is 100, at the apex
|
484 |
+
of the cannonball's trajectory. Apex is not defined as terminal, so both
|
485 |
+
apex and hit_ground are found. There is no information at t=20, so the sol
|
486 |
+
attribute is used to evaluate the solution. The sol attribute is returned
|
487 |
+
by setting ``dense_output=True``. Alternatively, the `y_events` attribute
|
488 |
+
can be used to access the solution at the time of the event.
|
489 |
+
|
490 |
+
>>> def apex(t, y): return y[1]
|
491 |
+
>>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
|
492 |
+
... events=(hit_ground, apex), dense_output=True)
|
493 |
+
>>> print(sol.t_events)
|
494 |
+
[array([40.]), array([20.])]
|
495 |
+
>>> print(sol.t)
|
496 |
+
[0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
|
497 |
+
1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
|
498 |
+
>>> print(sol.sol(sol.t_events[1][0]))
|
499 |
+
[100. 0.]
|
500 |
+
>>> print(sol.y_events)
|
501 |
+
[array([[-5.68434189e-14, -1.00000000e+01]]),
|
502 |
+
array([[1.00000000e+02, 1.77635684e-15]])]
|
503 |
+
|
504 |
+
As an example of a system with additional parameters, we'll implement
|
505 |
+
the Lotka-Volterra equations [12]_.
|
506 |
+
|
507 |
+
>>> def lotkavolterra(t, z, a, b, c, d):
|
508 |
+
... x, y = z
|
509 |
+
... return [a*x - b*x*y, -c*y + d*x*y]
|
510 |
+
...
|
511 |
+
|
512 |
+
We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
|
513 |
+
argument.
|
514 |
+
|
515 |
+
>>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
|
516 |
+
... dense_output=True)
|
517 |
+
|
518 |
+
Compute a dense solution and plot it.
|
519 |
+
|
520 |
+
>>> t = np.linspace(0, 15, 300)
|
521 |
+
>>> z = sol.sol(t)
|
522 |
+
>>> import matplotlib.pyplot as plt
|
523 |
+
>>> plt.plot(t, z.T)
|
524 |
+
>>> plt.xlabel('t')
|
525 |
+
>>> plt.legend(['x', 'y'], shadow=True)
|
526 |
+
>>> plt.title('Lotka-Volterra System')
|
527 |
+
>>> plt.show()
|
528 |
+
|
529 |
+
A couple examples of using solve_ivp to solve the differential
|
530 |
+
equation ``y' = Ay`` with complex matrix ``A``.
|
531 |
+
|
532 |
+
>>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
|
533 |
+
... [0.25 + 0.58j, -0.2 + 0.14j, 0],
|
534 |
+
... [0, 0.2 + 0.4j, -0.1 + 0.97j]])
|
535 |
+
|
536 |
+
Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
|
537 |
+
|
538 |
+
>>> def deriv_vec(t, y):
|
539 |
+
... return A @ y
|
540 |
+
>>> result = solve_ivp(deriv_vec, [0, 25],
|
541 |
+
... np.array([10 + 0j, 20 + 0j, 30 + 0j]),
|
542 |
+
... t_eval=np.linspace(0, 25, 101))
|
543 |
+
>>> print(result.y[:, 0])
|
544 |
+
[10.+0.j 20.+0.j 30.+0.j]
|
545 |
+
>>> print(result.y[:, -1])
|
546 |
+
[18.46291039+45.25653651j 10.01569306+36.23293216j
|
547 |
+
-4.98662741+80.07360388j]
|
548 |
+
|
549 |
+
Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
|
550 |
+
|
551 |
+
>>> def deriv_mat(t, y):
|
552 |
+
... return (A @ y.reshape(3, 3)).flatten()
|
553 |
+
>>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
|
554 |
+
... [5 + 0j, 6 + 0j, 7 + 0j],
|
555 |
+
... [9 + 0j, 34 + 0j, 78 + 0j]])
|
556 |
+
|
557 |
+
>>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
|
558 |
+
... t_eval=np.linspace(0, 25, 101))
|
559 |
+
>>> print(result.y[:, 0].reshape(3, 3))
|
560 |
+
[[ 2.+0.j 3.+0.j 4.+0.j]
|
561 |
+
[ 5.+0.j 6.+0.j 7.+0.j]
|
562 |
+
[ 9.+0.j 34.+0.j 78.+0.j]]
|
563 |
+
>>> print(result.y[:, -1].reshape(3, 3))
|
564 |
+
[[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j
|
565 |
+
37.83405768 +63.25138759j]
|
566 |
+
[ 3.39949503 +11.82123994j 21.32530996 +44.88668871j
|
567 |
+
53.17531184+103.80400411j]
|
568 |
+
[ -2.26105874 +22.19277664j -15.1255713 +70.19616341j
|
569 |
+
-38.34616845+153.29039931j]]
|
570 |
+
|
571 |
+
|
572 |
+
"""
|
573 |
+
if method not in METHODS and not (
|
574 |
+
inspect.isclass(method) and issubclass(method, OdeSolver)):
|
575 |
+
raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
|
576 |
+
|
577 |
+
t0, tf = map(float, t_span)
|
578 |
+
|
579 |
+
if args is not None:
|
580 |
+
# Wrap the user's fun (and jac, if given) in lambdas to hide the
|
581 |
+
# additional parameters. Pass in the original fun as a keyword
|
582 |
+
# argument to keep it in the scope of the lambda.
|
583 |
+
try:
|
584 |
+
_ = [*(args)]
|
585 |
+
except TypeError as exp:
|
586 |
+
suggestion_tuple = (
|
587 |
+
"Supplied 'args' cannot be unpacked. Please supply `args`"
|
588 |
+
f" as a tuple (e.g. `args=({args},)`)"
|
589 |
+
)
|
590 |
+
raise TypeError(suggestion_tuple) from exp
|
591 |
+
|
592 |
+
def fun(t, x, fun=fun):
|
593 |
+
return fun(t, x, *args)
|
594 |
+
jac = options.get('jac')
|
595 |
+
if callable(jac):
|
596 |
+
options['jac'] = lambda t, x: jac(t, x, *args)
|
597 |
+
|
598 |
+
if t_eval is not None:
|
599 |
+
t_eval = np.asarray(t_eval)
|
600 |
+
if t_eval.ndim != 1:
|
601 |
+
raise ValueError("`t_eval` must be 1-dimensional.")
|
602 |
+
|
603 |
+
if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
|
604 |
+
raise ValueError("Values in `t_eval` are not within `t_span`.")
|
605 |
+
|
606 |
+
d = np.diff(t_eval)
|
607 |
+
if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
|
608 |
+
raise ValueError("Values in `t_eval` are not properly sorted.")
|
609 |
+
|
610 |
+
if tf > t0:
|
611 |
+
t_eval_i = 0
|
612 |
+
else:
|
613 |
+
# Make order of t_eval decreasing to use np.searchsorted.
|
614 |
+
t_eval = t_eval[::-1]
|
615 |
+
# This will be an upper bound for slices.
|
616 |
+
t_eval_i = t_eval.shape[0]
|
617 |
+
|
618 |
+
if method in METHODS:
|
619 |
+
method = METHODS[method]
|
620 |
+
|
621 |
+
solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
|
622 |
+
|
623 |
+
if t_eval is None:
|
624 |
+
ts = [t0]
|
625 |
+
ys = [y0]
|
626 |
+
elif t_eval is not None and dense_output:
|
627 |
+
ts = []
|
628 |
+
ti = [t0]
|
629 |
+
ys = []
|
630 |
+
else:
|
631 |
+
ts = []
|
632 |
+
ys = []
|
633 |
+
|
634 |
+
interpolants = []
|
635 |
+
|
636 |
+
if events is not None:
|
637 |
+
events, max_events, event_dir = prepare_events(events)
|
638 |
+
event_count = np.zeros(len(events))
|
639 |
+
if args is not None:
|
640 |
+
# Wrap user functions in lambdas to hide the additional parameters.
|
641 |
+
# The original event function is passed as a keyword argument to the
|
642 |
+
# lambda to keep the original function in scope (i.e., avoid the
|
643 |
+
# late binding closure "gotcha").
|
644 |
+
events = [lambda t, x, event=event: event(t, x, *args)
|
645 |
+
for event in events]
|
646 |
+
g = [event(t0, y0) for event in events]
|
647 |
+
t_events = [[] for _ in range(len(events))]
|
648 |
+
y_events = [[] for _ in range(len(events))]
|
649 |
+
else:
|
650 |
+
t_events = None
|
651 |
+
y_events = None
|
652 |
+
|
653 |
+
status = None
|
654 |
+
while status is None:
|
655 |
+
message = solver.step()
|
656 |
+
|
657 |
+
if solver.status == 'finished':
|
658 |
+
status = 0
|
659 |
+
elif solver.status == 'failed':
|
660 |
+
status = -1
|
661 |
+
break
|
662 |
+
|
663 |
+
t_old = solver.t_old
|
664 |
+
t = solver.t
|
665 |
+
y = solver.y
|
666 |
+
|
667 |
+
if dense_output:
|
668 |
+
sol = solver.dense_output()
|
669 |
+
interpolants.append(sol)
|
670 |
+
else:
|
671 |
+
sol = None
|
672 |
+
|
673 |
+
if events is not None:
|
674 |
+
g_new = [event(t, y) for event in events]
|
675 |
+
active_events = find_active_events(g, g_new, event_dir)
|
676 |
+
if active_events.size > 0:
|
677 |
+
if sol is None:
|
678 |
+
sol = solver.dense_output()
|
679 |
+
|
680 |
+
event_count[active_events] += 1
|
681 |
+
root_indices, roots, terminate = handle_events(
|
682 |
+
sol, events, active_events, event_count, max_events,
|
683 |
+
t_old, t)
|
684 |
+
|
685 |
+
for e, te in zip(root_indices, roots):
|
686 |
+
t_events[e].append(te)
|
687 |
+
y_events[e].append(sol(te))
|
688 |
+
|
689 |
+
if terminate:
|
690 |
+
status = 1
|
691 |
+
t = roots[-1]
|
692 |
+
y = sol(t)
|
693 |
+
|
694 |
+
g = g_new
|
695 |
+
|
696 |
+
if t_eval is None:
|
697 |
+
ts.append(t)
|
698 |
+
ys.append(y)
|
699 |
+
else:
|
700 |
+
# The value in t_eval equal to t will be included.
|
701 |
+
if solver.direction > 0:
|
702 |
+
t_eval_i_new = np.searchsorted(t_eval, t, side='right')
|
703 |
+
t_eval_step = t_eval[t_eval_i:t_eval_i_new]
|
704 |
+
else:
|
705 |
+
t_eval_i_new = np.searchsorted(t_eval, t, side='left')
|
706 |
+
# It has to be done with two slice operations, because
|
707 |
+
# you can't slice to 0th element inclusive using backward
|
708 |
+
# slicing.
|
709 |
+
t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1]
|
710 |
+
|
711 |
+
if t_eval_step.size > 0:
|
712 |
+
if sol is None:
|
713 |
+
sol = solver.dense_output()
|
714 |
+
ts.append(t_eval_step)
|
715 |
+
ys.append(sol(t_eval_step))
|
716 |
+
t_eval_i = t_eval_i_new
|
717 |
+
|
718 |
+
if t_eval is not None and dense_output:
|
719 |
+
ti.append(t)
|
720 |
+
|
721 |
+
message = MESSAGES.get(status, message)
|
722 |
+
|
723 |
+
if t_events is not None:
|
724 |
+
t_events = [np.asarray(te) for te in t_events]
|
725 |
+
y_events = [np.asarray(ye) for ye in y_events]
|
726 |
+
|
727 |
+
if t_eval is None:
|
728 |
+
ts = np.array(ts)
|
729 |
+
ys = np.vstack(ys).T
|
730 |
+
elif ts:
|
731 |
+
ts = np.hstack(ts)
|
732 |
+
ys = np.hstack(ys)
|
733 |
+
|
734 |
+
if dense_output:
|
735 |
+
if t_eval is None:
|
736 |
+
sol = OdeSolution(
|
737 |
+
ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False
|
738 |
+
)
|
739 |
+
else:
|
740 |
+
sol = OdeSolution(
|
741 |
+
ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False
|
742 |
+
)
|
743 |
+
else:
|
744 |
+
sol = None
|
745 |
+
|
746 |
+
return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events,
|
747 |
+
nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu,
|
748 |
+
status=status, message=message, success=status >= 0)
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.integrate import ode
|
3 |
+
from .common import validate_tol, validate_first_step, warn_extraneous
|
4 |
+
from .base import OdeSolver, DenseOutput
|
5 |
+
|
6 |
+
|
7 |
+
class LSODA(OdeSolver):
|
8 |
+
"""Adams/BDF method with automatic stiffness detection and switching.
|
9 |
+
|
10 |
+
This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
|
11 |
+
automatically between the nonstiff Adams method and the stiff BDF method.
|
12 |
+
The method was originally detailed in [2]_.
|
13 |
+
|
14 |
+
Parameters
|
15 |
+
----------
|
16 |
+
fun : callable
|
17 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
18 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
19 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
20 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
21 |
+
information.
|
22 |
+
t0 : float
|
23 |
+
Initial time.
|
24 |
+
y0 : array_like, shape (n,)
|
25 |
+
Initial state.
|
26 |
+
t_bound : float
|
27 |
+
Boundary time - the integration won't continue beyond it. It also
|
28 |
+
determines the direction of the integration.
|
29 |
+
first_step : float or None, optional
|
30 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
31 |
+
should choose.
|
32 |
+
min_step : float, optional
|
33 |
+
Minimum allowed step size. Default is 0.0, i.e., the step size is not
|
34 |
+
bounded and determined solely by the solver.
|
35 |
+
max_step : float, optional
|
36 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
37 |
+
bounded and determined solely by the solver.
|
38 |
+
rtol, atol : float and array_like, optional
|
39 |
+
Relative and absolute tolerances. The solver keeps the local error
|
40 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
41 |
+
relative accuracy (number of correct digits), while `atol` controls
|
42 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
43 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
44 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
45 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
46 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
47 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
48 |
+
than `atol`. If components of y have different scales, it might be
|
49 |
+
beneficial to set different `atol` values for different components by
|
50 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
51 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
52 |
+
jac : None or callable, optional
|
53 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
54 |
+
``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
|
55 |
+
equal to ``d f_i / d y_j``. The function will be called as
|
56 |
+
``jac(t, y)``. If None (default), the Jacobian will be
|
57 |
+
approximated by finite differences. It is generally recommended to
|
58 |
+
provide the Jacobian rather than relying on a finite-difference
|
59 |
+
approximation.
|
60 |
+
lband, uband : int or None
|
61 |
+
Parameters defining the bandwidth of the Jacobian,
|
62 |
+
i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
|
63 |
+
these requires your jac routine to return the Jacobian in the packed format:
|
64 |
+
the returned array must have ``n`` columns and ``uband + lband + 1``
|
65 |
+
rows in which Jacobian diagonals are written. Specifically
|
66 |
+
``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
|
67 |
+
in `scipy.linalg.solve_banded` (check for an illustration).
|
68 |
+
These parameters can be also used with ``jac=None`` to reduce the
|
69 |
+
number of Jacobian elements estimated by finite differences.
|
70 |
+
vectorized : bool, optional
|
71 |
+
Whether `fun` may be called in a vectorized fashion. False (default)
|
72 |
+
is recommended for this solver.
|
73 |
+
|
74 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
75 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
76 |
+
|
77 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
78 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
79 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
80 |
+
the returned array is the time derivative of the state corresponding
|
81 |
+
with a column of ``y``).
|
82 |
+
|
83 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
84 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
85 |
+
will result in slower execution for this solver.
|
86 |
+
|
87 |
+
Attributes
|
88 |
+
----------
|
89 |
+
n : int
|
90 |
+
Number of equations.
|
91 |
+
status : string
|
92 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
93 |
+
t_bound : float
|
94 |
+
Boundary time.
|
95 |
+
direction : float
|
96 |
+
Integration direction: +1 or -1.
|
97 |
+
t : float
|
98 |
+
Current time.
|
99 |
+
y : ndarray
|
100 |
+
Current state.
|
101 |
+
t_old : float
|
102 |
+
Previous time. None if no steps were made yet.
|
103 |
+
nfev : int
|
104 |
+
Number of evaluations of the right-hand side.
|
105 |
+
njev : int
|
106 |
+
Number of evaluations of the Jacobian.
|
107 |
+
|
108 |
+
References
|
109 |
+
----------
|
110 |
+
.. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
|
111 |
+
Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
|
112 |
+
pp. 55-64, 1983.
|
113 |
+
.. [2] L. Petzold, "Automatic selection of methods for solving stiff and
|
114 |
+
nonstiff systems of ordinary differential equations", SIAM Journal
|
115 |
+
on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
|
116 |
+
1983.
|
117 |
+
"""
|
118 |
+
def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
|
119 |
+
max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
|
120 |
+
uband=None, vectorized=False, **extraneous):
|
121 |
+
warn_extraneous(extraneous)
|
122 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
123 |
+
|
124 |
+
if first_step is None:
|
125 |
+
first_step = 0 # LSODA value for automatic selection.
|
126 |
+
else:
|
127 |
+
first_step = validate_first_step(first_step, t0, t_bound)
|
128 |
+
|
129 |
+
first_step *= self.direction
|
130 |
+
|
131 |
+
if max_step == np.inf:
|
132 |
+
max_step = 0 # LSODA value for infinity.
|
133 |
+
elif max_step <= 0:
|
134 |
+
raise ValueError("`max_step` must be positive.")
|
135 |
+
|
136 |
+
if min_step < 0:
|
137 |
+
raise ValueError("`min_step` must be nonnegative.")
|
138 |
+
|
139 |
+
rtol, atol = validate_tol(rtol, atol, self.n)
|
140 |
+
|
141 |
+
solver = ode(self.fun, jac)
|
142 |
+
solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
|
143 |
+
min_step=min_step, first_step=first_step,
|
144 |
+
lband=lband, uband=uband)
|
145 |
+
solver.set_initial_value(y0, t0)
|
146 |
+
|
147 |
+
# Inject t_bound into rwork array as needed for itask=5.
|
148 |
+
solver._integrator.rwork[0] = self.t_bound
|
149 |
+
solver._integrator.call_args[4] = solver._integrator.rwork
|
150 |
+
|
151 |
+
self._lsoda_solver = solver
|
152 |
+
|
153 |
+
def _step_impl(self):
|
154 |
+
solver = self._lsoda_solver
|
155 |
+
integrator = solver._integrator
|
156 |
+
|
157 |
+
# From lsoda.step and lsoda.integrate itask=5 means take a single
|
158 |
+
# step and do not go past t_bound.
|
159 |
+
itask = integrator.call_args[2]
|
160 |
+
integrator.call_args[2] = 5
|
161 |
+
solver._y, solver.t = integrator.run(
|
162 |
+
solver.f, solver.jac or (lambda: None), solver._y, solver.t,
|
163 |
+
self.t_bound, solver.f_params, solver.jac_params)
|
164 |
+
integrator.call_args[2] = itask
|
165 |
+
|
166 |
+
if solver.successful():
|
167 |
+
self.t = solver.t
|
168 |
+
self.y = solver._y
|
169 |
+
# From LSODA Fortran source njev is equal to nlu.
|
170 |
+
self.njev = integrator.iwork[12]
|
171 |
+
self.nlu = integrator.iwork[12]
|
172 |
+
return True, None
|
173 |
+
else:
|
174 |
+
return False, 'Unexpected istate in LSODA.'
|
175 |
+
|
176 |
+
def _dense_output_impl(self):
|
177 |
+
iwork = self._lsoda_solver._integrator.iwork
|
178 |
+
rwork = self._lsoda_solver._integrator.rwork
|
179 |
+
|
180 |
+
# We want to produce the Nordsieck history array, yh, up to the order
|
181 |
+
# used in the last successful iteration. The step size is unimportant
|
182 |
+
# because it will be scaled out in LsodaDenseOutput. Some additional
|
183 |
+
# work may be required because ODEPACK's LSODA implementation produces
|
184 |
+
# the Nordsieck history in the state needed for the next iteration.
|
185 |
+
|
186 |
+
# iwork[13] contains order from last successful iteration, while
|
187 |
+
# iwork[14] contains order to be attempted next.
|
188 |
+
order = iwork[13]
|
189 |
+
|
190 |
+
# rwork[11] contains the step size to be attempted next, while
|
191 |
+
# rwork[10] contains step size from last successful iteration.
|
192 |
+
h = rwork[11]
|
193 |
+
|
194 |
+
# rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
|
195 |
+
# Nordsieck array in state needed for next iteration. We want
|
196 |
+
# the entries up to order for the last successful step so use the
|
197 |
+
# following.
|
198 |
+
yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
|
199 |
+
(self.n, order + 1), order='F').copy()
|
200 |
+
if iwork[14] < order:
|
201 |
+
# If the order is set to decrease then the final column of yh
|
202 |
+
# has not been updated within ODEPACK's LSODA
|
203 |
+
# implementation because this column will not be used in the
|
204 |
+
# next iteration. We must rescale this column to make the
|
205 |
+
# associated step size consistent with the other columns.
|
206 |
+
yh[:, -1] *= (h / rwork[10]) ** order
|
207 |
+
|
208 |
+
return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
|
209 |
+
|
210 |
+
|
211 |
+
class LsodaDenseOutput(DenseOutput):
|
212 |
+
def __init__(self, t_old, t, h, order, yh):
|
213 |
+
super().__init__(t_old, t)
|
214 |
+
self.h = h
|
215 |
+
self.yh = yh
|
216 |
+
self.p = np.arange(order + 1)
|
217 |
+
|
218 |
+
def _call_impl(self, t):
|
219 |
+
if t.ndim == 0:
|
220 |
+
x = ((t - self.t) / self.h) ** self.p
|
221 |
+
else:
|
222 |
+
x = ((t - self.t) / self.h) ** self.p[:, None]
|
223 |
+
|
224 |
+
return np.dot(self.yh, x)
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
ADDED
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from scipy.linalg import lu_factor, lu_solve
|
3 |
+
from scipy.sparse import csc_matrix, issparse, eye
|
4 |
+
from scipy.sparse.linalg import splu
|
5 |
+
from scipy.optimize._numdiff import group_columns
|
6 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
7 |
+
norm, num_jac, EPS, warn_extraneous,
|
8 |
+
validate_first_step)
|
9 |
+
from .base import OdeSolver, DenseOutput
|
10 |
+
|
11 |
+
S6 = 6 ** 0.5
|
12 |
+
|
13 |
+
# Butcher tableau. A is not used directly, see below.
|
14 |
+
C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
|
15 |
+
E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
|
16 |
+
|
17 |
+
# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
|
18 |
+
# and a complex conjugate pair. They are written below.
|
19 |
+
MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
|
20 |
+
MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
|
21 |
+
- 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
|
22 |
+
|
23 |
+
# These are transformation matrices.
|
24 |
+
T = np.array([
|
25 |
+
[0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
|
26 |
+
[0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
|
27 |
+
[1, 1, 0]])
|
28 |
+
TI = np.array([
|
29 |
+
[4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
|
30 |
+
[-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
|
31 |
+
[0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
|
32 |
+
# These linear combinations are used in the algorithm.
|
33 |
+
TI_REAL = TI[0]
|
34 |
+
TI_COMPLEX = TI[1] + 1j * TI[2]
|
35 |
+
|
36 |
+
# Interpolator coefficients.
|
37 |
+
P = np.array([
|
38 |
+
[13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
|
39 |
+
[13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
|
40 |
+
[1/3, -8/3, 10/3]])
|
41 |
+
|
42 |
+
|
43 |
+
NEWTON_MAXITER = 6 # Maximum number of Newton iterations.
|
44 |
+
MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
|
45 |
+
MAX_FACTOR = 10 # Maximum allowed increase in a step size.
|
46 |
+
|
47 |
+
|
48 |
+
def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
|
49 |
+
LU_real, LU_complex, solve_lu):
|
50 |
+
"""Solve the collocation system.
|
51 |
+
|
52 |
+
Parameters
|
53 |
+
----------
|
54 |
+
fun : callable
|
55 |
+
Right-hand side of the system.
|
56 |
+
t : float
|
57 |
+
Current time.
|
58 |
+
y : ndarray, shape (n,)
|
59 |
+
Current state.
|
60 |
+
h : float
|
61 |
+
Step to try.
|
62 |
+
Z0 : ndarray, shape (3, n)
|
63 |
+
Initial guess for the solution. It determines new values of `y` at
|
64 |
+
``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
|
65 |
+
scale : ndarray, shape (n)
|
66 |
+
Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
|
67 |
+
tol : float
|
68 |
+
Tolerance to which solve the system. This value is compared with
|
69 |
+
the normalized by `scale` error.
|
70 |
+
LU_real, LU_complex
|
71 |
+
LU decompositions of the system Jacobians.
|
72 |
+
solve_lu : callable
|
73 |
+
Callable which solves a linear system given a LU decomposition. The
|
74 |
+
signature is ``solve_lu(LU, b)``.
|
75 |
+
|
76 |
+
Returns
|
77 |
+
-------
|
78 |
+
converged : bool
|
79 |
+
Whether iterations converged.
|
80 |
+
n_iter : int
|
81 |
+
Number of completed iterations.
|
82 |
+
Z : ndarray, shape (3, n)
|
83 |
+
Found solution.
|
84 |
+
rate : float
|
85 |
+
The rate of convergence.
|
86 |
+
"""
|
87 |
+
n = y.shape[0]
|
88 |
+
M_real = MU_REAL / h
|
89 |
+
M_complex = MU_COMPLEX / h
|
90 |
+
|
91 |
+
W = TI.dot(Z0)
|
92 |
+
Z = Z0
|
93 |
+
|
94 |
+
F = np.empty((3, n))
|
95 |
+
ch = h * C
|
96 |
+
|
97 |
+
dW_norm_old = None
|
98 |
+
dW = np.empty_like(W)
|
99 |
+
converged = False
|
100 |
+
rate = None
|
101 |
+
for k in range(NEWTON_MAXITER):
|
102 |
+
for i in range(3):
|
103 |
+
F[i] = fun(t + ch[i], y + Z[i])
|
104 |
+
|
105 |
+
if not np.all(np.isfinite(F)):
|
106 |
+
break
|
107 |
+
|
108 |
+
f_real = F.T.dot(TI_REAL) - M_real * W[0]
|
109 |
+
f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
|
110 |
+
|
111 |
+
dW_real = solve_lu(LU_real, f_real)
|
112 |
+
dW_complex = solve_lu(LU_complex, f_complex)
|
113 |
+
|
114 |
+
dW[0] = dW_real
|
115 |
+
dW[1] = dW_complex.real
|
116 |
+
dW[2] = dW_complex.imag
|
117 |
+
|
118 |
+
dW_norm = norm(dW / scale)
|
119 |
+
if dW_norm_old is not None:
|
120 |
+
rate = dW_norm / dW_norm_old
|
121 |
+
|
122 |
+
if (rate is not None and (rate >= 1 or
|
123 |
+
rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
|
124 |
+
break
|
125 |
+
|
126 |
+
W += dW
|
127 |
+
Z = T.dot(W)
|
128 |
+
|
129 |
+
if (dW_norm == 0 or
|
130 |
+
rate is not None and rate / (1 - rate) * dW_norm < tol):
|
131 |
+
converged = True
|
132 |
+
break
|
133 |
+
|
134 |
+
dW_norm_old = dW_norm
|
135 |
+
|
136 |
+
return converged, k + 1, Z, rate
|
137 |
+
|
138 |
+
|
139 |
+
def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
|
140 |
+
"""Predict by which factor to increase/decrease the step size.
|
141 |
+
|
142 |
+
The algorithm is described in [1]_.
|
143 |
+
|
144 |
+
Parameters
|
145 |
+
----------
|
146 |
+
h_abs, h_abs_old : float
|
147 |
+
Current and previous values of the step size, `h_abs_old` can be None
|
148 |
+
(see Notes).
|
149 |
+
error_norm, error_norm_old : float
|
150 |
+
Current and previous values of the error norm, `error_norm_old` can
|
151 |
+
be None (see Notes).
|
152 |
+
|
153 |
+
Returns
|
154 |
+
-------
|
155 |
+
factor : float
|
156 |
+
Predicted factor.
|
157 |
+
|
158 |
+
Notes
|
159 |
+
-----
|
160 |
+
If `h_abs_old` and `error_norm_old` are both not None then a two-step
|
161 |
+
algorithm is used, otherwise a one-step algorithm is used.
|
162 |
+
|
163 |
+
References
|
164 |
+
----------
|
165 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
166 |
+
Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
167 |
+
"""
|
168 |
+
if error_norm_old is None or h_abs_old is None or error_norm == 0:
|
169 |
+
multiplier = 1
|
170 |
+
else:
|
171 |
+
multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
|
172 |
+
|
173 |
+
with np.errstate(divide='ignore'):
|
174 |
+
factor = min(1, multiplier) * error_norm ** -0.25
|
175 |
+
|
176 |
+
return factor
|
177 |
+
|
178 |
+
|
179 |
+
class Radau(OdeSolver):
|
180 |
+
"""Implicit Runge-Kutta method of Radau IIA family of order 5.
|
181 |
+
|
182 |
+
The implementation follows [1]_. The error is controlled with a
|
183 |
+
third-order accurate embedded formula. A cubic polynomial which satisfies
|
184 |
+
the collocation conditions is used for the dense output.
|
185 |
+
|
186 |
+
Parameters
|
187 |
+
----------
|
188 |
+
fun : callable
|
189 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
190 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
191 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
192 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
193 |
+
information.
|
194 |
+
t0 : float
|
195 |
+
Initial time.
|
196 |
+
y0 : array_like, shape (n,)
|
197 |
+
Initial state.
|
198 |
+
t_bound : float
|
199 |
+
Boundary time - the integration won't continue beyond it. It also
|
200 |
+
determines the direction of the integration.
|
201 |
+
first_step : float or None, optional
|
202 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
203 |
+
should choose.
|
204 |
+
max_step : float, optional
|
205 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
206 |
+
bounded and determined solely by the solver.
|
207 |
+
rtol, atol : float and array_like, optional
|
208 |
+
Relative and absolute tolerances. The solver keeps the local error
|
209 |
+
estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
|
210 |
+
relative accuracy (number of correct digits), while `atol` controls
|
211 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
212 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
213 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
214 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
215 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
216 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
217 |
+
than `atol`. If components of y have different scales, it might be
|
218 |
+
beneficial to set different `atol` values for different components by
|
219 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
220 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
221 |
+
jac : {None, array_like, sparse_matrix, callable}, optional
|
222 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
223 |
+
y, required by this method. The Jacobian matrix has shape (n, n) and
|
224 |
+
its element (i, j) is equal to ``d f_i / d y_j``.
|
225 |
+
There are three ways to define the Jacobian:
|
226 |
+
|
227 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
228 |
+
be constant.
|
229 |
+
* If callable, the Jacobian is assumed to depend on both
|
230 |
+
t and y; it will be called as ``jac(t, y)`` as necessary.
|
231 |
+
For the 'Radau' and 'BDF' methods, the return value might be a
|
232 |
+
sparse matrix.
|
233 |
+
* If None (default), the Jacobian will be approximated by
|
234 |
+
finite differences.
|
235 |
+
|
236 |
+
It is generally recommended to provide the Jacobian rather than
|
237 |
+
relying on a finite-difference approximation.
|
238 |
+
jac_sparsity : {None, array_like, sparse matrix}, optional
|
239 |
+
Defines a sparsity structure of the Jacobian matrix for a
|
240 |
+
finite-difference approximation. Its shape must be (n, n). This argument
|
241 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
|
242 |
+
elements in *each* row, providing the sparsity structure will greatly
|
243 |
+
speed up the computations [2]_. A zero entry means that a corresponding
|
244 |
+
element in the Jacobian is always zero. If None (default), the Jacobian
|
245 |
+
is assumed to be dense.
|
246 |
+
vectorized : bool, optional
|
247 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
248 |
+
|
249 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
250 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
251 |
+
|
252 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
253 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
254 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
255 |
+
the returned array is the time derivative of the state corresponding
|
256 |
+
with a column of ``y``).
|
257 |
+
|
258 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
259 |
+
approximation of the Jacobian by this method, but may result in slower
|
260 |
+
execution overall in some circumstances (e.g. small ``len(y0)``).
|
261 |
+
|
262 |
+
Attributes
|
263 |
+
----------
|
264 |
+
n : int
|
265 |
+
Number of equations.
|
266 |
+
status : string
|
267 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
268 |
+
t_bound : float
|
269 |
+
Boundary time.
|
270 |
+
direction : float
|
271 |
+
Integration direction: +1 or -1.
|
272 |
+
t : float
|
273 |
+
Current time.
|
274 |
+
y : ndarray
|
275 |
+
Current state.
|
276 |
+
t_old : float
|
277 |
+
Previous time. None if no steps were made yet.
|
278 |
+
step_size : float
|
279 |
+
Size of the last successful step. None if no steps were made yet.
|
280 |
+
nfev : int
|
281 |
+
Number of evaluations of the right-hand side.
|
282 |
+
njev : int
|
283 |
+
Number of evaluations of the Jacobian.
|
284 |
+
nlu : int
|
285 |
+
Number of LU decompositions.
|
286 |
+
|
287 |
+
References
|
288 |
+
----------
|
289 |
+
.. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
|
290 |
+
Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
291 |
+
.. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
292 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
293 |
+
and its Applications, 13, pp. 117-120, 1974.
|
294 |
+
"""
|
295 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
296 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
297 |
+
vectorized=False, first_step=None, **extraneous):
|
298 |
+
warn_extraneous(extraneous)
|
299 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
300 |
+
self.y_old = None
|
301 |
+
self.max_step = validate_max_step(max_step)
|
302 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
303 |
+
self.f = self.fun(self.t, self.y)
|
304 |
+
# Select initial step assuming the same order which is used to control
|
305 |
+
# the error.
|
306 |
+
if first_step is None:
|
307 |
+
self.h_abs = select_initial_step(
|
308 |
+
self.fun, self.t, self.y, self.f, self.direction,
|
309 |
+
3, self.rtol, self.atol)
|
310 |
+
else:
|
311 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
312 |
+
self.h_abs_old = None
|
313 |
+
self.error_norm_old = None
|
314 |
+
|
315 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
316 |
+
self.sol = None
|
317 |
+
|
318 |
+
self.jac_factor = None
|
319 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
320 |
+
if issparse(self.J):
|
321 |
+
def lu(A):
|
322 |
+
self.nlu += 1
|
323 |
+
return splu(A)
|
324 |
+
|
325 |
+
def solve_lu(LU, b):
|
326 |
+
return LU.solve(b)
|
327 |
+
|
328 |
+
I = eye(self.n, format='csc')
|
329 |
+
else:
|
330 |
+
def lu(A):
|
331 |
+
self.nlu += 1
|
332 |
+
return lu_factor(A, overwrite_a=True)
|
333 |
+
|
334 |
+
def solve_lu(LU, b):
|
335 |
+
return lu_solve(LU, b, overwrite_b=True)
|
336 |
+
|
337 |
+
I = np.identity(self.n)
|
338 |
+
|
339 |
+
self.lu = lu
|
340 |
+
self.solve_lu = solve_lu
|
341 |
+
self.I = I
|
342 |
+
|
343 |
+
self.current_jac = True
|
344 |
+
self.LU_real = None
|
345 |
+
self.LU_complex = None
|
346 |
+
self.Z = None
|
347 |
+
|
348 |
+
def _validate_jac(self, jac, sparsity):
|
349 |
+
t0 = self.t
|
350 |
+
y0 = self.y
|
351 |
+
|
352 |
+
if jac is None:
|
353 |
+
if sparsity is not None:
|
354 |
+
if issparse(sparsity):
|
355 |
+
sparsity = csc_matrix(sparsity)
|
356 |
+
groups = group_columns(sparsity)
|
357 |
+
sparsity = (sparsity, groups)
|
358 |
+
|
359 |
+
def jac_wrapped(t, y, f):
|
360 |
+
self.njev += 1
|
361 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
362 |
+
self.atol, self.jac_factor,
|
363 |
+
sparsity)
|
364 |
+
return J
|
365 |
+
J = jac_wrapped(t0, y0, self.f)
|
366 |
+
elif callable(jac):
|
367 |
+
J = jac(t0, y0)
|
368 |
+
self.njev = 1
|
369 |
+
if issparse(J):
|
370 |
+
J = csc_matrix(J)
|
371 |
+
|
372 |
+
def jac_wrapped(t, y, _=None):
|
373 |
+
self.njev += 1
|
374 |
+
return csc_matrix(jac(t, y), dtype=float)
|
375 |
+
|
376 |
+
else:
|
377 |
+
J = np.asarray(J, dtype=float)
|
378 |
+
|
379 |
+
def jac_wrapped(t, y, _=None):
|
380 |
+
self.njev += 1
|
381 |
+
return np.asarray(jac(t, y), dtype=float)
|
382 |
+
|
383 |
+
if J.shape != (self.n, self.n):
|
384 |
+
raise ValueError("`jac` is expected to have shape {}, but "
|
385 |
+
"actually has {}."
|
386 |
+
.format((self.n, self.n), J.shape))
|
387 |
+
else:
|
388 |
+
if issparse(jac):
|
389 |
+
J = csc_matrix(jac)
|
390 |
+
else:
|
391 |
+
J = np.asarray(jac, dtype=float)
|
392 |
+
|
393 |
+
if J.shape != (self.n, self.n):
|
394 |
+
raise ValueError("`jac` is expected to have shape {}, but "
|
395 |
+
"actually has {}."
|
396 |
+
.format((self.n, self.n), J.shape))
|
397 |
+
jac_wrapped = None
|
398 |
+
|
399 |
+
return jac_wrapped, J
|
400 |
+
|
401 |
+
def _step_impl(self):
|
402 |
+
t = self.t
|
403 |
+
y = self.y
|
404 |
+
f = self.f
|
405 |
+
|
406 |
+
max_step = self.max_step
|
407 |
+
atol = self.atol
|
408 |
+
rtol = self.rtol
|
409 |
+
|
410 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
411 |
+
if self.h_abs > max_step:
|
412 |
+
h_abs = max_step
|
413 |
+
h_abs_old = None
|
414 |
+
error_norm_old = None
|
415 |
+
elif self.h_abs < min_step:
|
416 |
+
h_abs = min_step
|
417 |
+
h_abs_old = None
|
418 |
+
error_norm_old = None
|
419 |
+
else:
|
420 |
+
h_abs = self.h_abs
|
421 |
+
h_abs_old = self.h_abs_old
|
422 |
+
error_norm_old = self.error_norm_old
|
423 |
+
|
424 |
+
J = self.J
|
425 |
+
LU_real = self.LU_real
|
426 |
+
LU_complex = self.LU_complex
|
427 |
+
|
428 |
+
current_jac = self.current_jac
|
429 |
+
jac = self.jac
|
430 |
+
|
431 |
+
rejected = False
|
432 |
+
step_accepted = False
|
433 |
+
message = None
|
434 |
+
while not step_accepted:
|
435 |
+
if h_abs < min_step:
|
436 |
+
return False, self.TOO_SMALL_STEP
|
437 |
+
|
438 |
+
h = h_abs * self.direction
|
439 |
+
t_new = t + h
|
440 |
+
|
441 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
442 |
+
t_new = self.t_bound
|
443 |
+
|
444 |
+
h = t_new - t
|
445 |
+
h_abs = np.abs(h)
|
446 |
+
|
447 |
+
if self.sol is None:
|
448 |
+
Z0 = np.zeros((3, y.shape[0]))
|
449 |
+
else:
|
450 |
+
Z0 = self.sol(t + h * C).T - y
|
451 |
+
|
452 |
+
scale = atol + np.abs(y) * rtol
|
453 |
+
|
454 |
+
converged = False
|
455 |
+
while not converged:
|
456 |
+
if LU_real is None or LU_complex is None:
|
457 |
+
LU_real = self.lu(MU_REAL / h * self.I - J)
|
458 |
+
LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
|
459 |
+
|
460 |
+
converged, n_iter, Z, rate = solve_collocation_system(
|
461 |
+
self.fun, t, y, h, Z0, scale, self.newton_tol,
|
462 |
+
LU_real, LU_complex, self.solve_lu)
|
463 |
+
|
464 |
+
if not converged:
|
465 |
+
if current_jac:
|
466 |
+
break
|
467 |
+
|
468 |
+
J = self.jac(t, y, f)
|
469 |
+
current_jac = True
|
470 |
+
LU_real = None
|
471 |
+
LU_complex = None
|
472 |
+
|
473 |
+
if not converged:
|
474 |
+
h_abs *= 0.5
|
475 |
+
LU_real = None
|
476 |
+
LU_complex = None
|
477 |
+
continue
|
478 |
+
|
479 |
+
y_new = y + Z[-1]
|
480 |
+
ZE = Z.T.dot(E) / h
|
481 |
+
error = self.solve_lu(LU_real, f + ZE)
|
482 |
+
scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
|
483 |
+
error_norm = norm(error / scale)
|
484 |
+
safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
|
485 |
+
+ n_iter)
|
486 |
+
|
487 |
+
if rejected and error_norm > 1:
|
488 |
+
error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
|
489 |
+
error_norm = norm(error / scale)
|
490 |
+
|
491 |
+
if error_norm > 1:
|
492 |
+
factor = predict_factor(h_abs, h_abs_old,
|
493 |
+
error_norm, error_norm_old)
|
494 |
+
h_abs *= max(MIN_FACTOR, safety * factor)
|
495 |
+
|
496 |
+
LU_real = None
|
497 |
+
LU_complex = None
|
498 |
+
rejected = True
|
499 |
+
else:
|
500 |
+
step_accepted = True
|
501 |
+
|
502 |
+
recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
|
503 |
+
|
504 |
+
factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
|
505 |
+
factor = min(MAX_FACTOR, safety * factor)
|
506 |
+
|
507 |
+
if not recompute_jac and factor < 1.2:
|
508 |
+
factor = 1
|
509 |
+
else:
|
510 |
+
LU_real = None
|
511 |
+
LU_complex = None
|
512 |
+
|
513 |
+
f_new = self.fun(t_new, y_new)
|
514 |
+
if recompute_jac:
|
515 |
+
J = jac(t_new, y_new, f_new)
|
516 |
+
current_jac = True
|
517 |
+
elif jac is not None:
|
518 |
+
current_jac = False
|
519 |
+
|
520 |
+
self.h_abs_old = self.h_abs
|
521 |
+
self.error_norm_old = error_norm
|
522 |
+
|
523 |
+
self.h_abs = h_abs * factor
|
524 |
+
|
525 |
+
self.y_old = y
|
526 |
+
|
527 |
+
self.t = t_new
|
528 |
+
self.y = y_new
|
529 |
+
self.f = f_new
|
530 |
+
|
531 |
+
self.Z = Z
|
532 |
+
|
533 |
+
self.LU_real = LU_real
|
534 |
+
self.LU_complex = LU_complex
|
535 |
+
self.current_jac = current_jac
|
536 |
+
self.J = J
|
537 |
+
|
538 |
+
self.t_old = t
|
539 |
+
self.sol = self._compute_dense_output()
|
540 |
+
|
541 |
+
return step_accepted, message
|
542 |
+
|
543 |
+
def _compute_dense_output(self):
|
544 |
+
Q = np.dot(self.Z.T, P)
|
545 |
+
return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
|
546 |
+
|
547 |
+
def _dense_output_impl(self):
|
548 |
+
return self.sol
|
549 |
+
|
550 |
+
|
551 |
+
class RadauDenseOutput(DenseOutput):
|
552 |
+
def __init__(self, t_old, t, y_old, Q):
|
553 |
+
super().__init__(t_old, t)
|
554 |
+
self.h = t - t_old
|
555 |
+
self.Q = Q
|
556 |
+
self.order = Q.shape[1] - 1
|
557 |
+
self.y_old = y_old
|
558 |
+
|
559 |
+
def _call_impl(self, t):
|
560 |
+
x = (t - self.t_old) / self.h
|
561 |
+
if t.ndim == 0:
|
562 |
+
p = np.tile(x, self.order + 1)
|
563 |
+
p = np.cumprod(p)
|
564 |
+
else:
|
565 |
+
p = np.tile(x, (self.order + 1, 1))
|
566 |
+
p = np.cumprod(p, axis=0)
|
567 |
+
# Here we don't multiply by h, not a mistake.
|
568 |
+
y = np.dot(self.Q, p)
|
569 |
+
if y.ndim == 2:
|
570 |
+
y += self.y_old[:, None]
|
571 |
+
else:
|
572 |
+
y += self.y_old
|
573 |
+
|
574 |
+
return y
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
ADDED
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from .base import OdeSolver, DenseOutput
|
3 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
4 |
+
norm, warn_extraneous, validate_first_step)
|
5 |
+
from . import dop853_coefficients
|
6 |
+
|
7 |
+
# Multiply steps computed from asymptotic behaviour of errors by this.
|
8 |
+
SAFETY = 0.9
|
9 |
+
|
10 |
+
MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
|
11 |
+
MAX_FACTOR = 10 # Maximum allowed increase in a step size.
|
12 |
+
|
13 |
+
|
14 |
+
def rk_step(fun, t, y, f, h, A, B, C, K):
|
15 |
+
"""Perform a single Runge-Kutta step.
|
16 |
+
|
17 |
+
This function computes a prediction of an explicit Runge-Kutta method and
|
18 |
+
also estimates the error of a less accurate method.
|
19 |
+
|
20 |
+
Notation for Butcher tableau is as in [1]_.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
----------
|
24 |
+
fun : callable
|
25 |
+
Right-hand side of the system.
|
26 |
+
t : float
|
27 |
+
Current time.
|
28 |
+
y : ndarray, shape (n,)
|
29 |
+
Current state.
|
30 |
+
f : ndarray, shape (n,)
|
31 |
+
Current value of the derivative, i.e., ``fun(x, y)``.
|
32 |
+
h : float
|
33 |
+
Step to use.
|
34 |
+
A : ndarray, shape (n_stages, n_stages)
|
35 |
+
Coefficients for combining previous RK stages to compute the next
|
36 |
+
stage. For explicit methods the coefficients at and above the main
|
37 |
+
diagonal are zeros.
|
38 |
+
B : ndarray, shape (n_stages,)
|
39 |
+
Coefficients for combining RK stages for computing the final
|
40 |
+
prediction.
|
41 |
+
C : ndarray, shape (n_stages,)
|
42 |
+
Coefficients for incrementing time for consecutive RK stages.
|
43 |
+
The value for the first stage is always zero.
|
44 |
+
K : ndarray, shape (n_stages + 1, n)
|
45 |
+
Storage array for putting RK stages here. Stages are stored in rows.
|
46 |
+
The last row is a linear combination of the previous rows with
|
47 |
+
coefficients
|
48 |
+
|
49 |
+
Returns
|
50 |
+
-------
|
51 |
+
y_new : ndarray, shape (n,)
|
52 |
+
Solution at t + h computed with a higher accuracy.
|
53 |
+
f_new : ndarray, shape (n,)
|
54 |
+
Derivative ``fun(t + h, y_new)``.
|
55 |
+
|
56 |
+
References
|
57 |
+
----------
|
58 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
59 |
+
Equations I: Nonstiff Problems", Sec. II.4.
|
60 |
+
"""
|
61 |
+
K[0] = f
|
62 |
+
for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
|
63 |
+
dy = np.dot(K[:s].T, a[:s]) * h
|
64 |
+
K[s] = fun(t + c * h, y + dy)
|
65 |
+
|
66 |
+
y_new = y + h * np.dot(K[:-1].T, B)
|
67 |
+
f_new = fun(t + h, y_new)
|
68 |
+
|
69 |
+
K[-1] = f_new
|
70 |
+
|
71 |
+
return y_new, f_new
|
72 |
+
|
73 |
+
|
74 |
+
class RungeKutta(OdeSolver):
|
75 |
+
"""Base class for explicit Runge-Kutta methods."""
|
76 |
+
C: np.ndarray = NotImplemented
|
77 |
+
A: np.ndarray = NotImplemented
|
78 |
+
B: np.ndarray = NotImplemented
|
79 |
+
E: np.ndarray = NotImplemented
|
80 |
+
P: np.ndarray = NotImplemented
|
81 |
+
order: int = NotImplemented
|
82 |
+
error_estimator_order: int = NotImplemented
|
83 |
+
n_stages: int = NotImplemented
|
84 |
+
|
85 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
86 |
+
rtol=1e-3, atol=1e-6, vectorized=False,
|
87 |
+
first_step=None, **extraneous):
|
88 |
+
warn_extraneous(extraneous)
|
89 |
+
super().__init__(fun, t0, y0, t_bound, vectorized,
|
90 |
+
support_complex=True)
|
91 |
+
self.y_old = None
|
92 |
+
self.max_step = validate_max_step(max_step)
|
93 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
94 |
+
self.f = self.fun(self.t, self.y)
|
95 |
+
if first_step is None:
|
96 |
+
self.h_abs = select_initial_step(
|
97 |
+
self.fun, self.t, self.y, self.f, self.direction,
|
98 |
+
self.error_estimator_order, self.rtol, self.atol)
|
99 |
+
else:
|
100 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
101 |
+
self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
|
102 |
+
self.error_exponent = -1 / (self.error_estimator_order + 1)
|
103 |
+
self.h_previous = None
|
104 |
+
|
105 |
+
def _estimate_error(self, K, h):
|
106 |
+
return np.dot(K.T, self.E) * h
|
107 |
+
|
108 |
+
def _estimate_error_norm(self, K, h, scale):
|
109 |
+
return norm(self._estimate_error(K, h) / scale)
|
110 |
+
|
111 |
+
def _step_impl(self):
|
112 |
+
t = self.t
|
113 |
+
y = self.y
|
114 |
+
|
115 |
+
max_step = self.max_step
|
116 |
+
rtol = self.rtol
|
117 |
+
atol = self.atol
|
118 |
+
|
119 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
120 |
+
|
121 |
+
if self.h_abs > max_step:
|
122 |
+
h_abs = max_step
|
123 |
+
elif self.h_abs < min_step:
|
124 |
+
h_abs = min_step
|
125 |
+
else:
|
126 |
+
h_abs = self.h_abs
|
127 |
+
|
128 |
+
step_accepted = False
|
129 |
+
step_rejected = False
|
130 |
+
|
131 |
+
while not step_accepted:
|
132 |
+
if h_abs < min_step:
|
133 |
+
return False, self.TOO_SMALL_STEP
|
134 |
+
|
135 |
+
h = h_abs * self.direction
|
136 |
+
t_new = t + h
|
137 |
+
|
138 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
139 |
+
t_new = self.t_bound
|
140 |
+
|
141 |
+
h = t_new - t
|
142 |
+
h_abs = np.abs(h)
|
143 |
+
|
144 |
+
y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
|
145 |
+
self.B, self.C, self.K)
|
146 |
+
scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
|
147 |
+
error_norm = self._estimate_error_norm(self.K, h, scale)
|
148 |
+
|
149 |
+
if error_norm < 1:
|
150 |
+
if error_norm == 0:
|
151 |
+
factor = MAX_FACTOR
|
152 |
+
else:
|
153 |
+
factor = min(MAX_FACTOR,
|
154 |
+
SAFETY * error_norm ** self.error_exponent)
|
155 |
+
|
156 |
+
if step_rejected:
|
157 |
+
factor = min(1, factor)
|
158 |
+
|
159 |
+
h_abs *= factor
|
160 |
+
|
161 |
+
step_accepted = True
|
162 |
+
else:
|
163 |
+
h_abs *= max(MIN_FACTOR,
|
164 |
+
SAFETY * error_norm ** self.error_exponent)
|
165 |
+
step_rejected = True
|
166 |
+
|
167 |
+
self.h_previous = h
|
168 |
+
self.y_old = y
|
169 |
+
|
170 |
+
self.t = t_new
|
171 |
+
self.y = y_new
|
172 |
+
|
173 |
+
self.h_abs = h_abs
|
174 |
+
self.f = f_new
|
175 |
+
|
176 |
+
return True, None
|
177 |
+
|
178 |
+
def _dense_output_impl(self):
|
179 |
+
Q = self.K.T.dot(self.P)
|
180 |
+
return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
|
181 |
+
|
182 |
+
|
183 |
+
class RK23(RungeKutta):
|
184 |
+
"""Explicit Runge-Kutta method of order 3(2).
|
185 |
+
|
186 |
+
This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
|
187 |
+
assuming accuracy of the second-order method, but steps are taken using the
|
188 |
+
third-order accurate formula (local extrapolation is done). A cubic Hermite
|
189 |
+
polynomial is used for the dense output.
|
190 |
+
|
191 |
+
Can be applied in the complex domain.
|
192 |
+
|
193 |
+
Parameters
|
194 |
+
----------
|
195 |
+
fun : callable
|
196 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
197 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
198 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
199 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
200 |
+
information.
|
201 |
+
t0 : float
|
202 |
+
Initial time.
|
203 |
+
y0 : array_like, shape (n,)
|
204 |
+
Initial state.
|
205 |
+
t_bound : float
|
206 |
+
Boundary time - the integration won't continue beyond it. It also
|
207 |
+
determines the direction of the integration.
|
208 |
+
first_step : float or None, optional
|
209 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
210 |
+
should choose.
|
211 |
+
max_step : float, optional
|
212 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
213 |
+
bounded and determined solely by the solver.
|
214 |
+
rtol, atol : float and array_like, optional
|
215 |
+
Relative and absolute tolerances. The solver keeps the local error
|
216 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
217 |
+
relative accuracy (number of correct digits), while `atol` controls
|
218 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
219 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
220 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
221 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
222 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
223 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
224 |
+
than `atol`. If components of y have different scales, it might be
|
225 |
+
beneficial to set different `atol` values for different components by
|
226 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
227 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
228 |
+
vectorized : bool, optional
|
229 |
+
Whether `fun` may be called in a vectorized fashion. False (default)
|
230 |
+
is recommended for this solver.
|
231 |
+
|
232 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
233 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
234 |
+
|
235 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
236 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
237 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
238 |
+
the returned array is the time derivative of the state corresponding
|
239 |
+
with a column of ``y``).
|
240 |
+
|
241 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
242 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
243 |
+
will result in slower execution for this solver.
|
244 |
+
|
245 |
+
Attributes
|
246 |
+
----------
|
247 |
+
n : int
|
248 |
+
Number of equations.
|
249 |
+
status : string
|
250 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
251 |
+
t_bound : float
|
252 |
+
Boundary time.
|
253 |
+
direction : float
|
254 |
+
Integration direction: +1 or -1.
|
255 |
+
t : float
|
256 |
+
Current time.
|
257 |
+
y : ndarray
|
258 |
+
Current state.
|
259 |
+
t_old : float
|
260 |
+
Previous time. None if no steps were made yet.
|
261 |
+
step_size : float
|
262 |
+
Size of the last successful step. None if no steps were made yet.
|
263 |
+
nfev : int
|
264 |
+
Number evaluations of the system's right-hand side.
|
265 |
+
njev : int
|
266 |
+
Number of evaluations of the Jacobian.
|
267 |
+
Is always 0 for this solver as it does not use the Jacobian.
|
268 |
+
nlu : int
|
269 |
+
Number of LU decompositions. Is always 0 for this solver.
|
270 |
+
|
271 |
+
References
|
272 |
+
----------
|
273 |
+
.. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
|
274 |
+
Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
|
275 |
+
"""
|
276 |
+
order = 3
|
277 |
+
error_estimator_order = 2
|
278 |
+
n_stages = 3
|
279 |
+
C = np.array([0, 1/2, 3/4])
|
280 |
+
A = np.array([
|
281 |
+
[0, 0, 0],
|
282 |
+
[1/2, 0, 0],
|
283 |
+
[0, 3/4, 0]
|
284 |
+
])
|
285 |
+
B = np.array([2/9, 1/3, 4/9])
|
286 |
+
E = np.array([5/72, -1/12, -1/9, 1/8])
|
287 |
+
P = np.array([[1, -4 / 3, 5 / 9],
|
288 |
+
[0, 1, -2/3],
|
289 |
+
[0, 4/3, -8/9],
|
290 |
+
[0, -1, 1]])
|
291 |
+
|
292 |
+
|
293 |
+
class RK45(RungeKutta):
|
294 |
+
"""Explicit Runge-Kutta method of order 5(4).
|
295 |
+
|
296 |
+
This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
|
297 |
+
assuming accuracy of the fourth-order method accuracy, but steps are taken
|
298 |
+
using the fifth-order accurate formula (local extrapolation is done).
|
299 |
+
A quartic interpolation polynomial is used for the dense output [2]_.
|
300 |
+
|
301 |
+
Can be applied in the complex domain.
|
302 |
+
|
303 |
+
Parameters
|
304 |
+
----------
|
305 |
+
fun : callable
|
306 |
+
Right-hand side of the system. The calling signature is ``fun(t, y)``.
|
307 |
+
Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
|
308 |
+
It can either have shape (n,); then ``fun`` must return array_like with
|
309 |
+
shape (n,). Alternatively it can have shape (n, k); then ``fun``
|
310 |
+
must return an array_like with shape (n, k), i.e., each column
|
311 |
+
corresponds to a single column in ``y``. The choice between the two
|
312 |
+
options is determined by `vectorized` argument (see below).
|
313 |
+
t0 : float
|
314 |
+
Initial time.
|
315 |
+
y0 : array_like, shape (n,)
|
316 |
+
Initial state.
|
317 |
+
t_bound : float
|
318 |
+
Boundary time - the integration won't continue beyond it. It also
|
319 |
+
determines the direction of the integration.
|
320 |
+
first_step : float or None, optional
|
321 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
322 |
+
should choose.
|
323 |
+
max_step : float, optional
|
324 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
325 |
+
bounded and determined solely by the solver.
|
326 |
+
rtol, atol : float and array_like, optional
|
327 |
+
Relative and absolute tolerances. The solver keeps the local error
|
328 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
329 |
+
relative accuracy (number of correct digits), while `atol` controls
|
330 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
331 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
332 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
333 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
334 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
335 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
336 |
+
than `atol`. If components of y have different scales, it might be
|
337 |
+
beneficial to set different `atol` values for different components by
|
338 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
339 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
340 |
+
vectorized : bool, optional
|
341 |
+
Whether `fun` is implemented in a vectorized fashion. Default is False.
|
342 |
+
|
343 |
+
Attributes
|
344 |
+
----------
|
345 |
+
n : int
|
346 |
+
Number of equations.
|
347 |
+
status : string
|
348 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
349 |
+
t_bound : float
|
350 |
+
Boundary time.
|
351 |
+
direction : float
|
352 |
+
Integration direction: +1 or -1.
|
353 |
+
t : float
|
354 |
+
Current time.
|
355 |
+
y : ndarray
|
356 |
+
Current state.
|
357 |
+
t_old : float
|
358 |
+
Previous time. None if no steps were made yet.
|
359 |
+
step_size : float
|
360 |
+
Size of the last successful step. None if no steps were made yet.
|
361 |
+
nfev : int
|
362 |
+
Number evaluations of the system's right-hand side.
|
363 |
+
njev : int
|
364 |
+
Number of evaluations of the Jacobian.
|
365 |
+
Is always 0 for this solver as it does not use the Jacobian.
|
366 |
+
nlu : int
|
367 |
+
Number of LU decompositions. Is always 0 for this solver.
|
368 |
+
|
369 |
+
References
|
370 |
+
----------
|
371 |
+
.. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
|
372 |
+
formulae", Journal of Computational and Applied Mathematics, Vol. 6,
|
373 |
+
No. 1, pp. 19-26, 1980.
|
374 |
+
.. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
|
375 |
+
of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
|
376 |
+
"""
|
377 |
+
order = 5
|
378 |
+
error_estimator_order = 4
|
379 |
+
n_stages = 6
|
380 |
+
C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
|
381 |
+
A = np.array([
|
382 |
+
[0, 0, 0, 0, 0],
|
383 |
+
[1/5, 0, 0, 0, 0],
|
384 |
+
[3/40, 9/40, 0, 0, 0],
|
385 |
+
[44/45, -56/15, 32/9, 0, 0],
|
386 |
+
[19372/6561, -25360/2187, 64448/6561, -212/729, 0],
|
387 |
+
[9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
|
388 |
+
])
|
389 |
+
B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
|
390 |
+
E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
|
391 |
+
1/40])
|
392 |
+
# Corresponds to the optimum value of c_6 from [2]_.
|
393 |
+
P = np.array([
|
394 |
+
[1, -8048581381/2820520608, 8663915743/2820520608,
|
395 |
+
-12715105075/11282082432],
|
396 |
+
[0, 0, 0, 0],
|
397 |
+
[0, 131558114200/32700410799, -68118460800/10900136933,
|
398 |
+
87487479700/32700410799],
|
399 |
+
[0, -1754552775/470086768, 14199869525/1410260304,
|
400 |
+
-10690763975/1880347072],
|
401 |
+
[0, 127303824393/49829197408, -318862633887/49829197408,
|
402 |
+
701980252875 / 199316789632],
|
403 |
+
[0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
|
404 |
+
[0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
|
405 |
+
|
406 |
+
|
407 |
+
class DOP853(RungeKutta):
|
408 |
+
"""Explicit Runge-Kutta method of order 8.
|
409 |
+
|
410 |
+
This is a Python implementation of "DOP853" algorithm originally written
|
411 |
+
in Fortran [1]_, [2]_. Note that this is not a literal translation, but
|
412 |
+
the algorithmic core and coefficients are the same.
|
413 |
+
|
414 |
+
Can be applied in the complex domain.
|
415 |
+
|
416 |
+
Parameters
|
417 |
+
----------
|
418 |
+
fun : callable
|
419 |
+
Right-hand side of the system. The calling signature is ``fun(t, y)``.
|
420 |
+
Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
|
421 |
+
It can either have shape (n,); then ``fun`` must return array_like with
|
422 |
+
shape (n,). Alternatively it can have shape (n, k); then ``fun``
|
423 |
+
must return an array_like with shape (n, k), i.e. each column
|
424 |
+
corresponds to a single column in ``y``. The choice between the two
|
425 |
+
options is determined by `vectorized` argument (see below).
|
426 |
+
t0 : float
|
427 |
+
Initial time.
|
428 |
+
y0 : array_like, shape (n,)
|
429 |
+
Initial state.
|
430 |
+
t_bound : float
|
431 |
+
Boundary time - the integration won't continue beyond it. It also
|
432 |
+
determines the direction of the integration.
|
433 |
+
first_step : float or None, optional
|
434 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
435 |
+
should choose.
|
436 |
+
max_step : float, optional
|
437 |
+
Maximum allowed step size. Default is np.inf, i.e. the step size is not
|
438 |
+
bounded and determined solely by the solver.
|
439 |
+
rtol, atol : float and array_like, optional
|
440 |
+
Relative and absolute tolerances. The solver keeps the local error
|
441 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
442 |
+
relative accuracy (number of correct digits), while `atol` controls
|
443 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
444 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
445 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
446 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
447 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
448 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
449 |
+
than `atol`. If components of y have different scales, it might be
|
450 |
+
beneficial to set different `atol` values for different components by
|
451 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
452 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
453 |
+
vectorized : bool, optional
|
454 |
+
Whether `fun` is implemented in a vectorized fashion. Default is False.
|
455 |
+
|
456 |
+
Attributes
|
457 |
+
----------
|
458 |
+
n : int
|
459 |
+
Number of equations.
|
460 |
+
status : string
|
461 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
462 |
+
t_bound : float
|
463 |
+
Boundary time.
|
464 |
+
direction : float
|
465 |
+
Integration direction: +1 or -1.
|
466 |
+
t : float
|
467 |
+
Current time.
|
468 |
+
y : ndarray
|
469 |
+
Current state.
|
470 |
+
t_old : float
|
471 |
+
Previous time. None if no steps were made yet.
|
472 |
+
step_size : float
|
473 |
+
Size of the last successful step. None if no steps were made yet.
|
474 |
+
nfev : int
|
475 |
+
Number evaluations of the system's right-hand side.
|
476 |
+
njev : int
|
477 |
+
Number of evaluations of the Jacobian. Is always 0 for this solver
|
478 |
+
as it does not use the Jacobian.
|
479 |
+
nlu : int
|
480 |
+
Number of LU decompositions. Is always 0 for this solver.
|
481 |
+
|
482 |
+
References
|
483 |
+
----------
|
484 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
485 |
+
Equations I: Nonstiff Problems", Sec. II.
|
486 |
+
.. [2] `Page with original Fortran code of DOP853
|
487 |
+
<http://www.unige.ch/~hairer/software.html>`_.
|
488 |
+
"""
|
489 |
+
n_stages = dop853_coefficients.N_STAGES
|
490 |
+
order = 8
|
491 |
+
error_estimator_order = 7
|
492 |
+
A = dop853_coefficients.A[:n_stages, :n_stages]
|
493 |
+
B = dop853_coefficients.B
|
494 |
+
C = dop853_coefficients.C[:n_stages]
|
495 |
+
E3 = dop853_coefficients.E3
|
496 |
+
E5 = dop853_coefficients.E5
|
497 |
+
D = dop853_coefficients.D
|
498 |
+
|
499 |
+
A_EXTRA = dop853_coefficients.A[n_stages + 1:]
|
500 |
+
C_EXTRA = dop853_coefficients.C[n_stages + 1:]
|
501 |
+
|
502 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
503 |
+
rtol=1e-3, atol=1e-6, vectorized=False,
|
504 |
+
first_step=None, **extraneous):
|
505 |
+
super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
|
506 |
+
vectorized, first_step, **extraneous)
|
507 |
+
self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
|
508 |
+
self.n), dtype=self.y.dtype)
|
509 |
+
self.K = self.K_extended[:self.n_stages + 1]
|
510 |
+
|
511 |
+
def _estimate_error(self, K, h): # Left for testing purposes.
|
512 |
+
err5 = np.dot(K.T, self.E5)
|
513 |
+
err3 = np.dot(K.T, self.E3)
|
514 |
+
denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
|
515 |
+
correction_factor = np.ones_like(err5)
|
516 |
+
mask = denom > 0
|
517 |
+
correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
|
518 |
+
return h * err5 * correction_factor
|
519 |
+
|
520 |
+
def _estimate_error_norm(self, K, h, scale):
|
521 |
+
err5 = np.dot(K.T, self.E5) / scale
|
522 |
+
err3 = np.dot(K.T, self.E3) / scale
|
523 |
+
err5_norm_2 = np.linalg.norm(err5)**2
|
524 |
+
err3_norm_2 = np.linalg.norm(err3)**2
|
525 |
+
if err5_norm_2 == 0 and err3_norm_2 == 0:
|
526 |
+
return 0.0
|
527 |
+
denom = err5_norm_2 + 0.01 * err3_norm_2
|
528 |
+
return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
|
529 |
+
|
530 |
+
def _dense_output_impl(self):
|
531 |
+
K = self.K_extended
|
532 |
+
h = self.h_previous
|
533 |
+
for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
|
534 |
+
start=self.n_stages + 1):
|
535 |
+
dy = np.dot(K[:s].T, a[:s]) * h
|
536 |
+
K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
|
537 |
+
|
538 |
+
F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
|
539 |
+
dtype=self.y_old.dtype)
|
540 |
+
|
541 |
+
f_old = K[0]
|
542 |
+
delta_y = self.y - self.y_old
|
543 |
+
|
544 |
+
F[0] = delta_y
|
545 |
+
F[1] = h * f_old - delta_y
|
546 |
+
F[2] = 2 * delta_y - h * (self.f + f_old)
|
547 |
+
F[3:] = h * np.dot(self.D, K)
|
548 |
+
|
549 |
+
return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
|
550 |
+
|
551 |
+
|
552 |
+
class RkDenseOutput(DenseOutput):
|
553 |
+
def __init__(self, t_old, t, y_old, Q):
|
554 |
+
super().__init__(t_old, t)
|
555 |
+
self.h = t - t_old
|
556 |
+
self.Q = Q
|
557 |
+
self.order = Q.shape[1] - 1
|
558 |
+
self.y_old = y_old
|
559 |
+
|
560 |
+
def _call_impl(self, t):
|
561 |
+
x = (t - self.t_old) / self.h
|
562 |
+
if t.ndim == 0:
|
563 |
+
p = np.tile(x, self.order + 1)
|
564 |
+
p = np.cumprod(p)
|
565 |
+
else:
|
566 |
+
p = np.tile(x, (self.order + 1, 1))
|
567 |
+
p = np.cumprod(p, axis=0)
|
568 |
+
y = self.h * np.dot(self.Q, p)
|
569 |
+
if y.ndim == 2:
|
570 |
+
y += self.y_old[:, None]
|
571 |
+
else:
|
572 |
+
y += self.y_old
|
573 |
+
|
574 |
+
return y
|
575 |
+
|
576 |
+
|
577 |
+
class Dop853DenseOutput(DenseOutput):
|
578 |
+
def __init__(self, t_old, t, y_old, F):
|
579 |
+
super().__init__(t_old, t)
|
580 |
+
self.h = t - t_old
|
581 |
+
self.F = F
|
582 |
+
self.y_old = y_old
|
583 |
+
|
584 |
+
def _call_impl(self, t):
|
585 |
+
x = (t - self.t_old) / self.h
|
586 |
+
|
587 |
+
if t.ndim == 0:
|
588 |
+
y = np.zeros_like(self.y_old)
|
589 |
+
else:
|
590 |
+
x = x[:, None]
|
591 |
+
y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
|
592 |
+
|
593 |
+
for i, f in enumerate(reversed(self.F)):
|
594 |
+
y += f
|
595 |
+
if i % 2 == 0:
|
596 |
+
y *= x
|
597 |
+
else:
|
598 |
+
y *= 1 - x
|
599 |
+
y += self.y_old
|
600 |
+
|
601 |
+
return y.T
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc
ADDED
Binary file (29.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-310.pyc
ADDED
Binary file (1.92 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
ADDED
@@ -0,0 +1,1135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import product
|
2 |
+
from numpy.testing import (assert_, assert_allclose, assert_array_less,
|
3 |
+
assert_equal, assert_no_warnings, suppress_warnings)
|
4 |
+
import pytest
|
5 |
+
from pytest import raises as assert_raises
|
6 |
+
import numpy as np
|
7 |
+
from scipy.optimize._numdiff import group_columns
|
8 |
+
from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
|
9 |
+
from scipy.integrate import OdeSolution
|
10 |
+
from scipy.integrate._ivp.common import num_jac
|
11 |
+
from scipy.integrate._ivp.base import ConstantDenseOutput
|
12 |
+
from scipy.sparse import coo_matrix, csc_matrix
|
13 |
+
|
14 |
+
|
15 |
+
def fun_zero(t, y):
|
16 |
+
return np.zeros_like(y)
|
17 |
+
|
18 |
+
|
19 |
+
def fun_linear(t, y):
|
20 |
+
return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
|
21 |
+
|
22 |
+
|
23 |
+
def jac_linear():
|
24 |
+
return np.array([[-1, -5], [1, 1]])
|
25 |
+
|
26 |
+
|
27 |
+
def sol_linear(t):
|
28 |
+
return np.vstack((-5 * np.sin(2 * t),
|
29 |
+
2 * np.cos(2 * t) + np.sin(2 * t)))
|
30 |
+
|
31 |
+
|
32 |
+
def fun_rational(t, y):
|
33 |
+
return np.array([y[1] / t,
|
34 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
|
35 |
+
|
36 |
+
|
37 |
+
def fun_rational_vectorized(t, y):
|
38 |
+
return np.vstack((y[1] / t,
|
39 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
|
40 |
+
|
41 |
+
|
42 |
+
def jac_rational(t, y):
|
43 |
+
return np.array([
|
44 |
+
[0, 1 / t],
|
45 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
46 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
47 |
+
])
|
48 |
+
|
49 |
+
|
50 |
+
def jac_rational_sparse(t, y):
|
51 |
+
return csc_matrix([
|
52 |
+
[0, 1 / t],
|
53 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
54 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
55 |
+
])
|
56 |
+
|
57 |
+
|
58 |
+
def sol_rational(t):
|
59 |
+
return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
|
60 |
+
|
61 |
+
|
62 |
+
def fun_medazko(t, y):
|
63 |
+
n = y.shape[0] // 2
|
64 |
+
k = 100
|
65 |
+
c = 4
|
66 |
+
|
67 |
+
phi = 2 if t <= 5 else 0
|
68 |
+
y = np.hstack((phi, 0, y, y[-2]))
|
69 |
+
|
70 |
+
d = 1 / n
|
71 |
+
j = np.arange(n) + 1
|
72 |
+
alpha = 2 * (j * d - 1) ** 3 / c ** 2
|
73 |
+
beta = (j * d - 1) ** 4 / c ** 2
|
74 |
+
|
75 |
+
j_2_p1 = 2 * j + 2
|
76 |
+
j_2_m3 = 2 * j - 2
|
77 |
+
j_2_m1 = 2 * j
|
78 |
+
j_2 = 2 * j + 1
|
79 |
+
|
80 |
+
f = np.empty(2 * n)
|
81 |
+
f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
|
82 |
+
beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
|
83 |
+
k * y[j_2_m1] * y[j_2])
|
84 |
+
f[1::2] = -k * y[j_2] * y[j_2_m1]
|
85 |
+
|
86 |
+
return f
|
87 |
+
|
88 |
+
|
89 |
+
def medazko_sparsity(n):
|
90 |
+
cols = []
|
91 |
+
rows = []
|
92 |
+
|
93 |
+
i = np.arange(n) * 2
|
94 |
+
|
95 |
+
cols.append(i[1:])
|
96 |
+
rows.append(i[1:] - 2)
|
97 |
+
|
98 |
+
cols.append(i)
|
99 |
+
rows.append(i)
|
100 |
+
|
101 |
+
cols.append(i)
|
102 |
+
rows.append(i + 1)
|
103 |
+
|
104 |
+
cols.append(i[:-1])
|
105 |
+
rows.append(i[:-1] + 2)
|
106 |
+
|
107 |
+
i = np.arange(n) * 2 + 1
|
108 |
+
|
109 |
+
cols.append(i)
|
110 |
+
rows.append(i)
|
111 |
+
|
112 |
+
cols.append(i)
|
113 |
+
rows.append(i - 1)
|
114 |
+
|
115 |
+
cols = np.hstack(cols)
|
116 |
+
rows = np.hstack(rows)
|
117 |
+
|
118 |
+
return coo_matrix((np.ones_like(cols), (cols, rows)))
|
119 |
+
|
120 |
+
|
121 |
+
def fun_complex(t, y):
|
122 |
+
return -y
|
123 |
+
|
124 |
+
|
125 |
+
def jac_complex(t, y):
|
126 |
+
return -np.eye(y.shape[0])
|
127 |
+
|
128 |
+
|
129 |
+
def jac_complex_sparse(t, y):
|
130 |
+
return csc_matrix(jac_complex(t, y))
|
131 |
+
|
132 |
+
|
133 |
+
def sol_complex(t):
|
134 |
+
y = (0.5 + 1j) * np.exp(-t)
|
135 |
+
return y.reshape((1, -1))
|
136 |
+
|
137 |
+
|
138 |
+
def fun_event_dense_output_LSODA(t, y):
|
139 |
+
return y * (t - 2)
|
140 |
+
|
141 |
+
|
142 |
+
def jac_event_dense_output_LSODA(t, y):
|
143 |
+
return t - 2
|
144 |
+
|
145 |
+
|
146 |
+
def sol_event_dense_output_LSODA(t):
|
147 |
+
return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
|
148 |
+
|
149 |
+
|
150 |
+
def compute_error(y, y_true, rtol, atol):
|
151 |
+
e = (y - y_true) / (atol + rtol * np.abs(y_true))
|
152 |
+
return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
|
153 |
+
|
154 |
+
|
155 |
+
def test_integration():
|
156 |
+
rtol = 1e-3
|
157 |
+
atol = 1e-6
|
158 |
+
y0 = [1/3, 2/9]
|
159 |
+
|
160 |
+
for vectorized, method, t_span, jac in product(
|
161 |
+
[False, True],
|
162 |
+
['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
|
163 |
+
[[5, 9], [5, 1]],
|
164 |
+
[None, jac_rational, jac_rational_sparse]):
|
165 |
+
|
166 |
+
if vectorized:
|
167 |
+
fun = fun_rational_vectorized
|
168 |
+
else:
|
169 |
+
fun = fun_rational
|
170 |
+
|
171 |
+
with suppress_warnings() as sup:
|
172 |
+
sup.filter(UserWarning,
|
173 |
+
"The following arguments have no effect for a chosen "
|
174 |
+
"solver: `jac`")
|
175 |
+
res = solve_ivp(fun, t_span, y0, rtol=rtol,
|
176 |
+
atol=atol, method=method, dense_output=True,
|
177 |
+
jac=jac, vectorized=vectorized)
|
178 |
+
assert_equal(res.t[0], t_span[0])
|
179 |
+
assert_(res.t_events is None)
|
180 |
+
assert_(res.y_events is None)
|
181 |
+
assert_(res.success)
|
182 |
+
assert_equal(res.status, 0)
|
183 |
+
|
184 |
+
if method == 'DOP853':
|
185 |
+
# DOP853 spends more functions evaluation because it doesn't
|
186 |
+
# have enough time to develop big enough step size.
|
187 |
+
assert_(res.nfev < 50)
|
188 |
+
else:
|
189 |
+
assert_(res.nfev < 40)
|
190 |
+
|
191 |
+
if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
|
192 |
+
assert_equal(res.njev, 0)
|
193 |
+
assert_equal(res.nlu, 0)
|
194 |
+
else:
|
195 |
+
assert_(0 < res.njev < 3)
|
196 |
+
assert_(0 < res.nlu < 10)
|
197 |
+
|
198 |
+
y_true = sol_rational(res.t)
|
199 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
200 |
+
assert_(np.all(e < 5))
|
201 |
+
|
202 |
+
tc = np.linspace(*t_span)
|
203 |
+
yc_true = sol_rational(tc)
|
204 |
+
yc = res.sol(tc)
|
205 |
+
|
206 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
207 |
+
assert_(np.all(e < 5))
|
208 |
+
|
209 |
+
tc = (t_span[0] + t_span[-1]) / 2
|
210 |
+
yc_true = sol_rational(tc)
|
211 |
+
yc = res.sol(tc)
|
212 |
+
|
213 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
214 |
+
assert_(np.all(e < 5))
|
215 |
+
|
216 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
217 |
+
|
218 |
+
|
219 |
+
def test_integration_complex():
|
220 |
+
rtol = 1e-3
|
221 |
+
atol = 1e-6
|
222 |
+
y0 = [0.5 + 1j]
|
223 |
+
t_span = [0, 1]
|
224 |
+
tc = np.linspace(t_span[0], t_span[1])
|
225 |
+
for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
|
226 |
+
[None, jac_complex, jac_complex_sparse]):
|
227 |
+
with suppress_warnings() as sup:
|
228 |
+
sup.filter(UserWarning,
|
229 |
+
"The following arguments have no effect for a chosen "
|
230 |
+
"solver: `jac`")
|
231 |
+
res = solve_ivp(fun_complex, t_span, y0, method=method,
|
232 |
+
dense_output=True, rtol=rtol, atol=atol, jac=jac)
|
233 |
+
|
234 |
+
assert_equal(res.t[0], t_span[0])
|
235 |
+
assert_(res.t_events is None)
|
236 |
+
assert_(res.y_events is None)
|
237 |
+
assert_(res.success)
|
238 |
+
assert_equal(res.status, 0)
|
239 |
+
|
240 |
+
if method == 'DOP853':
|
241 |
+
assert res.nfev < 35
|
242 |
+
else:
|
243 |
+
assert res.nfev < 25
|
244 |
+
|
245 |
+
if method == 'BDF':
|
246 |
+
assert_equal(res.njev, 1)
|
247 |
+
assert res.nlu < 6
|
248 |
+
else:
|
249 |
+
assert res.njev == 0
|
250 |
+
assert res.nlu == 0
|
251 |
+
|
252 |
+
y_true = sol_complex(res.t)
|
253 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
254 |
+
assert np.all(e < 5)
|
255 |
+
|
256 |
+
yc_true = sol_complex(tc)
|
257 |
+
yc = res.sol(tc)
|
258 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
259 |
+
|
260 |
+
assert np.all(e < 5)
|
261 |
+
|
262 |
+
|
263 |
+
def test_integration_sparse_difference():
|
264 |
+
n = 200
|
265 |
+
t_span = [0, 20]
|
266 |
+
y0 = np.zeros(2 * n)
|
267 |
+
y0[1::2] = 1
|
268 |
+
sparsity = medazko_sparsity(n)
|
269 |
+
|
270 |
+
for method in ['BDF', 'Radau']:
|
271 |
+
res = solve_ivp(fun_medazko, t_span, y0, method=method,
|
272 |
+
jac_sparsity=sparsity)
|
273 |
+
|
274 |
+
assert_equal(res.t[0], t_span[0])
|
275 |
+
assert_(res.t_events is None)
|
276 |
+
assert_(res.y_events is None)
|
277 |
+
assert_(res.success)
|
278 |
+
assert_equal(res.status, 0)
|
279 |
+
|
280 |
+
assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
|
281 |
+
assert_allclose(res.y[79, -1], 0, atol=1e-3)
|
282 |
+
assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
|
283 |
+
assert_allclose(res.y[149, -1], 0, atol=1e-3)
|
284 |
+
assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
|
285 |
+
assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
|
286 |
+
assert_allclose(res.y[238, -1], 0, atol=1e-3)
|
287 |
+
assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
|
288 |
+
|
289 |
+
|
290 |
+
def test_integration_const_jac():
|
291 |
+
rtol = 1e-3
|
292 |
+
atol = 1e-6
|
293 |
+
y0 = [0, 2]
|
294 |
+
t_span = [0, 2]
|
295 |
+
J = jac_linear()
|
296 |
+
J_sparse = csc_matrix(J)
|
297 |
+
|
298 |
+
for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
|
299 |
+
res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
|
300 |
+
method=method, dense_output=True, jac=jac)
|
301 |
+
assert_equal(res.t[0], t_span[0])
|
302 |
+
assert_(res.t_events is None)
|
303 |
+
assert_(res.y_events is None)
|
304 |
+
assert_(res.success)
|
305 |
+
assert_equal(res.status, 0)
|
306 |
+
|
307 |
+
assert_(res.nfev < 100)
|
308 |
+
assert_equal(res.njev, 0)
|
309 |
+
assert_(0 < res.nlu < 15)
|
310 |
+
|
311 |
+
y_true = sol_linear(res.t)
|
312 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
313 |
+
assert_(np.all(e < 10))
|
314 |
+
|
315 |
+
tc = np.linspace(*t_span)
|
316 |
+
yc_true = sol_linear(tc)
|
317 |
+
yc = res.sol(tc)
|
318 |
+
|
319 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
320 |
+
assert_(np.all(e < 15))
|
321 |
+
|
322 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
|
323 |
+
|
324 |
+
|
325 |
+
@pytest.mark.slow
|
326 |
+
@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
|
327 |
+
def test_integration_stiff(method):
|
328 |
+
rtol = 1e-6
|
329 |
+
atol = 1e-6
|
330 |
+
y0 = [1e4, 0, 0]
|
331 |
+
tspan = [0, 1e8]
|
332 |
+
|
333 |
+
def fun_robertson(t, state):
|
334 |
+
x, y, z = state
|
335 |
+
return [
|
336 |
+
-0.04 * x + 1e4 * y * z,
|
337 |
+
0.04 * x - 1e4 * y * z - 3e7 * y * y,
|
338 |
+
3e7 * y * y,
|
339 |
+
]
|
340 |
+
|
341 |
+
res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
|
342 |
+
atol=atol, method=method)
|
343 |
+
|
344 |
+
# If the stiff mode is not activated correctly, these numbers will be much bigger
|
345 |
+
assert res.nfev < 5000
|
346 |
+
assert res.njev < 200
|
347 |
+
|
348 |
+
|
349 |
+
def test_events():
|
350 |
+
def event_rational_1(t, y):
|
351 |
+
return y[0] - y[1] ** 0.7
|
352 |
+
|
353 |
+
def event_rational_2(t, y):
|
354 |
+
return y[1] ** 0.6 - y[0]
|
355 |
+
|
356 |
+
def event_rational_3(t, y):
|
357 |
+
return t - 7.4
|
358 |
+
|
359 |
+
event_rational_3.terminal = True
|
360 |
+
|
361 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
362 |
+
res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
|
363 |
+
events=(event_rational_1, event_rational_2))
|
364 |
+
assert_equal(res.status, 0)
|
365 |
+
assert_equal(res.t_events[0].size, 1)
|
366 |
+
assert_equal(res.t_events[1].size, 1)
|
367 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
368 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
369 |
+
|
370 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
371 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
372 |
+
assert np.isclose(
|
373 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
374 |
+
assert np.isclose(
|
375 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
376 |
+
|
377 |
+
event_rational_1.direction = 1
|
378 |
+
event_rational_2.direction = 1
|
379 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
380 |
+
events=(event_rational_1, event_rational_2))
|
381 |
+
assert_equal(res.status, 0)
|
382 |
+
assert_equal(res.t_events[0].size, 1)
|
383 |
+
assert_equal(res.t_events[1].size, 0)
|
384 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
385 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
386 |
+
assert_equal(res.y_events[1].shape, (0,))
|
387 |
+
assert np.isclose(
|
388 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
389 |
+
|
390 |
+
event_rational_1.direction = -1
|
391 |
+
event_rational_2.direction = -1
|
392 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
393 |
+
events=(event_rational_1, event_rational_2))
|
394 |
+
assert_equal(res.status, 0)
|
395 |
+
assert_equal(res.t_events[0].size, 0)
|
396 |
+
assert_equal(res.t_events[1].size, 1)
|
397 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
398 |
+
assert_equal(res.y_events[0].shape, (0,))
|
399 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
400 |
+
assert np.isclose(
|
401 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
402 |
+
|
403 |
+
event_rational_1.direction = 0
|
404 |
+
event_rational_2.direction = 0
|
405 |
+
|
406 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
407 |
+
events=(event_rational_1, event_rational_2,
|
408 |
+
event_rational_3), dense_output=True)
|
409 |
+
assert_equal(res.status, 1)
|
410 |
+
assert_equal(res.t_events[0].size, 1)
|
411 |
+
assert_equal(res.t_events[1].size, 0)
|
412 |
+
assert_equal(res.t_events[2].size, 1)
|
413 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
414 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
415 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
416 |
+
assert_equal(res.y_events[1].shape, (0,))
|
417 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
418 |
+
assert np.isclose(
|
419 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
420 |
+
assert np.isclose(
|
421 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
422 |
+
|
423 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
424 |
+
events=event_rational_1, dense_output=True)
|
425 |
+
assert_equal(res.status, 0)
|
426 |
+
assert_equal(res.t_events[0].size, 1)
|
427 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
428 |
+
|
429 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
430 |
+
assert np.isclose(
|
431 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
432 |
+
|
433 |
+
# Also test that termination by event doesn't break interpolants.
|
434 |
+
tc = np.linspace(res.t[0], res.t[-1])
|
435 |
+
yc_true = sol_rational(tc)
|
436 |
+
yc = res.sol(tc)
|
437 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
438 |
+
assert_(np.all(e < 5))
|
439 |
+
|
440 |
+
# Test that the y_event matches solution
|
441 |
+
assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
|
442 |
+
rtol=1e-3, atol=1e-6)
|
443 |
+
|
444 |
+
# Test in backward direction.
|
445 |
+
event_rational_1.direction = 0
|
446 |
+
event_rational_2.direction = 0
|
447 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
448 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
449 |
+
events=(event_rational_1, event_rational_2))
|
450 |
+
assert_equal(res.status, 0)
|
451 |
+
assert_equal(res.t_events[0].size, 1)
|
452 |
+
assert_equal(res.t_events[1].size, 1)
|
453 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
454 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
455 |
+
|
456 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
457 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
458 |
+
assert np.isclose(
|
459 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
460 |
+
assert np.isclose(
|
461 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
462 |
+
|
463 |
+
event_rational_1.direction = -1
|
464 |
+
event_rational_2.direction = -1
|
465 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
466 |
+
events=(event_rational_1, event_rational_2))
|
467 |
+
assert_equal(res.status, 0)
|
468 |
+
assert_equal(res.t_events[0].size, 1)
|
469 |
+
assert_equal(res.t_events[1].size, 0)
|
470 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
471 |
+
|
472 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
473 |
+
assert_equal(res.y_events[1].shape, (0,))
|
474 |
+
assert np.isclose(
|
475 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
476 |
+
|
477 |
+
event_rational_1.direction = 1
|
478 |
+
event_rational_2.direction = 1
|
479 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
480 |
+
events=(event_rational_1, event_rational_2))
|
481 |
+
assert_equal(res.status, 0)
|
482 |
+
assert_equal(res.t_events[0].size, 0)
|
483 |
+
assert_equal(res.t_events[1].size, 1)
|
484 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
485 |
+
|
486 |
+
assert_equal(res.y_events[0].shape, (0,))
|
487 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
488 |
+
assert np.isclose(
|
489 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
490 |
+
|
491 |
+
event_rational_1.direction = 0
|
492 |
+
event_rational_2.direction = 0
|
493 |
+
|
494 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
495 |
+
events=(event_rational_1, event_rational_2,
|
496 |
+
event_rational_3), dense_output=True)
|
497 |
+
assert_equal(res.status, 1)
|
498 |
+
assert_equal(res.t_events[0].size, 0)
|
499 |
+
assert_equal(res.t_events[1].size, 1)
|
500 |
+
assert_equal(res.t_events[2].size, 1)
|
501 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
502 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
503 |
+
|
504 |
+
assert_equal(res.y_events[0].shape, (0,))
|
505 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
506 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
507 |
+
assert np.isclose(
|
508 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
509 |
+
assert np.isclose(
|
510 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
511 |
+
|
512 |
+
# Also test that termination by event doesn't break interpolants.
|
513 |
+
tc = np.linspace(res.t[-1], res.t[0])
|
514 |
+
yc_true = sol_rational(tc)
|
515 |
+
yc = res.sol(tc)
|
516 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
517 |
+
assert_(np.all(e < 5))
|
518 |
+
|
519 |
+
assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
|
520 |
+
rtol=1e-3, atol=1e-6)
|
521 |
+
assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
|
522 |
+
rtol=1e-3, atol=1e-6)
|
523 |
+
|
524 |
+
|
525 |
+
def _get_harmonic_oscillator():
|
526 |
+
def f(t, y):
|
527 |
+
return [y[1], -y[0]]
|
528 |
+
|
529 |
+
def event(t, y):
|
530 |
+
return y[0]
|
531 |
+
|
532 |
+
return f, event
|
533 |
+
|
534 |
+
|
535 |
+
@pytest.mark.parametrize('n_events', [3, 4])
|
536 |
+
def test_event_terminal_integer(n_events):
|
537 |
+
f, event = _get_harmonic_oscillator()
|
538 |
+
event.terminal = n_events
|
539 |
+
res = solve_ivp(f, (0, 100), [1, 0], events=event)
|
540 |
+
assert len(res.t_events[0]) == n_events
|
541 |
+
assert len(res.y_events[0]) == n_events
|
542 |
+
assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
|
543 |
+
|
544 |
+
|
545 |
+
def test_event_terminal_iv():
|
546 |
+
f, event = _get_harmonic_oscillator()
|
547 |
+
args = (f, (0, 100), [1, 0])
|
548 |
+
|
549 |
+
event.terminal = None
|
550 |
+
res = solve_ivp(*args, events=event)
|
551 |
+
event.terminal = 0
|
552 |
+
ref = solve_ivp(*args, events=event)
|
553 |
+
assert_allclose(res.t_events, ref.t_events)
|
554 |
+
|
555 |
+
message = "The `terminal` attribute..."
|
556 |
+
event.terminal = -1
|
557 |
+
with pytest.raises(ValueError, match=message):
|
558 |
+
solve_ivp(*args, events=event)
|
559 |
+
event.terminal = 3.5
|
560 |
+
with pytest.raises(ValueError, match=message):
|
561 |
+
solve_ivp(*args, events=event)
|
562 |
+
|
563 |
+
|
564 |
+
def test_max_step():
|
565 |
+
rtol = 1e-3
|
566 |
+
atol = 1e-6
|
567 |
+
y0 = [1/3, 2/9]
|
568 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
569 |
+
for t_span in ([5, 9], [5, 1]):
|
570 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
571 |
+
max_step=0.5, atol=atol, method=method,
|
572 |
+
dense_output=True)
|
573 |
+
assert_equal(res.t[0], t_span[0])
|
574 |
+
assert_equal(res.t[-1], t_span[-1])
|
575 |
+
assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
|
576 |
+
assert_(res.t_events is None)
|
577 |
+
assert_(res.success)
|
578 |
+
assert_equal(res.status, 0)
|
579 |
+
|
580 |
+
y_true = sol_rational(res.t)
|
581 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
582 |
+
assert_(np.all(e < 5))
|
583 |
+
|
584 |
+
tc = np.linspace(*t_span)
|
585 |
+
yc_true = sol_rational(tc)
|
586 |
+
yc = res.sol(tc)
|
587 |
+
|
588 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
589 |
+
assert_(np.all(e < 5))
|
590 |
+
|
591 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
592 |
+
|
593 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
594 |
+
t_span[1], max_step=-1)
|
595 |
+
|
596 |
+
if method is not LSODA:
|
597 |
+
solver = method(fun_rational, t_span[0], y0, t_span[1],
|
598 |
+
rtol=rtol, atol=atol, max_step=1e-20)
|
599 |
+
message = solver.step()
|
600 |
+
|
601 |
+
assert_equal(solver.status, 'failed')
|
602 |
+
assert_("step size is less" in message)
|
603 |
+
assert_raises(RuntimeError, solver.step)
|
604 |
+
|
605 |
+
|
606 |
+
def test_first_step():
|
607 |
+
rtol = 1e-3
|
608 |
+
atol = 1e-6
|
609 |
+
y0 = [1/3, 2/9]
|
610 |
+
first_step = 0.1
|
611 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
612 |
+
for t_span in ([5, 9], [5, 1]):
|
613 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
614 |
+
max_step=0.5, atol=atol, method=method,
|
615 |
+
dense_output=True, first_step=first_step)
|
616 |
+
|
617 |
+
assert_equal(res.t[0], t_span[0])
|
618 |
+
assert_equal(res.t[-1], t_span[-1])
|
619 |
+
assert_allclose(first_step, np.abs(res.t[1] - 5))
|
620 |
+
assert_(res.t_events is None)
|
621 |
+
assert_(res.success)
|
622 |
+
assert_equal(res.status, 0)
|
623 |
+
|
624 |
+
y_true = sol_rational(res.t)
|
625 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
626 |
+
assert_(np.all(e < 5))
|
627 |
+
|
628 |
+
tc = np.linspace(*t_span)
|
629 |
+
yc_true = sol_rational(tc)
|
630 |
+
yc = res.sol(tc)
|
631 |
+
|
632 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
633 |
+
assert_(np.all(e < 5))
|
634 |
+
|
635 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
636 |
+
|
637 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
638 |
+
t_span[1], first_step=-1)
|
639 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
640 |
+
t_span[1], first_step=5)
|
641 |
+
|
642 |
+
|
643 |
+
def test_t_eval():
|
644 |
+
rtol = 1e-3
|
645 |
+
atol = 1e-6
|
646 |
+
y0 = [1/3, 2/9]
|
647 |
+
for t_span in ([5, 9], [5, 1]):
|
648 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
649 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
650 |
+
t_eval=t_eval)
|
651 |
+
assert_equal(res.t, t_eval)
|
652 |
+
assert_(res.t_events is None)
|
653 |
+
assert_(res.success)
|
654 |
+
assert_equal(res.status, 0)
|
655 |
+
|
656 |
+
y_true = sol_rational(res.t)
|
657 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
658 |
+
assert_(np.all(e < 5))
|
659 |
+
|
660 |
+
t_eval = [5, 5.01, 7, 8, 8.01, 9]
|
661 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
662 |
+
t_eval=t_eval)
|
663 |
+
assert_equal(res.t, t_eval)
|
664 |
+
assert_(res.t_events is None)
|
665 |
+
assert_(res.success)
|
666 |
+
assert_equal(res.status, 0)
|
667 |
+
|
668 |
+
y_true = sol_rational(res.t)
|
669 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
670 |
+
assert_(np.all(e < 5))
|
671 |
+
|
672 |
+
t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
|
673 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
674 |
+
t_eval=t_eval)
|
675 |
+
assert_equal(res.t, t_eval)
|
676 |
+
assert_(res.t_events is None)
|
677 |
+
assert_(res.success)
|
678 |
+
assert_equal(res.status, 0)
|
679 |
+
|
680 |
+
t_eval = [5.01, 7, 8, 8.01]
|
681 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
682 |
+
t_eval=t_eval)
|
683 |
+
assert_equal(res.t, t_eval)
|
684 |
+
assert_(res.t_events is None)
|
685 |
+
assert_(res.success)
|
686 |
+
assert_equal(res.status, 0)
|
687 |
+
|
688 |
+
y_true = sol_rational(res.t)
|
689 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
690 |
+
assert_(np.all(e < 5))
|
691 |
+
|
692 |
+
t_eval = [4.99, 3, 1.5, 1.1, 1.01]
|
693 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
694 |
+
t_eval=t_eval)
|
695 |
+
assert_equal(res.t, t_eval)
|
696 |
+
assert_(res.t_events is None)
|
697 |
+
assert_(res.success)
|
698 |
+
assert_equal(res.status, 0)
|
699 |
+
|
700 |
+
t_eval = [4, 6]
|
701 |
+
assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
|
702 |
+
rtol=rtol, atol=atol, t_eval=t_eval)
|
703 |
+
|
704 |
+
|
705 |
+
def test_t_eval_dense_output():
|
706 |
+
rtol = 1e-3
|
707 |
+
atol = 1e-6
|
708 |
+
y0 = [1/3, 2/9]
|
709 |
+
t_span = [5, 9]
|
710 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
711 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
712 |
+
t_eval=t_eval)
|
713 |
+
res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
714 |
+
t_eval=t_eval, dense_output=True)
|
715 |
+
assert_equal(res.t, t_eval)
|
716 |
+
assert_(res.t_events is None)
|
717 |
+
assert_(res.success)
|
718 |
+
assert_equal(res.status, 0)
|
719 |
+
|
720 |
+
assert_equal(res.t, res_d.t)
|
721 |
+
assert_equal(res.y, res_d.y)
|
722 |
+
assert_(res_d.t_events is None)
|
723 |
+
assert_(res_d.success)
|
724 |
+
assert_equal(res_d.status, 0)
|
725 |
+
|
726 |
+
# if t and y are equal only test values for one case
|
727 |
+
y_true = sol_rational(res.t)
|
728 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
729 |
+
assert_(np.all(e < 5))
|
730 |
+
|
731 |
+
|
732 |
+
def test_t_eval_early_event():
|
733 |
+
def early_event(t, y):
|
734 |
+
return t - 7
|
735 |
+
|
736 |
+
early_event.terminal = True
|
737 |
+
|
738 |
+
rtol = 1e-3
|
739 |
+
atol = 1e-6
|
740 |
+
y0 = [1/3, 2/9]
|
741 |
+
t_span = [5, 9]
|
742 |
+
t_eval = np.linspace(7.5, 9, 16)
|
743 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
744 |
+
with suppress_warnings() as sup:
|
745 |
+
sup.filter(UserWarning,
|
746 |
+
"The following arguments have no effect for a chosen "
|
747 |
+
"solver: `jac`")
|
748 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
749 |
+
method=method, t_eval=t_eval, events=early_event,
|
750 |
+
jac=jac_rational)
|
751 |
+
assert res.success
|
752 |
+
assert res.message == 'A termination event occurred.'
|
753 |
+
assert res.status == 1
|
754 |
+
assert not res.t and not res.y
|
755 |
+
assert len(res.t_events) == 1
|
756 |
+
assert res.t_events[0].size == 1
|
757 |
+
assert res.t_events[0][0] == 7
|
758 |
+
|
759 |
+
|
760 |
+
def test_event_dense_output_LSODA():
|
761 |
+
def event_lsoda(t, y):
|
762 |
+
return y[0] - 2.02e-5
|
763 |
+
|
764 |
+
rtol = 1e-3
|
765 |
+
atol = 1e-6
|
766 |
+
y0 = [0.05]
|
767 |
+
t_span = [-2, 2]
|
768 |
+
first_step = 1e-3
|
769 |
+
res = solve_ivp(
|
770 |
+
fun_event_dense_output_LSODA,
|
771 |
+
t_span,
|
772 |
+
y0,
|
773 |
+
method="LSODA",
|
774 |
+
dense_output=True,
|
775 |
+
events=event_lsoda,
|
776 |
+
first_step=first_step,
|
777 |
+
max_step=1,
|
778 |
+
rtol=rtol,
|
779 |
+
atol=atol,
|
780 |
+
jac=jac_event_dense_output_LSODA,
|
781 |
+
)
|
782 |
+
|
783 |
+
assert_equal(res.t[0], t_span[0])
|
784 |
+
assert_equal(res.t[-1], t_span[-1])
|
785 |
+
assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
|
786 |
+
assert res.success
|
787 |
+
assert_equal(res.status, 0)
|
788 |
+
|
789 |
+
y_true = sol_event_dense_output_LSODA(res.t)
|
790 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
791 |
+
assert_array_less(e, 5)
|
792 |
+
|
793 |
+
tc = np.linspace(*t_span)
|
794 |
+
yc_true = sol_event_dense_output_LSODA(tc)
|
795 |
+
yc = res.sol(tc)
|
796 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
797 |
+
assert_array_less(e, 5)
|
798 |
+
|
799 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
800 |
+
|
801 |
+
|
802 |
+
def test_no_integration():
|
803 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
804 |
+
sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
|
805 |
+
method=method, dense_output=True)
|
806 |
+
assert_equal(sol.sol(4), [2, 3])
|
807 |
+
assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
|
808 |
+
|
809 |
+
|
810 |
+
def test_no_integration_class():
|
811 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
812 |
+
solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
|
813 |
+
solver.step()
|
814 |
+
assert_equal(solver.status, 'finished')
|
815 |
+
sol = solver.dense_output()
|
816 |
+
assert_equal(sol(0.0), [10.0, 0.0])
|
817 |
+
assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
|
818 |
+
|
819 |
+
solver = method(lambda t, y: -y, 0.0, [], np.inf)
|
820 |
+
solver.step()
|
821 |
+
assert_equal(solver.status, 'finished')
|
822 |
+
sol = solver.dense_output()
|
823 |
+
assert_equal(sol(100.0), [])
|
824 |
+
assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
|
825 |
+
|
826 |
+
|
827 |
+
def test_empty():
|
828 |
+
def fun(t, y):
|
829 |
+
return np.zeros((0,))
|
830 |
+
|
831 |
+
y0 = np.zeros((0,))
|
832 |
+
|
833 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
834 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
|
835 |
+
method=method, dense_output=True)
|
836 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
837 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
838 |
+
|
839 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
840 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
|
841 |
+
method=method, dense_output=True)
|
842 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
843 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
844 |
+
|
845 |
+
|
846 |
+
def test_ConstantDenseOutput():
|
847 |
+
sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
|
848 |
+
assert_allclose(sol(1.5), [1, 2])
|
849 |
+
assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
|
850 |
+
|
851 |
+
sol = ConstantDenseOutput(0, 1, np.array([]))
|
852 |
+
assert_allclose(sol(1.5), np.empty(0))
|
853 |
+
assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
|
854 |
+
|
855 |
+
|
856 |
+
def test_classes():
|
857 |
+
y0 = [1 / 3, 2 / 9]
|
858 |
+
for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
859 |
+
solver = cls(fun_rational, 5, y0, np.inf)
|
860 |
+
assert_equal(solver.n, 2)
|
861 |
+
assert_equal(solver.status, 'running')
|
862 |
+
assert_equal(solver.t_bound, np.inf)
|
863 |
+
assert_equal(solver.direction, 1)
|
864 |
+
assert_equal(solver.t, 5)
|
865 |
+
assert_equal(solver.y, y0)
|
866 |
+
assert_(solver.step_size is None)
|
867 |
+
if cls is not LSODA:
|
868 |
+
assert_(solver.nfev > 0)
|
869 |
+
assert_(solver.njev >= 0)
|
870 |
+
assert_equal(solver.nlu, 0)
|
871 |
+
else:
|
872 |
+
assert_equal(solver.nfev, 0)
|
873 |
+
assert_equal(solver.njev, 0)
|
874 |
+
assert_equal(solver.nlu, 0)
|
875 |
+
|
876 |
+
assert_raises(RuntimeError, solver.dense_output)
|
877 |
+
|
878 |
+
message = solver.step()
|
879 |
+
assert_equal(solver.status, 'running')
|
880 |
+
assert_equal(message, None)
|
881 |
+
assert_equal(solver.n, 2)
|
882 |
+
assert_equal(solver.t_bound, np.inf)
|
883 |
+
assert_equal(solver.direction, 1)
|
884 |
+
assert_(solver.t > 5)
|
885 |
+
assert_(not np.all(np.equal(solver.y, y0)))
|
886 |
+
assert_(solver.step_size > 0)
|
887 |
+
assert_(solver.nfev > 0)
|
888 |
+
assert_(solver.njev >= 0)
|
889 |
+
assert_(solver.nlu >= 0)
|
890 |
+
sol = solver.dense_output()
|
891 |
+
assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
|
892 |
+
|
893 |
+
|
894 |
+
def test_OdeSolution():
|
895 |
+
ts = np.array([0, 2, 5], dtype=float)
|
896 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
897 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
898 |
+
|
899 |
+
sol = OdeSolution(ts, [s1, s2])
|
900 |
+
|
901 |
+
assert_equal(sol(-1), [-1])
|
902 |
+
assert_equal(sol(1), [-1])
|
903 |
+
assert_equal(sol(2), [-1])
|
904 |
+
assert_equal(sol(3), [1])
|
905 |
+
assert_equal(sol(5), [1])
|
906 |
+
assert_equal(sol(6), [1])
|
907 |
+
|
908 |
+
assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
|
909 |
+
np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
|
910 |
+
|
911 |
+
ts = np.array([10, 4, -3])
|
912 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
913 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
914 |
+
|
915 |
+
sol = OdeSolution(ts, [s1, s2])
|
916 |
+
assert_equal(sol(11), [-1])
|
917 |
+
assert_equal(sol(10), [-1])
|
918 |
+
assert_equal(sol(5), [-1])
|
919 |
+
assert_equal(sol(4), [-1])
|
920 |
+
assert_equal(sol(0), [1])
|
921 |
+
assert_equal(sol(-3), [1])
|
922 |
+
assert_equal(sol(-4), [1])
|
923 |
+
|
924 |
+
assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
|
925 |
+
np.array([[-1, 1, -1, 1, -1, 1, -1]]))
|
926 |
+
|
927 |
+
ts = np.array([1, 1])
|
928 |
+
s = ConstantDenseOutput(1, 1, np.array([10]))
|
929 |
+
sol = OdeSolution(ts, [s])
|
930 |
+
assert_equal(sol(0), [10])
|
931 |
+
assert_equal(sol(1), [10])
|
932 |
+
assert_equal(sol(2), [10])
|
933 |
+
|
934 |
+
assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
|
935 |
+
|
936 |
+
|
937 |
+
def test_num_jac():
|
938 |
+
def fun(t, y):
|
939 |
+
return np.vstack([
|
940 |
+
-0.04 * y[0] + 1e4 * y[1] * y[2],
|
941 |
+
0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
|
942 |
+
3e7 * y[1] ** 2
|
943 |
+
])
|
944 |
+
|
945 |
+
def jac(t, y):
|
946 |
+
return np.array([
|
947 |
+
[-0.04, 1e4 * y[2], 1e4 * y[1]],
|
948 |
+
[0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
|
949 |
+
[0, 6e7 * y[1], 0]
|
950 |
+
])
|
951 |
+
|
952 |
+
t = 1
|
953 |
+
y = np.array([1, 0, 0])
|
954 |
+
J_true = jac(t, y)
|
955 |
+
threshold = 1e-5
|
956 |
+
f = fun(t, y).ravel()
|
957 |
+
|
958 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, None)
|
959 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
960 |
+
|
961 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, factor)
|
962 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
963 |
+
|
964 |
+
|
965 |
+
def test_num_jac_sparse():
|
966 |
+
def fun(t, y):
|
967 |
+
e = y[1:]**3 - y[:-1]**2
|
968 |
+
z = np.zeros(y.shape[1])
|
969 |
+
return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
|
970 |
+
|
971 |
+
def structure(n):
|
972 |
+
A = np.zeros((n, n), dtype=int)
|
973 |
+
A[0, 0] = 1
|
974 |
+
A[0, 1] = 1
|
975 |
+
for i in range(1, n - 1):
|
976 |
+
A[i, i - 1: i + 2] = 1
|
977 |
+
A[-1, -1] = 1
|
978 |
+
A[-1, -2] = 1
|
979 |
+
|
980 |
+
return A
|
981 |
+
|
982 |
+
np.random.seed(0)
|
983 |
+
n = 20
|
984 |
+
y = np.random.randn(n)
|
985 |
+
A = structure(n)
|
986 |
+
groups = group_columns(A)
|
987 |
+
|
988 |
+
f = fun(0, y[:, None]).ravel()
|
989 |
+
|
990 |
+
# Compare dense and sparse results, assuming that dense implementation
|
991 |
+
# is correct (as it is straightforward).
|
992 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
|
993 |
+
sparsity=(A, groups))
|
994 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
|
995 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
996 |
+
rtol=1e-12, atol=1e-14)
|
997 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
998 |
+
|
999 |
+
# Take small factors to trigger their recomputing inside.
|
1000 |
+
factor = np.random.uniform(0, 1e-12, size=n)
|
1001 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
|
1002 |
+
sparsity=(A, groups))
|
1003 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
|
1004 |
+
|
1005 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
1006 |
+
rtol=1e-12, atol=1e-14)
|
1007 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
1008 |
+
|
1009 |
+
|
1010 |
+
def test_args():
|
1011 |
+
|
1012 |
+
# sys3 is actually two decoupled systems. (x, y) form a
|
1013 |
+
# linear oscillator, while z is a nonlinear first order
|
1014 |
+
# system with equilibria at z=0 and z=1. If k > 0, z=1
|
1015 |
+
# is stable and z=0 is unstable.
|
1016 |
+
|
1017 |
+
def sys3(t, w, omega, k, zfinal):
|
1018 |
+
x, y, z = w
|
1019 |
+
return [-omega*y, omega*x, k*z*(1 - z)]
|
1020 |
+
|
1021 |
+
def sys3_jac(t, w, omega, k, zfinal):
|
1022 |
+
x, y, z = w
|
1023 |
+
J = np.array([[0, -omega, 0],
|
1024 |
+
[omega, 0, 0],
|
1025 |
+
[0, 0, k*(1 - 2*z)]])
|
1026 |
+
return J
|
1027 |
+
|
1028 |
+
def sys3_x0decreasing(t, w, omega, k, zfinal):
|
1029 |
+
x, y, z = w
|
1030 |
+
return x
|
1031 |
+
|
1032 |
+
def sys3_y0increasing(t, w, omega, k, zfinal):
|
1033 |
+
x, y, z = w
|
1034 |
+
return y
|
1035 |
+
|
1036 |
+
def sys3_zfinal(t, w, omega, k, zfinal):
|
1037 |
+
x, y, z = w
|
1038 |
+
return z - zfinal
|
1039 |
+
|
1040 |
+
# Set the event flags for the event functions.
|
1041 |
+
sys3_x0decreasing.direction = -1
|
1042 |
+
sys3_y0increasing.direction = 1
|
1043 |
+
sys3_zfinal.terminal = True
|
1044 |
+
|
1045 |
+
omega = 2
|
1046 |
+
k = 4
|
1047 |
+
|
1048 |
+
tfinal = 5
|
1049 |
+
zfinal = 0.99
|
1050 |
+
# Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
|
1051 |
+
# The condition z(tfinal) = zfinal is the terminal event.
|
1052 |
+
z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
|
1053 |
+
|
1054 |
+
w0 = [0, -1, z0]
|
1055 |
+
|
1056 |
+
# Provide the jac argument and use the Radau method to ensure that the use
|
1057 |
+
# of the Jacobian function is exercised.
|
1058 |
+
# If event handling is working, the solution will stop at tfinal, not tend.
|
1059 |
+
tend = 2*tfinal
|
1060 |
+
sol = solve_ivp(sys3, [0, tend], w0,
|
1061 |
+
events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
|
1062 |
+
dense_output=True, args=(omega, k, zfinal),
|
1063 |
+
method='Radau', jac=sys3_jac,
|
1064 |
+
rtol=1e-10, atol=1e-13)
|
1065 |
+
|
1066 |
+
# Check that we got the expected events at the expected times.
|
1067 |
+
x0events_t = sol.t_events[0]
|
1068 |
+
y0events_t = sol.t_events[1]
|
1069 |
+
zfinalevents_t = sol.t_events[2]
|
1070 |
+
assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
|
1071 |
+
assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
|
1072 |
+
assert_allclose(zfinalevents_t, [tfinal])
|
1073 |
+
|
1074 |
+
# Check that the solution agrees with the known exact solution.
|
1075 |
+
t = np.linspace(0, zfinalevents_t[0], 250)
|
1076 |
+
w = sol.sol(t)
|
1077 |
+
assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
|
1078 |
+
assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
|
1079 |
+
assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
|
1080 |
+
rtol=1e-9, atol=1e-12)
|
1081 |
+
|
1082 |
+
# Check that the state variables have the expected values at the events.
|
1083 |
+
x0events = sol.sol(x0events_t)
|
1084 |
+
y0events = sol.sol(y0events_t)
|
1085 |
+
zfinalevents = sol.sol(zfinalevents_t)
|
1086 |
+
assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
|
1087 |
+
assert_allclose(x0events[1], np.ones_like(x0events[1]))
|
1088 |
+
assert_allclose(y0events[0], np.ones_like(y0events[0]))
|
1089 |
+
assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
|
1090 |
+
assert_allclose(zfinalevents[2], [zfinal])
|
1091 |
+
|
1092 |
+
|
1093 |
+
def test_array_rtol():
|
1094 |
+
# solve_ivp had a bug with array_like `rtol`; see gh-15482
|
1095 |
+
# check that it's fixed
|
1096 |
+
def f(t, y):
|
1097 |
+
return y[0], y[1]
|
1098 |
+
|
1099 |
+
# no warning (or error) when `rtol` is array_like
|
1100 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
|
1101 |
+
err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
1102 |
+
|
1103 |
+
# warning when an element of `rtol` is too small
|
1104 |
+
with pytest.warns(UserWarning, match="At least one element..."):
|
1105 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
|
1106 |
+
err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
1107 |
+
|
1108 |
+
# tighter rtol improves the error
|
1109 |
+
assert err2 < err1
|
1110 |
+
|
1111 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
|
1112 |
+
def test_integration_zero_rhs(method):
|
1113 |
+
result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
|
1114 |
+
assert_(result.success)
|
1115 |
+
assert_equal(result.status, 0)
|
1116 |
+
assert_allclose(result.y, 1.0, rtol=1e-15)
|
1117 |
+
|
1118 |
+
|
1119 |
+
def test_args_single_value():
|
1120 |
+
def fun_with_arg(t, y, a):
|
1121 |
+
return a*y
|
1122 |
+
|
1123 |
+
message = "Supplied 'args' cannot be unpacked."
|
1124 |
+
with pytest.raises(TypeError, match=message):
|
1125 |
+
solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
|
1126 |
+
|
1127 |
+
sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
|
1128 |
+
assert_allclose(sol.y[0, -1], np.exp(-0.1))
|
1129 |
+
|
1130 |
+
@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
|
1131 |
+
def test_initial_state_finiteness(f0_fill):
|
1132 |
+
# regression test for gh-17846
|
1133 |
+
msg = "All components of the initial state `y0` must be finite."
|
1134 |
+
with pytest.raises(ValueError, match=msg):
|
1135 |
+
solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from numpy.testing import assert_allclose, assert_
|
3 |
+
import numpy as np
|
4 |
+
from scipy.integrate import RK23, RK45, DOP853
|
5 |
+
from scipy.integrate._ivp import dop853_coefficients
|
6 |
+
|
7 |
+
|
8 |
+
@pytest.mark.parametrize("solver", [RK23, RK45, DOP853])
|
9 |
+
def test_coefficient_properties(solver):
|
10 |
+
assert_allclose(np.sum(solver.B), 1, rtol=1e-15)
|
11 |
+
assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14)
|
12 |
+
|
13 |
+
|
14 |
+
def test_coefficient_properties_dop853():
|
15 |
+
assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15)
|
16 |
+
assert_allclose(np.sum(dop853_coefficients.A, axis=1),
|
17 |
+
dop853_coefficients.C,
|
18 |
+
rtol=1e-14)
|
19 |
+
|
20 |
+
|
21 |
+
@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
|
22 |
+
def test_error_estimation(solver_class):
|
23 |
+
step = 0.2
|
24 |
+
solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step)
|
25 |
+
solver.step()
|
26 |
+
error_estimate = solver._estimate_error(solver.K, step)
|
27 |
+
error = solver.y - np.exp([step])
|
28 |
+
assert_(np.abs(error) < np.abs(error_estimate))
|
29 |
+
|
30 |
+
|
31 |
+
@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
|
32 |
+
def test_error_estimation_complex(solver_class):
|
33 |
+
h = 0.2
|
34 |
+
solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h)
|
35 |
+
solver.step()
|
36 |
+
err_norm = solver._estimate_error_norm(solver.K, h, scale=[1])
|
37 |
+
assert np.isrealobj(err_norm)
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_ode.py
ADDED
@@ -0,0 +1,1376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Authors: Pearu Peterson, Pauli Virtanen, John Travers
|
2 |
+
"""
|
3 |
+
First-order ODE integrators.
|
4 |
+
|
5 |
+
User-friendly interface to various numerical integrators for solving a
|
6 |
+
system of first order ODEs with prescribed initial conditions::
|
7 |
+
|
8 |
+
d y(t)[i]
|
9 |
+
--------- = f(t,y(t))[i],
|
10 |
+
d t
|
11 |
+
|
12 |
+
y(t=0)[i] = y0[i],
|
13 |
+
|
14 |
+
where::
|
15 |
+
|
16 |
+
i = 0, ..., len(y0) - 1
|
17 |
+
|
18 |
+
class ode
|
19 |
+
---------
|
20 |
+
|
21 |
+
A generic interface class to numeric integrators. It has the following
|
22 |
+
methods::
|
23 |
+
|
24 |
+
integrator = ode(f, jac=None)
|
25 |
+
integrator = integrator.set_integrator(name, **params)
|
26 |
+
integrator = integrator.set_initial_value(y0, t0=0.0)
|
27 |
+
integrator = integrator.set_f_params(*args)
|
28 |
+
integrator = integrator.set_jac_params(*args)
|
29 |
+
y1 = integrator.integrate(t1, step=False, relax=False)
|
30 |
+
flag = integrator.successful()
|
31 |
+
|
32 |
+
class complex_ode
|
33 |
+
-----------------
|
34 |
+
|
35 |
+
This class has the same generic interface as ode, except it can handle complex
|
36 |
+
f, y and Jacobians by transparently translating them into the equivalent
|
37 |
+
real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
|
38 |
+
an alternative to ode with the zvode solver, sometimes performing better.
|
39 |
+
"""
|
40 |
+
# XXX: Integrators must have:
|
41 |
+
# ===========================
|
42 |
+
# cvode - C version of vode and vodpk with many improvements.
|
43 |
+
# Get it from http://www.netlib.org/ode/cvode.tar.gz.
|
44 |
+
# To wrap cvode to Python, one must write the extension module by
|
45 |
+
# hand. Its interface is too much 'advanced C' that using f2py
|
46 |
+
# would be too complicated (or impossible).
|
47 |
+
#
|
48 |
+
# How to define a new integrator:
|
49 |
+
# ===============================
|
50 |
+
#
|
51 |
+
# class myodeint(IntegratorBase):
|
52 |
+
#
|
53 |
+
# runner = <odeint function> or None
|
54 |
+
#
|
55 |
+
# def __init__(self,...): # required
|
56 |
+
# <initialize>
|
57 |
+
#
|
58 |
+
# def reset(self,n,has_jac): # optional
|
59 |
+
# # n - the size of the problem (number of equations)
|
60 |
+
# # has_jac - whether user has supplied its own routine for Jacobian
|
61 |
+
# <allocate memory,initialize further>
|
62 |
+
#
|
63 |
+
# def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
|
64 |
+
# # this method is called to integrate from t=t0 to t=t1
|
65 |
+
# # with initial condition y0. f and jac are user-supplied functions
|
66 |
+
# # that define the problem. f_params,jac_params are additional
|
67 |
+
# # arguments
|
68 |
+
# # to these functions.
|
69 |
+
# <calculate y1>
|
70 |
+
# if <calculation was unsuccessful>:
|
71 |
+
# self.success = 0
|
72 |
+
# return t1,y1
|
73 |
+
#
|
74 |
+
# # In addition, one can define step() and run_relax() methods (they
|
75 |
+
# # take the same arguments as run()) if the integrator can support
|
76 |
+
# # these features (see IntegratorBase doc strings).
|
77 |
+
#
|
78 |
+
# if myodeint.runner:
|
79 |
+
# IntegratorBase.integrator_classes.append(myodeint)
|
80 |
+
|
81 |
+
__all__ = ['ode', 'complex_ode']
|
82 |
+
|
83 |
+
import re
|
84 |
+
import warnings
|
85 |
+
|
86 |
+
from numpy import asarray, array, zeros, isscalar, real, imag, vstack
|
87 |
+
|
88 |
+
from . import _vode
|
89 |
+
from . import _dop
|
90 |
+
from . import _lsoda
|
91 |
+
|
92 |
+
|
93 |
+
_dop_int_dtype = _dop.types.intvar.dtype
|
94 |
+
_vode_int_dtype = _vode.types.intvar.dtype
|
95 |
+
_lsoda_int_dtype = _lsoda.types.intvar.dtype
|
96 |
+
|
97 |
+
|
98 |
+
# ------------------------------------------------------------------------------
|
99 |
+
# User interface
|
100 |
+
# ------------------------------------------------------------------------------
|
101 |
+
|
102 |
+
|
103 |
+
class ode:
|
104 |
+
"""
|
105 |
+
A generic interface class to numeric integrators.
|
106 |
+
|
107 |
+
Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
|
108 |
+
|
109 |
+
*Note*: The first two arguments of ``f(t, y, ...)`` are in the
|
110 |
+
opposite order of the arguments in the system definition function used
|
111 |
+
by `scipy.integrate.odeint`.
|
112 |
+
|
113 |
+
Parameters
|
114 |
+
----------
|
115 |
+
f : callable ``f(t, y, *f_args)``
|
116 |
+
Right-hand side of the differential equation. t is a scalar,
|
117 |
+
``y.shape == (n,)``.
|
118 |
+
``f_args`` is set by calling ``set_f_params(*args)``.
|
119 |
+
`f` should return a scalar, array or list (not a tuple).
|
120 |
+
jac : callable ``jac(t, y, *jac_args)``, optional
|
121 |
+
Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
|
122 |
+
``jac_args`` is set by calling ``set_jac_params(*args)``.
|
123 |
+
|
124 |
+
Attributes
|
125 |
+
----------
|
126 |
+
t : float
|
127 |
+
Current time.
|
128 |
+
y : ndarray
|
129 |
+
Current variable values.
|
130 |
+
|
131 |
+
See also
|
132 |
+
--------
|
133 |
+
odeint : an integrator with a simpler interface based on lsoda from ODEPACK
|
134 |
+
quad : for finding the area under a curve
|
135 |
+
|
136 |
+
Notes
|
137 |
+
-----
|
138 |
+
Available integrators are listed below. They can be selected using
|
139 |
+
the `set_integrator` method.
|
140 |
+
|
141 |
+
"vode"
|
142 |
+
|
143 |
+
Real-valued Variable-coefficient Ordinary Differential Equation
|
144 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
145 |
+
implicit Adams method (for non-stiff problems) and a method based on
|
146 |
+
backward differentiation formulas (BDF) (for stiff problems).
|
147 |
+
|
148 |
+
Source: http://www.netlib.org/ode/vode.f
|
149 |
+
|
150 |
+
.. warning::
|
151 |
+
|
152 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
153 |
+
instances using the "vode" integrator at the same time.
|
154 |
+
|
155 |
+
This integrator accepts the following parameters in `set_integrator`
|
156 |
+
method of the `ode` class:
|
157 |
+
|
158 |
+
- atol : float or sequence
|
159 |
+
absolute tolerance for solution
|
160 |
+
- rtol : float or sequence
|
161 |
+
relative tolerance for solution
|
162 |
+
- lband : None or int
|
163 |
+
- uband : None or int
|
164 |
+
Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
|
165 |
+
Setting these requires your jac routine to return the jacobian
|
166 |
+
in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
|
167 |
+
dimension of the matrix must be (lband+uband+1, len(y)).
|
168 |
+
- method: 'adams' or 'bdf'
|
169 |
+
Which solver to use, Adams (non-stiff) or BDF (stiff)
|
170 |
+
- with_jacobian : bool
|
171 |
+
This option is only considered when the user has not supplied a
|
172 |
+
Jacobian function and has not indicated (by setting either band)
|
173 |
+
that the Jacobian is banded. In this case, `with_jacobian` specifies
|
174 |
+
whether the iteration method of the ODE solver's correction step is
|
175 |
+
chord iteration with an internally generated full Jacobian or
|
176 |
+
functional iteration with no Jacobian.
|
177 |
+
- nsteps : int
|
178 |
+
Maximum number of (internally defined) steps allowed during one
|
179 |
+
call to the solver.
|
180 |
+
- first_step : float
|
181 |
+
- min_step : float
|
182 |
+
- max_step : float
|
183 |
+
Limits for the step sizes used by the integrator.
|
184 |
+
- order : int
|
185 |
+
Maximum order used by the integrator,
|
186 |
+
order <= 12 for Adams, <= 5 for BDF.
|
187 |
+
|
188 |
+
"zvode"
|
189 |
+
|
190 |
+
Complex-valued Variable-coefficient Ordinary Differential Equation
|
191 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
192 |
+
implicit Adams method (for non-stiff problems) and a method based on
|
193 |
+
backward differentiation formulas (BDF) (for stiff problems).
|
194 |
+
|
195 |
+
Source: http://www.netlib.org/ode/zvode.f
|
196 |
+
|
197 |
+
.. warning::
|
198 |
+
|
199 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
200 |
+
instances using the "zvode" integrator at the same time.
|
201 |
+
|
202 |
+
This integrator accepts the same parameters in `set_integrator`
|
203 |
+
as the "vode" solver.
|
204 |
+
|
205 |
+
.. note::
|
206 |
+
|
207 |
+
When using ZVODE for a stiff system, it should only be used for
|
208 |
+
the case in which the function f is analytic, that is, when each f(i)
|
209 |
+
is an analytic function of each y(j). Analyticity means that the
|
210 |
+
partial derivative df(i)/dy(j) is a unique complex number, and this
|
211 |
+
fact is critical in the way ZVODE solves the dense or banded linear
|
212 |
+
systems that arise in the stiff case. For a complex stiff ODE system
|
213 |
+
in which f is not analytic, ZVODE is likely to have convergence
|
214 |
+
failures, and for this problem one should instead use DVODE on the
|
215 |
+
equivalent real system (in the real and imaginary parts of y).
|
216 |
+
|
217 |
+
"lsoda"
|
218 |
+
|
219 |
+
Real-valued Variable-coefficient Ordinary Differential Equation
|
220 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
221 |
+
automatic method switching between implicit Adams method (for non-stiff
|
222 |
+
problems) and a method based on backward differentiation formulas (BDF)
|
223 |
+
(for stiff problems).
|
224 |
+
|
225 |
+
Source: http://www.netlib.org/odepack
|
226 |
+
|
227 |
+
.. warning::
|
228 |
+
|
229 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
230 |
+
instances using the "lsoda" integrator at the same time.
|
231 |
+
|
232 |
+
This integrator accepts the following parameters in `set_integrator`
|
233 |
+
method of the `ode` class:
|
234 |
+
|
235 |
+
- atol : float or sequence
|
236 |
+
absolute tolerance for solution
|
237 |
+
- rtol : float or sequence
|
238 |
+
relative tolerance for solution
|
239 |
+
- lband : None or int
|
240 |
+
- uband : None or int
|
241 |
+
Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
|
242 |
+
Setting these requires your jac routine to return the jacobian
|
243 |
+
in packed format, jac_packed[i-j+uband, j] = jac[i,j].
|
244 |
+
- with_jacobian : bool
|
245 |
+
*Not used.*
|
246 |
+
- nsteps : int
|
247 |
+
Maximum number of (internally defined) steps allowed during one
|
248 |
+
call to the solver.
|
249 |
+
- first_step : float
|
250 |
+
- min_step : float
|
251 |
+
- max_step : float
|
252 |
+
Limits for the step sizes used by the integrator.
|
253 |
+
- max_order_ns : int
|
254 |
+
Maximum order used in the nonstiff case (default 12).
|
255 |
+
- max_order_s : int
|
256 |
+
Maximum order used in the stiff case (default 5).
|
257 |
+
- max_hnil : int
|
258 |
+
Maximum number of messages reporting too small step size (t + h = t)
|
259 |
+
(default 0)
|
260 |
+
- ixpr : int
|
261 |
+
Whether to generate extra printing at method switches (default False).
|
262 |
+
|
263 |
+
"dopri5"
|
264 |
+
|
265 |
+
This is an explicit runge-kutta method of order (4)5 due to Dormand &
|
266 |
+
Prince (with stepsize control and dense output).
|
267 |
+
|
268 |
+
Authors:
|
269 |
+
|
270 |
+
E. Hairer and G. Wanner
|
271 |
+
Universite de Geneve, Dept. de Mathematiques
|
272 |
+
CH-1211 Geneve 24, Switzerland
|
273 |
+
e-mail: [email protected], [email protected]
|
274 |
+
|
275 |
+
This code is described in [HNW93]_.
|
276 |
+
|
277 |
+
This integrator accepts the following parameters in set_integrator()
|
278 |
+
method of the ode class:
|
279 |
+
|
280 |
+
- atol : float or sequence
|
281 |
+
absolute tolerance for solution
|
282 |
+
- rtol : float or sequence
|
283 |
+
relative tolerance for solution
|
284 |
+
- nsteps : int
|
285 |
+
Maximum number of (internally defined) steps allowed during one
|
286 |
+
call to the solver.
|
287 |
+
- first_step : float
|
288 |
+
- max_step : float
|
289 |
+
- safety : float
|
290 |
+
Safety factor on new step selection (default 0.9)
|
291 |
+
- ifactor : float
|
292 |
+
- dfactor : float
|
293 |
+
Maximum factor to increase/decrease step size by in one step
|
294 |
+
- beta : float
|
295 |
+
Beta parameter for stabilised step size control.
|
296 |
+
- verbosity : int
|
297 |
+
Switch for printing messages (< 0 for no messages).
|
298 |
+
|
299 |
+
"dop853"
|
300 |
+
|
301 |
+
This is an explicit runge-kutta method of order 8(5,3) due to Dormand
|
302 |
+
& Prince (with stepsize control and dense output).
|
303 |
+
|
304 |
+
Options and references the same as "dopri5".
|
305 |
+
|
306 |
+
Examples
|
307 |
+
--------
|
308 |
+
|
309 |
+
A problem to integrate and the corresponding jacobian:
|
310 |
+
|
311 |
+
>>> from scipy.integrate import ode
|
312 |
+
>>>
|
313 |
+
>>> y0, t0 = [1.0j, 2.0], 0
|
314 |
+
>>>
|
315 |
+
>>> def f(t, y, arg1):
|
316 |
+
... return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
|
317 |
+
>>> def jac(t, y, arg1):
|
318 |
+
... return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
|
319 |
+
|
320 |
+
The integration:
|
321 |
+
|
322 |
+
>>> r = ode(f, jac).set_integrator('zvode', method='bdf')
|
323 |
+
>>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
|
324 |
+
>>> t1 = 10
|
325 |
+
>>> dt = 1
|
326 |
+
>>> while r.successful() and r.t < t1:
|
327 |
+
... print(r.t+dt, r.integrate(r.t+dt))
|
328 |
+
1 [-0.71038232+0.23749653j 0.40000271+0.j ]
|
329 |
+
2.0 [0.19098503-0.52359246j 0.22222356+0.j ]
|
330 |
+
3.0 [0.47153208+0.52701229j 0.15384681+0.j ]
|
331 |
+
4.0 [-0.61905937+0.30726255j 0.11764744+0.j ]
|
332 |
+
5.0 [0.02340997-0.61418799j 0.09523835+0.j ]
|
333 |
+
6.0 [0.58643071+0.339819j 0.08000018+0.j ]
|
334 |
+
7.0 [-0.52070105+0.44525141j 0.06896565+0.j ]
|
335 |
+
8.0 [-0.15986733-0.61234476j 0.06060616+0.j ]
|
336 |
+
9.0 [0.64850462+0.15048982j 0.05405414+0.j ]
|
337 |
+
10.0 [-0.38404699+0.56382299j 0.04878055+0.j ]
|
338 |
+
|
339 |
+
References
|
340 |
+
----------
|
341 |
+
.. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
|
342 |
+
Differential Equations i. Nonstiff Problems. 2nd edition.
|
343 |
+
Springer Series in Computational Mathematics,
|
344 |
+
Springer-Verlag (1993)
|
345 |
+
|
346 |
+
"""
|
347 |
+
|
348 |
+
def __init__(self, f, jac=None):
|
349 |
+
self.stiff = 0
|
350 |
+
self.f = f
|
351 |
+
self.jac = jac
|
352 |
+
self.f_params = ()
|
353 |
+
self.jac_params = ()
|
354 |
+
self._y = []
|
355 |
+
|
356 |
+
@property
|
357 |
+
def y(self):
|
358 |
+
return self._y
|
359 |
+
|
360 |
+
def set_initial_value(self, y, t=0.0):
|
361 |
+
"""Set initial conditions y(t) = y."""
|
362 |
+
if isscalar(y):
|
363 |
+
y = [y]
|
364 |
+
n_prev = len(self._y)
|
365 |
+
if not n_prev:
|
366 |
+
self.set_integrator('') # find first available integrator
|
367 |
+
self._y = asarray(y, self._integrator.scalar)
|
368 |
+
self.t = t
|
369 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
370 |
+
return self
|
371 |
+
|
372 |
+
def set_integrator(self, name, **integrator_params):
|
373 |
+
"""
|
374 |
+
Set integrator by name.
|
375 |
+
|
376 |
+
Parameters
|
377 |
+
----------
|
378 |
+
name : str
|
379 |
+
Name of the integrator.
|
380 |
+
**integrator_params
|
381 |
+
Additional parameters for the integrator.
|
382 |
+
"""
|
383 |
+
integrator = find_integrator(name)
|
384 |
+
if integrator is None:
|
385 |
+
# FIXME: this really should be raise an exception. Will that break
|
386 |
+
# any code?
|
387 |
+
message = f'No integrator name match with {name!r} or is not available.'
|
388 |
+
warnings.warn(message, stacklevel=2)
|
389 |
+
else:
|
390 |
+
self._integrator = integrator(**integrator_params)
|
391 |
+
if not len(self._y):
|
392 |
+
self.t = 0.0
|
393 |
+
self._y = array([0.0], self._integrator.scalar)
|
394 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
395 |
+
return self
|
396 |
+
|
397 |
+
def integrate(self, t, step=False, relax=False):
|
398 |
+
"""Find y=y(t), set y as an initial condition, and return y.
|
399 |
+
|
400 |
+
Parameters
|
401 |
+
----------
|
402 |
+
t : float
|
403 |
+
The endpoint of the integration step.
|
404 |
+
step : bool
|
405 |
+
If True, and if the integrator supports the step method,
|
406 |
+
then perform a single integration step and return.
|
407 |
+
This parameter is provided in order to expose internals of
|
408 |
+
the implementation, and should not be changed from its default
|
409 |
+
value in most cases.
|
410 |
+
relax : bool
|
411 |
+
If True and if the integrator supports the run_relax method,
|
412 |
+
then integrate until t_1 >= t and return. ``relax`` is not
|
413 |
+
referenced if ``step=True``.
|
414 |
+
This parameter is provided in order to expose internals of
|
415 |
+
the implementation, and should not be changed from its default
|
416 |
+
value in most cases.
|
417 |
+
|
418 |
+
Returns
|
419 |
+
-------
|
420 |
+
y : float
|
421 |
+
The integrated value at t
|
422 |
+
"""
|
423 |
+
if step and self._integrator.supports_step:
|
424 |
+
mth = self._integrator.step
|
425 |
+
elif relax and self._integrator.supports_run_relax:
|
426 |
+
mth = self._integrator.run_relax
|
427 |
+
else:
|
428 |
+
mth = self._integrator.run
|
429 |
+
|
430 |
+
try:
|
431 |
+
self._y, self.t = mth(self.f, self.jac or (lambda: None),
|
432 |
+
self._y, self.t, t,
|
433 |
+
self.f_params, self.jac_params)
|
434 |
+
except SystemError as e:
|
435 |
+
# f2py issue with tuple returns, see ticket 1187.
|
436 |
+
raise ValueError(
|
437 |
+
'Function to integrate must not return a tuple.'
|
438 |
+
) from e
|
439 |
+
|
440 |
+
return self._y
|
441 |
+
|
442 |
+
def successful(self):
|
443 |
+
"""Check if integration was successful."""
|
444 |
+
try:
|
445 |
+
self._integrator
|
446 |
+
except AttributeError:
|
447 |
+
self.set_integrator('')
|
448 |
+
return self._integrator.success == 1
|
449 |
+
|
450 |
+
def get_return_code(self):
|
451 |
+
"""Extracts the return code for the integration to enable better control
|
452 |
+
if the integration fails.
|
453 |
+
|
454 |
+
In general, a return code > 0 implies success, while a return code < 0
|
455 |
+
implies failure.
|
456 |
+
|
457 |
+
Notes
|
458 |
+
-----
|
459 |
+
This section describes possible return codes and their meaning, for available
|
460 |
+
integrators that can be selected by `set_integrator` method.
|
461 |
+
|
462 |
+
"vode"
|
463 |
+
|
464 |
+
=========== =======
|
465 |
+
Return Code Message
|
466 |
+
=========== =======
|
467 |
+
2 Integration successful.
|
468 |
+
-1 Excess work done on this call. (Perhaps wrong MF.)
|
469 |
+
-2 Excess accuracy requested. (Tolerances too small.)
|
470 |
+
-3 Illegal input detected. (See printed message.)
|
471 |
+
-4 Repeated error test failures. (Check all input.)
|
472 |
+
-5 Repeated convergence failures. (Perhaps bad Jacobian
|
473 |
+
supplied or wrong choice of MF or tolerances.)
|
474 |
+
-6 Error weight became zero during problem. (Solution
|
475 |
+
component i vanished, and ATOL or ATOL(i) = 0.)
|
476 |
+
=========== =======
|
477 |
+
|
478 |
+
"zvode"
|
479 |
+
|
480 |
+
=========== =======
|
481 |
+
Return Code Message
|
482 |
+
=========== =======
|
483 |
+
2 Integration successful.
|
484 |
+
-1 Excess work done on this call. (Perhaps wrong MF.)
|
485 |
+
-2 Excess accuracy requested. (Tolerances too small.)
|
486 |
+
-3 Illegal input detected. (See printed message.)
|
487 |
+
-4 Repeated error test failures. (Check all input.)
|
488 |
+
-5 Repeated convergence failures. (Perhaps bad Jacobian
|
489 |
+
supplied or wrong choice of MF or tolerances.)
|
490 |
+
-6 Error weight became zero during problem. (Solution
|
491 |
+
component i vanished, and ATOL or ATOL(i) = 0.)
|
492 |
+
=========== =======
|
493 |
+
|
494 |
+
"dopri5"
|
495 |
+
|
496 |
+
=========== =======
|
497 |
+
Return Code Message
|
498 |
+
=========== =======
|
499 |
+
1 Integration successful.
|
500 |
+
2 Integration successful (interrupted by solout).
|
501 |
+
-1 Input is not consistent.
|
502 |
+
-2 Larger nsteps is needed.
|
503 |
+
-3 Step size becomes too small.
|
504 |
+
-4 Problem is probably stiff (interrupted).
|
505 |
+
=========== =======
|
506 |
+
|
507 |
+
"dop853"
|
508 |
+
|
509 |
+
=========== =======
|
510 |
+
Return Code Message
|
511 |
+
=========== =======
|
512 |
+
1 Integration successful.
|
513 |
+
2 Integration successful (interrupted by solout).
|
514 |
+
-1 Input is not consistent.
|
515 |
+
-2 Larger nsteps is needed.
|
516 |
+
-3 Step size becomes too small.
|
517 |
+
-4 Problem is probably stiff (interrupted).
|
518 |
+
=========== =======
|
519 |
+
|
520 |
+
"lsoda"
|
521 |
+
|
522 |
+
=========== =======
|
523 |
+
Return Code Message
|
524 |
+
=========== =======
|
525 |
+
2 Integration successful.
|
526 |
+
-1 Excess work done on this call (perhaps wrong Dfun type).
|
527 |
+
-2 Excess accuracy requested (tolerances too small).
|
528 |
+
-3 Illegal input detected (internal error).
|
529 |
+
-4 Repeated error test failures (internal error).
|
530 |
+
-5 Repeated convergence failures (perhaps bad Jacobian or tolerances).
|
531 |
+
-6 Error weight became zero during problem.
|
532 |
+
-7 Internal workspace insufficient to finish (internal error).
|
533 |
+
=========== =======
|
534 |
+
"""
|
535 |
+
try:
|
536 |
+
self._integrator
|
537 |
+
except AttributeError:
|
538 |
+
self.set_integrator('')
|
539 |
+
return self._integrator.istate
|
540 |
+
|
541 |
+
def set_f_params(self, *args):
|
542 |
+
"""Set extra parameters for user-supplied function f."""
|
543 |
+
self.f_params = args
|
544 |
+
return self
|
545 |
+
|
546 |
+
def set_jac_params(self, *args):
|
547 |
+
"""Set extra parameters for user-supplied function jac."""
|
548 |
+
self.jac_params = args
|
549 |
+
return self
|
550 |
+
|
551 |
+
def set_solout(self, solout):
|
552 |
+
"""
|
553 |
+
Set callable to be called at every successful integration step.
|
554 |
+
|
555 |
+
Parameters
|
556 |
+
----------
|
557 |
+
solout : callable
|
558 |
+
``solout(t, y)`` is called at each internal integrator step,
|
559 |
+
t is a scalar providing the current independent position
|
560 |
+
y is the current solution ``y.shape == (n,)``
|
561 |
+
solout should return -1 to stop integration
|
562 |
+
otherwise it should return None or 0
|
563 |
+
|
564 |
+
"""
|
565 |
+
if self._integrator.supports_solout:
|
566 |
+
self._integrator.set_solout(solout)
|
567 |
+
if self._y is not None:
|
568 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
569 |
+
else:
|
570 |
+
raise ValueError("selected integrator does not support solout,"
|
571 |
+
" choose another one")
|
572 |
+
|
573 |
+
|
574 |
+
def _transform_banded_jac(bjac):
|
575 |
+
"""
|
576 |
+
Convert a real matrix of the form (for example)
|
577 |
+
|
578 |
+
[0 0 A B] [0 0 0 B]
|
579 |
+
[0 0 C D] [0 0 A D]
|
580 |
+
[E F G H] to [0 F C H]
|
581 |
+
[I J K L] [E J G L]
|
582 |
+
[I 0 K 0]
|
583 |
+
|
584 |
+
That is, every other column is shifted up one.
|
585 |
+
"""
|
586 |
+
# Shift every other column.
|
587 |
+
newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
|
588 |
+
newjac[1:, ::2] = bjac[:, ::2]
|
589 |
+
newjac[:-1, 1::2] = bjac[:, 1::2]
|
590 |
+
return newjac
|
591 |
+
|
592 |
+
|
593 |
+
class complex_ode(ode):
|
594 |
+
"""
|
595 |
+
A wrapper of ode for complex systems.
|
596 |
+
|
597 |
+
This functions similarly as `ode`, but re-maps a complex-valued
|
598 |
+
equation system to a real-valued one before using the integrators.
|
599 |
+
|
600 |
+
Parameters
|
601 |
+
----------
|
602 |
+
f : callable ``f(t, y, *f_args)``
|
603 |
+
Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
|
604 |
+
``f_args`` is set by calling ``set_f_params(*args)``.
|
605 |
+
jac : callable ``jac(t, y, *jac_args)``
|
606 |
+
Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
|
607 |
+
``jac_args`` is set by calling ``set_f_params(*args)``.
|
608 |
+
|
609 |
+
Attributes
|
610 |
+
----------
|
611 |
+
t : float
|
612 |
+
Current time.
|
613 |
+
y : ndarray
|
614 |
+
Current variable values.
|
615 |
+
|
616 |
+
Examples
|
617 |
+
--------
|
618 |
+
For usage examples, see `ode`.
|
619 |
+
|
620 |
+
"""
|
621 |
+
|
622 |
+
def __init__(self, f, jac=None):
|
623 |
+
self.cf = f
|
624 |
+
self.cjac = jac
|
625 |
+
if jac is None:
|
626 |
+
ode.__init__(self, self._wrap, None)
|
627 |
+
else:
|
628 |
+
ode.__init__(self, self._wrap, self._wrap_jac)
|
629 |
+
|
630 |
+
def _wrap(self, t, y, *f_args):
|
631 |
+
f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
|
632 |
+
# self.tmp is a real-valued array containing the interleaved
|
633 |
+
# real and imaginary parts of f.
|
634 |
+
self.tmp[::2] = real(f)
|
635 |
+
self.tmp[1::2] = imag(f)
|
636 |
+
return self.tmp
|
637 |
+
|
638 |
+
def _wrap_jac(self, t, y, *jac_args):
|
639 |
+
# jac is the complex Jacobian computed by the user-defined function.
|
640 |
+
jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
|
641 |
+
|
642 |
+
# jac_tmp is the real version of the complex Jacobian. Each complex
|
643 |
+
# entry in jac, say 2+3j, becomes a 2x2 block of the form
|
644 |
+
# [2 -3]
|
645 |
+
# [3 2]
|
646 |
+
jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
|
647 |
+
jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
|
648 |
+
jac_tmp[1::2, ::2] = imag(jac)
|
649 |
+
jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
|
650 |
+
|
651 |
+
ml = getattr(self._integrator, 'ml', None)
|
652 |
+
mu = getattr(self._integrator, 'mu', None)
|
653 |
+
if ml is not None or mu is not None:
|
654 |
+
# Jacobian is banded. The user's Jacobian function has computed
|
655 |
+
# the complex Jacobian in packed format. The corresponding
|
656 |
+
# real-valued version has every other column shifted up.
|
657 |
+
jac_tmp = _transform_banded_jac(jac_tmp)
|
658 |
+
|
659 |
+
return jac_tmp
|
660 |
+
|
661 |
+
@property
|
662 |
+
def y(self):
|
663 |
+
return self._y[::2] + 1j * self._y[1::2]
|
664 |
+
|
665 |
+
def set_integrator(self, name, **integrator_params):
|
666 |
+
"""
|
667 |
+
Set integrator by name.
|
668 |
+
|
669 |
+
Parameters
|
670 |
+
----------
|
671 |
+
name : str
|
672 |
+
Name of the integrator
|
673 |
+
**integrator_params
|
674 |
+
Additional parameters for the integrator.
|
675 |
+
"""
|
676 |
+
if name == 'zvode':
|
677 |
+
raise ValueError("zvode must be used with ode, not complex_ode")
|
678 |
+
|
679 |
+
lband = integrator_params.get('lband')
|
680 |
+
uband = integrator_params.get('uband')
|
681 |
+
if lband is not None or uband is not None:
|
682 |
+
# The Jacobian is banded. Override the user-supplied bandwidths
|
683 |
+
# (which are for the complex Jacobian) with the bandwidths of
|
684 |
+
# the corresponding real-valued Jacobian wrapper of the complex
|
685 |
+
# Jacobian.
|
686 |
+
integrator_params['lband'] = 2 * (lband or 0) + 1
|
687 |
+
integrator_params['uband'] = 2 * (uband or 0) + 1
|
688 |
+
|
689 |
+
return ode.set_integrator(self, name, **integrator_params)
|
690 |
+
|
691 |
+
def set_initial_value(self, y, t=0.0):
|
692 |
+
"""Set initial conditions y(t) = y."""
|
693 |
+
y = asarray(y)
|
694 |
+
self.tmp = zeros(y.size * 2, 'float')
|
695 |
+
self.tmp[::2] = real(y)
|
696 |
+
self.tmp[1::2] = imag(y)
|
697 |
+
return ode.set_initial_value(self, self.tmp, t)
|
698 |
+
|
699 |
+
def integrate(self, t, step=False, relax=False):
|
700 |
+
"""Find y=y(t), set y as an initial condition, and return y.
|
701 |
+
|
702 |
+
Parameters
|
703 |
+
----------
|
704 |
+
t : float
|
705 |
+
The endpoint of the integration step.
|
706 |
+
step : bool
|
707 |
+
If True, and if the integrator supports the step method,
|
708 |
+
then perform a single integration step and return.
|
709 |
+
This parameter is provided in order to expose internals of
|
710 |
+
the implementation, and should not be changed from its default
|
711 |
+
value in most cases.
|
712 |
+
relax : bool
|
713 |
+
If True and if the integrator supports the run_relax method,
|
714 |
+
then integrate until t_1 >= t and return. ``relax`` is not
|
715 |
+
referenced if ``step=True``.
|
716 |
+
This parameter is provided in order to expose internals of
|
717 |
+
the implementation, and should not be changed from its default
|
718 |
+
value in most cases.
|
719 |
+
|
720 |
+
Returns
|
721 |
+
-------
|
722 |
+
y : float
|
723 |
+
The integrated value at t
|
724 |
+
"""
|
725 |
+
y = ode.integrate(self, t, step, relax)
|
726 |
+
return y[::2] + 1j * y[1::2]
|
727 |
+
|
728 |
+
def set_solout(self, solout):
|
729 |
+
"""
|
730 |
+
Set callable to be called at every successful integration step.
|
731 |
+
|
732 |
+
Parameters
|
733 |
+
----------
|
734 |
+
solout : callable
|
735 |
+
``solout(t, y)`` is called at each internal integrator step,
|
736 |
+
t is a scalar providing the current independent position
|
737 |
+
y is the current solution ``y.shape == (n,)``
|
738 |
+
solout should return -1 to stop integration
|
739 |
+
otherwise it should return None or 0
|
740 |
+
|
741 |
+
"""
|
742 |
+
if self._integrator.supports_solout:
|
743 |
+
self._integrator.set_solout(solout, complex=True)
|
744 |
+
else:
|
745 |
+
raise TypeError("selected integrator does not support solouta,"
|
746 |
+
+ "choose another one")
|
747 |
+
|
748 |
+
|
749 |
+
# ------------------------------------------------------------------------------
|
750 |
+
# ODE integrators
|
751 |
+
# ------------------------------------------------------------------------------
|
752 |
+
|
753 |
+
def find_integrator(name):
|
754 |
+
for cl in IntegratorBase.integrator_classes:
|
755 |
+
if re.match(name, cl.__name__, re.I):
|
756 |
+
return cl
|
757 |
+
return None
|
758 |
+
|
759 |
+
|
760 |
+
class IntegratorConcurrencyError(RuntimeError):
|
761 |
+
"""
|
762 |
+
Failure due to concurrent usage of an integrator that can be used
|
763 |
+
only for a single problem at a time.
|
764 |
+
|
765 |
+
"""
|
766 |
+
|
767 |
+
def __init__(self, name):
|
768 |
+
msg = ("Integrator `%s` can be used to solve only a single problem "
|
769 |
+
"at a time. If you want to integrate multiple problems, "
|
770 |
+
"consider using a different integrator "
|
771 |
+
"(see `ode.set_integrator`)") % name
|
772 |
+
RuntimeError.__init__(self, msg)
|
773 |
+
|
774 |
+
|
775 |
+
class IntegratorBase:
|
776 |
+
runner = None # runner is None => integrator is not available
|
777 |
+
success = None # success==1 if integrator was called successfully
|
778 |
+
istate = None # istate > 0 means success, istate < 0 means failure
|
779 |
+
supports_run_relax = None
|
780 |
+
supports_step = None
|
781 |
+
supports_solout = False
|
782 |
+
integrator_classes = []
|
783 |
+
scalar = float
|
784 |
+
|
785 |
+
def acquire_new_handle(self):
|
786 |
+
# Some of the integrators have internal state (ancient
|
787 |
+
# Fortran...), and so only one instance can use them at a time.
|
788 |
+
# We keep track of this, and fail when concurrent usage is tried.
|
789 |
+
self.__class__.active_global_handle += 1
|
790 |
+
self.handle = self.__class__.active_global_handle
|
791 |
+
|
792 |
+
def check_handle(self):
|
793 |
+
if self.handle is not self.__class__.active_global_handle:
|
794 |
+
raise IntegratorConcurrencyError(self.__class__.__name__)
|
795 |
+
|
796 |
+
def reset(self, n, has_jac):
|
797 |
+
"""Prepare integrator for call: allocate memory, set flags, etc.
|
798 |
+
n - number of equations.
|
799 |
+
has_jac - if user has supplied function for evaluating Jacobian.
|
800 |
+
"""
|
801 |
+
|
802 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
803 |
+
"""Integrate from t=t0 to t=t1 using y0 as an initial condition.
|
804 |
+
Return 2-tuple (y1,t1) where y1 is the result and t=t1
|
805 |
+
defines the stoppage coordinate of the result.
|
806 |
+
"""
|
807 |
+
raise NotImplementedError('all integrators must define '
|
808 |
+
'run(f, jac, t0, t1, y0, f_params, jac_params)')
|
809 |
+
|
810 |
+
def step(self, f, jac, y0, t0, t1, f_params, jac_params):
|
811 |
+
"""Make one integration step and return (y1,t1)."""
|
812 |
+
raise NotImplementedError('%s does not support step() method' %
|
813 |
+
self.__class__.__name__)
|
814 |
+
|
815 |
+
def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
|
816 |
+
"""Integrate from t=t0 to t>=t1 and return (y1,t)."""
|
817 |
+
raise NotImplementedError('%s does not support run_relax() method' %
|
818 |
+
self.__class__.__name__)
|
819 |
+
|
820 |
+
# XXX: __str__ method for getting visual state of the integrator
|
821 |
+
|
822 |
+
|
823 |
+
def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
|
824 |
+
"""
|
825 |
+
Wrap a banded Jacobian function with a function that pads
|
826 |
+
the Jacobian with `ml` rows of zeros.
|
827 |
+
"""
|
828 |
+
|
829 |
+
def jac_wrapper(t, y):
|
830 |
+
jac = asarray(jacfunc(t, y, *jac_params))
|
831 |
+
padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
|
832 |
+
return padded_jac
|
833 |
+
|
834 |
+
return jac_wrapper
|
835 |
+
|
836 |
+
|
837 |
+
class vode(IntegratorBase):
|
838 |
+
runner = getattr(_vode, 'dvode', None)
|
839 |
+
|
840 |
+
messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
|
841 |
+
-2: 'Excess accuracy requested. (Tolerances too small.)',
|
842 |
+
-3: 'Illegal input detected. (See printed message.)',
|
843 |
+
-4: 'Repeated error test failures. (Check all input.)',
|
844 |
+
-5: 'Repeated convergence failures. (Perhaps bad'
|
845 |
+
' Jacobian supplied or wrong choice of MF or tolerances.)',
|
846 |
+
-6: 'Error weight became zero during problem. (Solution'
|
847 |
+
' component i vanished, and ATOL or ATOL(i) = 0.)'
|
848 |
+
}
|
849 |
+
supports_run_relax = 1
|
850 |
+
supports_step = 1
|
851 |
+
active_global_handle = 0
|
852 |
+
|
853 |
+
def __init__(self,
|
854 |
+
method='adams',
|
855 |
+
with_jacobian=False,
|
856 |
+
rtol=1e-6, atol=1e-12,
|
857 |
+
lband=None, uband=None,
|
858 |
+
order=12,
|
859 |
+
nsteps=500,
|
860 |
+
max_step=0.0, # corresponds to infinite
|
861 |
+
min_step=0.0,
|
862 |
+
first_step=0.0, # determined by solver
|
863 |
+
):
|
864 |
+
|
865 |
+
if re.match(method, r'adams', re.I):
|
866 |
+
self.meth = 1
|
867 |
+
elif re.match(method, r'bdf', re.I):
|
868 |
+
self.meth = 2
|
869 |
+
else:
|
870 |
+
raise ValueError('Unknown integration method %s' % method)
|
871 |
+
self.with_jacobian = with_jacobian
|
872 |
+
self.rtol = rtol
|
873 |
+
self.atol = atol
|
874 |
+
self.mu = uband
|
875 |
+
self.ml = lband
|
876 |
+
|
877 |
+
self.order = order
|
878 |
+
self.nsteps = nsteps
|
879 |
+
self.max_step = max_step
|
880 |
+
self.min_step = min_step
|
881 |
+
self.first_step = first_step
|
882 |
+
self.success = 1
|
883 |
+
|
884 |
+
self.initialized = False
|
885 |
+
|
886 |
+
def _determine_mf_and_set_bands(self, has_jac):
|
887 |
+
"""
|
888 |
+
Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
|
889 |
+
|
890 |
+
In the Fortran code, the legal values of `MF` are:
|
891 |
+
10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
|
892 |
+
-11, -12, -14, -15, -21, -22, -24, -25
|
893 |
+
but this Python wrapper does not use negative values.
|
894 |
+
|
895 |
+
Returns
|
896 |
+
|
897 |
+
mf = 10*self.meth + miter
|
898 |
+
|
899 |
+
self.meth is the linear multistep method:
|
900 |
+
self.meth == 1: method="adams"
|
901 |
+
self.meth == 2: method="bdf"
|
902 |
+
|
903 |
+
miter is the correction iteration method:
|
904 |
+
miter == 0: Functional iteration; no Jacobian involved.
|
905 |
+
miter == 1: Chord iteration with user-supplied full Jacobian.
|
906 |
+
miter == 2: Chord iteration with internally computed full Jacobian.
|
907 |
+
miter == 3: Chord iteration with internally computed diagonal Jacobian.
|
908 |
+
miter == 4: Chord iteration with user-supplied banded Jacobian.
|
909 |
+
miter == 5: Chord iteration with internally computed banded Jacobian.
|
910 |
+
|
911 |
+
Side effects: If either self.mu or self.ml is not None and the other is None,
|
912 |
+
then the one that is None is set to 0.
|
913 |
+
"""
|
914 |
+
|
915 |
+
jac_is_banded = self.mu is not None or self.ml is not None
|
916 |
+
if jac_is_banded:
|
917 |
+
if self.mu is None:
|
918 |
+
self.mu = 0
|
919 |
+
if self.ml is None:
|
920 |
+
self.ml = 0
|
921 |
+
|
922 |
+
# has_jac is True if the user provided a Jacobian function.
|
923 |
+
if has_jac:
|
924 |
+
if jac_is_banded:
|
925 |
+
miter = 4
|
926 |
+
else:
|
927 |
+
miter = 1
|
928 |
+
else:
|
929 |
+
if jac_is_banded:
|
930 |
+
if self.ml == self.mu == 0:
|
931 |
+
miter = 3 # Chord iteration with internal diagonal Jacobian.
|
932 |
+
else:
|
933 |
+
miter = 5 # Chord iteration with internal banded Jacobian.
|
934 |
+
else:
|
935 |
+
# self.with_jacobian is set by the user in
|
936 |
+
# the call to ode.set_integrator.
|
937 |
+
if self.with_jacobian:
|
938 |
+
miter = 2 # Chord iteration with internal full Jacobian.
|
939 |
+
else:
|
940 |
+
miter = 0 # Functional iteration; no Jacobian involved.
|
941 |
+
|
942 |
+
mf = 10 * self.meth + miter
|
943 |
+
return mf
|
944 |
+
|
945 |
+
def reset(self, n, has_jac):
|
946 |
+
mf = self._determine_mf_and_set_bands(has_jac)
|
947 |
+
|
948 |
+
if mf == 10:
|
949 |
+
lrw = 20 + 16 * n
|
950 |
+
elif mf in [11, 12]:
|
951 |
+
lrw = 22 + 16 * n + 2 * n * n
|
952 |
+
elif mf == 13:
|
953 |
+
lrw = 22 + 17 * n
|
954 |
+
elif mf in [14, 15]:
|
955 |
+
lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
|
956 |
+
elif mf == 20:
|
957 |
+
lrw = 20 + 9 * n
|
958 |
+
elif mf in [21, 22]:
|
959 |
+
lrw = 22 + 9 * n + 2 * n * n
|
960 |
+
elif mf == 23:
|
961 |
+
lrw = 22 + 10 * n
|
962 |
+
elif mf in [24, 25]:
|
963 |
+
lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
|
964 |
+
else:
|
965 |
+
raise ValueError('Unexpected mf=%s' % mf)
|
966 |
+
|
967 |
+
if mf % 10 in [0, 3]:
|
968 |
+
liw = 30
|
969 |
+
else:
|
970 |
+
liw = 30 + n
|
971 |
+
|
972 |
+
rwork = zeros((lrw,), float)
|
973 |
+
rwork[4] = self.first_step
|
974 |
+
rwork[5] = self.max_step
|
975 |
+
rwork[6] = self.min_step
|
976 |
+
self.rwork = rwork
|
977 |
+
|
978 |
+
iwork = zeros((liw,), _vode_int_dtype)
|
979 |
+
if self.ml is not None:
|
980 |
+
iwork[0] = self.ml
|
981 |
+
if self.mu is not None:
|
982 |
+
iwork[1] = self.mu
|
983 |
+
iwork[4] = self.order
|
984 |
+
iwork[5] = self.nsteps
|
985 |
+
iwork[6] = 2 # mxhnil
|
986 |
+
self.iwork = iwork
|
987 |
+
|
988 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
989 |
+
self.rwork, self.iwork, mf]
|
990 |
+
self.success = 1
|
991 |
+
self.initialized = False
|
992 |
+
|
993 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
994 |
+
if self.initialized:
|
995 |
+
self.check_handle()
|
996 |
+
else:
|
997 |
+
self.initialized = True
|
998 |
+
self.acquire_new_handle()
|
999 |
+
|
1000 |
+
if self.ml is not None and self.ml > 0:
|
1001 |
+
# Banded Jacobian. Wrap the user-provided function with one
|
1002 |
+
# that pads the Jacobian array with the extra `self.ml` rows
|
1003 |
+
# required by the f2py-generated wrapper.
|
1004 |
+
jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
|
1005 |
+
|
1006 |
+
args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
|
1007 |
+
(f_params, jac_params))
|
1008 |
+
y1, t, istate = self.runner(*args)
|
1009 |
+
self.istate = istate
|
1010 |
+
if istate < 0:
|
1011 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
1012 |
+
warnings.warn('{:s}: {:s}'.format(self.__class__.__name__,
|
1013 |
+
self.messages.get(istate, unexpected_istate_msg)),
|
1014 |
+
stacklevel=2)
|
1015 |
+
self.success = 0
|
1016 |
+
else:
|
1017 |
+
self.call_args[3] = 2 # upgrade istate from 1 to 2
|
1018 |
+
self.istate = 2
|
1019 |
+
return y1, t
|
1020 |
+
|
1021 |
+
def step(self, *args):
|
1022 |
+
itask = self.call_args[2]
|
1023 |
+
self.call_args[2] = 2
|
1024 |
+
r = self.run(*args)
|
1025 |
+
self.call_args[2] = itask
|
1026 |
+
return r
|
1027 |
+
|
1028 |
+
def run_relax(self, *args):
|
1029 |
+
itask = self.call_args[2]
|
1030 |
+
self.call_args[2] = 3
|
1031 |
+
r = self.run(*args)
|
1032 |
+
self.call_args[2] = itask
|
1033 |
+
return r
|
1034 |
+
|
1035 |
+
|
1036 |
+
if vode.runner is not None:
|
1037 |
+
IntegratorBase.integrator_classes.append(vode)
|
1038 |
+
|
1039 |
+
|
1040 |
+
class zvode(vode):
|
1041 |
+
runner = getattr(_vode, 'zvode', None)
|
1042 |
+
|
1043 |
+
supports_run_relax = 1
|
1044 |
+
supports_step = 1
|
1045 |
+
scalar = complex
|
1046 |
+
active_global_handle = 0
|
1047 |
+
|
1048 |
+
def reset(self, n, has_jac):
|
1049 |
+
mf = self._determine_mf_and_set_bands(has_jac)
|
1050 |
+
|
1051 |
+
if mf in (10,):
|
1052 |
+
lzw = 15 * n
|
1053 |
+
elif mf in (11, 12):
|
1054 |
+
lzw = 15 * n + 2 * n ** 2
|
1055 |
+
elif mf in (-11, -12):
|
1056 |
+
lzw = 15 * n + n ** 2
|
1057 |
+
elif mf in (13,):
|
1058 |
+
lzw = 16 * n
|
1059 |
+
elif mf in (14, 15):
|
1060 |
+
lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
|
1061 |
+
elif mf in (-14, -15):
|
1062 |
+
lzw = 16 * n + (2 * self.ml + self.mu) * n
|
1063 |
+
elif mf in (20,):
|
1064 |
+
lzw = 8 * n
|
1065 |
+
elif mf in (21, 22):
|
1066 |
+
lzw = 8 * n + 2 * n ** 2
|
1067 |
+
elif mf in (-21, -22):
|
1068 |
+
lzw = 8 * n + n ** 2
|
1069 |
+
elif mf in (23,):
|
1070 |
+
lzw = 9 * n
|
1071 |
+
elif mf in (24, 25):
|
1072 |
+
lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
|
1073 |
+
elif mf in (-24, -25):
|
1074 |
+
lzw = 9 * n + (2 * self.ml + self.mu) * n
|
1075 |
+
|
1076 |
+
lrw = 20 + n
|
1077 |
+
|
1078 |
+
if mf % 10 in (0, 3):
|
1079 |
+
liw = 30
|
1080 |
+
else:
|
1081 |
+
liw = 30 + n
|
1082 |
+
|
1083 |
+
zwork = zeros((lzw,), complex)
|
1084 |
+
self.zwork = zwork
|
1085 |
+
|
1086 |
+
rwork = zeros((lrw,), float)
|
1087 |
+
rwork[4] = self.first_step
|
1088 |
+
rwork[5] = self.max_step
|
1089 |
+
rwork[6] = self.min_step
|
1090 |
+
self.rwork = rwork
|
1091 |
+
|
1092 |
+
iwork = zeros((liw,), _vode_int_dtype)
|
1093 |
+
if self.ml is not None:
|
1094 |
+
iwork[0] = self.ml
|
1095 |
+
if self.mu is not None:
|
1096 |
+
iwork[1] = self.mu
|
1097 |
+
iwork[4] = self.order
|
1098 |
+
iwork[5] = self.nsteps
|
1099 |
+
iwork[6] = 2 # mxhnil
|
1100 |
+
self.iwork = iwork
|
1101 |
+
|
1102 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
1103 |
+
self.zwork, self.rwork, self.iwork, mf]
|
1104 |
+
self.success = 1
|
1105 |
+
self.initialized = False
|
1106 |
+
|
1107 |
+
|
1108 |
+
if zvode.runner is not None:
|
1109 |
+
IntegratorBase.integrator_classes.append(zvode)
|
1110 |
+
|
1111 |
+
|
1112 |
+
class dopri5(IntegratorBase):
|
1113 |
+
runner = getattr(_dop, 'dopri5', None)
|
1114 |
+
name = 'dopri5'
|
1115 |
+
supports_solout = True
|
1116 |
+
|
1117 |
+
messages = {1: 'computation successful',
|
1118 |
+
2: 'computation successful (interrupted by solout)',
|
1119 |
+
-1: 'input is not consistent',
|
1120 |
+
-2: 'larger nsteps is needed',
|
1121 |
+
-3: 'step size becomes too small',
|
1122 |
+
-4: 'problem is probably stiff (interrupted)',
|
1123 |
+
}
|
1124 |
+
|
1125 |
+
def __init__(self,
|
1126 |
+
rtol=1e-6, atol=1e-12,
|
1127 |
+
nsteps=500,
|
1128 |
+
max_step=0.0,
|
1129 |
+
first_step=0.0, # determined by solver
|
1130 |
+
safety=0.9,
|
1131 |
+
ifactor=10.0,
|
1132 |
+
dfactor=0.2,
|
1133 |
+
beta=0.0,
|
1134 |
+
method=None,
|
1135 |
+
verbosity=-1, # no messages if negative
|
1136 |
+
):
|
1137 |
+
self.rtol = rtol
|
1138 |
+
self.atol = atol
|
1139 |
+
self.nsteps = nsteps
|
1140 |
+
self.max_step = max_step
|
1141 |
+
self.first_step = first_step
|
1142 |
+
self.safety = safety
|
1143 |
+
self.ifactor = ifactor
|
1144 |
+
self.dfactor = dfactor
|
1145 |
+
self.beta = beta
|
1146 |
+
self.verbosity = verbosity
|
1147 |
+
self.success = 1
|
1148 |
+
self.set_solout(None)
|
1149 |
+
|
1150 |
+
def set_solout(self, solout, complex=False):
|
1151 |
+
self.solout = solout
|
1152 |
+
self.solout_cmplx = complex
|
1153 |
+
if solout is None:
|
1154 |
+
self.iout = 0
|
1155 |
+
else:
|
1156 |
+
self.iout = 1
|
1157 |
+
|
1158 |
+
def reset(self, n, has_jac):
|
1159 |
+
work = zeros((8 * n + 21,), float)
|
1160 |
+
work[1] = self.safety
|
1161 |
+
work[2] = self.dfactor
|
1162 |
+
work[3] = self.ifactor
|
1163 |
+
work[4] = self.beta
|
1164 |
+
work[5] = self.max_step
|
1165 |
+
work[6] = self.first_step
|
1166 |
+
self.work = work
|
1167 |
+
iwork = zeros((21,), _dop_int_dtype)
|
1168 |
+
iwork[0] = self.nsteps
|
1169 |
+
iwork[2] = self.verbosity
|
1170 |
+
self.iwork = iwork
|
1171 |
+
self.call_args = [self.rtol, self.atol, self._solout,
|
1172 |
+
self.iout, self.work, self.iwork]
|
1173 |
+
self.success = 1
|
1174 |
+
|
1175 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
1176 |
+
x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
|
1177 |
+
tuple(self.call_args) + (f_params,)))
|
1178 |
+
self.istate = istate
|
1179 |
+
if istate < 0:
|
1180 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
1181 |
+
warnings.warn('{:s}: {:s}'.format(self.__class__.__name__,
|
1182 |
+
self.messages.get(istate, unexpected_istate_msg)),
|
1183 |
+
stacklevel=2)
|
1184 |
+
self.success = 0
|
1185 |
+
return y, x
|
1186 |
+
|
1187 |
+
def _solout(self, nr, xold, x, y, nd, icomp, con):
|
1188 |
+
if self.solout is not None:
|
1189 |
+
if self.solout_cmplx:
|
1190 |
+
y = y[::2] + 1j * y[1::2]
|
1191 |
+
return self.solout(x, y)
|
1192 |
+
else:
|
1193 |
+
return 1
|
1194 |
+
|
1195 |
+
|
1196 |
+
if dopri5.runner is not None:
|
1197 |
+
IntegratorBase.integrator_classes.append(dopri5)
|
1198 |
+
|
1199 |
+
|
1200 |
+
class dop853(dopri5):
|
1201 |
+
runner = getattr(_dop, 'dop853', None)
|
1202 |
+
name = 'dop853'
|
1203 |
+
|
1204 |
+
def __init__(self,
|
1205 |
+
rtol=1e-6, atol=1e-12,
|
1206 |
+
nsteps=500,
|
1207 |
+
max_step=0.0,
|
1208 |
+
first_step=0.0, # determined by solver
|
1209 |
+
safety=0.9,
|
1210 |
+
ifactor=6.0,
|
1211 |
+
dfactor=0.3,
|
1212 |
+
beta=0.0,
|
1213 |
+
method=None,
|
1214 |
+
verbosity=-1, # no messages if negative
|
1215 |
+
):
|
1216 |
+
super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
|
1217 |
+
ifactor, dfactor, beta, method, verbosity)
|
1218 |
+
|
1219 |
+
def reset(self, n, has_jac):
|
1220 |
+
work = zeros((11 * n + 21,), float)
|
1221 |
+
work[1] = self.safety
|
1222 |
+
work[2] = self.dfactor
|
1223 |
+
work[3] = self.ifactor
|
1224 |
+
work[4] = self.beta
|
1225 |
+
work[5] = self.max_step
|
1226 |
+
work[6] = self.first_step
|
1227 |
+
self.work = work
|
1228 |
+
iwork = zeros((21,), _dop_int_dtype)
|
1229 |
+
iwork[0] = self.nsteps
|
1230 |
+
iwork[2] = self.verbosity
|
1231 |
+
self.iwork = iwork
|
1232 |
+
self.call_args = [self.rtol, self.atol, self._solout,
|
1233 |
+
self.iout, self.work, self.iwork]
|
1234 |
+
self.success = 1
|
1235 |
+
|
1236 |
+
|
1237 |
+
if dop853.runner is not None:
|
1238 |
+
IntegratorBase.integrator_classes.append(dop853)
|
1239 |
+
|
1240 |
+
|
1241 |
+
class lsoda(IntegratorBase):
|
1242 |
+
runner = getattr(_lsoda, 'lsoda', None)
|
1243 |
+
active_global_handle = 0
|
1244 |
+
|
1245 |
+
messages = {
|
1246 |
+
2: "Integration successful.",
|
1247 |
+
-1: "Excess work done on this call (perhaps wrong Dfun type).",
|
1248 |
+
-2: "Excess accuracy requested (tolerances too small).",
|
1249 |
+
-3: "Illegal input detected (internal error).",
|
1250 |
+
-4: "Repeated error test failures (internal error).",
|
1251 |
+
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
|
1252 |
+
-6: "Error weight became zero during problem.",
|
1253 |
+
-7: "Internal workspace insufficient to finish (internal error)."
|
1254 |
+
}
|
1255 |
+
|
1256 |
+
def __init__(self,
|
1257 |
+
with_jacobian=False,
|
1258 |
+
rtol=1e-6, atol=1e-12,
|
1259 |
+
lband=None, uband=None,
|
1260 |
+
nsteps=500,
|
1261 |
+
max_step=0.0, # corresponds to infinite
|
1262 |
+
min_step=0.0,
|
1263 |
+
first_step=0.0, # determined by solver
|
1264 |
+
ixpr=0,
|
1265 |
+
max_hnil=0,
|
1266 |
+
max_order_ns=12,
|
1267 |
+
max_order_s=5,
|
1268 |
+
method=None
|
1269 |
+
):
|
1270 |
+
|
1271 |
+
self.with_jacobian = with_jacobian
|
1272 |
+
self.rtol = rtol
|
1273 |
+
self.atol = atol
|
1274 |
+
self.mu = uband
|
1275 |
+
self.ml = lband
|
1276 |
+
|
1277 |
+
self.max_order_ns = max_order_ns
|
1278 |
+
self.max_order_s = max_order_s
|
1279 |
+
self.nsteps = nsteps
|
1280 |
+
self.max_step = max_step
|
1281 |
+
self.min_step = min_step
|
1282 |
+
self.first_step = first_step
|
1283 |
+
self.ixpr = ixpr
|
1284 |
+
self.max_hnil = max_hnil
|
1285 |
+
self.success = 1
|
1286 |
+
|
1287 |
+
self.initialized = False
|
1288 |
+
|
1289 |
+
def reset(self, n, has_jac):
|
1290 |
+
# Calculate parameters for Fortran subroutine dvode.
|
1291 |
+
if has_jac:
|
1292 |
+
if self.mu is None and self.ml is None:
|
1293 |
+
jt = 1
|
1294 |
+
else:
|
1295 |
+
if self.mu is None:
|
1296 |
+
self.mu = 0
|
1297 |
+
if self.ml is None:
|
1298 |
+
self.ml = 0
|
1299 |
+
jt = 4
|
1300 |
+
else:
|
1301 |
+
if self.mu is None and self.ml is None:
|
1302 |
+
jt = 2
|
1303 |
+
else:
|
1304 |
+
if self.mu is None:
|
1305 |
+
self.mu = 0
|
1306 |
+
if self.ml is None:
|
1307 |
+
self.ml = 0
|
1308 |
+
jt = 5
|
1309 |
+
lrn = 20 + (self.max_order_ns + 4) * n
|
1310 |
+
if jt in [1, 2]:
|
1311 |
+
lrs = 22 + (self.max_order_s + 4) * n + n * n
|
1312 |
+
elif jt in [4, 5]:
|
1313 |
+
lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
|
1314 |
+
else:
|
1315 |
+
raise ValueError('Unexpected jt=%s' % jt)
|
1316 |
+
lrw = max(lrn, lrs)
|
1317 |
+
liw = 20 + n
|
1318 |
+
rwork = zeros((lrw,), float)
|
1319 |
+
rwork[4] = self.first_step
|
1320 |
+
rwork[5] = self.max_step
|
1321 |
+
rwork[6] = self.min_step
|
1322 |
+
self.rwork = rwork
|
1323 |
+
iwork = zeros((liw,), _lsoda_int_dtype)
|
1324 |
+
if self.ml is not None:
|
1325 |
+
iwork[0] = self.ml
|
1326 |
+
if self.mu is not None:
|
1327 |
+
iwork[1] = self.mu
|
1328 |
+
iwork[4] = self.ixpr
|
1329 |
+
iwork[5] = self.nsteps
|
1330 |
+
iwork[6] = self.max_hnil
|
1331 |
+
iwork[7] = self.max_order_ns
|
1332 |
+
iwork[8] = self.max_order_s
|
1333 |
+
self.iwork = iwork
|
1334 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
1335 |
+
self.rwork, self.iwork, jt]
|
1336 |
+
self.success = 1
|
1337 |
+
self.initialized = False
|
1338 |
+
|
1339 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
1340 |
+
if self.initialized:
|
1341 |
+
self.check_handle()
|
1342 |
+
else:
|
1343 |
+
self.initialized = True
|
1344 |
+
self.acquire_new_handle()
|
1345 |
+
args = [f, y0, t0, t1] + self.call_args[:-1] + \
|
1346 |
+
[jac, self.call_args[-1], f_params, 0, jac_params]
|
1347 |
+
y1, t, istate = self.runner(*args)
|
1348 |
+
self.istate = istate
|
1349 |
+
if istate < 0:
|
1350 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
1351 |
+
warnings.warn('{:s}: {:s}'.format(self.__class__.__name__,
|
1352 |
+
self.messages.get(istate, unexpected_istate_msg)),
|
1353 |
+
stacklevel=2)
|
1354 |
+
self.success = 0
|
1355 |
+
else:
|
1356 |
+
self.call_args[3] = 2 # upgrade istate from 1 to 2
|
1357 |
+
self.istate = 2
|
1358 |
+
return y1, t
|
1359 |
+
|
1360 |
+
def step(self, *args):
|
1361 |
+
itask = self.call_args[2]
|
1362 |
+
self.call_args[2] = 2
|
1363 |
+
r = self.run(*args)
|
1364 |
+
self.call_args[2] = itask
|
1365 |
+
return r
|
1366 |
+
|
1367 |
+
def run_relax(self, *args):
|
1368 |
+
itask = self.call_args[2]
|
1369 |
+
self.call_args[2] = 3
|
1370 |
+
r = self.run(*args)
|
1371 |
+
self.call_args[2] = itask
|
1372 |
+
return r
|
1373 |
+
|
1374 |
+
|
1375 |
+
if lsoda.runner:
|
1376 |
+
IntegratorBase.integrator_classes.append(lsoda)
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (83.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
ADDED
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Author: Travis Oliphant
|
2 |
+
|
3 |
+
__all__ = ['odeint', 'ODEintWarning']
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
from . import _odepack
|
7 |
+
from copy import copy
|
8 |
+
import warnings
|
9 |
+
|
10 |
+
|
11 |
+
class ODEintWarning(Warning):
|
12 |
+
"""Warning raised during the execution of `odeint`."""
|
13 |
+
pass
|
14 |
+
|
15 |
+
|
16 |
+
_msgs = {2: "Integration successful.",
|
17 |
+
1: "Nothing was done; the integration time was 0.",
|
18 |
+
-1: "Excess work done on this call (perhaps wrong Dfun type).",
|
19 |
+
-2: "Excess accuracy requested (tolerances too small).",
|
20 |
+
-3: "Illegal input detected (internal error).",
|
21 |
+
-4: "Repeated error test failures (internal error).",
|
22 |
+
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
|
23 |
+
-6: "Error weight became zero during problem.",
|
24 |
+
-7: "Internal workspace insufficient to finish (internal error).",
|
25 |
+
-8: "Run terminated (internal error)."
|
26 |
+
}
|
27 |
+
|
28 |
+
|
29 |
+
def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
|
30 |
+
ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
|
31 |
+
hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
|
32 |
+
mxords=5, printmessg=0, tfirst=False):
|
33 |
+
"""
|
34 |
+
Integrate a system of ordinary differential equations.
|
35 |
+
|
36 |
+
.. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
|
37 |
+
differential equation.
|
38 |
+
|
39 |
+
Solve a system of ordinary differential equations using lsoda from the
|
40 |
+
FORTRAN library odepack.
|
41 |
+
|
42 |
+
Solves the initial value problem for stiff or non-stiff systems
|
43 |
+
of first order ode-s::
|
44 |
+
|
45 |
+
dy/dt = func(y, t, ...) [or func(t, y, ...)]
|
46 |
+
|
47 |
+
where y can be a vector.
|
48 |
+
|
49 |
+
.. note:: By default, the required order of the first two arguments of
|
50 |
+
`func` are in the opposite order of the arguments in the system
|
51 |
+
definition function used by the `scipy.integrate.ode` class and
|
52 |
+
the function `scipy.integrate.solve_ivp`. To use a function with
|
53 |
+
the signature ``func(t, y, ...)``, the argument `tfirst` must be
|
54 |
+
set to ``True``.
|
55 |
+
|
56 |
+
Parameters
|
57 |
+
----------
|
58 |
+
func : callable(y, t, ...) or callable(t, y, ...)
|
59 |
+
Computes the derivative of y at t.
|
60 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
61 |
+
`tfirst` must be set ``True``.
|
62 |
+
y0 : array
|
63 |
+
Initial condition on y (can be a vector).
|
64 |
+
t : array
|
65 |
+
A sequence of time points for which to solve for y. The initial
|
66 |
+
value point should be the first element of this sequence.
|
67 |
+
This sequence must be monotonically increasing or monotonically
|
68 |
+
decreasing; repeated values are allowed.
|
69 |
+
args : tuple, optional
|
70 |
+
Extra arguments to pass to function.
|
71 |
+
Dfun : callable(y, t, ...) or callable(t, y, ...)
|
72 |
+
Gradient (Jacobian) of `func`.
|
73 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
74 |
+
`tfirst` must be set ``True``.
|
75 |
+
col_deriv : bool, optional
|
76 |
+
True if `Dfun` defines derivatives down columns (faster),
|
77 |
+
otherwise `Dfun` should define derivatives across rows.
|
78 |
+
full_output : bool, optional
|
79 |
+
True if to return a dictionary of optional outputs as the second output
|
80 |
+
printmessg : bool, optional
|
81 |
+
Whether to print the convergence message
|
82 |
+
tfirst : bool, optional
|
83 |
+
If True, the first two arguments of `func` (and `Dfun`, if given)
|
84 |
+
must ``t, y`` instead of the default ``y, t``.
|
85 |
+
|
86 |
+
.. versionadded:: 1.1.0
|
87 |
+
|
88 |
+
Returns
|
89 |
+
-------
|
90 |
+
y : array, shape (len(t), len(y0))
|
91 |
+
Array containing the value of y for each desired time in t,
|
92 |
+
with the initial value `y0` in the first row.
|
93 |
+
infodict : dict, only returned if full_output == True
|
94 |
+
Dictionary containing additional output information
|
95 |
+
|
96 |
+
======= ============================================================
|
97 |
+
key meaning
|
98 |
+
======= ============================================================
|
99 |
+
'hu' vector of step sizes successfully used for each time step
|
100 |
+
'tcur' vector with the value of t reached for each time step
|
101 |
+
(will always be at least as large as the input times)
|
102 |
+
'tolsf' vector of tolerance scale factors, greater than 1.0,
|
103 |
+
computed when a request for too much accuracy was detected
|
104 |
+
'tsw' value of t at the time of the last method switch
|
105 |
+
(given for each time step)
|
106 |
+
'nst' cumulative number of time steps
|
107 |
+
'nfe' cumulative number of function evaluations for each time step
|
108 |
+
'nje' cumulative number of jacobian evaluations for each time step
|
109 |
+
'nqu' a vector of method orders for each successful step
|
110 |
+
'imxer' index of the component of largest magnitude in the
|
111 |
+
weighted local error vector (e / ewt) on an error return, -1
|
112 |
+
otherwise
|
113 |
+
'lenrw' the length of the double work array required
|
114 |
+
'leniw' the length of integer work array required
|
115 |
+
'mused' a vector of method indicators for each successful time step:
|
116 |
+
1: adams (nonstiff), 2: bdf (stiff)
|
117 |
+
======= ============================================================
|
118 |
+
|
119 |
+
Other Parameters
|
120 |
+
----------------
|
121 |
+
ml, mu : int, optional
|
122 |
+
If either of these are not None or non-negative, then the
|
123 |
+
Jacobian is assumed to be banded. These give the number of
|
124 |
+
lower and upper non-zero diagonals in this banded matrix.
|
125 |
+
For the banded case, `Dfun` should return a matrix whose
|
126 |
+
rows contain the non-zero bands (starting with the lowest diagonal).
|
127 |
+
Thus, the return matrix `jac` from `Dfun` should have shape
|
128 |
+
``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
|
129 |
+
The data in `jac` must be stored such that ``jac[i - j + mu, j]``
|
130 |
+
holds the derivative of the ``i``\\ th equation with respect to the
|
131 |
+
``j``\\ th state variable. If `col_deriv` is True, the transpose of
|
132 |
+
this `jac` must be returned.
|
133 |
+
rtol, atol : float, optional
|
134 |
+
The input parameters `rtol` and `atol` determine the error
|
135 |
+
control performed by the solver. The solver will control the
|
136 |
+
vector, e, of estimated local errors in y, according to an
|
137 |
+
inequality of the form ``max-norm of (e / ewt) <= 1``,
|
138 |
+
where ewt is a vector of positive error weights computed as
|
139 |
+
``ewt = rtol * abs(y) + atol``.
|
140 |
+
rtol and atol can be either vectors the same length as y or scalars.
|
141 |
+
Defaults to 1.49012e-8.
|
142 |
+
tcrit : ndarray, optional
|
143 |
+
Vector of critical points (e.g., singularities) where integration
|
144 |
+
care should be taken.
|
145 |
+
h0 : float, (0: solver-determined), optional
|
146 |
+
The step size to be attempted on the first step.
|
147 |
+
hmax : float, (0: solver-determined), optional
|
148 |
+
The maximum absolute step size allowed.
|
149 |
+
hmin : float, (0: solver-determined), optional
|
150 |
+
The minimum absolute step size allowed.
|
151 |
+
ixpr : bool, optional
|
152 |
+
Whether to generate extra printing at method switches.
|
153 |
+
mxstep : int, (0: solver-determined), optional
|
154 |
+
Maximum number of (internally defined) steps allowed for each
|
155 |
+
integration point in t.
|
156 |
+
mxhnil : int, (0: solver-determined), optional
|
157 |
+
Maximum number of messages printed.
|
158 |
+
mxordn : int, (0: solver-determined), optional
|
159 |
+
Maximum order to be allowed for the non-stiff (Adams) method.
|
160 |
+
mxords : int, (0: solver-determined), optional
|
161 |
+
Maximum order to be allowed for the stiff (BDF) method.
|
162 |
+
|
163 |
+
See Also
|
164 |
+
--------
|
165 |
+
solve_ivp : solve an initial value problem for a system of ODEs
|
166 |
+
ode : a more object-oriented integrator based on VODE
|
167 |
+
quad : for finding the area under a curve
|
168 |
+
|
169 |
+
Examples
|
170 |
+
--------
|
171 |
+
The second order differential equation for the angle `theta` of a
|
172 |
+
pendulum acted on by gravity with friction can be written::
|
173 |
+
|
174 |
+
theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
|
175 |
+
|
176 |
+
where `b` and `c` are positive constants, and a prime (') denotes a
|
177 |
+
derivative. To solve this equation with `odeint`, we must first convert
|
178 |
+
it to a system of first order equations. By defining the angular
|
179 |
+
velocity ``omega(t) = theta'(t)``, we obtain the system::
|
180 |
+
|
181 |
+
theta'(t) = omega(t)
|
182 |
+
omega'(t) = -b*omega(t) - c*sin(theta(t))
|
183 |
+
|
184 |
+
Let `y` be the vector [`theta`, `omega`]. We implement this system
|
185 |
+
in Python as:
|
186 |
+
|
187 |
+
>>> import numpy as np
|
188 |
+
>>> def pend(y, t, b, c):
|
189 |
+
... theta, omega = y
|
190 |
+
... dydt = [omega, -b*omega - c*np.sin(theta)]
|
191 |
+
... return dydt
|
192 |
+
...
|
193 |
+
|
194 |
+
We assume the constants are `b` = 0.25 and `c` = 5.0:
|
195 |
+
|
196 |
+
>>> b = 0.25
|
197 |
+
>>> c = 5.0
|
198 |
+
|
199 |
+
For initial conditions, we assume the pendulum is nearly vertical
|
200 |
+
with `theta(0)` = `pi` - 0.1, and is initially at rest, so
|
201 |
+
`omega(0)` = 0. Then the vector of initial conditions is
|
202 |
+
|
203 |
+
>>> y0 = [np.pi - 0.1, 0.0]
|
204 |
+
|
205 |
+
We will generate a solution at 101 evenly spaced samples in the interval
|
206 |
+
0 <= `t` <= 10. So our array of times is:
|
207 |
+
|
208 |
+
>>> t = np.linspace(0, 10, 101)
|
209 |
+
|
210 |
+
Call `odeint` to generate the solution. To pass the parameters
|
211 |
+
`b` and `c` to `pend`, we give them to `odeint` using the `args`
|
212 |
+
argument.
|
213 |
+
|
214 |
+
>>> from scipy.integrate import odeint
|
215 |
+
>>> sol = odeint(pend, y0, t, args=(b, c))
|
216 |
+
|
217 |
+
The solution is an array with shape (101, 2). The first column
|
218 |
+
is `theta(t)`, and the second is `omega(t)`. The following code
|
219 |
+
plots both components.
|
220 |
+
|
221 |
+
>>> import matplotlib.pyplot as plt
|
222 |
+
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
|
223 |
+
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
|
224 |
+
>>> plt.legend(loc='best')
|
225 |
+
>>> plt.xlabel('t')
|
226 |
+
>>> plt.grid()
|
227 |
+
>>> plt.show()
|
228 |
+
"""
|
229 |
+
|
230 |
+
if ml is None:
|
231 |
+
ml = -1 # changed to zero inside function call
|
232 |
+
if mu is None:
|
233 |
+
mu = -1 # changed to zero inside function call
|
234 |
+
|
235 |
+
dt = np.diff(t)
|
236 |
+
if not ((dt >= 0).all() or (dt <= 0).all()):
|
237 |
+
raise ValueError("The values in t must be monotonically increasing "
|
238 |
+
"or monotonically decreasing; repeated values are "
|
239 |
+
"allowed.")
|
240 |
+
|
241 |
+
t = copy(t)
|
242 |
+
y0 = copy(y0)
|
243 |
+
output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
|
244 |
+
full_output, rtol, atol, tcrit, h0, hmax, hmin,
|
245 |
+
ixpr, mxstep, mxhnil, mxordn, mxords,
|
246 |
+
int(bool(tfirst)))
|
247 |
+
if output[-1] < 0:
|
248 |
+
warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
|
249 |
+
f"get quantitative information.")
|
250 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
251 |
+
elif printmessg:
|
252 |
+
warning_msg = _msgs[output[-1]]
|
253 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
254 |
+
|
255 |
+
if full_output:
|
256 |
+
output[1]['message'] = _msgs[output[-1]]
|
257 |
+
|
258 |
+
output = output[:-1]
|
259 |
+
if len(output) == 1:
|
260 |
+
return output[0]
|
261 |
+
else:
|
262 |
+
return output
|